{"modulePath":"github.com/CommitBrief/commitbrief","version":"v1.23.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package render\n\n## Constants\n\n```go\nconst (\n\tRemoteStatusSubmitted    = \"submitted\"\n\tRemoteStatusNoNewCommits = \"no_new_commits\"\n\tRemoteStatusDegraded     = \"degraded\"\n\tRemoteStatusTooVolatile  = \"too_volatile\"\n\tRemoteStatusFailed       = \"failed\"\n\n\tRemoteModeFull        = \"full\"\n\tRemoteModeIncremental = \"incremental\"\n\tRemoteModeNone        = \"none\"\n\n\tRemoteSyncSynced   = \"synced\"\n\tRemoteSyncPostOnly = \"post_only\"\n\tRemoteSyncSkipped  = \"skipped\"\n)\n```\nRemote report enum values (ADR-0048 §2, §3).\n\n```go\nconst (\n\t// SARIFCategoryReview is the review and diff category (the default).\n\tSARIFCategoryReview = sarifCategory\n\t// SARIFCategoryGuard is the `commitbrief guard` category.\n\tSARIFCategoryGuard = \"commitbrief/guard/\"\n\t// SARIFCategoryLeaks is the `commitbrief leaks` category.\n\tSARIFCategoryLeaks = \"commitbrief/leaks/\"\n)\n```\nCode 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.\n\n```go\nconst SchemaVersion = 1\n```\nSchemaVersion 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.\n\nVersioning policy (see docs/json-schema.md):\n\n  - 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:\n  - \\`content\\` is populated only on graceful degrade (LLM produced unparseable output); empty on the happy path.\n  - \\`summary\\` is reserved for a future LLM-authored prose summary; v1 always emits it as \\`{}\\`.\n  - 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.\n  - Renaming, removing, or changing the type of any documented field IS a breaking change and requires bumping SchemaVersion to 2.\n\n## Functions\n\n```go\nfunc BranchTopology(w io.Writer, branches []git.Branch, opts GraphOptions) error\n```\nBranchTopology writes the \\`--branches\\` view: one row per branch with its ahead/behind position relative to the base.\n\n```go\nfunc BuildCopyPayload(findings []Finding) string\n```\nBuildCopyPayload 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).\n\nReturns \"\" 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.\n\n```go\nfunc Cards(w io.Writer, p Payload) error\n```\nCards 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.\n\nUnder 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.\n\n```go\nfunc CopyText(f Finding) string\n```\nCopyText returns a plain-text representation of f suitable for pasting into chat, an issue tracker, or a code editor. Format:\n\n\t[💥 CRITICAL] internal/auth/session.go:142\n\tSQL fragment built from request input\n\n\tString concatenation feeds db.Query directly — bypasses the\n\tprepared statement path used elsewhere in this package.\n\n\t→ Switch to a prepared statement with bound parameters here so\n\tuser input never reaches the SQL string concatenation path.\n\nThe 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.\n\n```go\nfunc CountFiles(findings []Finding) int\n```\nCountFiles returns the number of distinct files referenced across the given findings.\n\n```go\nfunc Fingerprint(file, ruleID, symbol string) string\n```\nFingerprint returns the stable identity of a finding (ADR-0045):\n\n\tlowercase_hex(sha256(path + \"\\x00\" + ruleID + \"\\x00\" + symbol))\n\npath 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.\n\n```go\nfunc FooterLine(m Meta, findings []Finding) string\n```\nFooterLine returns the \"✓ Done in … · … tokens · $cost\" line.\n\n```go\nfunc Graph(w io.Writer, rows []GraphRow, opts GraphOptions) error\n```\nGraph writes the commit DAG. Rows must already be laid out by graph.Layout and carry their commit metadata.\n\n```go\nfunc HeaderLine(m Meta) string\n```\nHeaderLine, 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.\n\n```go\nfunc JSON(w io.Writer, p Payload) error\n```\n\n```go\nfunc Markdown(w io.Writer, p Payload) error\n```\nMarkdown 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:\n\n  - p.Findings == nil  → emit p.Content verbatim (parse failed upstream).\n  - p.OutputTemplate == \"\" → emit p.Content verbatim (no template loaded).\n  - 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.\n\n```go\nfunc RelativeAge(t, now time.Time) string\n```\nRelativeAge 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.\n\n```go\nfunc SARIF(w io.Writer, p Payload) error\n```\nSARIF writes the findings of p as a SARIF 2.1.0 document (ADR-0047).\n\nThe 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.\n\n```go\nfunc SARIFWithCategory(w io.Writer, findings []Finding, category string, extraProps []map[string]any) error\n```\nSARIFWithCategory 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.\n\n```go\nfunc StatusLine(m Meta) string\n```\nStatusLine returns the \"analyzing N files · …\" line, or \"\" when no diff stats are populated.\n\n```go\nfunc TemplateFuncs() template.FuncMap\n```\nTemplateFuncs 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.\n\n```go\nfunc Terminal(w io.Writer, p Payload) error\n```\n\n```go\nfunc ValidateOutputTemplate(content string) error\n```\nValidateOutputTemplate 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:\n\n 1. Parse — text/template syntax check.\n 2. Empty-findings execute — does the template crash on the empty case?\n 3. Sample-findings execute — does the template crash with two findings (critical + info) populated, covering both branches of any severity-based conditional logic.\n\nReturns the first failure verbatim, wrapped with a stable prefix the CLI uses to format an i18n'd error message. Returns nil on success.\n\n```go\nfunc VerboseFooter(m Meta) string\n```\nVerboseFooter 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.\n\n## Types\n\n```go\ntype Finding struct {\n\tSeverity    Severity `json:\"severity\"`\n\tFile        string   `json:\"file\"`\n\tLine        int      `json:\"line\"`\n\tLineEnd     int      `json:\"line_end,omitempty\"`\n\tTitle       string   `json:\"title\"`\n\tDescription string   `json:\"description\"`\n\tSuggestion  string   `json:\"suggestion\"`\n\tLanguage    string   `json:\"language,omitempty\"`\n\tSnippet     string   `json:\"snippet,omitempty\"`\n\n\t// RuleID is the finding's class from the closed rule taxonomy\n\t// (internal/rules, ADR-0045). The model proposes it; the CLI normalises\n\t// it right after parse (unknown or empty -\u003e general.other), so a finding\n\t// that reaches a renderer carries a canonical id. Additive and omitempty:\n\t// JSON schema stays 1.\n\tRuleID string `json:\"rule_id,omitempty\"`\n\t// Fingerprint is the finding's stable identity, see Fingerprint. It is\n\t// computed by the CLI after parse and never read from the model, never\n\t// stored in the response cache. Additive and omitempty: schema stays 1.\n\tFingerprint string `json:\"fingerprint,omitempty\"`\n}\n```\nFinding is one review item the LLM returned. See ADR-0014 §1 for the full contract, including which fields are required.\n\n```go\nfunc ParseFindings(content string) ([]Finding, error)\n```\nParseFindings 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.\n\n```go\nfunc (f Finding) LineRef() string\n```\nLineRef 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 \\\u003c= 0 so callers can branch on the missing case rather than emit \"path:0\".\n\nLineEnd 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 \\\u003c 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.\n\n```go\nfunc (f Finding) PathRef() string\n```\nPathRef joins File and LineRef with \":\" so callers don't repeat the conditional logic. Returns File alone when LineRef is empty.\n\n```go\ntype Format int\n```\n\n```go\nconst (\n\tFormatTerminal Format = iota\n\tFormatMarkdown\n\tFormatJSON\n)\n```\n\n```go\nfunc (f Format) String() string\n```\n\n```go\ntype GraphOptions struct {\n\t// Color enables ANSI styling. Callers pass ui.ColorEnabled(w, mode).\n\tColor bool\n\t// Unicode selects box-drawing glyphs over the ASCII fallback. Callers\n\t// normally tie this to Color: a terminal that refused ANSI is also the\n\t// one most likely to mangle U+2502.\n\tUnicode bool\n\t// Width is the terminal width; 0 means unknown, so do not clip.\n\tWidth int\n\t// Filtered marks that a commit filter was active, which is what makes the\n\t// matched/context distinction meaningful. Without it every commit renders\n\t// as matched and no legend is printed.\n\tFiltered bool\n\t// Now anchors relative dates. Zero means time.Now() — injectable so tests\n\t// are not clock-dependent.\n\tNow time.Time\n}\n```\nGraphOptions controls appearance. The zero value is a safe ASCII, no-colour, unclipped render — what a pipe or a test buffer should get.\n\n```go\ntype GraphRow struct {\n\tRow    graph.Row\n\tCommit git.CommitMeta\n\tRefs   []string // branch/tag labels pointing at this commit\n}\n```\nGraphRow pairs a laid-out row with the commit metadata needed to describe it.\n\n```go\ntype Meta struct {\n\tProvider string\n\tModel    string\n\tLang     string\n\tUsage    provider.Usage\n\tCost     float64\n\t// CostUnknown marks a run whose provider has no declared price\n\t// (openai-compatible without pricing in config). The cards and verbose\n\t// footers then print \"unknown\" instead of $0.0000; the JSON cost_usd\n\t// field is deliberately unchanged (existing schema contract).\n\tCostUnknown bool\n\tLatency     time.Duration\n\tCached      bool\n\tTimestamp   time.Time\n\t// Stats describing what went into this review. Used by the Cards\n\t// renderer for its pre-body status line; zero values cause the line\n\t// to be omitted. Markdown / JSON / verbose-footer renderers ignore\n\t// these fields, so adding more here is backwards-compatible.\n\tFiles        int  // post-filter file count\n\tLinesAdded   int  // total `+` lines in the reviewed diff\n\tLinesRemoved int  // total `-` lines in the reviewed diff\n\tRulesLoaded  bool // a non-default COMMITBRIEF.md was loaded\n\n\t// Signal-control removals (ADR-0027). Baselined counts findings dropped\n\t// because their fingerprint is in the user-private baseline; Suppressed\n\t// counts findings dropped by an inline commitbrief-ignore marker. Both\n\t// are surfaced as optional additive JSON meta counts and a one-line human\n\t// footer; zero values are omitted from the JSON output (omitempty) so the\n\t// locked schema-v1 shape is unchanged when no signal control fired.\n\tBaselined  int\n\tSuppressed int\n\n\t// Recovery observability (ADR-0031). Retries counts repair retries issued\n\t// on this live review (0 or 1); DegradeReason is a stable snake-case tag\n\t// (\"malformed-json\" / \"schema\" / \"empty\" / \"retry-error\") set only when the\n\t// review degraded to markdown-fallback. Both are additive optional JSON\n\t// meta fields (omitempty) plus verbose-footer lines. Retries is zero on a\n\t// cache replay (no provider call was made); DegradeReason is replayed from\n\t// the cache entry, so a degraded response stays marked as degraded.\n\tRetries       int\n\tDegradeReason string\n\n\t// FilteredCommits is how many commits the commit-level filters selected\n\t// (ADR-0035), i.e. how many commits' patches make up the reviewed diff.\n\t// Zero — and therefore omitted from JSON — for every ordinary\n\t// staged/unstaged/range review, which has no commit set to report.\n\tFilteredCommits int\n\n\t// WalkTruncated is set by `leaks` when the history walk hit its fixed\n\t// commit ceiling, so older history was never scanned (ADR-0036 §Update\n\t// 2026-10-20). Optional additive JSON meta field, omitted when false.\n\tWalkTruncated bool\n\n\t// Truncated is set by `leaks` when --max-commits cut the selected history\n\t// short: more commits matched than the window allowed, so the oldest were\n\t// not scanned (ADR-0036 §Update 2026-10-25). Optional additive JSON meta field (meta.truncated),\n\t// omitted when false. Unlike WalkTruncated, raising --max-commits lifts it.\n\tTruncated bool\n}\n```\n\n```go\ntype ParseError struct {\n\tKind ParseErrorKind\n\t// contains filtered or unexported fields\n}\n```\nParseError 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.\n\n```go\nfunc (e *ParseError) Error() string\n```\n\n```go\nfunc (e *ParseError) Unwrap() error\n```\n\n```go\ntype ParseErrorKind int\n```\nParseErrorKind 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.\n\n```go\nconst (\n\t// ParseErrEmpty — the response was empty (or whitespace only) after\n\t// trimming; there was no JSON at all. Recovered with a hard \"JSON only\"\n\t// reset, same as prose / schema-ignored output.\n\tParseErrEmpty ParseErrorKind = iota\n\t// ParseErrProse — json.Unmarshal failed and the payload does not even look\n\t// like a JSON attempt (it starts with commentary, not `{`/`[`): the model\n\t// ignored the schema and wrote prose. Recovered with a hard \"JSON only,\n\t// no prose\" reset — asking it to \"complete the JSON\" would be nonsense.\n\tParseErrProse\n\t// ParseErrMalformedJSON — json.Unmarshal failed but the payload looks like\n\t// a genuine JSON attempt that is truncated or syntactically broken (often\n\t// max_tokens exhaustion). Recovered by asking the model to complete/correct\n\t// the JSON, with a raised token ceiling.\n\tParseErrMalformedJSON\n\t// ParseErrSchema — the payload decoded as JSON but violated the findings\n\t// contract (unknown severity or a missing required field). Recovered with\n\t// a clean schema-conformant redraw.\n\tParseErrSchema\n)\n```\n\n```go\ntype Payload struct {\n\t// Content is the raw provider response — under ADR-0014 a JSON string\n\t// matching the findings schema; on graceful degrade it may be free-form\n\t// markdown left over from a malformed JSON response. Cached as-is.\n\tContent string\n\n\t// Findings is the parsed structured response from the LLM. A non-nil\n\t// empty slice means \"no review-worthy issues\"; a nil slice signals\n\t// graceful degrade — the JSON parse failed and renderers must fall\n\t// back to rendering Content directly (Stage A behavior).\n\tFindings []Finding\n\n\t// OutputTemplate is the loaded OUTPUT.md template body, consumed by the\n\t// Markdown renderer. Empty string falls back to emitting Content\n\t// unchanged (also the path used during degrade).\n\tOutputTemplate string\n\n\t// Compact requests one-line-per-finding rendering in the Cards layout,\n\t// useful when a review surfaces many findings and per-finding panels\n\t// would dominate the terminal. Header/status/footer stay; the body\n\t// becomes a severity-ordered list of \"[icon] SEVERITY • file:line —\n\t// title\" lines. Other renderers (Markdown/JSON) ignore this field.\n\tCompact bool\n\n\tMeta    Meta\n\tVerbose bool\n\n\t// Remote is the `remote pr` posting-mode report (ADR-0048). Only the JSON\n\t// renderer reads it; nil for every other producer.\n\tRemote *RemoteReport\n}\n```\n\n```go\ntype RemotePR struct {\n\tRepo   string `json:\"repo\"`\n\tNumber int    `json:\"number\"`\n}\n```\nRemotePR identifies the pull request the review was addressed to. Repo is the base repository \"owner/name\".\n\n```go\ntype RemoteReport struct {\n\tStatus          string          `json:\"status\"`\n\tPR              RemotePR        `json:\"pr\"`\n\tHeadOID         string          `json:\"head_oid\"`\n\tVerdict         string          `json:\"verdict,omitempty\"`\n\tVerdictUncapped string          `json:\"verdict_uncapped,omitempty\"`\n\tMaxVerdict      string          `json:\"max_verdict\"`\n\tReview          RemoteReview    `json:\"review\"`\n\tSync            *RemoteSync     `json:\"sync,omitempty\"`\n\tWarnings        []RemoteWarning `json:\"warnings\"`\n}\n```\nRemoteReport is the optional top-level \\`remote\\` container of the JSON v1 document. It is present only in the document \\`remote pr \\\u003cID\u003e --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.\n\nEvolution 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.\n\n```go\ntype RemoteReview struct {\n\tMode          string `json:\"mode\"`\n\tFullReason    string `json:\"full_reason,omitempty\"`\n\tPreviousOID   string `json:\"previous_oid,omitempty\"`\n\tAttempts      int    `json:\"attempts\"`\n\tMarkerWritten bool   `json:\"marker_written\"`\n}\n```\nRemoteReview describes how the review was produced.\n\n```go\ntype RemoteSync struct {\n\tMode       string `json:\"mode\"`\n\tPosted     int    `json:\"posted\"`\n\tUpdated    int    `json:\"updated\"`\n\tUnchanged  int    `json:\"unchanged\"`\n\tResolved   int    `json:\"resolved\"`\n\tReplied    int    `json:\"replied\"`\n\tHeld       int    `json:\"held\"`\n\tPostFailed int    `json:\"post_failed\"`\n\tUnanchored int    `json:\"unanchored\"`\n}\n```\nRemoteSync carries the counters of the \\`Synced:\\` stderr line plus the two failure-shaped counts (ADR-0048 §2).\n\n```go\ntype RemoteWarning struct {\n\tCode   string `json:\"code\"`\n\tOp     string `json:\"op,omitempty\"`\n\tRef    string `json:\"ref,omitempty\"`\n\tCount  int    `json:\"count,omitempty\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n```\nRemoteWarning 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.\n\n```go\ntype Severity string\n```\nSeverity 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.\n\n```go\nconst (\n\tSeverityCritical Severity = \"critical\"\n\tSeverityHigh     Severity = \"high\"\n\tSeverityMedium   Severity = \"medium\"\n\tSeverityLow      Severity = \"low\"\n\tSeverityInfo     Severity = \"info\"\n)\n```\n\n```go\nfunc (s Severity) IsValid() bool\n```\nIsValid reports whether s is one of the five canonical levels.\n\n```go\ntype SeverityGroup struct {\n\tSeverity Severity\n\tItems    []Finding\n}\n```\nSeverityGroup is the value type produced by GroupBySeverity for template consumption. Items preserve the order they appeared in the source slice.\n\n```go\nfunc GroupBySeverity(findings []Finding) []SeverityGroup\n```\nGroupBySeverity returns findings grouped by severity, ordered critical → info. Empty buckets are omitted so templates can iterate without a presence check.\n\n```go\ntype Summary struct {\n}\n```\n\n```go\ntype TemplateData struct {\n\tFindings []Finding\n}\n```\nTemplateData 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.\n\n","path":"github.com/CommitBrief/commitbrief/internal/render","name":"render","synopsis":"","isRedistributable":true}
