efficiency

package
v0.16.521 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 22 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

Overview

Package efficiency is the hub's side of the «Эффективность» screen: collectors that take facts from outside sources through one provider interface, the facts stored in the hub's database, and the figures computed from them on read. Addresses and tokens of a source are configuration; nothing here names a particular installation.

Index

Constants

View Source
const (
	// KindArtifact is the source of the documents agents published: one fact per document, at its first version.
	KindArtifact = "artifacts"
	// CollectorArtifacts is the name of the collector in eff_source_state.
	CollectorArtifacts = "artifacts"
	// ArtifactsWindow is how far back the first publications are read.
	ArtifactsWindow = 60 * 24 * time.Hour
)
View Source
const (
	CollectorMRs      = "mrs"
	CollectorComments = "tracker"
	CollectorCommits  = "commits"
	CollectorSkills   = "skills"
	CollectorProgress = "tracker-progress"
)

Collector names, the source column of eff_source_state.

View Source
const (
	// Every is how often the sources are read.
	Every = time.Hour
	// Overlap is how far before the newest stored fact a pass looks, so that a request updated late is not missed.
	Overlap     = 48 * time.Hour
	FirstWindow = 60 * 24 * time.Hour
)
View Source
const (
	KindMR      = "mr"
	KindComment = "comment"
	// KindRevert and KindSkill are the commits of the code host: a revert of any project, and a change of a skill.
	KindRevert = "revert-commit"
	KindSkill  = "skill-commit"
)

The kinds of facts, stored as the source column.

View Source
const (

	// KindProgress is the source of the issues in progress: one fact per issue with the time of its last activity.
	KindProgress = "tracker-progress"
	// CommentKeep is how long the facts of comments are kept.
	CommentKeep = 40 * 24 * time.Hour
)
View Source
const SkillsWindow = 35 * 24 * time.Hour

SkillsWindow is how far back the commits that changed a skill are read.

View Source
const SourceMarker = "marker"

SourceMarker is the source of the markers in eff_source_facts: a fact per marker, keyed by its dedupe key, so putting the same marker again changes nothing. A marker is a dated change of how agents work (a model, a rule, a memory note) that the screen draws over the charts.

View Source
const SwitchOverview = "hub-efficiency"

SwitchOverview is the rollout switch (docs/hub/rollout-switches.md) that gives a person the overview and the personal tab from the hub. Without a row the endpoints answer 404 and the screen keeps asking the gateway.

Variables

This section is empty.

Functions

func ImportMarkers

func ImportMarkers(ctx context.Context, st store.Store, raw string, now time.Time) (int, error)

ImportMarkers stores the markers of raw, a JSON array of {key?, at (RFC 3339), kind, title, detail?}, and says how many it stored. The instance's own markers come this way, from a file kept in its repository (HUB_EFFICIENCY_MARKERS), and every start stores them again: a marker with the same key is replaced, never doubled.

func ImportRegressions

func ImportRegressions(ctx context.Context, st store.Store, raw string) (int, error)

ImportRegressions stores the alerts of raw, a JSON array of {id, batch_id?, metric, baseline, observed, band, fingerprint_from?, fingerprint_to?, diff?, addressee, seen_at?, state?, resolved_by?, created_at (RFC 3339)}, and says how many it read. The instance's own alerts come this way (HUB_EFFICIENCY_REGRESSIONS); every start reads them again and an alert already stored is left as it is.

func IsRevert

func IsRevert(title string) bool

IsRevert says that a request undoes another: GitLab titles it `Revert "<title>"`.

func IsRevertCommit

func IsRevertCommit(title, message string) bool

IsRevertCommit says whether a commit reverts another: a «Revert» title or the line git writes into a revert's message.

Types

type Artifact

type Artifact struct {
	Slug        string    `json:"slug"`
	At          time.Time `json:"at"`
	AuthorEmail string    `json:"author_email"`
	AuthorName  string    `json:"author_name"`
	Task        string    `json:"task"`
}

Artifact is a document on its first publication: who published it and which task it belongs to.

type ArtifactSource

type ArtifactSource interface {
	Published(ctx context.Context, since time.Time) ([]Artifact, error)
}

ArtifactSource is a source of the documents published since a time.

type Artifacts

type Artifacts struct {
	URL    string
	Token  string
	Client *http.Client
}

Artifacts is an ArtifactSource over the read API of the documents service.

func NewArtifacts

func NewArtifacts(rawURL, token string) *Artifacts

NewArtifacts returns the provider; nil when the source is not configured.

func (*Artifacts) Published

func (a *Artifacts) Published(ctx context.Context, since time.Time) ([]Artifact, error)

Published lists the documents created since a time with the author of their first version. A document whose versions cannot be read is skipped and the first error is returned with the rest.

type CodeHost

type CodeHost interface {
	MergedMRs(ctx context.Context, since time.Time) ([]MR, error)
}

CodeHost is a source of merged requests: GitLab, GitHub or any other that can list what was merged since a time. It reports every merged request however it was created (a web form, a push option, the host's API); counting only the ones a session mentioned made the money per request lie (see Summary).

type Collector

type Collector struct {
	Store   store.Store
	Code    CodeHost
	Tracker Tracker
	// Documents is the source of the documents agents published; nil reads none.
	Documents ArtifactSource
	Log       *slog.Logger
	Now       func() time.Time
}

Collector reads the configured sources into the store. A source that is not configured is recorded as such and leaves the others alone.

func (*Collector) Once

func (c *Collector) Once(ctx context.Context) bool

Once makes one pass over every source and says whether all of them succeeded.

func (*Collector) Run

func (c *Collector) Run(ctx context.Context)

Run collects until ctx ends, backing off after a failed pass.

type Comment

type Comment struct {
	Issue  string    `json:"issue"`
	Author string    `json:"author"`
	At     time.Time `json:"at"`
	Head   string    `json:"head"`
}

Comment is a comment of a tracker issue; only the head of the text is kept.

type Commit

type Commit struct {
	Project string    `json:"project"`
	SHA     string    `json:"sha"`
	Title   string    `json:"title"`
	Message string    `json:"message"`
	At      time.Time `json:"at"`
}

Commit is a commit of a code host; only the head of the message is kept.

type CommitHost

type CommitHost interface {
	RevertCommits(ctx context.Context, since time.Time) ([]Commit, error)
	SkillCommits(ctx context.Context, since time.Time) ([]SkillCommit, error)
}

CommitHost is a source of commits, next to the merged requests of a CodeHost: the revert commits of every project and the commits that changed a skill. A host that cannot list them leaves the interface unimplemented.

type CostFn

type CostFn func(ctx context.Context, day string, loc *time.Location) (float64, bool)

CostFn gives the cost in US dollars of the work done on a day (YYYY-MM-DD in loc), false when it is not known.

func RollupCost

func RollupCost(ctx context.Context, st store.Store, orgID string, from, to time.Time, loc *time.Location) (CostFn, error)

RollupCost reads the organization's spend of [from, to) from usage_rollup_hour once and answers per day of loc. The money is the list price in US dollars (what the same calls cost on API prices): it needs no account and is the same whoever pays, so a subscription's fee in another currency never mixes in. A day without a single call is unknown, not zero, so the figure is never invented; calls the hub could not price yet add nothing to the sum.

type Day

type Day struct {
	Day     string   `json:"day"`
	MRs     int      `json:"mrs"`
	Reverts int      `json:"reverts"`
	CostUSD *float64 `json:"costUsd"`
	// USDPerMR is the cost of the day's work over the requests merged that day; null when either is unknown.
	USDPerMR *float64 `json:"usdPerMr"`
}

Day is one calendar day of the organization's time zone.

type GitLab

type GitLab struct {
	URL    string
	Groups []string
	Token  string
	Client *http.Client
	// SkillsProject is the project (group/name) whose SKILL.md files are the skills; empty reads no skill commits.
	SkillsProject string
}

GitLab is a CodeHost over the GitLab REST API: the merged requests of some groups.

func NewGitLab

func NewGitLab(rawURL string, groups []string, token string) *GitLab

NewGitLab returns the provider; nil when the source is not configured.

func (*GitLab) MergedMRs

func (g *GitLab) MergedMRs(ctx context.Context, since time.Time) ([]MR, error)

MergedMRs lists what was merged in the groups since a time, however the request was created. A group that fails does not hold back the others; the first error is returned together with what was read.

func (*GitLab) RevertCommits

func (g *GitLab) RevertCommits(ctx context.Context, since time.Time) ([]Commit, error)

RevertCommits lists the revert commits of every project of the groups since a time. A project that fails does not hold back the others; the first error is returned together with what was read.

func (*GitLab) SkillCommits

func (g *GitLab) SkillCommits(ctx context.Context, since time.Time) ([]SkillCommit, error)

SkillCommits lists the commits that touched a SKILL.md of the skills project, merges left out. Nothing is read when no skills project is configured.

type MR

type MR struct {
	Project   string    `json:"project"`
	IID       int       `json:"iid"`
	Title     string    `json:"title"`
	Branch    string    `json:"branch"`
	Author    string    `json:"author"`
	MergedBy  string    `json:"mergedBy"`
	CreatedAt time.Time `json:"createdAt"`
	MergedAt  time.Time `json:"mergedAt"`
	// Approved says somebody other than the author approved it; ForeignNotes that somebody else commented.
	Approved     bool `json:"approved"`
	ForeignNotes bool `json:"foreignNotes"`
}

MR is a merged merge request as a code-host provider reports it.

func (MR) Key

func (m MR) Key() string

Key is the stable identity of the request across passes.

type Marker

type Marker struct {
	At     string  `json:"at"`
	Kind   string  `json:"kind"`
	Title  string  `json:"title"`
	Detail *string `json:"detail"`
}

Marker is IEffMarker.

type Me

type Me struct {
	Person    string      `json:"person"`
	From      string      `json:"from"`
	To        string      `json:"to"`
	Attention MeAttention `json:"attention"`
	Limit     MeLimit     `json:"limit"`
	Sessions  []MeSession `json:"sessions"`
}

Me is IEffMe.

func ComputeMe

func ComputeMe(ctx context.Context, st store.Store, org, user, name string, from, to time.Time, loc *time.Location) (Me, error)

ComputeMe is the personal tab: how the person's attention is spent and their newest sessions.

type MeAttention

type MeAttention struct {
	ReplyP50Min    *float64 `json:"replyP50Min"`
	ReplyP90Min    *float64 `json:"replyP90Min"`
	AutonomyP90Min *float64 `json:"autonomyP90Min"`
	AskWaitP90Min  *float64 `json:"askWaitP90Min"`
	ParallelP90    *float64 `json:"parallelP90"`
	Questions      int      `json:"questions"`
	Interrupts     int      `json:"interrupts"`
}

MeAttention is how much the person's attention costs the agents.

type MeLimit

type MeLimit struct {
	WeekUsedPct *float64 `json:"weekUsedPct"`
	EvalWeekPct float64  `json:"evalWeekPct"`
	ResetsAt    *string  `json:"resetsAt"`
}

MeLimit is the subscription limit: the fullest seven-day window of Claude among the person's machines that reported lately (machine_provider_limits); empty when none did.

type MeSession

type MeSession struct {
	FileID        string    `json:"fileId"`
	SessionUUID   *string   `json:"sessionUuid"`
	Title         *string   `json:"title"`
	Channel       string    `json:"channel"`
	StartedAt     *string   `json:"startedAt"`
	EndedAt       *string   `json:"endedAt"`
	CostUSD       float64   `json:"costUsd"`
	MRs           int       `json:"mrs"`
	ModelCalls    int64     `json:"modelCalls"`
	PeakCtx       *float64  `json:"peakCtx"`
	AvgCtx        *float64  `json:"avgCtx"`
	Cardio        []float64 `json:"cardio"`
	Over250kShare *float64  `json:"over250kShare"`
}

MeSession is IEffSession.

type Metric

type Metric struct {
	ID      string   `json:"id"`
	Title   string   `json:"title"`
	What    string   `json:"what"`
	How     string   `json:"how"`
	Unit    string   `json:"unit"` // usd | count
	Better  string   `json:"better"`
	Value   *float64 `json:"value"`
	Prev    *float64 `json:"prev"`
	Target  *float64 `json:"target"`
	Trend   *float64 `json:"trendPct"`
	Verdict string   `json:"verdict"` // good | bad | flat | nodata
	Link    struct {
		Tab string `json:"tab"`
	} `json:"link"`
}

Metric is one row of the screen's «where we stand» list (IEffSummaryMetric in web/app/types/efficiency.ts).

type Overview

type Overview struct {
	Scope     string            `json:"scope"`
	From      string            `json:"from"`
	To        string            `json:"to"`
	Days      []OverviewDay     `json:"days"`
	Markers   []Marker          `json:"markers"`
	Channels  []OverviewChannel `json:"channels"`
	Totals    OverviewTotals    `json:"totals"`
	ScannedAt *string           `json:"scannedAt"`
}

Overview is the answer of the overview endpoint.

func ComputeOverview

func ComputeOverview(ctx context.Context, st store.Store, org, user string, from, to time.Time, loc *time.Location) (Overview, error)

ComputeOverview is the overview of [from, to) for the whole organization or one person (when user is set).

func ComputeOverviewForScope

func ComputeOverviewForScope(ctx context.Context, st store.Store, org string, f OverviewFilter, from, to time.Time, loc *time.Location) (Overview, error)

ComputeOverviewForScope is the overview of [from, to) filtered to f: per day the spend and calls of the rollup, the sessions and their metrics, and the requests merged.

type OverviewChannel

type OverviewChannel struct {
	Channel  string  `json:"channel"`
	Sessions int     `json:"sessions"`
	CostUSD  float64 `json:"costUsd"`
	MRs      int     `json:"mrs"`
}

OverviewChannel is IEffChannel.

func SessionChannels

func SessionChannels(ctx context.Context, st store.Store, ss []store.AgentSession) ([]OverviewChannel, error)

SessionChannels totals the list-price cost (including subagents) and MRs of the supplied top-level sessions by launch channel.

type OverviewDay

type OverviewDay struct {
	Day                 string   `json:"day"`
	CostUSD             float64  `json:"costUsd"`
	Sessions            int      `json:"sessions"`
	ModelCalls          int64    `json:"modelCalls"`
	MRs                 int      `json:"mrs"`
	AvgCtx              *float64 `json:"avgCtx"`
	FirstCtxP50         *float64 `json:"firstCtxP50"`
	CarryShare          *float64 `json:"carryShare"`
	ToolErrorRate       *float64 `json:"toolErrorRate"`
	GuardStopRate       *float64 `json:"guardStopRate"`
	RedGateRate         *float64 `json:"redGateRate"`
	SubagentSonnetShare *float64 `json:"subagentSonnetShare"`
	GateVisibleShare    *float64 `json:"gateVisibleShare"`
	HumanReplyP90Min    *float64 `json:"humanReplyP90Min"`
	SleepHours          float64  `json:"sleepHours"`
	CIPollsPerMR        *float64 `json:"ciPollsPerMr"`
}

OverviewDay is IEffDay.

type OverviewFilter

type OverviewFilter struct {
	UserID  string
	SpaceID string
	TeamID  string
}

OverviewFilter narrows ComputeOverviewForScope to one person, one tenant, or one team inside the organization.

type OverviewTotals

type OverviewTotals struct {
	CostUSD      float64  `json:"costUsd"`
	Sessions     int      `json:"sessions"`
	MRs          int      `json:"mrs"`
	CarryTokens  int64    `json:"carryTokens"`
	ResultTokens int64    `json:"resultTokens"`
	ReadingShare *float64 `json:"readingShare"`
}

OverviewTotals is the totals of IEffOverview.

type Progress

type Progress struct {
	Issue          string    `json:"issue"`
	LastActivityAt time.Time `json:"lastActivityAt"`
}

Progress is an issue in progress and the time of its last comment or change of State.

type ProgressTracker

type ProgressTracker interface {
	InProgress(ctx context.Context) ([]Progress, error)
}

ProgressTracker is a Tracker that can also list the issues in progress.

type Pulse

type Pulse struct {
	Week     string        `json:"week"` // Monday of the current week in the organization's time zone
	Answered bool          `json:"answered"`
	Answers  []PulseAnswer `json:"answers"`
}

Pulse is the answer of GET .../efficiency/pulse (IEffPulse in web/app/types/efficiency.ts). Only the person's own answers are ever read: nobody else, an administrator included, gets an endpoint to see them.

type PulseAnswer

type PulseAnswer struct {
	Week     string `json:"week"`
	Speed    int    `json:"speed"`
	Quality  int    `json:"quality"`
	Friction int    `json:"friction"`
}

PulseAnswer is one week of a person's pulse.

type Regression

type Regression struct {
	ID              string   `json:"id"`
	BatchID         string   `json:"batchId"`
	Metric          string   `json:"metric"`
	Baseline        float64  `json:"baseline"`
	Observed        float64  `json:"observed"`
	Band            int      `json:"band"`
	FingerprintFrom string   `json:"fingerprintFrom"`
	FingerprintTo   string   `json:"fingerprintTo"`
	Diff            []string `json:"diff"`
	State           string   `json:"state"`
	SeenAt          *string  `json:"seenAt"`
	CreatedAt       string   `json:"createdAt"`
}

Regression is one alert of GET .../efficiency/regressions: a metric that left its band after a change of the harness.

type Service

type Service struct {
	DB *store.DB
	// Gate is the guard of an organization's route (orgs.Service.OrgGate).
	OrgGate  func(tenant.Handler) httpx.Handler
	Features features.Gate
	// Switches decides per person whether the overview and the personal tab come from the hub (SwitchOverview).
	Switches switches.Gate
	Cost     CostFn
	Now      func() time.Time
}

Service serves the figures of the screen. Everything is behind the organization flag features.Efficiency.

func (*Service) Mount

func (s *Service) Mount(mux *http.ServeMux)

Mount registers the endpoints.

type SkillCommit

type SkillCommit struct {
	SHA   string    `json:"sha"`
	Title string    `json:"title"`
	At    time.Time `json:"at"`
}

SkillCommit is a commit that touched a skill of the skills repository.

type SourceState

type SourceState struct {
	Source string `json:"source"`
	OK     bool   `json:"ok"`
	Error  string `json:"error,omitempty"`
	Facts  int    `json:"facts"`
	OKAt   *int64 `json:"okAt"`
	At     int64  `json:"collectedAt"`
}

SourceState is how a collector stands, for the screen's «data is late» marks.

type Summary

type Summary struct {
	Scope     string        `json:"scope"`
	From      string        `json:"from"`
	To        string        `json:"to"` // the last day of the period, inclusive
	Days      []Day         `json:"days"`
	Totals    Totals        `json:"totals"`
	Metrics   []Metric      `json:"metrics"`
	Fixes     []struct{}    `json:"fixes"`
	Changes   []struct{}    `json:"changes"`
	ScannedAt *string       `json:"scannedAt"`
	Sources   []SourceState `json:"sources"`
}

Summary is the answer of the summary endpoint.

The fields scope, metrics, fixes, changes and scannedAt (and sessions, readingShare in totals) are what the screen's types/efficiency.ts IEffSummary reads, so the screen needs no adapter. The hub has no transcript scanner yet: fixes and changes are empty and sessions is 0 until one feeds them.

func Compute

func Compute(ctx context.Context, st store.Store, from, to time.Time, loc *time.Location, cost CostFn) (Summary, error)

Compute counts the merged requests of [from, to) per day and divides the cost by them.

The denominator is every request the code host reports as merged, whoever created it and however: the form, a push option or the host's API. It is never the requests sessions mention. Agents create and merge requests through the API, no session notices them, and counting by what sessions saw made the money per request read several times too high (an earlier scanner counted 120 requests in a week when 713 had merged). A revert is not a delivered task: it is counted on its own and kept out of the denominator.

type Totals

type Totals struct {
	MRs          int      `json:"mrs"`
	Reverts      int      `json:"reverts"`
	CostUSD      *float64 `json:"costUsd"`
	USDPerMR     *float64 `json:"usdPerMr"`
	Sessions     int      `json:"sessions"`
	ReadingShare *float64 `json:"readingShare"`
}

Totals are the sums over the period.

type Tracker

type Tracker interface {
	Comments(ctx context.Context, from, to time.Time) ([]Comment, error)
}

Tracker is a source of issue comments.

type YouTrack

type YouTrack struct {
	URL     string
	Token   string
	Project string
	Client  *http.Client
}

YouTrack is a Tracker over the YouTrack REST API, restricted to one project.

func NewYouTrack

func NewYouTrack(rawURL, token, project string) *YouTrack

NewYouTrack returns the provider; nil when the source is not configured.

func (*YouTrack) Comments

func (y *YouTrack) Comments(ctx context.Context, from, to time.Time) ([]Comment, error)

Comments lists the comments added to the project's issues within [from, to).

func (*YouTrack) InProgress

func (y *YouTrack) InProgress(ctx context.Context) ([]Progress, error)

InProgress lists the project's issues in the State «In Progress» with the time of their last comment or State change.

Jump to

Keyboard shortcuts

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