Documentation
¶
Overview ¶
Package thread folds raw history facts into conversation-owned thread items.
Index ¶
- Constants
- Variables
- type Change
- type CheckpointCompatibilityError
- type CheckpointItem
- type CheckpointState
- type ChildCursor
- type ChildPageResult
- type ChildSummary
- type CompactQueryResult
- type Fold
- func (f *Fold) ExportCheckpoint() (CheckpointState, []CheckpointItem, error)
- func (f *Fold) Feed(entries []history.Entry) error
- func (f *Fold) FeedChanges(entries []history.Entry) (Observation, error)
- func (f *Fold) Items() []Item
- func (f *Fold) Observe() Observation
- func (f *Fold) Render() ([]Item, error)
- func (f *Fold) Version() uint64
- type HistorySource
- type Item
- type Observation
- type QueryResult
- type Snapshot
- type SnapshotState
- type Store
- func (s *Store) CatchUp(ctx context.Context, id conversations.ConversationID, epoch string, ...) (QueryResult, error)
- func (s *Store) Changes(ctx context.Context, id conversations.ConversationID, epoch string, ...) (Observation, error)
- func (s *Store) ChildPage(ctx context.Context, id conversations.ConversationID, epoch string, ...) (ChildPageResult, error)
- func (s *Store) CompactCatchUp(ctx context.Context, id conversations.ConversationID, epoch string, ...) (CompactQueryResult, error)
- func (s *Store) CompactChanges(ctx context.Context, id conversations.ConversationID, epoch string, ...) (CompactQueryResult, error)
- func (s *Store) CompactHistoryPage(ctx context.Context, id conversations.ConversationID, upperOrder uint64, ...) (CompactQueryResult, error)
- func (s *Store) CompactNewestWindow(ctx context.Context, id conversations.ConversationID, limit int) (CompactQueryResult, error)
- func (s *Store) HistoryPage(ctx context.Context, id conversations.ConversationID, upperOrder uint64, ...) (QueryResult, error)
- func (s *Store) Load(ctx context.Context, id conversations.ConversationID) error
- func (s *Store) NewestWindow(ctx context.Context, id conversations.ConversationID, limit int) (QueryResult, error)
- func (s *Store) Observe(id conversations.ConversationID) Observation
- func (s *Store) Retry(ctx context.Context, id conversations.ConversationID) error
- func (s *Store) Shutdown() error
- func (s *Store) Snapshot(id conversations.ConversationID) Snapshot
- func (s *Store) Status(id conversations.ConversationID) Snapshot
- func (s *Store) ToolBody(ctx context.Context, id conversations.ConversationID, expectedEpoch string, ...) (ToolBodyResult, error)
- func (s *Store) Unload(id conversations.ConversationID) error
- func (s *Store) UnloadedLastShownVersion(id conversations.ConversationID) (uint64, bool)
- type ToolBodyResult
Constants ¶
const MaxCatchUpGap = 1024
MaxCatchUpGap is the inclusive maximum consumed history-ID distance for catch-up.
const MaxQueryItems = 256
MaxQueryItems caps ordered rows requested in a page or newest window. Active items, parent closure and ties at the lower bound are additional rows.
Variables ¶
var ( ErrInvalidChildScope = errors.New("thread: child page requires epoch, parent and revision") ErrChildParentNotFound = errors.New("thread: public child-page parent not found") ErrStaleChildPage = errors.New("thread: stale child page capture") ErrInvalidChildCursor = errors.New("thread: invalid child page cursor") )
var ( ErrClosed = errors.New("thread: store is shut down") ErrUnloading = errors.New("thread: conversation is unloading") ErrNotLoaded = errors.New("thread: conversation is not loaded") )
var ( ErrInvalidBodyScope = errors.New("thread: body requires epoch, item ID and revision") ErrStaleBody = errors.New("thread: body epoch or revision is stale") ErrBodyNotFound = errors.New("thread: body item is not public") ErrBodyKind = errors.New("thread: body item must be tool_call or agent") )
var ErrInvalidLimit = errors.New("thread: query limit must be positive")
var ErrPersistence = errors.New("thread: cache persistence unavailable")
ErrPersistence reports a recoverable cache I/O failure.
Functions ¶
This section is empty.
Types ¶
type Change ¶
type Change struct {
ID, PreviousRev, Rev, Version uint64
Addition *Item
Fields map[string]json.RawMessage
TextAppend string
// ResultContent is the complete resulting content for a combined field/text
// change. It lets consumers publish one atomic replacement without changing
// the Fields-then-TextAppend application contract. Suffix-only changes omit it.
ResultContent json.RawMessage
}
Change applies to ID at PreviousRev, producing Rev. Fields use Item field names and replace values, including zero/null. Apply Fields, then TextAppend to Content.text, then Rev. Addition instead supplies the complete new item. Version is the consumed publication boundary, which may exceed Rev.
type CheckpointCompatibilityError ¶ added in v0.40.3
type CheckpointCompatibilityError struct{ Schema, Rules int }
CheckpointCompatibilityError identifies an unsupported schema or folding rules.
func (*CheckpointCompatibilityError) Error ¶ added in v0.40.3
func (e *CheckpointCompatibilityError) Error() string
type CheckpointItem ¶ added in v0.40.3
type CheckpointItem struct {
Metadata checkpointMetadata `json:"metadata"`
Recipe checkpointRecipe `json:"recipe"`
}
CheckpointItem holds metadata and an unrendered recipe for every internal row, including unresolved children and suppressed deliveries. It owns its storage.
type CheckpointState ¶ added in v0.40.3
type CheckpointState struct {
Schema int `json:"schema"`
Rules int `json:"rules"`
ConversationID string `json:"conversation_id"`
Version uint64 `json:"version"`
LastShown uint64 `json:"last_shown"`
Suppressed uint64 `json:"suppressed"`
UnprovenThrough uint64 `json:"unproven_through"`
ItemIDs []uint64 `json:"item_ids"`
Published map[uint64]bool `json:"published"`
Touches map[uint64]uint64 `json:"touches"`
PublicVisible map[uint64]bool `json:"public_visible"`
Successor checkpointSource `json:"successor"`
LastBoundary uint64 `json:"last_boundary"`
LegacyScope uint64 `json:"legacy_scope"`
PendingBoundaries []checkpointBoundary `json:"pending_boundaries"`
CurrentTurns []checkpointTurnRef `json:"current_turns"`
Openings map[uint64]int `json:"openings"`
OpenTexts []int `json:"open_texts"`
Turns []checkpointTurn `json:"turns"`
MainCalls []checkpointMainCall `json:"main_calls"`
Outcomes []checkpointOutcome `json:"outcomes"`
Accepted map[uint64]int `json:"accepted"`
Messages map[uint64]int `json:"messages"`
ChildTurns []checkpointChildTurn `json:"child_turns"`
ChildCalls []checkpointChildCall `json:"child_calls"`
ChildReports []checkpointChildCall `json:"child_reports"`
Children map[int]checkpointChild `json:"children"`
ChildEndings map[int]checkpointEnding `json:"child_endings"`
Groups []checkpointGroup `json:"groups"`
AgentCalls []checkpointAgentCall `json:"agent_calls"`
Reports []checkpointReport `json:"reports"`
Lifetimes []checkpointLifetime `json:"lifetimes"`
Observations map[uint64][]checkpointObservation `json:"observations"`
}
CheckpointState is the private continuation part of a reference fold checkpoint. ItemIDs is the complete creation-ordered manifest for the separate item records. Table references are one-based, with zero meaning nil. Item indexes are zero-based and retain negative sentinels. Importers must validate both parts.
type ChildCursor ¶ added in v0.41.0
type ChildCursor struct {
ConversationID conversations.ConversationID
Epoch string
Version, Parent, ParentRev uint64
Order, ID uint64
}
ChildCursor is a position within one exact publication and parent revision. It is consistency evidence, not authorization or a wire encoding.
type ChildPageResult ¶ added in v0.41.0
type ChildPageResult struct {
State SnapshotState
ConversationID conversations.ConversationID
Epoch string
Version, Parent, ParentRev uint64
Items []ChildSummary
More, Complete bool
Err error
}
ChildPageResult carries authoritative completion only for StateUsable. Rows are strictly direct children, ascending by (Order, ID), without extras.
func (ChildPageResult) CursorAfter ¶ added in v0.41.0
func (p ChildPageResult) CursorAfter(n int) (ChildCursor, error)
CursorAfter resumes after the first n returned rows, allowing byte packers to deliver a nonempty prefix without skipping selected but undelivered rows.
type ChildSummary ¶ added in v0.41.0
type ChildSummary struct {
ID, Order, Rev uint64
EndedOrder uint64
Kind, Subtype, Session, Agent string
NoChild bool
Turn string
Parent uint64
Status string
Active, Shown bool
Headline string
DetailOmitted bool
ErrorSummary *string
PublicChildCount *uint64
HasPublicChildren *bool
SubtreeVersion *uint64
}
ChildSummary is detached metadata. DetailOmitted distinguishes absent detail from an available empty body. Headline/error are plain text of at most 200 Unicode code points. Nil facts are unknown; known counts include public hidden and dropped rows. SubtreeVersion is epoch-scoped freshness independent of Rev.
type CompactQueryResult ¶ added in v0.41.0
type CompactQueryResult struct {
State SnapshotState
ConversationID conversations.ConversationID
Projection, Epoch string
Version uint64
Items []Item
Headers []ChildSummary
LowerOrder, UpperOrder, Continuation uint64
OlderExists bool
FromVersion uint64 // exclusive interval bound for nonzero catch-up and live progress
ResetRequired bool // no rows or bounds; reinitialize with a version-zero window
Err error
}
CompactQueryResult certifies a compact root range in one publication, without certifying complete-thread or expansion coverage. Only StateUsable carries identity, rows and bounds. Items and Headers have no presentation-order guarantee.
type Fold ¶
type Fold struct {
// contains filtered or unexported fields
}
Fold belongs to one conversation. Its owner must serialize all access. The zero value is not bound to a conversation; construct folds with New.
func ImportCheckpoint ¶ added in v0.40.3
func ImportCheckpoint(conversationID string, source HistorySource, d CheckpointState, rows []CheckpointItem) (*Fold, error)
ImportCheckpoint restores detached continuation state without reading history or rendering. It returns no fold on invalid input. The expected owner and source must belong to the same conversation; source contents are verified when used.
func NewReference ¶ added in v0.40.3
func NewReference(conversationID string, source HistorySource) *Fold
NewReference creates a fold that retains history references rather than inline payloads. The caller supplies a non-nil source for the conversation's history.
func (*Fold) ExportCheckpoint ¶ added in v0.40.3
func (f *Fold) ExportCheckpoint() (CheckpointState, []CheckpointItem, error)
ExportCheckpoint returns two detached JSON-compatible parts without reading history or rendering content. The owner must serialize access and call it at a completed Feed boundary. Inline folds made with New do not support export.
func (*Fold) Feed ¶
Feed consumes increasing IDs. Unsupported or malformed facts still advance version, but cannot affect items, attribution or joins. An invalid ID returns an error before consuming that entry; earlier entries remain consumed. Reference folds can also fail when resolving a claimed delivery's content.
func (*Fold) FeedChanges ¶
func (f *Fold) FeedChanges(entries []history.Entry) (Observation, error)
FeedChanges consumes entries with Feed's partial-error semantics and returns detached progress from the pre-feed baseline, after private joins resolve.
func (*Fold) Items ¶
Items returns a creation-ID-ordered snapshot that callers may mutate independently. Claimed delivery rows are represented by their permanent acceptance item.
func (*Fold) Observe ¶
func (f *Fold) Observe() Observation
Observe returns a detached complete baseline. Fold access must be serialized.
type HistorySource ¶ added in v0.40.3
HistorySource supplies immutable history entries by ID. A fold's owner must serialize access and keep the source available for subsequent Feed and Render.
type Item ¶
type Item struct {
ID, Order, Rev uint64
EndedOrder uint64
Kind, Session, Agent string
NoChild bool
Turn string
Parent uint64
Status string
Active, Shown bool
Summary, Subtype string
Content json.RawMessage
}
Item is a stable row. Content retains the source kind's saved JSON fields as inert data; NoChild distinguishes explicit no-child provenance from unknown.
type Observation ¶
Observation is either a complete baseline (Items) or progress from FromVersion through Version. BaselineRequired carries no applicable changes: acquire a new baseline. Only usable observations carry epoch, versions or watermark.
type QueryResult ¶
type QueryResult struct {
State SnapshotState
Items []Item
Epoch string
Version uint64
LowerOrder, UpperOrder, Continuation uint64
OlderExists bool
FromVersion uint64 // exclusive covered bound for nonzero catch-up
ResetRequired bool // no items or covered/page bounds; acquire a newest window
Err error
}
QueryResult is detached from one publication. Only StateUsable carries items, epoch, consumed version and bounds. Continuation equals the inclusive lower order; OlderExists certifies an ordered public row strictly below it. Extras do not affect bounds, and Items has no presentation-order guarantee.
type Snapshot ¶
type Snapshot struct {
Active bool // includes private unresolved work omitted from Items
State SnapshotState
Items []Item
Version uint64
LastShownVersion uint64 // latest first shown publication or nonempty shown text append
Epoch string
Err error
}
Snapshot is a detached view. Only StateUsable carries items, versions and epoch; ErrUnavailable describes recoverable failure without exposing source errors.
type SnapshotState ¶
type SnapshotState uint8
SnapshotState describes whether a conversation has a complete consumed view.
const ( StateNotLoaded SnapshotState = iota StateRebuilding StateUsable )
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store follows raw history for caller-authorized conversations. Construct it with NewStore; all public methods are safe for concurrent use.
func NewStore ¶
func NewStore(h *history.Store, beforeFold ...func(context.Context, conversations.ConversationID) error) *Store
NewStore creates a background cache owner; history is the durable source. Tail notifications cover commits through the supplied history Store only. An optional fold barrier runs before each replay/tail chunk. It must return promptly or honor cancellation; failure withdraws the conversation view.
func (*Store) CatchUp ¶
func (s *Store) CatchUp(ctx context.Context, id conversations.ConversationID, epoch string, afterVersion uint64, limit int) (QueryResult, error)
CatchUp returns current full states touched in (afterVersion, Version], every active public item and complete public parents. The caller must be authorized for id. It neither loads nor waits for recovery. It renders selected references. Nonzero queries ignore limit; zero selects NewestWindow with its validation and clamp. ResetRequired carries the current epoch/version but no items or covered bounds. Cancellation discards partial results and leaves the worker running.
func (*Store) Changes ¶
func (s *Store) Changes(ctx context.Context, id conversations.ConversationID, epoch string, after uint64) (Observation, error)
Changes waits for progress beyond after in epoch. Only retained publication boundaries establish continuity. Missing ranges, epoch mismatches and suppressed rows require a fresh Observe baseline. Cancellation returns the context error; retirement/failure returns a nonusable observation. No waiter owns a worker.
func (*Store) ChildPage ¶ added in v0.41.0
func (s *Store) ChildPage(ctx context.Context, id conversations.ConversationID, epoch string, parent, revision uint64, limit int, continuation *ChildCursor) (ChildPageResult, error)
ChildPage reads revision-scoped public direct children without rendering or history lookups. Callers authorize id; this method never loads or waits. Positive limits clamp at 256 and are hard row ceilings, including across ties.
func (*Store) CompactCatchUp ¶ added in v0.41.0
func (s *Store) CompactCatchUp(ctx context.Context, id conversations.ConversationID, epoch string, afterVersion uint64, limit int) (CompactQueryResult, error)
CompactCatchUp returns, from one publication, the final state of every root whose compact state changed in (afterVersion, Version] plus all roots with public subtree activity. Version zero returns CompactNewestWindow for any epoch, with its validation and clamp; nonzero ignores limit. A reset carries identity but no rows or bounds: recover with a version-zero window. Results certify compact root coverage only. The caller must be authorized for id.
func (*Store) CompactChanges ¶ added in v0.41.0
func (s *Store) CompactChanges(ctx context.Context, id conversations.ConversationID, epoch string, after uint64) (CompactQueryResult, error)
CompactChanges waits while after is the current version of epoch, then returns the coalesced final states of roots whose compact state changed in (after, Version], without activity extras. A usable result without rows is explicit consumed progress. Resets follow CompactCatchUp. Cancellation returns the context error; retirement returns the zero result. No waiter owns a worker.
func (*Store) CompactHistoryPage ¶ added in v0.41.0
func (s *Store) CompactHistoryPage(ctx context.Context, id conversations.ConversationID, upperOrder uint64, limit int) (CompactQueryResult, error)
CompactHistoryPage reads the public root range below exclusive upperOrder, including all lower-bound ties. Continuation equals the inclusive LowerOrder; OlderExists certifies an ordered root strictly below it. Pages add no extras.
func (*Store) CompactNewestWindow ¶ added in v0.41.0
func (s *Store) CompactNewestWindow(ctx context.Context, id conversations.ConversationID, limit int) (CompactQueryResult, error)
CompactNewestWindow reads ordered public roots and all roots with public subtree activity. Callers authorize id; this method never loads or waits.
func (*Store) HistoryPage ¶
func (s *Store) HistoryPage(ctx context.Context, id conversations.ConversationID, upperOrder uint64, limit int) (QueryResult, error)
HistoryPage selects the newest ordered public range below upperOrder, plus complete public parent closure. The caller must already be authorized for id. It does not load or wait for recovery. Only selected references are read.
func (*Store) Load ¶
func (s *Store) Load(ctx context.Context, id conversations.ConversationID) error
Load starts background replay without waiting for history I/O. Repeated loads keep the existing worker, including an unavailable view requiring Retry. ctx governs the loaded worker's lifetime, rather than just the Load call. The caller must already be authorized for id.
func (*Store) NewestWindow ¶
func (s *Store) NewestWindow(ctx context.Context, id conversations.ConversationID, limit int) (QueryResult, error)
NewestWindow selects the newest ordered range below consumed Version+1, plus every active public item and complete public parents of all returned rows. The caller must already be authorized for id.
func (*Store) Observe ¶
func (s *Store) Observe(id conversations.ConversationID) Observation
Observe renders a consistent detached baseline from one publication.
func (*Store) Retry ¶
func (s *Store) Retry(ctx context.Context, id conversations.ConversationID) error
Retry replaces an unavailable view using validated disk state, discarding private reader/fold progress. It never replaces a rebuilding or usable worker.
func (*Store) Shutdown ¶
Shutdown closes admission and joins workers, certifying each independently. Already unloaded certificates are preserved. Concurrent callers share the result.
func (*Store) Snapshot ¶
func (s *Store) Snapshot(id conversations.ConversationID) Snapshot
Snapshot renders one immutable publication outside the store mutex. Source failure returns only unavailable State/Err and withdraws the captured worker.
func (*Store) Status ¶ added in v0.40.3
func (s *Store) Status(id conversations.ConversationID) Snapshot
Status returns Snapshot's metadata and readiness from one publication, with nil Items. It performs no I/O, worker load, item traversal or allocation.
func (*Store) ToolBody ¶ added in v0.41.0
func (s *Store) ToolBody(ctx context.Context, id conversations.ConversationID, expectedEpoch string, itemID, expectedRev uint64) (ToolBodyResult, error)
ToolBody reads a public tool_call or agent at the expected epoch/revision. Hidden and dropped rows remain public. Only the selected body and its recipe dependencies are rendered; no parent or descendant rows are returned. The caller must already be authorized for id. This read never loads or waits for recovery, and unrelated consumed-version advances do not invalidate it.
func (*Store) Unload ¶
func (s *Store) Unload(id conversations.ConversationID) error
Unload cancels and joins one worker, certifies its complete progress clean, and releases all items/private fold state. Persistence or incomplete recovery failures are returned without source data.
func (*Store) UnloadedLastShownVersion ¶ added in v0.40.3
func (s *Store) UnloadedLastShownVersion(id conversations.ConversationID) (uint64, bool)
UnloadedLastShownVersion reads clean certificate metadata for an unloaded, caller-authorized conversation only at exactly known current raw progress. It opens at most one certificate and never reads segments, starts a worker or proves replay equality or retained-range continuity. Zero can be present.
type ToolBodyResult ¶ added in v0.41.0
type ToolBodyResult struct {
State SnapshotState
ID, Rev uint64
Kind string
Content json.RawMessage
Epoch string
Version uint64
Err error
}
ToolBodyResult carries one detached complete body from one publication. Only StateUsable carries ID, Rev, Kind, Content, Epoch and consumed Version. Refusals and cancellation return a zero result and a separate error.
Source Files
¶
- agent.go
- agent_markers.go
- boundaries.go
- cache.go
- catch_up.go
- checkpoint_document.go
- checkpoint_export.go
- checkpoint_import.go
- checkpoint_read.go
- checkpoint_write.go
- child.go
- child_headers.go
- child_pages.go
- compact_intervals.go
- compact_queries.go
- fold.go
- main.go
- main_markers.go
- observations.go
- observations_store.go
- publication.go
- queries.go
- query_tree.go
- render.go
- sends.go
- shell.go
- store.go
- store_checkpoint.go
- store_render.go
- store_resume.go
- text.go
- tool_body.go