Documentation
¶
Overview ¶
Package task holds what the daemon, the bridge and `stagent task` share about tasks (タスク): the canonical path of a source checkout (元のチェ ックアウト), which paths lie in a worktree, and running git.
Index ¶
- Constants
- func Canonical(ctx context.Context, env []string, dir string) (string, error)
- func CanonicalPath(p string) string
- func Changes(ctx context.Context, env []string, worktree string, links []string) ([]string, error)
- func CheckBranch(ctx context.Context, env []string, repo, name string) error
- func CopyFiles(ctx context.Context, j CopyJob)
- func CurrentBranch(ctx context.Context, env []string, dir string) (string, error)
- func DefaultBranch(ctx context.Context, env []string, repo string) (string, error)
- func GH(ctx context.Context, env []string, dir string, args ...string) ([]byte, error)
- func Git(ctx context.Context, env []string, dir string, args ...string) ([]byte, error)
- func GitBash(git string) string
- func HasRef(ctx context.Context, env []string, repo, ref string) bool
- func IsDir(p string) bool
- func IsLink(fi fs.FileInfo) bool
- func IssueBranch(number int, title string) string
- func LinkDir(target, link string) error
- func Main(args []string) int
- func Merged(ctx context.Context, env []string, repo, head string, bases ...string) (bool, error)
- func NewID() string
- func NoLocks(env []string) []string
- func PosixPath(p string) string
- func Prepare(ctx context.Context, p Prep) error
- func Preview(ctx context.Context, env []string, repo string, patterns []string) (*wire.TaskPreviewResult, error)
- func PullRequestRefs(ctx context.Context, env []string, repo string, number int) (head, base string, err error)
- func Refusals(ctx context.Context, env []string, ws []Worktree, worktree string, ours bool) ([]wire.RemoveRefusal, error)
- func RelayRef(id string) string
- func Remove(ctx context.Context, r Removal) (keptBranch string, err error)
- func RemoveEmptyParent(folder, path string) string
- func RemoveMissing(ctx context.Context, r Removal) (keptBranch string)
- func RunScript(ctx context.Context, s Script) error
- func SameKey(t *wire.Task, repo, kind string, number int, name string) bool
- func SamePath(a, b string) bool
- func SaveRelayPrep(dir string, p RelayPrep) error
- func SavedConfig(configPath string) wire.Config
- func SavedPatterns(configPath, repo string) []string
- func SavedWorktreeFolder(configPath string) string
- func SetupApproved(path, repo, hash string) bool
- func SetupHash(script string) string
- func ShareLinks(repo, worktree string) []string
- func Submodules(ctx context.Context, env []string, worktree string) (*wire.RemoveRefusal, error)
- func Unpushed(ctx context.Context, env []string, repo, branch string) (int, error)
- func UnregisterArgs(ctx context.Context, env []string, dir string) []string
- func ValidName(ctx context.Context, env []string, repo, name string) error
- func ValidPattern(p string) error
- func ValidRepoKey(key string) error
- func WithLimit(ctx context.Context, env []string, d time.Duration) (context.Context, context.CancelFunc)
- func Within(p, dir string) bool
- func Worktrees(ctx context.Context, env []string, repo string) ([]string, error)
- type CopyJob
- type CopyPlan
- type CopySpec
- type GitError
- type LimitError
- type Orca
- type OrcaError
- type Prep
- type RefusedError
- type RelayPrep
- type Removal
- type RemovalResult
- type Script
- type ScriptPlan
- type SetupApproval
- type SetupApprovals
- type StageError
- type Worktree
Constants ¶
const ( ExitFailure = 1 ExitUsage = 2 ExitNotFound = 127 )
Exit codes of `stagent task`.
const ( // MaxCopyBytes and MaxCopyEntries bound what one worktree gets; an // entry that would pass either is skipped (limit). MaxCopyBytes = 2 << 30 MaxCopyEntries = 50_000 )
const ( // LimitRelayBundle: git bundle create. LimitRelayBundle = 180 * time.Second // LimitRelayGit: each other git command of relay.prepare and // relay.start. LimitRelayGit = limitCheck // LimitRelayClone: git clone of relay.start's clone. LimitRelayClone = 600 * time.Second )
The time limits of a relay's git commands (PROTOCOL.md "Relay"), scaled the same way.
const ( RelayBundle = "repo.bundle" RelayStaged = "staged.patch" RelayUnstaged = "unstaged.patch" RelayUntracked = "untracked" // RelayPrepFile is RelayPrep in the relay's directory. RelayPrepFile = "task.json" )
The working tree parts of a relay, in RelayPrep.Tree.
const AddingLock = "initializing"
AddingLock is the reason of the lock `git worktree add` holds on the worktree it is making until its checkout is done. stagent runs its own add in the C locale, where git does not translate it.
const EnvGitTimeoutScale = "STAGENT_GIT_TIMEOUT_SCALE"
EnvGitTimeoutScale multiplies those limits by a positive number (5: five times as long) for a repository too large for them (LFS). Set in the login shell's environment, it reaches the bridge and the task's sessions.
const IncludeFile = ".worktreeinclude"
IncludeFile is Orca's list of paths to copy, at a checkout's root.
const OrcaFile = "orca.yaml"
OrcaFile is Orca's per-repository settings file, at a checkout's root. stagent only reads it.
Variables ¶
This section is empty.
Functions ¶
func Canonical ¶
Canonical returns the canonical path (正の形) of the source checkout that dir lies in: `git rev-parse --show-toplevel`, symlinks resolved (CanonicalPath). A linked worktree is a checkout of its own: it is not mapped to its main worktree. Task.Repo and task.preview's repo are this value, as is the key of config.json's repos.
func CanonicalPath ¶
CanonicalPath makes p absolute and clean, resolves its symlinks when it exists and, on Windows, upper-cases its drive letter.
func Changes ¶
Changes lists what removing worktree would lose, as `git status --porcelain` lines: tracked files changed (staged or not) and untracked files git does not ignore. Ignored files (a copied .env) are not changes, nor are the shared-directory links named in links (paths relative to worktree, see ShareLinks). The user's git settings (status.showUntrackedFiles, submodule ignores) do not hide any: each untracked file is a line, and a submodule with changes inside is one. git status takes no optional lock (NoLocks): an agent may be working in worktree. A git status over its time limit (limitCheck) is an error wrapping a *LimitError.
func CheckBranch ¶
CheckBranch fails when name cannot be a branch name.
func CopyFiles ¶
CopyFiles links the shared directories and then copies what is to be copied into j.Dest, leaving every destination that exists as it is (a retry copies only what is missing), and nothing under a link. A shared directory that cannot be linked gets one warning line; what is listed under it is copied as ordinary files instead. Nothing here fails the task: errors are lines in the terminal.
func CurrentBranch ¶
CurrentBranch is the branch checked out in dir, "" when detached.
func DefaultBranch ¶
DefaultBranch is the repository's default branch as the checkout repo knows it: origin/HEAD (set by clone, or `git remote set-head origin --auto`), else origin's main or master.
func GH ¶
GH runs gh in dir with env (nil: this process's), found on env's PATH, and returns its standard output. A failing gh is an error with its last stderr line, or wrapping its *LimitError when ctx's limit stopped it.
func Git ¶
Git runs git in dir with env (nil: this process's environment) and returns its standard output, running it again while it fails on a lock another git holds (retryLocked). git is looked up in env's PATH. On Windows every call gets -c core.longpaths=true. A git that cannot be found is an error wrapping exec.ErrNotFound; one that fails is a *GitError, wrapping a *LimitError when ctx's limit stopped it.
func GitBash ¶ added in v0.19.0
GitBash finds Git for Windows' bash.exe from git's path (…\Git\cmd\ git.exe, …\Git\bin\git.exe or …\Git\mingw64\bin\git.exe): bin\bash.exe or usr\bin\bash.exe under the installation. "" when there is none — System32's bash.exe is WSL's, not Git Bash.
func IssueBranch ¶
IssueBranch is an issue's default branch: <number>-<slug>, the slug being its title lower-cased, every run of characters other than a-z and 0-9 one hyphen, trimmed of hyphens, at most 40 characters. When nothing of the title is left the branch is issue-<number>.
func LinkDir ¶
LinkDir makes link a symbolic link to the directory target (a shared directory of a task's worktree).
func Merged ¶ added in v0.19.0
Merged reports whether removing a branch at commit head loses nothing its bases do not have. bases are branch names, each compared as origin's remote-tracking branch and as the local branch, whichever exist: head is an ancestor of one (a merge), or its changes are in one already (a squash or rebase merge). That is, `git merge-tree --write-tree` of the base and head comes out as the base's own tree; when the base changed the same lines since, every commit of a branch without merges has its patch in the base (`git cherry`), or merging head into the base's commit that touched exactly the files head changed comes out as that commit's tree. Changes nobody made (empty commits) are not merged. What git writes meanwhile goes to a temporary object directory: telling leaves nothing in the repository.
An error means git could not tell: one before 2.38 has no merge-tree --write-tree.
func NoLocks ¶ added in v0.19.0
NoLocks is env (nil: this process's) with git's optional locks off, so git status never writes the index of a worktree an agent works in.
func Prepare ¶
Prepare runs the stages of p's task in order — fetch, branch, worktree, copy, setup — stopping at the first that fails (*StageError). A worktree task whose directory is left empty then has it removed (after leaving it when it is the working directory). Every stage can run twice: a task that failed is prepared again with the same task (ADR 0006).
func Preview ¶
func Preview(ctx context.Context, env []string, repo string, patterns []string) (*wire.TaskPreviewResult, error)
Preview is task.preview for the source checkout repo (canonical) with the app's patterns: the plan, at most wire.TaskPreviewRows copies and skips, and the checkout's orca.yaml scripts.setup or why that file is unusable (its sharedDirectories then ignored).
func PullRequestRefs ¶
func PullRequestRefs(ctx context.Context, env []string, repo string, number int) (head, base string, err error)
PullRequestRefs asks gh, in the checkout repo, for a pull request's head branch (a task's branch, what `gh pr checkout` checks out) and base branch.
func Refusals ¶ added in v0.19.0
func Refusals(ctx context.Context, env []string, ws []Worktree, worktree string, ours bool) ([]wire.RemoveRefusal, error)
Refusals lists why worktree (canonical), of the repository whose worktrees are ws (ListWorktrees), is not removed whatever force says (確認に並ぶ断る理由): the one place task.remove, worktree.remove and worktree.list tell them. In this order: the other worktrees of ws inside it whose directory is there (nested_worktrees, in git's order) — git worktree remove would take them with it, their changes included, when the outer worktree ignores them; its submodules (submodules, see Submodules), which git worktree remove refuses; a lock on it (locked). The lock of a killed git worktree add (HalfMade) is no refusal when ours — worktree is a task's, whose add only its own preparation runs, so that add is gone and 片付け takes the worktree — but is for another tool's worktree, whose add may still be at work.
func RelayRef ¶ added in v0.26.0
RelayRef is the ref a relay's bundle is fetched to until its branch is made.
func Remove ¶
Remove runs the stages of r's removal in order — archive (when asked), worktree (unlink the shared-directory links, then git worktree remove), branch — stopping at the first that fails (*StageError). A worktree with Refusals (ours when r.Task is a task, with an ID) is not touched: the worktree stage fails with a *RefusedError before archive. A task's worktree a killed `git worktree add` left half made has no archive (nothing was checked out). git's worktree list is read once, and again after an archive script ran: the script may have removed or unregistered the worktree itself. It returns the task's branch when it is kept (see removeBranch). Remote branches are never deleted.
func RemoveEmptyParent ¶ added in v0.19.0
RemoveEmptyParent removes the directory path was in when that is <folder>/<repo name> — directly in the worktree folder — and empty now but for macOS Finder's .DS_Store, and returns it ("" otherwise, and without folder).
func RemoveMissing ¶ added in v0.19.0
RemoveMissing is 片付け of a missing task, what `stagent task remove --missing` runs: its own worktree is unregistered when git still lists it without its directory (best effort — the record goes anyway — and never the repository's other worktrees, ADR 0016), then the branch stage as in Remove. A directory that is there is not touched. It returns the branch when it is kept.
func RunScript ¶
RunScript runs s (PlanScript for this OS) in s.Dir and waits for it. A script exiting non-zero is an error naming its exit code.
func SameKey ¶ added in v0.14.0
SameKey reports whether t is the task keyed by the source checkout repo (canonical) and, for kind name, name (exactly), else number: a named task never shares its key with an issue's or PR's.
func SamePath ¶
SamePath reports whether two canonical paths name the same place (case-insensitively on Windows).
func SaveRelayPrep ¶ added in v0.26.0
SaveRelayPrep writes p to dir/RelayPrepFile.
func SavedConfig ¶ added in v0.18.0
SavedConfig is config.json as stored (defaults not applied); a missing or unreadable one is empty.
func SavedPatterns ¶
SavedPatterns reads the app's patterns for the source checkout repo (canonical) from config.json at configPath. Only the daemon writes that file (config.set); a missing or unreadable one has none.
func SavedWorktreeFolder ¶ added in v0.14.0
SavedWorktreeFolder reads the worktree folder (worktree の置き場) from config.json at configPath, as config.set stored it: absolute and clean. "": none set, or a missing or unreadable file.
func SetupApproved ¶ added in v0.19.0
SetupApproved reports whether the approvals file at path ("": none) approves hash for repo; one that cannot be read approves nothing.
func SetupHash ¶ added in v0.19.0
SetupHash names a scripts.setup content: the hex SHA-256 of its text.
func ShareLinks ¶
ShareLinks lists the shared directories (worktree.sharedDirectories of the source checkout's orca.yaml) that are links in worktree — symbolic links, or junctions on Windows — as slash-separated paths relative to it. An orca.yaml that cannot be read has none.
func Submodules ¶ added in v0.19.0
Submodules is the submodules refusal of worktree (an existing directory), nil when it has none: as git worktree remove decides, its git directory has modules, or a submodule of its index is checked out. Paths are the submodules of its index (canonical). It takes no lock.
func Unpushed ¶
Unpushed counts the commits of the checkout repo's local branch that no remote-tracking branch has (`git rev-list <branch> --not --remotes --count`); 0 when there is no such branch.
func UnregisterArgs ¶ added in v0.19.0
UnregisterArgs are the git arguments that unregister the worktree at dir, whose directory is gone, and no other worktree: `worktree remove <dir>` on git 2.18 and later. An older git cannot remove a worktree whose directory is gone, so `worktree prune` stands in, unregistering every such worktree of the repository. Neither touches a locked worktree: remove refuses it, prune skips it.
func ValidName ¶ added in v0.14.0
ValidName fails when name cannot be a named task's name: it must be 1–64 characters without whitespace, control characters or any of / \ : * ? " < > |, not start with . or -, and be a branch name git takes as it is (`git check-ref-format --branch`, run in the checkout repo, printing it back: @ and @{-N} name other branches). The name is also a directory under the worktree folder and the default branch; the app mirrors all but the git check.
func ValidPattern ¶
ValidPattern reports why p cannot be an app pattern (a git pathspec glob from the checkout's root): empty, a negation (!), absolute, or with a .. or .git component.
func ValidRepoKey ¶
ValidRepoKey reports why key cannot be a key of config.json's repos: it must be an absolute, clean path (no trailing separator). Whether it exists does not matter.
func WithLimit ¶ added in v0.26.0
func WithLimit(ctx context.Context, env []string, d time.Duration) (context.Context, context.CancelFunc)
WithLimit limits ctx to d scaled by env's EnvGitTimeoutScale (env nil: this process's). When the limit ends it, context.Cause is a *LimitError.
Types ¶
type CopyJob ¶
type CopyJob struct {
CopySpec
Dest string
// Out (the terminal) gets one line per link, copy and skip.
Out io.Writer
// Link makes link point to the directory target; nil: LinkDir.
Link func(target, link string) error
}
CopyJob is the copy stage: spec's links and copies made in Dest, a new worktree of spec.Repo.
type CopyPlan ¶
type CopyPlan struct {
Copies []wire.TaskCopy
Links []string // shared directories, relative with / separators
Skipped []wire.TaskSkip
TotalBytes int64
}
CopyPlan is a resolved CopySpec, every shared directory taken as linked.
type CopySpec ¶
type CopySpec struct {
// Repo is the source checkout (canonical).
Repo string
// Env is git's environment (nil: this process's).
Env []string
// Patterns are the app's (config.json repos.<Repo>.worktree_include).
Patterns []string
Shared []string
}
CopySpec is what a worktree of Repo gets copied and linked.
type LimitError ¶ added in v0.19.0
LimitError is a git or gh command stopped at its time limit.
func (*LimitError) Error ¶ added in v0.19.0
func (e *LimitError) Error() string
type Orca ¶
type Orca struct {
Setup string // scripts.setup ("": none)
Archive string // scripts.archive ("": none)
}
Orca is what stagent uses of an orca.yaml. Which checkout's file counts depends on the key: scripts.setup comes from the task's worktree; scripts.archive and worktree.sharedDirectories from the source checkout (元のチェックアウト).
func LoadOrca ¶
LoadOrca reads the orca.yaml in dir. No file is (nil, nil). Like Orca, a file that is larger than 256 KiB, is not valid YAML, repeats a key or is not a mapping is refused whole (*OrcaError); a value of the wrong type, or a string over 64 KiB, is dropped alone and the rest kept. Unknown keys are ignored.
type Prep ¶
type Prep struct {
Task wire.Task
// SwitchBranch (in_place only): switch the checkout to Task.Branch.
SwitchBranch bool
// Setup (in_place only): run scripts.setup. A worktree task always
// runs it.
Setup bool
// WorktreeInclude are the app's patterns of files to copy into a
// worktree task's worktree (config.json repos.<repo>.worktree_include).
WorktreeInclude []string
// Env is the environment of git, gh and the setup script; nil: this
// process's.
Env []string
// Stdin feeds the setup script (nil: none); Out, the terminal, gets
// the stage headers, the commands run and their output.
Stdin io.Reader
Out io.Writer
// Stage is told each stage as it starts (task.progress).
Stage func(stage string)
// SetupApprovals is the file of the scripts.setup contents the user
// approved (paths.Layout.SetupApprovals; "": none).
SetupApprovals string
// AskSetup is asked, with the script, when the worktree's
// scripts.setup is neither the source checkout's nor approved for it
// (ADR 0023): true runs it, false skips it. nil: it is skipped.
AskSetup func(ctx context.Context, script string) (bool, error)
// Relay (a relay's task, never in_place): its fetch and branch stages
// take the relay's commits and a relay stage after worktree applies
// its uncommitted changes and untracked files.
Relay *RelayPrep
}
Prep is a task to prepare: what `stagent task run` does in the task's first session before it starts the agent (ADR 0006).
type RefusedError ¶ added in v0.19.0
type RefusedError struct {
Worktree string
Refusals []wire.RemoveRefusal
}
RefusedError is a removal refused for Refusals of Worktree.
func (*RefusedError) Error ¶ added in v0.19.0
func (e *RefusedError) Error() string
type RelayPrep ¶ added in v0.26.0
type RelayPrep struct {
ID string `json:"relay_id"`
// Tree holds the working tree parts: RelayBundle, RelayStaged,
// RelayUnstaged and RelayUntracked/ (each absent when empty).
Tree string `json:"tree"`
// Remote is the checkout's remote whose URL is the package's (""
// none): fetched first, for the commits the bundle builds on.
Remote string `json:"remote,omitempty"`
// Head is the source's HEAD commit, the branch's tip.
Head string `json:"head"`
// CwdRel is where in the worktree the agent starts ("/" separated).
CwdRel string `json:"cwd_rel,omitempty"`
// contains filtered or unexported fields
}
RelayPrep is what a relay target's task (`stagent task run --relay`) takes from the relay: where the package's working tree parts are and what its branch is made from (PROTOCOL.md "Relay"). relay.start writes it to RelayPrepFile in the relay's directory.
func LoadRelayPrep ¶ added in v0.26.0
LoadRelayPrep reads dir/RelayPrepFile.
type Removal ¶
type Removal struct {
Task wire.Task
// Archive runs scripts.archive of the source checkout's orca.yaml
// first, in the worktree.
Archive bool
// Force removes a worktree with changes (git worktree remove --force).
Force bool
// Env is the environment of git, gh and the archive script; nil: this
// process's.
Env []string
// Stdin feeds the archive script (nil: none); Out, the terminal (nil:
// nowhere), gets the stage headers, the commands run and their output.
Stdin io.Reader
Out io.Writer
// Stage is told each stage as it starts (task.progress).
Stage func(stage string)
}
Removal is 片付け of a worktree task once its sessions have stopped: what `stagent task remove` runs in a session of the source checkout, and `stagent task remove-worktree` for a worktree no task has (ADR 0006).
type RemovalResult ¶ added in v0.19.0
type RemovalResult struct {
KeptBranch string `json:"kept_branch,omitempty"`
RemovedParent string `json:"removed_parent,omitempty"`
Error string `json:"error,omitempty"`
Refusals []wire.RemoveRefusal `json:"refusals,omitempty"`
}
RemovalResult is what `stagent task remove` and `stagent task remove-worktree` write to the --result file once the removal is over: the branch it kept and the empty parent it removed (RemoveEmptyParent), or why it failed (with the refusal reasons when it was refused).
type Script ¶
type Script struct {
Text string
// Dir is the task's worktree: the working directory and
// ORCA_WORKTREE_PATH (ORCA_WORKSPACE_NAME is its base name).
Dir string
// Root is the source checkout (元のチェックアウト): ORCA_ROOT_PATH.
Root string
// Env is the environment before the ORCA_* variables; nil: this
// process's.
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
Script is an orca.yaml script (scripts.setup, scripts.archive) to run the way Orca runs it.
type ScriptPlan ¶
ScriptPlan is how a Script runs: Program with Args and, when Runner is set, the path of a file holding Runner (suffix RunnerExt) as the last argument; Env is its environment.
func PlanScript ¶
func PlanScript(goos string, s Script, git string) (ScriptPlan, error)
PlanScript decides how s runs on goos. git is git's path, used on Windows only, to find Git for Windows' bash.exe next to it.
- Linux, macOS: the login shell (SHELL of s.Env when it is a POSIX shell, else /bin/sh) as `<shell> -l -c`, with `set -e` first: the first failing command fails the script.
- Windows: cmd.exe (%ComSpec%) runs a .cmd runner, as Orca's: every line is `call`ed and the first one failing (errorlevel) ends it. A script starting with #! runs in Git for Windows' bash.exe instead, with `set -e` and the ORCA_* paths in /c/… form; without that bash it is an error.
type SetupApproval ¶ added in v0.19.0
type SetupApproval struct {
Repo string `json:"repo"`
Hash string `json:"hash"`
At time.Time `json:"at"`
}
SetupApproval is one content (Hash, SetupHash) approved for the source checkout Repo (canonical).
type SetupApprovals ¶ added in v0.19.0
type SetupApprovals struct {
Approved []SetupApproval `json:"approved"`
}
SetupApprovals is the file of approved scripts.setup contents (paths.Layout.SetupApprovals), written by the daemon only (task.setup).
func LoadSetupApprovals ¶ added in v0.19.0
func LoadSetupApprovals(path string) (SetupApprovals, error)
LoadSetupApprovals reads the approvals file (none: no approvals).
func (SetupApprovals) Has ¶ added in v0.19.0
func (a SetupApprovals) Has(repo, hash string) bool
Has reports whether hash is approved for repo.
type StageError ¶
StageError is the stage that failed and why.
func (*StageError) Error ¶
func (e *StageError) Error() string
func (*StageError) Unwrap ¶
func (e *StageError) Unwrap() error
type Worktree ¶
type Worktree struct {
Path string // canonical
Branch string // short name; "" when detached (or bare)
Head string
Missing bool // its directory is gone (prunable)
Locked bool
LockReason string
}
Worktree is one entry of `git worktree list`.
func FindWorktree ¶ added in v0.19.0
FindWorktree is the entry of ws at worktree (canonical), nil when there is none.
func ListWorktrees ¶
ListWorktrees lists the worktrees `git worktree list` knows for the checkout repo, its main worktree first. An error means git could not answer: not found (wrapping exec.ErrNotFound) or failing, e.g. because repo is gone.
func WorktreeAt ¶ added in v0.19.0
WorktreeAt is the entry of the checkout repo's worktree list at worktree (canonical), nil when git does not list it. An error means git could not answer, as for ListWorktrees.