projects

package
v0.152.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 34 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 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

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

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

View Source
const (
	CleanupOff  = "off"
	CleanupAsk  = "ask"
	CleanupAuto = "auto"
)

The cleanup modes (config.json "worktree_cleanup").

View Source
const (
	OpRunning = "running"
	OpDone    = "done"
	OpFailed  = "failed"
)

Op states.

View Source
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
)
View Source
const (
	// ScanDepth is how far below a folder Add project looks for
	// repositories: ~/work/api (1) and ~/work/services/web (2).
	ScanDepth = 2

	// MaxRepos caps a multi-repo project's members.
	MaxRepos = 100
)
View Source
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.

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

View Source
const (
	// ActivityDays is the window the Repos section counts.
	ActivityDays = 14
)
View Source
const CleanupStateFile = cleanupStateFile

CleanupStateFile is the state's file name in the data directory.

View Source
const MaxImageBytes = 10 << 20

MaxImageBytes caps an image a Markdown file shows; past it, refused.

View Source
const MaxInstructionBytes = 64 << 10

MaxInstructionBytes is how much of one instruction file a scan returns.

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

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

View Source
var (
	// ErrNotImage is a path whose extension is not a picture's.
	ErrNotImage = errors.New("not an image")
	// ErrTooLarge is an image past MaxImageBytes.
	ErrTooLarge = errors.New("the image is too large to show")
)

The refusals of an image read, apart from those of a file read.

CleanupModes lists the modes in the order Settings shows them.

View Source
var ErrCopyNeedsConfirm = errors.New("removing it would lose work")

ErrCopyNeedsConfirm is a removal that would lose work, asked without Force.

View Source
var ErrNoWorktree = errors.New("no such worktree")

ErrNoWorktree is an unknown or missing worktree name.

View Source
var InstructionFileNames = []string{"CLAUDE.md", ".claude/CLAUDE.md", "AGENTS.md"}

InstructionFileNames are looked for at a folder's top, in this order.

Functions

func CheckCloneURL

func CheckCloneURL(raw string) error

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 CheckFolderName added in v0.119.0

func CheckFolderName(name string) error

CheckFolderName refuses anything that is not one ordinary folder name.

func CheckMessage added in v0.78.0

func CheckMessage(msg string) (string, error)

CheckMessage refuses an empty or unreasonable commit message, and returns it with trailing space trimmed.

func EmptyDir added in v0.95.0

func EmptyDir(dir string) bool

EmptyDir reports whether dir is a folder with nothing in it, hidden files included: git refuses to clone into a folder holding even a .DS_Store.

func ExpandHome added in v0.119.0

func ExpandHome(path string) string

ExpandHome turns a leading ~ into the user's home folder.

func FindRepos added in v0.111.0

func FindRepos(dir string, depth int) ([]string, bool)

FindRepos lists the git repositories at most depth levels below dir, in path order. A repository is not descended into; hidden folders, dependency trees and, below a folder macOS does not guard, guarded ones are skipped. capped says the walk stopped at its limits.

func ImageType added in v0.122.0

func ImageType(rel string) string

ImageType is the media type of a picture by its extension; "" when the path is not one.

func LangOf added in v0.92.0

func LangOf(path string) string

LangOf names a file's language by its extension; "text" when unknown.

func NewOpID added in v0.119.0

func NewOpID() string

NewOpID is an operation id for a client that sent none.

func NormalizeCleanup added in v0.112.1

func NormalizeCleanup(m string) string

NormalizeCleanup is the effective mode: ask when unset or unknown.

func ParseGitProgress added in v0.119.0

func ParseGitProgress(line string) (string, int, bool)

ParseGitProgress reads one of git's progress lines ("Receiving objects: 45% ...") as its phase and percentage.

func ParseShortstat added in v0.115.0

func ParseShortstat(out []byte, start time.Time, days int) (commits, added, deleted []int, last int64)

ParseShortstat reads `git log --format=%x1e%ct --shortstat` into per-day commits, lines added and lines deleted over the days days from start, and the newest commit's time (unix ms). A commit outside the window is left out; a commit with no shortstat line (an empty one) still counts. CRLF is read like LF (parseRecords).

func RepoName added in v0.115.0

func RepoName(root string) string

RepoName is the last segment of a repository root, with either separator: a root from Windows may arrive as C:\dev\app or C:/dev/app.

func SetupCommandOf added in v0.102.0

func SetupCommandOf(defaults string) string

SetupCommandOf is defaults' setup_command, "" when absent or unreadable.

func SplitCRLF added in v0.119.0

func SplitCRLF(data []byte, atEOF bool) (int, []byte, error)

SplitCRLF is a bufio.SplitFunc on CR or LF, for git's redrawn progress.

func ValidCleanupMode added in v0.112.1

func ValidCleanupMode(m string) bool

ValidCleanupMode reports whether m is one of CleanupModes.

func ValidOpID added in v0.119.0

func ValidOpID(id string) bool

ValidOpID reports whether id is what a client may name an operation.

Types

type BusyFunc added in v0.102.0

type BusyFunc func(dir string, except []string) []string

BusyFunc says what is running in a folder or below it — sessions and shells — by names a person recognises, leaving out what runs inside any of except (the copies nested in it: Caprock's live under the main checkout). The API supplies it.

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 CleanupCandidate added in v0.112.1

type CleanupCandidate struct {
	Path       string `json:"path"`
	Branch     string `json:"branch"`
	Size       *int64 `json:"size"` // null while measured
	SizeCapped bool   `json:"size_capped,omitempty"`
	// Since is when it became a candidate, Unix ms; Due, in Auto mode, when
	// it is removed.
	Since int64 `json:"since"`
	Due   int64 `json:"due,omitempty"`
	// PR is the merged pull request that made it one, when git alone did
	// not (a squash merge).
	PR int `json:"pr,omitempty"`
}

CleanupCandidate is one finished copy.

type CleanupRecord added in v0.112.1

type CleanupRecord struct {
	ID        string `json:"id"`
	ProjectID int64  `json:"project_id"`
	Path      string `json:"path"`
	Branch    string `json:"branch,omitempty"`
	Head      string `json:"head,omitempty"`
	Bytes     int64  `json:"bytes"`
	At        int64  `json:"at"`  // Unix ms
	How       string `json:"how"` // auto | ask | manual
	// BranchDeleted: the branch went with it (asked for, manual) or after
	// the 7 days.
	BranchDeleted bool  `json:"branch_deleted,omitempty"`
	RestoredAt    int64 `json:"restored_at,omitempty"`
	// Settled: the 7 days are over and the branch was dealt with.
	Settled bool `json:"settled,omitempty"`
	// Restorable is worked out on read: within 7 days, not restored, the
	// folder free.
	Restorable bool `json:"restorable"`
}

CleanupRecord is one removed copy in the history.

type CleanupRestored added in v0.112.1

type CleanupRestored struct {
	ID       string `json:"id"`
	Path     string `json:"path,omitempty"`
	Restored bool   `json:"restored"`
	Error    string `json:"error,omitempty"`
}

CleanupRestored is what Restore did with one record.

type CleanupView added in v0.112.1

type CleanupView struct {
	Mode       string             `json:"mode"`
	Candidates []CleanupCandidate `json:"candidates"`
	Total      int64              `json:"total"`
	Pending    bool               `json:"pending,omitempty"`
	// Removed are the copies cleaned up (Ask or Auto, not the copies
	// sheet) in the last day and not restored: the "Removed 3 copies ·
	// Undo" line.
	Removed []CleanupRecord `json:"removed"`
	// History is this project's removals, newest first.
	History   []CleanupRecord `json:"history"`
	CheckedAt int64           `json:"checked_at"`
}

CleanupView is GET /v1/projects/{id}/cleanup.

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 CopiesView added in v0.102.0

type CopiesView struct {
	Copies        []Copy `json:"copies"`
	DefaultBranch string `json:"default_branch,omitempty"`
	HasRemote     bool   `json:"has_remote"`
	// Total is the sum of the linked copies' known sizes; Pending says some
	// are still being measured, Capped that some are floors.
	Total   int64 `json:"total"`
	Pending bool  `json:"pending,omitempty"`
	Capped  bool  `json:"capped,omitempty"`
}

CopiesView is a project's copies and their total size.

type Copy added in v0.102.0

type Copy struct {
	// Name is git's name for a linked worktree (<common>/worktrees/<name>);
	// empty for the main checkout.
	Name     string `json:"name,omitempty"`
	Path     string `json:"path"` // the OS's own form
	Main     bool   `json:"main,omitempty"`
	Branch   string `json:"branch,omitempty"`
	Head     string `json:"head,omitempty"` // the commit
	Detached bool   `json:"detached,omitempty"`
	Caprock  bool   `json:"caprock"`
	Locked   bool   `json:"locked,omitempty"`
	// Missing is a worktree whose folder is gone (git calls it prunable).
	Missing bool `json:"missing,omitempty"`
	// CommittedAt is the newest commit's time, Unix seconds; 0 unknown.
	CommittedAt int64 `json:"committed_at,omitempty"`
	// Merged: every commit on it is in the default branch (local or
	// origin's), so deleting the branch loses nothing. Never set for the
	// default branch itself or the main checkout.
	Merged bool `json:"merged"`
	// Unpushed counts commits on it that no remote has; only meaningful
	// when the repository has a remote (HasRemote on the view).
	Unpushed int `json:"unpushed"`
	// Orphaned counts commits on a detached HEAD that no branch or remote
	// holds: removing the copy leaves them reachable only from the reflog.
	Orphaned int  `json:"orphaned,omitempty"`
	Dirty    bool `json:"dirty"`
	Changed  int  `json:"changed"`
	// Live names what runs in it: a session or a shell. A copy with any is
	// not removed.
	Live []string `json:"live"`
	// Size is the folder's size in bytes, null while it is being measured
	// (and always for the main checkout, which is not measured).
	Size *int64 `json:"size"`
	// SizeCapped: the walk stopped at its file or time limit, so Size is a
	// floor.
	SizeCapped bool `json:"size_capped,omitempty"`
	// Stale: a copy Caprock made with no commit for 14 days and no pull
	// request known for its branch. Suggested, never removed for it
	// (cleanup.go).
	Stale bool   `json:"stale,omitempty"`
	Error string `json:"error,omitempty"`
}

Copy is one worktree of a project as the copies view shows it.

type CopyRemoval added in v0.102.0

type CopyRemoval struct {
	Path  string `json:"path"`
	Force bool   `json:"force,omitempty"`
}

CopyRemoval asks to remove one copy. Force says the person has seen what would be lost — uncommitted changes, unpushed or orphaned commits — and confirmed it.

type CopyRemoved added in v0.102.0

type CopyRemoved struct {
	Path    string `json:"path"`
	Removed bool   `json:"removed"`
	// BranchDeleted is the local branch deleted with it, when asked and
	// merged.
	BranchDeleted string `json:"branch_deleted,omitempty"`
	// Confirm is set when the copy was kept because it would lose work and
	// the request did not say force; Error says what.
	Confirm bool   `json:"confirm,omitempty"`
	Error   string `json:"error,omitempty"`
}

CopyRemoved is what happened to one copy.

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 FileList added in v0.92.0

type FileList struct {
	Files     []string `json:"files"`
	Truncated bool     `json:"truncated,omitempty"`
}

FileList is the files of a worktree, relative and in slash form.

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 FoundRepo added in v0.111.0

type FoundRepo struct {
	Path string `json:"path"` // the OS's own form
	// Name is its path below the scanned folder, forward slashes: "api",
	// "services/web".
	Name string `json:"name"`
	// ProjectID is set when the repository is listed as a project of its
	// own; MemberOf when it is a member of a multi-repo project.
	ProjectID   int64  `json:"project_id,omitempty"`
	ProjectName string `json:"project_name,omitempty"`
	MemberOf    int64  `json:"member_of,omitempty"`
	// InstructionFiles are the repository's own instruction files at its
	// top (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md), names only.
	InstructionFiles []string `json:"instruction_files,omitempty"`
}

FoundRepo is one repository a scan found below a folder.

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 InstructionFile added in v0.117.0

type InstructionFile struct {
	Name      string `json:"name"` // slash form, below the scanned folder
	Text      string `json:"text"`
	Truncated bool   `json:"truncated,omitempty"`
}

InstructionFile is one instruction file a scan found, with its text.

type Op

type Op struct {
	ID        string `json:"op_id"`
	Kind      string `json:"kind"`            // clone | template
	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"`

	// A project started from a template (kind "template", internal/templates)
	// also says which step it is on, the GitHub repository it made, what
	// the person should know (notes), whether a failed one may be tried
	// again, and whether the folder it made was taken away again.
	Step      string   `json:"step,omitempty"` // create | clone | copy | brief | commit | add
	Repo      string   `json:"repo,omitempty"` // owner/name on GitHub
	RepoURL   string   `json:"repo_url,omitempty"`
	Notes     []string `json:"notes,omitempty"`
	Retryable bool     `json:"retryable,omitempty"`
	Removed   bool     `json:"removed,omitempty"`
}

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"`
	// Repos replaces a project's member repositories (ADR-055); [] makes a
	// multi-repo project an ordinary one.
	Repos *[]string `json:"repos,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 RepoActivity added in v0.115.0

type RepoActivity struct {
	Root string `json:"root"`
	Name string `json:"name"`
	// Branch is the branch checked out at the root, "" when detached or
	// not read.
	Branch string `json:"branch,omitempty"`
	// Days are the local calendar days covered, oldest first, "2006-01-02".
	Days []string `json:"days"`
	// Commits, Added and Deleted are per day, on every branch, merges left
	// out: `git log --all --no-merges`, the lines from each commit's
	// `--shortstat`.
	Commits []int `json:"commits"`
	Added   []int `json:"added"`
	Deleted []int `json:"deleted"`
	// LinesPartial says some commits' lines are not counted yet: diffing
	// them ran past activityLineBudget, and the next read goes on from
	// where this one stopped.
	LinesPartial bool `json:"lines_partial,omitempty"`
	// LastCommitAt is the newest commit's time (unix ms), 0 when none in
	// the window.
	LastCommitAt int64 `json:"last_commit_at,omitempty"`
	// Dirty is how many files `git status` lists as changed or new.
	Dirty int `json:"dirty"`
	// CheckedMs is when git was read; the answer is kept activityKept.
	CheckedMs int64  `json:"checked_ms"`
	Error     string `json:"error,omitempty"`
}

RepoActivity is what a repository's own git says about its last ActivityDays days: the Now screen's Repos section (.ai/04-ui.md § Repos). Read from the local checkout only — nothing is sent anywhere (rule 4).

type RepoView added in v0.111.0

type RepoView struct {
	Path         string     `json:"path"` // the OS's own form
	Name         string     `json:"name"` // below the project's root, else its last segment
	Exists       bool       `json:"exists"`
	Git          *GitStatus `json:"git"` // null until git first answers
	Sessions     Sessions   `json:"sessions"`
	CostToday    float64    `json:"cost_today"`
	LastActivity int64      `json:"last_activity"`
	// OpenPRs is the repository's open pull requests on GitHub, when the
	// project page asked for them (GET /v1/projects/{id}/repos) and GitHub
	// is connected; PRsError says why there is no count.
	OpenPRs  *int   `json:"open_prs,omitempty"`
	PRsError string `json:"prs_error,omitempty"`
}

RepoView is one member of a multi-repo project, with its own git state and the share of the project's sessions and spend that ran in it.

type ScanResult added in v0.111.0

type ScanResult struct {
	Root string `json:"root"`
	// RepoRoot is set when the folder is inside a repository: adding it
	// adds that repository, and there is nothing to choose.
	RepoRoot string      `json:"repo_root,omitempty"`
	Repos    []FoundRepo `json:"repos"`
	Capped   bool        `json:"capped,omitempty"`
	// InstructionFiles are the instruction files at the top of the
	// repository the folder is in (RepoRoot), else of the folder itself,
	// with their text: the app shows them before the project is added.
	InstructionFiles []InstructionFile `json:"instruction_files,omitempty"`
}

ScanResult is GET /v1/projects/scan.

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

	// Finished copies cleaning themselves up (cleanup.go). CleanupFile is
	// where the state is kept ("" keeps it in memory); CleanupMode is
	// off | ask | auto (ask when nil); Busy says what runs in a folder;
	// PRState is the cached pull request of a branch of the repository at
	// remoteURL — its state, number and head commit — without asking GitHub.
	CleanupFile string
	CleanupMode func() string
	Busy        func(ctx context.Context) BusyFunc
	PRState     func(remoteURL, branch string) (state string, number int, head string)
	// contains filtered or unexported fields
}

Service is the projects list and its git watcher.

func New

func New(st *store.Store, b *bus.Bus, log *slog.Logger) *Service

New builds a service; Start brings it up.

func (*Service) Activity added in v0.115.0

func (s *Service) Activity(ctx context.Context, root string) RepoActivity

Activity is root's figures, read from git at most once per activityKept (activityPartialKept while lines are still being counted). A git that fails or times out listing the commits is an answer with Error set, kept like the others, so a broken repository is not asked every minute.

func (*Service) Add

func (s *Service) Add(ctx context.Context, path string) (View, bool, error)

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) AddMulti added in v0.111.0

func (s *Service) AddMulti(ctx context.Context, root string, repos []string) (View, bool, error)

AddMulti lists root as one project of the repositories repos (at least two). A repository listed as a project of its own is taken off the list (its sessions now count here), and one that was a member of another project moves. Nothing on disk is touched.

func (*Service) AddRemote added in v0.78.0

func (s *Service) AddRemote(ctx context.Context, id int64, name, url string) (Changes, error)

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) AddRepos added in v0.133.0

func (s *Service) AddRepos(ctx context.Context, repos []string, name string) (View, bool, error)

AddRepos lists one project of the repositories repos (at least two), chosen one by one, with no folder of its own (ADR-077): its root is the first of them, the home repository agents start in, and every one of them is a member. The home repository's own project, if listed, becomes this project (its settings and history kept); the others are folded in. name, when set, names it. Nothing on disk is touched.

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

func (s *Service) Changes(ctx context.Context, id int64, worktree string) (Changes, error)

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) CheckCleanup added in v0.112.1

func (s *Service) CheckCleanup(ctx context.Context, id int64) error

CheckCleanup works out a project's finished copies now, and in Auto mode removes those whose 24 hours are up.

func (*Service) CleanUp added in v0.112.1

func (s *Service) CleanUp(ctx context.Context, id int64, paths []string) ([]CopyRemoved, error)

CleanUp removes exactly the listed copies of the ones last found finished, after judging them again now ("Clean up" in Ask mode, and "Clean up now" in Auto mode). A path that is no longer finished is kept, with the reason.

func (*Service) Cleanup added in v0.112.1

func (s *Service) Cleanup(ctx context.Context, id int64) (CleanupView, error)

Cleanup is a project's finished copies and its removal history. The first ask after a start checks the project; later ones answer from the last check, with sizes from the size cache.

func (*Service) CleanupBranchesMerged added in v0.112.1

func (s *Service) CleanupBranchesMerged(branches []string)

CleanupBranchesMerged is told the branches whose pull requests were just seen merged; each project with a copy of Caprock's on one is checked.

func (*Service) CleanupModeChanged added in v0.112.1

func (s *Service) CleanupModeChanged()

CleanupModeChanged checks every project with copies again.

func (*Service) CleanupSoon added in v0.112.1

func (s *Service) CleanupSoon(id int64)

CleanupSoon checks a project shortly: a session in one of its copies ended.

func (*Service) Clone

func (s *Service) Clone(opID, rawURL, parent, name string) (Op, bool, error)

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) Copies added in v0.102.0

func (s *Service) Copies(ctx context.Context, id int64, busy BusyFunc) (CopiesView, error)

Copies lists every worktree of a project, the main checkout first, with each linked copy's size from the cache; a size not yet known is measured in the background and is null until then.

func (*Service) Create

func (s *Service) Create(ctx context.Context, parent, name string, gitInit bool) (View, error)

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) FinishOp added in v0.119.0

func (s *Service) FinishOp(id string, projectID int64, err error)

FinishOp ends an operation: done with projectID, or failed with err.

func (*Service) Get

func (s *Service) Get(ctx context.Context, id int64) (View, error)

Get returns one project, archived or not.

func (*Service) GetOp

func (s *Service) GetOp(id string) (Op, bool)

GetOp returns one operation.

func (*Service) GitRuns

func (s *Service) GitRuns() int64

GitRuns is how many git status processes this service has started.

func (*Service) List

func (s *Service) List(ctx context.Context) ([]View, error)

List returns every listed project with its git state and activity.

func (*Service) ListCreated added in v0.119.0

func (s *Service) ListCreated(ctx context.Context, root, source string) (View, error)

ListCreated lists a repository Caprock just made at root; source is store.ProjectSourceClone or store.ProjectSourceNew.

func (*Service) ListDirFiles added in v0.104.0

func (s *Service) ListDirFiles(ctx context.Context, dir string) (FileList, error)

ListDirFiles is ListFiles for a folder named directly: a session's working directory, for the chat field's @ picker (ADR-053). Paths are relative to dir; in a repository, only the files under dir.

func (*Service) ListFiles added in v0.92.0

func (s *Service) ListFiles(ctx context.Context, id int64, worktree string) (FileList, error)

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

func (s *Service) ListedAt(dir string) (store.Project, bool)

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) Merge added in v0.111.0

func (s *Service) Merge(ctx context.Context, ids []int64) (View, error)

Merge makes one multi-repo project of several projects: their repositories (a repository project's root, a multi-repo project's members) become the members of one of them — the multi-repo project among them, or else the first repository project, whose repository becomes the home one (ADR-077; until then a new project at the folder holding them all, which for two repositories in ~/dev was ~/dev). The others are taken off the list.

func (*Service) Ops

func (s *Service) Ops() []Op

Ops lists the operations still remembered, newest first.

func (*Service) OtherRepos added in v0.111.0

func (s *Service) OtherRepos(dir string) []string

OtherRepos is what an agent started in dir is given beside its working directory: every member repository of the multi-repo project dir is in, except the one dir is inside and those inside dir (already in reach). Claude Code gets them as --add-dir (ADR-055). Empty outside a multi-repo project.

func (*Service) Project

func (s *Service) Project(id int64) (store.Project, bool)

Project returns a listed project's row.

func (*Service) ProjectFor

func (s *Service) ProjectFor(dir string) (store.Project, bool)

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) ReadImage added in v0.122.0

func (s *Service) ReadImage(ctx context.Context, id int64, worktree, rel string) ([]byte, string, error)

ReadImage reads a picture inside a project's folder, whole, for an image in a Markdown file: the same path rules as ReadFile, an image extension, and at most MaxImageBytes.

func (*Service) RemoveCopies added in v0.102.0

func (s *Service) RemoveCopies(ctx context.Context, id int64, asks []CopyRemoval, deleteMerged bool, busy BusyFunc) ([]CopyRemoved, error)

RemoveCopies removes the copies asked for, one at a time, each judged on its state now rather than when the list was shown. Only a copy Caprock made is removed; never the main checkout, a locked copy or one with a session or shell running in it. A copy with changes, unpushed or orphaned commits needs Force. With deleteMerged the copy's local branch goes too, but only when every commit on it is in the default branch.

func (*Service) RemoveWorktree

func (s *Service) RemoveWorktree(ctx context.Context, id int64, name string) error

RemoveWorktree removes a clean worktree Caprock made. Anything else is refused with the reason.

func (*Service) RepoViews added in v0.111.0

func (s *Service) RepoViews(ctx context.Context, id int64, fresh bool) ([]RepoView, error)

RepoViews is a project's members with their git state and activity, for the project page. fresh asks git again about any member whose answer is older than memberGitTTL; the frame that follows carries it.

func (*Service) Repos added in v0.111.0

func (s *Service) Repos(id int64) []string

Repos is a listed project's member repositories (normalised), nil for an ordinary project.

func (*Service) Restore added in v0.112.1

func (s *Service) Restore(ctx context.Context, id int64, ids []string) ([]CleanupRestored, error)

Restore puts removed copies back from their kept branches (Undo, and Restore in the copies sheet): `git worktree add <path> <branch>`, or, if the branch is gone, `git worktree add -b <branch> <path> <commit>`. A restored copy is not a candidate again until its HEAD moves.

func (*Service) Scan added in v0.111.0

func (s *Service) Scan(ctx context.Context, path string) (ScanResult, error)

Scan says what adding dir would add: the repository it is in, or the repositories below it (ScanDepth), each marked when it is already listed.

func (*Service) SetRepos added in v0.111.0

func (s *Service) SetRepos(ctx context.Context, id int64, repos []string) (View, error)

SetRepos replaces a project's member repositories (the editor's add and remove, Rescan's additions, and the project menu's Add a repository). An empty list makes it an ordinary project again; a removed member is neither listed nor deleted. A repository project keeps its own root among its members while it has another (ADR-077); a folder project's own folder is never one.

func (*Service) SetupCommand added in v0.102.0

func (s *Service) SetupCommand(dir string) string

SetupCommand is the command set to run in a fresh worktree of the project dir is in before its agent starts — its defaults.setup_command — or "".

func (*Service) Split added in v0.111.0

func (s *Service) Split(ctx context.Context, id int64) ([]View, error)

Split lists each member of a multi-repo project as a project of its own (one that was listed before comes back with its old name and settings) and takes the multi-repo project off the list — unless its root is one of the members (ADR-077): then the project stays, as that repository alone, with its name. Nothing on disk is touched.

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

func (s *Service) Start(ctx context.Context) error

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) StartOp added in v0.119.0

func (s *Service) StartOp(op Op) (Op, bool)

StartOp registers op (its ID set; it starts running) and sends its first frame. An id already known is returned as it is, with existing true, and nothing is registered: Clone's rule.

func (*Service) Subjects added in v0.78.0

func (s *Service) Subjects(ctx context.Context, id int64, worktree, base string) ([]string, error)

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

func (s *Service) SystemPrompt(dir string) string

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) TeamSignal added in v0.96.0

func (s *Service) TeamSignal(ctx context.Context, days int) (TeamSignal, error)

TeamSignal counts distinct commit authors across the listed repositories over the last `days` days, at most once per teamSignalTTL. A repository whose git fails or times out is skipped: an undercount only hides a card.

func (*Service) Unlist

func (s *Service) Unlist(ctx context.Context, id int64) error

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

func (s *Service) Update(ctx context.Context, id int64, patch Patch) (View, error)

Update applies a patch and returns the project after it.

func (*Service) UpdateOp added in v0.119.0

func (s *Service) UpdateOp(id string, fn func(*Op)) (Op, bool)

UpdateOp changes a remembered operation with fn and sends the frame; false for an id no longer known.

func (*Service) WorktreePath added in v0.78.0

func (s *Service) WorktreePath(ctx context.Context, id int64, name string) (string, error)

WorktreePath is the folder of a project's main checkout (name "") or of its linked worktree name.

func (*Service) Worktrees

func (s *Service) Worktrees(ctx context.Context, id int64) ([]WorktreeView, error)

Worktrees lists a project's linked worktrees, from the git cache.

type Sessions

type Sessions struct {
	Live    int64 `json:"live"`
	Waiting int64 `json:"waiting"`
	Total   int64 `json:"total"`
}

Sessions counts a project's sessions.

type TeamSignal added in v0.96.0

type TeamSignal struct {
	// Authors is the number of distinct commit authors across the listed
	// repositories in the window, bots left out.
	Authors int `json:"authors"`
	// Repos is how many repositories were read.
	Repos int `json:"repos"`
	// WindowDays is the span the count covers.
	WindowDays int `json:"window_days"`
	// CheckedMs is when the count was made; it is cached for teamSignalTTL.
	CheckedMs int64 `json:"checked_ms"`
}

TeamSignal is how many people committed to the listed repositories lately.

It exists for one card in the dashboard: Caprock for Teams is offered only when somebody other than the reader commits to the same code, because "your team runs agents too" said to a person who works alone is a claim the product cannot back. Only counts leave this file — no names, no addresses — and nothing leaves the machine (rule 4).

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"`
	// Repos are the member repositories of a multi-repo project (ADR-055),
	// each with its own git state and share of the activity; absent for an
	// ordinary project.
	Repos []RepoView `json:"repos,omitempty"`
	// InstructionFiles are the repository's own instruction files
	// (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md) at the root, then each
	// member's as "<member>/<file>"; absent when there are none.
	InstructionFiles []string `json:"instruction_files,omitempty"`
	// 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.

Jump to

Keyboard shortcuts

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