setup

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 21 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 setup is otag's first-run setup: it detects the agent CLIs and tools on the machine, proposes accounts, profiles and a project, renders them as commented TOML and writes the files atomically. It holds no UI: `otag init` (internal/cli) and the setup wizard (internal/tui/wizard) drive it, and every function but the Prober and Write is pure, so the choices are unit-testable with injected detection results.

Index

Constants

View Source
const (
	TierSmart  = "smart"  // coordinator and hard tasks
	TierWorker = "worker" // the default for children
	TierFast   = "fast"   // quick, cheap tasks
)

Profile tiers: they order fallbacks and pick a project's default profiles.

View Source
const (
	Create  = "create"
	Append  = "append"
	Replace = "replace"
)

File actions.

View Source
const DocsURL = "https://github.com/nesiler/otag/blob/main/docs/SETUP.md"

DocsURL is where the generated files point for every key.

Variables

View Source
var DefaultDeny = []string{".env*", "*.pem"}

DefaultDeny is the deny list of a new project.

Functions

func AsideName

func AsideName(path string) string

AsideName is where a replace moves path while it puts the new file in place.

func CreateNew

func CreateNew(path string, data []byte, perm os.FileMode) error

CreateNew writes data to path only if nothing is there: a temporary file in the same directory, renamed into place without replacing (an existing path is fs.ErrExist).

func CreateUnique

func CreateUnique(base string, data []byte, perm os.FileMode) (string, error)

CreateUnique is CreateNew at base, else base-2, base-3, ...; it returns the path used.

func DefaultProfiles

func DefaultProfiles(refs []Ref) (coord, def, review string)

DefaultProfiles picks a project's coordinator (a Claude profile, the smartest), default (a Claude worker, else any worker, else the first) and review profile (of another harness than the default when there is one; else another profile).

func Efforts

func Efforts(h string) []string

Efforts are the effort values the wizard offers per harness ("" = the harness's default). OpenCode has no effort setting of its own.

func HarnessTitle

func HarnessTitle(h string) string

HarnessTitle is a harness's product name.

func InstallHint

func InstallHint(name string) string

InstallHint is the command that installs a harness or a required tool.

func LoadExisting

func LoadExisting(dir string, getenv paths.Getenv) (cfg *registry.Config, exists bool, err error)

LoadExisting loads the registry in dir. exists is false when registry.toml is not there (cfg is then nil and err nil).

func LockConfig

func LockConfig(dir string, wait time.Duration) (func(), error)

LockConfig takes the config dir's lock (an flock, waiting up to wait), so two `otag init` / `otag project` commands never read and write the config at once. The returned function releases it; the file stays.

func LockFile

func LockFile(dir string) string

LockFile is the lock that serializes otag's changes to the config dir.

func LookPath

func LookPath(name, pathEnv string) (string, bool)

LookPath finds an executable named name in the directories of pathEnv (the process's own PATH is not consulted, so tests and the CLI's injected environment agree).

func Preflight

func Preflight(configDir string, files []File, getenv paths.Getenv) (*registry.Config, error)

Preflight loads the configuration as it will be after files are written (a copy in a temporary directory), so nothing is written that `otag sync` would refuse.

func ProjectFile

func ProjectFile(dir, name string) string

ProjectFile is the path of a project's TOML in dir.

func Recover

func Recover(dir string) ([]string, error)

Recover undoes interrupted changes; the caller holds the config lock. A file moved aside whose original is missing goes back (a no-replace rename); the returned notes say which. When both exist it touches neither and refuses (CONFLICT, naming both): the user decides which one stays. Temporary files of unfinished writes are removed.

func RegistryFile

func RegistryFile(dir string) string

RegistryFile is the path of registry.toml in dir.

func RemovingName

func RemovingName(path string) string

RemovingName is where `otag project remove` keeps a project file until the project is retired.

func RenameNoReplace

func RenameNoReplace(from, to string) error

RenameNoReplace moves from to to, failing with fs.ErrExist when to exists.

func RenameUnique

func RenameUnique(from, base string) (string, error)

RenameUnique moves from to base (else base-2, base-3, ...) without ever replacing a file there, and returns the new path.

func RenderAppend

func RenderAppend(b Base, c Choices, now time.Time) string

RenderAppend is the block appended to an existing registry.toml: the accounts and profiles of the harnesses it does not use yet. The user's own text above it is kept byte for byte.

func RenderProject

func RenderProject(p Project, home string, now time.Time) string

RenderProject is a projects/<name>.toml.

func RenderRegistry

func RenderRegistry(b Base, c Choices, now time.Time) string

RenderRegistry is a new registry.toml with the active accounts and profiles.

func SamePath

func SamePath(a, b string) bool

SamePath reports whether a and b name the same directory (symlinks resolved, case ignored as APFS does).

func SanitizeName

func SanitizeName(s string) string

SanitizeName turns a directory name into a project name: lower case, runs of other characters as "-", no leading or trailing punctuation ("project" when nothing is left).

func Sum

func Sum(b []byte) string

Sum is the hex sha256 of b.

func TildePath

func TildePath(p, home string) string

TildePath writes p under home as ~/... (home also with its symlinks resolved: git reports /private/var/... for a home under /var).

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a valid account, profile or project name.

func ValidPrefix

func ValidPrefix(s string) bool

ValidPrefix reports whether s is a valid task id prefix.

func Write

func Write(files []File) error

Write writes files under the config lock (LockConfig) the caller holds. Editors do not take that lock, so a replace never trusts a check made earlier:

  • create: a temporary file renamed into place without replacing (RENAME_EXCL): a file there (another setup, an editor) is never replaced;
  • append, replace: the new content goes to a temporary file first. Then the current file is moved aside (rename, to the backup name or a hidden name) and the moved file is hashed: if it is not the content the change was computed from (File.Base), it is moved back and nothing is written. If it is, the new file is renamed into place without replacing: a save that landed after the move recreated the file, so the placement fails and both are kept (the save in place, the old content aside). Only then is the aside copy removed (append) or kept as the backup (replace; File.Backup gets the name used).

The moved-aside file is never lost: every failure leaves it in place or under a name the error gives. A reader sees the old or the new file (or, for an instant, none), never a part.

func WriteAtomic

func WriteAtomic(path string, data []byte, perm os.FileMode) error

WriteAtomic writes data to path through a temporary file in the same directory and a rename (replacing what is there).

Types

type Account

type Account struct {
	Name      string `json:"name"`
	Harness   string `json:"harness"`
	ConfigDir string `json:"config_dir,omitempty"`
	On        bool   `json:"on"`
}

Account is a proposed account: one per harness. Its config_dir is unset (each adapter then uses the harness's default login: ~/.claude, ~/.codex, OpenCode's ~/.config/opencode) unless the environment chose another one ($CLAUDE_CONFIG_DIR, $CODEX_HOME; Tool.CustomConfigDir), which runs would otherwise lose.

type Base

type Base struct {
	ConfigDir string
	Home      string
	Detect    Detection
	// Existing is the registry kept on disk; new accounts and profiles are appended to
	// it. Nil: there is none, or Force replaces it.
	Existing *registry.Config
	// RegistryExists: registry.toml is on disk (with Force it is backed up and replaced).
	RegistryExists bool
	// RegistrySum is the sha256 (Sum) of registry.toml when setup read it: a change
	// computed later is refused if the file no longer has it ("" = not checked).
	RegistrySum string
	Force       bool
	// Known maps every project the database knows, retired ones too, to its prefix: a
	// new project never takes the prefix of another project's old task ids, and a
	// project added again gets its old one back.
	Known map[string]string
	// KnownPaths maps the path of every project the database knows to its name: a
	// repository added again gets its old name (and so its prefix and tasks) back.
	KnownPaths map[string]string
	// DaemonInstalled / SkillInstalled: offered again only when false.
	DaemonInstalled bool
	SkillInstalled  bool
}

Base is what setup starts from.

func (Base) CheckProject

func (b Base) CheckProject(p Project, c Choices) error

CheckProject checks a proposed project's fields.

func (Base) Defaults

func (b Base) Defaults() Choices

Defaults are the proposed choices: every offered harness with its presets, the repository of the current directory as a project (when it is not registered yet), the daemon when it is not installed, no skill.

func (Base) Files

func (b Base) Files(c Choices, now time.Time) ([]File, error)

Files lists what setup writes for c: registry.toml (created, replaced after a backup with Force, or appended to) and the project's file. It checks the choices; Preflight then loads the result as `otag sync` would.

func (Base) NewProject

func (b Base) NewProject(dir string, c Choices) Project

NewProject proposes a project for the git checkout dir.

func (Base) Offered

func (b Base) Offered() []string

Offered lists the harnesses setup proposes: those on PATH that no existing account uses.

func (Base) PrefixTaken

func (b Base) PrefixTaken(prefix, name string) bool

PrefixTaken reports whether a project other than name (in the registry, or any the database knows) uses prefix.

func (Base) ProjectName

func (b Base) ProjectName(dir string) string

ProjectName proposes the name of a project at dir: the name the database knows for that path (a project removed earlier), else the directory's name, numbered while a registered project or another known project has it.

func (Base) Refresh

func (b Base) Refresh(p *Project)

Refresh chooses p's automatic name and prefix again (after Known and KnownPaths were read anew); what the user chose stays, and CheckProject still refuses a clash.

func (Base) Refs

func (b Base) Refs(c Choices) []Ref

Refs lists the profiles that exist after setup: the existing ones (sorted by name), then the active new ones.

func (Base) RepoRegistered

func (b Base) RepoRegistered(dir string) bool

RepoRegistered reports whether an existing project already uses dir.

func (Base) UniquePrefix

func (b Base) UniquePrefix(name string) string

UniquePrefix proposes a short task id prefix for project name: its old prefix when the database knows the project, else the name itself when it has at most four letters and digits, else its first three, made longer (then numbered) until no other project uses it.

type Choices

type Choices struct {
	Accounts []Account `json:"accounts"` // one per harness offered
	Profiles []Profile `json:"profiles"` // the presets of every offered harness
	Project  *Project  `json:"project,omitempty"`
	Daemon   bool      `json:"daemon"` // install the launch agent
	Skill    bool      `json:"skill"`  // install the agent skill
}

Choices is what setup will write: the defaults (Base.Defaults), then the wizard's or the flags' edits.

func (Choices) AccountOn

func (c Choices) AccountOn(h string) bool

AccountOn reports whether the account of harness h is chosen.

func (Choices) Active

func (c Choices) Active() []Profile

Active lists the profiles that will be written: chosen, of a chosen account.

func (*Choices) Wire

func (c *Choices) Wire(b Base)

Wire sets the fallback list of every new profile: for each other harness, its profile of the nearest tier (smart, then the tier below), then the next lower tier of the profile's own harness. claude-opus falls back to codex, then claude-sonnet. Lists name only profiles that exist after setup; existing profiles keep theirs.

type Detection

type Detection struct {
	Harnesses []Tool `json:"harnesses"` // registry.Harnesses order
	Tmux      Tool   `json:"tmux"`
	Git       Tool   `json:"git"`
	// Repo is the top-level directory of the git repository the current directory is
	// in ("" = none).
	Repo string `json:"repo,omitempty"`
}

Detection is what the machine has.

func (Detection) Found

func (d Detection) Found() []string

Found lists the harnesses on PATH, in registry.Harnesses order.

func (Detection) Harness

func (d Detection) Harness(h string) Tool

Harness returns the detection result of harness h.

func (Detection) Missing

func (d Detection) Missing() []string

Missing lists the required tools (tmux, git) that are not on PATH.

type File

type File struct {
	Path   string `json:"path"`
	Action string `json:"action"`           // create | append | replace
	Backup string `json:"backup,omitempty"` // replace: the old file is copied here first
	// Content is the whole new file; Added is what it adds (append: the new block).
	Content []byte `json:"-"`
	Added   string `json:"-"`
	// Base is the sha256 of the file the change was computed from (append, replace):
	// Write refuses when the file no longer has it.
	Base string `json:"-"`
}

File is one file setup writes.

type Leftover

type Leftover struct {
	Aside    string `json:"aside"`    // the file moved aside
	Original string `json:"original"` // where it belongs
	// Both: the original exists again too (written after the move): otag cannot tell
	// which one is wanted and changes nothing until one is deleted.
	Both bool `json:"both"`
}

Leftover is a file an interrupted otag change left aside.

func Leftovers

func Leftovers(dir string) ([]Leftover, error)

Leftovers lists the moved-aside files in the config dir and its projects dir. It only reads.

type Prober

type Prober struct {
	PATH string // the PATH searched (not the process's own)
	Home string
	// CodexHome is $CODEX_HOME ("" = ~/.codex); ClaudeConfigDir is $CLAUDE_CONFIG_DIR
	// ("" = ~/.claude).
	CodexHome       string
	ClaudeConfigDir string
	// Run runs bin with args and returns its combined output; nil = os/exec with a
	// 5 s timeout.
	Run func(ctx context.Context, bin string, args ...string) (string, error)
}

Prober detects tools. Its fields are the process environment; tests replace Run.

func (Prober) Detect

func (p Prober) Detect(ctx context.Context, cwd string) Detection

Detect looks for the harnesses, tmux and git, and the git repository of cwd. The version commands run in parallel.

func (Prober) Repo

func (p Prober) Repo(ctx context.Context, dir string) string

Repo is the top-level directory of the git repository dir is in ("" = none, or git is not on PATH).

type Profile

type Profile struct {
	Name        string   `json:"name"`
	Harness     string   `json:"harness"`
	Account     string   `json:"account"`
	Model       string   `json:"model,omitempty"`  // "" = the harness's default model
	Effort      string   `json:"effort,omitempty"` // "" = the harness's default effort
	Tier        string   `json:"tier"`
	Tags        []string `json:"tags,omitempty"`
	Description string   `json:"description,omitempty"`
	Fallback    []string `json:"fallback,omitempty"` // wired by Choices.Wire
	On          bool     `json:"on"`
}

Profile is a proposed profile.

type Project

type Project struct {
	Name        string   `json:"name"`
	Path        string   `json:"path"`
	Prefix      string   `json:"prefix"`
	Workspace   string   `json:"workspace"`
	Guard       string   `json:"guard"`
	Deny        []string `json:"deny"`
	Coordinator string   `json:"coordinator_profile,omitempty"`
	Default     string   `json:"default_profile,omitempty"`
	Review      string   `json:"review_profile,omitempty"`
	// AutoName / AutoPrefix: chosen by setup, not by the user. Apply chooses them
	// again against the database it then reads writable (Base.Refresh).
	AutoName   bool `json:"-"`
	AutoPrefix bool `json:"-"`
}

Project is a proposed projects/<name>.toml.

type Ref

type Ref struct {
	Name, Harness, Tier string
}

Ref is a profile a project or a fallback list may name.

type Tool

type Tool struct {
	Name    string `json:"name"`
	Path    string `json:"path,omitempty"`    // "" = not found
	Version string `json:"version,omitempty"` // the first line of its version output
	// ConfigDir is the harness's config directory when it exists (display).
	ConfigDir string `json:"config_dir,omitempty"`
	// CustomConfigDir is a non-default config directory chosen in the environment
	// ($CLAUDE_CONFIG_DIR, $CODEX_HOME). The adapters scrub those variables from a
	// run's environment, so the generated account names it as config_dir; empty, the
	// account leaves config_dir unset (the harness's default login).
	CustomConfigDir string `json:"custom_config_dir,omitempty"`
}

Tool is a program found (or not) on PATH.

func (Tool) Found

func (t Tool) Found() bool

Found reports whether the tool is on PATH.

Jump to

Keyboard shortcuts

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