orchestrator

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

SPDX-License-Identifier: MIT Purpose: Adversarial Reviewer — a second agent whose explicit mandate is to BREAK the change. Hypotheses become executable probes; a probe that runs red PROVES the attack landed. Surviving probes stay on disk as permanent regression tests (the change makes the suite stronger by failing review).

SPDX-License-Identifier: MIT Purpose: Agent abstraction + mock implementation. Real LLM-backed implementations would call a model API; for now, agents can be run in "mock" mode that produces deterministic placeholder output (useful for testing the dispatcher, planner, and aggregator in isolation).

SPDX-License-Identifier: MIT Purpose: aggregator — combines sub-task results into a final response for the user. Validates success, formats output.

SPDX-License-Identifier: MIT Purpose: Causal Blame — bisect the edit log to find the first edit that flipped a check green→red. O(log n) verification runs via binary search. Precondition: the full log fails the check (caller verified).

SPDX-License-Identifier: MIT Purpose: Repo Cartographer — PageRank-weighted symbol map with incremental updates. Ranks symbols by graph centrality; emits scored ContextItems for the compiler (relevance scores, not full-text dumps). Incremental invalidation: only files in the change set are re-parsed.

SPDX-License-Identifier: MIT Purpose: Calibrated Confidence — honest agent self-assessment. Agent declares P(passes); we score against reality (Brier) and learn a per-agent calibration curve. Auto-merge uses CALIBRATED, not raw.

SPDX-License-Identifier: MIT Purpose: Context Compiler — budget-aware knapsack over context items. Pinned items (contracts, active diagnoses) are constitutional and always included; the rest is greedy by relevance-per-token. Eviction is audited so a bad agent decision can be traced to missing/noisy context.

SPDX-License-Identifier: MIT Purpose: Intent Contract — machine-enforceable mandate compiled from a task. Pre-flight gate on every edit (instant) + post-hoc diff-scope check in the Verifier (authoritative). Agents cannot drift outside their scope.

SPDX-License-Identifier: MIT Purpose: Critic / Repair loop — bounded verify→diagnose→retry with stall detection. A failing Verdict is converted into structured context appended to the task description for the next attempt. Stops when score stalls, the budget runs out, or verification passes.

SPDX-License-Identifier: MIT Purpose: Plan-DAG Executor — tasks as a dependency graph with maximal safe parallelism. LeaseTable is the admission gate: ready nodes run in parallel up to MaxParallel; conflicting nodes serialize via the lease conflict signal. Failures cancel only the dependent subtree; independent branches keep running.

SPDX-License-Identifier: MIT Purpose: dispatcher — runs plan tasks in parallel with dependency-aware scheduling. Tasks whose DependsOn are still running block until those complete. Results are merged into a shared scratchpad.

SPDX-License-Identifier: MIT Purpose: Episodic Replay — persist verified plans as searchable episodes. Uses FTS5 over the existing SQLite memory DB. When a new task arrives, similar past episodes are injected as a planning prior so the agent stops re-deriving known-good strategies from scratch.

SPDX-License-Identifier: MIT Purpose: Budget Governor — escalating ladder of compute strategies. Rung 1 (cheap single-shot) → Rung 2 (repair) → Rung 3 (best-of-N). Each climb is logged with its justification (the failing verdict).

SPDX-License-Identifier: MIT Purpose: small helpers shared across orchestrator files.

SPDX-License-Identifier: MIT Purpose: Impact Oracle — predict blast-radius BEFORE editing. Builds a reverse-dependency graph from `go list -json ./...` and answers "if these files change, which packages and which tests are affected?".

SPDX-License-Identifier: MIT Purpose: Session Kernel — atomic repo+agent checkpoints with verified time-travel. Rewind restores BOTH the working tree AND the agent's state (episode cursor, leases, verdict log). "Rewind to last green" is a first-class operation, not file archaeology.

SPDX-License-Identifier: MIT Purpose: Lease Coordinator — collision-free multi-agent work via path leases with intent broadcast. Acquisition is all-or-nothing (deadlock impossible). Conflicts carry the holder's intent so the requesting agent can decide: wait, renegotiate, or work elsewhere.

SPDX-License-Identifier: MIT Purpose: Macros — pre-compiled fused chains exposed to the agent as single tool calls. sin_change fuses contract-guard + transactional edit + fast-verify; sin_refactor adds impact prediction and a mutation probe behind the green verdict.

SPDX-License-Identifier: MIT Purpose: Chain Miner — automatic distillation of successful tool sequences into new macro chains. The system manufactures its own tools from its own verified experience. New templates start in shadow mode and promote to active when live performance confirms historical evidence.

SPDX-License-Identifier: MIT Purpose: orchestrator data model — Plan, Task, Agent, Result, ScratchpadEntry.

SPDX-License-Identifier: MIT Purpose: Mutation Probe — verify tests actually OBSERVE the change. Injects k small mutations into changed lines only and re-runs the affected tests. Surviving mutations = tests are blind = block auto-merge.

SPDX-License-Identifier: MIT Purpose: LLMAgent — provider-agnostic LLM-backed agent. Uses the Provider field in AgentConfig to pick a backend (nim, openai, anthropic, ollama, groq, custom). Backwards-compatible: NIMAgent is a thin wrapper.

SPDX-License-Identifier: MIT Purpose: top-level Orchestrator — wires together Router, Planner, Dispatcher, Registry, Scratchpad, Aggregator. This is the main entry point.

SPDX-License-Identifier: MIT Purpose: typed, composable tool chains with trace-on-fail semantics. One fused call replaces 6-10 single-shot LLM round-trips; typechecks at construction; every stage may fail and the trace is the agent's resume context.

SPDX-License-Identifier: MIT Purpose: planner — turns a user prompt + classified intent into a Plan with ordered sub-tasks, each bound to a specialized agent.

SPDX-License-Identifier: MIT Purpose: agent registry — loads default agents, merges user agents from ~/.config/sin-code/agents/{name}/agent.toml, picks the right agent for a task type. Uses NIMAgent when SIN_NIM_API_KEY is set, MockAgent otherwise.

SPDX-License-Identifier: MIT Purpose: Pre-LLM router — cheap intent classification using keyword heuristics. In production, this would call a Haiku-class model. For now, deterministic keyword scoring is the fallback when no LLM is configured.

SPDX-License-Identifier: MIT Purpose: Semantic Merge for Go — declaration-level three-way merge. Line-based merge fails on adjacent but independent changes. Semantic merge diffs at function/type/var/import granularity and merges cleanly whenever sides touch DIFFERENT declarations, even when textual neighbors. Only genuine same-decl conflicts escalate.

SPDX-License-Identifier: MIT Purpose: Speculative Best-of-N — N agents in parallel, verifier picks the winner. Each candidate runs in its own worktree; losers are destroyed post-merge.

SPDX-License-Identifier: MIT Purpose: Adaptive Tool-Strategy Router (Thompson sampling). Per (task-class, strategy) Beta posterior learned from verified outcomes. No epsilon, no decay — exploration/exploitation in one mechanism.

SPDX-License-Identifier: MIT Purpose: Targeted Verification — run only the affected test packages. Inner loop: fast targeted suite. Final gate: full suite. Soundness is preserved; only the inner loop iterates 10-50x faster.

SPDX-License-Identifier: MIT Purpose: FsTxn — atomic filesystem transaction for chains that mutate multiple files. Snapshot on first touch, all-or-nothing semantics, idempotent Rollback safe to defer unconditionally.

SPDX-License-Identifier: MIT Purpose: Verified Execution — machine-checkable postconditions on agent output. Every agent action is gated by Check(s) returning a scored Verdict, not a binary "did not crash". Verdicts are replayable, weighted, and feed repair / selection loops.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultUserAgentsPath

func DefaultUserAgentsPath() string

func GenerateID

func GenerateID(prefix string) string

func HashScratchpad

func HashScratchpad(content []byte) string

func PlanningPrior

func PlanningPrior(episodes []*Episode) string

func UseLLM

func UseLLM() bool

UseLLM returns true if any LLM provider is configured.

func UseNIM

func UseNIM() bool

Types

type Adversary

type Adversary struct {
	Agent        AdversaryAgent
	Workdir      string
	MaxAttacks   int
	ProbeTimeout time.Duration
}

func NewAdversary

func NewAdversary(agent AdversaryAgent, workdir string) *Adversary

func (*Adversary) Review

func (adv *Adversary) Review(ctx context.Context, diff, impactBrief string) (*AdversaryResult, error)

type AdversaryAgent

type AdversaryAgent interface {
	ProposeAttacks(ctx context.Context, diff, impactBrief string, maxAttacks int) ([]Attack, error)
}

type AdversaryResult

type AdversaryResult struct {
	Attacks []Attack
	Landed  int
	Cleared bool
}

func (*AdversaryResult) CounterexampleBrief

func (r *AdversaryResult) CounterexampleBrief() string

type Agent

type Agent interface {
	Name() string
	Config() AgentConfig
	Run(ctx context.Context, task *Task, scratch *Scratchpad) (string, error)
}

type AgentConfig

type AgentConfig struct {
	Name          string   `toml:"name"`
	Description   string   `toml:"description"`
	Type          TaskType `toml:"type"`
	Provider      string   `toml:"provider"`
	BaseURL       string   `toml:"base_url"`
	Model         string   `toml:"model"`
	MaxTokens     int      `toml:"max_tokens"`
	Temperature   float64  `toml:"temperature"`
	SystemFile    string   `toml:"system_file"`
	MaxContext    int      `toml:"max_context_tokens"`
	ToolsAllow    []string `toml:"tools_allow"`
	ToolsDeny     []string `toml:"tools_deny"`
	MemoryNS      string   `toml:"memory_namespace"`
	RetentionDays int      `toml:"retention_days"`
}

func DefaultAgents

func DefaultAgents() []AgentConfig

func LoadUserAgents

func LoadUserAgents(baseDir string) ([]AgentConfig, error)

type AgentFactory

type AgentFactory func(rung Rung) []Agent

type AgentState

type AgentState struct {
	TaskID         string          `json:"task_id"`
	EpisodeCursor  int64           `json:"episode_cursor"`
	ScratchpadHash string          `json:"scratchpad_hash"`
	HeldLeases     []int64         `json:"held_leases"`
	LastVerdict    json.RawMessage `json:"last_verdict,omitempty"`
}

type Aggregator

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

func NewAggregator

func NewAggregator(scratch *Scratchpad) *Aggregator

func (*Aggregator) Aggregate

func (a *Aggregator) Aggregate(plan *Plan) *Result

type Artifact

type Artifact struct {
	Type string
	Data any
}

type Attack

type Attack struct {
	Kind        AttackKind
	Hypothesis  string
	ProbeSource string
	Landed      bool
	Output      string
}

type AttackKind

type AttackKind string
const (
	AttackBoundary    AttackKind = "boundary"
	AttackConcurrency AttackKind = "concurrency"
	AttackResource    AttackKind = "resource"
	AttackContract    AttackKind = "contract"
	AttackInjection   AttackKind = "injection"
)

type Attempt

type Attempt struct {
	Round    int
	Output   string
	Verdict  *Verdict
	Diagnose string
}

type BlameResult

type BlameResult struct {
	Culprit    *EditRecord
	Check      Check
	Bisections int
	PriorGreen int
}

func (*BlameResult) Diagnosis

func (b *BlameResult) Diagnosis() string

type Blamer

type Blamer struct {
	Verifier *Verifier
}

func (*Blamer) Blame

func (bl *Blamer) Blame(ctx context.Context, log *EditLog, failing Check) (*BlameResult, error)

type Calibrator

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

func NewCalibrator

func NewCalibrator(db *sql.DB) (*Calibrator, error)

func (*Calibrator) BrierScore

func (c *Calibrator) BrierScore(ctx context.Context, agent string) (float64, int, error)

func (*Calibrator) Calibrate

func (c *Calibrator) Calibrate(ctx context.Context, agent string, declared float64) (float64, error)

func (*Calibrator) Record

func (c *Calibrator) Record(ctx context.Context, claim ConfidenceClaim) error

type Candidate

type Candidate struct {
	ID       string
	Agent    Agent
	Worktree string
	Output   string
	Verdict  *Verdict
	Err      error
}

type Cartographer

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

func NewCartographer

func NewCartographer(repoRoot string) *Cartographer

func (*Cartographer) IndexAll

func (c *Cartographer) IndexAll(ctx context.Context) error

func (*Cartographer) Invalidate

func (c *Cartographer) Invalidate(files []string)

func (*Cartographer) SliceFor

func (c *Cartographer) SliceFor(imp *Impact, k int) []ContextItem

func (*Cartographer) SymbolCount

func (c *Cartographer) SymbolCount() int

type Chain

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

func NewChain

func NewChain(name string, stages ...Stage) (*Chain, error)

func (*Chain) Run

func (c *Chain) Run(ctx context.Context, in Artifact) (Artifact, *Trace)

type ChainTemplate

type ChainTemplate struct {
	ID            int64
	Class         TaskClass
	Sequence      []ToolCall
	Support       int
	SuccessRate   float64
	Status        string
	LiveTrials    int
	LiveSuccesses int
}

func (*ChainTemplate) Key

func (t *ChainTemplate) Key() string

type ChangedLine

type ChangedLine struct {
	File string
	Line int
	Text string
}

func ParseAddedLines

func ParseAddedLines(diff string) []ChangedLine

type Check

type Check struct {
	Kind         CheckKind
	Name         string
	Cmd          []string
	Timeout      time.Duration
	AllowedPaths []string
}

func DefaultGoChecks

func DefaultGoChecks() []Check

type CheckKind

type CheckKind string
const (
	CheckBuild     CheckKind = "build"
	CheckTest      CheckKind = "test"
	CheckLint      CheckKind = "lint"
	CheckPredicate CheckKind = "predicate"
	CheckDiffScope CheckKind = "diff-scope"
)

type CheckResult

type CheckResult struct {
	Check    Check
	Passed   bool
	Output   string
	Duration time.Duration
}

type Checkpoint

type Checkpoint struct {
	ID        int64
	Label     string
	TreeSHA   string
	State     AgentState
	Green     bool
	CreatedAt time.Time
}

type CompiledContext

type CompiledContext struct {
	Prompt   string
	Included []string
	Evicted  []string
	Used     int
	Budget   int
}

type ConfidenceClaim

type ConfidenceClaim struct {
	AgentName string
	TaskClass TaskClass
	Declared  float64
	Passed    bool
}

type Conflict

type Conflict struct {
	HeldBy  string
	TaskID  string
	Intent  string
	Overlap string
}

type ContextCompiler

type ContextCompiler struct {
	Budget   int
	KindCaps map[string]int
}

func NewContextCompiler

func NewContextCompiler(budget int) *ContextCompiler

func (*ContextCompiler) Compile

func (cc *ContextCompiler) Compile(items []ContextItem) (*CompiledContext, error)

type ContextItem

type ContextItem struct {
	Kind      string
	Name      string
	Body      string
	Relevance float64
	Pinned    bool
}

func GatherStandard

func GatherStandard(
	contract *Contract,
	diagnosis string,
	impact *Impact,
	episodes []*Episode,
	suggestions string,
	fileSlices map[string]string,
	fileScores map[string]float64,
) []ContextItem

type Contract

type Contract struct {
	TaskID             string
	AllowedGlobs       []string
	FrozenGlobs        []string
	ForbiddenPatterns  []ForbiddenPattern
	MaxFilesChanged    int
	MaxLinesChanged    int
	RequiredInvariants []Check
}

func CompileContract

func CompileContract(task *Task) *Contract

func (*Contract) AsChecks

func (c *Contract) AsChecks() []Check

func (*Contract) CheckDiffStats

func (c *Contract) CheckDiffStats(filesChanged, linesChanged int) []Violation

func (*Contract) CheckEdit

func (c *Contract) CheckEdit(path string, addedLines []string) []Violation

type Critic

type Critic struct {
	Verifier *Verifier
	Checks   []Check
	Policy   RepairPolicy
}

func NewCritic

func NewCritic(vf *Verifier, checks []Check) *Critic

func (*Critic) Drive

func (c *Critic) Drive(ctx context.Context, ag Agent, task *Task, scratch *Scratchpad) (*CriticResult, error)

type CriticResult

type CriticResult struct {
	Attempts []Attempt
	Final    *Verdict
	Passed   bool
}

type DagExecutor

type DagExecutor struct {
	Leases      *LeaseTable
	MaxParallel int
	AgentID     string
}

func NewDagExecutor

func NewDagExecutor(leases *LeaseTable, agentID string) *DagExecutor

func (*DagExecutor) Execute

func (d *DagExecutor) Execute(ctx context.Context, nodes []*PlanNode, run NodeRunner) (*DagResult, error)

type DagResult

type DagResult struct {
	Status map[string]NodeStatus
	Order  []string
}

func (*DagResult) Brief

func (r *DagResult) Brief() string

type Decision

type Decision string
const (
	DecisionAutoMerge   Decision = "auto-merge"
	DecisionGreenReview Decision = "green-needs-review"
	DecisionBlock       Decision = "block"
)

type Decl

type Decl struct {
	Key string
	Src string
	Pos int
}

type Dispatcher

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

func NewDispatcher

func NewDispatcher(registry *Registry, scratch *Scratchpad, maxParallel int) *Dispatcher

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, plan *Plan) error

type EditLog

type EditLog struct {
	TaskID  string
	Workdir string
	Base    string
	Edits   []EditRecord
}

type EditRecord

type EditRecord struct {
	Seq     int
	SHA     string
	Path    string
	Summary string
}

type EditRequest

type EditRequest struct {
	TaskID             string
	Edits              map[string][]byte
	DeclaredConfidence float64
}

type Episode

type Episode struct {
	ID        int64           `json:"id"`
	Intent    string          `json:"intent"`
	TaskTitle string          `json:"task_title"`
	PlanJSON  json.RawMessage `json:"plan"`
	Diff      string          `json:"diff,omitempty"`
	Score     float64         `json:"score"`
	Passed    bool            `json:"passed"`
	Rounds    int             `json:"rounds"`
	CreatedAt time.Time       `json:"created_at"`
}

type EpisodeStore

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

func NewEpisodeStore

func NewEpisodeStore(db *sql.DB) (*EpisodeStore, error)

func (*EpisodeStore) Record

func (s *EpisodeStore) Record(ctx context.Context, ep *Episode) error

func (*EpisodeStore) Similar

func (s *EpisodeStore) Similar(ctx context.Context, taskTitle string, k int) ([]*Episode, error)

type Escalation

type Escalation struct {
	FromRung string
	ToRung   string
	Reason   string
	Verdict  *Verdict
	At       time.Time
}

type ForbiddenPattern

type ForbiddenPattern struct {
	Name        string
	Pattern     *regexp.Regexp
	OnlyNewCode bool
}

func DefaultForbidden

func DefaultForbidden() []ForbiddenPattern

type FsTxn

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

func BeginTxn

func BeginTxn(workdir string) *FsTxn

func (*FsTxn) Commit

func (t *FsTxn) Commit() error

func (*FsTxn) DeleteFile

func (t *FsTxn) DeleteFile(relPath string) error

func (*FsTxn) Rollback

func (t *FsTxn) Rollback() error

func (*FsTxn) Touched

func (t *FsTxn) Touched() []string

func (*FsTxn) WriteFile

func (t *FsTxn) WriteFile(relPath string, content []byte) error

type FuncStage

type FuncStage struct {
	StageName string
	In, Out   string
	Fn        func(ctx context.Context, in Artifact) (Artifact, error)
}

func (*FuncStage) InType

func (f *FuncStage) InType() string

func (*FuncStage) Name

func (f *FuncStage) Name() string

func (*FuncStage) OutType

func (f *FuncStage) OutType() string

func (*FuncStage) Run

func (f *FuncStage) Run(ctx context.Context, in Artifact) (Artifact, error)

type Governor

type Governor struct {
	Ladder   []Rung
	Verifier *Verifier
	Checks   []Check
	RepoRoot string
	Factory  AgentFactory
	Router   *StrategyRouter
}

func (*Governor) Execute

func (g *Governor) Execute(ctx context.Context, task *Task, scratch *Scratchpad) (*GovernorResult, error)

type GovernorResult

type GovernorResult struct {
	Passed      bool
	FinalRung   string
	Verdict     *Verdict
	Escalations []Escalation
	TotalRounds int
}

type Impact

type Impact struct {
	ChangedPkgs      []string
	AffectedPkgs     []string
	AffectedTestPkgs []string
	Radius           float64
}

func (*Impact) RiskBrief

func (i *Impact) RiskBrief() string

type ImpactGraph

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

func BuildImpactGraph

func BuildImpactGraph(ctx context.Context, repoRoot string) (*ImpactGraph, error)

func (*ImpactGraph) Predict

func (g *ImpactGraph) Predict(changedFiles []string) *Impact

type Intent

type Intent string
const (
	IntentCodebase     Intent = "codebase_change"
	IntentTest         Intent = "test_work"
	IntentReview       Intent = "code_review"
	IntentDocs         Intent = "documentation"
	IntentSecurity     Intent = "security_audit"
	IntentArchitecture Intent = "architecture"
	IntentGeneral      Intent = "general_query"
)

type Kernel

type Kernel struct {
	Workdir string
	// contains filtered or unexported fields
}

func NewKernel

func NewKernel(db *sql.DB, workdir string) (*Kernel, error)

func (*Kernel) Capture

func (k *Kernel) Capture(ctx context.Context, label string, state AgentState, green bool) (*Checkpoint, error)

func (*Kernel) LastGreen

func (k *Kernel) LastGreen(ctx context.Context) (int64, string, error)

func (*Kernel) Rewind

func (k *Kernel) Rewind(ctx context.Context, checkpointID int64) (*AgentState, error)

func (*Kernel) Timeline

func (k *Kernel) Timeline(ctx context.Context, limit int) (string, error)

type LLMAgent

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

func NewLLMAgent

func NewLLMAgent(cfg AgentConfig) *LLMAgent

func NewLLMAgentWithClient

func NewLLMAgentWithClient(cfg AgentConfig, client *llm.Client) *LLMAgent

func (*LLMAgent) Config

func (a *LLMAgent) Config() AgentConfig

func (*LLMAgent) Name

func (a *LLMAgent) Name() string

func (*LLMAgent) Run

func (a *LLMAgent) Run(ctx context.Context, task *Task, scratch *Scratchpad) (string, error)

type Lease

type Lease struct {
	ID        int64
	AgentID   string
	TaskID    string
	Globs     []string
	Intent    string
	ExpiresAt time.Time
}

type LeaseTable

type LeaseTable struct {
	DefaultTTL time.Duration
	// contains filtered or unexported fields
}

func NewLeaseTable

func NewLeaseTable() *LeaseTable

func (*LeaseTable) Acquire

func (lt *LeaseTable) Acquire(agentID, taskID, intent string, globs []string) (*Lease, []Conflict, error)

func (*LeaseTable) Board

func (lt *LeaseTable) Board() string

func (*LeaseTable) Count

func (lt *LeaseTable) Count() int

func (*LeaseTable) Release

func (lt *LeaseTable) Release(id int64, agentID string) error

func (*LeaseTable) Renew

func (lt *LeaseTable) Renew(id int64, agentID string) error

type MacroResult

type MacroResult struct {
	Applied       bool
	Verdict       *Verdict
	Trace         *Trace
	Decision      Decision
	ResumeContext string
}

type Macros

type Macros struct {
	Workdir  string
	Contract *Contract
	Targeted *TargetedVerifier
	Probe    func(testCmd []string) *MutationProbe
	Calib    *Calibrator
	Policy   MergePolicy
	Agent    string
	Class    TaskClass
}

func (*Macros) SinChange

func (m *Macros) SinChange(ctx context.Context, req EditRequest) (*MacroResult, error)

func (*Macros) SinRefactor

func (m *Macros) SinRefactor(ctx context.Context, req EditRequest) (*MacroResult, error)

type MergePolicy

type MergePolicy struct {
	AutoMergeThreshold float64
	ReviewThreshold    float64
}

func DefaultMergePolicy

func DefaultMergePolicy() MergePolicy

func (MergePolicy) Decide

func (p MergePolicy) Decide(verified bool, calibrated float64) Decision

type MergeResult

type MergeResult struct {
	Merged     []byte
	Conflicts  []SemConflict
	AutoMerged int
}

func SemanticMergeGo

func SemanticMergeGo(base, a, b []byte) (*MergeResult, error)

func (*MergeResult) ConflictBrief

func (r *MergeResult) ConflictBrief() string

type Miner

type Miner struct {
	MinSupport     int
	MinSuccessRate float64
	MinLength      int
	MaxLength      int
	// contains filtered or unexported fields
}

func NewMiner

func NewMiner(db *sql.DB) (*Miner, error)

func (*Miner) Mine

func (m *Miner) Mine(ctx context.Context, class TaskClass) ([]*ChainTemplate, error)

func (*Miner) RecordSequence

func (m *Miner) RecordSequence(ctx context.Context, ep SeqEpisode) error

func (*Miner) ReportLive

func (m *Miner) ReportLive(ctx context.Context, templateID int64, success bool) error

func (*Miner) SuggestionsFor

func (m *Miner) SuggestionsFor(ctx context.Context, class TaskClass) (string, error)

type MockAgent

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

func NewMockAgent

func NewMockAgent(cfg AgentConfig) *MockAgent

func (*MockAgent) Config

func (m *MockAgent) Config() AgentConfig

func (*MockAgent) Name

func (m *MockAgent) Name() string

func (*MockAgent) Run

func (m *MockAgent) Run(ctx context.Context, task *Task, scratch *Scratchpad) (string, error)

type Mutation

type Mutation struct {
	File   string
	Line   int
	Before string
	After  string
	Rule   string
	Killed bool
}

type MutationProbe

type MutationProbe struct {
	Workdir      string
	TestCmd      []string
	MaxMutations int
}

func NewMutationProbe

func NewMutationProbe(workdir string, testCmd []string) *MutationProbe

func (*MutationProbe) Run

func (mp *MutationProbe) Run(ctx context.Context, lines []ChangedLine) (*ProbeResult, error)

type NIMAgent

type NIMAgent = LLMAgent

Backwards-compat alias.

func NewNIMAgent

func NewNIMAgent(cfg AgentConfig) *NIMAgent

func NewNIMAgentWithClient

func NewNIMAgentWithClient(cfg AgentConfig, client *llm.Client) *NIMAgent

type NodeRunner

type NodeRunner func(ctx context.Context, node *PlanNode) error

type NodeStatus

type NodeStatus string
const (
	NodePending NodeStatus = "pending"
	NodeRunning NodeStatus = "running"
	NodeGreen   NodeStatus = "green"
	NodeRed     NodeStatus = "red"
	NodeSkipped NodeStatus = "skipped"
)

type Orchestrator

type Orchestrator struct {
	Registry    *Registry
	Planner     *Planner
	Dispatcher  *Dispatcher
	Aggregator  *Aggregator
	Scratchpad  *Scratchpad
	MaxParallel int
}

func New

func New() *Orchestrator

func NewWithAgents

func NewWithAgents(extraConfigs []AgentConfig) *Orchestrator

func (*Orchestrator) Plan

func (o *Orchestrator) Plan(prompt string) *Plan

func (*Orchestrator) Run

func (o *Orchestrator) Run(ctx context.Context, prompt string, opts ...RunOption) (*Result, error)

func (*Orchestrator) String

func (o *Orchestrator) String() string

type PkgNode

type PkgNode struct {
	ImportPath string
	Dir        string
	GoFiles    []string
	TestFiles  []string
	Imports    []string
}

type Plan

type Plan struct {
	ID         string    `json:"id"`
	Prompt     string    `json:"prompt"`
	Intent     Intent    `json:"intent"`
	Tasks      []*Task   `json:"tasks"`
	Created    time.Time `json:"created"`
	Started    time.Time `json:"started"`
	Completed  time.Time `json:"completed"`
	TotalCost  float64   `json:"total_cost"`
	TokensUsed int       `json:"tokens_used"`
	Success    bool      `json:"success"`
}

type PlanNode

type PlanNode struct {
	Task      *Task
	DependsOn []string
	PathGlobs []string
}

type Planner

type Planner struct {
	Router *Router
	Agents []AgentConfig
}

func NewPlanner

func NewPlanner(agents []AgentConfig) *Planner

func (*Planner) BuildPlan

func (p *Planner) BuildPlan(prompt string) *Plan

type ProbeResult

type ProbeResult struct {
	Mutations          []Mutation
	Killed             int
	Survived           int
	ObservabilityScore float64
}

func (*ProbeResult) Diagnosis

func (p *ProbeResult) Diagnosis() string

type Registry

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

func NewRegistry

func NewRegistry(agents []Agent) *Registry

func NewRegistryWithDefaults

func NewRegistryWithDefaults(extraConfigs []AgentConfig) *Registry

func (*Registry) ForType

func (r *Registry) ForType(tt TaskType) (Agent, bool)

func (*Registry) Get

func (r *Registry) Get(name string) (Agent, bool)

func (*Registry) List

func (r *Registry) List() []AgentConfig

func (*Registry) Register

func (r *Registry) Register(a Agent)

type RepairPolicy

type RepairPolicy struct {
	MaxAttempts    int
	MinImprovement float64
}

func DefaultRepairPolicy

func DefaultRepairPolicy() RepairPolicy

type Result

type Result struct {
	Plan        *Plan
	Sections    map[string]string
	TotalTasks  int
	OKTasks     int
	FailedTasks int
	Summary     string
}

type Router

type Router struct {
	Keywords map[Intent][]string
}

func NewRouter

func NewRouter() *Router

func (*Router) Classify

func (r *Router) Classify(prompt string) Intent

func (*Router) SubIntents

func (r *Router) SubIntents(prompt string) []Intent

type RunOption

type RunOption func(*runConfig)

func WithMaxParallel

func WithMaxParallel(n int) RunOption

func WithTimeout

func WithTimeout(d time.Duration) RunOption

type Rung

type Rung struct {
	Name         string
	Agents       int
	RepairRounds int
	Timeout      time.Duration
}

func DefaultLadder

func DefaultLadder() []Rung

type Scratchpad

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

func NewScratchpad

func NewScratchpad() *Scratchpad

func (*Scratchpad) Merge

func (s *Scratchpad) Merge(other *Scratchpad)

func (*Scratchpad) Read

func (s *Scratchpad) Read(section string) (string, bool)

func (*Scratchpad) ReadAll

func (s *Scratchpad) ReadAll() map[string]*ScratchpadEntry

func (*Scratchpad) Write

func (s *Scratchpad) Write(agent, section, content string)

type ScratchpadEntry

type ScratchpadEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Agent     string    `json:"agent"`
	Section   string    `json:"section"`
	Content   string    `json:"content"`
	Version   int       `json:"version"`
}

type SemConflict

type SemConflict struct {
	Key        string
	Base, A, B string
}

type SeqEpisode

type SeqEpisode struct {
	EpisodeID int64
	Class     TaskClass
	Sequence  []ToolCall
	Passed    bool
}

type SpecResult

type SpecResult struct {
	Winner     *Candidate
	Candidates []*Candidate
}

type SpeculativeRunner

type SpeculativeRunner struct {
	RepoRoot    string
	Checks      []Check
	MaxParallel int
	KeepLosers  bool
	WorkdirBase string // optional override (defaults to os.TempDir()/sin-spec)
}

func NewSpeculativeRunner

func NewSpeculativeRunner(repoRoot string, checks []Check) *SpeculativeRunner

func (*SpeculativeRunner) MergeWinner

func (s *SpeculativeRunner) MergeWinner(ctx context.Context, winner *Candidate) (string, error)

func (*SpeculativeRunner) Run

func (s *SpeculativeRunner) Run(ctx context.Context, task *Task, agents []Agent, scratch *Scratchpad) (*SpecResult, error)

type Stage

type Stage interface {
	Name() string
	InType() string
	OutType() string
	Run(ctx context.Context, in Artifact) (Artifact, error)
}

func Guard

func Guard(inner Stage, check func(Artifact) error) Stage

func Parallel

func Parallel(name, outType string, merge func([]Artifact) (Artifact, error), branches ...Stage) Stage

type StageResult

type StageResult struct {
	Stage    string
	Duration time.Duration
	Output   Artifact
	Err      error
}

type Strategy

type Strategy string
const (
	StratASTEdit  Strategy = "ast-edit"
	StratHashline Strategy = "hashline-patch"
	StratRewrite  Strategy = "full-rewrite"
	StratShellGen Strategy = "shell-codegen"
)

type StrategyRouter

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

func NewStrategyRouter

func NewStrategyRouter(db *sql.DB, seed int64) (*StrategyRouter, error)

func (*StrategyRouter) Pick

func (r *StrategyRouter) Pick(class TaskClass, candidates []Strategy) Strategy

func (*StrategyRouter) Posterior

func (r *StrategyRouter) Posterior(class TaskClass, s Strategy) (mean float64, n int)

func (*StrategyRouter) Report

func (r *StrategyRouter) Report(ctx context.Context, class TaskClass, s Strategy, success bool) error

type Symbol

type Symbol struct {
	Key       string
	File      string
	Line      int
	Kind      string
	Signature string
	Rank      float64
}

type TargetedVerifier

type TargetedVerifier struct {
	Inner *Verifier
	Graph *ImpactGraph
}

func NewTargetedVerifier

func NewTargetedVerifier(inner *Verifier, graph *ImpactGraph) *TargetedVerifier

func (*TargetedVerifier) FastChecks

func (tv *TargetedVerifier) FastChecks(changedFiles []string) []Check

func (*TargetedVerifier) FinalChecks

func (tv *TargetedVerifier) FinalChecks() []Check

func (*TargetedVerifier) Speedup

func (tv *TargetedVerifier) Speedup(changedFiles []string) string

func (*TargetedVerifier) VerifyStaged

func (tv *TargetedVerifier) VerifyStaged(ctx context.Context, taskID, candidate string, changedFiles []string) *Verdict

type Task

type Task struct {
	ID          string     `json:"id"`
	Type        TaskType   `json:"type"`
	Title       string     `json:"title,omitempty"`
	Description string     `json:"description"`
	AgentName   string     `json:"agent"`
	DependsOn   []string   `json:"depends_on,omitempty"`
	Status      TaskStatus `json:"status"`
	Result      string     `json:"result,omitempty"`
	Error       string     `json:"error,omitempty"`
	Created     time.Time  `json:"created"`
	Started     *time.Time `json:"started,omitempty"`
	Completed   *time.Time `json:"completed,omitempty"`
	TokensUsed  int        `json:"tokens_used"`
	Cost        float64    `json:"cost"`
}

type TaskClass

type TaskClass string
const (
	ClassRename     TaskClass = "rename"
	ClassRefactor   TaskClass = "refactor"
	ClassBugfix     TaskClass = "bugfix"
	ClassGreenfield TaskClass = "greenfield"
	ClassConfig     TaskClass = "config"
	ClassUnknown    TaskClass = "unknown"
)

func ClassifyTask

func ClassifyTask(task *Task) TaskClass

type TaskStatus

type TaskStatus string
const (
	TaskPending   TaskStatus = "pending"
	TaskRunning   TaskStatus = "running"
	TaskCompleted TaskStatus = "completed"
	TaskFailed    TaskStatus = "failed"
	TaskCancelled TaskStatus = "cancelled"
	TaskBlocked   TaskStatus = "blocked"
)

type TaskType

type TaskType string
const (
	TaskCode      TaskType = "code"
	TaskTest      TaskType = "test"
	TaskReview    TaskType = "review"
	TaskDocs      TaskType = "docs"
	TaskSecurity  TaskType = "security"
	TaskArchitect TaskType = "architect"
	TaskGeneral   TaskType = "general"
)

type ToolCall

type ToolCall struct {
	Tool     string `json:"tool"`
	ArgShape string `json:"arg_shape"`
}

type Trace

type Trace struct {
	Chain    string
	Results  []StageResult
	Halted   bool
	HaltedAt string
}

func (*Trace) Diagnosis

func (t *Trace) Diagnosis() string

type Verdict

type Verdict struct {
	TaskID    string
	Candidate string
	Results   []CheckResult
	Score     float64
	Passed    bool
	CreatedAt time.Time
}

func BestVerdict

func BestVerdict(verdicts []*Verdict) *Verdict

func (*Verdict) Diagnosis

func (v *Verdict) Diagnosis() string

type Verifier

type Verifier struct {
	Workdir        string
	MandatoryKinds []CheckKind
}

func NewVerifier

func NewVerifier(workdir string) *Verifier

func (*Verifier) Verify

func (vf *Verifier) Verify(ctx context.Context, taskID, candidate string, checks []Check) *Verdict

type Violation

type Violation struct {
	Kind   string
	Path   string
	Line   int
	Detail string
}

func (Violation) String

func (v Violation) String() string

Jump to

Keyboard shortcuts

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