session

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package session bundles everything one decision-backed kb run needs for a topic: resolved topic, topic.yaml settings and active contract, the decision engine and generation client sharing one budget and receipts log, the state store, the owned-key writer, a lazily loaded corpus, and the decision modes (body links, relevance gates, quality gates).

Index

Constants

View Source
const (
	ModeShadow = "shadow"
	ModeApply  = "apply"
)

Decision mode values.

View Source
const CalibrationFile = "calibration.json"

CalibrationFile is the per-topic calibration record written by `kb review calibrate --write` (spec §12.3).

View Source
const MinCalibrationLabels = 30

MinCalibrationLabels is the label floor behind an automatic relevance `apply` (spec §7 default mode).

Variables

View Source
var ErrDecisionsRequired = errors.New("decision model is required")

ErrDecisionsRequired is returned when the decision model is not configured.

Functions

func CalibrationPath

func CalibrationPath(topicRoot string) string

CalibrationPath returns <topic>/.decisions/calibration.json.

Types

type Calibration

type Calibration struct {
	Time     string                        `json:"time"`
	Purposes map[string]CalibrationPurpose `json:"purposes"`
}

Calibration is the calibration.json record (spec §12.3).

func ReadCalibration

func ReadCalibration(topicRoot string) (*Calibration, error)

ReadCalibration reads calibration.json; a missing file returns nil, nil.

type CalibrationMetrics

type CalibrationMetrics struct {
	Precision  float64 `json:"precision"`
	Recall     float64 `json:"recall"`
	Coverage   float64 `json:"coverage"`
	ReviewRate float64 `json:"review_rate"`
	N          int     `json:"n"`
}

CalibrationMetrics are precision/recall/coverage/review rate at the chosen thresholds.

type CalibrationPurpose

type CalibrationPurpose struct {
	Contract       string             `json:"contract"`
	Model          string             `json:"model"`
	Banks          map[string]string  `json:"banks"`
	DevLabels      int                `json:"dev_labels"`
	HoldoutLabels  int                `json:"holdout_labels"`
	ImportedLabels int                `json:"imported_labels,omitempty"`
	Thresholds     map[string]float64 `json:"thresholds"`
	Dev            CalibrationMetrics `json:"dev"`
	Holdout        CalibrationMetrics `json:"holdout"`
}

CalibrationPurpose is the stored calibration of one purpose, with the decision context its scores were joined under: the contract hash, the decision model and the version of each built-in bank asking the gate quantity (bank id → version).

type Flags

type Flags struct {
	// BudgetUSD overrides [decisions].budget_usd when BudgetSet (or when
	// > 0). An explicit 0 is a cache-only run: no new call is made.
	BudgetUSD float64
	// BudgetSet reports that --budget was given, so an explicit 0 is
	// honored instead of read as "not set".
	BudgetSet bool
	// Decisions overrides the decision mode for this run: "", shadow or apply.
	Decisions string
}

Flags are the per-run overrides shared by decision-backed commands.

func (Flags) Budget

func (f Flags) Budget() (*decisions.Budget, error)

Budget returns the run budget the flags ask for: nil when --budget was not given (the engine then uses decisions.budget_usd), else a budget of BudgetUSD (0 = cache-only). A negative, NaN or infinite amount is an error.

type Options

type Options struct {
	Config    config.Config
	VaultPath string
	Topic     string
	// Command names the kb command for error messages ("kb classify").
	Command    string
	Flags      Flags
	HTTPClient *http.Client
	Now        func() time.Time
	Logger     *slog.Logger
}

Options configures Open.

type Session

type Session struct {
	Config    config.Config
	VaultPath string
	Topic     models.TopicInfo
	Settings  contract.Settings
	// Contract is the active contract, nil when none is accepted.
	Contract *contract.Contract
	Ref      decisions.TopicRef
	Engine   *decisions.Engine
	Gen      *generation.Client
	State    *corpus.StateStore
	Writer   *corpus.Writer
	Now      func() time.Time
	Logger   *slog.Logger
	Flags    Flags
	// contains filtered or unexported fields
}

Session is one decision-backed run over one topic.

func Open

func Open(opts Options) (*Session, error)

Open resolves the topic and builds a session. It fails fast, naming what is missing, when the decision model is not configured (spec §2 principle 2).

func (*Session) BodyMode

func (s *Session) BodyMode() string

BodyMode is the body-link insertion mode: decisions.mode, then topic.yaml decisions.mode, then --decisions.

func (*Session) ContractHash

func (s *Session) ContractHash() string

ContractHash returns the active contract hash ("" without a contract).

func (*Session) Corpus

func (s *Session) Corpus() (*corpus.Corpus, error)

Corpus loads the topic corpus once per session (decisions.exclude applied).

func (*Session) Excluded

func (s *Session) Excluded(topicRel string) bool

Excluded reports whether a topic-relative path matches decisions.exclude (the same match the engine and the generation client apply to every request Subject).

func (*Session) ExtraBanks

func (s *Session) ExtraBanks(purpose decisions.Purpose) []*questions.Bank

ExtraBanks returns the topic's extra question banks for purpose, loaded from <topic>/.decisions/banks/*.json at Open (spec §4.3). Their questions are added to built-in requests of that purpose; their answers are only recorded in receipts and never replace a built-in answer.

func (*Session) GateModeReason

func (s *Session) GateModeReason() string

GateModeReason explains the relevance gate mode for run summaries.

func (*Session) PrivacyNotice

func (s *Session) PrivacyNotice(w io.Writer)

PrivacyNotice prints, once per topic, where judged content is sent (spec §14). The marker lives under .decisions/.

func (*Session) QualityGateMode

func (s *Session) QualityGateMode() string

QualityGateMode is apply unless --decisions=shadow.

func (*Session) RelevanceCalibrated

func (s *Session) RelevanceCalibrated() bool

RelevanceCalibrated reports whether calibration.json records ≥30 relevance labels given in review (dev + holdout minus imported): imported labels never are the only evidence behind an automatic apply (spec §20). The calibration must also belong to the active decision context: the active contract, the engine's model and the current relevance bank version. A contract, model or bank change invalidates it until `kb review calibrate --write` runs again.

func (*Session) RelevanceEnabled

func (s *Session) RelevanceEnabled() bool

RelevanceEnabled is false when topic.yaml sets decisions.relevance: off.

func (*Session) RelevanceGateMode

func (s *Session) RelevanceGateMode() string

RelevanceGateMode is shadow until the topic has an accepted contract and either a stored calibration with ≥30 relevance labels or decisions.gates: apply (spec §7). --decisions overrides it for the run, except that --decisions=apply never enables relevance quarantine or skips without an accepted contract or with relevance off (spec §5.1: relevance then runs in shadow).

func (*Session) ReloadCorpus

func (s *Session) ReloadCorpus()

ReloadCorpus drops the cached corpus so the next Corpus call re-reads disk.

func (*Session) Request

func (s *Session) Request(purpose decisions.Purpose, subject string, bank *questions.Bank, state any, qs []questions.Q) decisions.Request

Request builds a decisions request for this topic.

func (*Session) Root

func (s *Session) Root() string

Root returns the topic root path.

func (*Session) StateMeta

func (s *Session) StateMeta(banks ...*questions.Bank) corpus.StateMeta

StateMeta builds the state-row metadata for a write made from answers of the given banks under the active contract.

func (*Session) Summary

func (s *Session) Summary() decisions.Summary

Summary returns the combined decisions + generation run summary.

func (*Session) SummaryLines

func (s *Session) SummaryLines() []string

SummaryLines renders the run summary, prefixed with budget state.

func (*Session) Threshold

func (s *Session) Threshold(name string) float64

Threshold returns a named threshold for this topic.

func (*Session) WithExtras

func (s *Session) WithExtras(purpose decisions.Purpose, bank *questions.Bank, qs []questions.Q, elements ...string) (*questions.Bank, []questions.Q, error)

WithExtras adds the topic's extra questions of purpose to a built-in request: it returns the bank to send (the built-in bank composed with the extras, or the built-in bank unchanged without extras, so the cache key only changes when a topic adds questions) and qs followed by the extra questions (templates instantiated once per element id, see questions.Instantiate).

func (*Session) WriteSummary

func (s *Session) WriteSummary(w io.Writer)

WriteSummary prints the run summary to w.

Jump to

Keyboard shortcuts

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