autonomy

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 28 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 autonomy is the away mode: the person's word that they are away and sessions should work on, held once per repository on the machine, and the shapes the stop check reads (itd-2610180912189125, spc-2610180914469489).

It is a library: it returns values and errors, and never prints. The front doors (`abcd mode autonomous|back|queue`, and later the hooks) format what it returns.

The away store

One folder per repository, keyed on the repository's root commit as the worktree store is, below abcd's home: `away/<root-sha>/` (Store.Dir, Store.Rel). Every working copy of the repository reads the same folder. It holds:

  • record.json (RecordFile, Store.RecordPath): the Record;
  • lock (LockFile, Store.LockPath): the one lock every read-modify-write in the folder holds, the record's and any sibling file's alike;
  • sibling files other parts of the slice add (a working copy's created branches, a session's start copy), read and written through Store.ReadFile and Store.WriteFile inside Store.WithLock.

Every file in it is used only when it is a regular file this account owns that no one else can write, within MaxFileBytes (64 KiB), and only through folders no one else can change: the checks a user-layer rules.json gets. A file failing them is ErrUnsafe, naming the file. Writes go through fsutil's atomic writer.

The lock

Store.WithLock holds fsutil.WithFileLock on the lock file for at most LockTimeout (two seconds); past it the call returns ErrLockBusy. Store.Update re-reads the record inside the lock, hands it to the caller's function, and writes what that returns, so two writers never lose an update and a check that read the record before a slow forge listing never writes away back after `abcd mode back` (Store.RecordStop records only while the re-read record still holds).

Failing open

Store.Away is the hooks' read: an unreadable or unsafe record (or lock) reads as not away, with the reason returned for a stderr line. A verb asked to change such a record refuses, naming the file, except Back: ending the mode never depends on the record (end.go). A record past its bound is printed whole and kept fitted (Record.Fit); one that does not parse, names another schema or is not safely this account's is replaced by a closed record, printing nothing from it; parts of the wrong shape are left out; and a lock not had within LockTimeout, or not safe to take, is gone around, the atomic write re-checked. BackResult.Notes names each.

Record

Record is the away record. Its fields, as written to record.json:

schema_version  1
set_by          who set it (Who.Name): the holder name reservations
                resolve without a network read, else git's user.name
set_from        the working copy it was set from (Who.Copy, its root)
start, until    when it was set and when it ends
open_ended      set without --until (until is then start plus MaxWindow)
hold_pushes     the person said pushes wait (--hold-pushes); it narrows
                and grants nothing
queue           []QueuedStep: steps for the person (`abcd mode queue`)
handed_back     []HandBack: items the stop check handed back, by branch
                and head, once each
stops           []Stop: the stops recorded, a stop identical to one
                already recorded, anywhere, kept as that entry with a
                count and the last time
dropped_*       what was let go to stay within MaxFileBytes, counted:
                the oldest stops and hand-backs past their own bounds,
                and queued steps only when SetAway carries, or Back
                closes, a record past its bound; a queue past its bound
                refuses the next step (ErrQueueFull) instead
closed          *Closing: once ended by word, who ended it and from
                which copy

A record holds (Record.Holds) while it is not closed and now is before Record.Ends, which is never more than MaxWindow (seven days) after its start, whatever is stored. Past its end and not yet closed it is lapsed (Record.Lapsed). A human prompt never ends it.

Owed

Owed is the stop check's input: the owed items, each an OwedItem with its OwedKind, whether it is capped (an item the session can act on itself, which a wake releases at most twice in a row), and its branch or record id (plus its pull request and head where it has them). The kinds, in the order the next item is chosen (owedKinds): a renewal due, a failing pull request, a behind one, a stacked branch, an unpushed branch, and a reservation whose work no pull request carries. Owed.Fingerprint and Owed.CappedFingerprint compare two owed sets item by item, ignoring order and reasons. Owed.NextRenewal is the earliest renewal due among the live reservations under this copy's key (zero when none), Owed.WakeBy the latest a wake may fire for them (a renewal not yet due, or the lapse of one already due, so a renewal only due keeps releasing on a wake), and Owed.HandedBack the items a queued step handed back, which the verdict accepts only under --hold-pushes and only for an unpushed branch's item with its head.

The stop verdict

Judge(record, owed, input, session, now) is the stop check's verdict, pure: present, it allows (with a SystemMessage naming owed work); away, the seven rows of the plan decide, from the owed set, the host's payload (StopInput: stop_hook_active, the last message, session_crons, background_tasks, the host's cap) and the session's SessionState. A wake qualifies (qualifyingWake) when a session cron's latest fire time (latestFire: its next match, by abcd's own five-field cron parser, parseCron, plus the host's lateness) is no later than wakeDeadline. The session's state lives in the copy's local tier (SessionsDir, LoadSession, SaveSession), keyed by a session id ValidSessionID accepts. The session-start hook notes each session's start copy in the store (Store.NoteSessionCopy); ResolveCopy reads it back.

The created-branch list

The guard's pre-tool hook records the branches a session creates (spc-2610180914469489 step 3) through RecordCreated(copyRoot, runDir, changes, Options), whether or not the person is away: a BranchCreated name only when no branch of that name exists yet, a BranchCheckedOut one (`git worktree add <path> [<branch>]`) when it is a branch no worktree has checked out (git refuses that command, which runs after the recorder) or names nothing git resolves, and a BranchMoved rename carrying a record by whole name. The list is createdFile(copyKey) in the away store, keyed on the working copy's reservation copy key (claim.CopyKey), written under the store's lock (Store.RecordBranches) and capped at MaxCreatedBranches, the oldest dropped; Store.CreatedBranches reads it. A checkout abcd does not manage (Managed: no `.abcd/` at its root, nor at its main worktree's) records nothing, and every away hook returns at once there.

Reading the owed work

ReadOwed is the stop check's one seam onto owed work:

func ReadOwed(ctx context.Context, o ReadOptions) (Owed, error)

o.Root is the session's working copy and o.Record the away record as the check read it. While o.Record does not hold at o.Now the person is present and ReadOwed reads disk only: renewals due and unpushed own branches, with no forge call. While it holds, ReadOwed adds one `gh pr list` of the open pull requests (o.Forge, landing.GHContext by default) under ForgeDeadline (ten seconds, o.ForgeDeadline in a test), for failing, behind (the forge's merge state: BEHIND, and DIRTY as behind; UNKNOWN is a note), stacked and uncarried work. A listing that fails or is late is a note, and the check judges from disk alone: a pushed branch is compared with the last-fetched default branch, naming the fetch, and no reservation is reported uncarried (adr-2610181003541997).

A branch is the session's own when this copy's HEAD reflog has checked it out or the copy's created-branch list holds it, either only while it holds a commit of this checkout's author email made within StaleWindow (14 days) or a live reservation under this copy's key links it; when it is a lane of an unfinished run in this copy's local tier whose reservation is live under this copy's key; or when it heads an open pull request of the person's that a live reservation under this copy's key links. Never the default branch, nor a branch whose open pull request another person authored. A pull request carries a reservation's work when the record id is in its head branch's name or on a Resolves: or Delivers: line of its body, on word boundaries; a Refs: line carries it only for a head already own.

A stacked branch (its pull request's base is not the default branch, or, with none, its nearest own ancestor branch is not in the default branch) is owed by the clearing rule alone: while it is behind its base, failing, has a review outstanding (CHANGES_REQUESTED, or a run lane with no passing review of its head) or is not verified (a preflight receipt naming its head where the repository mints receipts, else passing checks); an item whose only unmet condition is checks still running is not capped. With --hold-pushes, an unpushed own branch a queued step names as a whole name, whose head contains its base's last-fetched tip and has a receipt, is handed back: moved out of Owed.Items into Owed.HandedBack. ReadOwed records nothing: the verdict accepts the hand-back (Verdict.HandBacks) and the stop hook records it, once per branch and head (Store.RecordHandBack), so a hand-back has one owner. Owed.NextRenewal is filled present or away. The items come sorted by owedKinds' order. The error is a root that is not a working copy; anything else ReadOwed could not read is a note in Owed.Notes.

Every git call ReadOwed makes is bound to ctx, and the stack-base search reads each own branch's reflog once a check and walks each branch's own history once, so its cost grows with the branches, not their pairs. A context that ends before everything is read stops the reading where it is: Owed.Incomplete is set, a note says what was not read, and Judge allows the stop with a line naming it, recording a StopCheckIncomplete while away. A branch with no upstream and no commit in any remote branch is owed only when merging it into the last-fetched default branch would change it; one squash- or rebase-merged already is not, and one that cannot be told is a note. A listing at its limit of 200 may be truncated: a note says so, and no reservation is reported uncarried from it.

Index

Constants

View Source
const (
	StateWorking = "working"
	StateWaiting = "waiting"
	StateStopped = "stopped"
)

The session states while away (dcn-2610180936577720): working (the stop is blocked), waiting (allowed with a qualifying wake), and stopped (the host's cap overrode a block, recorded).

View Source
const (
	// StoreDir is the away store's folder below abcd's home; each repository
	// has StoreDir/<root-sha>/.
	StoreDir = "away"
	// RecordFile is the away record's file name in a repository's folder.
	RecordFile = "record.json"
	// LockFile is the lock file's name in a repository's folder.
	LockFile = "lock"
	// MaxFileBytes is the most any file in the store may hold.
	MaxFileBytes = 64 << 10
	// LockTimeout is how long a writer waits for the lock.
	LockTimeout = 2 * time.Second
)
View Source
const (
	// OwedCeiling is the furthest a qualifying wake may fire while work is
	// owed: a session with owed work waits half an hour at most.
	OwedCeiling = 30 * time.Minute
	// IdleCeiling is the furthest a qualifying wake may fire while nothing
	// is owed.
	IdleCeiling = time.Hour
	// MaxLateness is the most the host runs a recurring task late: half the
	// gap to its following run, at most this.
	MaxLateness = 30 * time.Minute
)
View Source
const DefaultBlockCap = 8

DefaultBlockCap is the host's cap on consecutive stop-hook continuations: after eight in a row it overrides the next block and ends the turn (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises it).

View Source
const ForgeDeadline = 10 * time.Second

ForgeDeadline bounds the away check's one pull-request listing (adr-2610181003541997): past it the check judges from disk alone.

View Source
const MaxCreatedBranches = 100

MaxCreatedBranches bounds a working copy's created-branch list; past it the oldest record is dropped. A hundred names at git's 255-byte limit stay well within the store's 64 KiB per file (spc-2610180914469489 leaves the bound to the builder).

View Source
const MaxSessionNotes = 256

MaxSessionNotes bounds the notes kept; the oldest go first.

View Source
const MaxStepLen = 500

MaxStepLen bounds a queued step, in characters, so one step cannot fill the record's 64 KiB.

View Source
const MaxWakesUnchanged = 2

MaxWakesUnchanged is how many wakes in a row may release an unchanged set of capped items (dcn-2610181035361997).

View Source
const MaxWindow = 7 * 24 * time.Hour

MaxWindow is the stale-record cap: a record ends at most seven days after it was set, so a forgotten one lapses while a run of several days fits (dcn-2610180937181736).

View Source
const SchemaVersion = 1

SchemaVersion is the record's shape version, written as schema_version.

View Source
const SessionNoteTTL = 30 * 24 * time.Hour

SessionNoteTTL is how long a note is kept: a session older than this is long over.

View Source
const SessionsDir = mode.TierRelPath + "/autonomy/sessions"

SessionsDir is the session-state folder below a working copy's root: one file per session id, in the copy's local tier.

View Source
const SessionsFile = "sessions.json"

SessionsFile is the away store's note of each session's start copy: the worktree a session started in, keyed by session id, so a hook run after the session changed directory into a worktree it made still reads the start copy's key, local tier and session state ("Which copy").

View Source
const StaleWindow = 14 * 24 * time.Hour

StaleWindow bounds ownership through the reflog or a recorded creation: such a branch is the session's own only while it holds a commit of this checkout's made within it, or a live reservation links it (dcn-2610181003463367).

View Source
const StoreName = "the away store"

StoreName is the noun the checkout-root refusals are phrased with.

Variables

View Source
var (
	// ErrUntilUnreadable is an --until that is neither a clock time nor a
	// timestamp.
	ErrUntilUnreadable = errors.New("autonomy: --until is not a time")
	// ErrUntilPast is an --until already past.
	ErrUntilPast = errors.New("autonomy: --until is already past")
	// ErrUntilBeyondCap is an --until later than seven days on.
	ErrUntilBeyondCap = errors.New("autonomy: --until is past the seven-day cap")
	// ErrStepEmpty is a queued step with no words.
	ErrStepEmpty = errors.New("autonomy: the step is empty")
	// ErrStepTooLong is a queued step past MaxStepLen.
	ErrStepTooLong = errors.New("autonomy: the step is too long")
	// ErrQueueFull is a step the queue has no room for.
	ErrQueueFull = errors.New("autonomy: the queue is full")
)
View Source
var (
	// ErrUnsafe is a store file that is not a regular file this account owns
	// that no one else can write, within MaxFileBytes, or that does not parse.
	ErrUnsafe = errors.New("autonomy: away store file refused")
	// ErrLockBusy is the store's lock not had within LockTimeout.
	ErrLockBusy = errors.New("autonomy: away store lock busy")
	// ErrNoRootCommit is a repository with no root commit to key the store on.
	ErrNoRootCommit = errors.New("autonomy: the repository has no root commit to key the away store on")
	// ErrNoHome is a home directory that is unset or not absolute.
	ErrNoHome = errors.New("autonomy: no home directory for the away store")
	// ErrRecordFull is a record that would pass MaxFileBytes if written.
	ErrRecordFull = errors.New("autonomy: the away record would pass 64 KiB")
)
View Source
var (
	// ErrNoLocalTier is the set's refusal in a checkout abcd does not manage:
	// the mode store's own refusal, so a front door maps both alike.
	ErrNoLocalTier = mode.ErrNoLocalTier
	// ErrNotAway is a queued step with no away record holding.
	ErrNotAway = errors.New("autonomy: the person is not away")
)
View Source
var ErrCron = errors.New("autonomy: not a five-field cron expression abcd reads")

ErrCron is a cron expression abcd's parser does not read. Such an expression never qualifies as a wake.

View Source
var ErrSessionID = errors.New("autonomy: the session id is not [A-Za-z0-9_-]{1,128}")

ErrSessionID is a session id outside [A-Za-z0-9_-]{1,128}.

Functions

func Managed

func Managed(root string) bool

Managed reports whether abcd manages the checkout at root: `.abcd/` is a directory at its root (a symbolic link is not), or root is a linked worktree of a repository whose main worktree has one. A worktree a session makes shares the repository's away store, and a branch cut before `.abcd/` was committed, or a `.abcd/` never committed, leaves it out of the worktree. The away mode's hooks and recorder act only in such a checkout, so a plugin installed for every repository reads nothing, writes nothing, runs no git past naming the roots, and says nothing in any other.

func QuestionRoute

func QuestionRoute() string

QuestionRoute is how a question is routed while the person is away, one line each: the queue route and the person-only acts, then the decide route for every other question, then that nothing detects the act and the away mode grants nothing. A front door puts its own head line above it.

func RecordCreated

func RecordCreated(copyRoot, runDir string, changes []BranchChange, o Options) error

RecordCreated is the created-branch recorder the guard's pre-tool hook runs, before the command does, whether or not the person is away: it judges each change against the repository as it stands (a created branch only when no branch of that name exists yet; a checked-out one when it is a branch no worktree has checked out, or names nothing git can resolve) and records what passes under the copy's key (claim.CopyKey, minted as a reservation verb mints it) in the away store. copyRoot is the session's working copy; runDir is where the command runs, whose current branch a rename with no old name renames. A checkout abcd does not manage (Managed), or with no root commit, records nothing and is no error. The error is a store the recorder could not write; it never refuses the command.

func SaveSession

func SaveSession(copyRoot, sessionID string, st SessionState) error

SaveSession writes the session's state below copyRoot through fsutil's atomic writer, making the folders owner-only on the way.

func ValidSessionID

func ValidSessionID(id string) bool

ValidSessionID reports whether id is one abcd keys a file on.

Types

type BackResult

type BackResult struct {
	// State is what the record was before: "away" (it held and is now
	// ended), "lapsed" (its time had passed and it is now closed), or "none"
	// (no record, or one already closed: nothing to end).
	State string
	// Record is the record after the verb, nil when there was none.
	Record *Record
	// Lines are the record's lines, printed one each.
	Lines []string
	// Notes say what could not be read or done as usual on the way to
	// ending the mode (a record past its bound, unparsable or not safely
	// this account's; a lock held past its timeout), one line each.
	Notes []string
}

BackResult is what `abcd mode back` found and did.

func Back

func Back(cwd string, o Options) (BackResult, error)

Back is `abcd mode back` from cwd: under the lock it reads the record's lines, records who ended it and from which copy, and closes it, on a record whose time has passed as on one that holds. It ends the mode whatever state the record is in (end.go): a record past its bound is printed whole and kept fitted; one it cannot read, or not safely this account's, is replaced by a closed record, printing nothing from it; and a lock not had within its timeout, or not safe to take, is gone around, closing without it. Each is named in the result's notes.

type BackgroundTask

type BackgroundTask struct {
	ID          string `json:"id"`
	Type        string `json:"type"`
	Status      string `json:"status"`
	Description string `json:"description,omitempty"`
	Command     string `json:"command,omitempty"`
}

BackgroundTask is one in-flight task the Stop payload's background_tasks carries. A background task is never a wake on its own while away: a `sleep 36000` or a `tail -f` would otherwise hold a session idle.

type BranchChange

type BranchChange struct {
	Kind BranchChangeKind
	Name string
	From string
}

BranchChange is one change the created-branch recorder applies.

type BranchChangeKind

type BranchChangeKind string

BranchChangeKind is what a recorded command did to a branch.

const (
	// BranchCreated is a branch the command creates; RecordCreated keeps it
	// only when no branch of that name exists yet.
	BranchCreated BranchChangeKind = "created"
	// BranchCheckedOut is a branch `git worktree add` checks out in a new
	// worktree; RecordCreated keeps it when it exists as a branch, or when the
	// name resolves to nothing at all, so git creates it.
	BranchCheckedOut BranchChangeKind = "checked-out"
	// BranchMoved is a rename: a record of From (the current branch of the
	// command's worktree when "") is carried to Name.
	BranchMoved BranchChangeKind = "moved"
)

type Closing

type Closing struct {
	By   string    `json:"by"`
	From string    `json:"from"`
	At   time.Time `json:"at"`
}

Closing is who ended the record by word, from which copy, and when.

type CreatedBranch

type CreatedBranch struct {
	Name string    `json:"name"`
	At   time.Time `json:"at"`
}

CreatedBranch is one branch a session in the working copy created, and when it was recorded.

type Cron

type Cron struct {
	// contains filtered or unexported fields
}

Cron is a parsed five-field cron expression: minute, hour, day of month, month and day of week, each a set of the values it matches. It follows vixie cron, as the host says its scheduled tasks do: when both day fields are restricted either matches, and a day field written from `*` (`*/n` included) counts as unrestricted for that rule.

func (Cron) Next

func (c Cron) Next(from, until time.Time, loc *time.Location) (time.Time, bool)

Next is the first time strictly after from, and no later than until, at which the expression matches, read in loc's wall-clock time (nil means the machine's local time, as the host reads its tasks). It steps minute by minute in absolute time, so a wall-clock minute a daylight-saving change skips never matches, and one it repeats matches only at its first occurrence.

type Forge

type Forge func(ctx context.Context, dir string, args ...string) (string, error)

Forge runs the forge client (`gh`) with args from dir, bound to ctx, and returns its stdout: landing.GHContext, or a test's fake.

type HandBack

type HandBack struct {
	Branch string    `json:"branch"`
	Head   string    `json:"head"`
	At     time.Time `json:"at"`
}

HandBack is one owed item the stop check handed back to the person, by its branch and the head it had then.

type Options

type Options struct {
	// Home is the home directory the away store lives under; "" means the
	// process's own.
	Home string
	// Now is the clock; nil means time.Now.
	Now func() time.Time
	// Who names the person acting in the checkout at root; nil means
	// resolveWho.
	Who func(root string) string
}

Options carry what the verbs read from the machine; the zero value reads the process's own home, clock and identity.

type Owed

type Owed struct {
	Items []OwedItem `json:"items"`
	// Notes say what was not read and how the set was judged instead, such
	// as pull requests not read when the forge listing failed.
	Notes []string `json:"notes,omitempty"`
	// NextRenewal is the earliest renewal due among the live reservations
	// under this copy's key, due or not yet; zero when there is none. The
	// stop verdict's deadline is it less lease.Skew, when that is sooner than
	// the ceiling (dcn-2610181003455731).
	NextRenewal time.Time `json:"next_renewal,omitempty"`
	// WakeBy is the latest a wake may fire for this copy's live
	// reservations: the earliest of each one's renewal while it is not yet
	// due, and its lapse once it is. A renewal already due is owed, and a
	// wake before the lease lapses releases it as the spec has it; zero when
	// there is no reservation, and wakeDeadline then reads NextRenewal.
	WakeBy time.Time `json:"wake_by,omitempty"`
	// HandedBack are the items a queued step handed back this check, taken
	// out of Items by the reader (dcn-2610181035355741). The verdict accepts
	// only an unpushed branch's item, with its head, under --hold-pushes,
	// and puts any other back among the owed items.
	HandedBack []OwedItem `json:"handed_back,omitempty"`
	// Incomplete is a reading the check's time budget cut short: Notes say
	// what was not read, and the verdict allows the stop, naming it, rather
	// than judge from part of the work.
	Incomplete bool `json:"incomplete,omitempty"`
}

Owed is the owed set a stop check judges.

func ReadOwed

func ReadOwed(ctx context.Context, o ReadOptions) (Owed, error)

ReadOwed is the owed work of the working copy at o.Root (spc-2610180914469489, "Owed work"): the stop check's one reading.

While the person is present (o.Record does not hold) it reads disk only: renewals due and unpushed own branches, and never calls the forge. While away it adds one listing of the open pull requests under ForgeDeadline, for failing, behind, stacked and uncarried work; a listing that fails or is late is named in Owed.Notes and the check judges from disk alone (adr-2610181003541997). With --hold-pushes, an unpushed own branch a queued step names, whose head contains its base's last-fetched tip and has a preflight receipt, is handed back: moved out of Owed.Items into Owed.HandedBack, for the verdict to accept and the stop hook to record. Owed.NextRenewal is the earliest renewal due among the live reservations under this copy's key, due or not yet, present or away.

The error is a root that is not a working copy; every other failure to read something is a note, and the set is judged without it.

func (Owed) CappedFingerprint

func (o Owed) CappedFingerprint() string

CappedFingerprint is Fingerprint over the capped items alone, so a renewal falling due or done does not change it.

func (Owed) Empty

func (o Owed) Empty() bool

Empty reports whether nothing is owed.

func (Owed) Fingerprint

func (o Owed) Fingerprint() string

Fingerprint identifies the owed set by its items' kind, branch, record, pull request and head, whatever their order and reasons.

func (Owed) HasCapped

func (o Owed) HasCapped() bool

HasCapped reports whether any owed item is capped.

func (Owed) Next

func (o Owed) Next() (OwedItem, bool)

Next is the item the session is handed: the first by owedKinds' order, the items of one kind in the order they were given.

type OwedItem

type OwedItem struct {
	Kind OwedKind `json:"kind"`
	// Capped marks an item the session can act on itself, which a qualifying
	// wake releases at most twice in a row (dcn-2610181035361997).
	Capped bool `json:"capped"`
	// Branch is the branch the item is about, when it is about one.
	Branch string `json:"branch,omitempty"`
	// Record is the reservation's record id, when the item is about one.
	Record string `json:"record,omitempty"`
	// PR is the pull request's number, when the item has one.
	PR int `json:"pr,omitempty"`
	// Head is the branch's head commit, when known.
	Head string `json:"head,omitempty"`
	// Reason says, in plain words, why the item is owed and what to do. It is
	// not part of the item's identity.
	Reason string `json:"reason,omitempty"`
}

OwedItem is one owed item.

type OwedKind

type OwedKind string

OwedKind is one of the four kinds of owed work, the reservation kind split in two (a renewal due, and work no pull request carries) and the pull request kind split in two (failing, behind).

const (
	// OwedRenewal is a live reservation under this copy's key whose renewal
	// is due. It is never capped.
	OwedRenewal OwedKind = "renewal"
	// OwedFailing is an open pull request of the session's own failing its
	// checks.
	OwedFailing OwedKind = "failing"
	// OwedBehind is an open pull request of the session's own behind its base
	// (or conflicting).
	OwedBehind OwedKind = "behind"
	// OwedStacked is an own branch stacked on a change still open, while the
	// clearing rule owes it.
	OwedStacked OwedKind = "stacked"
	// OwedUnpushed is an own branch with commits not pushed.
	OwedUnpushed OwedKind = "unpushed"
	// OwedUncarried is a live reservation under this copy's key whose work no
	// open pull request carries yet.
	OwedUncarried OwedKind = "uncarried"
)

type QueuedStep

type QueuedStep struct {
	Step string    `json:"step"`
	At   time.Time `json:"at"`
	From string    `json:"from"`
}

QueuedStep is one step queued for the person's return.

type ReadOptions

type ReadOptions struct {
	// Root is the session's working copy: the root of the worktree the
	// session started in.
	Root string
	// Record is the away record as the stop check read it, nil when there is
	// none. The forge is read only while it holds at Now; its queue and
	// HoldPushes decide what a queued push hands back.
	Record *Record
	// Home is the home directory the away store lives under; "" means the
	// process's own.
	Home string
	// Now is the clock; nil means time.Now.
	Now func() time.Time
	// Forge runs the forge client; nil means landing.GHContext.
	Forge Forge
	// ForgeDeadline bounds the listing; zero means ForgeDeadline.
	ForgeDeadline time.Duration
	// Reservations reads the reservations as last fetched, with no network;
	// nil means claim.View.
	Reservations func(root string, now time.Time) (claim.Snapshot, error)
	// Person is the person's forge name, which tells their pull requests
	// from another person's; "" means the holder name reservations resolve
	// without a network read (claim.ReaderHolder), and when that is unknown
	// too the listing asks for the person's own pull requests alone.
	Person string
	// Email is this checkout's author email, which tells its commits from
	// another author's; "" means the email git would author a commit with.
	Email string
}

ReadOptions carry what ReadOwed reads; every seam's zero value reads the machine.

type Record

type Record struct {
	SchemaVersion int          `json:"schema_version"`
	SetBy         string       `json:"set_by"`
	SetFrom       string       `json:"set_from"`
	Start         time.Time    `json:"start"`
	Until         time.Time    `json:"until"`
	OpenEnded     bool         `json:"open_ended"`
	HoldPushes    bool         `json:"hold_pushes"`
	Queue         []QueuedStep `json:"queue"`
	HandedBack    []HandBack   `json:"handed_back"`
	Stops         []Stop       `json:"stops"`
	Closed        *Closing     `json:"closed,omitempty"`
	// DroppedStops, DroppedHandBacks and DroppedSteps count what was let go
	// to keep the record within MaxFileBytes: the oldest stops (by their
	// counts) and hand-backs as new ones arrive, and, only when a record
	// past its bound is carried or closed, the oldest queued steps.
	DroppedStops     int `json:"dropped_stops,omitempty"`
	DroppedHandBacks int `json:"dropped_handed_back,omitempty"`
	DroppedSteps     int `json:"dropped_queue,omitempty"`
}

Record is the away record. The package comment lists its fields.

func AwayAt

func AwayAt(root string, o Options) (*Record, bool, error)

AwayAt reads whether the person is away for the checkout at root, failing open: an unreadable record reads as not away, with the reason returned.

func QueueStep

func QueueStep(cwd, step string, o Options) (*Record, error)

QueueStep is `abcd mode queue "<step>"` from cwd: the step is kept for the person's return while the record holds, and refused otherwise.

func SetAway

func SetAway(cwd, until string, holdPushes bool, o Options) (*Record, error)

SetAway is `abcd mode autonomous [--until <time>] [--hold-pushes]` from cwd: until "" is open-ended. A past or unreadable --until, one past seven days, no checkout, and a checkout without the local tier are refused with nothing written; so is a store whose record or lock fails the checks.

func (*Record) AddHandBack

func (r *Record) AddHandBack(branch, head string, now time.Time) bool

AddHandBack records an item handed back, once per branch and head; it reports whether this call added it.

func (*Record) AddStep

func (r *Record) AddStep(step, from string, now time.Time) error

AddStep queues a step for the person. Its whitespace is folded to single spaces, so it is one line; an empty step, or one past MaxStepLen characters, is refused and nothing is kept.

func (*Record) AddStop

func (r *Record) AddStop(s Stop, now time.Time)

AddStop records a stop at now. A stop identical to one already recorded, anywhere in the list (same kind, error type, detail, which names the item, and cap label), adds to that entry's count and last time instead, so two copies blocked on different items, alternating, keep two entries. Past stopsBudget the stop seen least recently goes, counted in DroppedStops.

func (*Record) Close

func (r *Record) Close(who Who, now time.Time)

Close ends the record by word: who ended it, from which copy, and when.

func (*Record) Ends

func (r *Record) Ends() time.Time

Ends is when the record ends: its stored end, but never later than seven days after its start, whatever is stored.

func (*Record) Fit

func (r *Record) Fit()

Fit lets go of what a record past its bound cannot hold, oldest first and counted: stops, then hand-backs, then queued steps. A record within its bound is unchanged. begin fits what it carries and Back what it closes, so neither ever fails on size; Back prints every line before it fits.

func (*Record) Holds

func (r *Record) Holds(now time.Time) bool

Holds reports whether the person is away at now: a record, not closed, and now before its end. No record is not away.

func (*Record) Lapsed

func (r *Record) Lapsed(now time.Time) bool

Lapsed reports whether the record's end has passed while it is still unclosed: what is in it has not been read by `abcd mode back`.

func (*Record) LapsedLine

func (r *Record) LapsedLine() string

LapsedLine is the one line the prompt hook shows the person on every prompt while the record has lapsed unclosed holding a queued step or a recorded stop, and "" otherwise (dcn-2610181003474765).

func (*Record) Lines

func (r *Record) Lines() []string

Lines are what `abcd mode back` prints: one plain line per queued step, per handed-back item and per recorded stop, the cap label and count included.

func (*Record) PersonLine

func (r *Record) PersonLine() string

PersonLine is the one line the prompt hook shows the person on every prompt while the record holds: until when, set by whom and from which working copy, the counts of queued steps and handed-back items, and the literal `abcd mode back` as the way to end it (dcn-2610181035355741).

func (*Record) Terms

func (r *Record) Terms() []string

Terms are the record's plain statement, one line each: until when, set by whom and from which copy; that pushes wait, when the person said so; that the mode grants no rights, the person's standing instruction deciding; and how it ends.

type SessionCron

type SessionCron struct {
	ID        string `json:"id"`
	Schedule  string `json:"schedule"`
	Recurring bool   `json:"recurring"`
	Prompt    string `json:"prompt"`
}

SessionCron is one of the host's scheduled tasks for the session, as the Stop payload's session_crons carries it.

type SessionNote

type SessionNote struct {
	ID   string    `json:"id"`
	Copy string    `json:"copy"`
	At   time.Time `json:"at"`
}

SessionNote is one session's start copy.

type SessionState

type SessionState struct {
	SchemaVersion int `json:"schema_version"`
	// State is working, waiting or stopped, as the last verdict left it.
	State string `json:"state,omitempty"`
	// NextLook is the qualifying wake's next fire time while waiting.
	NextLook time.Time `json:"next_look,omitempty"`
	// Fingerprint is the owed set's at the last check (Owed.Fingerprint).
	Fingerprint string `json:"fingerprint,omitempty"`
	// QuestionHash is the last prose question blocked, hashed.
	QuestionHash string `json:"question_hash,omitempty"`
	// Blocks is the count of consecutive blocks, which stop_hook_active alone
	// drives (dcn-2610181003484631).
	Blocks int `json:"blocks"`
	// Wakes is how many times in a row a wake released an unchanged set of
	// capped items, and WakeFingerprint those items' fingerprint
	// (dcn-2610181035361997).
	Wakes           int    `json:"wakes"`
	WakeFingerprint string `json:"wake_fingerprint,omitempty"`
}

SessionState is one session's stop-check state, kept between hook runs in SessionsDir/<session-id>.json.

func LoadSession

func LoadSession(copyRoot, sessionID string) (SessionState, error)

LoadSession reads the session's state below copyRoot, through an os.Root at copyRoot so nothing outside the copy is read; an absent file is the zero state. A file over MaxFileBytes, or one that does not parse, is an error.

type Stop

type Stop struct {
	Kind StopKind `json:"kind"`
	// ErrorType is the host's error type for StopAPIError (rate_limit, …).
	ErrorType string `json:"error_type,omitempty"`
	// Detail is the next item at the stop, in plain words.
	Detail string `json:"detail,omitempty"`
	// PossiblyForcedByCap marks a stop at the host's continuation cap.
	PossiblyForcedByCap bool      `json:"possibly_forced_by_cap,omitempty"`
	Count               int       `json:"count"`
	First               time.Time `json:"first"`
	Last                time.Time `json:"last"`
}

Stop is one recorded stop. Count, First and Last are kept by AddStop: a stop identical to the last one recorded adds to that entry instead of a new one.

type StopInput

type StopInput struct {
	SessionID            string
	StopHookActive       bool
	LastAssistantMessage string
	SessionCrons         []SessionCron
	BackgroundTasks      []BackgroundTask
	// Cap is the host's continuation cap; 0 means DefaultBlockCap. The front
	// door reads CLAUDE_CODE_STOP_HOOK_BLOCK_CAP.
	Cap int
	// Location is the zone the host reads its tasks' schedules in; nil means
	// the machine's local time.
	Location *time.Location
}

StopInput is what the Stop hook's payload carries, as the front door maps it, and the two values it reads from the machine for the verdict.

type StopKind

type StopKind string

StopKind is why a recorded stop happened.

const (
	// StopWorkOwed is a stop with work owed.
	StopWorkOwed StopKind = "work-owed"
	// StopNoNextLook is a stop with nothing owed and no next look scheduled.
	StopNoNextLook StopKind = "no-next-look"
	// StopAPIError is a turn the host ended on an API error.
	StopAPIError StopKind = "api-error"
	// StopCheckIncomplete is a stop allowed because the check's time budget
	// ran out before it had read the owed work; Detail says what was not
	// read.
	StopCheckIncomplete StopKind = "check-incomplete"
)

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is one repository's folder in the away store.

func Resolve

func Resolve(cwd string, o Options) (root string, st Store, err error)

Resolve is the checkout root a caller standing in cwd acts from, the away store its repository keys, and the home it lives under.

func ResolveCopy

func ResolveCopy(cwd, sessionID string, o Options) (string, Store, error)

ResolveCopy is the working copy a session acts from: the start copy its session-start noted, else the worktree of cwd; and the away store its repository keys. The store is keyed on the root commit, so every worktree of the repository opens the same one and finds the note.

func StoreAt

func StoreAt(home, rootSHA string) (Store, error)

StoreAt is the away store keyed on rootSHA, a full object name, below home.

func (Store) Away

func (s Store) Away(now time.Time) (*Record, bool, error)

Away is the hooks' read, which fails open: the stored record and whether it holds at now. A record that cannot be read safely reads as not away (nil, false) with the reason returned, for one line on stderr.

func (Store) CreatedBranches

func (s Store) CreatedBranches(copyKey string) ([]CreatedBranch, error)

CreatedBranches is the created-branch list of the working copy whose key is copyKey, oldest first; empty when none is kept. A list the store's checks refuse, or that does not parse, is ErrUnsafe.

func (Store) Dir

func (s Store) Dir() string

Dir is the store's folder.

func (Store) Display

func (s Store) Display(name string) string

Display is a file of the store in the tilde form a message names it by.

func (Store) LockPath

func (s Store) LockPath() string

LockPath is the lock file's path.

func (Store) NoteSessionCopy

func (s Store) NoteSessionCopy(sessionID, copy string, now time.Time) (bool, error)

NoteSessionCopy notes copy as the session's start copy, under the store's lock, unless the session already has a note: the first note is the start, so a compaction or resume run from a worktree the session made keeps it. It reports whether it wrote. Notes past SessionNoteTTL, and the oldest past MaxSessionNotes, are dropped.

func (Store) Read

func (s Store) Read() (*Record, error)

Read returns the stored record, or nil when there is none. A record or lock refused by the store's checks, or a record that does not parse, is ErrUnsafe naming the file.

func (Store) ReadFile

func (s Store) ReadFile(name string) ([]byte, error)

ReadFile reads the store file name under the store's checks: a regular file this account owns that no one else can write, within MaxFileBytes, reached through folders no one else can change. An absent file is an error for which errors.Is(err, fs.ErrNotExist) holds; a refused one is ErrUnsafe, naming it. A caller reading to modify holds WithLock around it.

func (Store) RecordBranches

func (s Store) RecordBranches(copyKey string, changes []BranchChange, now time.Time) error

RecordBranches applies changes, already judged, to the created-branch list of the working copy whose key is copyKey, under the store's lock and with the list re-read inside it: a created or checked-out name is added once, a rename carries the record whose name is From, whole name to whole name, and the list keeps the newest MaxCreatedBranches.

func (Store) RecordHandBack

func (s Store) RecordHandBack(branch, head string, now time.Time) (bool, error)

RecordHandBack records an item handed back (its branch and head) at now, once per branch and head, only if the record re-read inside the lock still holds; it reports whether it wrote.

func (Store) RecordPath

func (s Store) RecordPath() string

RecordPath is the away record's path.

func (Store) RecordStop

func (s Store) RecordStop(st Stop, now time.Time) (bool, error)

RecordStop records a stop at now, only if the record re-read inside the lock still holds; it reports whether it wrote.

func (Store) Rel

func (s Store) Rel() string

Rel is the store's folder as a slash path relative to the home directory.

func (Store) RootSHA

func (s Store) RootSHA() string

RootSHA is the root commit the store is keyed on.

func (Store) SessionCopy

func (s Store) SessionCopy(sessionID string) (string, bool)

SessionCopy is the session's noted start copy, when it has one that is still a directory.

func (Store) Update

func (s Store) Update(fn func(cur *Record) (*Record, error)) (*Record, error)

Update is the store's read-modify-write: under the lock it re-reads the record (nil when there is none) and hands it to fn, and writes what fn returns. fn returning nil writes nothing; its error is returned and nothing is written. Update returns the record written, or the one read when nothing was.

func (Store) WithLock

func (s Store) WithLock(fn func() error) error

WithLock holds the store's lock across fn: the store's folders are made (owner-only) if absent, the lock file is checked as every store file is, and the lock not had within LockTimeout is ErrLockBusy. fn's error is returned as it is.

func (Store) WriteFile

func (s Store) WriteFile(name string, data []byte) error

WriteFile replaces the store file name through fsutil's atomic writer, creating the store's folders (owner-only) on the way, and refuses data past MaxFileBytes. The caller holds WithLock.

type Verdict

type Verdict struct {
	// Block holds the stop, with Reason handed to the agent.
	Block  bool
	Reason string
	// SystemMessage is the line shown to the person on an allow while
	// present with work owed (stopped, flagged).
	SystemMessage string
	// Row is the away row that decided (1 to 7), or 0 while present.
	Row int
	// State is the session's state to save, when Save is set (while away).
	State SessionState
	Save  bool
	// Stop is a stop to record in the away record: the block passing the
	// host's cap, possibly forced by it.
	Stop *Stop
	// HandBacks are the hand-backs the verdict accepted, to record in the
	// away record under its lock, once per branch and head.
	HandBacks []OwedItem
}

Verdict is the stop check's answer.

func Judge

func Judge(rec *Record, owed Owed, in StopInput, st SessionState, now time.Time) Verdict

Judge is the stop verdict, pure over the away record, the owed set, the host's payload, the session's state and now. rec not holding at now is the person present: with owed work the stop is allowed with a line naming it, and with none silently. While away the rows of the plan are read in order and the first that matches decides:

  1. the last message ends on a line ending in `?`, not yet blocked for this message: block with the reroute's reason;
  2. owed, the set changed (or the first check): block, naming the next item and the count;
  3. owed, unchanged, a qualifying wake, and no capped item owed or the wake count below two: allow (waiting; the wake count adds one if a capped item is owed);
  4. owed, unchanged, a qualifying wake, a capped item owed and the wake count at two: block;
  5. owed, unchanged, no qualifying wake: block;
  6. none owed, a qualifying wake: allow (waiting);
  7. none owed, no qualifying wake: block, taking the next ready item first.

stop_hook_active decides no row; it alone drives the count of consecutive blocks (false sets it to one, true adds one), and the block whose count passes the cap is recorded as a stop possibly forced by the cap.

type Who

type Who struct {
	Name string
	Copy string
}

Who names a person acting on the record and the working copy they act from (its root, as git names it).

Jump to

Keyboard shortcuts

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