team

package
v0.210.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 35 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 team is the laptop side of Caprock Teams (ADR-120): when, and only when, the user has enrolled this computer in a Caprock Teams server with `caprock team join`, it sends that server per-session, per-hour usage counters (teamapi.UsageReport) and nothing else.

Without an enrolment it is inert: Enrolled reports false, the daemon does not start the Service, and nothing of Teams runs, shows or calls out. That is the owner's rule for Teams in the free product — it concerns only Teams, visibly — and inert_test.go holds it.

Index

Constants

View Source
const Backfill = 35 * 24 * time.Hour

Backfill is how far back the first report reaches. Team week compares a week with the median of the four before it, so five weeks; the join screen says so before anything is sent.

View Source
const DefaultTick = 5 * time.Minute

DefaultTick is how often the daemon looks for new turns to report. A design choice, not a measurement: a lead reads Team week daily, and five minutes keeps "last report" honest without a request per turn.

View Source
const GivenFile = "team-rules-given.json"

GivenFile records which rules each session was given, so "why did the agent do that" has an answer on this computer. The newest GivenKeep.

View Source
const GivenKeep = 500

GivenKeep is how many sessions GivenFile remembers.

View Source
const LastSentFile = "team-last-sent.json"

LastSentFile keeps the exact bytes of the last report the server accepted, so `caprock team preview --last` shows what already left.

View Source
const RulesFile = "team-rules.json"

RulesFile holds the rules last taken from the server, 0600.

View Source
const RulesMaxRunes = 2000

RulesMaxRunes caps the rules block at session start: whole rules are added until the next would not fit, and the rest are named as left out. Sized beside 2nd Brain's own caps (1,200 + 1,500 + 700 runes), which reports of large SessionStart replies being dropped keep small.

View Source
const StateFile = "team.json"

StateFile holds the enrolment in the data directory, 0600. Its presence is the one switch: no file, no Teams.

Variables

View Source
var ErrNotEnrolled = errors.New("this computer is not enrolled in a Caprock Teams server")

ErrNotEnrolled is returned when there is no team.json.

View Source
var SecretItem = secret.Item{
	Service: "dev.caprock.teams",
	Label:   "Caprock Teams machine secret",
	File:    "team-machine-secret",
	Noun:    "Caprock Teams machine secret",
}

SecretItem is the per-machine secret the server issued at enrolment, kept in the OS secret store (else a 0600 file), never in team.json and never logged.

Functions

func CheckServerURL

func CheckServerURL(raw string) (string, error)

CheckServerURL accepts https, and http only to a loopback address (a server on the same box, tests). It returns the URL without a trailing slash.

func Enrolled

func Enrolled(dataDir string) bool

Enrolled reports whether this computer has joined a Caprock Teams server. It only looks for the file; it never reads the network.

func ExcludedHere

func ExcludedHere(s State, repo, dir string) bool

ExcludedHere reports whether the user excluded repo (a web URL) or dir from the team on this computer.

func ForSession

func ForSession(ctx context.Context, dataDir, sessionID, cwd, root string, g Git) string

ForSession is the rules block for a new session in cwd's repository, the part an agent is given at start. It records what was given. Not enrolled, Receive off, the repository excluded, or no rules: "".

func Forget

func Forget(ctx context.Context, dataDir string, sec secret.Store) error

Forget removes every trace of the enrolment on this computer: the state, the last-sent copy, the team rules and their record, and the machine secret.

func IsRevoked

func IsRevoked(err error) bool

IsRevoked reports whether err says this machine's secret is no longer valid.

func Leave

func Leave(ctx context.Context, dataDir string, sec secret.Store, keepServer bool, mk func(base, caFile, secret string) (*Client, error)) (serverErr error, err error)

Leave is the leave the CLI and the dashboard share.

func NewMachineID

func NewMachineID() string

NewMachineID makes the random id this computer is known by to one team. It is not the relay identity, the 2nd Brain id or a hardware id, so a team server cannot link this computer to anything else it might see.

func Pages

func Pages(s State, b Batch, version string) []teamapi.UsageReport

Pages splits a batch into the reports that carry it, at most teamapi.MaxBuckets buckets each. `caprock team preview` prints exactly these; the Service sends exactly these.

func RulesFor

func RulesFor(all []teamapi.Rule, repo string) []teamapi.Rule

RulesFor returns the rules that apply in repo (a web URL; "" outside a repository): rules naming it first, then the team-wide ones, each group newest first.

func RulesText

func RulesText(teamName string, rules []teamapi.Rule, max int) (string, []teamapi.Rule)

RulesText is the block an agent is given, and the rules it holds. Whole rules are added until the next would pass max runes.

func Save

func Save(dataDir string, s State) error

Save writes the enrolment, 0600.

func Speaks

func Speaks(h teamapi.Hello, f string) bool

Speaks reports whether h serves contract major 1 and the feature f.

func StatusOf

func StatusOf(s State, version string) teamapi.Status

StatusOf is the machine status sent with enrolment and every report.

Types

type Batch

type Batch struct {
	Buckets []teamapi.Bucket
	Ceiling int64 // the highest events.id these buckets account for
	Skipped Skipped
}

Batch is what one round would send: the buckets, and the events.id the cursor moves to once the server has accepted all of them.

func Build

func Build(ctx context.Context, q store.Querier, p Params, s State) (Batch, error)

Build collects the buckets touched since s.Cursor: every (session, hour) that gained an assistant turn after the cursor is aggregated again in full, so a turn that arrives late for an hour already reported replaces that hour's bucket rather than adding a second one. The first round (cursor 0) reaches back Backfill. It reads only; it never writes and never calls out.

type Client

type Client struct {
	Base   string
	Secret string // the machine secret; empty before enrolment
	HTTP   *http.Client
}

Client talks to one Caprock Teams server. It sends only teamapi types.

func NewClient

func NewClient(base, caFile, secret string) (*Client, error)

NewClient builds a client for base, trusting caFile's certificates in addition to the system's when it is set.

func (*Client) Enrol

Enrol trades the team token for this machine's secret.

func (*Client) FetchRules

func (c *Client) FetchRules(ctx context.Context, have string) (teamapi.RulesResponse, bool, bool, error)

FetchRules asks the server for its rules unless they did not change. It reports whether the server has the feature at all (a 404 means it does not).

func (*Client) Hello

func (c *Client) Hello(ctx context.Context) (teamapi.Hello, error)

Hello asks the server who it is and what it speaks.

func (*Client) Leave

func (c *Client) Leave(ctx context.Context) error

Leave asks the server to delete this machine's rows.

func (*Client) Report

Report sends one page of buckets.

type Commit

type Commit struct {
	SHA string
	At  time.Time
}

Commit is one commit a session made: its hash and its commit time.

type Controller

type Controller struct {
	DataDir    string
	Store      *store.Store
	Table      *cost.Table
	Secret     secret.Store
	Version    string
	Log        *slog.Logger
	LoopK      int
	LoopWindow time.Duration
	// Go runs f as a background task the daemon waits for on shutdown.
	Go func(f func())
	// Git and NewClient replace the real ones in tests.
	Git       Git
	NewClient func(base, caFile, secret string) (*Client, error)
	// contains filtered or unexported fields
}

Controller is the daemon's handle on Teams: it starts the Service when this computer joins and stops it when it leaves, without a restart, and answers the dashboard's Teams section. On a computer that never joined, Reload starts nothing and every other method returns ErrNotEnrolled.

func (*Controller) Leave

func (c *Controller) Leave(ctx context.Context, keepServer bool) (serverErr error, err error)

Leave asks the server to delete this computer's data (unless keepServer), forgets the enrolment here and stops the Service. serverErr says why the server could not be asked; the local leave happens regardless.

func (*Controller) Patch

func (c *Controller) Patch(_ context.Context, p Patch) (View, error)

Patch applies p to the enrolment and returns it.

func (*Controller) Preview

func (c *Controller) Preview(ctx context.Context) (Preview, error)

Preview builds the next report from the database, the way a round would.

func (*Controller) Reload

func (c *Controller) Reload(_ context.Context) (bool, error)

Reload starts or stops the Service to match team.json. It reports whether the Service runs afterwards.

func (*Controller) Running

func (c *Controller) Running() bool

Running reports whether the Service runs.

func (*Controller) Start

func (c *Controller) Start(ctx context.Context)

Start remembers the daemon's context and starts the Service if this computer has joined. Call once at boot.

func (*Controller) View

func (c *Controller) View(_ context.Context) (View, error)

View returns the enrolment, or ErrNotEnrolled.

type Git

type Git interface {
	Remote(ctx context.Context, root string) string // web URL, credentials stripped; "" when none
	Email(ctx context.Context, root string) string  // git config user.email; "" when none
	// Commits lists the commits authored by email in [from, to), by commit
	// time: the hash and when it was made. Hashes only — never a message.
	Commits(ctx context.Context, root, email string, from, to time.Time) []Commit
}

Git reads a repository's remote URL and user.email. The daemon and the CLI use gitRunner; tests replace it.

func RealGit

func RealGit() Git

RealGit reads repositories with the git on PATH.

type Given

type Given struct {
	SessionID string   `json:"session_id"`
	At        int64    `json:"at"` // unix ms
	Repo      string   `json:"repo,omitempty"`
	Rules     []string `json:"rules"` // "id@revision"
}

Given is one session's record in GivenFile.

func GivenTo

func GivenTo(dataDir, sessionID string) (Given, bool)

GivenTo returns what a session was given; ok false when nothing.

type Params

type Params struct {
	Table      *cost.Table // pricing, for re-reads and loops; nil leaves them unpriced
	Git        Git
	LoopK      int           // the loop detector's settings (config loop_k)
	LoopWindow time.Duration // and loop_t_minutes
	Now        time.Time
}

Params are what Build reads besides the database and the enrolment.

type Patch

type Patch struct {
	Report     *bool     `json:"report,omitempty"`
	Receive    *bool     `json:"receive,omitempty"`
	HideEmail  *bool     `json:"hide_email,omitempty"`
	HideBranch *bool     `json:"hide_branch,omitempty"`
	HideDir    *bool     `json:"hide_dir,omitempty"`
	Exclude    *[]string `json:"exclude,omitempty"`
}

Patch changes switches and exclusions; a nil field is left as it is.

func (Patch) Apply

func (p Patch) Apply(s *State)

Apply changes s by p.

type Preview

type Preview struct {
	Summary Summary               `json:"summary"`
	Pages   []teamapi.UsageReport `json:"pages"`
}

Preview is the next report: its summary and the exact pages.

type Rules

type Rules struct {
	Version   string         `json:"version"`
	FetchedAt int64          `json:"fetched_at"` // unix ms
	Rules     []teamapi.Rule `json:"rules"`
}

Rules is what RulesFile holds.

func LoadRules

func LoadRules(dataDir string) (Rules, error)

LoadRules reads RulesFile; none is an empty set.

type ServerError

type ServerError struct {
	Status int
	Body   teamapi.Error
}

ServerError is a non-2xx answer.

func (*ServerError) Error

func (e *ServerError) Error() string

type Service

type Service struct {
	DataDir string
	Store   *store.Store
	Table   *cost.Table
	// LoopK and LoopWindow are the loop detector's settings (config).
	LoopK      int
	LoopWindow time.Duration
	Secret     secret.Store
	Git        Git
	Version    string
	Log        *slog.Logger
	Now        func() time.Time
	Tick       time.Duration
	// NewClient builds the client; tests replace it.
	NewClient func(base, caFile, secret string) (*Client, error)
}

Service sends usage reports while this computer is enrolled with reporting on. The daemon starts it only when Enrolled(DataDir) is true.

func (*Service) Round

func (s *Service) Round(ctx context.Context) error

Round sends whatever changed since the cursor, page by page, and moves the cursor once every page was accepted. The server upserts each bucket, so a round cut short is simply sent again.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

Run reports every Tick until ctx ends. It returns at once when this computer is not enrolled: Teams is inert without an enrolment.

type Skipped

type Skipped struct {
	Personal int `json:"personal"` // sessions in a folder labelled Personal (ADR-091)
	Excluded int `json:"excluded"` // sessions in an excluded repository or folder
}

Skipped counts what was left out on purpose, for `caprock team preview`.

type State

type State struct {
	Server    string `json:"server"`     // base URL, https (http only to loopback)
	Team      string `json:"team"`       // the team's name, as the server gave it
	MachineID string `json:"machine_id"` // random, made at enrolment, for this team only
	CAFile    string `json:"ca_file,omitempty"`
	JoinedAt  int64  `json:"joined_at"` // unix ms

	Report  bool `json:"report"`  // send usage reports
	Receive bool `json:"receive"` // take team rules (contract 1.1); memories later

	HideEmail  bool     `json:"hide_email,omitempty"`  // leave the Git email out
	HideBranch bool     `json:"hide_branch,omitempty"` // send branch names hashed
	HideDir    bool     `json:"hide_dir,omitempty"`    // send folder names hashed
	Exclude    []string `json:"exclude,omitempty"`     // repository URLs or folder paths never reported

	Cursor   int64  `json:"cursor"`              // events.id up to which turns were reported
	LastSent int64  `json:"last_sent,omitempty"` // unix ms of the last accepted report
	LastErr  string `json:"last_error,omitempty"`
}

State is the enrolment. Every switch and exclusion is here, on the laptop: the server cannot widen what leaves (ADR-120 §1).

func Load

func Load(dataDir string) (State, error)

Load reads the enrolment from dataDir. ErrNotEnrolled when there is none.

func (State) Hidden

func (s State) Hidden() []string

Hidden lists which Hide* options are on, for teamapi.Status.

type Summary

type Summary struct {
	Buckets   int      `json:"buckets"`
	Sessions  int      `json:"sessions"`
	Repos     []string `json:"repos"`
	CostUSD   float64  `json:"cost_usd"`
	FirstHour int64    `json:"first_hour,omitempty"` // unix seconds
	LastHour  int64    `json:"last_hour,omitempty"`
	Commits   int      `json:"commits"`
	Loops     int      `json:"loops"`
	Skipped   Skipped  `json:"skipped"`
}

Summary says in figures what a batch holds.

func Summarize

func Summarize(b Batch) Summary

Summarize sums a batch.

type View

type View struct {
	Team       string   `json:"team"`
	Server     string   `json:"server"`
	JoinedAt   int64    `json:"joined_at"`
	Report     bool     `json:"report"`
	Receive    bool     `json:"receive"`
	HideEmail  bool     `json:"hide_email"`
	HideBranch bool     `json:"hide_branch"`
	HideDir    bool     `json:"hide_dir"`
	Exclude    []string `json:"exclude"`
	LastSent   int64    `json:"last_sent,omitempty"`
	LastError  string   `json:"last_error,omitempty"`
	Running    bool     `json:"running"`
	Rules      int      `json:"rules"`              // team rules on this computer now
	RulesAt    int64    `json:"rules_at,omitempty"` // when they were last taken, unix ms
}

View is what the dashboard shows of the enrolment. No secret.

Jump to

Keyboard shortcuts

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