checkpoint

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 17 Imported by: ? 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

Overview

Package checkpoint provides pure context-checkpoint selection and rendering. It has no workflow, activity, store, or provider side effects.

Index

Constants

View Source
const (
	// ReceiptArgsBytes bounds the eligible call argument preview stored by K12.
	ReceiptArgsBytes = 160
	// MaxReceiptLineBytes caps one rendered receipt line including its newline.
	MaxReceiptLineBytes = 512
)
View Source
const BytesPerToken = 2

BytesPerToken is the fixed conversion used by every checkpoint text budget.

Variables

View Source
var (

	// ErrCitesNonUser rejects citations to assistant messages and tool results.
	ErrCitesNonUser = errors.New("citation does not name a user message")
	// ErrCitesUnknown rejects citations to missing messages.
	ErrCitesUnknown = errors.New("citation names an unknown message")
	// ErrCitesNotBehind rejects citations outside checkpoint coverage.
	ErrCitesNotBehind = errors.New("citation is not behind the checkpoint")
)
View Source
var DefaultLimits = Limits{MaxPins: 32, UserIndexLineBytes: 160, MaxPinnedParts: 2}

DefaultLimits holds the design's pin and index defaults.

View Source
var ErrCheckpointBudget = errors.New("checkpoint budget is too small")

ErrCheckpointBudget reports a budget too small for checkpoint framing.

Functions

func BoundSummary

func BoundSummary(text string, maxBytes int, closing string) string

BoundSummary allocates a byte budget across ordered Markdown sections. Whole text is unchanged. Short sections pass their unused share forward.

func CheckpointID

func CheckpointID(recordID string) string

CheckpointID identifies an immutable record with an eight-hex digest.

func ChooseTail

func ChooseTail(units []Unit, tokens UnitTokens, keepRecent int) index.MessageID

ChooseTail keeps the newest unit even when it exceeds keepRecent.

func ClearedResult

func ClearedResult(bytes int, toolUseID, errFirstLine string) string

ClearedResult names the original result without recommending a tool.

func ClearedText

func ClearedText(ctx context.Context, source index.Source, entries []index.MessageEntry, through index.MessageID) (map[index.MessageID]string, error)

clearedText derives placeholders from immutable result facts, never bodies.

func Compare

func Compare(a, b OrderKey) int

Compare returns the chronological ordering of two keys.

func ConsumesHiddenResult

func ConsumesHiddenResult(entry index.MessageEntry) bool

consumesHiddenResult mirrors Renderer.appendResult, including structural results.

func CutPoints

func CutPoints(units []Unit) []index.MessageID

CutPoints returns tail starts between units, never before the first unit.

func Handle

func Handle(part, recordID string) string

Handle names one collapsed part of a stored checkpoint record.

func HeadTail

func HeadTail(text string, maxBytes int) string

HeadTail makes a deterministic UTF-8-safe preview within maxBytes.

func Label

func Label(id index.MessageID, origin *index.Origin, currentPos int) string

Label renders a local or qualified original message reference.

func LookupLine

func LookupLine(id, args string, maxBytes int) string

LookupLine is the shared K13 lookup description, hiding the internal tool name. A negative limit retains all eligible arguments; bounded callers reserve newline bytes.

func MaxBytes

func MaxBytes(b index.RenderBudget) int

MaxBytes converts current checkpoint token budgets at exactly two bytes/token.

func MinCheckpointBytes

func MinCheckpointBytes(b index.RenderBudget) int

MinCheckpointBytes returns the total byte threshold guaranteeing framing capacity. It reserves the full user allowance (at least a compact users line), the largest header/labels, two compact receipt lines and a compact summary closing line. Component token budgets must be nonnegative.

func PartPlaceholder

func PartPlaceholder(part model.Part, label string, number int) string

PartPlaceholder names an omitted original attachment without retaining its bytes.

func PrefixHidden

func PrefixHidden(entries []index.MessageEntry) map[string]bool

prefixHidden retains unmatched hidden calls whose results may lie in the tail.

func Project

func Project(ctx context.Context, source index.Source, entries []index.MessageEntry, view index.ViewRef) ([]*model.Message, error)

Project reconstructs a committed view without storing or changing evidence.

func Qualify

func Qualify(text string, summaryPos, currentPos int) string

Qualify binds bare citations to the original summary run before copying.

func Render

func Render(in Input, b index.RenderBudget, lim Limits, pt PartTokens) (*model.Message, error)

Render constructs one bounded user-role checkpoint from record-authored inputs. Framing deficits consume receipt then summary bytes above their handle floors. Tiny component budgets borrow capacity for compact handles. K17 validates component budgets before loading.

func ResultText

func ResultText(ctx context.Context, source index.Source, entries []index.MessageEntry, view index.ViewRef) (map[index.MessageID]string, error)

ResultText derives recovery projections with forced clearing taking precedence over ordinary clearing and previews. Immutable Keep flags remain unchanged.

func SelectPins

func SelectPins(users []UserMessage, budget index.RenderBudget, limits Limits) []index.MessageID

SelectPins selects the first user then a contiguous newest-first suffix.

func SummaryBytes

func SummaryBytes(in Input, b index.RenderBudget) (int, error)

SummaryBytes returns the exact post-framing allowance used by Render. It includes K12's discovery floors and rejects the same invalid budgets.

func ValidTail

func ValidTail(entries []index.MessageEntry, tail index.MessageID) error

Types

type ByteRange

type ByteRange = index.ByteRange

ByteRange is an inclusive unsummarised byte range in the original result.

type Citation

type Citation struct {
	Pos        int
	ID         index.MessageID
	Start, End int
}

Citation is an exact bracket reference; Pos zero means the summary's run.

func ParseCitations

func ParseCitations(text string) []Citation

ParseCitations accepts exactly [message N] and [rK message N].

type CitationResolver

type CitationResolver interface {
	// Resolve returns canonical entry kind, role and record-authored user text.
	Resolve(OrderKey) (CitationTarget, bool, error)
	// Behind checks coverage in the referenced run, including predecessor runs.
	Behind(OrderKey) bool
}

CitationResolver resolves only authorized records and checks checkpoint coverage.

type CitationTarget

type CitationTarget struct {
	Line UserLine
	Kind index.EntryKind
	Role model.ConversationRole
}

CitationTarget distinguishes user-authored entries from user-role tool results.

type EarlierCounts

type EarlierCounts struct {
	Calls, Assistants int
	FirstPos, LastPos int
}

EarlierCounts carries bounded receipt totals for predecessor runs.

type Input

type Input struct {
	Through       index.MessageID
	CurrentPos    int
	RunPos        map[string]int
	ID            string
	Summary       *Summary
	CitedUsers    []UserLine
	Users         []UserMessage
	Pinned        []index.MessageID
	Receipt       iter.Seq[ReceiptItem]
	Earlier       EarlierCounts
	ContinuedFrom int
}

Input is independent of stored record encodings; K12 supplies FromRecord. Users contain only user-authored entries covered by Through. Receipt is a repeatable newest-first sequence over the whole chain, excluding Earlier.

func FromRecord

func FromRecord(ctx context.Context, source index.Source, hash runstore.Hash, entries []index.MessageEntry, currentPos int) (Input, error)

FromRecord reads a checkpoint and its Prev chain without writes. Receipts are repeatable and newest-first. It loads only eligible users and summary text, never entry.Record. currentPos qualifies recorded origins without walking earlier scopes.

type Limits

type Limits struct {
	MaxPins, UserIndexLineBytes, MaxPinnedParts int
}

Limits caps pin count, index text bytes and held non-text parts.

func BudgetLimits

func BudgetLimits(budget index.RenderBudget) Limits

BudgetLimits resolves pin-count overrides from the recorded view budget.

type OrderKey

type OrderKey struct {
	Pos int
	ID  index.MessageID
}

OrderKey orders original user messages by run position, then original ID.

func Key

func Key(id index.MessageID, origin *index.Origin, currentPos int) OrderKey

Key resolves provenance; nil origins belong to the current run.

type Parsed

type Parsed struct{ Header, Users, Summary, Receipt string }

Parsed contains the section bodies selected by Sections, without boundary labels. Header includes its trailing newlines. No whitespace is trimmed.

func Sections

func Sections(text string) (Parsed, bool)

Sections splits checkpoint text. Callers must establish checkpoint identity from Message.Meta[transcript.CheckpointMetaKey], never from text alone. It selects the first user label, the last receipt label after it, and the last summary label between those boundaries. Missing boundaries return false. The split is exact for label-free Render components. Embedded section labels can make the original boundaries ambiguous; the same precedence still applies. In eval/evidence this affects only source attribution among user_index, summary and receipt, which is reported, never gated. Presence and gated measures are unaffected by that attribution.

type PartTokens

type PartTokens func(model.Part) int

PartTokens estimates one non-text part; nil uses the design's fixed fallbacks.

type ReceiptItem

type ReceiptItem struct {
	ToolUseID, Tool, Args string
	// PartID identifies an unsummarised part; PartText is the framework annotation.
	PartID           index.MessageID
	Part, Bytes      int
	Format, PartText string
	// Lookup hides the runtime lookup tool name while retaining its call ID.
	Lookup       bool
	AssistantID  index.MessageID
	Text         string
	Unsummarised []ByteRange
	Origin       *index.Origin
}

ReceiptItem supplies a tool call and/or assistant text from the record chain.

type RoleOf

RoleOf loads the role of a Message entry from its canonical content.

type Summary

type Summary struct {
	Text, Run, ID string
	// RecordPos identifies the checkpoint scope holding this copy, when recorded.
	RecordPos *int
}

Summary preserves the source run and record of immutable stored summary text.

type Unit

type Unit struct {
	From, Through   index.MessageID
	StartsAssistant bool
	// contains filtered or unexported fields
}

Unit is an inclusive atomic entry range; a cut cannot split it.

func Units

func Units(entries []index.MessageEntry, role RoleOf, openFrom index.MessageID) []Unit

Units groups entries into atomic batches and one optional open-await suffix.

type UnitTokens

type UnitTokens func(Unit) int

UnitTokens measures a complete tail unit in estimated tokens.

type UserLine

type UserLine struct {
	ID     index.MessageID
	Origin *index.Origin
	Text   string
	Bytes  int
}

UserLine identifies a record-authored user index line, never summary prose.

func CarryUsers

func CarryUsers(in Input, budget index.RenderBudget) (pins, lines []UserLine)

CarryUsers returns exactly the selected text of pins and user index rows. Labels are regenerated from immutable origins in the next run. Non-text pin bodies are not copied; their rendered placeholders remain until multimodal carry.

func ValidateCitations

func ValidateCitations(text string, summaryPos int, resolver CitationResolver) ([]UserLine, error)

ValidateCitations returns unique record-authored user lines in citation order.

type UserMessage

type UserMessage struct {
	// IndexOnly marks a carried first line that cannot become a full pin.
	IndexOnly bool
	ID        index.MessageID
	Origin    *index.Origin
	Message   *model.Message
}

UserMessage supplies record-authored content and its original provenance.

Jump to

Keyboard shortcuts

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