kernel

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package kernel is pure: no I/O, no imports from store/wire/session (spec §4, §6).

Index

Constants

View Source
const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"

	KindText       Kind = "text"
	KindToolCall   Kind = "tool_call"
	KindToolResult Kind = "tool_result"
	KindReasoning  Kind = "reasoning"
	// KindOpaque is an input item of a type the codec does not model (for example
	// a Responses compaction item). It is kept in place and sent back unchanged. It
	// is never summarized or dropped by truncation: see CompressibleSpans,
	// EmergencyTruncateWith and Render. A carried opaque item (Carried) may lie
	// inside a block; every other opaque item is a barrier no block crosses.
	KindOpaque Kind = "opaque"
)
View Source
const DefaultCCRThreshold = 4000

DefaultCCRThreshold is the token count above which a tool output is stored in CCR and replaced by a stub (spec §14.1, CCRThresholdTokens).

View Source
const DefaultKeepRecent = 3

DefaultKeepRecent is the number of trailing raw messages emergency truncation never drops when the caller does not pass its own count (spec §10.2 PreserveRecentMessages).

Variables

View Source
var (
	// ErrNoSuchBlock is returned when a block id is not in the snapshot.
	ErrNoSuchBlock = errors.New("kernel: no such block")
	// ErrNotReachable is returned when a block is inactive and no active block
	// covers it, so decompressing it would not change the visible window.
	ErrNotReachable = errors.New("kernel: block is not covered by an active block")
	// ErrInvariant is returned when a plan would leave the block set in a state
	// that breaks I1, I2, I5 or I6 (spec §17.1).
	ErrInvariant = errors.New("kernel: block invariant violated")
)
View Source
var DefaultCalibAlpha = dec("0.2")

DefaultCalibAlpha is the EMA smoothing factor for calibration (spec §15).

Functions

func Barrier added in v1.0.2

func Barrier(m Message) bool

Barrier reports whether m is an opaque item that no block may cover.

func Carried added in v1.0.2

func Carried(m Message) bool

Carried reports whether m is an opaque item that a block may cover: a system message the client placed inside the conversation (an Anthropic "system" role message, such as a harness reminder), which the codec stores as an opaque user item. Its position carries no state the summary depends on, so it is not a barrier. A block that covers it still renders it verbatim, right after the block's envelope. Other opaque items (Responses compaction items, with role assistant) hold state tied to their position and stay barriers.

func CheckBlockInvariants

func CheckBlockInvariants(blocks []Block) error

CheckBlockInvariants verifies the block-level invariants of spec §17.1 on an in-memory block set:

  • I1/I2: active blocks do not overlap in [StartSeq, EndSeq] (so no message is covered by two active blocks);
  • I5: EndSeq >= StartSeq, and SumTokens < SrcTokens for every block;
  • I6: every active T2/T3 block has sources that are one tier lower, inactive, contiguous, and exactly cover its range. SrcTokens equals the sources' summed SumTokens. Each source is claimed by at most one active parent.

IDs must be unique and tiers must be 1..3. It returns the first violation.

func EstimateTokens

func EstimateTokens(s string) int

EstimateTokens is a fast local heuristic by character class (spec §15.1): runs of ASCII letters/digits cost ceil(len/4); each other ASCII symbol costs 1; each non-ASCII rune (CJK, accents, emoji) costs 1; whitespace only ends a run. Non-empty input yields at least 1. Empty input yields 0.

func ExpectedCalls

func ExpectedCalls(gaps []int, factor apd.Decimal, limit int) int

ExpectedCalls estimates K (spec §9.1): median gap between past folds, in calls, times factor, clamped to [0, limit]. With no history it returns 0, so a non-pressure nudge is not worth it until a fold exists.

func FoldablePending

func FoldablePending(s Snapshot, tier int) int

FoldablePending returns the largest pending amount for a fold into the given tier (2 or 3): the summed SumTokens of the best contiguous run of tier-1 active blocks. It is 0 when no run is foldable. It is the value to put in TriggerInput.Pending[tier].

func FormatRef

func FormatRef(seq int64) string

FormatRef renders a ledger position as a stable reference, e.g. 42 -> "m00042".

func FormatTokens

func FormatTokens(n int) string

FormatTokens renders a token count like "512 tokens" or "38.2K tokens".

func FramingCheck

func FramingCheck(summary string) error

FramingCheck is the opt-in heuristic of spec §11.2. It rejects a summary when a strict majority of its sentences start with an imperative verb from the lists above, which is the wrong mood for a record of past events. The check depends on the language, so it is off by default. A summary with no countable sentence passes. Sentences end at ., ! or ? followed by whitespace or the end of a line, and at each line break. List bullets, numbering, markdown, backticks and [mNNNNN] refs are stripped before the first word is read, so "foo.go:42" does not split a sentence.

func IntentPreview added in v1.0.2

func IntentPreview(text string) string

IntentPreview is IntentText cut to the length the <intents> block shows for an open intent.

func IntentText added in v1.0.2

func IntentText(text string) string

IntentText is the relevant excerpt of a user message for its intent (spec §11.3: "o texto literal (ou o trecho relevante)"). It drops the harness envelopes and lines above and trims the rest. An empty result means the message carries no request from the user, so it opens no intent. An unclosed envelope is kept as text.

func JSONFold

func JSONFold(text string) (string, bool)

JSONFold folds fields that hold the same value in every element of a JSON array of objects into a shared "_const" header. Lossless: each item is rebuilt by merging _const with its own fields. ok=false when the input is not an array of >=2 objects, has no constant field, or does not get shorter.

func LogSelect

func LogSelect(text string) (string, bool)

LogSelect keeps every ERROR/FAIL/panic line verbatim plus a few lines of head and tail, eliding the rest with a marker. It requires at least one error line (otherwise there is nothing to guarantee) and ok=false when the result is not shorter than the input.

func PendingTokens

func PendingTokens(s Snapshot, keep int) map[int]int

PendingTokens is the compressible tokens per tier, the P1..P3 of the decision log (spec §8.3). Tier 1 is the uncovered, non-system, non-first-user messages outside the last keep messages. Tiers 2 and 3 are FoldablePending. It mirrors the pending computation of the session that decides the nudge.

func ReadDensity

func ReadDensity(s Snapshot) apd.Decimal

ReadDensity is the share of tool_result tokens in the whole ledger (spec §8.4 input). It is 0 for an empty ledger.

func RefLabel

func RefLabel(m Message) string

RefLabel is the reference shown to the model in front of a raw message's text, for example "[m00042] ". It depends only on the ledger position, so it is byte-stable across turns. Synthetic messages (history envelopes, intents) and system messages have no label.

func Step

func Step(cfg Config, s Snapshot) int

Step returns the growth step S of spec §8.4 for the ledger in s: the adaptive step computed from its read density. It is the value DecideNudge uses, exported for the per-turn decision log (spec §20).

func Stub

func Stub(in StubInput) string

Stub renders the deterministic CCR placeholder (spec §14.1). It is a pure function of its input, so the same output always yields the same bytes (cache-stable).

func UpdateLowWater

func UpdateLowWater(prev, tokenCount int) int

UpdateLowWater applies spec §8.2: the valley only goes down. prev == 0 means unset (first observation), so the current count becomes the valley. After a successful compression the caller sets LowWater = TokenCount directly.

Types

type Block

type Block struct {
	ID        string // "b17"
	Tier      int    // 1..3
	Topic     string
	Summary   string
	StartSeq  int64
	EndSeq    int64
	SrcTokens int
	SumTokens int
	Active    bool
	Sources   []string // consumed blocks (T2/T3)
}

func ApplyDecompress

func ApplyDecompress(blocks []Block, p DecompressPlan) ([]Block, error)

ApplyDecompress returns a new block set with the plan applied, and leaves the input unchanged. It checks that Target is active, and that Reactivate is exactly Target's direct sources, all inactive. Overlap is rejected: if reactivation would break I1 or I2, it returns ErrInvariant and does not change anything.

func ApplyTierPlan

func ApplyTierPlan(blocks []Block, p TierPlan, nb Block) ([]Block, error)

ApplyTierPlan returns a new block set with the plan applied, and leaves the input unchanged. The sources become inactive, and nb is added as an active block of the plan's tier with Sources set. nb carries the model's ID, Topic, Summary and SumTokens. It returns an error if the plan does not match the blocks, or if the result breaks I1, I2, I5 or I6.

type Calib

type Calib struct {
	Alpha   apd.Decimal // EMA weight of a new sample
	Factor  apd.Decimal // reported/estimated ratio, EMA-smoothed
	Samples int
	MAE     apd.Decimal // EMA of |reported - predicted| / reported, before each update
}

Calib maps local estimates onto provider-reported token counts (spec §15). The zero value is usable: Factor 0 means 1.0 and Alpha 0 means DefaultCalibAlpha. Only feed clean samples (no images, no failures); the kernel does not judge cleanliness.

func NewCalib

func NewCalib(alpha apd.Decimal) Calib

NewCalib returns a calibrator with Factor 1.0 and the given alpha (DefaultCalibAlpha when alpha <= 0 or > 1).

func (*Calib) Tokens

func (c *Calib) Tokens(estimated int) int

Tokens returns the calibrated count for a local estimate.

func (*Calib) Update

func (c *Calib) Update(estimated, reported int)

Update folds one sample in. It is a no-op when either count is <= 0.

type Config

type Config struct {
	StepBase       int         // S before adaptation: 50K
	StepMin        int         // 30K
	StepMax        int         // 100K
	StepReadGain   apd.Decimal // 1.0
	MinGrowthFloor int         // 20K
	UFloor         apd.Decimal // 0.30; 0 disables the floor (original behaviour)
	UHigh          apd.Decimal // 0.75
	UEmerg         apd.Decimal // 0.95
	TiersEnabled   bool        // gates rows 7 and 8
	// MaxRefusals is the number of consecutive refusals after which nudges are
	// suspended until U >= UHigh: 3 (spec §8.3). 0 never suspends them.
	MaxRefusals int
}

Config holds the compression trigger thresholds (spec §8.1, §8.4). DefaultConfig returns the values from the spec.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the spec §8.1 defaults.

type CostModel

type CostModel struct {
	PriceUncached apd.Decimal
	PriceCached   apd.Decimal
	Margin        apd.Decimal
}

CostModel holds per-token prices (any consistent unit) and the worth margin (spec §9.1).

func DefaultCostModel

func DefaultCostModel() CostModel

DefaultCostModel uses p_c = 0.1 * p_u and margin 1.5 (spec §9.1).

type CrushResult

type CrushResult struct {
	Text     string
	Strategy Strategy
	Lossless bool
}

CrushResult is the output of a crush strategy. Lossless is false when the strategy dropped content (code-trim); the caller must keep the original in CCR.

func CodeTrim

func CodeTrim(text string) (CrushResult, bool)

CodeTrim removes whole-line comments (// and #) and collapses runs of blank lines. Lossy: Lossless is false. It is never chosen automatically because the kernel cannot tell comment syntax per language; callers opt in.

func Crush

func Crush(text string) CrushResult

Crush applies the automatic strategies in order (json-fold, then log-select) and returns the first that shrinks the text. json-fold is lossless; log-select only guarantees error lines (spec §14.2), so its result is marked lossy. Otherwise the text is returned unchanged with StrategyNone.

type Decision

type Decision struct {
	Nudge  bool
	Tier   int
	Voice  Voice
	Row    string
	Reason string
}

Decision is the outcome of DecideNudge. Row is the spec §8.3 row label ("row1".."row9"), or "guard" for invalid input and "refusal" when refusals suspend nudges. Every decision carries a label so behaviour can be read from events.

func DecideNudge

func DecideNudge(in TriggerInput, cfg Config) Decision

DecideNudge implements the spec §8.3 decision table (§8.5 code), evaluated top-down.

type DecompressPlan

type DecompressPlan struct {
	Requested  string
	Target     string
	Reactivate []string // direct sources of Target, ascending by StartSeq
	Redirected bool
	StartSeq   int64 // range of Target, for the cache anchor
	EndSeq     int64
}

DecompressPlan reactivates the direct sources of Target and deactivates Target (spec §13.1, mode "context"). Target is the requested block when that block is active. When the requested block is inactive, Target is its active ancestor and Redirected is true: its content is still folded under that ancestor, so one level is expanded per call.

The store must clear parent_block on every block in Reactivate. Target is active, so it has no parent to clear. An active T1 target has no sources, so it becomes an inactive T1 with no parent. The store's I7 query flags that state (see internal/store/invariants.go); the caller has to resolve it.

func PlanDecompress

func PlanDecompress(s Snapshot, id string) (DecompressPlan, error)

PlanDecompress builds the reactivation plan for a block. It fails with ErrNoSuchBlock for an unknown id, and with ErrNotReachable when the block is inactive and no active block covers it. It also fails when applying the plan would overlap another active block (I2).

type FoldCost

type FoldCost struct {
	Recovered int         // R = src_tokens - sum_tokens
	Tail      int         // T: tokens after the anchor, which lose cache once
	Calls     int         // K: expected remaining calls
	Cost      apd.Decimal // T * (p_u - p_c)
	Benefit   apd.Decimal // R * p_c * K
	Worth     bool        // Benefit >= Cost * Margin
}

FoldCost is the estimate for one candidate fold.

func EstimateFold

func EstimateFold(m CostModel, srcTokens, sumTokens, tailTokens, calls int) FoldCost

EstimateFold applies the spec §9.1 cost model to one fold.

type GateAction

type GateAction int

GateAction is the cache gate outcome for a nudge (spec §9.3).

const (
	GateNone GateAction = iota
	GateInject
	GateDefer
)

func GateNudge

func GateNudge(d Decision, worth, deferred bool, idleSeconds, cacheTTL int) GateAction

GateNudge applies the spec §9.3 cacheGate to a §8 decision. Pressure nudges (firm, emergency) are never deferred. A worthwhile nudge is injected now. Otherwise the nudge is deferred, unless it was already deferred and the cache is cold (idleSeconds > cacheTTL), when injecting costs no cache.

type Intent

type Intent struct {
	ID        int64
	OriginSeq int64
	Text      string
	Status    string // open | done | superseded
}

type Kind

type Kind string

type Message

type Message struct {
	Seq        int64
	Ref        string // "m00042"
	Role       Role
	Kind       Kind
	ToolName   string
	ToolCallID string
	Text       string
	Tokens     int
	CCRStored  bool
}

Message is the protocol-independent normalized view.

func EmergencyTruncate

func EmergencyTruncate(window []Message, limit int, tokensOf func(Message) int) []Message

EmergencyTruncate is RenderWithLimit's core applied to an existing window; see EmergencyTruncateWith for the rules. It uses DefaultKeepRecent.

func Render

func Render(s Snapshot) []Message

Render builds the visible window (spec §11.1): system messages, pinned first user message, history envelopes, intents (as of the last fold), then the raw zone in natural order. The last user message keeps its natural position, so it never lands after a tool round it started (§11.4). Render does not apply the limit: use RenderWithLimit for the I8 bound (emergency truncation, truncate.go).

func RenderWithLimit

func RenderWithLimit(s Snapshot, limit int, tok func(Message) int) []Message

RenderWithLimit is Render followed by emergency truncation (spec §11, I8): the visible window never exceeds limit unless the protected content alone does. tok is the token count of one message, for example a calibrated estimate. limit <= 0 disables truncation.

type RecallHint

type RecallHint struct {
	Kind    RecallKind
	BlockID string // active block covering the folded content
	Ref     string // folded message ref ("m00340"), when the hint names one
	Path    string // target path of a re-read, when one was found in the args
	Text    string // hint wording (spec §13.2 style)
}

RecallHint is an ephemeral pointer from folded content to the active block that covers it. The hint is never written to history; BlockID is the block the model should pass to decompress.

func DetectRecall

func DetectRecall(s Snapshot) []RecallHint

DetectRecall returns recall hints for the current turn (spec §13.2). It is deterministic and pure. Two signals are checked:

  • re-read: a tool call after the latest user text has the same tool name and the same target path (or the same canonical args when no path exists) as a tool call that is already folded into an active block;
  • reference: the latest user or assistant text cites a folded message ref (m00340) or a folded block id (b12). The hint points at the active block that covers it.

Hints are sorted by block, kind, ref and path, and duplicates are removed.

type RecallKind

type RecallKind string

RecallKind classifies a recall hint (spec §13.2).

const (
	RecallReread  RecallKind = "reread" // a recent tool call repeats a folded one
	RecallRef     RecallKind = "ref"    // latest text cites a folded message ref
	RecallBlockID RecallKind = "block"  // latest text cites a folded block id
)

type ReduceResult

type ReduceResult struct {
	Visible string
	Stored  bool
}

ReduceResult is what a tool output becomes for the visible window. Stored=true means the caller must persist the original Text in CCR (contents, deduplicated by hash). Visible is then either the stub (the crushed text still exceeds the threshold) or the lossy crushed text (the crush dropped content, so the original must stay recoverable).

func Reduce

func Reduce(in StubInput, threshold int) ReduceResult

Reduce crushes text and, if the result still exceeds threshold tokens, replaces it with a CCR stub built from the original text. Otherwise the crushed text is shown inline; if that crush was lossy, the original is still stored. threshold <= 0 uses DefaultCCRThreshold.

type Role

type Role string

type Snapshot

type Snapshot struct {
	SessionID    string
	ContextLimit int
	Messages     []Message // full ledger, ordered by Seq
	Blocks       []Block
	Intents      []Intent
	Trigger      TriggerState
}

Snapshot is everything the kernel needs to decide a turn. Phase 1 subset: cache stats, idle time and token count arrive with §8/§9.

type Span

type Span struct {
	Start    string // ref of the first message, inclusive
	End      string // ref of the last message, inclusive
	StartSeq int64
	EndSeq   int64
	Tokens   int // sum of the messages' token estimates
}

Span is a run of ledger messages that a compress call may cover now.

func CompressibleSpans

func CompressibleSpans(s Snapshot, keep int) []Span

CompressibleSpans lists the ranges that may be compressed now (spec §10.2), in ledger order. A message is a candidate when it is not a system message, not a barrier opaque item (no span crosses it; a carried one may lie inside a span but never bounds it, and its tokens are not counted), not covered by an active block, not the pinned first user message and not in the last keep messages. A tool call and its result must both be candidates, and every message between them too, so no compressed range splits a pair. Each span starts on a non-result and ends on a non-call, as compress requires.

type Strategy

type Strategy string

Strategy names the deterministic crush strategy that produced a result.

const (
	StrategyNone      Strategy = "none"
	StrategyJSONFold  Strategy = "json-fold"
	StrategyLogSelect Strategy = "log-select"
	StrategyCodeTrim  Strategy = "code-trim"
)

type StubInput

type StubInput struct {
	Ref    string // "m00451"
	Tool   string
	Cmd    string // optional
	Exit   *int   // optional
	Text   string // original full output
	Tokens int    // estimated tokens of Text
}

StubInput describes a stored tool output for the CCR placeholder.

type TierPlan

type TierPlan struct {
	Tier      int      // target tier: 2 or 3
	Sources   []string // consumed blocks, ascending by StartSeq, contiguous
	StartSeq  int64    // first source's StartSeq
	EndSeq    int64    // last source's EndSeq
	SrcTokens int      // sum of the sources' SumTokens (tokens folded)
}

TierPlan describes a T2 or T3 fold: a contiguous run of active blocks one tier below, consumed by one new block of the target tier (spec §12). It is pure data. The summary is written later by the model, and ApplyTierPlan validates the result.

func PlanFold

func PlanFold(s Snapshot, cfg Config, d Decision, contextLimit int, readDensity apd.Decimal, tokenCount int) (TierPlan, bool)

PlanFold plans the fold that a DecideNudge decision asks for, so the kernel never nudges a tier it cannot plan (spec §10.2). Rows 1 and 3 (pressure) take the best run with at least Bmin pending and ignore the growth threshold and the cadence, as the decision table does. Rows 7 and 8 use PlanTierFold. Other decisions, and tier 1, return false. contextLimit is TriggerInput.ContextLimit.

func PlanTierFold

func PlanTierFold(s Snapshot, cfg Config, tier int, readDensity apd.Decimal, tokenCount int) (TierPlan, bool)

PlanTierFold selects the run to fold into a new block of the given tier (2 or 3), using the thresholds and cadence of spec §8.3 rows 7 and 8 and §12. A run qualifies when it has at least two blocks, its pending tokens reach 1.5·S, and the cadence for that tier has passed, meaning tokenCount minus the last tier nudge is at least F. Among qualifying runs the one with the most pending tokens wins, and ties go to the earlier run. It returns false when nothing qualifies or tiers are disabled.

func (TierPlan) ParentOf

func (p TierPlan) ParentOf(newID string) map[string]string

ParentOf returns the store's link map for this plan: each consumed source points at newID, the block the fold creates. The store writes it as parent_block when it deactivates the sources (CompressPlan.ParentOf).

type TriggerInput

type TriggerInput struct {
	TokenCount   int         // current context size in tokens
	ContextLimit int         // L
	ReadDensity  apd.Decimal // share of recent growth from tool_result (0..1)
	Pending      map[int]int // compressible tokens per tier (keys 1..3)
	Trigger      TriggerState
}

TriggerInput is the per-turn observation fed to DecideNudge.

type TriggerState

type TriggerState struct {
	LowWater     int
	NudgePending bool
	NudgeShownAt int
	LastShownT2  int
	LastShownT3  int
	Refusals     int
}

type Truncation

type Truncation struct {
	Window []Message // the window to send
	// Dropped lists the refs of the raw messages removed from the window, in
	// ledger order. The originals stay in the ledger.
	Dropped []string
	// Marker reports that the truncated-history marker is in Window.
	Marker bool
	// Overflow reports that the protected content alone (system, pinned first
	// user message, history envelopes, intents, the last user turn and the recent
	// zone, with tool pairs kept whole) exceeds the limit. Window then holds only
	// that protected content, without a marker, and cannot fit.
	Overflow bool
}

Truncation is the outcome of an emergency truncation (spec §17.1 I8).

func EmergencyTruncateWith

func EmergencyTruncateWith(window []Message, limit, keep int, tokensOf func(Message) int) Truncation

EmergencyTruncateWith drops the oldest raw messages of window until its tokens fit limit, keeping one marker in their place. The rules:

  • A message is raw when it has a Ref. Messages without a Ref are synthetic (history envelopes, intents, markers) and are kept, as are system messages.
  • The first raw user text message is pinned and kept.
  • Protected tail: everything from the last raw user text message onward, and the last keep raw messages. Tool pairs are kept whole, so a pair that reaches into the tail is protected entirely.
  • Droppable units are built from the oldest raw messages before the tail. A unit is the smallest contiguous run that closes every tool pair it opens, so no tool_call or tool_result is split (I3).
  • Units are dropped oldest first and the scan stops at the first unit that cannot be dropped. The marker covers the first and last dropped refs and replaces the first dropped message in position.

A window that already fits is returned unchanged, with no marker. When the marker itself does not fit after every unit is gone, the units are dropped without a marker, and Overflow reports whether the protected content still exceeds limit. limit <= 0 means no limit. The result depends only on the input, so it is byte-stable and idempotent: applying it to its own output changes nothing.

func RenderTruncated

func RenderTruncated(s Snapshot, limit, keep int, tok func(Message) int) Truncation

RenderTruncated is RenderWithLimit with the recent zone size given by the caller and the full Truncation report.

type TurnPlan

type TurnPlan struct {
	Visible []Message
}

TurnPlan is what the kernel returns. Phase 1 subset: Visible only.

type Voice

type Voice string

Voice is the tone of a nudge shown to the model (spec §8.3).

const (
	VoiceNone      Voice = ""
	VoiceGentle    Voice = "gentle"
	VoiceFirm      Voice = "firm"
	VoiceEmergency Voice = "emergency"
)

Jump to

Keyboard shortcuts

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