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). While away, a capped item on a branch carries Live, the live work standing for it, when the preflight's whole test run of this account (a full preflight at the load gate or running past it, whose waiter records itself: implement.WholeRunMarker; a records-only preflight writes no marker) has a marker that says its command is the preflight's stages and names the item's head as the commit it was queued or started at, runs in the worktree the item's branch is checked out in, and no receipt names that head (livework.go); Owed.CappedAllLive reports that every capped item has it. The commit the stages test is not known: a run queued or started before a commit does not count for it. A checkout whose abcd predates the marker's present shape writes none that counts. A process of this account can write a marker and run under abcd's name, so the proof holds against other accounts and stale state, not against this account's own agent: that a counted marker is a real preflight is a must nothing enforces. A build run's lane agent and a host's background agent abcd did not start are not live work, and must not be counted as such until something proves them; nothing enforces that beyond the reader reading neither. 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 set whose every capped item has live work is waiting, not stuck: a qualifying wake releases it however many wakes have passed, and the wake count does not advance, for LiveWorkBound (one preflight's bound, 18 hours) from the first check that found it (SessionState.WaitingSince, reset with the capped set, so the bound does not hold against a set that keeps changing, as the wake count does not); past it the two-wake rule holds again, and its block says the wait on the named branch is past the bound. Without a wake, the block names the branch, the live work and since when. 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, which is never sooner than now plus MinWakeLead. 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, its creator with it. Each name added keeps the session that created it (Options.SessionID), when the hook had one. The worktree store's add verb, whose branch no git command line shows the hook, records it through RecordAdded once the worktree stands, with the session its environment names (iss-2611211734561033). 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 pull request into the default branch that is BEHIND, and not a draft, is judged by the merge queue where one guards that branch (iss-2610311339274372, dcn-2611081501502395): the queue tests every entry against the latest base, so merging the base in would only move the head and void its receipts. The forge's live rules for the branch are read once (`gh api repos/{owner}/{repo}/rules/branches/<branch>`, never the in-tree mirror under .abcd/work/rulesets/), and where they declare a merge queue a pull request armed, or already queued (claim.ArmedPullRequestsQuery, read once and only for one the listing shows unarmed), is not owed; one nobody armed is owed with "arm it" as its next move. Each read runs under RulesetDeadline (three seconds, o.RulesetDeadline in a test); one that fails, is late or cannot be read whole is a note, and the pull request is owed its merge as before, unless the check's own deadline ended it: then it owes nothing on that account and the reading is marked cut short. A conflict (DIRTY), failing checks and a stacked base are owed as they were.
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.
Several sessions can work from one copy, or from the worktrees beside it. With o.SessionID set, what another live session holds is left out of the owed work and named once in a note, holder by holder (holders.go): the lanes of a run whose control record names that session as its driver, a branch the guard recorded it creating (CreatedBranch.Session, which RecordCreated keeps from Options.SessionID), a branch checked out in the worktree it started in (its occupancy marker), and a reservation only its runs are for. The session's own evidence wins over another's: a branch it recorded creating, or a lane of a run it drives, stays its own. An item whose holder cannot be told stays owed: a record with no session kept (unless it is checked out in a worktree of the machine-scoped store other than this copy while another live session works in the repository: then it is left out, and a note says to leave it unless this session made it; anywhere else (this copy, a worktree outside the store, or nowhere) while another live session works in this copy, it stays owed but marked OwedItem.Unclaimed, and the stop names it as owed only if this session made it, tells that session how to push it or queue the push, and tells any other to leave it untouched, iss-2611211734561033), a lane of a run no session drives (unless a live session started in the worktree it is checked out in, or a live drive holds it, below), a reservation made by hand, a holder that has ended (its work returns to the sessions left), and every session's item when the session has no id or the live sessions (ReadOptions.LiveSessions, occupancy.Live by default) cannot be read. With or without a session id, the lanes of a run whose control record names a live drive as its driver, and a reservation only such runs are for, are the drive's and named in a note (iss-2611150851542274): a drive started in a plain terminal records its own process and no session, and the record is the drive's while the process table proves that process alive, abcd by its program name, this account's, and neither the check's own process nor one above it; a drive that has ended, or any process that cannot be told so, leaves the lane owed. A branch created again under a name the guard recorded is its new creator's. A branch a peer holds still serves as the base of the session's own branch stacked on it. Whenever owed work remains, a copy another live session started in is named, once, as a breach of one session per checkout.
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.
These reads of ReadOwed are bound to ctx: finding the checkout, the author's identity and the reservations' holder, the default branch and the local branches, the fetch stamp, the receipt folder and the landing receipt, the runs' tracked check, the created-branch list's store key and this copy's key, the other worktrees, each branch's own history, reflog, ancestry and landing, the reservations as last fetched (claim.ViewContext), the forge reads and the live sessions' wait. 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. These reads mark the reading cut short, which sets Owed.Incomplete, when the context ended them: the author's identity, the holder, the default branch, the receipt folder, the landing receipt, the runs' tracked check, this copy's key and the created-branch list's store, the other worktrees, the fetch stamp, the stack index, the reservations as last fetched, the live sessions' wait, the merge queue's rules and its armed set, and each call made through `r.git`. A reservations read the context ended uses none of what it read: no reservation reads as live from it, and none counts as this copy's. The pull-request listing and the landing check's merge-driver, merge-tree and cherry reads are marked when the reading runs out. Four of the reads owe nothing on their own account once the context has ended: no preflight for a receipt it could not read, no merge for an ancestry it could not ask, and no merge or arming for a merge queue's rules or armed set it could not read. 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
- Variables
- func JudgeChecklist(v Verdict, b Behind, in StopInput, st SessionState, away bool) (out Verdict, present SessionState, save bool)
- func Managed(root string) bool
- func ManagedContext(ctx context.Context, root string) bool
- func QuestionRoute() string
- func RecordAdded(copyRoot, branch string, made bool, o Options) error
- func RecordCreated(copyRoot, runDir string, changes []BranchChange, o Options) error
- func SaveSession(copyRoot, sessionID string, st SessionState) error
- func TakeChecklistNote(ctx context.Context, copyRoot, sessionID string) (string, error)
- func TrackedPRs(prev []BeatItem) []int
- func ValidSessionID(id string) bool
- func WriteHeartbeat(root string, at time.Time, items []BeatItem) error
- type BackResult
- type BackgroundTask
- type BeatChange
- type BeatItem
- type Behind
- type BranchChange
- type BranchChangeKind
- type Closing
- type CreatedBranch
- type Cron
- type Forge
- type HandBack
- type LiveWork
- type Options
- type Owed
- type OwedItem
- type OwedKind
- type OwnedRef
- type QueuedStep
- type ReadOptions
- type Record
- func (r *Record) AddHandBack(branch, head string, now time.Time) bool
- func (r *Record) AddStep(step, from string, now time.Time) error
- func (r *Record) AddStop(s Stop, now time.Time)
- func (r *Record) Close(who Who, now time.Time)
- func (r *Record) Ends() time.Time
- func (r *Record) Fit()
- func (r *Record) Holds(now time.Time) bool
- func (r *Record) Lapsed(now time.Time) bool
- func (r *Record) LapsedLine() string
- func (r *Record) LapsedSessionLine() string
- func (r *Record) Lines() []string
- func (r *Record) PersonLine() string
- func (r *Record) Terms() []string
- type SessionCron
- type SessionNote
- type SessionState
- type Stop
- type StopInput
- type StopKind
- type Store
- func (s Store) Away(now time.Time) (*Record, bool, error)
- func (s Store) CreatedBranches(copyKey string) ([]CreatedBranch, error)
- func (s Store) Dir() string
- func (s Store) Display(name string) string
- func (s Store) LockPath() string
- func (s Store) NoteSessionCopy(sessionID, copy string, now time.Time) (bool, error)
- func (s Store) Read() (*Record, error)
- func (s Store) ReadFile(name string) ([]byte, error)
- func (s Store) RecordBranches(copyKey string, changes []BranchChange, now time.Time) error
- func (s Store) RecordHandBack(branch, head string, now time.Time) (bool, error)
- func (s Store) RecordPath() string
- func (s Store) RecordStop(st Stop, now time.Time) (bool, error)
- func (s Store) Rel() string
- func (s Store) RootSHA() string
- func (s Store) SessionCopy(sessionID string) (string, bool)
- func (s Store) Update(fn func(cur *Record) (*Record, error)) (*Record, error)
- func (s Store) WithLock(fn func() error) error
- func (s Store) WriteFile(name string, data []byte) error
- type Verdict
- type Who
Constants ¶
const ( BeatReservation = "reservation" BeatPullRequest = "pull_request" BeatDisk = "disk" // BeatForge is a read the heartbeat could not make at all (the // reservations' fetch, the listing of the account's pull requests). BeatForge = "forge" )
The kinds of fact a heartbeat reports.
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).
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 )
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 // MinWakeLead is the least time from now a deadline is given: a few // minutes, the lead a wake set now needs to fire within, the host's // lateness for a task due in the next minute or two included // (iss-2611011332417169). A deadline any sooner is one no wake scheduled // now can meet. MinWakeLead = 3 * time.Minute )
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).
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.
const HeartbeatRel = ".abcd/.work.local/heartbeat.json"
HeartbeatRel is where the last heartbeat's facts are kept, in the checkout's local tier.
const LiveWorkBound = landing.PreflightBound
LiveWorkBound is how long a session waits on live work for one unchanged set of capped items before the set is held to MaxWakesUnchanged again: landing's bound on one `make preflight`, its wait at the load gate, its race stage's wait at the race gate and the run itself (12h + 2h + 4h), which landing's own test holds to the Makefile. It is measured from the first waiting check (SessionState.WaitingSince), and restarts when the capped set changes, so it does not hold against a set that keeps changing; the wake count has the same property.
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).
const MaxSessionNotes = 256
MaxSessionNotes bounds the notes kept; the oldest go first.
const MaxStepLen = 500
MaxStepLen bounds a queued step, in characters, so one step cannot fill the record's 64 KiB.
const MaxWakesUnchanged = 2
MaxWakesUnchanged is how many wakes in a row may release an unchanged set of capped items (dcn-2610181035361997), while live work does not stand for every one of them (Owed.CappedAllLive).
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).
const RulesetDeadline = 3 * time.Second
RulesetDeadline bounds each forge read that decides whether a merge queue keeps a behind pull request current (iss-2610311339274372): the default branch's live rules, and its armed or queued pull requests. Both run inside the stop check's own budget, after the listing.
const SchemaVersion = 1
SchemaVersion is the record's shape version, written as schema_version.
const SessionNoteTTL = 30 * 24 * time.Hour
SessionNoteTTL is how long a note is kept: a session older than this is long over.
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.
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").
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).
const StoreName = "the away store"
StoreName is the noun the checkout-root refusals are phrased with.
Variables ¶
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") )
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") )
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") )
var ErrChecklistNoteForeign = errors.New("the behind note in the session's state is not one abcd words, so it was dropped")
ErrChecklistNoteForeign is TakeChecklistNote's word for a note in the session's state that abcd did not word: it is cleared and nothing is shown.
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.
var ErrHeartbeatNoTier = errors.New("this checkout has no .abcd/.work.local/, so the heartbeat keeps nothing between runs; run abcd ahoy to set it up")
ErrHeartbeatNoTier is a checkout without its local tier, where the heartbeat keeps its facts.
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 JudgeChecklist ¶ added in v0.17.0
func JudgeChecklist(v Verdict, b Behind, in StopInput, st SessionState, away bool) (out Verdict, present SessionState, save bool)
JudgeChecklist folds the behind check into the stop verdict v that Judge returned over st, the session's state before it.
While away (v.Save), a set other than the one last blocked on blocks the stop once, naming it: added to a block's reason, or, on a stop Judge allowed, as a block of its own, counted toward the host's continuation cap as every block is and never past it. Only the last set is kept, so the block is once per consecutive set: a set that comes back after another blocks again, within the cap. The set last blocked on, or a block the cap would override, leaves v as it was. While present the stop is never blocked: a set not yet noted is kept in the session's state for the next prompt (TakeChecklistNote), and save says the state must be written.
func Managed ¶
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 ManagedContext ¶ added in v0.17.0
ManagedContext is Managed bound to ctx, for a hook on a deadline: the one git call a linked worktree takes is killed when ctx ends, and a call ctx ended answers false.
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 RecordAdded ¶
RecordAdded records the branch a verb has just checked out in a worktree it added, the worktree store's add verb (iss-2611211734561033), which the guard's recorder never sees, since it reads only git command lines: made, a branch the verb created, recorded as a creation (a name recorded before is this creation's now); otherwise an existing branch it checked out, added once. It runs after the worktree is made, so it judges nothing against the repository: the verb's own refusals did. Each name keeps the session o names (Options.SessionID) as its creator. A checkout abcd does not manage, or with no root commit, records nothing and is no error; the error is a store it could not write, which never undoes the worktree.
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, each added name with the session o names (Options.SessionID) as its creator, so the stop check can tell one session's branches from another's in a copy two share. 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 TakeChecklistNote ¶ added in v0.17.0
TakeChecklistNote is the behind note the stop hook left for this session, cleared as it is taken, so one note reaches one prompt; "" when none waits. The state's read runs under ctx, the prompt hook's deadline. The noted set is kept, so the same set is not noted again until the checklist has caught up.
The note is read back from a file any process of this account can write, so it is cleaned as it is read, not only as it was written: one line, no control or bidi character, within maxNoteBytes, and opening with the words Note opens with, so it can never start a heading of its own in the prompt.
func TrackedPRs ¶
TrackedPRs is each pull request number prev read that is not yet terminal, ascending: the next heartbeat reads them again, so a pull request that merged or closed is reported once even after it leaves the account's open listing.
func ValidSessionID ¶
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 BeatChange ¶
type BeatChange struct {
BeatItem
Was string `json:"was,omitempty"`
Gone bool `json:"gone,omitempty"`
}
BeatChange is a fact that changed since the last heartbeat: new, in another state (Was names the state it was in), or gone (a reservation no longer held, or a read that now succeeds).
func HeartbeatChanges ¶
func HeartbeatChanges(prev, now []BeatItem) []BeatChange
HeartbeatChanges is every fact of now that is new or in another state than in prev, then every fact of prev gone from now: a reservation, a disk reading or a failed read no longer there, and a pull request not yet terminal that is no longer read. A terminal pull request left out of now is no change: the heartbeat stops reading it once it has reported it. Facts come in now's order, then prev's.
type BeatItem ¶
type BeatItem struct {
Kind string `json:"kind"`
Key string `json:"key"`
State string `json:"state"`
Line string `json:"line"`
Terminal bool `json:"terminal,omitempty"`
}
BeatItem is one fact a heartbeat read: its kind, its key within the kind (a record id, "#N", the disk), the state it is compared on, and the line a person reads. Terminal marks a pull request merged or closed, which the next heartbeat no longer reads unless asked.
func ReadHeartbeat ¶
ReadHeartbeat is the last heartbeat's facts and when it ran, kept in the checkout at root; none and the zero time when no heartbeat has run here. A file that cannot be read or does not parse is an error, and the caller judges every fact new.
type Behind ¶ added in v0.17.0
type Behind struct {
// Unlisted are the owned references no item names.
Unlisted []string
// Moved are the listed references whose work moved after the checklist
// was last written.
Moved []string
}
Behind is what a checklist does not keep up with.
func CheckBehind ¶ added in v0.17.0
CheckBehind compares the owned work with the checklist a Read returned. A read that found no checklist lists nothing, so every owned reference is unlisted.
func (Behind) Empty ¶ added in v0.17.0
Empty reports whether the checklist keeps up with the owned work.
func (Behind) Fingerprint ¶ added in v0.17.0
Fingerprint identifies the set by its references, so a branch that moves again is not a new set until the checklist has caught up once.
type BranchChange ¶
type BranchChange struct {
Kind BranchChangeKind
Name string
From string
// Session is the host session making the change, kept on a name the
// change adds; "" keeps none. A rename carries the record's own.
Session 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, which it records // as BranchCreated. 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 CreatedBranch ¶
type CreatedBranch struct {
Name string `json:"name"`
At time.Time `json:"at"`
// Session is the host session that created it, as the guard's payload
// named it; "" in a record written before sessions were kept, or by a
// hook with no session id, which says nothing of whose it is.
Session string `json:"session,omitempty"`
}
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 ¶
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 ¶
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 LiveWork ¶ added in v0.17.0
LiveWork is what is running for an owed item, in plain words, and since when.
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
// SessionID is the host session acting, which RecordCreated keeps on
// each branch it records; "" (or an id ValidSessionID refuses) keeps none.
SessionID 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"`
// Owned is the work the session owns as the reading found it, which the
// checklist's behind check compares with the items' owner_refs
// (spc-2610230805429429 step 4).
Owned []OwnedRef `json:"owned,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). A behind pull request into the default branch is judged by its merge queue, read from the forge's live rules under RulesetDeadline (queueKeepsCurrent). 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) CappedAllLive ¶ added in v0.17.0
CappedAllLive reports whether some item is capped and every capped item has live work standing for it: the set is waiting on that work, not stuck.
func (Owed) CappedFingerprint ¶
CappedFingerprint is Fingerprint over the capped items alone, so a renewal falling due or done does not change it.
func (Owed) Fingerprint ¶
Fingerprint identifies the owed set by its items' kind, branch, record, pull request and head, whatever their order and reasons.
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) unless live
// work stands for it (Live).
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"`
// Live is the live work standing for the item, when the reading found
// some (livework.go): the preflight's whole test run of this account,
// its marker written at the item's head, in the worktree its branch is
// checked out in, while no receipt names the head. Nor is it part of the item's identity, so the fingerprints do not
// change as the run ages or ends.
Live *LiveWork `json:"live,omitempty"`
// Unclaimed marks a branch's item that is owed only if this session made
// the branch (iss-2611211734561033): no record names the session that
// did, it is not checked out in a store worktree, and another live
// session works in this copy. The stop then says so, tells the session
// that made it how to push it or queue the push, and says a branch this
// session did not make is a peer's, to be left untouched. Nor is it part
// of the item's identity.
Unclaimed bool `json:"unclaimed,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 OwnedRef ¶ added in v0.17.0
type OwnedRef struct {
Ref string `json:"ref"`
Aliases []string `json:"aliases,omitempty"`
Changed time.Time `json:"changed,omitempty"`
}
OwnedRef is one piece of work the session owns, spelled as a checklist item's owner_refs names it: `branch:<name>` or a reservation's record id. Aliases are other spellings of the same work (a branch's open pull request, `pr:<n>`), any one of which an item may name instead. Changed is when the work last moved (a branch's head commit), zero when unknown.
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
// RulesetDeadline bounds each read that decides whether a merge queue
// keeps a behind pull request current (forge.go): the default branch's
// live rules, and its armed or queued pull requests; zero means
// RulesetDeadline.
RulesetDeadline time.Duration
// Reservations reads the reservations as last fetched, with no network,
// under the check's ctx; nil means claim.ViewContext.
Reservations func(ctx context.Context, 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
// SessionID is the stopping session's id, as the Stop payload carries it.
// With one ValidSessionID accepts, an item another live session holds is
// left out of the owed work and named in a note (holders.go); "" leaves
// every item owed as this copy's, as does any item whose holder the
// evidence cannot tell.
SessionID string
// ProcTable reads the machine's process table under the check's ctx, for
// the live work standing for an owed item (livework.go); nil means
// machineload.ReadContext. It is read at most once a check, and only
// when a run's recorded driver is a process with no session (a drive's
// hold, holders.go) or, while away, a whole run's marker is found.
ProcTable func(ctx context.Context) (machineload.Snapshot, error)
// LiveSessions reads the sessions running on the machine, each with the
// checkout it started in; nil means occupancy.Live under Home with the
// machine's process table. It is read at most once a check, and only
// when an item may be another session's.
LiveSessions func() ([]occupancy.Session, error)
}
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 ¶
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 ¶
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 QueueStepOnce ¶
QueueStepOnce is QueueStep for a step a caller may offer more than once: the check that the record does not already hold the step (its words compared as AddStep keeps them) and the append are one update under the store's lock, so two callers racing queue it once. It reports whether this call queued it; a step already queued writes nothing.
func SetAway ¶
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 ¶
AddHandBack records an item handed back, once per branch and head; it reports whether this call added it.
func (*Record) AddStep ¶
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 ¶
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) Ends ¶
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 ¶
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 ¶
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 ¶
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). It says what is unread and what the end means: the checks the away mode adds are gone, so sessions ask and stop again (iss-2611211733085834).
func (*Record) LapsedSessionLine ¶
LapsedSessionLine is the one line the prompt hook gives the session on every prompt in the same case as LapsedLine, and "" otherwise (iss-2611211733085834): the window ended, the checks the away mode adds no longer hold, and only the person's word sets it again. Without it a session cannot tell that its questions and turn ends are no longer checked.
func (*Record) Lines ¶
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 ¶
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).
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). A wake that releases a set waiting on live work
// does not add to it.
Wakes int `json:"wakes"`
WakeFingerprint string `json:"wake_fingerprint,omitempty"`
// WaitingSince is the first check that found live work standing for
// every capped item of the set WakeFingerprint names (Owed.CappedAllLive),
// zero before one; reset with WakeFingerprint. The wait it starts is
// bounded by LiveWorkBound, measured from it rather than from the run's
// age, so a run restarted at each wake cannot renew it. It restarts when
// the capped set changes, so the bound does not hold against a set that
// keeps changing (nor does the wake count). A new commit changes the set,
// but a run whose marker was written at the old head does not count for
// the new one (TestLiveWholeRunHeadMovedUnderIt), so committing does not
// keep a hung run counted. A value later than now, the clock having
// stepped back, is moved to now, the earlier of the two
// (TestLiveWorkClockSteppedBack).
WaitingSince time.Time `json:"waiting_since,omitempty"`
// ChecklistBlocked is the behind set (Behind.Fingerprint) a stop was
// last blocked on while away, so a set blocks once per consecutive run of
// stops on it; "" once the
// checklist caught up.
ChecklistBlocked string `json:"checklist_blocked,omitempty"`
// ChecklistNoted is the behind set last left for the prompt hook while the
// person was present, and ChecklistNote that note, until the next prompt
// takes it into the session's context.
ChecklistNoted string `json:"checklist_noted,omitempty"`
ChecklistNote string `json:"checklist_note,omitempty"`
}
SessionState is one session's stop-check state, kept between hook runs in SessionsDir/<session-id>.json.
func LoadSession ¶
func LoadSession(ctx context.Context, 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. Its one git call, the tracked check, is bound to ctx: a hook reads it under its own deadline, and a ctx that ends first refuses, as git not answering does.
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 ¶
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 ¶
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 ResolveCopyContext ¶ added in v0.17.0
func ResolveCopyContext(ctx context.Context, cwd, sessionID string, o Options) (string, Store, error)
ResolveCopyContext is ResolveCopy bound to ctx, for a hook on a deadline: every git call it makes is killed when ctx ends. A noted copy whose check ctx cut short is not confirmed, as one git cannot answer for.
func (Store) Away ¶
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) NoteSessionCopy ¶
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 ¶
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 ¶
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 ¶
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 name is recorded anew, with this change's session and time, even when the list already holds it (a branch deleted and made again is a new branch, and its first creator's record would hand it to that session); a 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 ¶
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) RecordStop ¶
RecordStop records a stop at now, only if the record re-read inside the lock still holds; it reports whether it wrote.
func (Store) SessionCopy ¶
SessionCopy is the session's noted start copy, when it has one that is still a directory.
func (Store) Update ¶
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.
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 ¶
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:
- the last message ends on a line ending in `?`, not yet blocked for this message: block with the reroute's reason;
- owed, the set changed (or the first check): block, naming the next item and the count;
- owed, unchanged, a qualifying wake, and no capped item owed, live work standing for every capped item (Owed.CappedAllLive) within LiveWorkBound of the first check that found it, or the wake count below two: allow (waiting; the wake count adds one if a capped item is owed and live work does not stand for every one);
- owed, unchanged, a qualifying wake, a capped item owed and the wake count at two: block, saying the wait is past LiveWorkBound when live work stood for every capped item;
- owed, unchanged, no qualifying wake: block, naming the live work and since when when it stands for every capped item;
- none owed, a qualifying wake: allow (waiting);
- 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.