engine

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 58 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

Index

Constants

View Source
const MaxFragmentSize = 100 * 1024

MaxFragmentSize is the limit for a surgical read (100KB)

View Source
const MaxParseSize = 5 * 1024 * 1024

MaxParseSize is the limit for indexing a file (5MB)

Variables

View Source
var BlockedDirs = map[string]bool{
	"vendor":       true,
	"node_modules": true,
	".git":         true,
	"dist":         true,
	"build":        true,
}
View Source
var ErrEmptySource = errors.New("source file is empty")

ErrEmptySource indicates the resolved file contains no data.

View Source
var ErrInterruptedCommit = errors.New("ledger: an interrupted commit must be resolved before committing again")

ErrInterruptedCommit is returned when a commit is attempted while the journal still records an interrupted commit. The operator resolves it first, with Rollback or RollForward.

View Source
var PPool = &parserPool{
	pools: make(map[*gotreesitter.Language]*sync.Pool),
}
View Source
var SupportedExts = map[string]bool{
	".go":   true,
	".ts":   true,
	".tsx":  true,
	".js":   true,
	".py":   true,
	".java": true,
	".rs":   true,
}

Functions

func AnalyzeInterfaceImplementations

func AnalyzeInterfaceImplementations(prog *ssa.Program) map[string][]string

AnalyzeInterfaceImplementations finds all concrete implementations of interfaces.

func AnonymizeNode

func AnonymizeNode(node *gotreesitter.Node, source []byte, lang *gotreesitter.Language, includeBody bool) string

AnonymizeNode traverses the tree from the given node and returns an anonymized S-Expression. It masks identifiers and literals to preserve only the structural logic. When includeBody is false, function/method bodies are skipped (signature-only hash). When includeBody is true, bodies are included (full logic hash).

func ApplyPipeline

func ApplyPipeline(ctx context.Context, f *filter.Filter, input string, resolver filter.SourceResolver) (string, error)

ApplyPipeline executes filter actions sequentially.

func BatchLoadPackages

func BatchLoadPackages(dir string) (map[string]*ParsedPackageData, error)

func EncodeZON

func EncodeZON(slice interface{}) (string, error)

EncodeZON implements a minimal ZON (Zero Overhead Notation) table encoder. It converts slices of structs into a token-efficient tabular format for LLMs, saving 35-70% of tokens compared to JSON.

func EncodeZONImpact

func EncodeZONImpact(res *types.ImpactResult) string

func EncodeZONLSPHover

func EncodeZONLSPHover(hover *lsp.Hover) (string, error)

func EncodeZONLSPLocation

func EncodeZONLSPLocation(locs []lsp.Location) (string, error)

func EncodeZONNeighborhood

func EncodeZONNeighborhood(filePath string, imports []string, exports []store.Symbol, calls []store.Call) string

EncodeZONNeighborhood formats a 1-hop structural neighborhood (imports, exports, calls) into ZON format.

func EncodeZONPredict

func EncodeZONPredict(tests []types.TestTarget) string

func EncodeZONVerify

func EncodeZONVerify(diff *ChronosDiff) string

func ExtractImports

func ExtractImports(ctx context.Context, filePath string) ([]string, error)

func GetLogicHash

func GetLogicHash(node *gotreesitter.Node, source []byte, lang *gotreesitter.Language) string

GetLogicHash generates a SHA-256 hash including the function body for detecting internal logic changes.

func GetParser added in v1.2.0

func GetParser(lang *gotreesitter.Language) *gotreesitter.Parser

func GetStructuralHash

func GetStructuralHash(node *gotreesitter.Node, source []byte, lang *gotreesitter.Language) string

GetStructuralHash generates a SHA-256 hash of the anonymized structural representation (signature only).

func ParseFile

func ParseFile(ctx context.Context, filePath string, lspMgr *lsp.Manager) ([]types.ASTPointer, []types.ASTCall, []types.DataFlow, error)

ParseFile analyzes a file using the AST engine to index its structure and call graph. It is now a wrapper around StreamSymbols for backward compatibility.

func ParseGoMod

func ParseGoMod(ctx context.Context, filePath string) ([]types.Dependency, error)

ParseGoMod reads a go.mod file and extracts its dependencies.

func ParsePackageJSON

func ParsePackageJSON(ctx context.Context, filePath string) ([]types.Dependency, error)

ParsePackageJSON reads a package.json file and extracts its dependencies.

func Passthrough

func Passthrough(ctx context.Context, command string, args []string) (int, error)

Passthrough runs a command with inherited stdio (no capture).

func PutParser added in v1.2.0

func PutParser(lang *gotreesitter.Language, parser *gotreesitter.Parser)

func ReadFragment

func ReadFragment(ctx context.Context, filePath string, r types.Range) (string, error)

ReadFragment reads a specific code fragment from a file within the given range.

func SSACallGraph

func SSACallGraph(ctx context.Context, dir string) ([]types.ASTCall, error)

SSACallGraph generates a high-precision call graph using SSA and CHA.

func StreamSymbols

func StreamSymbols(ctx context.Context, filePath string) (iter.Seq[types.ASTPointer], iter.Seq[types.ASTCall], iter.Seq[types.DataFlow], error)

StreamSymbols analyzes a file and returns iterators for symbols, calls and data flows. Optimized for Go 1.25 to avoid large slice allocations.

func StreamSymbolsFromAST

func StreamSymbolsFromAST(ctx context.Context, fset *token.FileSet, astFile *ast.File, pkg *packages.Package) (iter.Seq[types.ASTPointer], iter.Seq[types.ASTCall], iter.Seq[types.DataFlow], error)

func StreamWithTreeSitter

func StreamWithTreeSitter(ctx context.Context, filePath string) (iter.Seq[types.ASTPointer], iter.Seq[types.ASTCall], iter.Seq[types.DataFlow], error)

func StructuralRefactor

func StructuralRefactor(ctx context.Context, filePath, pattern, template, ext string) (string, error)

Types

type ASTRuleEngine

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

ASTRuleEngine executes architectural rules using ast-grep.

func NewASTRuleEngine

func NewASTRuleEngine(rulesDir string) *ASTRuleEngine

NewASTRuleEngine creates a new engine pointing to the rules directory.

func (*ASTRuleEngine) Audit

func (e *ASTRuleEngine) Audit(ctx context.Context, targetPath string) ([]types.ASTRuleMatch, error)

Audit runs all rules in the rules directory against a specific file or directory.

func (*ASTRuleEngine) GetRules

func (e *ASTRuleEngine) GetRules() ([]string, error)

GetRules returns a list of available rule files.

type AnalysisEngine

type AnalysisEngine struct {
	ProjectRoot string
	// contains filtered or unexported fields
}

func NewAnalysisEngine

func NewAnalysisEngine(store AnalysisStore) *AnalysisEngine

func (*AnalysisEngine) BuildTypeUniverse

func (a *AnalysisEngine) BuildTypeUniverse() (map[string]*types.Package, error)

func (*AnalysisEngine) GetCriticalSymbols

func (a *AnalysisEngine) GetCriticalSymbols(ctx context.Context, limit int) ([]store.CriticalSymbol, error)

func (*AnalysisEngine) GetNeighborhood

func (a *AnalysisEngine) GetNeighborhood(ctx context.Context, filePath string) (string, error)

func (*AnalysisEngine) ResolveCentrality

func (a *AnalysisEngine) ResolveCentrality(ctx context.Context) error

func (*AnalysisEngine) ResolveInterfaces

func (a *AnalysisEngine) ResolveInterfaces(ctx context.Context) error

func (*AnalysisEngine) ResolvePagerank

func (a *AnalysisEngine) ResolvePagerank(ctx context.Context, opts ...PagerankOption) error

type AnalysisStore

AnalysisStore defines the data requirements for the AnalysisEngine.

type AnalyzeOption

type AnalyzeOption func(*AnalyzeOptions)

func WithSSA

func WithSSA(targetPkg, varName string) AnalyzeOption

type AnalyzeOptions

type AnalyzeOptions struct {
	UseSSA       bool
	SSATargetPkg string
	SSAVarName   string
}

type BFSPropagationStrategy

type BFSPropagationStrategy struct {
	ImpactEngine ImpactAnalyzer
	// contains filtered or unexported fields
}

BFSPropagationStrategy implements PropagationStrategy using BFS traversal.

func NewBFSPropagationStrategy

func NewBFSPropagationStrategy(s GraphStore, ie ImpactAnalyzer) *BFSPropagationStrategy

NewBFSPropagationStrategy creates a new breadth-first propagation strategy.

func (*BFSPropagationStrategy) Discover

func (s *BFSPropagationStrategy) Discover(ctx context.Context, startSymbol string, maxDepth int) iter.Seq2[PropagationTask, error]

type BuildValidator

type BuildValidator struct{}

BuildValidator ensures the project still builds after changes.

func (*BuildValidator) Validate

func (v *BuildValidator) Validate(ctx context.Context, ledger *Ledger) (ValidationResult, error)

type CentralityValidator

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

CentralityValidator detects architectural regressions via centrality spikes.

func NewCentralityValidator

func NewCentralityValidator(a *AnalysisEngine) *CentralityValidator

func (*CentralityValidator) Validate

func (v *CentralityValidator) Validate(ctx context.Context, ledger *Ledger) (ValidationResult, error)

type ChronosDiff

type ChronosDiff struct {
	MissingSymbols []string // Symbols that existed before but were deleted
	MangledSymbols []string // Symbols whose structural hash changed (broken syntax/logic)
	AddedSymbols   []string // New symbols added
	Unchanged      int      // Number of symbols that remained perfectly intact
}

ChronosDiff represents the structural differences found after an edit.

type ChronosEngine

type ChronosEngine struct{}

func NewChronosEngine

func NewChronosEngine() *ChronosEngine

func (*ChronosEngine) CompareSnapshot

func (e *ChronosEngine) CompareSnapshot(ctx context.Context, snapshot *ChronosSnapshot, currentFilePath string) (*ChronosDiff, error)

CompareSnapshot verifies a file against a previously taken snapshot.

func (*ChronosEngine) SemanticDiff added in v1.3.0

func (e *ChronosEngine) SemanticDiff(ctx context.Context, target string) (string, error)

func (*ChronosEngine) TakeSnapshot

func (e *ChronosEngine) TakeSnapshot(ctx context.Context, filePath string) (*ChronosSnapshot, error)

TakeSnapshot reads a file and captures its structural AST hashes.

type ChronosSnapshot

type ChronosSnapshot struct {
	ID        string
	FilePath  string
	Symbols   map[string]types.ASTPointer // Key: Symbol Name
	Timestamp time.Time
}

ChronosSnapshot represents a point-in-time structural map of a file.

type ChurnEngine

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

ChurnEngine analyzes the git history to identify tectonic plates (co-changing files).

func NewChurnEngine

func NewChurnEngine(s ChurnStore) *ChurnEngine

func (*ChurnEngine) AnalyzeChurn

func (e *ChurnEngine) AnalyzeChurn(ctx context.Context, repoPath string, commitLimit int) error

AnalyzeChurn calculates the co-change metrics and updates the store.

type ChurnStore

type ChurnStore interface {
	store.SymbolRegistry
	store.TransactionManager
}

ChurnStore defines the data requirements for the ChurnEngine.

type CommitPhase added in v1.4.0

type CommitPhase string

CommitPhase is the state of the mission recorded in the journal.

const (
	// PhaseStaged means the changes are staged and no commit was attempted.
	PhaseStaged CommitPhase = "staged"
	// PhaseCommitting means a commit started and did not reach its end. Only
	// the journal can describe the resulting tree.
	PhaseCommitting CommitPhase = "committing"
)

type CompactionEngine

type CompactionEngine struct {
	Ledger *Ledger
	// contains filtered or unexported fields
}

CompactionEngine handles context hygiene and latent memory anchoring.

func NewCompactionEngine

func NewCompactionEngine(s store.Store, l *Ledger) *CompactionEngine

func (*CompactionEngine) CompactSession

func (e *CompactionEngine) CompactSession(ctx context.Context, truthKernel string) (*types.CompactionResult, error)

CompactSession persists a boundary and provides the resumption prompt.

func (*CompactionEngine) CreateBoundary

func (e *CompactionEngine) CreateBoundary(ctx context.Context, truthKernel string) (*SovereignBoundary, error)

CreateBoundary generates a dense checkpoint of the current engine state.

func (*CompactionEngine) PruneHistory

func (e *CompactionEngine) PruneHistory(toolResults []string) []string

PruneHistory reduces the token weight of tool results while preserving signal.

type ContextEngine added in v1.4.0

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

ContextEngine synthesizes single-shot architectural context packets for AI agents.

func NewContextEngine added in v1.4.0

func NewContextEngine(s ContextStore) *ContextEngine

func (*ContextEngine) BuildFileContext added in v1.4.0

func (e *ContextEngine) BuildFileContext(ctx context.Context, filePath string) (*types.FileContextResult, error)

BuildFileContext returns an ultra-compact single-call context packet for a given file.

type ContextStore added in v1.4.0

type ContextStore interface {
	GraphStore
}

type DiagnosticContext added in v1.3.0

type DiagnosticContext struct {
	FailingFile  string
	ErrorLog     string
	OriginalCode string
	Prompt       string
	Target       *types.ASTPointer
}

DiagnosticContext contains everything needed to propose a fix.

type DiagnosticEngine

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

DiagnosticEngine is the read-only diagnosis entry point.

Doctor contract (ported from Engram's DOCTOR.md): diagnosis never mutates. Diagnose, DiagnoseHUD, AssessRisk and ExtractRCA perform no writes: no Ledger staging, no memory observation, no store mutation, no cursor or index change. Mutation lives behind explicit entry points only: HealerEngine.Fix stages a fix in the Ledger (STAGED, never applied), and applying a staged fix requires an explicit commit/rollback decision. A diagnostic report therefore never implies a tree change.

func (*DiagnosticEngine) AssessRisk

func (e *DiagnosticEngine) AssessRisk(ctx context.Context, symbol, path string) (*RiskAssessment, error)

AssessRisk provides a unified risk assessment.

func (*DiagnosticEngine) BuildHealerContext added in v1.4.0

func (e *DiagnosticEngine) BuildHealerContext(ctx context.Context, target *types.ASTPointer, failingFile, errorLog string, allMatches [][]string, originalCode string) string

func (*DiagnosticEngine) Diagnose

func (e *DiagnosticEngine) Diagnose(ctx context.Context, errorLog string) (*DiagnosticReport, error)

Diagnose parses logs and enriches the failure context.

func (*DiagnosticEngine) DiagnoseHUD added in v1.3.0

func (e *DiagnosticEngine) DiagnoseHUD(ctx context.Context, errorLog string) (*DiagnosticHUD, error)

DiagnoseHUD ejecuta la visión de diagnóstico combinando Git, AST, Impacto y FTS. Retorna la representación del HUD en formato ZON.

func (*DiagnosticEngine) ExtractRCA added in v1.4.0

func (e *DiagnosticEngine) ExtractRCA(errorLog string) (string, int, [][]string, error)

type DiagnosticHUD

type DiagnosticHUD struct {
	FailingSymbol      string
	LastCommit         string
	RiskLevel          string
	RiskScore          float64
	BlastRadius        int
	SimilarPatternPath string
}

DiagnosticHUD representa la visión térmica/estructural del motor de diagnóstico.

type DiagnosticProvider

type DiagnosticProvider interface {
	Diagnose(ctx context.Context, errorLog string) (*DiagnosticReport, error)
	AssessRisk(ctx context.Context, symbol, path string) (*RiskAssessment, error)
	ExtractRCA(errorLog string) (string, int, [][]string, error)
	BuildHealerContext(ctx context.Context, target *types.ASTPointer, failingFile, errorLog string, allMatches [][]string, originalCode string) string
}

type DiagnosticReport

type DiagnosticReport struct {
	FailingSymbol string
	FailingFile   string
	Line          int
	ErrorLog      string
	Context       string
	Risk          *types.ImpactResult
	Insights      []string // Historical insights from Engram
}

DiagnosticReport represents the "Technical Truth" kernel of a failure.

type Embedder added in v1.4.0

type Embedder interface {
	GenerateEmbedding(ctx context.Context, text string) ([]float32, error)
}

type Enricher

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

Enricher coordinates semantic enrichment of the call graph using LSP.

func NewEnricher

func NewEnricher(s EnricherStore, lp LSPProvider) *Enricher

func (*Enricher) Enrich

func (e *Enricher) Enrich(ctx context.Context) error

Enrich methods with implementation data from LSP.

type EnricherStore

EnricherStore defines the data requirements for the Enricher.

type EvolutionEngine added in v1.3.0

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

func NewEvolutionEngine added in v1.3.0

func NewEvolutionEngine(store store.Store, ledger *Ledger, ripple *RippleEngine) *EvolutionEngine

func (*EvolutionEngine) CommitLedger added in v1.3.0

func (e *EvolutionEngine) CommitLedger(ctx context.Context) (string, error)

func (*EvolutionEngine) GetLedgerDiff added in v1.3.0

func (e *EvolutionEngine) GetLedgerDiff(ctx context.Context) (string, error)

func (*EvolutionEngine) GetLedgerSummary added in v1.3.0

func (e *EvolutionEngine) GetLedgerSummary(ctx context.Context) string

func (*EvolutionEngine) Propagate added in v1.3.0

func (e *EvolutionEngine) Propagate(ctx context.Context, symbol, transformation string, messenger Messenger) (string, error)

func (*EvolutionEngine) ProposeEvolution added in v1.3.0

func (e *EvolutionEngine) ProposeEvolution(ctx context.Context, proposal string, force bool, messenger Messenger) (string, error)

func (*EvolutionEngine) RollbackLedger added in v1.3.0

func (e *EvolutionEngine) RollbackLedger(ctx context.Context) (string, error)

func (*EvolutionEngine) StageMutation added in v1.3.0

func (e *EvolutionEngine) StageMutation(ctx context.Context, filePath, newContent string) error

func (*EvolutionEngine) StagedLedger added in v1.4.0

func (e *EvolutionEngine) StagedLedger() *Ledger

StagedLedger returns the canonical ledger this engine stages into. Callers inspect it directly instead of re-reading the staging file.

type FixCandidate added in v1.3.0

type FixCandidate struct {
	ID       int
	Code     string
	FullCode string
	Valid    bool
	Score    float64
}

FixCandidate represents a potential fix.

type GraphStore

type GraphStore interface {
	store.SymbolRegistry
	store.StructuralGraph
}

GraphStore defines the core read-only graph traversal capabilities.

type HealerEngine

type HealerEngine struct {
	Ledger *Ledger

	// Bridge to MCP sampling
	DoFixRequest func(ctx context.Context, prompt string) (string, error)

	Search *SearchEngine

	Diagnostic DiagnosticProvider
	// contains filtered or unexported fields
}

HealerEngine manages the autonomous RCA -> Fix -> Verify loop using the Shinigami Protocol.

func (*HealerEngine) Fix

func (e *HealerEngine) Fix(ctx context.Context, errorLog string) (*types.HealResult, error)

Fix attempts to repair a test failure using the Shinigami Protocol (Solver-Verifier).

Mutation boundary: Fix STAGES the winning candidate in the Ledger and records one memory observation. It never applies, commits, or rolls back: the staged fix takes effect only through an explicit commit/rollback decision on the Ledger. Callers that only need a diagnosis must use DiagnosticEngine and never reach this entry point.

func (*HealerEngine) Index

func (e *HealerEngine) Index(ctx context.Context, path string) error

Index parses and persists a file. (Internal helper for HealerEngine)

func (*HealerEngine) SetFixRequestHook added in v1.4.0

func (e *HealerEngine) SetFixRequestHook(hook func(ctx context.Context, prompt string) (string, error))

SetFixRequestHook allows setting the hook for LLM fix requests.

type HealthEngine

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

func NewHealthEngine

func NewHealthEngine(store TestResultStore) *HealthEngine

func (*HealthEngine) Ingest

func (h *HealthEngine) Ingest(ctx context.Context, r io.Reader) error

type ImpactAnalyzer

type ImpactAnalyzer interface {
	GetDeterministicCallers(ctx context.Context, symbolName string) ([]store.Call, error)
}

ImpactAnalyzer abstracts the capabilities of the ImpactEngine required by other engines.

type ImpactEngine

type ImpactEngine struct {
	LSPManager *lsp.Manager
	// contains filtered or unexported fields
}

func NewImpactEngine

func NewImpactEngine(s GraphStore, lm *lsp.Manager, mem memory.MemoryProvider) *ImpactEngine

func (*ImpactEngine) Analyze

func (e *ImpactEngine) Analyze(ctx context.Context, symbol string, path string, maxDepth int, opts ...AnalyzeOption) (*types.ImpactResult, error)

Analyze performs a deep impact analysis for a given symbol.

func (*ImpactEngine) GetDeterministicCallers

func (e *ImpactEngine) GetDeterministicCallers(ctx context.Context, symbolName string) ([]store.Call, error)

func (*ImpactEngine) IdentifyCriticalContext

func (e *ImpactEngine) IdentifyCriticalContext(ctx context.Context, diff string) ([]types.ImpactEntity, error)

IdentifyCriticalContext finds high-risk symbols affected by the current diff.

func (*ImpactEngine) PredictTests

func (e *ImpactEngine) PredictTests(ctx context.Context, diff string) ([]types.TestTarget, error)

PredictTests identifies tests affected by changes described in the diff string.

type IndexerConfig added in v1.1.0

type IndexerConfig struct {
	Store    store.Store
	Semantic Embedder
	Analyzer *AnalysisEngine
	Search   *SearchEngine
	ASTRules *ASTRuleEngine
	Churn    *ChurnEngine
	Logger   *slog.Logger
}

type IndexerPipeline added in v1.1.0

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

func NewIndexerPipeline added in v1.1.0

func NewIndexerPipeline(cfg IndexerConfig) *IndexerPipeline

func (*IndexerPipeline) Index added in v1.4.0

func (ip *IndexerPipeline) Index(ctx context.Context, path string) error

type LLMSolver added in v1.3.0

type LLMSolver struct {
	DoFixRequest func(ctx context.Context, prompt string) (string, error)
}

func (*LLMSolver) Generate added in v1.3.0

func (s *LLMSolver) Generate(ctx context.Context, diag *DiagnosticContext) (<-chan FixCandidate, error)

type LSPProvider

type LSPProvider interface {
	GetClient(ctx context.Context, filePath string) (lsp.LSPClient, error)
}

LSPProvider defines the requirement for retrieving an LSP client.

type LSPValidator

type LSPValidator struct {
	ProjectRoot string
}

LSPValidator uses go/packages with Overlays to perform zero-disk verification of interface implementations across the entire workspace.

func NewLSPValidator

func NewLSPValidator(root string) *LSPValidator

func (*LSPValidator) Validate

func (v *LSPValidator) Validate(ctx context.Context, ledger *Ledger) (ValidationResult, error)

type LSPVerifier added in v1.3.0

type LSPVerifier struct{}

func (*LSPVerifier) Evaluate added in v1.3.0

func (v *LSPVerifier) Evaluate(ctx context.Context, diag *DiagnosticContext, c *FixCandidate) (bool, error)

type LanguageConfig

type LanguageConfig struct {
	Language    *gotreesitter.Language
	Query       *gotreesitter.Query
	CallQuery   *gotreesitter.Query
	ImportQuery *gotreesitter.Query
	FlowQuery   *gotreesitter.Query
}

type Ledger

type Ledger struct {
	Staged    map[string]Patch `json:"staged"`
	Stats     MissionStats     `json:"stats"`
	KiLimit   int64            `json:"ki_limit"`
	TurnLimit int              `json:"turn_limit"`
	Project   string           `json:"project"`
	Phase     CommitPhase      `json:"phase,omitempty"`
	Applied   []string         `json:"applied,omitempty"`
	Pending   []string         `json:"pending,omitempty"`
	// contains filtered or unexported fields
}

Ledger holds staged changes and mission metrics.

func NewLedger

func NewLedger() *Ledger

func (*Ledger) AffectedFiles

func (l *Ledger) AffectedFiles() []string

AffectedFiles is an alias for StagedFiles.

func (*Ledger) CommitStaged

func (l *Ledger) CommitStaged(ctx context.Context) error

CommitStaged applies all staged changes to the filesystem using a two-phase commit.

Each file is replaced atomically, but the batch is not atomic across files: the files are applied one at a time, in sorted path order. The journal therefore records the commit before the filesystem is touched, and keeps the list of files already replaced, so an interrupted commit can be resolved afterwards with Rollback or RollForward.

func (*Ledger) GetStaged

func (l *Ledger) GetStaged() []Patch

GetStaged returns all pending patches.

func (*Ledger) HasInterruptedCommit added in v1.4.0

func (l *Ledger) HasInterruptedCommit() bool

HasInterruptedCommit reports whether the journal records a commit that started and did not finish.

func (*Ledger) IncrementTurn

func (l *Ledger) IncrementTurn()

IncrementTurn advances the mission turn counter.

func (*Ledger) InterruptedAppliedFiles added in v1.4.0

func (l *Ledger) InterruptedAppliedFiles() []string

InterruptedAppliedFiles returns the files the interrupted commit had already replaced.

func (*Ledger) InterruptedPendingFiles added in v1.4.0

func (l *Ledger) InterruptedPendingFiles() []string

InterruptedPendingFiles returns the files the interrupted commit had not replaced yet.

func (*Ledger) Load

func (l *Ledger) Load() error

Load restores the ledger state from disk.

func (*Ledger) RollForward added in v1.4.0

func (l *Ledger) RollForward(ctx context.Context) error

RollForward completes an interrupted commit by applying the files it had not replaced yet. It is the explicit counterpart of Rollback: the operator decides which side of the interruption the tree ends on.

func (*Ledger) Rollback

func (l *Ledger) Rollback(ctx context.Context) error

Rollback clears the staged changes.

When the journal records an interrupted commit, the files that commit already replaced are restored first, so the tree returns to the state it had before the commit. A file whose content changed after the interruption is never overwritten: the rollback fails instead of destroying work that the journal does not know about.

func (*Ledger) Save

func (l *Ledger) Save() error

Save persists the current ledger state to disk.

func (*Ledger) SetBudget

func (l *Ledger) SetBudget(kiLimit int64, turnLimit int)

SetBudget sets the limits for the current mission.

func (*Ledger) SetLedgerPath

func (l *Ledger) SetLedgerPath(path string)

SetLedgerPath updates the persistence path and attempts to load it.

func (*Ledger) Stage

func (l *Ledger) Stage(path string, patch Patch) error

Stage adds a patch to the ledger and saves to disk.

func (*Ledger) StagedFiles

func (l *Ledger) StagedFiles() []string

StagedFiles returns the list of paths in the ledger.

func (*Ledger) Summary

func (l *Ledger) Summary() string

Summary returns a human-readable mission report.

func (*Ledger) Unstage

func (l *Ledger) Unstage(path string)

Unstage removes a patch from the ledger.

type LineProvenance

type LineProvenance struct {
	Line           int
	Commit         string
	Author         string
	EngineeringEra string
}

LineProvenance tracks the origin of a specific line.

func GetFileProvenance

func GetFileProvenance(ctx context.Context, repoPath, filePath string) ([]LineProvenance, error)

GetFileProvenance performs a deep blame analysis using go-git to reconstruct the evolutionary narrative of a file.

type Linker

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

func NewLinker

func NewLinker(logger *slog.Logger) *Linker

func (*Linker) LinkInterfaces

func (l *Linker) LinkInterfaces(ctx context.Context, repo store.Store, lspMgr *lsp.Manager) error

LinkInterfaces performs semantic linking between interfaces and their implementations using the LSP 'textDocument/implementation' request.

type LocalFileResolver

type LocalFileResolver struct{}

LocalFileResolver implements filter.SourceResolver for local filesystem reads.

func (*LocalFileResolver) ResolveSource

func (r *LocalFileResolver) ResolveSource(ctx context.Context, file string, line int) (string, error)

ResolveSource fetches a context window around a specific line in a file. It returns a 5-line window (2 before, 2 after the target line).

type MCPTransformer

type MCPTransformer struct {
	DoTransform func(ctx context.Context, file, symbol, transformation string) (string, error)
	// contains filtered or unexported fields
}

MCPTransformer implements Transformer using MCP Sampling.

func NewMCPTransformer

func NewMCPTransformer(s GraphStore, bridge func(context.Context, string, string, string) (string, error)) *MCPTransformer

func (*MCPTransformer) Transform

func (t *MCPTransformer) Transform(ctx context.Context, file, symbol, transformation string) (string, error)

type Messenger

type Messenger interface {
	Ask(ctx context.Context, systemPrompt, message string) (string, error)
}

Messenger provides a callback for asking questions to an oracle (LLM/User)

type MissionStats

type MissionStats struct {
	StartTime  time.Time `json:"start_time"`
	TotalKi    int64     `json:"total_ki"`   // Token usage (approximated)
	TurnCount  int       `json:"turn_count"` // Number of iterations
	FilesCount int       `json:"files_count"`
}

MissionStats tracks the resource consumption of the current operation.

type PagerankOption

type PagerankOption func(*PagerankOptions)

func WithTaskSeeds

func WithTaskSeeds(seeds []string) PagerankOption

type PagerankOptions

type PagerankOptions struct {
	TaskSeeds []string
}

type ParsedPackageData

type ParsedPackageData struct {
	File *ast.File
	Fset *token.FileSet
	Pkg  *packages.Package
}

type Patch

type Patch struct {
	FilePath   string      `json:"file_path"`
	Original   string      `json:"original,omitempty"`
	NewContent string      `json:"new_content"`
	Diff       string      `json:"diff,omitempty"`
	Mode       os.FileMode `json:"mode,omitempty"`
	IsNew      bool        `json:"is_new,omitempty"`
}

Patch represents a pending file modification.

type Pipeline

type Pipeline struct {
	Registry   *filter.Registry
	Tracker    *telemetry.Tracker
	LSPManager *lsp.Manager

	TeeConfig    tee.Config
	Verbose      int
	GainLevel    int // 0: compact, 1: signal (SNR), 2: raw
	UltraCompact bool
	Enrich       bool
	// contains filtered or unexported fields
}

Pipeline orchestrates command execution, filtering, tracking, and tee.

func (*Pipeline) PassiveHealthIngest

func (p *Pipeline) PassiveHealthIngest(ctx context.Context, output string)

PassiveHealthIngest parses test results from stdout and updates the risk map.

func (*Pipeline) Passthrough

func (p *Pipeline) Passthrough(ctx context.Context, command string, args []string) int

Passthrough runs a command directly without filtering.

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, command string, args []string) int

Run executes a command through the full pipeline.

func (*Pipeline) ShadowIndex

func (p *Pipeline) ShadowIndex(ctx context.Context)

ShadowIndex re-indexes files modified by the current execution.

type PropagationStrategy

type PropagationStrategy interface {
	Discover(ctx context.Context, startSymbol string, depth int) iter.Seq2[PropagationTask, error]
}

PropagationStrategy defines the traversal logic for symbol discovery.

type PropagationTask

type PropagationTask struct {
	SymbolName     string // Local name for matching (e.g., "Greet")
	ImpactedSymbol string // FQN of the impacted symbol (e.g., "tests.S1.Greet")
	FilePath       string
	Action         string
}

PropagationTask represents a single unit of work in the ripple propagation.

type Result

type Result struct {
	Stdout   string
	Stderr   string
	ExitCode int
	Duration time.Duration
}

Result holds the output of a command execution.

func Execute

func Execute(ctx context.Context, command string, args []string) (*Result, error)

Execute runs a command, capturing stdout and stderr concurrently via goroutines.

type RippleEngine

type RippleEngine struct {
	Transformer  Transformer
	ImpactEngine ImpactAnalyzer
	Strategy     PropagationStrategy
	Validators   []Validator
	// contains filtered or unexported fields
}

func NewRippleEngine

func NewRippleEngine(s GraphStore, t Transformer, ie ImpactAnalyzer) *RippleEngine

func (*RippleEngine) Propagate

func (e *RippleEngine) Propagate(ctx context.Context, symbolName string, transformation string, maxDepth int) (*Ledger, error)

Propagate traces the blast radius of a symbol and applies the transformation to all affected files.

type RiskAssessment

type RiskAssessment struct {
	Symbol     string
	Path       string
	RiskScore  float64
	Centrality int
	Callers    int
	RiskLevel  string
}

RiskAssessment consolidates centrality and blast radius metrics.

type SearchEngine

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

func (*SearchEngine) FindLogicalTwins added in v1.4.0

func (e *SearchEngine) FindLogicalTwins(ctx context.Context, symbolName, path string) ([]types.Symbol, error)

func (*SearchEngine) HybridSearch

func (e *SearchEngine) HybridSearch(ctx context.Context, query string, limit, offset int, pathPrefix string) (*types.HybridSearchResult, error)

HybridSearch executes parallel lookups in the AST, FTS, and Engram databases.

func (*SearchEngine) IndexSymbol

func (e *SearchEngine) IndexSymbol(docID string, data map[string]interface{}) error

type SemanticEngine

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

func NewSemanticEngine added in v1.4.0

func NewSemanticEngine() (*SemanticEngine, error)

func (*SemanticEngine) GenerateEmbedding

func (s *SemanticEngine) GenerateEmbedding(ctx context.Context, text string) ([]float32, error)

func (*SemanticEngine) Init

func (s *SemanticEngine) Init(ctx context.Context, modelPath string) error

type ShinigamiPipeline added in v1.3.0

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

ShinigamiPipeline orchestrates the Solver and Verifier.

func NewShinigamiPipeline added in v1.3.0

func NewShinigamiPipeline(s Solver, v Verifier) *ShinigamiPipeline

func (*ShinigamiPipeline) Run added in v1.3.0

type Solver added in v1.3.0

type Solver interface {
	Generate(ctx context.Context, diag *DiagnosticContext) (<-chan FixCandidate, error)
}

Solver is the generative interface (LLM/AI).

type SovereignBoundary

type SovereignBoundary struct {
	ID          string           `json:"boundary_id"`
	TruthKernel string           `json:"truth_kernel"` // Dense summary of discoveries
	StagingArea map[string]Patch `json:"staging_area"` // Current Ledger state
	Budget      MissionStats     `json:"budget"`       // Ki/Turns consumption
	Timestamp   string           `json:"timestamp"`
}

SovereignBoundary represents a technical checkpoint in the conversation.

type StructuralMatch

type StructuralMatch struct {
	Path      string            `json:"path"`
	Range     types.Range       `json:"range"`
	StartLine int               `json:"start_line"`
	EndLine   int               `json:"end_line"`
	Content   string            `json:"content"`
	Captures  map[string]string `json:"captures"`
}

func StructuralSearch

func StructuralSearch(ctx context.Context, rootPath, pattern, ext string) ([]StructuralMatch, error)

func StructuralSearchWithRule

func StructuralSearchWithRule(ctx context.Context, rootPath string, rule types.StructuralRule, ext string) ([]StructuralMatch, error)

type StructuralTransformer

type StructuralTransformer struct {
	Pattern string
}

StructuralTransformer implements Transformer using structural search and replace.

func (*StructuralTransformer) Transform

func (t *StructuralTransformer) Transform(ctx context.Context, file, symbol, transformation string) (string, error)

type TestResultStore

type TestResultStore interface {
	SaveTestResult(ctx context.Context, res *types.TestResult) error
}

type TestValidator

type TestValidator struct {
	SpecificTests []string
}

TestValidator ensures relevant tests still pass.

func (*TestValidator) Validate

func (v *TestValidator) Validate(ctx context.Context, ledger *Ledger) (ValidationResult, error)

type TransactionalStore

type TransactionalStore interface {
	GraphStore
	store.DiagnosticStore
	store.TransactionManager
}

TransactionalStore defines the complete contract required by HealerEngine.

type Transformer

type Transformer interface {
	Transform(ctx context.Context, file string, symbolName string, transformation string) (string, error)
}

Transformer defines how to modify a file based on a symbolic change.

type ValidationResult

type ValidationResult struct {
	Valid   bool
	Message string
	Details map[string]any
}

ValidationResult carries the outcome of a validation stage.

type Validator

type Validator interface {
	Validate(ctx context.Context, ledger *Ledger) (ValidationResult, error)
}

Validator defines the interface for verifying the integrity of staged changes.

type Verifier added in v1.3.0

type Verifier interface {
	Evaluate(ctx context.Context, diag *DiagnosticContext, c *FixCandidate) (bool, error)
}

Verifier evaluates a candidate's validity (LSP/AST).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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