engine

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 59 Imported by: 0

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{
		".git":         true,
		".scouter":     true,
		"node_modules": true,
		"vendor":       true,
	}
	SupportedExts = map[string]bool{
		".go":  true,
		".ts":  true,
		".tsx": true,
		".js":  true,
		".jsx": true,
		".py":  true,
	}
)
View Source
var ErrEmptySource = errors.New("source file is empty")

ErrEmptySource indicates the resolved file contains no data.

View Source
var PPool = &parserPool{
	pools: make(map[*gotreesitter.Language]*sync.Pool),
}

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 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 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
}

func (*DiagnosticEngine) AssessRisk

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

AssessRisk provides a unified risk assessment.

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 Bleve. Retorna la representación del HUD en formato ZON.

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)
}

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 DiscoveryService added in v1.1.0

type DiscoveryService interface {
	HybridSearch(ctx context.Context, query string, limit, offset int) (*types.HybridSearchResult, error)
	FindLogicalTwins(ctx context.Context, symbolName, path string) ([]types.Symbol, error)
	GetNeighborhood(ctx context.Context, filePath string) (string, 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

type EvolutionService added in v1.1.0

type EvolutionService interface {
	ProposeEvolution(ctx context.Context, proposal string, force bool, messenger Messenger) (string, error)
	Propagate(ctx context.Context, symbol, transformation string, messenger Messenger) (string, error)
	CommitLedger(ctx context.Context) (string, error)
	RollbackLedger(ctx context.Context) (string, error)
	GetLedgerDiff(ctx context.Context) (string, error)
	GetLedgerSummary(ctx context.Context) string
	StageMutation(ctx context.Context, filePath, newContent string) error
}

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 *DiagnosticEngine
	// 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).

func (*HealerEngine) Index

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

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

type HealerService added in v1.1.0

type HealerService interface {
	Fix(ctx context.Context, errorLog string, messenger Messenger) (string, error)
	DiagnoseHUD(ctx context.Context, errorLog string) (*DiagnosticHUD, error)
}

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 *SemanticEngine
	Analyzer *AnalysisEngine
	Search   *SearchEngine
	ASTRules *ASTRuleEngine
	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) Run added in v1.1.0

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

type IndexerService added in v1.1.0

type IndexerService interface {
	Index(ctx context.Context, path string) error
}

type IntelligenceService added in v1.1.0

type IntelligenceService interface {
	AnalyzeImpact(ctx context.Context, symbol, path string, verbose bool, messenger Messenger) (*types.ImpactResult, error)
	GetCriticalSymbols(ctx context.Context, limit int) ([]store.CriticalSymbol, error)
	PredictTests(ctx context.Context, diff string) ([]types.TestTarget, error)
	AuditArchitecture(ctx context.Context, targetPath string) ([]types.ASTRuleMatch, 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"`
	// 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 atomically using a two-phase commit.

func (*Ledger) GetStaged

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

GetStaged returns all pending patches.

func (*Ledger) IncrementTurn

func (l *Ledger) IncrementTurn()

IncrementTurn advances the mission turn counter.

func (*Ledger) Load

func (l *Ledger) Load() error

Load restores the ledger state from disk.

func (*Ledger) Rollback

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

Rollback clears all staged changes and removes the ledger file.

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 string, userPrompt string) (string, error)
}

Messenger defines the interface for the TruthEngine to communicate with the user via the underlying protocol (e.g., MCP Sampling).

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"`
}

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) HybridSearch

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

HybridSearch executes parallel lookups in the AST, Bleve, 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 (*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 TruthEngine

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

TruthEngine is the central orchestrator for all "truth-seeking" operations. It decouples the MCP handlers from the core logic and manages the coordination between different specialized engines.

func NewTruthEngine

func NewTruthEngine(store store.Store, opts ...TruthOption) *TruthEngine

NewTruthEngine initializes a new TruthEngine with its dependencies.

func (*TruthEngine) AnalyzeImpact

func (e *TruthEngine) AnalyzeImpact(ctx context.Context, symbol, path string, verbose bool, messenger Messenger) (*types.ImpactResult, error)

func (*TruthEngine) AuditArchitecture added in v1.2.0

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

func (*TruthEngine) Compact

func (e *TruthEngine) Compact() *CompactionEngine

func (*TruthEngine) CompactSession

func (e *TruthEngine) CompactSession(ctx context.Context, log string) (*types.CompactionResult, error)

func (*TruthEngine) DiagnoseHUD added in v1.1.0

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

func (*TruthEngine) FindLogicalTwins

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

func (*TruthEngine) Fix

func (e *TruthEngine) Fix(ctx context.Context, errorLog string, messenger Messenger) (string, error)

func (*TruthEngine) GetCriticalSymbols

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

func (*TruthEngine) GetNeighborhood

func (e *TruthEngine) GetNeighborhood(ctx context.Context, filePath string) (string, error)

func (*TruthEngine) Healer

func (e *TruthEngine) Healer() *HealerEngine

func (*TruthEngine) HybridSearch

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

func (*TruthEngine) IdentifyCriticalContext

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

func (*TruthEngine) Index

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

func (*TruthEngine) MemoryProvider

func (e *TruthEngine) MemoryProvider() memory.MemoryProvider

func (*TruthEngine) PredictTests

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

func (*TruthEngine) SemanticSearch

func (e *TruthEngine) SemanticSearch(ctx context.Context, query string, limit int) ([]types.Symbol, error)

type TruthOption

type TruthOption func(*TruthEngine)

TruthOption defines a functional option for configuring a TruthEngine.

func WithASTRules

func WithASTRules(a *ASTRuleEngine) TruthOption

func WithAnalyzer

func WithAnalyzer(a *AnalysisEngine) TruthOption

func WithCompact

func WithCompact(c *CompactionEngine) TruthOption

func WithDiagnostic

func WithDiagnostic(d *DiagnosticEngine) TruthOption

func WithHealer

func WithHealer(h *HealerEngine) TruthOption

func WithImpact

func WithImpact(i *ImpactEngine) TruthOption

func WithLSP

func WithLSP(l *lsp.Manager) TruthOption

func WithLedger

func WithLedger(l *Ledger) TruthOption

func WithMemory

func WithMemory(m memory.MemoryProvider) TruthOption

func WithMessenger

func WithMessenger(m Messenger) TruthOption

func WithRipple

func WithRipple(r *RippleEngine) TruthOption

func WithSearch

func WithSearch(s *SearchEngine) TruthOption

func WithSemantic

func WithSemantic(s *SemanticEngine) TruthOption

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