state

package
v0.47.2 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package state is the session state entry of the manager digest (card 162, .context/plans/manager-digest.md §5.1): one JSON file per session that the session's own machine writes into the repository's state folder — the folder the team file's `sync.state` names, kept in step with every teammate's checkout by folder sync — carrying the facts the hooks know (member, session name, repository, branch, times, the commits made since the session started) and what the model publishes on purpose (its doing lines, its notes). Nothing from the transcript: no prompt, no answer, no tool call, no model, no token count.

Every entry has two copies. The CANONICAL one lives under Brigade's private state directory, 0600, and is the one the writer reads back and adds to; every write projects it into the folder, whole-file, so an entry a teammate's machine deleted from the folder is healed at the writer's next hook, and one writer per file means the sync engine never produces a conflict copy. A folder entry is a teammate's text: the readers here cap and sanitise every string of it and skip a file whose name, size or shape is not an entry's.

Retention (ruling 2, 2026-10-29): a live entry while it lives, an ended one EndedRetention after its end; an entry whose session never ended — its machine never came back — StaleRetention after its last write. The writer prunes its own canonical entries at session start (Store.PruneOwn) and any watcher prunes the folder (PruneFolder).

Index

Constants

View Source
const (
	// MaxOptions caps the options offered; MaxOptionChars each one;
	// MaxQuestionChars the question and MaxOutcomeChars the outcome
	// (the note's cap, in code points).
	MaxOptions       = 8
	MaxOptionChars   = 200
	MaxQuestionChars = MaxNoteChars
	MaxOutcomeChars  = MaxNoteChars
	// DecisionRetention is how long a closed decision stays in the
	// folder; an open one stays for good (ruling 2).
	DecisionRetention = 30 * 24 * time.Hour
)

The caps of a decision.

View Source
const (
	SentSlack   = "slack"
	SentEmail   = "email"
	SentSession = "session"
)

The ways a decision's ask went out, Decision.Sent: through the Slack or the mail gateway, to the addressee's own session when no gateway was on the roster, or not at all.

View Source
const (
	// ReportsVersion is the file's own version: 2 is the subscriber
	// list; 1, the manager of 0.43, is read as one subscriber.
	ReportsVersion = 2
	// MaxSubscribers caps the list; MaxRecipients a subscriber's
	// recipients; MaxRecipientChars one recipient (a handle, a channel,
	// an address).
	MaxSubscribers    = 64
	MaxRecipients     = 8
	MaxRecipientChars = 256
	// DefaultEvery is the period when a subscriber sets none.
	DefaultEvery = 24 * time.Hour
	// OnlyMine is the one filter: the digest's decision sections list
	// only the decisions addressed to the subscriber; the contribution
	// sections stay the team's.
	OnlyMine = "mine"
)

The reports file's bounds.

View Source
const (
	RecipientSlack = "slack"
	RecipientEmail = "email"
)

The two kinds of recipient, by shape.

View Source
const (
	SessionsDir  = "sessions"
	DecisionsDir = "decisions"
	DigestsDir   = "digests"
	ReportsFile  = "reports.json"
)

The folder's layout (plan §5.1): the entries, the decisions, the producer's marker and the manager's settings.

View Source
const (
	// MaxEntryBytes caps a file a reader will decode.
	MaxEntryBytes = 64 << 10
	// MaxCommits, MaxDoing and MaxNotes cap the three lists: the newest
	// stay.
	MaxCommits = 100
	MaxDoing   = 50
	MaxNotes   = 20
	// MaxSubjectChars caps a commit subject; MaxDoingChars a doing line
	// (the wire's own cap, protocol.MaxDescriptionChars); MaxNoteChars a
	// note (plan §5.2: `brigade note` reads at most 1,000 bytes); the
	// others the short fields. All in code points.
	MaxSubjectChars = 200
	MaxDoingChars   = protocol.MaxDescriptionChars
	MaxNoteChars    = 1000
	MaxShortChars   = 128
)

The caps an entry keeps to, whoever wrote it.

View Source
const (
	EndedRetention = 14 * 24 * time.Hour
	StaleRetention = 14 * 24 * time.Hour
)

The retention terms (plan §5.1, ruling 2).

View Source
const Version = 1

Version is the entry shape this package writes and reads.

Variables

This section is empty.

Functions

func CheckID

func CheckID(id string) error

CheckID reports whether id can name an entry file: the by-native map's own rule (letters, digits, dash, underscore, at most 80), so a session id from any adapter is a safe path component or is refused.

func DecisionPath

func DecisionPath(folder, id string) string

DecisionPath is <folder>/decisions/<id>.json, for an id CheckID accepts.

func EntryPath

func EntryPath(folder, id string) string

EntryPath is <folder>/sessions/<id>.json, for an id CheckID accepts.

func LabelStem added in v0.44.0

func LabelStem(label string) string

LabelStem is the file stem of a label: its letters and digits in lower case, every other run of characters one dash, cut at labelStemChars, then a dash and six hex digits of the lower-cased label's hash — so "rjae@example.com" is "rjae-example-com-3f2a9c", two labels that slug alike stay apart, and the stem passes CheckID.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal and Unmarshal are the one JSON spelling of every file of the folder, the digest's marker included.

func NewDecisionID

func NewDecisionID(now time.Time) (string, error)

NewDecisionID is a fresh id, `d-<YYYYMMDD>-<6 hex>`: readable in a message, unique enough for a team's folder, and a path component CheckID accepts.

func PruneFolder

func PruneFolder(folder string, now time.Time) int

PruneFolder removes every folder entry and decision past its term at now and reports how many: a teammate's machine that never came back to end its session, or to prune its own, is covered by whichever watcher runs.

func ReadFolderFile

func ReadFolderFile(path string) ([]byte, error)

ReadFolderFile reads one file of the folder — a teammate's — within the rules every folder read keeps: a regular file, no symlink followed, at most MaxEntryBytes. The digest's marker is read through it too.

func RecipientKind

func RecipientKind(r string) string

RecipientKind says which gateway carries a recipient: RecipientSlack for `@name` or `#channel`, RecipientEmail for an address, "" for a shape neither gateway takes.

func ReportsPath

func ReportsPath(folder string) string

ReportsPath is <folder>/reports.json.

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal decodes what Marshal wrote.

func ValidDate

func ValidDate(s string) bool

ValidDate reports whether s is a `by` date, YYYY-MM-DD.

func WriteReports

func WriteReports(folder string, r *Reports) error

WriteReports writes the file into the folder, atomically, as version ReportsVersion after Sanitize: `brigade report subscribe` and `unsubscribe` are its writers.

Types

type Closer

type Closer struct {
	Member      string `json:"member,omitzero"`
	SessionName string `json:"session_name"`
	SessionID   string `json:"session_id"`
}

A Closer is who closed a decision.

type Commit

type Commit struct {
	Hash    string    `json:"hash"`
	Subject string    `json:"subject"`
	Card    int       `json:"card,omitzero"`
	At      time.Time `json:"at"`
	Made    bool      `json:"made,omitzero"`
}

A Commit is one commit the session made: its hash, its subject, the card number the subject starts with (0 for none) and its time.

Made says HEAD's reflog in the session's own checkout shows the commit made there (card 172), not pulled in: the same author's commit reaches every checkout that pulls it, and the digest credits a commit some entry made to that entry alone. False when the reflog says otherwise or could not be read, and in every entry before 0.45.1.

type Decision

type Decision struct {
	Version  int    `json:"version"`
	ID       string `json:"id"`
	Question string `json:"question"`
	// To is the roster label of the person the question is for (card
	// 167; absent in a 0.43 decision, which was the manager's).
	To string `json:"to,omitzero"`
	// Options are the answers offered, Default the one taken when the
	// addressee says nothing, By the date an answer is needed by
	// (YYYY-MM-DD), Card the card the question belongs to; each optional.
	Options []string `json:"options"`
	Default string   `json:"default,omitzero"`
	By      string   `json:"by,omitzero"`
	Card    int      `json:"card,omitzero"`
	// Member, SessionName, SessionID and Repository say who asked.
	Member      string `json:"member,omitzero"`
	SessionName string `json:"session_name"`
	SessionID   string `json:"session_id"`
	Repository  string `json:"repository,omitzero"`
	// Sent is how the ask reached the addressee (SentSlack, SentEmail,
	// SentSession), "" when it did not and the next digest carries it;
	// SentTo the recipient it went to (a Slack handle or channel, an
	// address, a session id).
	Sent   string `json:"sent,omitzero"`
	SentTo string `json:"sent_to,omitzero"`
	// CreatedAt is the ask; ClosedAt, Outcome and ClosedBy the close, zero
	// and absent while open.
	CreatedAt time.Time `json:"created_at"`
	ClosedAt  time.Time `json:"closed_at,omitzero"`
	Outcome   string    `json:"outcome,omitzero"`
	ClosedBy  *Closer   `json:"closed_by,omitzero"`
	UpdatedAt time.Time `json:"updated_at"`
}

A Decision is one question put to a teammate.

func ReadDecision

func ReadDecision(folder, id string) (*Decision, error)

ReadDecision reads one decision from the folder, sanitised — the copy another session of the member reads to close it. A missing one satisfies errors.Is(err, fs.ErrNotExist).

func ReadDecisions

func ReadDecisions(folder string) []*Decision

ReadDecisions reads every decision in the folder, each sanitised, with the strictness of ReadFolder; the order is the directory's.

func (*Decision) Expired

func (d *Decision) Expired(now time.Time) bool

Expired reports whether the decision is past its term: closed more than DecisionRetention ago. An open one never is.

func (*Decision) Lines

func (d *Decision) Lines() []string

Lines is the labelled shape of a decision, the same in the ask the gateway carries and in the digest (plan §5.2): the id and the question first, then whom it is for, who asked and when, the options, the default, the date, the card; for a closed one the close and its outcome. Plain text, a stable label at the start of each line, nothing a reader has to parse.

func (*Decision) Open

func (d *Decision) Open() bool

Open reports whether the decision awaits its answer.

func (*Decision) Sanitize

func (d *Decision) Sanitize()

Sanitize brings a decision read from the folder within the caps and character rules: the question, the options and the outcome folded and cut, the default dropped when it is none of the options, the date dropped when it is not one, the card bounded, the sent way one of the three words or "".

func (*Decision) Validate

func (d *Decision) Validate() error

Validate checks what every decision written must carry.

type Entry

type Entry struct {
	Version int `json:"version"`
	// Member is the member's label as the session registered it (the
	// account email by default); "" when the session sent none.
	Member string `json:"member,omitzero"`
	// SessionName is the session's name as the roster shows it; SessionID
	// the Brigade session id, also the file's name.
	SessionName string `json:"session_name"`
	SessionID   string `json:"session_id"`
	// Repository is the repository's name (teamfile.RepoName), Branch the
	// branch HEAD was on at the last write ("" when detached or unknown).
	Repository string `json:"repository,omitzero"`
	Branch     string `json:"branch,omitzero"`
	// Harness is the session's host (claude-code, muse, codex, grok).
	Harness string `json:"harness"`
	// StartedAt is when the entry was created; LastPromptAt the last
	// prompt the hooks saw; EndedAt and EndReason the session's end, zero
	// and "" while it lives.
	StartedAt    time.Time `json:"started_at"`
	LastPromptAt time.Time `json:"last_prompt_at,omitzero"`
	EndedAt      time.Time `json:"ended_at,omitzero"`
	EndReason    string    `json:"end_reason,omitzero"`
	// Inbound is the session's effective inbound policy (accept, hold,
	// refuse).
	Inbound string `json:"inbound"`
	// StartHead is HEAD when the entry was created and Head HEAD at the
	// last write; Commits the commits reachable from Head and not from
	// StartHead, by the session's author, newest first, at most
	// MaxCommits.
	StartHead string   `json:"start_head,omitzero"`
	Head      string   `json:"head,omitzero"`
	Commits   []Commit `json:"commits"`
	// Doing is the doing-line history (`brigade doing`, newest last, at
	// most MaxDoing); Notes the notes (`brigade note`, newest last, at
	// most MaxNotes).
	Doing []Stamped `json:"doing"`
	Notes []Stamped `json:"notes"`
	// UpdatedAt is the last write.
	UpdatedAt time.Time `json:"updated_at"`
}

An Entry is one session's state.

func New

func New(sessionID, sessionName string, startedAt time.Time) *Entry

New is a fresh entry for a session, with the two lists that are never nil and the version set.

func ReadFolder

func ReadFolder(folder string) []*Entry

ReadFolder reads every entry in the folder's sessions directory, each sanitised: a file whose name is not an id, whose size is past MaxEntryBytes, whose content is not an entry or names another session than its file is skipped. The order is the directory's (by name).

func (*Entry) AddDoing

func (e *Entry) AddDoing(text string, at time.Time)

AddDoing appends a doing line at the end, keeping the newest MaxDoing.

func (*Entry) AddNote

func (e *Entry) AddNote(text string, at time.Time)

AddNote appends a note at the end, keeping the newest MaxNotes.

func (*Entry) Expired

func (e *Entry) Expired(now time.Time) bool

Expired reports whether the entry is past its retention term at now: an ended one EndedRetention after its end, a live one StaleRetention after its last write (its machine never came back to end it).

func (*Entry) Sanitize

func (e *Entry) Sanitize()

Sanitize brings an entry read from the folder — a teammate's text — within the caps and the character rules of every field: a string that cannot be made to fit is dropped, a list is cut to its cap (the newest kept), a commit with no hash is dropped, and the two lists are never nil. The writer runs it too before writing, so both copies obey it.

func (*Entry) Validate

func (e *Entry) Validate() error

Validate checks what every entry written must carry: the version and a session id that can be a file name.

type Gateway

type Gateway struct {
	SessionID string
	To        string
	Kind      string
}

A Gateway is the roster session a recipient goes through: its id, the `to:` line's value, and the recipient's kind.

func PickGateway

func PickGateway(recipients []string, sessions []protocol.SessionRecord) (Gateway, bool)

PickGateway walks the recipients in order and picks the first that a gateway on the roster (not offline) can carry: a handle or a channel through the Slack gateway; an address through the Slack gateway too when the team has one — it finds the person by their email, as `/brigade:slack <address>` does — and else through the mail gateway. So Slack comes before email whatever shape the recipient has (ruling 5; owner 2026-10-29: a member's roster label is an address, and that must not mean mail). Kind says the road taken. false when no recipient can be carried.

type Reports

type Reports struct {
	Version     int          `json:"version"`
	Subscribers []Subscriber `json:"subscribers"`
	// Legacy is set by ReadReports for a file of the 0.43 shape (version
	// 1, `manager` and `recipients`): its one subscriber's marker is the
	// v1 marker until they have their own, and the first write carries
	// it over. Never written.
	Legacy bool `json:"-"`
}

Reports is the file: the subscribers, in the order they subscribed.

func ReadReports

func ReadReports(folder string) (*Reports, error)

ReadReports reads the folder's reports file, sanitised: each subscriber's label, the recipients that have a kind (the rest dropped, the list capped), the period members as given, each one line; a subscriber with no label, or a second with a label already seen, is dropped. A version-1 file reads as one subscriber (Legacy set). A missing file satisfies errors.Is(err, fs.ErrNotExist); a file of another version or shape is an error.

func (*Reports) Sanitize

func (r *Reports) Sanitize()

Sanitize applies the file's rules in place: every subscriber sanitised, the unlabelled and the duplicates dropped, the list capped, and never a nil list.

func (*Reports) Subscribe added in v0.44.0

func (r *Reports) Subscribe(s Subscriber)

Subscribe puts s in the list: in place of the entry with its label, or at the end.

func (*Reports) Subscriber added in v0.44.0

func (r *Reports) Subscriber(label string) *Subscriber

Subscriber is the entry of the label, compared without case; nil for none.

func (*Reports) Unsubscribe added in v0.44.0

func (r *Reports) Unsubscribe(label string) bool

Unsubscribe removes the entry of the label; false when there was none.

type Stamped

type Stamped struct {
	Text string    `json:"text"`
	At   time.Time `json:"at"`
}

A Stamped is one line the model published, and when.

type Store

type Store struct {
	StateDir string
	Folder   string
}

A Store is where one session's entries live: the private state directory for the canonical copies, the state folder for the projections. StateDir must be absolute; Folder is "" for a session whose project shares no state, and then Save writes the canonical copy alone.

func (Store) CanonicalDecisionPath

func (s Store) CanonicalDecisionPath(id string) (string, error)

CanonicalDecisionPath is the canonical copy of the decision id.

func (Store) CanonicalDir

func (s Store) CanonicalDir() string

CanonicalDir is ${stateDir}/state/entries.

func (Store) CanonicalPath

func (s Store) CanonicalPath(id string) (string, error)

CanonicalPath is the canonical copy of the entry for id.

func (Store) DecisionsDir

func (s Store) DecisionsDir() string

DecisionsDir is ${stateDir}/state/decisions, the canonical copies.

func (Store) FolderPath

func (s Store) FolderPath(id string) (string, error)

FolderPath is the projection of the entry for id in the folder, or "" with no error when the Store has no folder.

func (Store) Load

func (s Store) Load(id string) (*Entry, error)

Load reads the canonical entry for id through the strict private-file reader. A missing entry satisfies errors.Is(err, fs.ErrNotExist).

func (Store) LoadDecision

func (s Store) LoadDecision(id string) (*Decision, error)

LoadDecision reads the canonical copy of the decision id; a missing one satisfies errors.Is(err, fs.ErrNotExist).

func (Store) Project

func (s Store) Project(id string) error

Project writes the canonical entry for id into the folder again, from the canonical copy: the heal of a folder entry a teammate's machine deleted. Nothing when the Store has no folder or no canonical copy.

func (Store) PruneOwn

func (s Store) PruneOwn(now time.Time) int

PruneOwn removes every canonical entry and decision past its term at now, with its projection, and reports how many. Best effort: a file that cannot be read or removed is left for the next time.

func (Store) Remove

func (s Store) Remove(id string) error

Remove deletes both copies of the entry for id; a missing copy is not an error.

func (Store) RemoveDecision

func (s Store) RemoveDecision(id string) error

RemoveDecision deletes both copies; a missing copy is not an error.

func (Store) Save

func (s Store) Save(e *Entry) error

Save sanitises and validates e, writes the canonical copy (0600 in the private directory chain) and projects it into the folder. A folder that cannot be written is the error; the canonical copy stands, and the next Save projects it again.

func (Store) SaveDecision

func (s Store) SaveDecision(d *Decision) error

SaveDecision sanitises and validates d, writes the canonical copy and projects it into the folder, as Save does for an entry.

type Subscriber added in v0.44.0

type Subscriber struct {
	Label      string   `json:"label"`
	Recipients []string `json:"recipients"`
	Every      string   `json:"every,omitzero"`
	At         string   `json:"at,omitzero"`
	TZ         string   `json:"tz,omitzero"`
	Only       string   `json:"only,omitzero"`
}

A Subscriber is one entry: the member's roster label (the key), the recipients in precedence (a Slack handle or channel, or an address; each goes through the Slack gateway when the team has one, an address through the mail gateway otherwise; none means their own best session), the period — `every` as a Go duration ("24h", "4h"), or for a daily digest `at` ("08:00") in `tz` (an IANA zone) — and the filter, "" or OnlyMine.

func (*Subscriber) Period added in v0.44.0

func (s *Subscriber) Period() time.Duration

Period is the subscriber's period: `every` parsed, DefaultEvery when it is absent or not a duration or under a minute.

func (*Subscriber) Sanitize added in v0.44.0

func (s *Subscriber) Sanitize()

Sanitize applies a subscriber's rules in place, and fills an empty recipients list with the label when that is itself a recipient — an email address, which a roster label is by default (owner 2026-10-29): subscribing is then enough, and the Slack gateway finds them by it.

Jump to

Keyboard shortcuts

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