sessionaudit

package
v0.143.2 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const CollapseLookback = collapseMaxGap + 1

CollapseLookback is the default maximum turn distance between a prior same-group turn and the pending command within which the real-time nudge (CollapseNudgeFor) still fires — the same gap tolerance the batch detector applies between adjacent hits (splitRuns' gapOK).

View Source
const ContextLogCommits = 5

ContextLogCommits is how many commits `gk context --include=log` returns, and therefore the exact point where a raw `git log -n N` stops being a question gk context can answer. The classifier needs that boundary, so the number has to be named somewhere both sides can see it.

It lives HERE rather than beside the context command because the dependency only runs one way: internal/cli imports this package, never the reverse. Anyone changing the size must change it here — a literal that drifts apart from the classifier makes the audit quietly wrong instead of loudly broken.

Variables

This section is empty.

Functions

func AppendHistory

func AppendHistory(path string, e HistoryEntry) error

AppendHistory appends one entry as a JSON line, creating the directory and file as needed.

func CollapseGroups

func CollapseGroups() []string

CollapseGroups returns the collapse group keys (gkForGroup's domain), sorted. It exists so cli-side mirrors of the group set (the tuned contract's leak phrases) can be wiring-tested against the real groups instead of silently drifting when one is added here.

func DefaultPaths

func DefaultPaths(home string) []string

func ExtractCommands

func ExtractCommands(line []byte) []string

ExtractCommands returns shell command strings from one JSONL record.

func HistoryPath

func HistoryPath(home string) string

HistoryPath is where recorded runs accumulate. The audit is global (it scans the home session roots, not a repo), so history lives under the home, not a repo's .gk.

func NewestSessionFile

func NewestSessionFile(home string) (string, error)

NewestSessionFile returns the most recently modified .jsonl session file under the default session roots for home — the file `session digest --last` picks by default. Note: called from inside a live agent session, that is almost always the caller's OWN transcript (it is appended every turn); NthNewestSessionFile(home, 2) is the previous session.

func NthNewestSessionFile

func NthNewestSessionFile(home string, n int) (string, error)

NthNewestSessionFile returns the n-th most recently modified .jsonl session file (1 = newest) under the default session roots for home. It reuses the audit's discovery (collectFiles sorts newest-first) so `session digest --last` and `session audit` always agree on the corpus.

func Sparkline

func Sparkline(vals []float64) string

Sparkline renders a numeric series as block characters, scaled between the series min and max. Empty series → empty string; a flat series renders as the lowest block.

Types

type Adoption

type Adoption struct {
	// GitInvocations is RawGit + GitKit + GKShort — every git-shaped call.
	GitInvocations int `json:"git_invocations"`
	GitKit         int `json:"git_kit"`
	// Rate is GitKit / GitInvocations in [0,1].
	Rate float64 `json:"rate"`
	// CoveredRawHits is the number of raw-git pattern hits that already have a
	// git-kit replacement (the sum of covered raw-* findings). These are pure
	// habit leaks: the capability exists, the agent skipped it.
	CoveredRawHits int `json:"covered_raw_hits"`
	// UncoveredRawHits is the number of raw-git hits with no recognized git-kit
	// mapping (the uncovered-raw-git gap finding). Separating these from the rate
	// keeps the adoption number honest: plumbing like `git rev-parse` should not
	// count as a missed git-kit call.
	UncoveredRawHits int `json:"uncovered_raw_hits"`
}

Adoption tracks how often agents reach for git-kit versus raw git across the scanned sessions. It is the regression metric: rerun the audit over time and watch Rate climb and CoveredRawHits fall as guidance lands.

type BatchPlan

type BatchPlan struct {
	Steps   []BatchStep `json:"steps"`
	Omitted []string    `json:"omitted,omitempty"`
}

BatchPlan is a git-kit batch --plan payload synthesized from an observed shell chain: each mappable raw-git segment becomes a git-kit step, so the agent can replace the whole `git … && git … && git …` line with one `git-kit batch --plan -` call. Steps carries the executable plan; Omitted names the non-git-kit segments (echo, tail, …) that batch cannot run and that drop out of the replacement.

type BatchStep

type BatchStep struct {
	// Args is the git-kit argv for the step, e.g. ["context","--include=diff,log"].
	Args []string `json:"args"`
	// From is the raw git segment this step replaces, for human review.
	From string `json:"from,omitempty"`
}

type CollapseNudge

type CollapseNudge struct {
	Group      string   // the collapse group both share, e.g. "context"
	GkCommand  string   // the single git-kit call that covers the run
	PriorTurns int      // how many recent turns already ran this group
	Recent     []string // the recent commands, for the message
}

CollapseNudge is a real-time opportunity: the pending command continues a raw-git run the agent already started in a recent turn, so one git-kit call would have covered both. It is what turns the audit's after-the-fact measure into prevention at the PreToolUse hook.

func CollapseNudgeFor

func CollapseNudgeFor(current string, recent []TurnEvent, lastTurn, lookback int) *CollapseNudge

CollapseNudgeFor reports whether running `current` continues a same-group raw run from the recent turns — i.e. the agent could have folded them into one git-kit call. recent is oldest→newest; lastTurn is the session's last allocated turn index (SessionTurnsWithLast), which the pending command runs right after. A prior turn folds in only when its distance to that pending turn is within lookback — the batch detector's gap tolerance (splitRuns' gapOK). Distance is measured in turn indices, not inspected events: turns occupied by non-shell tools (Read/Edit) allocate indices without emitting events, and a probe separated from the pending one by several such turns is exactly what the turn metric refuses to count as collapsible. It applies the same per-turn primary attribution as the batch detector: `current` gets exactly one group (write groups win, non-trivial payload discounts), a mutating recent turn severs a read-only probe run — so a commit flow with trailing verification probes never nudges "use gk context" — and the repo and paging guards still apply.

type CollapsibleRun

type CollapsibleRun struct {
	Group      string   `json:"group"`
	GkCommand  string   `json:"gk_command"`
	Repo       string   `json:"repo,omitempty"`
	Turns      []int    `json:"turns"`
	Commands   []string `json:"commands"`
	TurnsSaved int      `json:"turns_saved"`
}

CollapsibleRun is a maximal run of same-group git commands spread across distinct turns that one git-kit call would have replaced. TurnsSaved is the number of agent round-trips removed: a run touching N distinct turns folds to one call, saving N-1.

func DetectCollapsibleRuns

func DetectCollapsibleRuns(events []TurnEvent, maxGap int) []CollapsibleRun

DetectCollapsibleRuns finds, per collapse group, the maximal local runs of that group's turns. Each distinct turn carries exactly one PRIMARY group (attributeTurns), so a compound write-plus-probe turn counts once and by_group sums never double-count. Runs break across a repo/worktree boundary, and read-only probe runs additionally break on any interleaved mutating turn. maxGap is the interleave tolerance (see collapseMaxGap).

func DetectGkReprobeRuns

func DetectGkReprobeRuns(events []TurnEvent, maxGap int) []CollapsibleRun

DetectGkReprobeRuns is DetectCollapsibleRuns read through the git-kit lens: runs of gk's own read verbs that one gk call would have answered. It measures waste that survives adoption, so its result must never be added to DetectCollapsibleRuns' — the two answer different questions.

type Digest

type Digest struct {
	Schema int    `json:"schema"`
	File   string `json:"file"`
	Source string `json:"source"` // claude | codex | unknown
	// Turns/Commands say how much was digested: distinct shell turns and the
	// shell commands they ran.
	Turns    int            `json:"turns"`
	Commands int            `json:"commands"`
	Repos    []RepoActivity `json:"repos,omitempty"`
	Branches []string       `json:"branches,omitempty"`
	// Commits carries extracted subject lines in execution order (most recent
	// last); CommitCount also counts commits with no extractable subject
	// (--amend, gk commit's generated messages).
	Commits     []string           `json:"commits,omitempty"`
	CommitCount int                `json:"commit_count,omitempty"`
	Integration *IntegrationDigest `json:"integration,omitempty"`
	Unfinished  *UnfinishedSignal  `json:"unfinished,omitempty"`
	Reprobes    []ReprobeDigest    `json:"reprobes,omitempty"`
}

Digest is one agent session's git activity compressed into a resume/handoff block: what happened (repos, branches, commits, integration), what may be unfinished, and which probe groups the session kept re-running (plus the one gk call that collapses each).

func DigestFile

func DigestFile(path string) (Digest, error)

DigestFile reads one session JSONL and compresses its git activity into a Digest. The transcript shape is taken from the path when it sits under a known session root and sniffed from the content otherwise, so explicit paths (copies, fixtures) work anywhere on disk.

type Evidence

type Evidence struct {
	File    string     `json:"file,omitempty"`
	Command string     `json:"command"`
	Plan    *BatchPlan `json:"plan,omitempty"`
}

type FileReport

type FileReport struct {
	Path        string `json:"path"`
	Source      string `json:"source"`
	Commands    int    `json:"commands"`
	RawGit      int    `json:"raw_git"`
	GitKit      int    `json:"git_kit"`
	GKShort     int    `json:"gk_short"`
	ShellChains int    `json:"shell_chains"`
}

type Finding

type Finding struct {
	Kind           string   `json:"kind"`
	Severity       string   `json:"severity"`
	Status         string   `json:"status"`
	Count          int      `json:"count"`
	Recommendation string   `json:"recommendation"`
	CoveredBy      []string `json:"covered_by,omitempty"`
	Gap            string   `json:"gap,omitempty"`
	// Subcommands breaks a gap finding down by raw-git subcommand
	// (e.g. {"stash":40,"reset":22}) — the roadmap signal for which verbs
	// git-kit has no answer for. Empty for covered findings.
	Subcommands map[string]int `json:"subcommands,omitempty"`
	// OneShot names the gap subcommands whose raw form is a single call, so a
	// gk verb would save ~0 turns. They are real coverage holes but low
	// leverage — without the label, count-ranking promotes them over
	// multi-turn workflow gaps (an apply/reset recovery arc).
	OneShot  []string   `json:"one_shot,omitempty"`
	Evidence []Evidence `json:"evidence,omitempty"`
	// contains filtered or unexported fields
}

type GkReprobeMetrics

type GkReprobeMetrics struct {
	GkTurns    int              `json:"gk_turns"`
	TurnsSaved int              `json:"turns_saved"`
	Rate       float64          `json:"rate"`
	ByGroup    map[string]int   `json:"by_group,omitempty"`
	Runs       []CollapsibleRun `json:"runs,omitempty"`
}

GkReprobeMetrics counts turns an already-adopted session spent re-asking gk a question one gk call answers. GkTurns is its own denominator: turns that ran git-kit at all.

type HintResult

type HintResult struct {
	Covered    bool     `json:"covered"`
	Kind       string   `json:"kind,omitempty"`
	Severity   string   `json:"severity,omitempty"`
	CoveredBy  []string `json:"covered_by,omitempty"`
	Suggestion string   `json:"suggestion,omitempty"`
	// Matched is the raw-git segment that triggered the hint, for the message.
	Matched string `json:"matched,omitempty"`
	// Caution stands on its own axis: it fires for a command gk does NOT cover
	// but that destroys uncommitted work, so Covered stays false and no
	// replacement is claimed. Silence is the right answer for an ordinary gap;
	// it is the wrong answer for one that is irreversible.
	Caution string `json:"caution,omitempty"`
	// CautionMatched is the segment that raised Caution.
	CautionMatched string `json:"caution_matched,omitempty"`
}

HintResult is the git-kit guidance for a single shell command: the covered raw-git pattern it matched and how to replace it. Covered is false when the command needs no nudge (already git-kit, read-only plumbing, or non-git).

func Hint

func Hint(command string) HintResult

Hint inspects a single shell command and returns the git-kit guidance for the highest-severity covered raw-git pattern it contains. It reuses the exact classifiers the session audit uses (gitSegmentFinding plus the gk short alias), so the audit and any PreToolUse hook share one source of truth — add a classifier once and both improve.

tag/push are intentionally not matched here: raw-release-sequence is a cross-segment aggregate (it needs both), so a lone push is left for the ship/push verbs rather than nagged inline.

type HistoryEntry

type HistoryEntry struct {
	Timestamp           string         `json:"ts"`
	Files               int            `json:"files"`
	GitTurns            int            `json:"git_turns"`
	EstimatedTurnsSaved int            `json:"estimated_turns_saved"`
	Rate                float64        `json:"rate"`
	AdoptionRate        float64        `json:"adoption_rate"`
	ByGroup             map[string]int `json:"by_group,omitempty"`
	// The git-kit lens, recorded alongside rather than folded in — the fields
	// above must keep meaning exactly what they meant in older entries, or the
	// trend readers comparing across runs get a third silent re-baseline. Absent
	// on every entry written before this existed, which is the honest signal
	// that the number was not measured then.
	GkTurns        int `json:"gk_turns,omitempty"`
	GkReprobeSaved int `json:"gk_reprobe_saved,omitempty"`
	// ByProject is what the aggregate rates above cannot say: whether a swing
	// came from behaviour changing or from the SCAN WINDOW changing. A recorded
	// run covers the newest N session files, so a project that goes quiet drops
	// out and a fresh one drops in — and a single un-onboarded project with
	// heavy raw-git use can move AdoptionRate several points without anyone's
	// habits changing. Without this the two are indistinguishable after the
	// fact, and the honest verdict on any swing is "cause unknown". Absent on
	// entries written before this existed — not measured then, not zero.
	ByProject []ProjectShare `json:"by_project,omitempty"`
}

HistoryEntry is one recorded audit run, so turn-reduction adoption can be tracked over time (is collapsible-raw-turn count trending down?). Timestamp is set by the caller (time.Now at the CLI) to keep this package deterministic.

func ReadHistory

func ReadHistory(path string) ([]HistoryEntry, error)

ReadHistory reads all recorded entries in file order (oldest first). A missing file is not an error: it returns an empty slice.

type IntegrationDigest

type IntegrationDigest struct {
	Attempts  int            `json:"attempts"`
	Errored   int            `json:"errored"`
	Verbs     map[string]int `json:"verbs,omitempty"`
	LastError string         `json:"last_error,omitempty"` // most recent errored attempt, truncated
}

IntegrationDigest summarizes pull/fetch/merge/rebase/cherry-pick/push activity (raw git and the git-kit verbs) and whether any attempt errored — the "did this session integrate cleanly" signal a resumer needs first.

type Options

type Options struct {
	Paths    []string
	Home     string
	MaxFiles int
	// Metric selects which view to compute: "occurrences" (default) keeps the
	// historical output; "turns" / "both" additionally compute the turn-reduction
	// metric over Claude sessions. Unknown/empty == "occurrences".
	Metric string
	// Since, when non-zero, keeps only session files modified at or after it.
	// The caller computes the cutoff (time.Now()-window at the CLI) so this
	// package stays deterministic. Without it the report aggregates the entire
	// session history, which dilutes "is adoption improving now" with sessions
	// that predate any guidance fix.
	Since time.Time
	// UncapEvidence lifts the per-finding evidence sample cap (maxEvidence).
	// The CLI sets it for --full, which always promised "uncapped evidence" —
	// but the cap lived at COLLECTION time, so --full was only uncapping the
	// serialization of data that had already stopped at five samples. Anyone
	// judging a 400-count finding from those five had to re-grep the corpus.
	UncapEvidence bool
}

Options controls how much local session history Audit reads.

type ProjectAdoption

type ProjectAdoption struct {
	Project string  `json:"project"`
	Files   int     `json:"files"`
	RawGit  int     `json:"raw_git"`
	GitKit  int     `json:"git_kit"`
	GKShort int     `json:"gk_short,omitempty"`
	Rate    float64 `json:"rate"`
}

ProjectAdoption is one project's share of the adoption picture. Rate uses the same definition as the global Adoption.Rate: GitKit over ALL git-shaped calls (raw + git-kit + short alias) — the discouraged short alias counts in the denominator but never as adoption.

type ProjectShare

type ProjectShare struct {
	Project string `json:"project"`
	Files   int    `json:"files"`
	RawGit  int    `json:"raw_git"`
	GitKit  int    `json:"git_kit"`
	GKShort int    `json:"gk_short,omitempty"`
}

ProjectShare is one project's slice of a recorded run. Deliberately its own minimal type rather than a reuse of ProjectAdoption: this file is read ACROSS time, so its shape must not drift every time the report's project row grows a field. Rate is omitted because it is derivable (GitKit over the sum), and a stored derived value is one more thing that can disagree with itself later.

type RepoActivity

type RepoActivity struct {
	Path     string `json:"path"`
	Commands int    `json:"commands"`
}

RepoActivity is one repo/worktree the session touched, with how many shell commands carried that scope.

type Report

type Report struct {
	Schema int `json:"schema"`
	// Since echoes the Options.Since cutoff (RFC3339) when a time window was
	// applied, so consumers know the numbers describe a window, not all history.
	Since    string       `json:"since,omitempty"`
	Files    []FileReport `json:"files"`
	Totals   Totals       `json:"totals"`
	Adoption Adoption     `json:"adoption"`
	Findings []Finding    `json:"findings,omitempty"`
	// Projects rolls adoption up per project (most raw git first), so the
	// global rate stops hiding WHERE agents leak raw git — the target list
	// for contract/hook installs. Claude sessions carry their workspace in
	// the parent directory name; Codex sessions aggregate as one bucket.
	Projects []ProjectAdoption `json:"projects,omitempty"`
	// Turns is the turn-reduction metric, present only when Options.Metric
	// requested it. Additive: existing consumers reading the fields above are
	// unaffected.
	Turns *TurnMetrics `json:"turns,omitempty"`
	// Trend carries the recorded run history when the CLI was asked for it
	// (--trend). Populated by the CLI from the history log, not by Audit —
	// present here so the agent envelope includes it instead of silently
	// dropping the flag on the JSON path.
	Trend []HistoryEntry `json:"trend,omitempty"`
	Notes []string       `json:"notes,omitempty"`
}

func Audit

func Audit(opts Options) (Report, error)

Audit reads local Codex/Claude JSONL sessions and reports git usage patterns.

type ReprobeDigest

type ReprobeDigest struct {
	Group      string `json:"group"`
	TurnsSaved int    `json:"turns_saved"`
	GkCommand  string `json:"gk_command"`
}

ReprobeDigest is one collapse group the session re-ran across turns, with the turns that one gk call would have saved and that call.

type Totals

type Totals struct {
	Files       int `json:"files"`
	Commands    int `json:"commands"`
	RawGit      int `json:"raw_git"`
	GitKit      int `json:"git_kit"`
	GKShort     int `json:"gk_short"`
	ShellChains int `json:"shell_chains"`
}

type TurnEvent

type TurnEvent struct {
	Cmd       string // the raw shell command the agent ran
	Turn      int    // dense, monotonic per session in first-seen execution order
	ToolUseID string // the tool_use id, joins to the matching tool_result
	IsError   bool   // resolved from that tool_result: true => the call failed
	Repo      string // working-dir scope inferred from the command (cd / -C), "" if unknown
}

TurnEvent is one shell command an agent ran, tagged with the turn it ran in.

Turn is the unit that matters for git-kit's value proposition: collapsing commands that already share a Turn saves nothing (they ran in one agent round-trip), while collapsing commands across distinct Turns is what removes real conversation turns. Turn is derived from the assistant message id, so parallel tool calls in one message — which the harness runs together — share a Turn even though they arrive as separate JSONL records.

func CodexSessionTurns

func CodexSessionTurns(data []byte) []TurnEvent

CodexSessionTurns parses one Codex rollout's JSONL into ordered shell-command turn events. A turn is a maximal run of consecutive function_call records (one model turn issues a batch, then all outputs return), so parallel calls share a turn exactly like Claude's message-id grouping. workdir gives the repo scope directly; the exit code embedded in the matching output gives IsError.

func SessionTurns

func SessionTurns(data []byte) []TurnEvent

SessionTurns parses one Claude session's JSONL bytes into the ordered shell commands an agent ran, each tagged with its turn, tool_use id, error status, and inferred repo. Records that are not Claude assistant tool calls (or carry no shell command) produce no events but still advance the turn counter when they occupy an agent round-trip, so genuine interleaving is visible to the collapse detector. Non-Claude (e.g. Codex) lines are skipped.

func SessionTurnsWithLast

func SessionTurnsWithLast(data []byte) (events []TurnEvent, lastTurn int)

SessionTurnsWithLast is SessionTurns plus the last turn index the session allocated. Non-command tool calls (Read/Edit) advance the turn counter without emitting a TurnEvent, so lastTurn can exceed the newest event's Turn — the real-time collapse nudge needs that distance to apply the same gap tolerance as the batch detector. lastTurn is -1 when the transcript allocated no turns.

type TurnMetrics

type TurnMetrics struct {
	Source              string           `json:"source"`
	GitTurns            int              `json:"git_turns"`
	EstimatedTurnsSaved int              `json:"estimated_turns_saved"`
	Rate                float64          `json:"rate"`
	ByGroup             map[string]int   `json:"by_group,omitempty"`
	Runs                []CollapsibleRun `json:"runs,omitempty"`
	// GkReprobe is the SECOND, independent number: waste that survives adoption.
	// It is reported beside the fields above and never folded into them —
	// EstimatedTurnsSaved answers "what would adopting gk remove", this answers
	// "what would using gk better remove". Summing them would double-count
	// nothing and mean nothing, and it would re-baseline the recorded history.
	GkReprobe *GkReprobeMetrics `json:"gk_reprobe,omitempty"`
}

TurnMetrics is the turn-reduction view of the audit: how many agent round-trips the scanned sessions could have saved by reaching for git-kit. It is computed only for Claude sessions (the message-id turn boundary and the tool_use/tool_result join the model needs) and only when the turn metric is requested, so the occurrence output stays byte-identical by default.

type UnfinishedSignal

type UnfinishedSignal struct {
	Turn    int    `json:"turn"`
	Command string `json:"command"` // truncated
	Reason  string `json:"reason"`
}

UnfinishedSignal flags a session that likely stopped mid-operation: an errored mutating command in the final turns (a failed push, a merge that conflicted) with nothing after it that resolved the state.

Jump to

Keyboard shortcuts

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