contextbuilder

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package contextbuilder assembles a structured Context Packet from a Synapses graph snapshot, SDLC phase/mode, and the Brain's learned data.

The Context Packet replaces raw graph nodes with semantic summaries, active constraints, team coordination info, quality gate requirements, and learned co-occurrence hints — capped at ~800 tokens for the main LLM consumer.

All types here are internal; pkg/brain converts them to public brain.* types.

Package contextbuilder — this file implements the Learner, which records co-occurrence patterns from agent decisions into brain.sqlite.

The Learner is pure Go (no LLM calls). It tracks which entities agents edit together, incrementing co-occurrence counters in context_patterns. These counters are used by the Builder to populate PatternHints.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentItem

type AgentItem struct {
	AgentID   string
	Scope     string
	ScopeType string
	ExpiresIn int // seconds until expiry (0 = unknown)
}

AgentItem represents another agent's work claim.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder assembles a Context Packet from a Synapses snapshot and brain data.

func New

func New(st *store.Store, mgr *sdlc.Manager, enr *enricher.Enricher) *Builder

New creates a Builder. enr may be nil to disable LLM insight generation.

func (*Builder) Build

func (b *Builder) Build(ctx context.Context, req Request) (*Packet, error)

Build assembles and returns a Context Packet for the given request. The fast path (SQLite lookups) always runs; the LLM path runs only if req.EnableLLM is true and the enricher is available.

type ClaimRef

type ClaimRef struct {
	AgentID   string
	Scope     string
	ScopeType string
	ExpiresAt string // RFC3339; empty = unknown
}

ClaimRef is a work claim from another agent.

type ConstraintItem

type ConstraintItem struct {
	RuleID      string
	Severity    string
	Description string
	Hint        string // cached fix suggestion, may be empty
}

ConstraintItem is a rule the agent must respect.

type DecisionInput

type DecisionInput struct {
	AgentID         string
	Phase           string
	EntityName      string
	Action          string   // "edit"|"test"|"review"|"fix_violation"
	RelatedEntities []string // entities touched in the same work session
	Outcome         string   // "success"|"violation"|"reverted"|""
	Notes           string
}

DecisionInput carries the data needed to update co-occurrence patterns. It mirrors brain.DecisionRequest but uses no pkg/brain import.

type Learner

type Learner struct {
	// contains filtered or unexported fields
}

Learner records agent decisions and updates co-occurrence patterns.

func NewLearner

func NewLearner(st *store.Store) *Learner

NewLearner creates a Learner backed by the given store.

func (*Learner) RecordDecision

func (l *Learner) RecordDecision(req DecisionInput) error

RecordDecision persists the decision in the audit log and updates co-occurrence patterns for all (entityName, relatedEntity) pairs, both directions.

Example: editing "AuthService" alongside "TokenCache" and "UserRepo" records:

  • AuthService → TokenCache (and TokenCache → AuthService)
  • AuthService → UserRepo (and UserRepo → AuthService)

This is a best-effort operation — individual pattern errors are aggregated and returned, but the log write always proceeds independently.

type Packet

type Packet struct {
	AgentID     string
	EntityName  string
	EntityType  string
	GeneratedAt string
	Phase       string
	QualityMode string

	RootSummary         string
	DependencySummaries map[string]string

	Insight  string
	Concerns []string
	LLMUsed  bool // true when the LLM was called for this packet

	ActiveConstraints []ConstraintItem
	// PacketQuality is a 0.0-1.0 heuristic reflecting how complete the packet is:
	//   1.0 = root summary + dep summaries + LLM insight all present
	//   0.5 = root summary present, no LLM insight
	//   0.0 = empty packet (no summaries ingested yet)
	PacketQuality float64
	TeamStatus    []AgentItem
	Gate          sdlc.Gate
	PatternHints  []PatternItem
	PhaseGuidance string

	// GraphWarnings are actionable warnings derived from graph topology.
	// Always populated (no LLM required) — deterministic, high-signal guidance.
	GraphWarnings []string

	// ComplexityScore is a dimensionless topology-derived risk indicator:
	// (fanIn + fanOut) * (1 + fanOut/10.0). Always populated (no LLM required).
	// 0.0 = isolated/leaf node; higher = more callers + dependencies = higher change risk.
	ComplexityScore float64

	// DeterministicPath is true when Phase and ComplexityScore were computed
	// from graph topology (always). False only when the enricher was not called.
	DeterministicPath bool
}

Packet is the assembled context document returned by Builder.Build(). pkg/brain converts this to brain.ContextPacket for the public API.

type PatternItem

type PatternItem struct {
	Trigger    string
	CoChange   string
	Reason     string
	Confidence float64
}

PatternItem is a learned co-occurrence: "when editing Trigger, also check CoChange".

type Request

type Request struct {
	ProjectID   string
	AgentID     string
	Phase       string // "" = use stored project phase
	QualityMode string // "" = use stored project mode
	EnableLLM   bool   // true = allow LLM insight generation (adds ~2-3s)

	// From Synapses snapshot:
	RootNodeID      string
	RootName        string
	RootType        string
	RootFile        string   // used for constraint hint lookups
	CalleeNames     []string // direct callees
	CallerNames     []string // direct callers
	RelatedNames    []string // transitive neighbours
	ApplicableRules []RuleRef
	ActiveClaims    []ClaimRef
	TaskContext     string
	TaskID          string

	// Graph topology signals (populated by synapses core):
	HasTests bool   // whether *_test.go exists for root file
	FanIn    int    // total caller count (may exceed len(CallerNames) when capped)
	RootDoc  string // AST doc comment; used as fallback when brain.sqlite has no summary
}

Request is the input to Builder.Build().

type RuleRef

type RuleRef struct {
	RuleID      string
	Severity    string
	Description string
}

RuleRef is a single architectural rule reference from the Synapses snapshot.

Jump to

Keyboard shortcuts

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