{"modulePath":"github.com/TMHSDigital/spackle","version":"v0.2.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package agent\n\nPackage agent holds the model-driven stages of the pipeline: planner, investigators, reviewer and the shared tool loop they run on.\n\nThe loop gives a model nothing but an allowlisted, read-only tool registry. Scope, budgets and tool permissions are enforced here in Go. Nothing a model or a target says can change them, because there is no tool whose effect is to change them.\n\n## Constants\n\n```go\nconst (\n\tStopNone       = \"\"\n\tStopTurns      = \"turn limit\"\n\tStopStagnation = \"stagnation\"\n\tStopRefusal    = \"provider refusal\"\n\tStopTruncated  = \"output truncated\"\n)\n```\nWhy a conversation stopped before the model chose to.\n\n```go\nconst (\n\tReviewConfirmed = \"confirmed\"\n\tReviewRefuted   = \"refuted\"\n\tReviewUncertain = \"uncertain\"\n)\n```\nReview verdicts.\n\n## Functions\n\n```go\nfunc ApplyReview(f finding.Finding, rev Review) finding.Finding\n```\nApplyReview returns the finding updated with the review's outcome.\n\n  - confirmed: unchanged, apart from a corrected severity.\n  - refuted: dismissed, with the reviewer's reason kept.\n  - uncertain: kept open, but confidence drops to plausible, because a second reader could not verify it.\n\n```go\nfunc BuildFinding(root string, d Draft, origin []string) (finding.Finding, error)\n```\nBuildFinding validates a draft against the target and converts it. It returns an error describing every problem, so a rejected draft can be sent back to the model once with specific corrections.\n\nWhat is checked: the class is known; the file exists inside the target; the line range is inside the file; every quoted line really appears in the file it cites (line numbers are corrected when the quote is found elsewhere in the same file); and the CVSS vector is valid. The score and label are computed here, never taken from the model.\n\n```go\nfunc CheckProofCommand(language string, cmd []string) error\n```\nCheckProofCommand checks the command of a proof: 1 to 16 arguments, the first a program the language table allows, with no control characters. There is no shell: a proof is one program run with an argument vector.\n\n```go\nfunc CheckProofFile(name string) (string, error)\n```\nCheckProofFile checks the name of one proof file and returns it cleaned: a relative path inside spackle\\_poc/, or a file named spackle\\_poc\\_test.go. A stored proof is held to it again before spackle verify runs it.\n\n```go\nfunc Correlate(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, fs []finding.Finding) ([]finding.Finding, error)\n```\nCorrelate asks the model which confirmed findings combine into a larger attack and returns the findings with their kill chain and related ids filled in. Chains that name unknown ids are ignored. A failure here is not fatal: the findings are returned unchanged with the error.\n\n```go\nfunc InconclusiveWhy(res sandbox.Result) string\n```\nInconclusiveWhy says, for a sentence, why a proof run was inconclusive: \"the proof \\\u003cwhy\u003e\".\n\n```go\nfunc NewMarker() (string, error)\n```\nNewMarker returns the random token a proof must print to count as a demonstration. It is unguessable so that a proof cannot \"succeed\" by accident, for example by echoing a file that happens to contain it.\n\n## Types\n\n```go\ntype Box struct {\n\tRuntime sandbox.Runtime\n\tProfile sandbox.Profile\n\tBudget  *budget.Budget\n\tRoot    string\n\t// Record is called after every sandbox run so the engine can write the\n\t// ledger event and the evidence file.\n\tRecord func(purpose string, spec sandbox.Spec, res sandbox.Result) error\n}\n```\nBox runs things in the sandbox and accounts for them. The engine supplies it; it is the only way the prover and fixer can execute anything.\n\n```go\nfunc (b *Box) Exec(ctx context.Context, purpose, image string, cmd []string, files map[string]string, sourceDir string) (sandbox.Result, error)\n```\nExec executes one command against a copy of sourceDir (the target when it is \"\") plus extra files. It is the one way to start a sandbox run: it counts the run against the sandbox cap, bounds it by the wall time that is left, and records it. A run stopped by the wall time cap returns an error wrapping budget.ErrExhausted.\n\n```go\ntype Check func(ctx context.Context, files map[string]string) (problem string, verification string, verified bool, err error)\n```\nCheck verifies one candidate fix. A non-empty problem rejects the fix and is sent back to the model. With an empty problem the fix is kept, and verified says whether it is proven or only offered.\n\n```go\ntype Diagnosis struct {\n\tTitle, RootCause string\n\t// File and Line name the faulty code. File is empty when the model named\n\t// a file that is not in the target.\n\tFile string\n\tLine int\n\t// Quotes are the evidence lines that really appear in the files they\n\t// cite, with corrected line numbers. Quotes that do not match are gone.\n\tQuotes          []DraftStep\n\tFixSummary, Why string\n\t// Files maps a target-relative path to its complete new content.\n\tFiles map[string]string\n\t// Patch is the unified diff Spackle computed from Files.\n\tPatch        string\n\tVerified     bool\n\tVerification string\n\tAttempts     int\n\t// Reason explains why there is no root cause or no accepted fix.\n\tReason string\n}\n```\nDiagnosis is the outcome of looking for a root cause and a fix.\n\n```go\nfunc Diagnose(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry,\n\troot string, failure string, wantFix bool, maxAttempts int, check Check) (Diagnosis, error)\n```\nDiagnose asks the model for the root cause and a fix, calls check to verify each candidate patch, and feeds a rejected attempt's problem back, up to maxAttempts times. When wantFix is false it asks only for the root cause. The failure text is untrusted and reaches the model only inside an envelope. A fix that check rejected is never returned.\n\n```go\ntype Draft struct {\n\tTitle             string      `json:\"title\"`\n\tClass             string      `json:\"class\"`\n\tCWE               []string    `json:\"cwe\"`\n\tFile              string      `json:\"file\"`\n\tStartLine         int         `json:\"start_line\"`\n\tEndLine           int         `json:\"end_line\"`\n\tSymbol            string      `json:\"symbol\"`\n\tVector            string      `json:\"cvss_vector\"`\n\tSeverityReasoning string      `json:\"severity_reasoning\"`\n\tDescription       string      `json:\"description\"`\n\tFlow              []DraftStep `json:\"flow\"`\n\tPreconditions     []string    `json:\"preconditions\"`\n\tAttackSteps       []string    `json:\"attack_steps\"`\n\tChainsInto        []string    `json:\"chains_into\"`\n\tGains             []string    `json:\"gains\"`\n\tExposed           []string    `json:\"exposed\"`\n\tFixSummary        string      `json:\"fix_summary\"`\n\tFixWhy            string      `json:\"fix_why\"`\n\tDefenseInDepth    []string    `json:\"defense_in_depth\"`\n\tConfidence        string      `json:\"confidence\"`\n\tConfidenceReason  string      `json:\"confidence_reason\"`\n}\n```\nDraft is a finding as a model proposes it. Nothing in a draft is trusted: BuildFinding checks every claim it can against the target before the draft becomes a finding.\n\n```go\ntype DraftStep struct {\n\tRole  string `json:\"role\"`\n\tFile  string `json:\"file\"`\n\tLine  int    `json:\"line\"`\n\tQuote string `json:\"quote\"`\n\tNote  string `json:\"note\"`\n}\n```\nDraftStep is one flow step in a draft.\n\n```go\ntype EndpointReview struct {\n\t// Confirmed is false when the investigator concluded the observation is\n\t// not a real flaw; Reason then says why.\n\tConfirmed bool\n\tReason    string\n\tFinding   finding.Finding\n\t// Rejected is set when the answer could not be used. The finding is\n\t// then left as the probe reported it.\n\tRejected string\n}\n```\nEndpointReview is an investigator's assessment of one running-target finding.\n\n```go\nfunc InvestigateEndpoint(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry, f finding.Finding, exchanges string, known func(id string) bool) (EndpointReview, error)\n```\nInvestigateEndpoint asks the model to confirm and explain one running-target finding. exchanges are the recorded request and response pairs that produced it, already redacted, as text. known reports whether an exchange id exists, so the model cannot cite evidence that was never recorded.\n\n```go\ntype FixInput struct {\n\tLanguage string\n\tImage    string\n\t// PoC is the proof that demonstrated the finding, or nil.\n\tPoC *PoC\n\t// TestCmd is the project's test command as an argument vector, or nil.\n\tTestCmd []string\n\t// BaselineTestsPass says whether TestCmd passed on the unmodified code.\n\t// A patch is only held to the suite when the suite was green to begin\n\t// with: a suite that already fails cannot tell a regression from noise.\n\tBaselineTestsPass bool\n\tMaxAttempts       int\n}\n```\nFixInput is what the fixer needs besides the finding.\n\n```go\ntype FixResult struct {\n\t// Files maps a target-relative path to its full new content.\n\tFiles map[string]string\n\t// Patch is the unified diff Spackle computed from Files.\n\tPatch string\n\tWhy   string\n\t// Verified is true only when a proof of concept that used to succeed no\n\t// longer does, and nothing that was checked got worse.\n\tVerified bool\n\t// Verification says, in a sentence, exactly what was and was not checked.\n\tVerification string\n\tAttempts     int\n\t// Reason explains a failure to produce any acceptable patch.\n\tReason string\n}\n```\nFixResult is the outcome of trying to fix a finding.\n\n```go\nfunc Fix(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry, box *Box, in FixInput, f finding.Finding) (FixResult, error)\n```\nFix asks the model for a patch and verifies it in the sandbox, up to MaxAttempts times. Each rejected attempt is sent back with the reason. A patch that fails verification is never returned.\n\n```go\ntype Intent = ledger.Intent\n```\nIntent is one planned investigation.\n\n```go\nfunc FallbackPlan(m mapper.Map, leads []seed.Lead, limit int) []Intent\n```\nFallbackPlan builds intents straight from leads, one per file and class, worst severity first. It is used when the planner fails or returns nothing usable, so a model problem degrades the run instead of ending it.\n\n```go\nfunc Plan(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, m mapper.Map, leads []seed.Lead, limit int) ([]Intent, error)\n```\nPlan asks the model for a prioritized list of investigations. Whatever the model returns is validated against the real map and leads: intents that name files or leads that do not exist lose those references, and intents left with nothing to look at are dropped.\n\n```go\nfunc ResumePlan(left []Intent, m mapper.Map, leads []seed.Lead, limit int) []Intent\n```\nResumePlan returns the plan of a resumed run: the investigations an earlier run planned and did not reach. They are checked against the current map and leads like any other plan, so a file or a lead that is gone since then drops out.\n\n```go\ntype Investigation struct {\n\tIntent Intent\n\t// Finding is set when the investigator reported a flaw that passed\n\t// validation.\n\tFinding *finding.Finding\n\t// NoFinding is the investigator's reason when it concluded the lead\n\t// does not hold up.\n\tNoFinding string\n\t// Rejected is why the result could not be used: malformed output, a\n\t// quote that is not in the file, a refusal, a cut-off answer.\n\tRejected string\n}\n```\nInvestigation is the result of investigating one intent.\n\n```go\nfunc Investigate(ctx context.Context, r *Runner, parent int64, root string, sealer *envelope.Sealer, reg *tools.Registry, intent Intent, leads []seed.Lead) (Investigation, error)\n```\nInvestigate runs one investigation. A draft that fails validation is sent back once with the specific problems; if the second answer also fails, the investigation is rejected and recorded, and the run continues.\n\n```go\ntype Outcome struct {\n\tText    string\n\tTurns   int\n\tStopped string\n\t// Note explains Stopped when there is more to say (a refusal category).\n\tNote string\n}\n```\nOutcome is the result of one conversation.\n\n```go\ntype PoC struct {\n\tFiles       map[string]string `json:\"files\"`\n\tCommand     []string          `json:\"command\"`\n\tMarker      string            `json:\"marker\"`\n\tLanguage    string            `json:\"language\"`\n\tImage       string            `json:\"image\"`\n\tExplanation string            `json:\"explanation,omitempty\"`\n}\n```\nPoC is a proof of concept: files added to a copy of the target and the command that runs them inside the sandbox.\n\n```go\nfunc (p *PoC) SortedFiles() []string\n```\nSortedFiles returns the proof's file names in a stable order.\n\n```go\ntype ProofOutcome int\n```\nProofOutcome is what one run of a proof of concept showed.\n\n```go\nconst (\n\t// ProofNotShown means the proof ran to an end and did not print its\n\t// marker: the flaw's effect was not observed.\n\tProofNotShown ProofOutcome = iota\n\t// ProofSucceeded means the proof printed its marker and exited with\n\t// code 0: the flaw's effect was observed.\n\tProofSucceeded\n\t// ProofInconclusive means the run shows neither: the proof timed out,\n\t// was killed, or printed its marker and then failed. A caller must not\n\t// read it as \"demonstrated\" and must not read it as \"fixed\".\n\tProofInconclusive\n)\n```\n\n```go\nfunc JudgeProof(res sandbox.Result, marker string) ProofOutcome\n```\nJudgeProof decides what one run of a proof showed. It is the one rule for the prover, the debugger's reproduction, the fixer's check of a patch and spackle verify, so \"demonstrated\" and \"fixed\" mean the same everywhere.\n\n```go\ntype ProofResult struct {\n\tPoC          *PoC\n\tDemonstrated bool\n\tOutput       string // redacted, clipped\n\tIsolation    string\n\tReason       string // why it was not demonstrated\n\tAttempts     int\n}\n```\nProofResult is the outcome of trying to demonstrate a finding.\n\n```go\nfunc Prove(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry, box *Box, language, image string, f finding.Finding) (ProofResult, error)\n```\nProve asks the model for a proof of concept and runs it in the sandbox. A proof that fails is sent back once with its output. The finding counts as demonstrated only when the run exits 0 and prints the marker.\n\n```go\nfunc Reproduce(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry,\n\tbox *Box, language, image, issue string) (ProofResult, error)\n```\nReproduce asks the model for a script that reproduces the issue. Same file and command rules as proofs (validatePoC); the script prints the marker only when the buggy behavior is observed. The issue counts as reproduced only when the run exits 0 and prints the marker. A script that fails is sent back once with its output.\n\n```go\ntype Review struct {\n\tVerdict string\n\tReason  string\n\t// Severity is set when the reviewer supplied a valid corrected vector.\n\tSeverity *finding.Severity\n}\n```\nReview is the reviewer's verdict on one finding.\n\n```go\nfunc ReviewFinding(ctx context.Context, r *Runner, parent int64, sealer *envelope.Sealer, reg *tools.Registry, f finding.Finding) (Review, error)\n```\nReviewFinding runs the adversarial review of one finding in a fresh conversation with its own tool registry.\n\n```go\ntype Runner struct {\n\tProvider llm.Provider\n\tPricer   llm.Pricer\n\tBudget   *budget.Budget\n\tLedger   *ledger.Writer\n\t// Stage names the pipeline stage in the ledger: planner, investigator,\n\t// reviewer, prover, fixer or mechanical.\n\tStage string\n\t// MaxTurns caps tool-use turns in one conversation.\n\tMaxTurns int\n\t// MaxTokens caps one completion.\n\tMaxTokens int\n}\n```\nRunner runs one stage's conversations against a provider.\n\n```go\nfunc (r *Runner) Run(ctx context.Context, parent int64, system, user string, reg *tools.Registry) (Outcome, error)\n```\nRun holds a conversation: it sends system and user, executes any tool calls through reg, and returns the model's final text. reg may be nil for a conversation with no tools. A budget error is returned as an error wrapping budget.ErrExhausted, with whatever was produced so far.\n\n","path":"github.com/TMHSDigital/spackle/internal/agent","name":"agent","synopsis":"Package agent holds the model-driven stages of the pipeline: planner, investigators, reviewer and the shared tool loop they run on.","isRedistributable":true}
