Documentation
¶
Overview ¶
Package cli implements the commands against the gh.IssueStore interface (plus gh.PullRequests, for `pr` alone), so cmd/hew is pure wiring and everything with behavior is testable against a fake.
Index ¶
- Constants
- func ExitCode(err error) int
- func FindProjectRoot(start string) (string, error)
- func ParseIssueNumber(arg, usage string) (int, error)
- func ParseRepoSpec(spec string) (gh.Repo, error)
- func RepoDetectError(err error, offerLocal bool) error
- func ValidateArgCount(args []string, min, max int, usage string) error
- func ValidateIssueNumbers(flag string, numbers ...int) error
- type App
- func (a *App) Apply(ctx context.Context, opts ApplyOpts) error
- func (a *App) Block(ctx context.Context, number int, blockers []int, allowClosed bool) error
- func (a *App) Close(ctx context.Context, number int, reason string, completed bool, ...) error
- func (a *App) Config(target ConfigTarget) error
- func (a *App) Create(ctx context.Context, opts CreateOpts) error
- func (a *App) Draft(_ context.Context, opts DraftOpts) error
- func (a *App) EpicCreate(ctx context.Context, opts EpicCreateOpts) error
- func (a *App) EpicStatus(ctx context.Context, opts EpicStatusOpts) error
- func (a *App) HooksInstall(projectRoot string, agent HookAgent) error
- func (a *App) HooksRemove(projectRoot string, agent HookAgent) error
- func (a *App) Init(ctx context.Context) error
- func (a *App) InitLocal(ctx context.Context, dir string) error
- func (a *App) List(ctx context.Context, opts ListOpts) error
- func (a *App) MigrateBeads(ctx context.Context, opts MigrateOpts) error
- func (a *App) MigrateLocal(ctx context.Context, opts MigrateLocalOpts) error
- func (a *App) PR(ctx context.Context, opts PROpts) error
- func (a *App) Prime(ctx context.Context, opts PrimeOpts) error
- func (a *App) Ready(ctx context.Context, opts ReadyOpts) error
- func (a *App) Release(ctx context.Context, number int, force bool) error
- func (a *App) Reopen(ctx context.Context, number int, reason string) error
- func (a *App) Search(ctx context.Context, opts SearchOpts) error
- func (a *App) Set(ctx context.Context, number int, opts SetOpts) error
- func (a *App) Show(ctx context.Context, number int) error
- func (a *App) Start(ctx context.Context, number int, opts StartOpts) error
- func (a *App) Triage(ctx context.Context, opts TriageOpts) error
- func (a *App) Unblock(ctx context.Context, number int, blockers []int, allowClosed bool) error
- type ApplyOpts
- type ConfigTarget
- type CreateOpts
- type DraftOpts
- type EpicCreateOpts
- type EpicStatusOpts
- type ExitError
- type HookAgent
- type ListOpts
- type MigrateLocalOpts
- type MigrateOpts
- type PROpts
- type PrimeOpts
- type ReadyOpts
- type SearchOpts
- type SetOpts
- type StartOpts
- type TriageOpts
Constants ¶
const ( ExitGeneric = 1 ExitUsage = 2 // ExitClaimed is start's "already claimed" refusal: pick the next // ready item instead of doubling up. ExitClaimed = 3 ExitAuth = 4 // ExitClaimedByYou splits the claim refusal: the claimant is the // authenticated user, so the work is already yours and the response is // to resume it, not to pick a different item. The guard is unchanged — // this only says whose claim blocked it. ExitClaimedByYou = 5 // ExitBlocked is start's "open blockers" refusal: ready hides the issue // until its blockers close, so pick the next ready item instead. ExitBlocked = 6 )
Exit codes, kept meaningful so agent loops can branch on them.
const DefaultReadyLimit = 30
DefaultReadyLimit caps `ready` output unless the caller says otherwise. It sits above primeReadyCap on purpose: the primer truncates its own ready section and points at `hew ready` for the rest, so a cap at or below that one would leave the pointer pointing at nothing new.
Variables ¶
This section is empty.
Functions ¶
func ExitCode ¶
ExitCode maps an error to the process exit code agent loops branch on: an ExitError's own code, ExitAuth for an auth failure (so "run gh auth login" is distinguishable), else ExitGeneric. nil maps to 0. The mapping lives here, not in main, so it is covered by tests.
Auth failures are matched through the cause chain, so a partial-operation error — a dependency edge that failed after earlier ones landed, a close whose state change failed after the comment posted — still exits 4. The library translates the store's failure once, into tracker.AuthError; the adapter adds no per-operation cases.
func FindProjectRoot ¶
FindProjectRoot walks up from start until it finds the directory containing .git (a directory in a normal checkout, a file in a worktree). Project-level Claude Code settings live at its .claude/.
func ParseIssueNumber ¶
ParseIssueNumber parses a required positional issue number, tolerating a leading '#'. It returns an ExitUsage error (with the given usage string) when the argument is missing or not a positive integer.
func ParseRepoSpec ¶
ParseRepoSpec parses an "owner/name" repository spec, returning an ExitUsage error when it is malformed.
func RepoDetectError ¶ added in v0.18.0
RepoDetectError turns the failure of detecting the GitHub repository from the git remote into one readable line that says what to do next. The cause arrives from go-gh as plain text, so the cases are told apart by the words it and git use for them; anything unrecognised keeps its message and the --repo escape hatch.
offerLocal says whether the caller reached GitHub only because no local tracker exists, which is when a repository with no remote can be pointed at `hew init --local`. A command that targets GitHub from an already-local checkout (migrate local) passes false: init would be no way forward there. Outside a git repository local mode is never offered, since it needs a checkout too.
func ValidateArgCount ¶ added in v0.15.0
ValidateArgCount rejects missing or surplus positionals before a command performs any I/O. min and max are inclusive; optional arguments use min 0.
func ValidateIssueNumbers ¶ added in v0.15.0
ValidateIssueNumbers checks values of an explicitly set issue-number flag. Callers distinguish an omitted optional flag from an explicit zero.
Types ¶
type App ¶
type App struct {
Client gh.IssueStore
// PRs is nil on a backend with no pull requests; `pr` refuses there.
PRs gh.PullRequests
Repo gh.Repo
// RepoKey is the identity batch checkpoints bind to, when it differs from
// Repo.String() (the local backend: a stable tracker id, not the checkout's
// directory name, which two checkouts can share and a rename changes).
// Empty means Repo.String().
RepoKey string
// Local marks the local-only backend: the primer and init output are the
// local variants, which have no pull-request step.
Local bool
Out io.Writer
ErrOut io.Writer
JSON bool
// Color is the precomputed TTY decision (render.ColorEnabled on the
// real stdout in main): text renderers wrap their semantic spans in
// ANSI only when it is set. JSON and piped output are never affected.
Color bool
// Edit opens an editor seeded with initial text and returns the result;
// wired to $EDITOR by main, injected by tests.
Edit func(initial string) (string, error)
// Git reads the local branch state `pr` opens from; wired to the git
// binary by main, injected by tests.
Git func() (git.State, error)
}
App holds the dependencies every command needs.
func (*App) Apply ¶
Apply batch-creates issues from a plan file: create in file order, checkpointing after every write, then wire parents and blockers — the migrate machinery generalized to arbitrary plans, with local ids playing the role of bead IDs. The execution itself lives in tracker.ApplyPlan; this command parses the file, validates the flags' extra rules and renders the result.
func (*App) Block ¶
Block adds native dependencies through tracker, which owns the transitive client-side cycle check — GitHub itself only rejects self-blocks and direct two-issue cycles. The typed refusal is rendered here in the command's own text; the library call is the same one any in-process consumer makes.
func (*App) Close ¶
func (a *App) Close(ctx context.Context, number int, reason string, completed bool, duplicateOf int, force bool) error
Close comments the reason and closes: not-planned unless --completed or --duplicate-of. Closing via PR is the norm; this is for wontfix/duplicate. An epic with open sub-issues is refused without force: closing one strands the children under a closed parent, and the guard names the flag rather than trusting a warning to be read. The decisions live in tracker.Close; what stays here is the CLI's wording and exit codes for its refusals.
func (*App) Config ¶ added in v0.18.0
func (a *App) Config(target ConfigTarget) error
Config prints the effective backend selection. The caller resolves the target and opens no store or client: this method only chooses the fields that backend has and renders them.
func (*App) Create ¶
func (a *App) Create(ctx context.Context, opts CreateOpts) error
Create files a new issue conforming to the conventions: exactly one priority and one type label, template-scaffolded body, native dependencies and parent links. The decisions live in tracker.Create; what stays here is the flag-level body input, the flag spelling of its refusals, the markup warning, and rendering the result.
func (*App) Draft ¶ added in v0.15.0
Draft composes or checks an issue body locally, before anything is published. create reports markup findings only after it has written the issue, which leaves the author correcting a body they have to fetch back; a draft file is corrected first and published as-is with create --body-file. It never touches a.Client, so it needs no credentials or network, and it never edits author text — findings are reported, not fixed.
func (*App) EpicCreate ¶
func (a *App) EpicCreate(ctx context.Context, opts EpicCreateOpts) error
EpicCreate files a parent issue and attaches existing children. Epics get the cosmetic title prefix, a priority label and the epic label but no type — they are containers, not work. The epic label is what keeps a childless epic triaged, listed and unworkable until its first child lands. The decisions live in tracker.CreateEpic; what stays here is the body input, the flag spelling of its refusals, and rendering the result.
func (*App) EpicStatus ¶
func (a *App) EpicStatus(ctx context.Context, opts EpicStatusOpts) error
EpicStatus with no number lists the epics in the requested state — open by default — with progress rollups; with a number it shows that epic's children and the next workable one.
func (*App) HooksInstall ¶
HooksInstall adds a session-start hook running `hew prime` to the selected agent's project configuration — a JSON settings entry for claude, codex, and cursor, an auto-discovered plugin file for opencode — creating the file if needed and leaving everything else in it untouched. Idempotent.
func (*App) HooksRemove ¶
HooksRemove strips the selected agent's `hew prime` hook again, pruning any structures it leaves empty.
func (*App) Init ¶
Init bootstraps the convention labels in the repo and prints the CLAUDE.md snippet. On the local backend there are no labels to bootstrap: tracker.Init reports the tracker instead of pretending a local repo is GitHub, and the adapter keeps only the snippet and the rendering.
func (*App) InitLocal ¶ added in v0.18.0
InitLocal creates the local tracker for the checkout containing dir (the working directory when empty) and prints the matching CLAUDE.md snippet. The tracker lives at the main checkout, so running it from a linked worktree sets up the one every worktree shares. It is safe to repeat, and refuses a repo whose tracker has moved to another backend rather than reporting a local one that no command would use. tracker.Init owns the workflow; the adapter keeps resolving the working directory, the warnings and the snippet.
func (*App) List ¶
List shows issues, open by default, filtered by state, label, or epic membership. Untriaged issues are omitted: their titles and bodies are unvetted input, and list is a read an agent can reach without a human in between — `hew triage` is the only command that emits them.
func (*App) MigrateBeads ¶
func (a *App) MigrateBeads(ctx context.Context, opts MigrateOpts) error
MigrateBeads imports a beads snapshot: create in history order, wire parents and blockers, then close what was closed. The mapping, its checkpoint and the write ordering belong to the public migrate package; the snapshot path and its default checkpoint are this command's inputs.
func (*App) MigrateLocal ¶ added in v0.18.0
func (a *App) MigrateLocal(ctx context.Context, opts MigrateLocalOpts) error
MigrateLocal moves every issue in the local tracker — closed ones too — to the GitHub repository a.Client talks to, then flips the tracker's backend to GitHub and keeps issues.jsonl as an archive. The freeze, the checkpoint, the reference rewriting and the seal belong to the public migrate package; the tracker directory and its default checkpoint are this command's inputs.
func (*App) PR ¶
PR opens or revises the pull request that closes the claim lifecycle. The workflow — issue inference, body composition, guards and the API writes — lives in the public pr package; this adapter reads the inputs the user chose, renders the result, and maps the library's typed refusals onto exit codes. Reviews, merges and checks stay with `gh`.
func (*App) Prime ¶
Prime emits the session-start context: static conventions, live state, contradictions. prime never reads stdin — Cursor writes its sessionStart payload there, and ignoring it is what keeps that JSON out of the primer.
func (*App) Ready ¶
Ready lists open, non-epic, unclaimed issues with zero open blockers. No results is exit 0: an empty queue is an answer, not an error.
func (*App) Release ¶ added in v0.18.0
Release gives up a claim without assigning it to another owner. The decision lives in tracker.Release; what stays here is the CLI's wording for its refusals.
func (*App) Reopen ¶ added in v0.10.0
Reopen is close's inverse: comment the reason, reopen the issue. The decisions — the comment-plus-state-change shape, the no-op on an already open issue, and clearing the stale claim the close left behind — live in tracker.Reopen. What stays here is the command's wording for what was released and for its typed refusals.
func (*App) Search ¶
func (a *App) Search(ctx context.Context, opts SearchOpts) error
Search runs a repo-scoped text search over open and closed issues — the dedupe step before filing discovered work, where "already fixed" answers the question as well as "already filed". Output keeps the API's best-match order rather than the list sort: relevance is the point. Untriaged matches are omitted (their text is unvetted input); the other half of dedup, over the untriaged queue, is `hew triage --search`.
func (*App) Set ¶
Set retriages or edits within the conventions. tracker.Edit owns the field validation, the priority/type swaps, the parent move and the partial-failure report; what stays here is reading the body file, the flag spelling of a refusal and the exit codes.
func (*App) Show ¶
Show prints one issue in full: body, deps, parent, children, comments. An epic's detail view also names its next workable child, which needs each child's blockers — a second two-state fetch, but only when the subject is an epic.
func (*App) Start ¶
Start claims an issue: assign @me plus the in-progress label. The decision lives in tracker.Start; what stays here is the CLI contract it cannot carry: the guard's refusals map to exit 3 for someone else's claim (pick the next ready item), exit 5 when the claim is already yours (resume), and exit 6 for open blockers ready would have hidden; --force overrides both. Claiming an untriaged issue requires --priority — claiming forces triage. An idea needs --for-discovery even under --force: the flag declares the caller's intent to investigate, which is a usage decision rather than a claim outcome.
func (*App) Triage ¶
func (a *App) Triage(ctx context.Context, opts TriageOpts) error
Triage lists issues missing their priority or type label, oldest first — work through them with `hew set`. With Search it is the dedup path over untriaged content, the one list-shaped read that emits it: an agent harness deny list keys on this command, so nothing else may.
type ApplyOpts ¶
type ApplyOpts struct {
// File is the JSONL plan.
File string
// StatePath is where the entry-key→issue-number mapping and the edges
// already wired are persisted after every write, making a failed run
// resumable and an unchanged finished one a quiet no-op. Bound to the
// repository and a digest of the plan, so an edited plan or a state file
// from elsewhere is refused rather than trusted (#81). Empty means
// File + ".state.json".
StatePath string
// DryRun prints the plan without creating anything. It still reads: the
// state file's issues and every existing issue the plan references are
// looked up, so it shows the refusal the real run would hit.
DryRun bool
// Throttle is slept between writes to stay under GitHub's secondary
// rate limits for content creation.
Throttle time.Duration
}
ApplyOpts configure a batch apply.
type ConfigTarget ¶ added in v0.18.0
ConfigTarget is a resolved backend selection in the shape the public tracker.Target reports: the backend, the GitHub repository, and the local tracker's directory and stable id. The caller resolves it; this package only chooses which fields to render.
type CreateOpts ¶
type CreateOpts struct {
Title string
Type string
Priority string // empty means DefaultPriority
Areas []string
BlockedBy []int
Parent int
DiscoveredFrom int
Sections conventions.Sections
BodyFile string
Edit bool
}
CreateOpts are the create command's inputs.
type DraftOpts ¶ added in v0.15.0
type DraftOpts struct {
Sections conventions.Sections
Out string
Check string
}
DraftOpts are the draft command's inputs: either section flags to compose (optionally into Out), or Check naming an existing draft to revalidate.
type EpicCreateOpts ¶
type EpicCreateOpts struct {
Title string
Children []int
Sections conventions.Sections
BodyFile string
Edit bool
}
EpicCreateOpts are the epic create inputs. The body paths match create: section flags, --body-file, or --edit.
type EpicStatusOpts ¶ added in v0.19.0
type EpicStatusOpts struct {
// Number, when positive, shows that epic's children instead of the rollup.
Number int
// State is "open", "closed", or "all" and selects which epics the rollup
// lists; empty means open. It has no meaning for one epic's children,
// which always show every state so progress reads as done and left.
State string
}
EpicStatusOpts selects what epic status shows.
type ExitError ¶
ExitError carries a specific exit code to main.
func UsageError ¶ added in v0.9.0
UsageError lets command wiring report a usage failure with the same exit contract as command-layer validation.
type HookAgent ¶ added in v0.9.0
type HookAgent string
HookAgent is an agent whose project-level session-start configuration hew manages.
func ParseHookAgent ¶ added in v0.9.0
ParseHookAgent accepts the agents whose hook file formats hew supports.
type ListOpts ¶
type ListOpts struct {
Label string
// Type keeps issues whose normalized type matches — bug, enhancement, task
// or idea — so `--type idea` lists ideas without matching a literal label.
Type string
Epic int
// NoEpic keeps issues outside every epic: no parent, and not an epic. It
// is an alternative to Epic.
NoEpic bool
// State is "open", "closed", or "all"; empty means the default, which is
// open — except under Epic, where progress means seeing what is done as
// well as what is left.
State string
// Closed is the older spelling of State "closed". Kept working for
// existing callers; passing both is a usage error rather than a silent
// precedence rule.
Closed bool
// Bodies carries each issue's body on the NDJSON lines — triaged-tracker
// dedup in one call (untriaged issues stay behind `hew triage`). JSON-only:
// text output has no place for bodies.
Bodies bool
// Limit caps how many issues are printed; 0, the default, prints all.
// The cap applies after sorting, so it keeps the top N of list order.
Limit int
}
ListOpts filters list output.
type MigrateLocalOpts ¶ added in v0.18.0
type MigrateLocalOpts struct {
// Dir is the local tracker directory (.hew at the main checkout).
Dir string
// StatePath is where the local number → GitHub number checkpoint is kept
// between a failed run and its rerun; default <Dir>/migration-state.json.
// Bound to the repository and to a digest of issues.jsonl.
StatePath string
// DryRun prints the plan without touching GitHub or the tracker.
DryRun bool
// Throttle is slept between writes to stay under GitHub's secondary
// rate limits for content creation.
Throttle time.Duration
}
MigrateLocalOpts configure the local-to-GitHub migration.
type MigrateOpts ¶
type MigrateOpts struct {
// File is the beads issues.jsonl snapshot.
File string
// StatePath is where the beadID→issue-number mapping is persisted
// after every create, making a failed run resumable. Bound to the repository
// and a digest of the snapshot (#81).
StatePath string
// DryRun prints the plan without touching GitHub.
DryRun bool
// IncludeClosed migrates closed beads too (created, commented with the
// close reason, then closed). Real databases are >95% closed, so this
// is opt-in.
IncludeClosed bool
// Throttle is slept between writes to stay under GitHub's secondary
// rate limits for content creation.
Throttle time.Duration
}
MigrateOpts configure the beads migration.
type PROpts ¶
type PROpts struct {
// Amend revises the open PR on this branch instead of creating one.
Amend bool
// SectionFlags records explicitly supplied flags, including empty values.
SectionFlags []string
// For overrides issue inference; empty means infer. Several values are a
// deliberate multi-issue PR: only declared issues are ever combined,
// never inferred ones.
For []int
Title string
Sections conventions.PRSections
BodyFile string
// Ready opens the PR for review instead of as a draft.
Ready bool
// Base overrides the target branch; empty means the repo default.
Base string
}
PROpts are the pr command's inputs. Every section is optional: the point of the command is that tracker state fills the gaps.
type PrimeOpts ¶ added in v0.11.0
type PrimeOpts struct {
// HookFormat is the session-start hook format to emit. Empty is the
// plain text primer; "cursor" JSON-encodes the primer into the
// additional_context field Cursor's sessionStart hook reads.
HookFormat string
}
PrimeOpts re-targets the primer's output at a caller with its own format, such as an agent hook whose stdout contract is not text.
type ReadyOpts ¶ added in v0.9.0
type ReadyOpts struct {
// Limit caps how many issues are printed; 0 means unlimited. Capping is
// safe because model.Ready is priority-sorted — the top N is the top N by
// priority — but it is never silent: ready is the queue agents branch on,
// and a truncated list read as complete reads as an empty backlog.
Limit int
}
ReadyOpts filters ready output.
type SearchOpts ¶ added in v0.19.0
type SearchOpts struct {
Terms string
// State is "open", "closed", or "all"; empty means all, because the
// point of search is finding "already fixed" as well as "already filed".
State string
// Limit caps how many matches are printed; 0, the default, prints all
// that came back.
Limit int
}
SearchOpts shapes a search.
type SetOpts ¶
type SetOpts struct {
Priority string
Type string
AddAreas []string
RemoveAreas []string
Parent int
NoParent bool
Title string
// TitleSet records that --title was passed, so an explicitly empty one is
// an error rather than the same thing as leaving the title alone.
TitleSet bool
Outcome *string
BodyFile string
AllowClosed bool
}
SetOpts are the retriage/edit inputs; zero values mean "leave alone".
type StartOpts ¶ added in v0.15.0
type StartOpts struct {
// Priority is required when the issue is untriaged (claiming is triage).
Priority string
// Force steals an already-claimed issue and claims one that has open
// blockers.
Force bool
// ForDiscovery declares that an idea is being claimed to investigate it;
// an idea that is not declared this way is refused.
ForDiscovery bool
// Show follows the claim confirmation with the issue's detail view, so
// claiming and reading are one call. --json already includes the body
// (as every mutation's JSON does, without text findings), so it ignores
// this.
Show bool
}
StartOpts are the claim inputs; zero values mean the default behavior.
type TriageOpts ¶ added in v0.11.0
type TriageOpts struct {
// Search restricts triage to search matches instead of the open queue:
// the dedup half over untriaged titles and bodies, spanning both states
// so "already fixed" answers as well as "already filed". Empty is the
// queue view: open untriaged issues, oldest first.
Search string
}
TriageOpts retargets triage at the dedup case.