session

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

This file implements the session/end-seed boundary marker (M20), following upstream session semantics. Resume replays persisted seed events, then writes end-seed before live work. Fork does the same after replaying its parent seed. Compaction uses this boundary to distinguish seed history from live events.

Session projections (M05) mirror packages/core/session in the upstream project. Fold functions derive state from events without modifying them. Incremental updates and full replay must agree. Compaction applies surface replacements when reading, leaving the original append-only event log intact.

This file validates session formats and event types (M44), following upstream session versioning. LoadSession validates the header version before checking every event against the known-type set. Unknown versions or types fail closed to avoid interpreting data with incompatible parsing rules.

SessionHeader metadata follows upstream session (M06). Static fields include format version, ID, creation time, cwd, fork parent, seed length, origin, and agent preset. They define persistence identity, lineage, and subagent depth.

This file implements incremental session projections (H04). Append applies only the new event rather than replaying history. Each projection has a pure Apply operation. Surface replacement marks messages dirty because prior contributions cannot be cheaply undone; the next message snapshot rebuilds that projection while metadata projections remain incremental. NewIncrementalFolder and FolderFromEvents initialize state; Append/AppendMany consume events; Snapshot lazily rebuilds messages; FullRebuild supports consistency checks against FoldAll.

This file defines append-only discipline and eight session invariants (N02), following upstream session and compaction. Append is the only mutation path; read views are copied. Surface replacement changes derived visibility, never source events. VerifyInvariants returns classified failures for persistence and checkpoint validation; callers may reject writes or record violations.

The session projection registry (M16) follows upstream session-projection. SDK consumers read derived state through registered projections rather than raw events. Each projection maintains state incrementally and exposes a changelog; snapshots should agree with their fold functions.

Session references follow upstream session-reference and file-reference modules (M17). User input selects sessions with @session/<id> and workspace files with #<path/file>. Mentions are only selection syntax: the model sees an aggregated untrusted snapshot in additionalContext, matching PreparedReferencedMessage. Raw refs are recorded on user/message for auditing. Failures use stable codes; host protocols must not parse prompt text.

This file implements request-header snapshots and request/context routing (M19), following upstream session/request-header. EpochHeader records config, system, and tool generations; RequestContext records routing and rebuild reason. RebuildFromHeader restores prompt/schema inputs after compaction without relying on original events; fields should match the sent payload.

Sequence-range encoding follows upstream session semantics for compact sourceEventSeqs storage. Strictly increasing runs of at least three values become inclusive ranges; shorter runs remain singletons. Decoding is lossless.

Package session provides event-sourced session logs, following upstream packages/core/session (M04). State derives entirely from an append-only log and can be replayed. EventData and concrete payload types form a typed union selected by the serialized type field. SessionLog.Append is the sole write path and rejects invalid turn/step pairing or tool call/result transitions.

Surface operations define the read-time view of SessionEvent history (M21).

Index

Constants

View Source
const AppendOnlyMarker = "SessionLog exposes a single write path: Append(EventData)"

AppendOnlyMarker documents SessionLog's append-only contract without runtime effects.

View Source
const SessionFormatVersion = 1

SessionFormatVersion identifies the current on-disk format. Incompatible header/event changes must increment it and reject other versions.

Variables

All event types for enumeration and serialization round-trip tests.

View Source
var KNOWN_SESSION_EVENT_TYPES = func() map[EventType]struct{} {
	m := map[EventType]struct{}{}
	for _, t := range AllEventTypes {
		m[t] = struct{}{}
	}
	return m
}()

KNOWN_SESSION_EVENT_TYPES lists supported types in lexical order for validation.

Functions

func AppendOnly

func AppendOnly(sl *SessionLog) error

AppendOnly permits only the Append mutation primitive. It guards persistence and replay paths against bypassing the sole SessionLog write entry point.

func DecodeSeqRanges

func DecodeSeqRanges(ranges []SeqRange, maxEntries int) ([]int, error)

DecodeSeqRanges expands ranges losslessly; maxEntries <= 0 disables the entry limit.

func EndSeedMarker

func EndSeedMarker(header *SessionHeader) uint64

EndSeedMarker returns the replayed seed length recorded in SessionHeader by the caller after Resume/Fork replay completes.

func FoldSurface

func FoldSurface(events []SessionEvent) (nodes []SurfaceNode, replacements []ReplaceRange)

FoldSurface applies surface replacements at read time and returns visible nodes and all replacement ranges for auditing. Source events remain unchanged. Like EffectiveEvents, visibility uses ranges clipped to the replacing event's sequence; the audit ranges retain their original bounds and event order.

func IsAfterEndSeed

func IsAfterEndSeed(events []SessionEvent, seq uint64) bool

IsAfterEndSeed reports whether a sequence belongs to the live region after the last marker.

func IsCorruptEventError

func IsCorruptEventError(err error) bool

IsCorruptEventError reports whether an error indicates a corrupt event.

func LoadSession

func LoadSession(headerBytes []byte, eventLines ...[]byte) (*SessionHeader, []SessionEvent, error)

LoadSession validates the header against SessionFormatVersion, checks each event type against KNOWN_SESSION_EVENT_TYPES, and reconstructs events through full deserialization. Incompatible versions are rejected.

func MarkEndSeed

func MarkEndSeed(sl *SessionLog, parentID brand.SessionID) (uint64, error)

MarkEndSeed records the boundary after Resume/Fork seed replay and before live work. id identifies the session or another unique seed; optional parentID records the fork source in EndSeedData.ParentSession.

func RebuildFromHeader

func RebuildFromHeader(snap *RequestHeaderSnapshot) (systemPrompt string, toolSchemas json.RawMessage, err error)

RebuildFromHeader restores prompt and schema text from the snapshot. Both fields should match the corresponding sent payload fields.

func SeedEndSeq

func SeedEndSeq(events []SessionEvent) uint64

SeedEndIndex returns the last end-seed event index, or -1 if absent. SeedEndSeq returns its sequence number, or zero if absent.

func SessionProjectionEqual

func SessionProjectionEqual(a, b SessionProjection) bool

SessionProjectionEqual compares aggregate projections for consistency checks.

func VerifyInvariants

func VerifyInvariants(events []SessionEvent) []error

VerifyInvariants checks all eight invariants; an empty result means success.

Types

type AgentErrorData

type AgentErrorData struct {
	Message string `json:"message"`
	Pkg     string `json:"pkg,omitempty"`
}

AgentErrorData records an internal agent/error.

func (AgentErrorData) EventType

func (AgentErrorData) EventType() EventType

type AgentPreStepData

type AgentPreStepData struct {
	Blocked bool `json:"blocked,omitempty"`
}

AgentPreStepData marks preprocessing before entering a step.

func (AgentPreStepData) EventType

func (AgentPreStepData) EventType() EventType

type AgentPresetChangeData

type AgentPresetChangeData struct {
	Preset string `json:"preset"`
}

AgentPresetChangeData records an agent-preset change.

func (AgentPresetChangeData) EventType

func (AgentPresetChangeData) EventType() EventType

type AgentRequestData

type AgentRequestData struct {
	Provider string `json:"provider"`
	Model    string `json:"model,omitempty"`
}

AgentRequestData records an assembled model request snapshot.

func (AgentRequestData) EventType

func (AgentRequestData) EventType() EventType

type AgentStatusData

type AgentStatusData struct {
	Status string `json:"status"`
}

AgentStatusData records idle/running lifecycle transitions.

func (AgentStatusData) EventType

func (AgentStatusData) EventType() EventType

type ApprovalDecidedData

type ApprovalDecidedData struct {
	RequestID brand.ApprovalRequestID `json:"requestId"`
	Allowed   bool                    `json:"allowed"`
}

ApprovalDecidedData records an approval decision.

func (ApprovalDecidedData) EventType

func (ApprovalDecidedData) EventType() EventType

type ApprovalPolicy

type ApprovalPolicy string

ApprovalPolicy identifies the approval strategy.

const (
	ApprovalAllowAll         ApprovalPolicy = "allow-all"
	ApprovalDenyAll          ApprovalPolicy = "deny-all"
	ApprovalAskDangerous     ApprovalPolicy = "ask-dangerous"
	ApprovalAskDangerousEdit ApprovalPolicy = "ask-dangerous-tool-edit"
)

Supported approval policies.

type ApprovalRequestIDData

type ApprovalRequestIDData struct {
	RequestID brand.ApprovalRequestID `json:"requestId"`
	Tool      string                  `json:"tool,omitempty"`
	Summary   string                  `json:"summary,omitempty"`
}

ApprovalAskedData records an approval request.

func (ApprovalRequestIDData) EventType

func (ApprovalRequestIDData) EventType() EventType

type AssistantChunkData

type AssistantChunkData struct {
	Text string `json:"text,omitempty"`
}

AssistantChunkData records streamed assistant text.

func (AssistantChunkData) EventType

func (AssistantChunkData) EventType() EventType

type AssistantMessageData

type AssistantMessageData struct {
	Reasoning   string   `json:"reasoning,omitempty"`
	Content     string   `json:"content"`
	ToolCallIDs []string `json:"toolCallIds,omitempty"`
}

AssistantMessageData records a completed assistant message.

func (AssistantMessageData) EventType

func (AssistantMessageData) EventType() EventType

type AssistantReasoningData

type AssistantReasoningData struct {
	Text string `json:"text,omitempty"`
}

AssistantReasoningData records streamed reasoning.

func (AssistantReasoningData) EventType

func (AssistantReasoningData) EventType() EventType

type AttachmentAddedData

type AttachmentAddedData struct {
	AttachmentID brand.AttachmentID `json:"attachmentId"`
	Name         string             `json:"name,omitempty"`
}

AttachmentAddedData records a new attachment.

func (AttachmentAddedData) EventType

func (AttachmentAddedData) EventType() EventType

type CommandDoneData

type CommandDoneData struct {
	Command string `json:"command"`
}

CommandDoneData records slash-command completion.

func (CommandDoneData) EventType

func (CommandDoneData) EventType() EventType

type CommandRunData

type CommandRunData struct {
	Command string `json:"command"`
	Args    string `json:"args,omitempty"`
}

CommandRunData records a slash-command invocation.

func (CommandRunData) EventType

func (CommandRunData) EventType() EventType

type CorruptEventError

type CorruptEventError struct {
	Seq  uint64
	Type EventType
}

CorruptEventError indicates an unknown type caused by corrupt or incompatible data.

func (*CorruptEventError) Error

func (e *CorruptEventError) Error() string

Error implements the error interface.

type EffectiveApprovalPolicy

type EffectiveApprovalPolicy struct {
	Present bool           `json:"present"`
	Policy  ApprovalPolicy `json:"policy,omitempty"`
	Source  string         `json:"source,omitempty"` // preset / user / session
}

EffectiveApprovalPolicy is the effective approval-policy projection.

func FoldEffectiveApprovalPolicy

func FoldEffectiveApprovalPolicy(events []SessionEvent) EffectiveApprovalPolicy

FoldEffectiveApprovalPolicy exposes effective approval-policy derivation.

func (EffectiveApprovalPolicy) Equal

Equal compares effective approval policies.

type EffectiveSandboxMode

type EffectiveSandboxMode struct {
	Present  bool        `json:"present"`
	Mode     SandboxMode `json:"mode,omitempty"`
	Enforced bool        `json:"enforced,omitempty"`
	Root     string      `json:"root,omitempty"`
}

EffectiveSandboxMode records the preset-derived mode, enforcement, and root.

func FoldEffectiveSandboxMode

func FoldEffectiveSandboxMode(events []SessionEvent) EffectiveSandboxMode

FoldEffectiveSandboxMode exposes effective sandbox-mode derivation.

func (EffectiveSandboxMode) Equal

Equal compares effective sandbox modes.

type EndSeedData

type EndSeedData struct {
	ParentSession brand.SessionID `json:"parentSession,omitempty"`
}

EndSeedData marks the first live boundary after Resume/Fork seed replay.

func (EndSeedData) EventType

func (EndSeedData) EventType() EventType

type EpochHeader

type EpochHeader struct {
	// ConfigEpoch increases when settings change.
	ConfigEpoch uint64 `json:"configEpoch"`
	// SystemHash is the stable system-prompt hash.
	SystemHash string `json:"systemHash"`
	// ToolCount records tool count as a tool-generation signal.
	ToolCount int `json:"toolCount"`
}

EpochHeader is the request/header snapshot.

func FoldEpochHeader

func FoldEpochHeader(events []SessionEvent) (EpochHeader, bool)

FoldEpochHeader returns the latest request/header snapshot.

type EventData

type EventData interface {
	EventType() EventType
}

EventData is implemented by every concrete event payload. EventType identifies the variant, forming a type-safe event union.

type EventType

type EventType string

EventType identifies an event using a string.

const (
	EventTurnStart         EventType = "turn/start"
	EventTurnEnd           EventType = "turn/end"
	EventTurnStopping      EventType = "turn/stopping"
	EventStepStart         EventType = "step/start"
	EventStepEnd           EventType = "step/end"
	EventAgentError        EventType = "agent/error"
	EventAgentPreStep      EventType = "agent/pre-step"
	EventAgentRequest      EventType = "agent/request"
	EventAgentStatus       EventType = "agent/status"
	EventAgentInboxSpliced EventType = "agent/inbox/spliced"
)

Group A: turn and step execution.

const (
	EventUserMessage        EventType = "user/message"
	EventAssistantMessage   EventType = "assistant/message"
	EventAssistantChunk     EventType = "assistant/chunk"
	EventAssistantReasoning EventType = "assistant/reasoning"
	EventInjectionContext   EventType = "injection/context"
	EventSessionTitle       EventType = "session/title"
)

Group B: messages.

const (
	EventToolCall         EventType = "tool/call"
	EventToolResult       EventType = "tool/result"
	EventToolError        EventType = "tool/error"
	EventToolObserved     EventType = "tool/observed"
	EventToolPresentation EventType = "tool/presentation"
)

Group C: tools.

const (
	EventPlanMode     EventType = "plan/mode"
	EventPlanApproval EventType = "plan/approval"
	EventGoalChange   EventType = "goal/change"
	EventGoalRound    EventType = "goal/round"
	EventTodoWrite    EventType = "todo/write"
	EventEndSeed      EventType = "session/end-seed"
	EventPlanUpdate   EventType = "project/plan-update"
)

Group D: planning.

const (
	EventRequestHeader     EventType = "request/header"
	EventRequestContext    EventType = "request/context"
	EventApprovalAsked     EventType = "approval/asked"
	EventApprovalDecided   EventType = "approval/decided"
	EventPresetChange      EventType = "permission/preset-change"
	EventAgentPresetChange EventType = "agent/preset-change"
	EventCommandRun        EventType = "command/run"
	EventCommandDone       EventType = "command/done"
)

Group E: requests and approvals.

const (
	EventFSWriteIntent EventType = "fs/write-intent"
	EventFSEditIntent  EventType = "fs/edit-intent"
	EventFSObserved    EventType = "fs/observed"
	EventFSVersionBump EventType = "fs/version-bump"
	EventFSRead        EventType = "fs/read"
	EventFSDirList     EventType = "fs/dir-list"
)

Group F: filesystem operations.

const (
	EventSkillsChange  EventType = "skills/change"
	EventSkillsCatalog EventType = "skills/catalog"
	EventSkillInject   EventType = "skill/inject"
)

Group G: skills.

const (
	EventLLMRequest EventType = "llm/request"
	EventLLMStream  EventType = "llm/stream"
	EventLLMRetry   EventType = "llm/retry"
	EventLLMError   EventType = "llm/error"
	EventLLMDone    EventType = "llm/done"
)

Group H: LLM operations.

const (
	EventSurfaceReplace          EventType = "surface/replace"
	EventAttachmentAdded         EventType = "attachment/added"
	EventSessionProjectionUpdate EventType = "session/projection-updated"
	EventWorkspaceChange         EventType = "workspace/change"
	EventUserQuestion            EventType = "user/question"
	EventSandboxMode             EventType = "sandbox/mode"
)

Group I: surface replacement and miscellaneous events.

func EventTypeOf

func EventTypeOf(d EventData) EventType

EventTypeOf returns a payload's type for callers and tests.

type FolderStats

type FolderStats struct {
	// IncrementalAppends counts incremental appends.
	IncrementalAppends uint64 `json:"incrementalAppends"`
	// DirtyRebuilds counts message rebuilds caused by surface replacement.
	DirtyRebuilds uint64 `json:"dirtyRebuilds"`
	// EventsScanned counts one per incremental event and all events during a rebuild.
	EventsScanned uint64 `json:"eventsScanned"`
}

FolderStats exposes H04 performance counters.

type FsDirListData

type FsDirListData struct {
	Path string `json:"path"`
}

FsDirListData records a directory listing.

func (FsDirListData) EventType

func (FsDirListData) EventType() EventType

type FsEditIntentData

type FsEditIntentData struct {
	Path    string `json:"path"`
	Version uint64 `json:"version,omitempty"`
}

FsEditIntentData records intent to edit a file.

func (FsEditIntentData) EventType

func (FsEditIntentData) EventType() EventType

type FsIntentData

type FsIntentData struct {
	Path     string `json:"path"`
	Kind     string `json:"kind,omitempty"`
	Version  uint64 `json:"version,omitempty"`
	Observed bool   `json:"observed,omitempty"`
}

FsIntentData shares fields across write/edit/observed/version-bump/read/directory events.

func (FsIntentData) EventType

func (FsIntentData) EventType() EventType

type FsObservedData

type FsObservedData struct {
	Path string `json:"path"`
}

FsObservedData records file observation for read-before-write policy.

func (FsObservedData) EventType

func (FsObservedData) EventType() EventType

type FsReadData

type FsReadData struct {
	Path string `json:"path"`
}

FsReadData records a file read.

func (FsReadData) EventType

func (FsReadData) EventType() EventType

type FsVersionBumpData

type FsVersionBumpData struct {
	Path    string `json:"path"`
	Version uint64 `json:"version"`
}

FsVersionBumpData records a file version increment.

func (FsVersionBumpData) EventType

func (FsVersionBumpData) EventType() EventType

type FsWriteIntentData

type FsWriteIntentData struct {
	Path     string `json:"path"`
	Version  uint64 `json:"version,omitempty"`
	Observed bool   `json:"observed,omitempty"`
}

FsWriteIntentData records intent to write a file.

func (FsWriteIntentData) EventType

func (FsWriteIntentData) EventType() EventType

type GoalBlockReason

type GoalBlockReason struct {
	// Code is a stable lower-kebab-case category.
	Code string `json:"code"`
	// Message is a nonempty explanation for users and models.
	Message string `json:"message"`
}

GoalBlockReason records the stable code and message for a blocked goal (R06). The goal domain sets it and persists it with goal/change.

type GoalChangeData

type GoalChangeData struct {
	GoalID      string    `json:"goalId"`
	Phase       GoalPhase `json:"phase"`
	Description string    `json:"description,omitempty"`
	MaxRounds   int       `json:"maxRounds,omitempty"`
	Revision    uint64    `json:"revision"`
	// BlockReason is present only for blocked goals and is persisted with the event.
	BlockReason *GoalBlockReason `json:"blockedReason,omitempty"`
}

GoalChangeData records a goal change with a CAS revision.

func (GoalChangeData) EventType

func (GoalChangeData) EventType() EventType

type GoalFold

type GoalFold struct {
	Present     bool      `json:"present"`
	GoalID      string    `json:"goalId,omitempty"`
	Phase       GoalPhase `json:"phase,omitempty"`
	Description string    `json:"description,omitempty"`
	MaxRounds   int       `json:"maxRounds,omitempty"`
	Revision    uint64    `json:"revision,omitempty"`
	// BlockReason is the latest blocking reason persisted by goal/change (R06).
	BlockReason *GoalBlockReason `json:"blockedReason,omitempty"`
}

GoalFold is the goal-state projection; its CAS revision guards concurrent updates.

func ApplyGoalChange

func ApplyGoalChange(s GoalFold, ev SessionEvent) GoalFold

ApplyGoalChange applies strictly increasing revisions with latest-wins CAS semantics.

func FoldGoalChange

func FoldGoalChange(events []SessionEvent) GoalFold

FoldGoalChange exposes goal-state derivation.

func (GoalFold) Equal

func (g GoalFold) Equal(o ProjectionState) bool

Equal compares goal projections.

type GoalPhase

type GoalPhase string

GoalPhase identifies the goal lifecycle phase.

type GoalRoundData

type GoalRoundData struct {
	Round int `json:"round"`
}

GoalRoundData marks continuation into another goal round.

func (GoalRoundData) EventType

func (GoalRoundData) EventType() EventType

type HeaderOrigin

type HeaderOrigin string

HeaderOrigin identifies how a session originated.

const (
	OriginCreated HeaderOrigin = "created" // Newly created session.
	OriginFork    HeaderOrigin = "fork"    // Forked from a parent session.
	OriginResume  HeaderOrigin = "resume"  // Resumed from persisted state.
)

Session origins.

func AsHeaderOrigin

func AsHeaderOrigin(s string) HeaderOrigin

AsHeaderOrigin converts an origin string for tests and external construction.

type InboxSplicedData

type InboxSplicedData struct {
	Target       InboxTarget `json:"target"`
	Start        int         `json:"start"`
	RemovedCount int         `json:"removedCount,omitempty"`
	Inserted     []string    `json:"inserted"`
	Outcome      string      `json:"outcome,omitempty"`
}

InboxSplicedData records a normalized persisted pending-input list change.

func (InboxSplicedData) EventType

func (InboxSplicedData) EventType() EventType

type InboxTarget

type InboxTarget string

InboxTarget selects next-turn or next-step input.

const (
	// InboxNextTurn holds input awaiting the next turn.
	InboxNextTurn InboxTarget = "next-turn"
	// InboxNextStep holds input awaiting the next step boundary.
	InboxNextStep InboxTarget = "next-step"
)

type IncrementalFolder

type IncrementalFolder struct {

	// Statistics support H04 monitoring and benchmarks.
	Stats FolderStats
	// contains filtered or unexported fields
}

IncrementalFolder maintains SessionProjection incrementally. Create a folder, Append events, then call Snapshot(events); history is read when messages are dirty. Projection state is not internally synchronized: callers must serialize access, as SessionLog.Append does under its mutex.

func FolderFromEvents

func FolderFromEvents(events []SessionEvent) *IncrementalFolder

FolderFromEvents initializes a baseline with FoldAll, then supports incremental appends. Its initial snapshot matches FoldAll(events).

func NewIncrementalFolder

func NewIncrementalFolder() *IncrementalFolder

NewIncrementalFolder creates empty projection state.

func (*IncrementalFolder) Append

func (f *IncrementalFolder) Append(ev SessionEvent)

Append applies one event incrementally; surface replacement only marks messages dirty.

func (*IncrementalFolder) AppendMany

func (f *IncrementalFolder) AppendMany(evs []SessionEvent)

AppendMany applies a batch through successive Append calls.

func (*IncrementalFolder) FullRebuild

func (f *IncrementalFolder) FullRebuild(events []SessionEvent) SessionProjection

FullRebuild recomputes all projections for consistency testing, bypassing dirty shortcuts.

func (*IncrementalFolder) MarkDirty

func (f *IncrementalFolder) MarkDirty()

MarkDirty explicitly invalidates messages after known history compaction or for debugging.

func (*IncrementalFolder) Snapshot

func (f *IncrementalFolder) Snapshot(events []SessionEvent) SessionProjection

Snapshot returns the aggregate projection. Dirty messages are lazily rebuilt on reading, while metadata reuses incremental state. Without replacements no rebuild occurs. The message slice is copied, but nested slices and pointers remain shared and must be treated as read-only. Use SnapshotMeta on hot paths that only need metadata to avoid copying the message slice.

func (*IncrementalFolder) SnapshotMeta

func (f *IncrementalFolder) SnapshotMeta(events []SessionEvent) SessionProjection

SnapshotMeta returns metadata only, with Messages always nil. Use it for Goal, Todo, Preset, Sandbox, Approval, PlanMode, Title, and RequestHeader when message copying would add unnecessary hot-path work.

func (*IncrementalFolder) StatsCopy

func (f *IncrementalFolder) StatsCopy() FolderStats

StatsCopy returns a synchronized statistics snapshot.

type InjectionContextData

type InjectionContextData struct {
	Name    string `json:"name"`
	Content string `json:"content"`
	Hash    string `json:"hash,omitempty"`
}

InjectionContextData records injected dynamic context, such as a skill catalog.

func (InjectionContextData) EventType

func (InjectionContextData) EventType() EventType

type InvariantCode

type InvariantCode string

InvariantCode identifies an invariant failure.

const (
	InvSeqContinuous    InvariantCode = "seq_continuous"
	InvTimeMonotonic    InvariantCode = "time_monotonic"
	InvTurnPaired       InvariantCode = "turn_start_end_paired"
	InvStepPaired       InvariantCode = "step_start_end_paired"
	InvApprovalPaired   InvariantCode = "approval_asked_decided_paired"
	InvGoalCAS          InvariantCode = "goal_revision_cas"
	InvToolCallResult   InvariantCode = "tool_call_result_paired"
	InvFormatConsistent InvariantCode = "persistence_format_consistent"
)

The eight invariant codes.

type InvariantFailure

type InvariantFailure struct {
	Code    InvariantCode
	Message string
}

InvariantFailure describes one failed invariant.

func (InvariantFailure) Error

func (f InvariantFailure) Error() string

type LLMDoneData

type LLMDoneData struct {
	PromptTokens     int `json:"promptTokens"`
	CompletionTokens int `json:"completionTokens"`
}

LLMDoneData records model completion and token usage.

func (LLMDoneData) EventType

func (LLMDoneData) EventType() EventType

type LLMErrorData

type LLMErrorData struct {
	Kind  string `json:"kind"` // overload/rate-limit/refusal/context-overflow
	Error string `json:"error"`
}

LLMErrorData records a failed model request.

func (LLMErrorData) EventType

func (LLMErrorData) EventType() EventType

type LLMRequestData

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

LLMRequestData records a model request.

func (LLMRequestData) EventType

func (LLMRequestData) EventType() EventType

type LLMRetryData

type LLMRetryData struct {
	Attempt   int    `json:"attempt"`
	BackoffMs int64  `json:"backoffMs"`
	Error     string `json:"error"`
}

LLMRetryData records a model retry and its backoff information.

func (LLMRetryData) EventType

func (LLMRetryData) EventType() EventType

type LLMStreamData

type LLMStreamData struct {
	Text string `json:"text,omitempty"`
}

LLMStreamData records a model stream chunk.

func (LLMStreamData) EventType

func (LLMStreamData) EventType() EventType

type Mention

type Mention struct {
	// Kind is session or file.
	Kind MentionKind
	// Raw is the complete source token, such as @session/abc or #src/main.go.
	Raw string
	// Value is the target session ID or file path.
	Value string
	// Start and End delimit Raw in source bytes for stripping mentions from readable text.
	Start int
	End   int
}

Mention identifies one reference in user input.

func ParseMentions

func ParseMentions(text string) []Mention

ParseMentions returns @session/<id> and #<path/file> references in source order. With no references it returns an empty, non-nil slice.

type MentionKind

type MentionKind string

MentionKind identifies the reference type.

const (
	// MentionSession selects a session with @session/<id>.
	MentionSession MentionKind = "session"
	// MentionFile selects a file with #<path/file>.
	MentionFile MentionKind = "file"
)

type Message

type Message struct {
	Role        string   `json:"role"` // "user" / "assistant"
	Content     string   `json:"content"`
	ToolCallIDs []string `json:"toolCallIds,omitempty"`
	Seq         uint64   `json:"seq"`
}

Message is a derived conversation message used to assemble model context.

func ApplyMessage

func ApplyMessage(msgs []Message, ev SessionEvent) ([]Message, bool)

ApplyMessage appends a message event and reports whether SurfaceReplace occurred. It does not remove replaced history; callers must mark messages dirty and rebuild them when necessary.

func DeriveMessages

func DeriveMessages(events []SessionEvent) []Message

DeriveMessages exposes message derivation to callers outside the package.

func (Message) Equal

func (m Message) Equal(o ProjectionState) bool

Equal implements ProjectionState.

type PermissionPresetFold

type PermissionPresetFold struct {
	Present bool   `json:"present"`
	Preset  string `json:"preset,omitempty"`
}

PermissionPresetFold is the permission-preset projection.

func ApplyPermissionPreset

func ApplyPermissionPreset(s PermissionPresetFold, ev SessionEvent) PermissionPresetFold

ApplyPermissionPreset keeps the latest permission preset.

func FoldPermissionPreset

func FoldPermissionPreset(events []SessionEvent) PermissionPresetFold

FoldPermissionPreset exposes permission-preset derivation.

func (PermissionPresetFold) Equal

Equal compares permission-preset projections.

type PlanApprovalData

type PlanApprovalData struct {
	Approved bool `json:"approved"`
}

PlanApprovalData records a plan approval outcome.

func (PlanApprovalData) EventType

func (PlanApprovalData) EventType() EventType

type PlanModeData

type PlanModeData struct {
	Mode string `json:"mode"` // "on" / "off"
}

PlanModeData records plan-mode activation or deactivation.

func (PlanModeData) EventType

func (PlanModeData) EventType() EventType

type PlanModeFold

type PlanModeFold struct {
	Present bool   `json:"present"`
	Mode    string `json:"mode,omitempty"` // "on" / "off"
}

PlanModeFold is the plan-mode projection.

func ApplyPlanMode

func ApplyPlanMode(s PlanModeFold, ev SessionEvent) PlanModeFold

ApplyPlanMode keeps the latest plan mode.

func FoldPlanMode

func FoldPlanMode(events []SessionEvent) PlanModeFold

FoldPlanMode exposes plan-mode derivation.

func (PlanModeFold) Equal

func (p PlanModeFold) Equal(o ProjectionState) bool

Equal compares plan-mode projections.

type PlanUpdateData

type PlanUpdateData struct {
	Content string `json:"content,omitempty"`
}

PlanUpdateData records updated plan content.

func (PlanUpdateData) EventType

func (PlanUpdateData) EventType() EventType

type PrepareRequest

type PrepareRequest struct {
	// AgentSessionID enables self-reference rejection; empty skips this check.
	AgentSessionID brand.SessionID
	// Text contains the original user message, possibly with mentions.
	Text string
	// Resolver resolves session and file references.
	Resolver SessionReferenceResolver
	// MaxContextBytes optionally limits aggregated context; nonpositive means unlimited.
	MaxContextBytes int
}

PrepareRequest describes reference preparation inputs.

type PreparedReferencedMessage

type PreparedReferencedMessage struct {
	// Content is readable message text with mention tokens removed.
	Content string
	// AdditionalContext contains aggregated untrusted reference context, or empty if absent.
	AdditionalContext string
	// References lists successfully resolved and included references in source order.
	References []ReferenceResolution
}

PreparedReferencedMessage combines readable text after mention removal with an optional aggregated additionalContext snapshot.

func Prepare

Prepare parses mentions, resolves each reference, and builds the prepared message. No references preserves Content and leaves AdditionalContext empty. Self references, resolution failures, excess reference counts, and exceeded context budgets return their stable error codes immediately.

type PresetChangeData

type PresetChangeData struct {
	Preset string `json:"preset"`
}

PresetChangeData records a permission-preset change.

func (PresetChangeData) EventType

func (PresetChangeData) EventType() EventType

type Projection

type Projection[S ProjectionState] struct {
	// contains filtered or unexported fields
}

Projection is a registered projection instance.

func RegisterProjection

func RegisterProjection[S ProjectionState](r *Registry, def *ProjectionDefinition[S]) (*Projection[S], error)

RegisterProjection registers a definition. It is a generic function because Go methods cannot declare their own type parameters.

func (*Projection[S]) State

func (p *Projection[S]) State() S

State returns the current projection state.

type ProjectionChange

type ProjectionChange struct {
	// ProjectionID identifies the projection.
	ProjectionID brand.ProjectionID `json:"projectionId"`
	// Seq is the changelog sequence number.
	Seq uint64 `json:"seq"`
	// EventSeq identifies the triggering event.
	EventSeq uint64 `json:"eventSeq"`
	// Changed reports whether state changed.
	Changed bool `json:"changed"`
}

ProjectionChange records a projection changelog entry.

type ProjectionDefinition

type ProjectionDefinition[S ProjectionState] struct {
	// ID uniquely identifies the projection.
	ID brand.ProjectionID
	// Init is the initial state.
	Init S
	// Apply incrementally applies an event to state.
	Apply func(state S, ev SessionEvent) S
	// Merge rebuilds state from complete event history, matching its fold function.
	Merge func(events []SessionEvent) S
}

ProjectionDefinition defines one projection.

type ProjectionState

type ProjectionState interface {
	// Equal detects state changes for incremental changelog entries.
	Equal(other ProjectionState) bool
}

ProjectionState constrains projection state types.

type ProjectionUpdateData

type ProjectionUpdateData struct {
	ProjectionID brand.ProjectionID `json:"projectionId"`
	Hash         string             `json:"hash,omitempty"`
}

ProjectionUpdateData records a projection-state update.

func (ProjectionUpdateData) EventType

func (ProjectionUpdateData) EventType() EventType

type Reason

type Reason string

Reason identifies why a request is rebuilt.

const (
	ReasonInitial Reason = "initial"
	ReasonResume  Reason = "resume"
	ReasonChange  Reason = "change"
	ReasonSeries  Reason = "series"
)

Request rebuild reasons.

type ReferenceResolution

type ReferenceResolution struct {
	Kind  MentionKind `json:"kind"`
	Raw   string      `json:"raw,omitempty"`
	Value string      `json:"value"`
	Label string      `json:"label,omitempty"`
	Slice string      `json:"slice,omitempty"` // Text fragment aggregated into additionalContext.
}

ReferenceResolution records one resolved reference for Refs auditing.

type Registry

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

Registry stores registered projections.

func NewProjectionRegistry

func NewProjectionRegistry() *Registry

NewProjectionRegistry creates an empty registry.

func (*Registry) ApplyEvents

func (r *Registry) ApplyEvents(events []SessionEvent)

ApplyEvents incrementally updates all projections and records changelog entries.

func (*Registry) Changelog

func (r *Registry) Changelog() []ProjectionChange

Changelog returns a snapshot in production order.

func (*Registry) Rebuild

func (r *Registry) Rebuild(events []SessionEvent)

Rebuild replays complete history into all projections for consistency checking.

func (*Registry) SnapshotAll

func (r *Registry) SnapshotAll() map[brand.ProjectionID]any

SnapshotAll returns a map of all current projection states.

type ReplaceRange

type ReplaceRange struct {
	Start uint64 `json:"start"`
	End   uint64 `json:"end"`
}

ReplaceRange is an inclusive sequence range covered by a surface replacement.

type RequestContext

type RequestContext struct {
	// Provider identifies the model provider.
	Provider string `json:"provider"`
	// Model names the model.
	Model string `json:"model"`
	// ContextWindow specifies context capacity.
	ContextWindow int `json:"contextWindow,omitempty"`
	// Reason identifies the rebuild trigger.
	Reason Reason `json:"reason,omitempty"`
}

RequestContext records request routing information.

func FoldRequestContext

func FoldRequestContext(events []SessionEvent) (RequestContext, bool)

FoldRequestContext returns the latest request/context state.

type RequestContextData

type RequestContextData struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
	Window   int    `json:"contextWindow,omitempty"`
	Reason   string `json:"reason,omitempty"` // initial/resume/change/series
}

RequestContextData records provider, model, and context-window routing.

func (RequestContextData) EventType

func (RequestContextData) EventType() EventType

type RequestHeaderData

type RequestHeaderData struct {
	ConfigEpoch uint64 `json:"configEpoch"`
	SystemHash  string `json:"systemHash,omitempty"`
	ToolCount   int    `json:"toolCount,omitempty"`
}

RequestHeaderData snapshots configuration, system, and tool epochs.

func (RequestHeaderData) EventType

func (RequestHeaderData) EventType() EventType

type RequestHeaderFold

type RequestHeaderFold struct {
	Present     bool   `json:"present"`
	ConfigEpoch uint64 `json:"configEpoch,omitempty"`
	SystemHash  string `json:"systemHash,omitempty"`
	ToolCount   int    `json:"toolCount,omitempty"`
}

RequestHeaderFold is the latest request/header snapshot.

func ApplyRequestHeader

func ApplyRequestHeader(s RequestHeaderFold, ev SessionEvent) RequestHeaderFold

ApplyRequestHeader keeps the latest request header.

func FoldRequestHeader

func FoldRequestHeader(events []SessionEvent) RequestHeaderFold

FoldRequestHeader exposes request-header derivation.

func (RequestHeaderFold) Equal

Equal compares request-header projections.

type RequestHeaderSnapshot

type RequestHeaderSnapshot struct {
	// Header contains the epoch snapshot.
	Header EpochHeader `json:"header"`
	// Context contains routing information.
	Context RequestContext `json:"context"`
	// SystemPrompt contains text used for rebuilding.
	SystemPrompt string `json:"systemPrompt,omitempty"`
	// ToolSchemas contains tool-schema JSON used for rebuilding.
	ToolSchemas json.RawMessage `json:"toolSchemas,omitempty"`
}

RequestHeaderSnapshot contains the complete request-rebuild inputs.

func (*RequestHeaderSnapshot) SnapshotHash

func (s *RequestHeaderSnapshot) SnapshotHash() string

SnapshotHash detects snapshot drift by concatenating key fields in this simplified implementation.

type SandboxMode

type SandboxMode string

SandboxMode identifies the sandbox access mode.

const (
	SandboxReadOnly         SandboxMode = "read-only"
	SandboxWorkspaceWrite   SandboxMode = "workspace-write"
	SandboxDangerFullAccess SandboxMode = "danger-full-access"
)

Supported sandbox modes.

type SandboxModeData

type SandboxModeData struct {
	Mode   string `json:"mode"`
	Source string `json:"source,omitempty"`
}

SandboxModeData records a log-only sandbox override excluded from the model transcript. The latest event wins, matching upstream session-mode semantics. A delegation source marks an override installed for a subagent.

func (SandboxModeData) EventType

func (SandboxModeData) EventType() EventType

type SeqRange

type SeqRange struct {
	From int
	To   int
}

SeqRange is inclusive; equal endpoints represent one sequence number.

func EncodeSeqRanges

func EncodeSeqRanges(values []int) []SeqRange

EncodeSeqRanges compresses strictly increasing values, otherwise preserving them as singletons.

type SessionEvent

type SessionEvent struct {
	// Seq increases contiguously from one.
	Seq uint64 `json:"seq"`
	// Time records monotonic event write time.
	Time time.Time `json:"time"`
	// Type identifies the event variant.
	Type EventType `json:"type"`
	// Data contains the typed payload union.
	Data EventData `json:"data"`
	// SurfaceOp describes read-time surface replacement, the supported compaction mechanism.
	SurfaceOp *SurfaceOp `json:"surfaceOp,omitempty"`
	// SourceEventSeqs records source sequences for compaction and derived messages.
	SourceEventSeqs []uint64 `json:"sourceEventSeqs,omitempty"`
}

SessionEvent represents one log entry.

func EffectiveEvents

func EffectiveEvents(events []SessionEvent) []SessionEvent

EffectiveEvents returns events not hidden by surface replacements, preserving their original order. Replacement intervals are inclusive and clipped to the replacing event's sequence number. The source events are never modified.

func (SessionEvent) MarshalJSON

func (e SessionEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes seq, time, type, data, and optional surface/source fields.

func (*SessionEvent) UnmarshalJSON

func (e *SessionEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON restores the event and dispatches its payload by type.

type SessionFormatUnsupportedError

type SessionFormatUnsupportedError struct {
	Version int
}

SessionFormatUnsupportedError indicates a rejected session format version.

func (*SessionFormatUnsupportedError) Error

Error implements the error interface.

type SessionHeader

type SessionHeader struct {
	// Version is written on serialization and checked fail-closed on loading.
	Version int `json:"version"`
	// ID uniquely identifies the session.
	ID brand.SessionID `json:"id"`
	// CreatedAt records session creation time.
	CreatedAt time.Time `json:"createdAt"`
	// Cwd is the working directory used by filesystem tools and relative paths.
	Cwd string `json:"cwd,omitempty"`
	// ParentSession records the fork source; empty means no parent.
	ParentSession brand.SessionID `json:"parentSession,omitempty"`
	// SeedLength counts stored events replayed during Resume/Fork and locates
	// the boundary between seed history and live work.
	SeedLength uint64 `json:"seedLength,omitempty"`
	// Origin is created, fork, or resume.
	Origin HeaderOrigin `json:"origin,omitempty"`
	// DelegationDepth counts recursive subagent levels, starting at zero.
	DelegationDepth int `json:"delegationDepth,omitempty"`
	// AgentPreset names the bound agent preset.
	AgentPreset string `json:"agentPreset,omitempty"`
}

SessionHeader contains static session metadata.

func NewSessionHeader

func NewSessionHeader(id brand.SessionID, cwd string) *SessionHeader

NewSessionHeader creates a current-version header with created origin and zero depth.

func UnmarshalSessionHeader

func UnmarshalSessionHeader(data []byte) (*SessionHeader, error)

UnmarshalSessionHeader decodes the header and rejects unsupported versions to avoid interpreting data with incompatible format rules.

func (*SessionHeader) Fork

func (h *SessionHeader) Fork(childID brand.SessionID) *SessionHeader

Fork derives a child header with this ID as ParentSession, fork origin, and depth increased by one. The caller sets SeedLength after replaying seeds.

func (*SessionHeader) Marshal

func (h *SessionHeader) Marshal() ([]byte, error)

Marshal serializes the header as JSON.

func (*SessionHeader) Validate

func (h *SessionHeader) Validate() error

Validate checks header completeness after loading.

type SessionLog

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

SessionLog owns the sole append path for the event-sourced log.

func NewSessionLog

func NewSessionLog(id brand.SessionID) *SessionLog

NewSessionLog creates an empty log and registers temporal invariant checks.

func (*SessionLog) Append

func (sl *SessionLog) Append(data EventData) (uint64, error)

Append is the sole write path. It assigns contiguous sequence numbers and monotonic timestamps, then rejects invalid turn, step, or tool pairing.

func (*SessionLog) Check

func (sl *SessionLog) Check() []error

Check validates whole-log turn, step, and tool pairing before persistence or flushing. Append already checks individual transitions; complete-log balance checks are unnecessary after each append because intermediate structures may legitimately remain open.

func (*SessionLog) DisableIncrementalProjection

func (sl *SessionLog) DisableIncrementalProjection()

DisableIncrementalProjection disables incremental state for performance comparisons.

func (*SessionLog) EnableIncrementalProjection

func (sl *SessionLog) EnableIncrementalProjection()

EnableIncrementalProjection establishes a baseline through FolderFromEvents if history already exists, then applies future appends incrementally. Without it, callers may continue using FoldAllFromLog.

func (*SessionLog) Events

func (sl *SessionLog) Events() []SessionEvent

Events returns a read-only snapshot of the event list.

func (*SessionLog) IncrementalEnabled

func (sl *SessionLog) IncrementalEnabled() bool

IncrementalEnabled reports whether incremental projections are enabled.

func (*SessionLog) IncrementalStats

func (sl *SessionLog) IncrementalStats() FolderStats

IncrementalStats returns counters, or zero FolderStats when disabled.

func (*SessionLog) LastSeq

func (sl *SessionLog) LastSeq() uint64

LastSeq returns the latest sequence number, or zero for an empty log.

func (*SessionLog) Len

func (sl *SessionLog) Len() int

Len returns the number of events.

func (*SessionLog) NextStep

func (sl *SessionLog) NextStep() uint64

NextStep returns the next step number, reset to one for each turn.

func (*SessionLog) NextTurn

func (sl *SessionLog) NextTurn() uint64

NextTurn returns the next zero-based turn number so Agent can construct turn/start.

func (*SessionLog) OpenStep

func (sl *SessionLog) OpenStep() (uint64, bool)

OpenStep returns the open step number, or zero and false if none.

func (*SessionLog) OpenTurn

func (sl *SessionLog) OpenTurn() (uint64, bool)

OpenTurn returns the open turn number, or zero and false if none.

func (*SessionLog) Projection

func (sl *SessionLog) Projection() SessionProjection

Projection returns current derived state. With incremental folding enabled, Snapshot reuses metadata and lazily rebuilds dirty messages; otherwise it falls back to a complete FoldAllFromLog.

func (*SessionLog) ProjectionMeta

func (sl *SessionLog) ProjectionMeta() SessionProjection

ProjectionMeta omits Messages to avoid large message-slice copies on hot paths. It returns header, sandbox, approval, preset, goal, todo, plan, and title.

func (*SessionLog) SandboxMode

func (sl *SessionLog) SandboxMode() (SandboxMode, bool)

SandboxMode returns the latest logged sandbox/mode override, or ok false if absent, matching upstream effectiveSandboxMode.

func (*SessionLog) SessionID

func (sl *SessionLog) SessionID() brand.SessionID

SessionID identifies the owning session.

type SessionProjection

type SessionProjection struct {
	Messages      []Message               `json:"messages"`
	RequestHeader RequestHeaderFold       `json:"requestHeader"`
	SandboxMode   EffectiveSandboxMode    `json:"sandboxMode"`
	Approval      EffectiveApprovalPolicy `json:"approvalPolicy"`
	Preset        PermissionPresetFold    `json:"preset"`
	Goal          GoalFold                `json:"goal"`
	Todo          TodoFold                `json:"todo"`
	PlanMode      PlanModeFold            `json:"planMode"`
	Title         SessionTitleFold        `json:"title"`
}

SessionProjection aggregates all derived projections.

func FoldAll

func FoldAll(events []SessionEvent) SessionProjection

FoldAll replays the event list to derive all projection states.

func FoldAllFromLog

func FoldAllFromLog(sl *SessionLog) SessionProjection

FoldAllFromLog derives projections directly from a SessionLog snapshot.

type SessionReferenceError

type SessionReferenceError struct {
	Code SessionReferenceErrorCode
	Msg  string
}

SessionReferenceError carries a stable reference error code.

func (*SessionReferenceError) Error

func (e *SessionReferenceError) Error() string

type SessionReferenceErrorCode

type SessionReferenceErrorCode string

SessionReferenceErrorCode identifies a reference failure category.

const (
	// RefCodeInvalidConfig indicates missing or invalid resolver/workspace configuration.
	RefCodeInvalidConfig SessionReferenceErrorCode = "SESSION_REFERENCE_INVALID_CONFIG"
	// RefCodeInvalidReference indicates invalid syntax or target.
	RefCodeInvalidReference SessionReferenceErrorCode = "SESSION_REFERENCE_INVALID_REFERENCE"
	// RefCodeSelfReference indicates a reference to the requesting agent's own session.
	RefCodeSelfReference SessionReferenceErrorCode = "SESSION_REFERENCE_SELF_REFERENCE"
	// RefCodeTooMany indicates the reference count exceeds the limit.
	RefCodeTooMany SessionReferenceErrorCode = "SESSION_REFERENCE_TOO_MANY"
	// RefCodeReadFailed indicates failure reading a source session.
	RefCodeReadFailed SessionReferenceErrorCode = "SESSION_REFERENCE_READ_FAILED"
	// RefCodeBudgetExceeded indicates aggregated context exceeds its budget.
	RefCodeBudgetExceeded SessionReferenceErrorCode = "SESSION_REFERENCE_BUDGET_EXCEEDED"
	// RefCodeCancelled indicates canceled reference preparation.
	RefCodeCancelled SessionReferenceErrorCode = "SESSION_REFERENCE_CANCELLED"
	// RefCodeSessionNotFound indicates the referenced session is missing (M17).
	RefCodeSessionNotFound SessionReferenceErrorCode = "SESSION_NOT_FOUND"
	// RefCodeFileNotFound indicates the referenced file is missing (M17).
	RefCodeFileNotFound SessionReferenceErrorCode = "FILE_NOT_FOUND"
	// RefCodeFileOutOfWorkspace rejects files outside the workspace root.
	RefCodeFileOutOfWorkspace SessionReferenceErrorCode = "FILE_OUT_OF_WORKSPACE"
)

Codes match upstream, with M17 additions for missing files and sessions.

func RefCodeFrom

func RefCodeFrom(err error) SessionReferenceErrorCode

RefCodeFrom extracts a stable reference code, returning empty for other errors.

type SessionReferenceInput

type SessionReferenceInput struct {
	// SessionID is the authoritative source-session identity.
	SessionID brand.SessionID
	// Label is an optional display label included in the snapshot.
	Label string
}

SessionReferenceInput is a host-provided structured source-session selection.

type SessionReferenceResolver

type SessionReferenceResolver interface {
	// ResolveSession returns readable snapshot text, RefCodeSessionNotFound
	// for a missing session, or RefCodeReadFailed for read errors.
	ResolveSession(id brand.SessionID) (string, error)
	// ResolveFile returns a summary, RefCodeFileNotFound for missing files,
	// or RefCodeFileOutOfWorkspace for targets outside the root.
	ResolveFile(path string) (string, error)
	// WorkspaceRoot returns the agent's workspace boundary for file containment checks.
	WorkspaceRoot() string
}

SessionReferenceResolver converts mention targets into context fragments. Session reads depend on persistence (M43), file reads on Filesystem (M35). Hosts and tests may inject real or stub implementations; the workspace file resolver provides existence and containment checks without reading contents.

type SessionTitleData

type SessionTitleData struct {
	Title string `json:"title"`
}

SessionTitleData records the latest-wins session title.

func (SessionTitleData) EventType

func (SessionTitleData) EventType() EventType

type SessionTitleFold

type SessionTitleFold struct {
	Present bool   `json:"present"`
	Title   string `json:"title,omitempty"`
}

SessionTitleFold is the latest session-title projection.

func ApplySessionTitle

func ApplySessionTitle(s SessionTitleFold, ev SessionEvent) SessionTitleFold

ApplySessionTitle keeps the latest session title.

func FoldSessionTitle

func FoldSessionTitle(events []SessionEvent) SessionTitleFold

FoldSessionTitle exposes session-title derivation.

func (SessionTitleFold) Equal

Equal compares session-title projections.

type SkillInjectData

type SkillInjectData struct {
	SkillName string `json:"skillName"`
	Content   string `json:"content,omitempty"`
}

SkillInjectData records skill content injected as a user message.

func (SkillInjectData) EventType

func (SkillInjectData) EventType() EventType

type SkillsCatalogData

type SkillsCatalogData struct {
	Catalog string `json:"catalog"`
	Hash    string `json:"hash"`
}

SkillsCatalogData records a complete skill catalog for change-only injection.

func (SkillsCatalogData) EventType

func (SkillsCatalogData) EventType() EventType

type SkillsChangeData

type SkillsChangeData struct {
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
	Changed []string `json:"changed,omitempty"`
}

SkillsChangeData records changes to the skill catalog.

func (SkillsChangeData) EventType

func (SkillsChangeData) EventType() EventType

type StepEndData

type StepEndData struct {
	Turn    uint64 `json:"turn"`
	Step    uint64 `json:"step"`
	StepSeq uint64 `json:"stepSeq,omitempty"` // Legacy field equivalent to Step.
}

StepEndData records step/end.

func (StepEndData) EventType

func (StepEndData) EventType() EventType

type StepStartData

type StepStartData struct {
	Turn    uint64 `json:"turn"`
	Step    uint64 `json:"step"`
	StepSeq uint64 `json:"stepSeq,omitempty"` // Legacy field equivalent to Step.
}

StepStartData records step/start. Step numbers start at one and increase within each turn, resetting when the next turn begins.

func (StepStartData) EventType

func (StepStartData) EventType() EventType

type SurfaceNode

type SurfaceNode struct {
	// Seq is the event sequence number.
	Seq uint64
	// Replaced reports whether this node carries a replace operation.
	Replaced bool
	// Event is the complete event represented by this node.
	Event SessionEvent
}

SurfaceNode is a visible original or replacement event after surface folding.

type SurfaceOp

type SurfaceOp struct {
	Op    SurfaceOpKind   `json:"op"`
	Start uint64          `json:"start,omitempty"`
	End   uint64          `json:"end,omitempty"`
	Data  json.RawMessage `json:"data,omitempty"`
}

SurfaceOp describes a persisted operation on the session's visible history. For replace operations, Start and End bound the inclusive source sequence range and Data holds the replacement payload. The operation is applied when reading SessionEvent.surfaceOp; it never rewrites the source events.

func NewAppendOp

func NewAppendOp() *SurfaceOp

NewAppendOp constructs an explicit append marker.

func NewReplaceOp

func NewReplaceOp(start, end uint64, data json.RawMessage) *SurfaceOp

NewReplaceOp constructs a replacement marker.

type SurfaceOpKind

type SurfaceOpKind string

SurfaceOpKind identifies a surface operation.

const (
	// SurfaceAppend is the default append operation and need not be specified explicitly.
	SurfaceAppend SurfaceOpKind = "append"
	// SurfaceReplace replaces an inclusive historical range at read time.
	// Source events remain immutable; compaction changes only the derived view.
	SurfaceReplace SurfaceOpKind = "replace"
)

Supported surface operations.

type SurfaceReplaceData

type SurfaceReplaceData struct {
	Start uint64          `json:"start"`
	End   uint64          `json:"end"`
	Data  json.RawMessage `json:"data,omitempty"`
}

SurfaceReplaceData records compaction's read-time replacement of history.

func (SurfaceReplaceData) EventType

func (SurfaceReplaceData) EventType() EventType

type TodoEntry

type TodoEntry struct {
	Content string `json:"content"`
	Status  string `json:"status"` // pending | in_progress | completed
}

TodoEntry is a todo item with one of three statuses, matching upstream TodoItem.

type TodoFold

type TodoFold struct {
	Present bool        `json:"present"`
	Items   []string    `json:"items,omitempty"`
	Entries []TodoEntry `json:"entries,omitempty"`
}

TodoFold is the todo-list projection, replaced in full by the latest write.

func ApplyTodoWrite

func ApplyTodoWrite(s TodoFold, ev SessionEvent) TodoFold

ApplyTodoWrite replaces the todo state with the latest complete value.

func FoldTodoWrite

func FoldTodoWrite(events []SessionEvent) TodoFold

FoldTodoWrite exposes todo-list derivation.

func (TodoFold) Equal

func (t TodoFold) Equal(o ProjectionState) bool

Equal compares todo projections.

type TodoWriteData

type TodoWriteData struct {
	Items   []string    `json:"items,omitempty"`
	Entries []TodoEntry `json:"entries,omitempty"`
}

TodoWriteData replaces the complete todo list. Items is the content-only compatibility field; Entries retains three-state status.

func (TodoWriteData) EventType

func (TodoWriteData) EventType() EventType

type ToolCallData

type ToolCallData struct {
	CallID brand.ToolCallID `json:"callId"`
	Tool   string           `json:"tool"`
	Input  json.RawMessage  `json:"input,omitempty"`
}

ToolCallData records initiation of a tool call.

func (ToolCallData) EventType

func (ToolCallData) EventType() EventType

type ToolErrorData

type ToolErrorData struct {
	CallID brand.ToolCallID `json:"callId"`
	Error  string           `json:"error"`
}

ToolErrorData records a tool execution failure.

func (ToolErrorData) EventType

func (ToolErrorData) EventType() EventType

type ToolObservedData

type ToolObservedData struct {
	CallID brand.ToolCallID `json:"callId"`
	Kind   string           `json:"kind"`
}

ToolObservedData records observable tool effects, including read-before-write observations.

func (ToolObservedData) EventType

func (ToolObservedData) EventType() EventType

type ToolPresentationData

type ToolPresentationData struct {
	CallID brand.ToolCallID `json:"callId"`
	Card   string           `json:"card"`
}

ToolPresentationData records a presentation card using neutral vocabulary.

func (ToolPresentationData) EventType

func (ToolPresentationData) EventType() EventType

type ToolResultData

type ToolResultData struct {
	CallID    brand.ToolCallID `json:"callId"`
	IsError   bool             `json:"isError,omitempty"`
	Output    string           `json:"output,omitempty"`
	Truncated bool             `json:"truncated,omitempty"`
	SpillPath string           `json:"spillPath,omitempty"`
}

ToolResultData records a tool result paired with its call by CallID.

func (ToolResultData) EventType

func (ToolResultData) EventType() EventType

type TurnEndData

type TurnEndData struct {
	Turn   uint64        `json:"turn"`
	Reason TurnEndReason `json:"reason"`
}

TurnEndData records turn/end.

func (TurnEndData) EventType

func (TurnEndData) EventType() EventType

type TurnEndReason

type TurnEndReason string

TurnEndReason identifies why a turn ended.

const (
	ReasonCompleted   TurnEndReason = "completed"
	ReasonFinished    TurnEndReason = "finished" // Legacy alias for completed.
	ReasonInterrupted TurnEndReason = "interrupted"
	ReasonAborted     TurnEndReason = "aborted"
	ReasonBlocked     TurnEndReason = "blocked"
	ReasonError       TurnEndReason = "error"
	ReasonMaxTokens   TurnEndReason = "max-tokens"
)

Turn endings match upstream TurnEndReasonMap: completed, aborted, blocked, error, max-tokens, and interrupted.

type TurnStartData

type TurnStartData struct {
	Turn uint64 `json:"turn"`
}

TurnStartData records turn/start. Turn numbers increase monotonically from zero, independently within each session.

func (TurnStartData) EventType

func (TurnStartData) EventType() EventType

type TurnStoppingData

type TurnStoppingData struct {
	Reason string `json:"reason,omitempty"`
}

TurnStoppingData marks turn/stopping for listeners such as the goal-round driver.

func (TurnStoppingData) EventType

func (TurnStoppingData) EventType() EventType

type UserMessageData

type UserMessageData struct {
	Content string `json:"content"`
	Source  string `json:"source,omitempty"` // e.g. "user" / "reference" / "injected"
	Refs    []any  `json:"refs,omitempty"`   // Referenced sessions or files.
}

UserMessageData records user/message.

func (UserMessageData) EventType

func (UserMessageData) EventType() EventType

type UserQuestionData

type UserQuestionData struct {
	Question string `json:"question"`
	Answer   string `json:"answer,omitempty"`
}

UserQuestionData records a user-question interaction.

func (UserQuestionData) EventType

func (UserQuestionData) EventType() EventType

type WorkspaceChangeData

type WorkspaceChangeData struct {
	WorkspaceID brand.WorkspaceID `json:"workspaceId"`
	Root        string            `json:"root,omitempty"`
}

WorkspaceChangeData records workspace metadata changes.

func (WorkspaceChangeData) EventType

func (WorkspaceChangeData) EventType() EventType

type WorkspaceFileResolver

type WorkspaceFileResolver struct {
	Root string
}

WorkspaceFileResolver checks file existence and workspace containment only. Like upstream path-only discovery, it does not read contents; content access belongs to the M35 Filesystem interface.

func (*WorkspaceFileResolver) ResolveFile

func (r *WorkspaceFileResolver) ResolveFile(path string) (string, error)

ResolveFile checks existence and returns a path-only summary; M35 handles content reads.

func (*WorkspaceFileResolver) ResolveSession

func (r *WorkspaceFileResolver) ResolveSession(brand.SessionID) (string, error)

ResolveSession reports an invalid-hook error because this resolver has no session capability.

func (*WorkspaceFileResolver) WorkspaceRoot

func (r *WorkspaceFileResolver) WorkspaceRoot() string

WorkspaceRoot returns the configured workspace root.

Jump to

Keyboard shortcuts

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