Documentation
¶
Index ¶
- Constants
- func BranchTopology(w io.Writer, branches []git.Branch, opts GraphOptions) error
- func BuildCopyPayload(findings []Finding) string
- func Cards(w io.Writer, p Payload) error
- func CopyText(f Finding) string
- func CountFiles(findings []Finding) int
- func Fingerprint(file, ruleID, symbol string) string
- func FooterLine(m Meta, findings []Finding) string
- func Graph(w io.Writer, rows []GraphRow, opts GraphOptions) error
- func HeaderLine(m Meta) string
- func JSON(w io.Writer, p Payload) error
- func Markdown(w io.Writer, p Payload) error
- func RelativeAge(t, now time.Time) string
- func SARIF(w io.Writer, p Payload) error
- func SARIFWithCategory(w io.Writer, findings []Finding, category string, extraProps []map[string]any) error
- func StatusLine(m Meta) string
- func TemplateFuncs() template.FuncMap
- func Terminal(w io.Writer, p Payload) error
- func ValidateOutputTemplate(content string) error
- func VerboseFooter(m Meta) string
- type Finding
- type Format
- type GraphOptions
- type GraphRow
- type Meta
- type ParseError
- type ParseErrorKind
- type Payload
- type RemotePR
- type RemoteReport
- type RemoteReview
- type RemoteSync
- type RemoteWarning
- type Severity
- type SeverityGroup
- type Summary
- type TemplateData
Constants ¶
const ( RemoteStatusSubmitted = "submitted" RemoteStatusNoNewCommits = "no_new_commits" RemoteStatusDegraded = "degraded" RemoteStatusTooVolatile = "too_volatile" RemoteStatusFailed = "failed" RemoteModeFull = "full" RemoteModeIncremental = "incremental" RemoteModeNone = "none" RemoteSyncSynced = "synced" RemoteSyncPostOnly = "post_only" RemoteSyncSkipped = "skipped" )
Remote report enum values (ADR-0048 §2, §3).
const ( // SARIFCategoryReview is the review and diff category (the default). SARIFCategoryReview = sarifCategory // SARIFCategoryGuard is the `commitbrief guard` category. SARIFCategoryGuard = "commitbrief/guard/" // SARIFCategoryLeaks is the `commitbrief leaks` category. SARIFCategoryLeaks = "commitbrief/leaks/" )
Code Scanning categories (runs[0].automationDetails.id) per command. Each command owns its own category so that uploading one never closes the alerts of another: Code Scanning treats a missing result as fixed within a category.
const SchemaVersion = 1
SchemaVersion is the integer in the "schema" field of every JSON document we emit. Consumers should refuse to parse if SchemaVersion is higher than what they expect.
Versioning policy (see docs/json-schema.md):
- v1 (current): top-level shape locked at {schema, content, findings, summary, meta}. `findings` is populated from the parsed LLM response under ADR-0014. `summary` and `content` remain in the schema for backwards compatibility:
- `content` is populated only on graceful degrade (LLM produced unparseable output); empty on the happy path.
- `summary` is reserved for a future LLM-authored prose summary; v1 always emits it as `{}`.
- Additive changes (new optional fields in `meta`, new keys in `summary`, new fields on a Finding) are NOT a version bump. Consumers MUST ignore unknown fields.
- Renaming, removing, or changing the type of any documented field IS a breaking change and requires bumping SchemaVersion to 2.
Variables ¶
This section is empty.
Functions ¶
func BranchTopology ¶ added in v1.15.0
BranchTopology writes the `--branches` view: one row per branch with its ahead/behind position relative to the base.
func BuildCopyPayload ¶ added in v0.9.0
BuildCopyPayload joins per-finding CopyText blocks with a markdown horizontal-rule separator (`\n---\n\n`). Order is preserved from the input slice — callers that want severity-ordered output should sort beforehand (GroupBySeverity / severityOrder).
Returns "" for an empty slice; callers should branch on the empty case and skip the clipboard call entirely so the user doesn't get a hint line about copying zero findings.
func Cards ¶ added in v0.6.0
Cards is the rich terminal renderer that frames the review with a styled header, a pre-body status line, one bordered panel per finding (severity- colored), and a one-line summary footer. It is the default Format when stdout is a TTY and neither --markdown nor --json is set.
Under ADR-0014 the LLM emits a JSON document parsed into Payload.Findings before render. If Findings is nil (graceful degrade — parse failed) the renderer falls back to a Stage A glamour-rendered body of Payload.Content so the user still sees something rather than a stack trace. Color resolution is delegated to lipgloss; NO_COLOR=1 and non-TTY stdout both downgrade automatically.
func CopyText ¶ added in v0.9.0
CopyText returns a plain-text representation of f suitable for pasting into chat, an issue tracker, or a code editor. Format:
[💥 CRITICAL] internal/auth/session.go:142 SQL fragment built from request input String concatenation feeds db.Query directly — bypasses the prepared statement path used elsewhere in this package. → Switch to a prepared statement with bound parameters here so user input never reaches the SQL string concatenation path.
The diff snippet is deliberately omitted — chat clients tend to mangle multi-line code blocks, and the path:line already gives the recipient enough to jump straight to the source. The description and suggestion are each flattened to a single paragraph (collapse internal whitespace) so they survive Slack/Discord rendering.
func CountFiles ¶ added in v0.6.0
CountFiles returns the number of distinct files referenced across the given findings.
func Fingerprint ¶ added in v1.19.0
Fingerprint returns the stable identity of a finding (ADR-0045):
lowercase_hex(sha256(path + "\x00" + ruleID + "\x00" + symbol))
path is the file in slash form without a leading "./". Title, Severity, description and line numbers are deliberately not part of the formula, so rewording a finding, re-grading it or moving it a few lines never changes its identity. symbol is the enclosing function text derived from the diff (diff.Diff.SymbolFor); it is "" when the diff offers none.
func FooterLine ¶ added in v1.2.1
FooterLine returns the "✓ Done in … · … tokens · $cost" line.
func Graph ¶ added in v1.15.0
func Graph(w io.Writer, rows []GraphRow, opts GraphOptions) error
Graph writes the commit DAG. Rows must already be laid out by graph.Layout and carry their commit metadata.
func HeaderLine ¶ added in v1.2.1
HeaderLine, StatusLine, and FooterLine expose the three context lines the Cards renderer wraps around its body, so non-card review surfaces (e.g. `remote pr`, whose findings go to GitHub) can print the exact same informational lines to the terminal. Keeping one implementation guarantees they stay identical across every review command type.
func Markdown ¶
Markdown writes a plain-markdown rendering of the review. Under ADR-0014 the renderer runs the user's OUTPUT.md as a Go text/template against the parsed Findings; it never sees the system prompt or any LLM-side formatting. Graceful degrade paths:
- p.Findings == nil → emit p.Content verbatim (parse failed upstream).
- p.OutputTemplate == "" → emit p.Content verbatim (no template loaded).
- template execute fails → return the error; pre-send validation (ADR-0014 §5) should have caught this, so if we land here a regression occurred and the caller deserves to see it rather than silently render half-formed output.
func RelativeAge ¶ added in v1.15.0
RelativeAge renders a coarse "how long ago" label. Deliberately low resolution — the graph wants a scannable column, not a precise duration, and a fixed-width-ish token keeps rows aligned.
func SARIF ¶ added in v1.19.0
SARIF writes the findings of p as a SARIF 2.1.0 document (ADR-0047).
The caller passes the post-signal-control set -- the same findings --json would emit -- and is responsible for refusing a degraded run: a nil p.Findings is NOT a valid input here, because an empty results[] tells Code Scanning every open alert is fixed (ADR-0047 §4, fail closed). SARIF still renders a nil slice as results: [] so the writer itself never panics; the refusal lives at the call site, which knows whether the run degraded.
func SARIFWithCategory ¶ added in v1.21.0
func SARIFWithCategory(w io.Writer, findings []Finding, category string, extraProps []map[string]any) error
SARIFWithCategory is SARIF for the commands that own their own Code Scanning category (guard, leaks). extraProps, when non-nil, is parallel to findings: extraProps[i] is merged into findings[i]'s properties bag, so a caller can attach command-specific keys without widening Finding. A key in extraProps never overrides the renderer's own keys.
func StatusLine ¶ added in v1.2.1
StatusLine returns the "analyzing N files · …" line, or "" when no diff stats are populated.
func TemplateFuncs ¶ added in v0.6.0
TemplateFuncs is the function map registered on every OUTPUT.md template the renderer parses. The set is the public template contract (ADR-0014 §2); additions are allowed in v1.x but removals require a schema bump.
func ValidateOutputTemplate ¶ added in v0.6.0
ValidateOutputTemplate is the pre-send guard from ADR-0014 §5. It runs three checks against a template body so a malformed user OUTPUT.md fails before any provider round-trip:
- Parse — text/template syntax check.
- Empty-findings execute — does the template crash on the empty case?
- Sample-findings execute — does the template crash with two findings (critical + info) populated, covering both branches of any severity-based conditional logic.
Returns the first failure verbatim, wrapped with a stable prefix the CLI uses to format an i18n'd error message. Returns nil on success.
func VerboseFooter ¶
VerboseFooter returns the multi-line footer appended after a review when --verbose is in effect. Format is stable: tokens, cost, latency, provider, model — each on its own line, aligned. Cached results get a `(cached)` marker on the tokens line so users see why a fast result was free.
Types ¶
type Finding ¶ added in v0.6.0
type Finding struct {
Severity Severity `json:"severity"`
File string `json:"file"`
Line int `json:"line"`
LineEnd int `json:"line_end,omitempty"`
Title string `json:"title"`
Description string `json:"description"`
Suggestion string `json:"suggestion"`
Language string `json:"language,omitempty"`
Snippet string `json:"snippet,omitempty"`
// RuleID is the finding's class from the closed rule taxonomy
// (internal/rules, ADR-0045). The model proposes it; the CLI normalises
// it right after parse (unknown or empty -> general.other), so a finding
// that reaches a renderer carries a canonical id. Additive and omitempty:
// JSON schema stays 1.
RuleID string `json:"rule_id,omitempty"`
// Fingerprint is the finding's stable identity, see Fingerprint. It is
// computed by the CLI after parse and never read from the model, never
// stored in the response cache. Additive and omitempty: schema stays 1.
Fingerprint string `json:"fingerprint,omitempty"`
}
Finding is one review item the LLM returned. See ADR-0014 §1 for the full contract, including which fields are required.
func ParseFindings ¶ added in v0.6.0
ParseFindings decodes the LLM-emitted JSON payload into a slice. The returned slice may be empty (a clean review) but is non-nil on success. Errors are *ParseError (classifiable via errors.As) and trigger the repair-oriented retry, then graceful degrade, at the caller (ADR-0014 §4, ADR-0031) — the pipeline never crashes on a malformed response.
func (Finding) LineRef ¶ added in v0.9.0
LineRef formats the line reference as "142" when the finding is pinned to a single line, or "142-145" when LineEnd is set and greater than Line. Used by all renderers (cards, copytext, markdown via .LineRef template field) so the range display stays consistent. Returns "" when Line <= 0 so callers can branch on the missing case rather than emit "path:0".
LineEnd is treated as a closed range — both endpoints inclusive, matching how source-code "lines 142–145" reads in human writing. Out-of-order values (LineEnd < Line) and equal values (LineEnd == Line) collapse to a single-line ref; we never emit "142-142" or "145-142", both of which would be confusing.
type GraphOptions ¶ added in v1.15.0
type GraphOptions struct {
// Color enables ANSI styling. Callers pass ui.ColorEnabled(w, mode).
Color bool
// Unicode selects box-drawing glyphs over the ASCII fallback. Callers
// normally tie this to Color: a terminal that refused ANSI is also the
// one most likely to mangle U+2502.
Unicode bool
// Width is the terminal width; 0 means unknown, so do not clip.
Width int
// Filtered marks that a commit filter was active, which is what makes the
// matched/context distinction meaningful. Without it every commit renders
// as matched and no legend is printed.
Filtered bool
// Now anchors relative dates. Zero means time.Now() — injectable so tests
// are not clock-dependent.
Now time.Time
}
GraphOptions controls appearance. The zero value is a safe ASCII, no-colour, unclipped render — what a pipe or a test buffer should get.
type GraphRow ¶ added in v1.15.0
type GraphRow struct {
Row graph.Row
Commit git.CommitMeta
Refs []string // branch/tag labels pointing at this commit
}
GraphRow pairs a laid-out row with the commit metadata needed to describe it.
type Meta ¶
type Meta struct {
Provider string
Model string
Lang string
Usage provider.Usage
Cost float64
// CostUnknown marks a run whose provider has no declared price
// (openai-compatible without pricing in config). The cards and verbose
// footers then print "unknown" instead of $0.0000; the JSON cost_usd
// field is deliberately unchanged (existing schema contract).
CostUnknown bool
Latency time.Duration
Cached bool
Timestamp time.Time
// Stats describing what went into this review. Used by the Cards
// renderer for its pre-body status line; zero values cause the line
// to be omitted. Markdown / JSON / verbose-footer renderers ignore
// these fields, so adding more here is backwards-compatible.
Files int // post-filter file count
LinesAdded int // total `+` lines in the reviewed diff
LinesRemoved int // total `-` lines in the reviewed diff
RulesLoaded bool // a non-default COMMITBRIEF.md was loaded
// Signal-control removals (ADR-0027). Baselined counts findings dropped
// because their fingerprint is in the user-private baseline; Suppressed
// counts findings dropped by an inline commitbrief-ignore marker. Both
// are surfaced as optional additive JSON meta counts and a one-line human
// footer; zero values are omitted from the JSON output (omitempty) so the
// locked schema-v1 shape is unchanged when no signal control fired.
Baselined int
Suppressed int
// Recovery observability (ADR-0031). Retries counts repair retries issued
// on this live review (0 or 1); DegradeReason is a stable snake-case tag
// ("malformed-json" / "schema" / "empty" / "retry-error") set only when the
// review degraded to markdown-fallback. Both are additive optional JSON
// meta fields (omitempty) plus verbose-footer lines. Retries is zero on a
// cache replay (no provider call was made); DegradeReason is replayed from
// the cache entry, so a degraded response stays marked as degraded.
Retries int
DegradeReason string
// FilteredCommits is how many commits the commit-level filters selected
// (ADR-0035), i.e. how many commits' patches make up the reviewed diff.
// Zero — and therefore omitted from JSON — for every ordinary
// staged/unstaged/range review, which has no commit set to report.
FilteredCommits int
// WalkTruncated is set by `leaks` when the history walk hit its fixed
// commit ceiling, so older history was never scanned (ADR-0036 §Update
// 2026-10-20). Optional additive JSON meta field, omitted when false.
WalkTruncated bool
// Truncated is set by `leaks` when --max-commits cut the selected history
// short: more commits matched than the window allowed, so the oldest were
// not scanned (ADR-0036 §Update 2026-10-25). Optional additive JSON meta field (meta.truncated),
// omitted when false. Unlike WalkTruncated, raising --max-commits lifts it.
Truncated bool
}
type ParseError ¶ added in v1.13.0
type ParseError struct {
Kind ParseErrorKind
// contains filtered or unexported fields
}
ParseError is the typed error ParseFindings returns. Its Error() text is kept byte-identical to the pre-ADR-0031 messages so existing substring assertions keep working; Kind adds machine-readable classification and Unwrap exposes the underlying json error for further inspection.
func (*ParseError) Error ¶ added in v1.13.0
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶ added in v1.13.0
func (e *ParseError) Unwrap() error
type ParseErrorKind ¶ added in v1.13.0
type ParseErrorKind int
ParseErrorKind classifies why ParseFindings rejected a payload so the retry/repair path (ADR-0031) can pick a failure-mode-specific recovery prompt instead of a blind re-roll of the identical request.
const ( // ParseErrEmpty — the response was empty (or whitespace only) after // trimming; there was no JSON at all. Recovered with a hard "JSON only" // reset, same as prose / schema-ignored output. ParseErrEmpty ParseErrorKind = iota // ParseErrProse — json.Unmarshal failed and the payload does not even look // like a JSON attempt (it starts with commentary, not `{`/`[`): the model // ignored the schema and wrote prose. Recovered with a hard "JSON only, // no prose" reset — asking it to "complete the JSON" would be nonsense. ParseErrProse // ParseErrMalformedJSON — json.Unmarshal failed but the payload looks like // a genuine JSON attempt that is truncated or syntactically broken (often // max_tokens exhaustion). Recovered by asking the model to complete/correct // the JSON, with a raised token ceiling. ParseErrMalformedJSON // ParseErrSchema — the payload decoded as JSON but violated the findings // contract (unknown severity or a missing required field). Recovered with // a clean schema-conformant redraw. ParseErrSchema )
type Payload ¶
type Payload struct {
// Content is the raw provider response — under ADR-0014 a JSON string
// matching the findings schema; on graceful degrade it may be free-form
// markdown left over from a malformed JSON response. Cached as-is.
Content string
// Findings is the parsed structured response from the LLM. A non-nil
// empty slice means "no review-worthy issues"; a nil slice signals
// graceful degrade — the JSON parse failed and renderers must fall
// back to rendering Content directly (Stage A behavior).
Findings []Finding
// OutputTemplate is the loaded OUTPUT.md template body, consumed by the
// Markdown renderer. Empty string falls back to emitting Content
// unchanged (also the path used during degrade).
OutputTemplate string
// Compact requests one-line-per-finding rendering in the Cards layout,
// useful when a review surfaces many findings and per-finding panels
// would dominate the terminal. Header/status/footer stay; the body
// becomes a severity-ordered list of "[icon] SEVERITY • file:line —
// title" lines. Other renderers (Markdown/JSON) ignore this field.
Compact bool
Meta Meta
Verbose bool
// Remote is the `remote pr` posting-mode report (ADR-0048). Only the JSON
// renderer reads it; nil for every other producer.
Remote *RemoteReport
}
type RemotePR ¶ added in v1.22.0
RemotePR identifies the pull request the review was addressed to. Repo is the base repository "owner/name".
type RemoteReport ¶ added in v1.22.0
type RemoteReport struct {
Status string `json:"status"`
PR RemotePR `json:"pr"`
HeadOID string `json:"head_oid"`
Verdict string `json:"verdict,omitempty"`
VerdictUncapped string `json:"verdict_uncapped,omitempty"`
MaxVerdict string `json:"max_verdict"`
Review RemoteReview `json:"review"`
Sync *RemoteSync `json:"sync,omitempty"`
Warnings []RemoteWarning `json:"warnings"`
}
RemoteReport is the optional top-level `remote` container of the JSON v1 document. It is present only in the document `remote pr <ID> --json` writes in posting mode (ADR-0048 §2); every other producer leaves Payload.Remote nil, so the v1 shape is byte-for-byte unchanged for them and `schema` stays 1.
Evolution follows the v1 rules (ADR-0048 §3): new optional fields may be added in a minor release; renaming, removing, retyping or changing the meaning of a field requires schema 2 for the whole envelope.
type RemoteReview ¶ added in v1.22.0
type RemoteReview struct {
Mode string `json:"mode"`
FullReason string `json:"full_reason,omitempty"`
PreviousOID string `json:"previous_oid,omitempty"`
Attempts int `json:"attempts"`
MarkerWritten bool `json:"marker_written"`
}
RemoteReview describes how the review was produced.
type RemoteSync ¶ added in v1.22.0
type RemoteSync struct {
Mode string `json:"mode"`
Posted int `json:"posted"`
Updated int `json:"updated"`
Unchanged int `json:"unchanged"`
Resolved int `json:"resolved"`
Replied int `json:"replied"`
Held int `json:"held"`
PostFailed int `json:"post_failed"`
Unanchored int `json:"unanchored"`
}
RemoteSync carries the counters of the `Synced:` stderr line plus the two failure-shaped counts (ADR-0048 §2).
type RemoteWarning ¶ added in v1.22.0
type RemoteWarning struct {
Code string `json:"code"`
Op string `json:"op,omitempty"`
Ref string `json:"ref,omitempty"`
Count int `json:"count,omitempty"`
Detail string `json:"detail,omitempty"`
}
RemoteWarning is one machine-readable condition of the run. Code is a stable, English, snake_case open set; Detail is raw, non-localized diagnostic text and is not stable.
type Severity ¶ added in v0.6.0
type Severity string
Severity ranks how urgently a finding should be addressed. The vocabulary is the wire contract with the LLM (ADR-0014 §1) and is intentionally English-only; UI strings around it are i18n-able at the renderer layer.
type SeverityGroup ¶ added in v0.6.0
SeverityGroup is the value type produced by GroupBySeverity for template consumption. Items preserve the order they appeared in the source slice.
func GroupBySeverity ¶ added in v0.6.0
func GroupBySeverity(findings []Finding) []SeverityGroup
GroupBySeverity returns findings grouped by severity, ordered critical → info. Empty buckets are omitted so templates can iterate without a presence check.
type TemplateData ¶ added in v0.6.0
type TemplateData struct {
Findings []Finding
}
TemplateData is the value passed to a parsed OUTPUT.md template at execution time. Keeping the struct named (rather than a bare slice) lets templates write `{{ range .Findings }}` and gives future fields a stable home.