Documentation
¶
Overview ¶
Package projects keeps the list of projects a person works in — added, created, cloned, or found from the sessions that ran there — with each one's live git state, its worktrees and what its sessions are doing (.ai/21-app.md § Projects, WP-05 and WP-08).
Git state is never polled. Each repository's `.git` (HEAD, index, refs, worktrees) is watched with fsnotify; a change is debounced and then answered by one `git status` under a timeout, with at most two git processes at once. An idle machine with fifty projects runs no git at all. The reference app ran about 29,000 background git commands in 17 days; this package exists partly so that number stays zero when nothing changes.
Index ¶
- Constants
- Variables
- func CheckCloneURL(raw string) error
- func CheckMessage(msg string) (string, error)
- func EmptyDir(dir string) bool
- func LangOf(path string) string
- type ChangeError
- type ChangeFile
- type Changes
- type CommitResult
- type DiscardPreview
- type FileContent
- type FileList
- type FilePatch
- type GitStatus
- type Hunk
- type Op
- type Patch
- type RemoteResult
- type Service
- func (s *Service) Add(ctx context.Context, path string) (View, bool, error)
- func (s *Service) AddRemote(ctx context.Context, id int64, name, url string) (Changes, error)
- func (s *Service) AddWorktree(ctx context.Context, id int64, spec agents.WorktreeSpec) (agents.Worktree, error)
- func (s *Service) Changes(ctx context.Context, id int64, worktree string) (Changes, error)
- func (s *Service) Clone(opID, rawURL, parent, name string) (Op, bool, error)
- func (s *Service) Close()
- func (s *Service) Commit(ctx context.Context, id int64, worktree, message string, all bool) (CommitResult, Changes, error)
- func (s *Service) Create(ctx context.Context, parent, name string, gitInit bool) (View, error)
- func (s *Service) Diff(ctx context.Context, id int64, worktree, path string, staged bool) (FilePatch, error)
- func (s *Service) Discard(ctx context.Context, id int64, worktree string, paths []string, confirm string) (*DiscardPreview, Changes, error)
- func (s *Service) Fetch(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
- func (s *Service) Get(ctx context.Context, id int64) (View, error)
- func (s *Service) GetOp(id string) (Op, bool)
- func (s *Service) GitRuns() int64
- func (s *Service) List(ctx context.Context) ([]View, error)
- func (s *Service) ListFiles(ctx context.Context, id int64, worktree string) (FileList, error)
- func (s *Service) ListedAt(dir string) (store.Project, bool)
- func (s *Service) Ops() []Op
- func (s *Service) Project(id int64) (store.Project, bool)
- func (s *Service) ProjectFor(dir string) (store.Project, bool)
- func (s *Service) Pull(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
- func (s *Service) Push(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
- func (s *Service) ReadFile(ctx context.Context, id int64, worktree, rel string) (FileContent, error)
- func (s *Service) RemoveWorktree(ctx context.Context, id int64, name string) error
- func (s *Service) Stage(ctx context.Context, id int64, worktree string, paths []string, all bool, ...) (Changes, error)
- func (s *Service) Start(ctx context.Context) error
- func (s *Service) Subjects(ctx context.Context, id int64, worktree, base string) ([]string, error)
- func (s *Service) SystemPrompt(dir string) string
- func (s *Service) Unlist(ctx context.Context, id int64) error
- func (s *Service) Unstage(ctx context.Context, id int64, worktree string, paths []string, all bool, ...) (Changes, error)
- func (s *Service) Update(ctx context.Context, id int64, patch Patch) (View, error)
- func (s *Service) WorktreePath(ctx context.Context, id int64, name string) (string, error)
- func (s *Service) Worktrees(ctx context.Context, id int64) ([]WorktreeView, error)
- type Sessions
- type View
- type WorktreeView
Constants ¶
const ( // MaxChangeFiles is how many files a status lists before it says // Truncated; a checkout with an unignored node_modules lists far more. MaxChangeFiles = 3000 // MaxPatchBytes is how much of one file's patch is returned. MaxPatchBytes = 1 << 20 )
Limits on what is read and returned.
const ( KindInvalid = "invalid" // the request names something it may not KindState = "state" // the worktree is not in a state for it KindStale = "stale" // it changed since the caller looked KindAuth = "auth" // the remote refused the credentials KindNetwork = "network" // the remote could not be reached KindRejected = "rejected" // the remote has commits this branch lacks KindDiverged = "diverged" // a pull cannot fast-forward KindHook = "hook" // a hook said no KindTimeout = "timeout" // git took too long and was stopped KindGit = "git" // anything else git refused )
Kinds of ChangeError.
const ( OpRunning = "running" OpDone = "done" OpFailed = "failed" )
Op states.
const ( // MaxFileBytes is how much of a file is returned; past it, truncated. MaxFileBytes = 1 << 20 // MaxListedFiles caps the file list the palette filters. MaxListedFiles = 20000 )
const ( // DefaultDebounce is how long a burst of changes to one `.git` is // gathered before git is asked once (21-app.md: 300 ms). DefaultDebounce = 300 * time.Millisecond // DefaultGitTimeout is how long one git command may take before it is // killed and the timeout reported. DefaultGitTimeout = 5 * time.Second )
Defaults for the service's knobs.
const ( FrameProject bus.FrameType = "project" FrameOp bus.FrameType = "op" )
FrameProject and FrameOp are the live frames this package sends: {"type":"project","data":View} and {"type":"op","data":Op}.
const SystemPromptMax = 16 << 10
SystemPromptMax caps a project's instructions: a page or two of text, and well under any argv limit, since it is passed on the command line.
Variables ¶
var ( // ErrFileEscape is a path whose real location is outside the folder. ErrFileEscape = errors.New("that path leads outside the project") // ErrNotRegular is a folder, a device, a socket or a pipe. ErrNotRegular = errors.New("not a regular file") // ErrNoFile is a path that does not exist. ErrNoFile = errors.New("no such file") )
The refusals of a file read, apart from an unknown project or worktree.
var ErrNoWorktree = errors.New("no such worktree")
ErrNoWorktree is an unknown or missing worktree name.
Functions ¶
func CheckCloneURL ¶
CheckCloneURL accepts an https:// URL or git's user@host:path ssh form — nothing else, so a clone can never name a local path, a file:// URL or a transport that runs a command (ext::).
func CheckMessage ¶ added in v0.78.0
CheckMessage refuses an empty or unreasonable commit message, and returns it with trailing space trimmed.
Types ¶
type ChangeError ¶ added in v0.78.0
type ChangeError struct {
Kind string
Message string
Output string
// Preview is set on a stale discard: the fresh list and token.
Preview *DiscardPreview
}
ChangeError is a refusal or a failed git command, with git's own output.
func (*ChangeError) Error ¶ added in v0.78.0
func (e *ChangeError) Error() string
type ChangeFile ¶ added in v0.78.0
type ChangeFile struct {
Path string `json:"path"`
OrigPath string `json:"orig_path,omitempty"` // a rename or copy's source
// Status is added, modified, deleted, renamed, copied, typechange,
// untracked or conflicted.
Status string `json:"status"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
Binary bool `json:"binary,omitempty"`
}
ChangeFile is one file in one area of a worktree.
type Changes ¶ added in v0.78.0
type Changes struct {
ProjectID int64 `json:"project_id"`
Worktree string `json:"worktree"` // "" for the main checkout
Path string `json:"path"`
Branch string `json:"branch"` // "" when detached
Detached bool `json:"detached,omitempty"`
Head string `json:"head,omitempty"` // the commit; "" before the first
Upstream string `json:"upstream,omitempty"`
Ahead int `json:"ahead"`
Behind int `json:"behind"`
// Remote is where a push goes: the upstream's remote, else origin, else
// the only remote; "" when there is none.
Remote string `json:"remote,omitempty"`
RemoteURL string `json:"remote_url,omitempty"`
DefaultBranch string `json:"default_branch,omitempty"`
// Published is true when the upstream is the branch of the same name on
// Remote — what a pull request is opened from.
Published bool `json:"published"`
// State is merging, rebasing, cherry-picking or reverting while one is
// under way.
State string `json:"state,omitempty"`
Staged []ChangeFile `json:"staged"`
Unstaged []ChangeFile `json:"unstaged"`
Conflicted []ChangeFile `json:"conflicted"`
Truncated bool `json:"truncated,omitempty"`
// Token changes whenever the status does.
Token string `json:"token"`
At int64 `json:"at"`
}
Changes is a worktree's uncommitted work and where its branch stands.
type CommitResult ¶ added in v0.78.0
type CommitResult struct {
SHA string `json:"sha"`
Short string `json:"short"`
Subject string `json:"subject"`
Output string `json:"output,omitempty"` // hooks and git's own lines
}
CommitResult is a commit just made.
type DiscardPreview ¶ added in v0.78.0
type DiscardPreview struct {
Confirm string `json:"confirm"`
Files []ChangeFile `json:"files"`
}
DiscardPreview is what a discard would remove, and the token that confirms it.
type FileContent ¶ added in v0.92.0
type FileContent struct {
Path string `json:"path"`
// Size is the whole file's, even when only the first MaxFileBytes come.
Size int64 `json:"size"`
Text string `json:"text"`
Truncated bool `json:"truncated,omitempty"`
// Binary: NUL bytes or invalid UTF-8; Text is then empty.
Binary bool `json:"binary,omitempty"`
Lang string `json:"lang"`
}
FileContent is one file, as the file tab shows it.
type FilePatch ¶ added in v0.78.0
type FilePatch struct {
Path string `json:"path"`
OrigPath string `json:"orig_path,omitempty"`
Staged bool `json:"staged"`
Status string `json:"status"`
Patch string `json:"patch"`
Binary bool `json:"binary,omitempty"`
Truncated bool `json:"truncated,omitempty"`
// TooLarge is a new file not diffed at all.
TooLarge bool `json:"too_large,omitempty"`
Bytes int `json:"bytes"` // the whole patch, before any cut
// Token names this exact patch; staging one hunk of it must quote it.
Token string `json:"token"`
}
FilePatch is one file's diff in one area.
type GitStatus ¶
type GitStatus struct {
Branch string `json:"branch"` // "" when detached
Detached bool `json:"detached,omitempty"` // HEAD is not on a branch
Dirty bool `json:"dirty"`
Changed int `json:"changed"` // files modified, staged, conflicted or untracked
Ahead int `json:"ahead"`
Behind int `json:"behind"`
Upstream string `json:"upstream,omitempty"`
DefaultBranch string `json:"default_branch,omitempty"`
RemoteURL string `json:"remote_url,omitempty"`
// Error is why the last refresh failed (git missing, a timeout, a broken
// repository), with git's own words; the other fields are then the last
// good answer, or zero.
Error string `json:"error,omitempty"`
// At is when git last answered, unix ms; 0 while the first answer is
// still on its way.
At int64 `json:"at"`
}
GitStatus is what git says about a project's working tree, as the sidebar shows it.
type Hunk ¶ added in v0.78.0
type Hunk struct {
Path string `json:"path"`
Index int `json:"index"` // 0-based, in patch order
Token string `json:"token"` // FilePatch.Token
}
Hunk names one hunk of a file's patch as the caller saw it.
type Op ¶
type Op struct {
ID string `json:"op_id"`
Kind string `json:"kind"` // clone
State string `json:"state"` // running | done | failed
Phase string `json:"phase,omitempty"` // git's words: "Receiving objects", "Resolving deltas", …
Progress int `json:"progress"` // 0–100 within the phase
URL string `json:"url,omitempty"`
Dest string `json:"dest,omitempty"`
ProjectID int64 `json:"project_id,omitempty"` // set when done
Error string `json:"error,omitempty"`
StartedAt int64 `json:"started_at"`
UpdatedAt int64 `json:"updated_at"`
}
Op is a long operation — a clone — that outlives the request and the connection that asked for it. A client names it with an op_id of its own; asking again with the same id returns the same operation, so a phone that dropped mid-clone and retries does not start a second one. Its progress goes out as op frames on /v1/live, and GET /v1/projects/ops answers what a reconnecting client missed.
type Patch ¶
type Patch struct {
Name *string `json:"name,omitempty"`
Pinned *bool `json:"pinned,omitempty"`
Sort *int64 `json:"sort,omitempty"`
Defaults *json.RawMessage `json:"defaults,omitempty"`
}
Patch is what may be changed on a project.
type RemoteResult ¶ added in v0.78.0
type RemoteResult struct {
Remote string `json:"remote,omitempty"`
Branch string `json:"branch,omitempty"`
UpstreamSet bool `json:"upstream_set,omitempty"` // the push named a new upstream
Output string `json:"output,omitempty"`
}
RemoteResult is a push, pull or fetch that worked.
type Service ¶
type Service struct {
Store *store.Store
Bus *bus.Bus
Log *slog.Logger
Now func() time.Time
// Eligible decides whether a repository a session ran in is listed
// without anyone adding it; store.ProjectWorthListing unless a test
// replaces it.
Eligible func(root string) bool
// Env is the environment a clone runs with (the login shell's, so ssh
// keys and credential helpers are found); os.Environ when nil.
Env func() []string
Debounce time.Duration
GitTimeout time.Duration
// contains filtered or unexported fields
}
Service is the projects list and its git watcher.
func (*Service) Add ¶
Add lists an existing folder. A folder inside a repository lists the repository, so its git state and its sessions are one row. Adding a folder already listed returns it; one that was unlisted is listed again.
func (*Service) AddRemote ¶ added in v0.78.0
AddRemote adds a remote to a project's repository (its main checkout), refusing a name that exists. The URL is an https:// address or git@host:path — the forms a clone accepts.
func (*Service) AddWorktree ¶
func (s *Service) AddWorktree(ctx context.Context, id int64, spec agents.WorktreeSpec) (agents.Worktree, error)
AddWorktree creates a worktree on any branch and returns it.
func (*Service) Changes ¶ added in v0.78.0
Changes reads a worktree's status: what is staged, what is not, what is in conflict, and where its branch stands against its upstream.
func (*Service) Clone ¶
Clone starts cloning url into parent/<name> (name defaults to the repository's) and returns the operation at once. With an opID already known it returns that operation and starts nothing (existing is true).
func (*Service) Close ¶
func (s *Service) Close()
Close stops watching and asking git, and returns once no refresh is running. Safe to call more than once.
func (*Service) Commit ¶ added in v0.78.0
func (s *Service) Commit(ctx context.Context, id int64, worktree, message string, all bool) (CommitResult, Changes, error)
Commit commits what is staged (everything first, when all) with message, as the author git is configured with. Hooks run; a hook that refuses is a KindHook error carrying its output, and what was staged stays staged.
func (*Service) Create ¶
Create makes a new folder name under parent, runs `git init` in it when gitInit, and lists it. parent must exist; one level is made, never a chain.
func (*Service) Diff ¶ added in v0.78.0
func (s *Service) Diff(ctx context.Context, id int64, worktree, path string, staged bool) (FilePatch, error)
Diff is one file's patch: staged (index against HEAD) or not (worktree against index; a new file against nothing). path must be in the status.
func (*Service) Discard ¶ added in v0.78.0
func (s *Service) Discard(ctx context.Context, id int64, worktree string, paths []string, confirm string) (*DiscardPreview, Changes, error)
Discard throws away the unstaged changes to paths (tracked files go back to their staged or committed content; untracked files are deleted). It takes two calls: without confirm it changes nothing and returns what it would discard and a token; with that token, and nothing changed since, it discards. Staged changes are never touched.
func (*Service) Fetch ¶ added in v0.78.0
func (s *Service) Fetch(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
Fetch updates what the worktree knows of its remote, so ahead and behind are current.
func (*Service) ListFiles ¶ added in v0.92.0
ListFiles is the worktree's files: git's tracked and untracked-but-not- ignored files in a repository, a walk that skips dot-folders and node_modules in a plain folder. At most MaxListedFiles.
func (*Service) ListedAt ¶ added in v0.95.0
ListedAt is the listed project that adding dir would return: the one whose root is dir, or the repository dir lies in. The folder field asks it so the Add project sheet can say "already in Caprock" before Add is pressed.
func (*Service) ProjectFor ¶
ProjectFor is the listed project dir lies in (the longest root that holds it), or false.
func (*Service) Pull ¶ added in v0.78.0
func (s *Service) Pull(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
Pull fast-forwards the branch to its upstream, or says why it cannot.
func (*Service) Push ¶ added in v0.78.0
func (s *Service) Push(ctx context.Context, id int64, worktree string) (RemoteResult, Changes, error)
Push sends the checked-out branch to the same-named branch on its remote, setting that as the upstream when it is not already (the first push of a new branch, or a worktree made to track the trunk). Never forced.
func (*Service) ReadFile ¶ added in v0.92.0
func (s *Service) ReadFile(ctx context.Context, id int64, worktree, rel string) (FileContent, error)
ReadFile reads rel, a clean relative path, inside a project's folder.
func (*Service) RemoveWorktree ¶
RemoveWorktree removes a clean worktree Caprock made. Anything else is refused with the reason.
func (*Service) Stage ¶ added in v0.78.0
func (s *Service) Stage(ctx context.Context, id int64, worktree string, paths []string, all bool, hunk *Hunk) (Changes, error)
Stage adds files (paths, every change when all) or one hunk to the index.
func (*Service) Start ¶
Start seeds the list on first run, starts watching every listed repository, asks git once about each, and follows the bus for sessions in folders not yet listed. It returns once the list is loaded; git answers arrive as project frames.
func (*Service) Subjects ¶ added in v0.78.0
Subjects are the subjects of the commits on a worktree's branch that its base lacks, newest first: against the remote's copy of base when there is one, else the local base. None when base is unknown or is the branch.
func (*Service) SystemPrompt ¶ added in v0.81.0
SystemPrompt is the instructions set for the project dir is in — its defaults.system_prompt — or "" when there are none or dir is in no project.
func (*Service) Unlist ¶
Unlist takes a project off the list. Nothing on disk is touched, and the sessions that ran there keep their cost and history.
func (*Service) Unstage ¶ added in v0.78.0
func (s *Service) Unstage(ctx context.Context, id int64, worktree string, paths []string, all bool, hunk *Hunk) (Changes, error)
Unstage takes files (paths, every staged change when all) or one hunk out of the index; the working tree is not touched.
func (*Service) WorktreePath ¶ added in v0.78.0
WorktreePath is the folder of a project's main checkout (name "") or of its linked worktree name.
type Sessions ¶
type Sessions struct {
Live int64 `json:"live"`
Waiting int64 `json:"waiting"`
Total int64 `json:"total"`
}
Sessions counts a project's sessions.
type View ¶
type View struct {
ID int64 `json:"id"`
Name string `json:"name"`
Root string `json:"root"` // the OS's own form of the path
Kind string `json:"kind"` // repo | folder
Source string `json:"source"`
Pinned bool `json:"pinned"`
Sort int64 `json:"sort"`
AddedAt int64 `json:"added_at"`
Archived bool `json:"archived,omitempty"`
Exists bool `json:"exists"` // the folder is on disk
Defaults json.RawMessage `json:"defaults"`
// Git is null for a folder that is not a repository.
Git *GitStatus `json:"git"`
Sessions Sessions `json:"sessions"`
CostToday float64 `json:"cost_today"`
LastActivity int64 `json:"last_activity"`
Worktrees []WorktreeView `json:"worktrees"`
// Removed is set on the frame sent when a project is taken off the list.
Removed bool `json:"removed,omitempty"`
}
View is a project as the API returns it.
type WorktreeView ¶
type WorktreeView struct {
Name string `json:"name"` // git's name for it (.git/worktrees/<name>)
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
Head string `json:"head,omitempty"` // the commit, when detached
Caprock bool `json:"caprock"` // made by Caprock, so removable from here
Locked bool `json:"locked,omitempty"`
Missing bool `json:"missing,omitempty"` // its folder is gone (git calls it prunable)
Dirty bool `json:"dirty"`
Changed int `json:"changed"`
Error string `json:"error,omitempty"`
}
WorktreeView is one linked worktree of a project.