Documentation
¶
Overview ¶
Package core implements the Connection Engine: decaying Beta posteriors, the surprise ledger, and the split/merge judgment (ADR-0001..0003).
Index ¶
- Constants
- func BernoulliEntropy(p float64) float64
- func BetaQuantile(a, b, q float64) float64
- func CanonToken(key, val string) string
- func CanonValue(s string) string
- func DecayFactor(fromMs, toMs int64) float64
- func ExcessSurprisal(p, y float64) float64
- func LnBF(kWith, nWith, kWithout, nWithout float64) float64
- func MarshalContext(ctx map[string]string) string
- func MarshalOutcome(o Outcome) string
- func OutcomeWeight(e *Experience) (y float64, ok bool)
- func RegIncBeta(x, a, b float64) float64
- func SampleBeta(rng *rand.Rand, a, b float64) float64
- type Connection
- func (c *Connection) Confidence(nowMs int64) float64
- func (c *Connection) Evidence(nowMs int64) float64
- func (c *Connection) Mean(nowMs int64) float64
- func (c *Connection) Observe(y float64, tsMs int64)
- func (c *Connection) PosteriorAt(nowMs int64) (a, b float64)
- func (c *Connection) Prior() (a, b float64)
- func (c *Connection) QuantileAt(nowMs int64, q float64) float64
- func (c *Connection) SampleAt(rng *rand.Rand, nowMs int64) float64
- func (c *Connection) Scope() Scope
- func (c *Connection) State(nowMs int64, ledgerSum float64) string
- type Engine
- func (en *Engine) Apply(exp *Experience) error
- func (en *Engine) LedgerSum(c *Connection, nowMs int64) (float64, error)
- func (en *Engine) PerceiveBatch(batch, known []*Experience, onRebuild func()) (rebuilt bool, err error)
- func (en *Engine) Rebuild() error
- func (en *Engine) ReconcileMerges(nowMs int64) error
- type Experience
- type LedgerEntry
- type Outcome
- type Repo
- type Scope
Constants ¶
const ( PriorAlpha = 1.0 PriorBeta = 1.0 // HalfLifeMs: evidence halves toward the prior every 90 days (ADR-0002). HalfLifeMs = 90 * 24 * 3600 * 1000 // ThetaTrigger: cumulative excess surprisal (nats) that marks a // connection Questioned and summons the judgment. ThetaTrigger = 2.0 // ThetaSplit / ThetaMerge: hysteresis band on the corrected ln BF // (ADR-0002: Schmitt trigger — formation needs strong evidence, // persistence is cheap). ThetaSplit = 3.0 ThetaMerge = 0.0 // InheritM0: the fixed mass m₀ a split child's inherited prior carries // (ADR-0013 Decision 1 — 「新入りの謙虚さ」の量). The parent may be a // thousand-battle veteran; the child is born an m₀-baby whose first // impression is the parent's opinion. InheritM0 = 2.0 // PrefKnownMin: the decayed preference evidence below which a pair's // preference no longer counts as known. Two organs must read the same // number — curiosity's re-ask ceiling (EMax: below this the question // reopens, ADR-0007 追記) and the face's S5 gate (at or above this Tomo // still knows the human pair, ADR-0045 Decision 3 追記) — or "Tomo would // ask again" and "Tomo still knows you" drift apart. It lives here, not // in curiosity, because face cannot import curiosity (curiosity → voice → // face is already an import path). PrefKnownMin = 0.5 )
Knobs (CONNECTION_ENGINE.md Open Questions — tuned via dogfood).
const ( KindExecution = "execution" KindPreference = "preference" KindReflection = "reflection" )
Experience kinds (SCHEMA.md D7; reflection added by ADR-0015).
const ( ConnCapability = "capability" ConnPreference = "preference" ConnPlan = "plan" )
Connection kinds. ConnPlan is the second bet target (ADR-0014 Decision 1: 台帳は賭ける対象を選ばない — the right side of a Connection is not limited to providers).
const ( StateBorn = "born" StateGrow = "grow" StateStable = "stable" StateQuestioned = "questioned" StateDormant = "dormant" )
Lifecycle states, derived by query.
Variables ¶
This section is empty.
Functions ¶
func BernoulliEntropy ¶
BernoulliEntropy H(p) in nats. p is strictly inside (0,1) because the prior keeps pseudo-counts positive.
func BetaQuantile ¶
BetaQuantile inverts the Beta(a,b) CDF at probability q by bisection — slower than Newton but monotone, branchless and immune to the flat tails a decayed posterior can develop. 80 halvings pin the result far below any gate's tolerance.
func CanonToken ¶
CanonToken canonicalizes a context attribute into "key=value" (SCHEMA.md D5: lowercase, trimmed).
func CanonValue ¶
CanonValue canonicalizes a single attribute value: trim, lowercase, strip every Unicode control character (ESC/CSI/BEL and friends), and map '|' to '-'. Control chars are stripped before trimming so a stray one doesn't hide whitespace at the new edge. LLM-extracted values are the entry point for this — a hostile "value" could otherwise carry a terminal escape sequence all the way to a rendered scope (SCHEMA.md D5).
'|' gets the same treatment for a different reason: it is the scope_key token separator (Scope.Key, SCHEMA.md D5). An unconstrained lang/framework/ topic value containing it (e.g. an extractor returning "CI|CD") would silently re-split into two tokens on the way through ParseScopeKey, changing the token count and orphaning the Connection — it would never SubsetOf-match its own scope again. Mapped to '-' rather than dropped so "ci|cd" and "cicd" stay distinguishable, mirroring the control-char stripping being a drop only because dropping there loses nothing. '=' is deliberately left alone: it separates key from value within one token (CanonToken), not tokens within a scope_key, and stripping it would mangle legitimate values like "a=b" instead of protecting anything.
func DecayFactor ¶
DecayFactor returns 2^(-Δt/halflife); 1 when to <= from.
func ExcessSurprisal ¶
ExcessSurprisal = cross-entropy of the (possibly weighted) outcome minus the predictive entropy: 驚き − 迷い (ADR-0002). Zero-mean under calibration; sinks on expected outcomes, rises on confident misses.
func LnBF ¶
LnBF is the log Bayes factor of H1 (the attribute partitions the world) against H0 (one p for all) — ADR-0002. Accepts fractional (decayed) counts.
func MarshalContext ¶
MarshalContext / MarshalOutcome keep JSON canonical for storage.
func MarshalOutcome ¶
func OutcomeWeight ¶
func OutcomeWeight(e *Experience) (y float64, ok bool)
OutcomeWeight resolves raw observations into y in [0,1] (ADR-0003 layer weights). Pure function: change it and `tomobit rebuild` reinterprets all history.
Returns ok=false when the experience carries no usable outcome signal (e.g. cancelled).
func RegIncBeta ¶
RegIncBeta is the regularized incomplete beta function I_x(a,b) — the Beta(a,b) CDF at x. Continued-fraction evaluation (Lentz), accurate to ~1e-12 for the posterior masses this engine sees.
Types ¶
type Connection ¶
type Connection struct {
Kind string
ScopeKey string
Target string
Alpha float64
Beta float64
LastUpdate int64
BornTS int64
ParentKey string
PriorA float64
PriorB float64
}
Connection is a projection row: the substance is Beta(α,β) plus the lazy decay anchor. Everything else is a derived view (One Ledger).
PriorA/PriorB are this connection's own prior (ADR-0013): a split child inherits Beta(μ·m₀, (1−μ)·m₀) from its parent's posterior mean, and decay sinks back to it — 忘却の底は白紙ではなく、家系の記憶である.
func (*Connection) Confidence ¶
func (c *Connection) Confidence(nowMs int64) float64
func (*Connection) Evidence ¶
func (c *Connection) Evidence(nowMs int64) float64
Evidence is the decayed pseudo-count in excess of the connection's prior.
func (*Connection) Mean ¶
func (c *Connection) Mean(nowMs int64) float64
Mean of the decayed posterior at nowMs.
func (*Connection) Observe ¶
func (c *Connection) Observe(y float64, tsMs int64)
Observe folds one weighted outcome into the posterior: decay to ts, then α += y, β += 1−y.
func (*Connection) PosteriorAt ¶
func (c *Connection) PosteriorAt(nowMs int64) (a, b float64)
PosteriorAt applies lazy decay: pseudo-counts shrink toward the connection's own prior (ADR-0013: the sink is the family memory, not a fixed Beta(1,1)). The stored (alpha, beta) are raw values anchored at lastUpdate.
func (*Connection) Prior ¶
func (c *Connection) Prior() (a, b float64)
Prior returns the connection's own prior, falling back to Beta(1,1) for parentless connections and legacy rows where the pair was never set (ADR-0003: 親を持たずに生まれるConnectionの初期値).
func (*Connection) QuantileAt ¶
func (c *Connection) QuantileAt(nowMs int64, q float64) float64
QuantileAt is the pessimistic quantile of the connection's decayed posterior — the capability gate's statistic (ADR-0012 Decision 2).
func (*Connection) SampleAt ¶
func (c *Connection) SampleAt(rng *rand.Rand, nowMs int64) float64
SampleAt draws once from the connection's decayed posterior — the Thompson Sampling primitive (ADR-0012 Decision 1).
func (*Connection) Scope ¶
func (c *Connection) Scope() Scope
type Engine ¶
type Engine struct {
Repo Repo
// contains filtered or unexported fields
}
Engine applies experiences to the Knowledge Network.
func (*Engine) Apply ¶
func (en *Engine) Apply(exp *Experience) error
Apply folds one experience into the projections: births granularity-1 connections, records surprise on every matching connection, updates posteriors, then summons the judgment where the ledger has surfaced.
All time arithmetic is anchored to exp.TS, never the wall clock, and the judgment only ever consults experiences at or before exp.TS.
Apply alone does not reproduce Rebuild's state: judge only runs on connections the incoming experience's scope touches, so a child gated out of production (ADR-0037) never gets judged again by Apply, while Rebuild always closes its replay with one reconcileMerges sweep over every connection (measured in TestLiveApplyAloneDoesNotReproduceRebuildForAGatedChild — live-only Apply calls leave such a child in place after Rebuild has already merged it away). The invariant is restored only when the caller also calls ReconcileMerges once at its own batch boundary — the responsibility cmd/tomobit, internal/curiosity and internal/reflection each hold after ADR-0037 Decision 2's wiring (confirmed in TestLiveApplyWithReconcileMergesAtBatchBoundaryMatchesRebuildForAGatedChild). If a live Apply ever runs out of (ts, id) order the projection can diverge regardless; `tomobit rebuild` restores the canonical state.
func (*Engine) LedgerSum ¶
func (en *Engine) LedgerSum(c *Connection, nowMs int64) (float64, error)
LedgerSum is the decayed cumulative excess surprisal of a connection — the trigger statistic (ADR-0002 第一段).
func (*Engine) PerceiveBatch ¶
func (en *Engine) PerceiveBatch(batch, known []*Experience, onRebuild func()) (rebuilt bool, err error)
PerceiveBatch folds one perceive run's batch into the projections: live Apply + ReconcileMerges when the batch stays in (ts, id) order with everything already perceived and introduces no re-perceived generation, or a full Rebuild otherwise (ADR-0041 決定1・2) — Apply's convergence to Rebuild is only proved for that in-order, single-generation case, so a batch that violates either must re-derive the canonical state rather than silently drift from it. batch must already be sorted by (ts, id) — every call site sorts its Perceiver.Run() result before handing it here, and PerceiveBatch trusts that instead of re-sorting a slice its two callers already sort identically. known is experiences_current as of just before batch was inserted; every caller already has it fetched for its own reasons (e.g. re-perception candidates), so this asks nothing extra of them.
onRebuild, if non-nil, runs immediately before Rebuild starts — not after it returns — because Rebuild is not one transaction (ADR-0041 前提と残す 露出): a crash partway through must not leave the operator without so much as the one honest line explaining why. The returned bool reports whether Rebuild ran to completion, never whether it merely started — "attempted" and "succeeded" are not the same claim, and a caller deciding whether the live projection can be trusted needs the latter. PerceiveBatch itself does no I/O beyond that callback, matching the rest of this package.
func (*Engine) Rebuild ¶
Rebuild wipes the projections and replays experiences_current in order — Knowledge is Rebuildable made executable (ADR-0004 D10).
func (*Engine) ReconcileMerges ¶
ReconcileMerges gives merge judgment the reach judge's touched-connection path cannot (ADR-0037 Decision 2): a child gated out of production is never picked, so it never receives an experience, so judge never runs on it, and its distinguishing token's ln BF — even once decay has carried it well under ThetaMerge — is never read. That is the self-reinforcing deadlock the ADR names: gated out → unused → untouched → unjudged. mergeCheck is a pure function of decayed evidence at nowMs, so sweeping every connection here reaches the same verdict the touched-connection path would have reached for the same child; only the reach changes, the rule does not.
This is deliberately the "重い、呼ばれた時だけ" side of the two-stage judge (ADR-0002): call it once per Apply batch and once per Rebuild (Rebuild does, at the end of its replay) — never per experience, which is exactly the cost ADR-0002's staging exists to avoid.
type Experience ¶
type Experience struct {
ID string
SessionID string
TS int64 // unix ms of the underlying work
Kind string
ExtractorVer int
ExtractorModel string
Context map[string]string
Provider string // execution only
Plan string // execution only (ADR-0014)
Outcome Outcome
Source string // "production" | "learning"
}
Experience is the immutable asset (SCHEMA.md: experiences table).
Plan is the harness-known plan the run followed (ADR-0014) — a machine attribute like Provider, never asked of the model. Empty for runs that used no plan machinery.
func (*Experience) ConnKind ¶
func (e *Experience) ConnKind() string
ConnKind maps an experience kind to the connection kind it feeds.
func (*Experience) Target ¶
func (e *Experience) Target() string
Target returns the connection target this experience is evidence for: the provider for execution, the canonical pair "a~b" for preference.
func (*Experience) Tokens ¶
func (e *Experience) Tokens() []string
Tokens returns the canonical attribute tokens of the context.
type LedgerEntry ¶
type LedgerEntry struct {
Kind string
ScopeKey string
Target string
ExperienceID string
TS int64
P float64
Y float64
SExcess float64
}
LedgerEntry is one row of the surprise ledger (ADR-0002).
type Outcome ¶
type Outcome struct {
TestsPassed *bool `json:"tests_passed,omitempty"`
Adopted string `json:"adopted,omitempty"` // "as-is" | "with-edits"
Reverted bool `json:"reverted,omitempty"`
// Failed is the objective execution-failure signal (provider.error /
// exit≠0), kept apart from Reverted on purpose (ADR-0028 Decision 5): a
// revert is the user's subjective pushback, a failure is the process not
// delivering — folding one into the other would blur two meanings rebuild
// could never separate again. It is the only signal a split subtask or a
// duel child carries (both have an empty task.finished).
Failed bool `json:"failed,omitempty"`
Verdict string `json:"verdict,omitempty"` // "up" | "down"
Cancelled bool `json:"cancelled,omitempty"`
Preferred string `json:"preferred,omitempty"` // preference kind
Over string `json:"over,omitempty"` // preference kind
Insight string `json:"insight,omitempty"` // reflection: candidate type told
Reaction string `json:"reaction,omitempty"` // reflection: "unexpected" | "known" | "wrong"
}
Outcome holds the raw observations of an experience. Weights are NOT stored here; they are resolved by OutcomeWeight (SCHEMA.md D11).
Insight/Reaction belong to reflection experiences (ADR-0015). They live in Outcome, not Context, on purpose: a context token like "insight=split" would enter the Split candidate vocabulary and let the judgment partition capability worlds on the mirror's own bookkeeping.
type Repo ¶
type Repo interface {
GetConnection(kind, scopeKey, target string) (*Connection, error)
UpsertConnection(c *Connection) error
DeleteConnection(kind, scopeKey, target string) error
ConnectionsFor(kind, target string) ([]*Connection, error)
AllConnections() ([]*Connection, error)
InsertLedger(e *LedgerEntry) error
LedgerFor(kind, scopeKey, target string) ([]*LedgerEntry, error)
DeleteLedgerFor(kind, scopeKey, target string) error
// CurrentExperiences returns experiences_current ordered by (ts, id).
CurrentExperiences() ([]*Experience, error)
ClearProjections() error
}
Repo is the storage the engine needs. Implemented by internal/store.
type Scope ¶
type Scope []string
Scope is a sorted, unique set of canonical "key=value" tokens. Its Key is the '|'-joined form used as the connections primary key (SCHEMA.md D5/D8).