task

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 32 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 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

View Source
const (
	ExitFailure  = 1
	ExitUsage    = 2
	ExitNotFound = 127
)

Exit codes of `stagent task`.

View Source
const (

	// MaxCopyBytes and MaxCopyEntries bound what one worktree gets; an
	// entry that would pass either is skipped (limit).
	MaxCopyBytes   = 2 << 30
	MaxCopyEntries = 50_000
)
View Source
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.

View Source
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.

View Source
const IncludeFile = ".worktreeinclude"

IncludeFile is Orca's list of paths to copy, at a checkout's root.

View Source
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

func Canonical(ctx context.Context, env []string, dir string) (string, error)

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

func CanonicalPath(p string) string

CanonicalPath makes p absolute and clean, resolves its symlinks when it exists and, on Windows, upper-cases its drive letter.

func Changes

func Changes(ctx context.Context, env []string, worktree string, links []string) ([]string, error)

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

func CheckBranch(ctx context.Context, env []string, repo, name string) error

CheckBranch fails when name cannot be a branch name.

func CopyFiles

func CopyFiles(ctx context.Context, j CopyJob)

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

func CurrentBranch(ctx context.Context, env []string, dir string) (string, error)

CurrentBranch is the branch checked out in dir, "" when detached.

func DefaultBranch

func DefaultBranch(ctx context.Context, env []string, repo string) (string, error)

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

func GH(ctx context.Context, env []string, dir string, args ...string) ([]byte, error)

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

func Git(ctx context.Context, env []string, dir string, args ...string) ([]byte, error)

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

func GitBash(git string) string

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 HasRef

func HasRef(ctx context.Context, env []string, repo, ref string) bool

HasRef reports whether ref names a commit in the checkout repo.

func IsDir

func IsDir(p string) bool

IsDir reports whether p is an existing directory.

func IsLink(fi fs.FileInfo) bool

IsLink reports whether fi (from os.Lstat) is a symbolic link.

func IssueBranch

func IssueBranch(number int, title string) string

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

func LinkDir(target, link string) error

LinkDir makes link a symbolic link to the directory target (a shared directory of a task's worktree).

func Main

func Main(args []string) int

Main is `stagent task`.

func Merged added in v0.19.0

func Merged(ctx context.Context, env []string, repo, head string, bases ...string) (bool, error)

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 NewID

func NewID() string

NewID returns a random 16-hex-char task id.

func NoLocks added in v0.19.0

func NoLocks(env []string) []string

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 PosixPath

func PosixPath(p string) string

PosixPath writes a Windows path the way Git Bash does: C:\a\b is /c/a/b.

func Prepare

func Prepare(ctx context.Context, p Prep) error

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 Remove

func Remove(ctx context.Context, r Removal) (keptBranch string, err error)

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

func RemoveEmptyParent(folder, path string) string

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

func RemoveMissing(ctx context.Context, r Removal) (keptBranch string)

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

func RunScript(ctx context.Context, s Script) error

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

func SameKey(t *wire.Task, repo, kind string, number int, name string) bool

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

func SamePath(a, b string) bool

SamePath reports whether two canonical paths name the same place (case-insensitively on Windows).

func SavedConfig added in v0.18.0

func SavedConfig(configPath string) wire.Config

SavedConfig is config.json as stored (defaults not applied); a missing or unreadable one is empty.

func SavedPatterns

func SavedPatterns(configPath, repo string) []string

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

func SavedWorktreeFolder(configPath string) string

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

func SetupApproved(path, repo, hash string) bool

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

func SetupHash(script string) string

SetupHash names a scripts.setup content: the hex SHA-256 of its text.

func ShareLinks(repo, worktree string) []string

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

func Submodules(ctx context.Context, env []string, worktree string) (*wire.RemoveRefusal, error)

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

func Unpushed(ctx context.Context, env []string, repo, branch string) (int, error)

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

func UnregisterArgs(ctx context.Context, env []string, dir string) []string

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

func ValidName(ctx context.Context, env []string, repo, name string) error

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

func ValidPattern(p string) error

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

func ValidRepoKey(key string) error

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 Within

func Within(p, dir string) bool

Within reports whether canonical path p is dir or lies inside it.

func Worktrees

func Worktrees(ctx context.Context, env []string, repo string) ([]string, error)

Worktrees lists the worktrees `git worktree list` knows for the checkout repo (its main worktree first), as canonical paths.

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.

func PlanCopies

func PlanCopies(ctx context.Context, spec CopySpec) (*CopyPlan, error)

PlanCopies resolves spec: what a new worktree would get when every shared directory links. Only git failing is an error.

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 is orca.yaml's worktree.sharedDirectories of Repo.
	Shared []string
}

CopySpec is what a worktree of Repo gets copied and linked.

type GitError

type GitError struct {
	Args   []string
	Stderr string
	Err    error
}

GitError is git exiting with an error: its first stderr line names why.

func (*GitError) Error

func (e *GitError) Error() string

func (*GitError) Unwrap

func (e *GitError) Unwrap() error

type LimitError added in v0.19.0

type LimitError struct {
	Limit time.Duration
}

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)
	SharedDirectories []string // worktree.sharedDirectories, as written
}

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

func LoadOrca(dir string) (*Orca, error)

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 OrcaError

type OrcaError struct {
	Path string
	Err  error
}

OrcaError is an orca.yaml that cannot be used at all.

func (*OrcaError) Error

func (e *OrcaError) Error() string

func (*OrcaError) Unwrap

func (e *OrcaError) Unwrap() error

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)
}

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 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

type ScriptPlan struct {
	Program   string
	Args      []string
	Runner    string
	RunnerExt string
	Env       []string
}

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

type StageError struct {
	Stage string
	Err   error
}

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

func FindWorktree(ws []Worktree, worktree string) *Worktree

FindWorktree is the entry of ws at worktree (canonical), nil when there is none.

func ListWorktrees

func ListWorktrees(ctx context.Context, env []string, repo string) ([]Worktree, error)

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

func WorktreeAt(ctx context.Context, env []string, repo, worktree string) (*Worktree, error)

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.

func (Worktree) HalfMade added in v0.19.0

func (w Worktree) HalfMade() bool

HalfMade reports whether w is a worktree `git worktree add` was killed making (作りかけ: a session stopped, a crash, power lost): still locked by the add, nothing or part of its files checked out.

Jump to

Keyboard shortcuts

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