Documentation
¶
Overview ¶
Package tracker provides hew's tracker in-process: initialize and open a local or GitHub tracker, read it, and write to it, with typed results and typed errors instead of flags, rendering and exit codes. The CLI is an adapter over this package, `pr` and `migrate`; DESIGN.md's "Tracker library" section is the contract and maps every command to the operation behind it.
Opening ¶
Open and Init take the worktree, and optionally the backend, repository and claimant, as arguments; nothing reads the process's working directory or environment, and nothing prints (notices go to Config.Notice). Detect reports which backend a worktree resolves to. A long-lived process should pin Config.Backend and treat a later Detect that disagrees as an error rather than following it.
Reading and writing ¶
Snapshot fetches the open issues once; Ready, List and Epics query it client-side, and Detail, Search, Triage and Primer carry the commands' own query policy, including the untriaged boundary: only Triage returns text no maintainer has vetted. Create, Edit, Start, Release, Close, Reopen, Block and Unblock write, and ApplyPlan creates a batch with a Checkpoint for resume. Every convention the CLI enforces on write is enforced here, and Block checks for dependency cycles before it mutates.
Identity and concurrency ¶
A local tracker has one claimant per worker: Config.Actor, or As on an open tracker. It is safe to write from several worktrees at once, because every mutation takes the tracker's lock and Start has exactly one winner. On GitHub every claim is the authenticated login, so two sessions are indistinguishable and As changes nothing; a consumer keeps its own record of which worker holds which issue. Read Identity for the effective claimant, and StartOutcomeOf to classify a refused Start. Every call takes a context.Context, and an interrupted multi-write operation reports the part that landed in a typed partial-write error.
Stability ¶
The API is experimental until hew 1.0 and may change in any v0.x minor release. A breaking change ships as a feat!: or fix!: commit, and CI diffs the exported surface of this package against the base commit. The GitHub backend needs the same gh credentials as the CLI; the local backend needs neither gh nor a network.
Example (Block) ¶
Dependency writes are cycle-checked client-side, exactly as `hew block` is, because GitHub accepts cycles longer than two issues.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"github.com/lumberbarons/hew/tracker"
)
// newLocalTracker opens a throwaway local tracker in a fresh git checkout, so
// the examples run without GitHub, gh credentials or a network.
func newLocalTracker(ctx context.Context) (*tracker.Tracker, func()) {
dir, err := os.MkdirTemp("", "hew-example-")
if err != nil {
log.Fatal(err)
}
if out, err := exec.Command("git", "-C", dir, "init", "--quiet").CombinedOutput(); err != nil {
log.Fatalf("git init: %v: %s", err, out)
}
if _, err := tracker.Init(ctx, tracker.InitConfig{Worktree: dir, Backend: tracker.BackendLocal}); err != nil {
log.Fatal(err)
}
t, err := tracker.Open(ctx, tracker.Config{Worktree: dir, Actor: "worker-1"})
if err != nil {
log.Fatal(err)
}
return t, func() { _ = os.RemoveAll(dir) }
}
func create(ctx context.Context, t *tracker.Tracker, title string) int {
res, err := t.Create(ctx, tracker.CreateRequest{
Title: title,
Type: "task",
Body: tracker.Body{Sections: tracker.Sections{
Goal: title,
Approach: "Do it.",
DoneWhen: []string{"It is done"},
}},
})
if err != nil {
log.Fatal(err)
}
return res.Issue.Number
}
func main() {
ctx := context.Background()
t, cleanup := newLocalTracker(ctx)
defer cleanup()
a := create(ctx, t, "First")
b := create(ctx, t, "Second")
if _, err := t.Block(ctx, b, []int{a}, tracker.BlockOptions{}); err != nil {
log.Fatal(err)
}
_, err := t.Block(ctx, a, []int{b}, tracker.BlockOptions{})
var cycle *tracker.CycleError
if errors.As(err, &cycle) {
fmt.Println(cycle.Cycle) // the ordered path
}
}
Output: [1 2 1]
Example (Claims) ¶
A local tracker carries one claimant per worker. As shares the open store; on GitHub every claim is the authenticated login and As changes nothing.
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"github.com/lumberbarons/hew/tracker"
)
// newLocalTracker opens a throwaway local tracker in a fresh git checkout, so
// the examples run without GitHub, gh credentials or a network.
func newLocalTracker(ctx context.Context) (*tracker.Tracker, func()) {
dir, err := os.MkdirTemp("", "hew-example-")
if err != nil {
log.Fatal(err)
}
if out, err := exec.Command("git", "-C", dir, "init", "--quiet").CombinedOutput(); err != nil {
log.Fatalf("git init: %v: %s", err, out)
}
if _, err := tracker.Init(ctx, tracker.InitConfig{Worktree: dir, Backend: tracker.BackendLocal}); err != nil {
log.Fatal(err)
}
t, err := tracker.Open(ctx, tracker.Config{Worktree: dir, Actor: "worker-1"})
if err != nil {
log.Fatal(err)
}
return t, func() { _ = os.RemoveAll(dir) }
}
func create(ctx context.Context, t *tracker.Tracker, title string) int {
res, err := t.Create(ctx, tracker.CreateRequest{
Title: title,
Type: "task",
Body: tracker.Body{Sections: tracker.Sections{
Goal: title,
Approach: "Do it.",
DoneWhen: []string{"It is done"},
}},
})
if err != nil {
log.Fatal(err)
}
return res.Issue.Number
}
func main() {
ctx := context.Background()
t, cleanup := newLocalTracker(ctx)
defer cleanup()
n := create(ctx, t, "Shared work")
worker3 := t.As("worker-3")
fmt.Println("claiming as", worker3.Identity())
if _, err := worker3.Start(ctx, n, tracker.StartOptions{}); err != nil {
log.Fatal(err)
}
// A second claimant is refused with a typed error, and StartOutcomeOf
// names the decision a work loop acts on.
_, err := t.Start(ctx, n, tracker.StartOptions{})
if outcome, ok := tracker.StartOutcomeOf(err); ok {
fmt.Println(outcome)
}
}
Output: claiming as worker-3 claimed_by_other
Example (Reads) ¶
Reads: one fetch of the open issues, queried client-side, then a single issue's full view.
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"github.com/lumberbarons/hew/tracker"
)
// newLocalTracker opens a throwaway local tracker in a fresh git checkout, so
// the examples run without GitHub, gh credentials or a network.
func newLocalTracker(ctx context.Context) (*tracker.Tracker, func()) {
dir, err := os.MkdirTemp("", "hew-example-")
if err != nil {
log.Fatal(err)
}
if out, err := exec.Command("git", "-C", dir, "init", "--quiet").CombinedOutput(); err != nil {
log.Fatalf("git init: %v: %s", err, out)
}
if _, err := tracker.Init(ctx, tracker.InitConfig{Worktree: dir, Backend: tracker.BackendLocal}); err != nil {
log.Fatal(err)
}
t, err := tracker.Open(ctx, tracker.Config{Worktree: dir, Actor: "worker-1"})
if err != nil {
log.Fatal(err)
}
return t, func() { _ = os.RemoveAll(dir) }
}
func create(ctx context.Context, t *tracker.Tracker, title string) int {
res, err := t.Create(ctx, tracker.CreateRequest{
Title: title,
Type: "task",
Body: tracker.Body{Sections: tracker.Sections{
Goal: title,
Approach: "Do it.",
DoneWhen: []string{"It is done"},
}},
})
if err != nil {
log.Fatal(err)
}
return res.Issue.Number
}
func main() {
ctx := context.Background()
t, cleanup := newLocalTracker(ctx)
defer cleanup()
parse := create(ctx, t, "Parse the config")
create(ctx, t, "Render the report")
snap, err := t.Snapshot(ctx, tracker.SnapshotOptions{}) // open issues, one fetch
if err != nil {
log.Fatal(err)
}
for _, issue := range snap.Ready() {
fmt.Println(issue.Number, issue.Title)
}
// A single issue's view carries its body, comments and advisory text findings.
detail, err := t.Detail(ctx, parse)
if err != nil {
log.Fatal(err)
}
fmt.Println(detail.Issue.Number, detail.Issue.Title, len(detail.TextFindings))
}
Output: 1 Parse the config 2 Render the report 1 Parse the config 0
Index ¶
- Constants
- func EdgeKey(kind EdgeKind, from, to int) string
- func FileDigest(data []byte) string
- func NormalizeAreas(areas []string) ([]string, error)
- func PlanBody(e PlanEntry) string
- func PlanBodyWithProvenance(e PlanEntry, digest string) string
- func PlanTitle(e PlanEntry) string
- func SaveCheckpointFile(path string, state *CheckpointState) error
- func ValidateAreaLabel(area string) error
- func ValidatePlan(entries []PlanEntry) error
- func ValidateSections(s Sections) error
- func ValidateTitle(title string) error
- type AppliedEntry
- type ApplyOptions
- type ApplyResult
- type AuthError
- type Backend
- type BlockOptions
- type BlockResult
- type BlockedError
- type Body
- type BodyCheck
- type Checkpoint
- type CheckpointEntry
- type CheckpointState
- type ClaimedError
- type CloseOptions
- type CloseResult
- type ClosedError
- type Comment
- type ComposedBody
- type Config
- type CreateEpicRequest
- type CreateRequest
- type CreateResult
- type CreateStage
- type CreatedEdge
- type CycleError
- type DiscoveryIntentError
- type Edge
- type EdgeKind
- type EditRequest
- type EditResult
- type EpicError
- type ExistingRef
- type FileCheckpoint
- func (c *FileCheckpoint) Created(key string) (int, bool)
- func (c *FileCheckpoint) CreatedEntries() []CheckpointEntry
- func (c *FileCheckpoint) Digest() string
- func (c *FileCheckpoint) RecordCreated(key string, number int) error
- func (c *FileCheckpoint) RecordStep(key string) error
- func (c *FileCheckpoint) RecordWired(kind EdgeKind, from, to int) error
- func (c *FileCheckpoint) Recorded(key string) bool
- func (c *FileCheckpoint) Wired(kind EdgeKind, from, to int) bool
- type Finding
- type FindingKind
- type InitConfig
- type InitResult
- type InitializedElsewhereError
- type InvalidInputError
- type Issue
- type IssueDetail
- type ListFilter
- type LockTimeoutError
- type MemoryCheckpoint
- func (c *MemoryCheckpoint) Created(key string) (int, bool)
- func (c *MemoryCheckpoint) CreatedEntries() []CheckpointEntry
- func (c *MemoryCheckpoint) Digest() string
- func (c *MemoryCheckpoint) RecordCreated(key string, number int) error
- func (c *MemoryCheckpoint) RecordStep(key string) error
- func (c *MemoryCheckpoint) RecordWired(kind EdgeKind, from, to int) error
- func (c *MemoryCheckpoint) Recorded(key string) bool
- func (c *MemoryCheckpoint) Wired(kind EdgeKind, from, to int) bool
- type MigratedError
- type NotClaimedError
- type NotFoundError
- type NotOpenError
- type NotOwnerError
- type OpenChildrenError
- type PRSections
- type PRTrailers
- type ParentedError
- type PartialCloseError
- type PartialCreateError
- type PartialEditError
- type PartialReleaseError
- type PartialReopenError
- type PartialWriteError
- type PlanEntry
- type PlanRef
- type PlannedEntry
- type PrimerResult
- type RateLimit
- type Reader
- type Ref
- type ReleaseOptions
- type ReopenOptions
- type ReopenResult
- type ReopenStage
- type SearchRequest
- type SearchResult
- type Sections
- type Snapshot
- func (s *Snapshot) Blocked() []Issue
- func (s *Snapshot) Children(epic int) []Issue
- func (s *Snapshot) Claimed() []Issue
- func (s *Snapshot) Epics() []Issue
- func (s *Snapshot) Get(number int) (Issue, bool)
- func (s *Snapshot) Issues() []Issue
- func (s *Snapshot) List(filter ListFilter) []Issue
- func (s *Snapshot) Ready() []Issue
- func (s *Snapshot) States() []State
- func (s *Snapshot) Untriaged() int
- func (s *Snapshot) Warnings() []Warning
- type SnapshotOptions
- type StartOptions
- type StartOutcome
- type StartResult
- type State
- type Target
- type TextFinding
- type Tracker
- func (t *Tracker) ApplyPlan(ctx context.Context, entries []PlanEntry, opts ApplyOptions) (ApplyResult, error)
- func (t *Tracker) As(actor string) *Tracker
- func (t *Tracker) Backend() Backend
- func (t *Tracker) Block(ctx context.Context, number int, blockers []int, opts BlockOptions) (BlockResult, error)
- func (t *Tracker) CheckCreate(ctx context.Context, req CreateRequest) error
- func (t *Tracker) CheckCreateEpic(ctx context.Context, req CreateEpicRequest) error
- func (t *Tracker) Close(ctx context.Context, number int, opts CloseOptions) (CloseResult, error)
- func (t *Tracker) Create(ctx context.Context, req CreateRequest) (CreateResult, error)
- func (t *Tracker) CreateEpic(ctx context.Context, req CreateEpicRequest) (CreateResult, error)
- func (t *Tracker) Detail(ctx context.Context, number int) (IssueDetail, error)
- func (t *Tracker) Edit(ctx context.Context, req EditRequest) (EditResult, error)
- func (t *Tracker) Get(ctx context.Context, number int) (Issue, error)
- func (t *Tracker) Identity() string
- func (t *Tracker) Init(ctx context.Context) (InitResult, error)
- func (t *Tracker) Primer(ctx context.Context) (PrimerResult, error)
- func (t *Tracker) RateLimit() (RateLimit, bool)
- func (t *Tracker) Release(ctx context.Context, number int, opts ReleaseOptions) error
- func (t *Tracker) Reopen(ctx context.Context, number int, opts ReopenOptions) (ReopenResult, error)
- func (t *Tracker) Repo() string
- func (t *Tracker) Search(ctx context.Context, req SearchRequest) (SearchResult, error)
- func (t *Tracker) Snapshot(ctx context.Context, opts SnapshotOptions) (*Snapshot, error)
- func (t *Tracker) Start(ctx context.Context, number int, opts StartOptions) (StartResult, error)
- func (t *Tracker) Triage(ctx context.Context, req TriageRequest) (TriageResult, error)
- func (t *Tracker) Unblock(ctx context.Context, number int, blockers []int, opts BlockOptions) (UnblockResult, error)
- type TriageRequest
- type TriageResult
- type UnblockResult
- type UntriagedError
- type UnverifiableCycleError
- type Warning
- type WarningKind
- type Writer
Examples ¶
Constants ¶
const ( TextFindingTitle = "title" TextFindingBody = "body" TextFindingComment = "comment" )
Sources a TextFinding can name.
const CheckpointVersion = 1
CheckpointVersion is the current resume-state schema. It exists so a state file this build cannot safely interpret is named as such instead of being reported as corrupt: version 0 is any file written before checkpoints carried a repository and source binding (#81).
const PlanTypeEpic = "epic"
PlanTypeEpic is the plan-only type marking a parent issue: no type label, the epic label, the cosmetic Epic title prefix, and (usually) other entries pointing at it.
Variables ¶
This section is empty.
Functions ¶
func EdgeKey ¶
EdgeKey identifies a wired edge by kind and resolved endpoints, so the record survives a plan whose local ids or line numbers moved.
func FileDigest ¶
FileDigest computes the sha256 digest a checkpoint binds to: a plan's or a snapshot's exact bytes.
func NormalizeAreas ¶
NormalizeAreas returns area names trimmed of surrounding whitespace and de-duplicated, or an *InvalidInputError naming the first rule broken. A name blank after trimming is refused — GitHub rejects a label with no visible name, and a local store would keep one that renders as `( )` and breaks a later `migrate local`. A name is also refused when it is longer than 50 characters, contains a comma, or collides with a priority, type, in-progress or epic label: the text renderer joins areas with commas, and convention labels would change priority, type or claim.
The CLI's area flags split on commas before calling this, so the comma rule guards the callers that hand over a name verbatim — `apply` plans and direct library use — while `--area x,y` stays two areas.
func PlanBody ¶
PlanBody is the body ApplyPlan creates for an entry before the provenance marker: the entry's body, or its composed sections, plus the discovered-from link when it has one. It goes through the same composition a direct caller uses, so a plan and the create command cannot drift apart.
func PlanBodyWithProvenance ¶
PlanBodyWithProvenance is the body actually written: PlanBody plus the marker binding the issue to this entry and this plan digest, which is what lets a later run tell an issue it created from one a checkpoint merely points at.
func PlanTitle ¶
PlanTitle is the title ApplyPlan creates for an entry: epic entries carry the cosmetic prefix exactly once.
func SaveCheckpointFile ¶
func SaveCheckpointFile(path string, state *CheckpointState) error
SaveCheckpointFile persists a checkpoint after every write. It is written to a temp name and renamed over the checkpoint: it is rewritten after every create, edge and comment, and a torn file would be refused as corrupt with only a duplicating restart on offer.
func ValidateAreaLabel ¶
ValidateAreaLabel refuses an area that names a convention label, which would otherwise change priority or type, or manufacture a claim. It checks the name only, without NormalizeAreas's trim, length or comma rules, so a removal can still name an oversized area an older tracker stored.
func ValidatePlan ¶
ValidatePlan checks typed plan entries the way Parse checks a JSONL file: every entry's own fields, then local-id resolution, dangling references and dependency or parent cycles. References may point forward — creation happens before wiring — but every local reference must resolve. Errors name the source line when the entry carries one, its position otherwise.
One area rule is not checked here: a plan built before `idea` was a type may carry that label as an area on an entry a checkpoint already created, and a resume has to accept it. ApplyPlan enforces the idea reservation on every pending entry — which is every entry of a fresh plan — before its first write (see validatePendingPlanFields).
The idea relationship rule is deferred for the same reason: whether a parent edge is still pending depends on the checkpoint, so ApplyPlan judges both endpoints by their normalized types and leaves an edge it already recorded as wired alone (see validatePendingPlanParents).
A rejection is an *InvalidInputError whose Reason names the entry and the rule, so a caller branches on the type rather than the text.
func ValidateSections ¶
ValidateSections enforces the issue body's section rules: Problem and Goal are one wording pair, Fix and Approach another, and an Open questions or Done when item cannot be blank. A rejection is an *InvalidInputError naming the offending field.
func ValidateTitle ¶
ValidateTitle enforces the write path's title rules — non-blank, a single line, at most 256 characters counted in runes, including any cosmetic Epic prefix. Every writer shares it, so a library caller cannot store a title the CLI would refuse. A rejection is an *InvalidInputError whose Field is "title".
Types ¶
type AppliedEntry ¶
type AppliedEntry struct {
Key string `json:"key"`
Issue int `json:"issue"`
// Created is false when the checkpoint already mapped the entry, so the
// run only reported it.
Created bool `json:"created"`
}
AppliedEntry is one entry's outcome in a real run.
type ApplyOptions ¶
type ApplyOptions struct {
DryRun bool
Throttle time.Duration
// Checkpoint is where progress is recorded and resumed from. Nil means a
// fresh in-memory checkpoint.
Checkpoint Checkpoint
// Digest identifies the plan source in provenance markers and checkpoint
// records. Empty means the checkpoint's own digest, or a digest computed
// from the entries when it has none; a caller that parses a file passes
// that file's digest so a checkpoint on disk agrees with the markers its
// issues carry.
Digest string
}
ApplyOptions configures plan application. The zero value applies the plan without a delay between writes and with an in-memory checkpoint, so nothing resumes across calls; DryRun validates without writing.
type ApplyResult ¶
type ApplyResult struct {
// DryRun reports which mode ran.
DryRun bool `json:"dryRun"`
// Created, Wired and Unwired count the run's writes. Unwired is the
// number of edges that did not land; they are listed in Warnings and a
// rerun retries them.
Created int `json:"created"`
Wired int `json:"wired"`
Unwired int `json:"unwired"`
// Warnings names the edges that did not land and the checkpoints that
// could not be saved.
Warnings []string `json:"warnings"`
// Mapping is every entry key → issue number after the run.
Mapping map[string]int `json:"mapping"`
// Applied is each entry's outcome in plan order, for progress rendering.
Applied []AppliedEntry `json:"applied"`
// WouldCreate and AlreadyCreated are the dry run's plan and the entries
// its checkpoint already accounts for. They are empty otherwise.
WouldCreate []PlannedEntry `json:"wouldCreate"`
AlreadyCreated map[string]int `json:"alreadyCreated"`
}
ApplyResult is what ApplyPlan did, or — under DryRun — what it would do.
func (ApplyResult) MarshalJSON ¶
func (r ApplyResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the run's collections as empty arrays and objects rather than null, so a consumer never has to distinguish an absent collection from an empty one.
type AuthError ¶
type AuthError struct{ Err error }
AuthError reports an authentication failure, retaining the backend cause.
type BlockOptions ¶
type BlockOptions struct {
AllowClosed bool
}
BlockOptions configures Block and Unblock. The zero value refuses a closed target; AllowClosed permits editing it. Cycle checks still apply.
type BlockResult ¶
BlockResult reports what Block changed. Added and Existing are the requested blockers in request order; an empty Added means the call was a no-op.
func (BlockResult) MarshalJSON ¶
func (r BlockResult) MarshalJSON() ([]byte, error)
MarshalJSON renders both blocker sets as arrays even when empty.
type BlockedError ¶
BlockedError reports the open blockers preventing a claim.
func (*BlockedError) Error ¶
func (e *BlockedError) Error() string
type Body ¶
type Body struct {
// Sections compose the issue template: Where, Problem or Goal, Fix or
// Approach, optional Open questions, and Done when. Wording pairs are
// exclusive, and Open questions and Done when items must be non-blank.
Sections Sections
// PRSections compose the pull-request template: What, Why, Testing and
// Risk.
PRSections PRSections
// Trailers are the closing references a pull request carries. With a
// pull-request body they are enforced and any missing ones appended; with
// issue sections they are refused.
Trailers PRTrailers
// Text is a body the caller already has — a file it read, an editor's
// output, or an existing body being revalidated. It is used verbatim:
// findings report what to improve and never rewrite it.
Text string
// DiscoveredFrom appends the link create's --discovered-from flag adds.
// It applies to issue bodies only.
DiscoveredFrom int
}
Body is one body to compose: structured sections for an issue, structured sections for a pull request, or text the caller already has — at most one source. A zero Body composes an empty body, which is what create does when no body flags are given.
Composition is pure: the caller reads files and launches editors, and hands the bytes over as Text. Nothing here touches a store or the network.
type BodyCheck ¶
type BodyCheck struct {
Findings []Finding `json:"findings"`
}
BodyCheck is the result of checking body text a caller already has. A check never rewrites the text: the caller keeps its bytes, and the findings say what to improve.
func CheckBody ¶
CheckBody reports advisory findings for body text the caller already has. It never rewrites the text and never fails on a finding.
func (BodyCheck) MarshalJSON ¶
MarshalJSON renders the findings as an array even when empty.
type Checkpoint ¶
type Checkpoint interface {
// Created reports the issue number already recorded for an entry key.
Created(key string) (int, bool)
// CreatedEntries returns every recorded mapping, sorted by key, so a
// validation pass fails on the same entry every time.
CreatedEntries() []CheckpointEntry
// RecordCreated records that key was created as number and persists the
// checkpoint. A failure means the issue exists but the resume record does
// not, which ApplyPlan reports without undoing the create.
RecordCreated(key string, number int) error
// Wired reports whether an edge was already recorded as wired.
Wired(kind EdgeKind, from, to int) bool
// RecordWired records a wired edge and persists the checkpoint. A failure
// means the edge landed but a rerun would attempt it again.
RecordWired(kind EdgeKind, from, to int) error
// Digest is the source identity the checkpoint is bound to, or empty for
// a checkpoint with no durable source. ApplyPlan uses it when the caller
// passes no digest, so a file checkpoint's markers agree with its binding.
Digest() string
}
Checkpoint is where ApplyPlan records progress and resumes from: the issue each entry became, and the dependency edges already wired. ApplyPlan reads it before writing anything and records every write through it.
The zero ApplyOptions uses a fresh MemoryCheckpoint, so nothing resumes unless the caller passes the same one back. FileCheckpoint persists to the state file `hew apply` uses and survives the process.
type CheckpointEntry ¶
CheckpointEntry is one recorded entry-key → issue-number mapping.
type CheckpointState ¶
type CheckpointState struct {
Version int `json:"version"`
Repo string `json:"repo"`
Digest string `json:"digest"`
Mapping map[string]int `json:"mapping"`
Edges map[string]bool `json:"edges,omitempty"`
}
CheckpointState is the on-disk shape of a batch checkpoint shared by `hew apply` and `hew migrate`: which source key became which issue, which dependency edges were already wired, and which named steps (a posted migration comment) were already taken. FileCheckpoint reads and writes it; the CLI's migrate path uses the same struct for the same files.
func LoadCheckpointFile ¶
func LoadCheckpointFile(path string, repo string, digest string, sourceNoun string) (*CheckpointState, error)
LoadCheckpointFile reads a checkpoint file. A missing file is a fresh start; a corrupt, unbound, or mismatched one aborts — treating it as empty would duplicate every already-created issue, and using an unbound or mismatched one could mutate unrelated issues (#81).
type ClaimedError ¶
ClaimedError reports an existing claim. Assignees may be empty for a label-only claim. Actor is the effective acting identity; on GitHub it is the authenticated login. ByActor means that identity owns the claim.
Err is set when the acting identity could not be read while answering: Actor is then empty and ByActor false, so a caller can tell "someone else holds it" from "cannot say who holds it" instead of reading the empty fields as a positive answer.
func (*ClaimedError) Error ¶
func (e *ClaimedError) Error() string
func (*ClaimedError) Unwrap ¶
func (e *ClaimedError) Unwrap() error
Unwrap exposes Err, so an authentication failure behind an unanswerable "whose claim is it" is still matchable as AuthError.
type CloseOptions ¶
type CloseOptions struct {
Reason string
Completed bool
DuplicateOf int
// Force closes an epic that still has open sub-issues.
Force bool
}
CloseOptions configures issue closure. Reason is required, except with DuplicateOf, which supplies one; the zero values of Completed and DuplicateOf select a not-planned closure.
type CloseResult ¶
type CloseResult struct {
StateReason string `json:"stateReason"`
}
CloseResult reports a completed closure. StateReason is the backend's close reason: COMPLETED, NOT_PLANNED or DUPLICATE.
type ClosedError ¶
ClosedError reports an operation refused on a closed target. Reason is the backend's close reason, when available.
func (*ClosedError) Error ¶
func (e *ClosedError) Error() string
type Comment ¶
type Comment struct {
Author string `json:"author"`
CreatedAt time.Time `json:"createdAt"`
Body string `json:"body"`
}
Comment is one recent issue comment.
type ComposedBody ¶
ComposedBody is the result of composing a body. Body is the text to publish; Findings are advisory and never fail the call or change the text.
func ComposeBody ¶
func ComposeBody(b Body) (ComposedBody, error)
ComposeBody renders a body from its structured sections or supplied text, enforcing the write path's rules first. Conflicting sources, a mixed issue/pull-request body, and a supplied pull-request body that closes a different set of issues are *InvalidInputError; markup findings ride on the result and never refuse it.
func (ComposedBody) MarshalJSON ¶
func (b ComposedBody) MarshalJSON() ([]byte, error)
MarshalJSON renders the findings as an array even when empty.
type Config ¶
type Config struct {
// Worktree is the directory the caller works from. Open answers every
// path and worktree question from it and never reads the process working
// directory.
Worktree string
// Backend optionally pins the backend. Empty means use the backend Detect
// finds. BackendGitHub opens GitHub even when the worktree has a local
// tracker (the CLI's --repo); BackendLocal refuses to fall back to GitHub
// when the tracker is gone.
Backend Backend
// Repo is the GitHub repository as owner/name. Empty means detect it from
// a github.com origin remote. Ignored by a local tracker.
Repo string
// Actor is the claimant identity. Empty means the backend's default: the
// OS login qualified by the worktree on a local tracker, the authenticated
// login on GitHub. Ignored on GitHub, where every claim is the
// authenticated login; read Identity to see the effective claimant.
// As(actor) changes it after Open on a local tracker.
Actor string
// Notice receives lock-wait and migration notices. Nil discards them; the
// tracker never writes to stderr.
Notice io.Writer
// Transport carries every GitHub API request, overriding the HTTP transport
// the GitHub client sends through. Nil uses go-gh's default — the process's
// network and gh's stored credentials; an in-process consumer's tests supply
// an httptest server's transport to answer GitHub without either. A local
// tracker ignores it.
Transport http.RoundTripper
}
Config configures Open.
type CreateEpicRequest ¶
type CreateEpicRequest struct {
Title string
// Children attaches these existing issues as sub-issues. Each must exist
// and have no parent yet.
Children []int
// Body is the epic's body, composed the same way an issue's is.
Body Body
}
CreateEpicRequest is one epic (parent issue) to file with CreateEpic. Title need not carry the cosmetic Epic prefix; CreateEpic adds it if missing.
type CreateRequest ¶
type CreateRequest struct {
Title string
// Type is bug, enhancement, task or idea. Use CreateEpic for a parent
// issue.
Type string
// Priority is P0..P4; empty means P2.
Priority string
Areas []string
// Body is the issue body: structured sections or text the caller already
// has. Create composes and validates it, appending DiscoveredFrom's link.
Body Body
// Parent attaches the new issue as a sub-issue of Parent. A closed parent
// is a valid reference; only a blocker has to be open.
Parent int
// BlockedBy makes the new issue depend on these issues, each of which must
// be open. A new issue has no dependents, so these edges cannot form a
// cycle; Block owns the transitive check for edges between existing issues.
BlockedBy []int
// DiscoveredFrom links the new issue to the issue that surfaced it. A
// body may carry the same number instead of this field.
DiscoveredFrom int
// Assignees claims the new issue for these logins, preserving a source
// claim when a migration files it. A non-empty list adds the in-progress
// label too, so the result is a claim the claim guard recognises rather
// than a bare assignment. An idea refuses assignees: capture never claims
// the issue it files — an investigation claim is a separate, explicit
// start.
Assignees []string
}
CreateRequest is one issue to file with Create: the typed counterpart of the `create` command's inputs, minus the flags and file and editor handling the adapter owns.
A zero Body composes an empty body. Title, Type, Priority, Areas and the Body are validated before anything is written, so a refused request leaves the tracker untouched.
type CreateResult ¶
type CreateResult struct {
Issue Issue `json:"issue"`
Edges []CreatedEdge `json:"edges"`
Findings []Finding `json:"findings"`
}
CreateResult is a creation that finished: the issue as the creation left it, the relationship edges it wrote in attempt order, and the advisory findings for the body it composed.
The Issue reflects the write rather than a re-read: it carries the number, title and labels the backend returned plus the body, assignees and edges the call wrote. Get is the live read when a caller needs the backend's own view.
func (CreateResult) MarshalJSON ¶
func (r CreateResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the edges and findings as arrays even when empty.
type CreateStage ¶
type CreateStage string
CreateStage names the step a creation was in when it stopped partway.
const ( // CreateStageAssignees adds the requested assignees. CreateStageAssignees CreateStage = "assignees" // CreateStageBlockedBy attaches the requested blockers. CreateStageBlockedBy CreateStage = "blocked-by" // CreateStageParent attaches the requested parent. CreateStageParent CreateStage = "parent" // CreateStageChildren attaches an epic's children. CreateStageChildren CreateStage = "children" )
type CreatedEdge ¶
CreatedEdge is one relationship a creation wrote after the issue existed. To is the other issue: the parent, a blocker, or a child.
func (CreatedEdge) String ¶
func (e CreatedEdge) String() string
String renders the edge as "blocked-by #2", the form error messages use.
type CycleError ¶
type CycleError struct{ Cycle []int }
CycleError reports a dependency cycle, including self-blocks. Cycle is the ordered issue-number path, ending with its first member again.
func (*CycleError) Error ¶
func (e *CycleError) Error() string
type DiscoveryIntentError ¶ added in v0.20.0
type DiscoveryIntentError struct{ Issue int }
DiscoveryIntentError reports a claim on an idea without explicit discovery intent. An idea captures a possible improvement; claiming it is a decision to investigate, which the caller has to declare (StartOptions.ForDiscovery, the CLI's --for-discovery, the REST request's forDiscovery) rather than stumble into from an ordinary work queue.
func (*DiscoveryIntentError) Error ¶ added in v0.20.0
func (e *DiscoveryIntentError) Error() string
type Edge ¶
Edge is one dependency the entry declares, still unresolved: the caller maps the reference to an issue number.
type EdgeKind ¶
type EdgeKind string
EdgeKind names the two dependency edges an entry can declare. The strings are the words the wiring step reports edges by, and — once resolved to issue numbers — part of the checkpoint key that keeps a resume from re-attempting an edge it already wired.
type EditRequest ¶
type EditRequest struct {
// Issue is the issue to edit.
Issue int
// Priority is P0..P4; the old priority label is swapped, never stacked.
Priority *string
// Type is bug|enhancement|task|idea; the old type label is swapped, never
// stacked.
Type *string
// Title replaces the issue's title.
Title *string
// Body replaces the whole issue body. An empty body is refused: an edit
// does not blank an issue.
Body *string
// Outcome appends a Markdown note to an idea's Outcome section. It
// cannot be combined with Body.
Outcome *string
// AddAreas and RemoveAreas change the issue's area labels. Added names
// are trimmed and de-duplicated; neither list may name a convention
// label.
AddAreas []string
RemoveAreas []string
// Parent moves the issue under that parent, replacing an existing one.
// NoParent removes the current parent. The two are mutually exclusive.
Parent *int
NoParent bool
// AllowClosed permits editing an issue that is already closed.
AllowClosed bool
}
EditRequest names the changes to make to one issue. Every field is optional: a nil pointer, an empty slice or a false flag leaves that part of the issue alone. The pointer fields carry presence rather than value, so an explicitly empty title, body, outcome, priority or type is refused instead of being read as an omitted field.
type EditResult ¶
EditResult reports what Edit carried out. Applied names the request fields that landed, in the order they were applied — a field whose requested value already held is named too, because the edit's intent covered it. ParentNoop reports a NoParent request on an issue that had no parent: the requested state already held and nothing was written for it.
func (EditResult) MarshalJSON ¶
func (r EditResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the applied field names as an array even when empty.
type EpicError ¶
type EpicError struct{ Issue int }
EpicError reports a claim on an epic. Epics are containers: their children are the workable issues.
type ExistingRef ¶
type ExistingRef struct {
// Line is the 1-based line of the entry carrying the reference.
Line int
// Field is the plan field it came from: parent, blocked-by or
// discovered-from.
Field string
Number int
}
ExistingRef is a numeric reference in a plan entry: an issue that must already exist, which validation cannot verify.
type FileCheckpoint ¶
type FileCheckpoint struct {
// contains filtered or unexported fields
}
FileCheckpoint is a Checkpoint persisted in the state file the CLI uses. OpenFileCheckpoint verifies the file belongs to repo and digest before any write, so a checkpoint from another repository or source is refused.
func OpenFileCheckpoint ¶
func OpenFileCheckpoint(path string, repo string, digest string, sourceNoun string) (*FileCheckpoint, error)
OpenFileCheckpoint opens or creates the checkpoint at path, bound to repo and digest. A missing file is a fresh run; an existing one must agree with both bindings, or it is refused rather than treated as empty.
func (*FileCheckpoint) CreatedEntries ¶
func (c *FileCheckpoint) CreatedEntries() []CheckpointEntry
func (*FileCheckpoint) Digest ¶
func (c *FileCheckpoint) Digest() string
Digest is the digest the file was opened with and every marker it verifies is bound to.
func (*FileCheckpoint) RecordCreated ¶
func (c *FileCheckpoint) RecordCreated(key string, number int) error
func (*FileCheckpoint) RecordStep ¶
func (c *FileCheckpoint) RecordStep(key string) error
RecordStep records a named step and persists the checkpoint. The key shares the record space with wired edges but is not one: callers pick a namespace that cannot collide with EdgeKey's "kind:from->to" form.
func (*FileCheckpoint) RecordWired ¶
func (c *FileCheckpoint) RecordWired(kind EdgeKind, from, to int) error
func (*FileCheckpoint) Recorded ¶
func (c *FileCheckpoint) Recorded(key string) bool
Recorded reports whether a named step was already recorded. Named steps are the migration engine's non-edge writes, such as a posted comment.
type Finding ¶
type Finding struct {
Kind FindingKind `json:"kind"`
// Tokens are the offending code-shaped tokens, de-duplicated and in order
// of first appearance, for FindingUnmarkedCode.
Tokens []string `json:"tokens"`
}
Finding is one piece of advice about body text.
func (Finding) MarshalJSON ¶
MarshalJSON renders the offending tokens as an array even when empty.
type FindingKind ¶
type FindingKind string
FindingKind identifies an advisory finding about body text, so a caller can filter by cause and render its own sentence.
const ( // FindingUnmarkedCode reports prose that looks like code and should be in // a backtick span. It is advice: the text is never rewritten. FindingUnmarkedCode FindingKind = "unmarked-code" )
type InitConfig ¶
type InitConfig struct {
// Worktree is the directory the caller works from. Local initialization
// creates the tracker at the main checkout containing it, so every linked
// worktree of the repository shares the one tracker.
Worktree string
// Backend optionally pins the backend, with Config.Backend's meaning:
// empty detects it from the worktree, BackendLocal creates or keeps the
// local tracker, and BackendGitHub bootstraps GitHub even when the repo
// tracks issues locally.
Backend Backend
// Repo is the GitHub repository as owner/name. Empty means detect it from
// the worktree's origin remote. Ignored by a local tracker.
Repo string
// Transport overrides the HTTP transport the GitHub client sends through,
// so a caller's tests need neither the network nor a gh process. Nil uses
// go-gh's default. Ignored by a local tracker.
Transport http.RoundTripper
}
InitConfig configures Init. Like Config it names the worktree and the target explicitly: initialization never reads the process working directory or its environment.
type InitResult ¶
type InitResult struct {
// Backend is the backend initialization ran against.
Backend Backend `json:"backend"`
// Path is the local tracker directory (the .hew directory). Empty on
// GitHub, which keeps no state in the checkout.
Path string `json:"path"`
// CreatedLabels names the convention labels the run created, in the
// conventions' order. It is non-nil and empty when none were missing, and
// always empty on the local backend, which carries its labels in the
// tracker itself.
CreatedLabels []string `json:"createdLabels"`
// IssuesRecreated reports a local tracker whose issues.jsonl was missing
// beside an existing config. The file is empty now and the tracker has a
// new id, so resume checkpoints bound to the old tracker start over.
IssuesRecreated bool `json:"issuesRecreated"`
// Notices are the warnings the run would have printed, in the order they
// happened. They are data because the library never writes to stdout or
// stderr; a caller renders or discards them.
Notices []string `json:"notices"`
}
InitResult reports what Init found and changed, so a caller can render it without asking the filesystem or the API again.
func Init ¶
func Init(ctx context.Context, cfg InitConfig) (InitResult, error)
Init bootstraps the tracker for the checkout containing cfg.Worktree, or for cfg.Repo, without going through the hew executable: on the local backend it creates .hew at the main checkout, and on GitHub it creates the convention labels the write path assumes.
It is idempotent. A local tracker keeps its issues, its configuration and its id across runs, and recreating a lost issues.jsonl is reported rather than hidden; a GitHub repository that already carries every convention label is left untouched.
A repository whose tracker belongs to another backend is refused with InitializedElsewhereError instead of being initialized locally, so a migrated repo's archive is never made live again. The other refusals are typed as the contract promises: InvalidInputError names a bad worktree, backend or repository, and an unusable GitHub credential is AuthError. Init never prints to stdout or stderr; the notices it would have printed come back in InitResult.Notices.
func (InitResult) MarshalJSON ¶
func (r InitResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the created labels and notices as arrays even when empty.
type InitializedElsewhereError ¶
InitializedElsewhereError reports a repository whose tracker belongs to another backend, so initializing it locally would create a second tracker no command would read. Path is the existing tracker's directory; Backend is the backend its config names. Moving that tracker is a migration, not an initialization.
func (*InitializedElsewhereError) Error ¶
func (e *InitializedElsewhereError) Error() string
type InvalidInputError ¶
InvalidInputError reports an invalid argument or plan entry field. Field names a library input, rather than a CLI flag.
func (*InvalidInputError) Error ¶
func (e *InvalidInputError) Error() string
type Issue ¶
type Issue struct {
Number int `json:"number"`
Title string `json:"title"`
State string `json:"state"`
Priority *string `json:"priority"`
Type *string `json:"type"`
Areas []string `json:"areas"`
Assignees []string `json:"assignees"`
Epic bool `json:"epic"`
InProgress bool `json:"inProgress"`
Untriaged bool `json:"untriaged"`
Parent *int `json:"parent"`
BlockedBy []int `json:"blockedBy"`
BlockedByTotal int `json:"blockedByTotal"`
OpenBlockers []int `json:"openBlockers"`
SubIssues []int `json:"subIssues"`
SubIssuesTotal int `json:"subIssuesTotal"`
SubIssuesCompleted int `json:"subIssuesCompleted"`
CreatedAt time.Time `json:"createdAt"`
// Next is set only for an epic's detail view (show --json): the next
// workable child's number. Absent, not null, for non-epics and when the
// sequence is dry — consumers key on the epic field for the difference.
Next *int `json:"next,omitempty"`
// Body is a pointer so presence tracks the mode (show, list --bodies, a
// snapshot read) rather than emptiness: modes that carry it emit the
// field on every issue, empty or not, and plain list lines stay
// byte-for-byte body-free.
Body *string `json:"body,omitempty"`
Comments []Comment `json:"comments,omitempty"`
CommentsTotal int `json:"commentsTotal,omitempty"`
// contains filtered or unexported fields
}
Issue is a tracker issue in the CLI's stable flat JSON schema: dependencies are number arrays and backend-specific shapes stay hidden.
A library read also carries what that schema cannot: raw labels, reference states, the parent's state and title, and the close reason. A value rebuilt by unmarshaling the schema carries the exported fields only, so the accessors below report that extra data as absent; use a Reader or Tracker read when it matters.
Epic is the hierarchy classification rather than the type: sub-issues or the epic marker outrank idea, so an issue a repository attached outside hew still reads as an epic with its relationships visible.
func (Issue) BlockedByRefs ¶
BlockedByRefs returns every blocker with its state, including closed ones — the flat schema's BlockedBy carries only numbers and OpenBlockers only the open ones.
func (Issue) HasLabel ¶
HasLabel reports whether the issue carries the label, case-insensitively — the same match the CLI applies to `--label`, so a library caller and a command agree on membership.
func (Issue) Labels ¶
Labels returns the issue's raw labels, in backend order. The flat schema derives priority, type and areas from them; a caller that wants the whole vocabulary reads them here instead.
func (Issue) ParentRef ¶
ParentRef returns the parent with its state. The flat schema's Parent carries only the number; a value unmarshaled from it has no state.
func (Issue) ParentTitle ¶
ParentTitle is the parent issue's title, when the issue has a parent.
func (Issue) StateReason ¶
StateReason is the backend's close reason when it has one (for example "completed" or "not planned"); empty while the issue is open.
func (Issue) SubIssueRefs ¶
SubIssueRefs returns the fetched sub-issues with their states. SubIssuesTotal may still exceed what was fetched when the connection was capped.
type IssueDetail ¶
type IssueDetail struct {
// Issue is the subject, with body, comments and close reason.
Issue Issue `json:"issue"`
// Children is an epic's full child set, oldest first, including closed
// and untriaged children: naming the epic is the explicit retrieval path.
// It is a list of rows, so it carries no bodies; it is nil for a
// non-epic.
Children []Issue `json:"children"`
// Next is the epic's next workable child, nil for a non-epic or when the
// sequence is dry.
Next *int `json:"next"`
// TextFindings annotates the title, body and displayed comments. Comments
// are scanned because Detail is a live single-issue read and carries them.
TextFindings []TextFinding `json:"textFindings"`
// Warnings is the snapshot's completeness notices for an epic read; nil
// for a non-epic, which fetches no snapshot.
Warnings []Warning `json:"warnings"`
}
IssueDetail is one issue's full view: the issue itself, an epic's parent-backlinked children and next workable child, the advisory findings for its text, and the snapshot warnings that bear on the view.
func (IssueDetail) MarshalJSON ¶
func (d IssueDetail) MarshalJSON() ([]byte, error)
MarshalJSON renders an epic's children, findings and warnings as arrays even when empty; next stays null for a non-epic or a dry sequence.
type ListFilter ¶
type ListFilter struct {
// Label keeps issues carrying the label, compared case-insensitively as
// GitHub and the CLI's --label both do.
Label string
// Type keeps issues whose normalized type matches. It is the type the
// write path would record — bug, enhancement, task or idea — not a label
// spelling, so a literal `idea` label on a task stays a task query. A type
// query excludes epics: an epic is a container, and a type names an
// ordinary issue's classification.
Type string
// Epic keeps issues whose parent is this epic. Zero applies no epic
// filter.
Epic int
// NoEpic keeps issues that belong to no epic: those with no parent that
// are not epics themselves. It cannot be combined with Epic.
NoEpic bool
}
ListFilter narrows a snapshot's list view. The zero value keeps every fetched, triaged issue in list order.
func (ListFilter) Validate ¶ added in v0.20.0
func (f ListFilter) Validate() error
Validate reports whether the filter names a type the tracker recognizes and does not ask for both one epic's children and no epic. An empty Type is valid. The rejection is an *InvalidInputError naming "type" or "noEpic", so the CLI and the daemon spell the same rule in their own words.
type LockTimeoutError ¶
LockTimeoutError reports an expired wait for a local tracker's lock. Err carries the store's own timeout when the boundary translated one, so the message keeps the detail that explains the wait — a running migration, or another hew process — instead of a generic retelling.
func (*LockTimeoutError) Error ¶
func (e *LockTimeoutError) Error() string
func (*LockTimeoutError) Unwrap ¶
func (e *LockTimeoutError) Unwrap() error
type MemoryCheckpoint ¶
type MemoryCheckpoint struct {
// contains filtered or unexported fields
}
MemoryCheckpoint is a Checkpoint that keeps its records in memory. The zero value is ready to use; nothing survives the process.
func NewMemoryCheckpoint ¶
func NewMemoryCheckpoint() *MemoryCheckpoint
NewMemoryCheckpoint returns an empty in-memory checkpoint.
func (*MemoryCheckpoint) CreatedEntries ¶
func (c *MemoryCheckpoint) CreatedEntries() []CheckpointEntry
func (*MemoryCheckpoint) Digest ¶
func (c *MemoryCheckpoint) Digest() string
Digest is always empty: an in-memory checkpoint has no durable source, so ApplyPlan derives one from the entries.
func (*MemoryCheckpoint) RecordCreated ¶
func (c *MemoryCheckpoint) RecordCreated(key string, number int) error
func (*MemoryCheckpoint) RecordStep ¶
func (c *MemoryCheckpoint) RecordStep(key string) error
RecordStep records a named step. The key shares the record space with wired edges but is not one: callers pick a namespace that cannot collide with EdgeKey's "kind:from->to" form.
func (*MemoryCheckpoint) RecordWired ¶
func (c *MemoryCheckpoint) RecordWired(kind EdgeKind, from, to int) error
func (*MemoryCheckpoint) Recorded ¶
func (c *MemoryCheckpoint) Recorded(key string) bool
Recorded reports whether a named step was already recorded. Named steps are the migration engine's non-edge writes, such as a posted comment.
type MigratedError ¶
MigratedError reports that a local tracker has moved to a GitHub repo. Repo is the repository the migration record names, empty when that record is unreadable. Err carries the store's own refusal when the boundary translated one, so the message names the tracker directory and the backend that owns it now; Path and Repo stay available for a caller that reports the move itself.
func (*MigratedError) Error ¶
func (e *MigratedError) Error() string
func (*MigratedError) Unwrap ¶
func (e *MigratedError) Unwrap() error
type NotClaimedError ¶
type NotClaimedError struct{ Issue int }
NotClaimedError reports a release of an issue nobody holds.
func (*NotClaimedError) Error ¶
func (e *NotClaimedError) Error() string
type NotFoundError ¶
NotFoundError reports an issue absent from the tracker. Err carries the store's own not-found error when the boundary translated one, so the backend's message — which may name the repository — is what a caller prints.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
type NotOpenError ¶
NotOpenError reports a dependency reference that is not an open issue: closed or absent from the tracker, and either way not something that blocks. Blocker names the reference; Issue names the edge's source.
func (*NotOpenError) Error ¶
func (e *NotOpenError) Error() string
type NotOwnerError ¶
NotOwnerError reports a release the acting identity may not make: the claim is not solely theirs. Assignees is empty for a label-only claim. Actor is the acting identity the claim was compared with.
func (*NotOwnerError) Error ¶
func (e *NotOwnerError) Error() string
type OpenChildrenError ¶
OpenChildrenError reports a close of an epic that still has Open open sub-issues, which would be stranded under a closed parent.
func (*OpenChildrenError) Error ¶
func (e *OpenChildrenError) Error() string
type PRSections ¶
PRSections are the pull-request body fields, mirroring the issue template: What replaces the issue's Fix/Approach, Why its Problem/Goal, Testing is the evidence an issue never carries, and Risk is the merge claim a reviewer weighs.
func (PRSections) Compose ¶
func (s PRSections) Compose(t PRTrailers) string
Compose renders the provided sections in template order, empty sections omitted, followed by the trailers — the same body `hew pr` writes.
func (PRSections) IsZero ¶
func (s PRSections) IsZero() bool
IsZero reports whether no pull-request section was provided.
type PRTrailers ¶
PRTrailers are the tracker links a pull-request body carries: one Fixes line per issue the pull request closes, plus each epic those issues hang off.
func (PRTrailers) Render ¶
func (t PRTrailers) Render() string
Render returns the trailer block, empty when there is nothing to link.
type ParentedError ¶
ParentedError reports an epic child that already belongs to another epic. AddSubIssue refuses the attach, and catching it before the epic is filed is what keeps a predictable failure from leaving a childless epic behind.
func (*ParentedError) Error ¶
func (e *ParentedError) Error() string
type PartialCloseError ¶
PartialCloseError reports a close whose reason comment posted but whose state change failed. A retry will comment again. Err is the backend cause.
func (*PartialCloseError) Error ¶
func (e *PartialCloseError) Error() string
func (*PartialCloseError) Unwrap ¶
func (e *PartialCloseError) Unwrap() error
type PartialCreateError ¶
type PartialCreateError struct {
Issue Issue
Stage CreateStage
Applied []CreatedEdge
Failed CreatedEdge
NotAttempted []CreatedEdge
Err error
}
PartialCreateError reports a creation that filed its issue but stopped before every follow-up write landed. Issue is the created issue and always exists; Stage names the step that failed.
Applied lists the relationship edges written before the failure, in attempt order. Failed is the edge whose write failed, and NotAttempted the edges after it that never ran; both are meaningful only for the edge stages (blocked-by, parent, children). An assignee failure has no edge to name, so Failed stays zero and Err identifies the assignee.
Err is the backend cause, retained for errors.Is and errors.As.
func (*PartialCreateError) Error ¶
func (e *PartialCreateError) Error() string
func (*PartialCreateError) Unwrap ¶
func (e *PartialCreateError) Unwrap() error
type PartialEditError ¶
PartialEditError reports an edit that stopped partway: the fields named in Applied were written, Failed is the field whose write failed, and the edits after it never ran. Err is the backend cause.
func (*PartialEditError) Error ¶
func (e *PartialEditError) Error() string
func (*PartialEditError) Unwrap ¶
func (e *PartialEditError) Unwrap() error
type PartialReleaseError ¶
PartialReleaseError reports a release that failed after it began clearing the claim, so the claim may be partly cleared. Err is the backend cause.
func (*PartialReleaseError) Error ¶
func (e *PartialReleaseError) Error() string
func (*PartialReleaseError) Unwrap ¶
func (e *PartialReleaseError) Unwrap() error
type PartialReopenError ¶
type PartialReopenError struct {
Issue int
Stage ReopenStage
Err error
}
PartialReopenError reports a reopen that stopped partway. Stage says what survived: the reason comment with the issue still closed, or an open issue that is still claimed. Err is the backend cause.
func (*PartialReopenError) Error ¶
func (e *PartialReopenError) Error() string
func (*PartialReopenError) Unwrap ¶
func (e *PartialReopenError) Unwrap() error
type PartialWriteError ¶
PartialWriteError reports a run of dependency-edge writes that stopped partway: the edges in Landed were written, Failed is the edge whose write failed, and NotAttempted never ran. Err is the backend cause, retained for errors.Is and errors.As.
func (*PartialWriteError) Error ¶
func (e *PartialWriteError) Error() string
func (*PartialWriteError) Unwrap ¶
func (e *PartialWriteError) Unwrap() error
type PlanEntry ¶
type PlanEntry struct {
// ID names the entry so other entries can reference it before issue
// numbers exist. Empty means the entry is keyed by its Line.
ID string
Title string
Type string // bug|enhancement|task|idea, or PlanTypeEpic
Priority string // P0..P4; empty means P2
Areas []string
// Body is the issue body. It is mutually exclusive with Sections.
Body string
Sections Sections
Parent *PlanRef
BlockedBy []PlanRef
// DiscoveredFrom links the created issue to the issue that surfaced it.
DiscoveredFrom int
// Line is the entry's 1-based source line when the plan came from a file.
// ApplyPlan uses the entry's position when it is zero, so id-less entries
// built in code still get distinct keys.
Line int
}
PlanEntry is one issue ApplyPlan creates: the typed counterpart of a JSONL plan line, for callers that build plans in code. A zero Priority means P2.
func (PlanEntry) Edges ¶
Edges returns the entry's dependency edges in wiring order — parent first, then blockers. Both are the same operation apart from the API call they make, so stating them as one list lets the wiring step treat them alike: resolve, skip if already wired, warn on failure.
func (PlanEntry) ExistingRefs ¶
func (e PlanEntry) ExistingRefs() []ExistingRef
ExistingRefs returns the entry's references to issues outside the plan, in field order: parent, blockers, then discovered-from. Local ids are left out — validation already proved they match an entry — so what remains is exactly what ApplyPlan has to look up before writing anything, since a number that names no issue is only discovered by the store.
type PlanRef ¶
PlanRef points at another issue: a plan entry by local id, or an existing issue by number. Exactly one field is set.
type PlannedEntry ¶
type PlannedEntry struct {
Key string `json:"key"`
Priority string `json:"priority"`
Type string `json:"type"`
Title string `json:"title"`
Areas []string `json:"areas"`
Parent *string `json:"parent"`
BlockedBy []string `json:"blockedBy"`
}
PlannedEntry is one issue a dry run would create, in the flat shape the CLI's plan output uses. Every field is present on every entry; Parent is null for an entry without one.
func (PlannedEntry) MarshalJSON ¶
func (p PlannedEntry) MarshalJSON() ([]byte, error)
MarshalJSON renders the planned entry's areas and blockers as arrays even when empty; the dry-run plan is the one result the CLI emits verbatim.
type PrimerResult ¶
type PrimerResult struct {
// Ready is every ready issue, priority-sorted; ideas are never in it, so
// the section offers implementation work only. ReadyTotal is its uncapped
// length.
Ready []Issue `json:"ready"`
ReadyTotal int `json:"readyTotal"`
// OpenTotal is the number of open issues the fetch returned, which is the
// denominator the primer reports.
OpenTotal int `json:"openTotal"`
// InProgress is every open, triaged issue carrying the in-progress label,
// priority-sorted; InProgressTotal is its length.
InProgress []Issue `json:"inProgress"`
InProgressTotal int `json:"inProgressTotal"`
// Epics is every open epic, priority-sorted; EpicsTotal is its length.
Epics []Issue `json:"epics"`
EpicsTotal int `json:"epicsTotal"`
// Untriaged counts open untriaged issues. Their titles and bodies are not
// in any section: Triage is the deliberate API that returns them.
Untriaged int `json:"untriaged"`
// Warnings is every contradiction and completeness notice the live state
// carries — multiple labels, an in-progress epic, a dependency cycle, and
// capped connections — in deterministic order.
Warnings []Warning `json:"warnings"`
// Conventions is the backend's static primer text: the GitHub variant with
// the pull-request workflow, or the local variant that completes with
// close --completed.
Conventions string `json:"conventions"`
}
PrimerResult is the live state a session-start primer renders: the ready, in-progress and epic sections with their uncapped totals, the untriaged count, every contradiction or completeness warning, and the backend's static convention text. Section caps, layout and the hook wrapper stay with the renderer; this value is the policy.
func (PrimerResult) MarshalJSON ¶
func (p PrimerResult) MarshalJSON() ([]byte, error)
MarshalJSON renders every section and the warnings as arrays even when empty.
type RateLimit ¶
type RateLimit struct {
Cost int `json:"cost"`
Remaining int `json:"remaining"`
ResetAt time.Time `json:"resetAt"`
}
RateLimit is the GitHub client's last observed API budget: the cost of the query that reported it, the calls remaining, and when the window resets. A consumer uses it to pace a long run without asking the API a second time. The local backend never reports one, so Known is false there.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader answers read queries over an already-open store. It is the read half of a Tracker, kept separate so no Tracker exists without the backend and actor its write operations need: hew's own CLI resolves the backend and opens the store once for every command, then wraps that store rather than opening a second one. A consumer outside this module cannot name gh.IssueStore and uses the read methods on the Tracker Open returns.
func Wrap ¶
func Wrap(store gh.IssueStore) *Reader
Wrap makes a Reader from an already-open store: the seam hew's own CLI uses for reads. External callers use Open.
func (*Reader) Snapshot ¶
Snapshot fetches the tracker's issues in the requested states, once. The zero SnapshotOptions fetches open issues only. Warnings report dependency cycles and capped blocker or sub-issue connections — the conditions that make a query's answer incomplete rather than merely empty.
type ReleaseOptions ¶
type ReleaseOptions struct {
Force bool
}
ReleaseOptions configures claim release. The zero value requires the issue to be claimed solely by the acting identity.
type ReopenOptions ¶
type ReopenOptions struct {
Reason string
}
ReopenOptions configures Reopen. The reason is required: it is the comment that records why closed work is coming back.
type ReopenResult ¶
type ReopenResult struct {
Reopened bool `json:"reopened"`
ReleasedLabel bool `json:"releasedLabel"`
ReleasedAssignees []string `json:"releasedAssignees"`
}
ReopenResult reports what Reopen changed. Reopened is false when the issue was already open: the requested state held, so nothing was written. ReleasedLabel and ReleasedAssignees name the stale claim the reopen cleared — the in-progress label and the assignees that carried it. Either half can be empty when the claim had only one.
func (ReopenResult) MarshalJSON ¶
func (r ReopenResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the released assignees as an array even when empty.
type ReopenStage ¶
type ReopenStage string
ReopenStage names the step a failed Reopen stopped at.
const ( // ReopenStageComment is a reopen whose reason comment posted but whose // state change did not land. A retry comments again. ReopenStageComment ReopenStage = "comment" // ReopenStageClaim is a reopen whose issue is open but whose stale claim // could not be cleared. A retry is a no-op reopen that will not clear it; // the claim needs a forced release. ReopenStageClaim ReopenStage = "claim" )
type SearchRequest ¶
type SearchRequest struct {
// Terms are the backend's search terms, passed through as written after
// trimming. Empty terms are invalid.
Terms string
// States narrows the search to these states before the backend's cap, so
// the cap bounds the matches asked for. Empty means open and closed —
// unlike SnapshotOptions.States, where empty means open only. An unknown
// state is an invalid-input error.
States []State
// Bodies carries each match's body and comments. The zero value omits
// them: dedup reads a title, a number and its labels, and a caller that
// needs the text reads the issue.
Bodies bool
}
SearchRequest is the dedup search before filing discovered work: terms matched by the backend across open and closed issues.
type SearchResult ¶
type SearchResult struct {
Issues []Issue `json:"issues"`
Total int `json:"total"`
Fetched int `json:"fetched"`
}
SearchResult is a search listing: the triaged matches in the backend's relevance order, plus the backend's full match count and how many matches it fetched. Total above Fetched means the result was capped. Issues carries bodies only when SearchRequest.Bodies asked for them.
func (SearchResult) MarshalJSON ¶
func (r SearchResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the matches as an array even when empty.
type Sections ¶
type Sections struct {
Where string
Problem string
Goal string
Fix string
Approach string
// OpenQuestions is the optional discovery section. The json tag omits an
// unset list so adding the field does not change the derived digest of a
// plan whose provenance markers were written before it existed.
OpenQuestions []string `json:"OpenQuestions,omitempty"`
DoneWhen []string
}
Sections is the structured body of a plan entry. ApplyPlan composes it into the issue template; callers that already have a body set PlanEntry.Body instead, never both.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is one fetch of the tracker's issues, with the read-side queries a caller needs answered from it. The queries are pure: they filter and sort what the fetch returned, never call the backend again, and every answer is scoped to the states the fetch covered.
func (*Snapshot) Blocked ¶
Blocked returns open issues with at least one open blocker, sorted by priority. A claimed issue can be blocked too: the queries answer different questions rather than partitioning the tracker.
func (*Snapshot) Children ¶
Children returns an epic's children, oldest first, from parent backlinks over the full fetch — complete even when the epic's own sub-issue connection was capped.
func (*Snapshot) Claimed ¶
Claimed returns open claimed issues — an assignee or the in-progress label — sorted by priority.
func (*Snapshot) Epics ¶
Epics returns the issues that have sub-issues or carry the epic label, sorted by priority. It spans the states the snapshot fetched, so the zero SnapshotOptions yields open epics and a closed fetch adds the finished ones.
func (*Snapshot) Get ¶
Get returns the issue from the snapshot, if the fetched states included it, with its body and comments: a single-issue read keeps the text even when the snapshot's list-shaped reads omit it. It is a lookup, not a fetch: use Reader.Get or Tracker.Get for an issue outside the snapshot.
func (*Snapshot) Issues ¶
Issues returns every fetched issue in list order — ready work first, then claimed, blocked, epics and closed — carrying the body and comments only when SnapshotOptions.Bodies asked for them. Callers that want one question answered use Ready, Blocked, Claimed, Epics or Children instead.
func (*Snapshot) List ¶
func (s *Snapshot) List(filter ListFilter) []Issue
List answers `hew list` from one snapshot: the fetched issues in list order — ready work first, then claimed, blocked, epics and closed — with the filter applied. Untriaged issues are omitted in every state and under every filter; Triage is the deliberate API that returns their text.
func (*Snapshot) Ready ¶
Ready returns open, non-epic, unclaimed, triaged, non-idea issues with no open blockers, sorted by priority — the same set `hew ready` prints and the same policy hewd's Ready queue answers from. An idea stays in Issues, List and Children: it is investigation work, never offered as implementation.
func (*Snapshot) States ¶
States returns the states this snapshot fetched. A query can only answer about issues in them, so Get returning false can mean the issue is closed and this snapshot was open-only rather than that it does not exist.
func (*Snapshot) Untriaged ¶
Untriaged returns how many open issues in the snapshot are untriaged — the same count Primer reports, with none of their titles or bodies. An untriaged issue is ordinary tracker state rather than a defect, so it stays out of the read queries; Triage is the deliberate API that returns its text. Epics are containers and are never untriaged, and a closed fetch holds no open triage work, so either counts zero.
type SnapshotOptions ¶
type SnapshotOptions struct {
// States selects the issue states to fetch. Empty means open only —
// unlike SearchRequest.States, where empty means open and closed.
States []State
// Bodies carries each issue's body and comments on the snapshot's
// list-shaped reads — Issues, Ready, List, Blocked, Claimed, Epics and
// Children. The zero value omits them, matching `hew list` without
// --bodies; Snapshot.Get is a single-issue read and always carries them.
Bodies bool
}
SnapshotOptions selects which issues to fetch. The zero value fetches open issues only. An unknown state is an invalid-input error.
type StartOptions ¶
type StartOptions struct {
// Priority optionally supplies P0..P4; required for an untriaged target.
Priority string
// Force replaces an existing claim and permits open blockers.
Force bool
// ForDiscovery declares that the caller is claiming an idea to investigate
// it. An idea is refused without it, forced or not: capture is not
// implementation work.
ForDiscovery bool
}
StartOptions configures a claim. The zero value preserves the existing priority and refuses an existing claim or open blockers.
type StartOutcome ¶
type StartOutcome string
StartOutcome is the decision a refused Start asks an agent loop to make. The three values are the whole vocabulary: the CLI's exit codes, the daemon's error kinds and a consumer's own branch points are spellings of them, so no caller re-derives the decision from ClaimedError.ByActor. Every other Start refusal — a closed target, an epic, an idea claimed without discovery intent, an untriaged issue, a bad priority, a write failure — is not a start outcome.
const ( // StartClaimedByOther means someone else holds the issue: pick the next // ready item (CLI exit 3). StartClaimedByOther StartOutcome = "claimed_by_other" // StartClaimedByYou means the acting identity already holds the issue: // resume that work (CLI exit 5). StartClaimedByYou StartOutcome = "claimed_by_you" // StartBlocked means open blockers remain: pick the next ready item // (CLI exit 6). StartBlocked StartOutcome = "blocked" )
func StartOutcomeOf ¶
func StartOutcomeOf(err error) (StartOutcome, bool)
StartOutcomeOf reports which of the three decisions err carries: a claim by someone else, a claim by the acting identity, or open blockers. ok is false for every other error, which callers report as itself rather than as a claim decision. The facts stay on *ClaimedError and *BlockedError; this names the decision, not a copy of them.
type StartResult ¶
StartResult is a completed claim: the issue as re-read after the claim and the identity the claim was made as. Claimant is what a caller compares the resulting assignees with to notice a racing claim; it is also the identity a consumer records for the work, without a second backend lookup.
type Target ¶
type Target struct {
// Backend is the implementation that owns the repository.
Backend Backend `json:"backend"`
// Repo is the GitHub repository as owner/name, resolved from the
// checkout's origin remote. It is empty for a local tracker and when the
// checkout has no github.com origin to read.
Repo string `json:"repo"`
// Dir is the local tracker directory (the .hew directory) when Backend is
// BackendLocal; empty for GitHub.
Dir string `json:"dir"`
// MainCheckout is the repository's main working tree, empty when the
// directory is not inside a git checkout.
MainCheckout string `json:"mainCheckout"`
// ID is the local tracker's stable identity from its config, the value
// batch checkpoints bind to. Empty on GitHub.
ID string `json:"id"`
}
Target is where a repository's issues live: the read-only backend report a caller gets before opening anything.
func Detect ¶
Detect reports which backend owns the repository containing dir and where its state lives. The worktree is dir, never the process working directory. It reads the filesystem and git; git's own environment (GIT_DIR and friends) is inherited, as it is for any git command.
Detect is read-only and opens no store or client. Repo is left empty rather than guessed when the origin remote is missing or not a github.com URL; Open, which has to name one, reports that in its own terms.
type TextFinding ¶
type TextFinding struct {
// Issue is the issue the text belongs to.
Issue int `json:"issue"`
// Source is TextFindingTitle, TextFindingBody or TextFindingComment.
Source string `json:"source"`
// Comment indexes Issue.Comments when Source is TextFindingComment: the
// comments actually fetched and displayed, not the server-side thread.
Comment int `json:"comment"`
ZeroWidth bool `json:"zeroWidth"`
BidiControl bool `json:"bidiControl"`
UnicodeTags bool `json:"unicodeTags"`
Confusable bool `json:"confusable"`
}
TextFinding is one field's advisory character findings. Source attributes the finding to the title, the body, or one displayed comment, so a reader knows which part of a long issue to inspect. The four flags are independent and may all be false on a clean field; findings never filter, rewrite or reject the text.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker is an open tracker: one backend, one worktree, and the identity claims are made as. As shares the open store; a Tracker is otherwise not copied.
func Open ¶
Open opens the tracker for cfg.Worktree. The backend is detected once, from that directory, unless cfg.Backend pins it, and is fixed for the life of the Tracker: a local tracker deleted underneath a long-lived process is not silently replaced by the repository's GitHub issues.
func WrapAs ¶
func WrapAs(store gh.IssueStore, backend Backend, actor string) *Tracker
WrapAs makes a Tracker around an already-open store, as actor: the seam hew's own CLI uses for writes and for the reads it delegates to Tracker, where it opens the store once for every command and already knows which backend it opened. External callers use Open, which also resolves the worktree and the backend. A read never resolves the actor, so it may be empty here.
An empty actor defers to the store's Viewer, read when an operation first needs the identity rather than at WrapAs. That is what keeps the CLI's identity rules — HEW_USER on a local tracker, the authenticated login on GitHub — outside this package while still letting a command refuse a claim before it has paid for the lookup: a refusal can name the claimant without the acting identity, and only a claim has to know who is acting. Identity reports the actor given, empty when it was deferred.
func (*Tracker) ApplyPlan ¶
func (t *Tracker) ApplyPlan(ctx context.Context, entries []PlanEntry, opts ApplyOptions) (ApplyResult, error)
ApplyPlan batch-creates issues from typed plan entries: create in entry order, checkpointing after every write, then wire parents and blockers — the same machinery `hew apply` runs over a JSONL plan, for callers that build plans in code.
A checkpoint makes an interrupted run resumable: every entry it maps is skipped, and an issue a checkpoint points at is verified to carry the provenance marker this plan wrote before anything is touched. The zero ApplyOptions uses an in-memory checkpoint; FileCheckpoint persists to a state file.
ApplyPlan validates the whole plan, verifies every existing-issue reference and every checkpoint mapping before the first write, so a refused plan leaves nothing behind. The write path's title and area rules — including the idea type's area reservation — are applied to pending entries only, so a plan whose checkpoint already created a task with `idea` as an area can still resume while a fresh plan is refused. Pending parent relationships are checked the same way, using the normalized type of both endpoints: an edge this run would still wire may not touch an idea, while an edge the checkpoint records as wired is left as it is. A create failure aborts with the checkpoint already holding the issues created so far; edge failures warn and are retried by a rerun, and are counted in ApplyResult.Unwired.
func (*Tracker) As ¶
As returns a tracker whose claims are made as actor, sharing this tracker's open store. It is a cheap clone; the receiver is unchanged. On GitHub the claim identity is the authenticated login, so As returns a tracker whose Identity is still that login. An empty actor, or the current identity, returns the receiver.
func (*Tracker) Block ¶
func (t *Tracker) Block(ctx context.Context, number int, blockers []int, opts BlockOptions) (BlockResult, error)
Block is Writer.Block over the tracker Open returned.
func (*Tracker) CheckCreate ¶
func (t *Tracker) CheckCreate(ctx context.Context, req CreateRequest) error
CheckCreate runs everything Create does before its first write — the field validation and the reference reads — and writes nothing. An adapter that must collect the body interactively calls it first, so a typo in a reference or a flag fails before the author has typed anything. The request's Body is validated as given; a caller that has not collected it yet passes the zero Body, and Create validates the real one.
Create runs the same preparation, so the pre-flight and the creation cannot disagree about what is refused.
func (*Tracker) CheckCreateEpic ¶
func (t *Tracker) CheckCreateEpic(ctx context.Context, req CreateEpicRequest) error
CheckCreateEpic is CheckCreate for an epic: the title, children and body validation and every reference read CreateEpic does before its first write, with nothing written. It exists so an adapter can refuse a missing or already-parented child before opening an editor; CreateEpic runs the same preparation, so the two cannot drift.
func (*Tracker) Close ¶
func (t *Tracker) Close(ctx context.Context, number int, opts CloseOptions) (CloseResult, error)
Close comments opts.Reason on an issue and closes it: not planned unless opts.Completed or opts.DuplicateOf says otherwise. Closing through a merged pull request is the norm; this is for work that was dropped, duplicated or finished out of band.
A duplicate closure with no Reason comments "Duplicate of #n", and a custom Reason that does not already name the original gets that line appended, so the original stays findable from the closed duplicate — GitHub stores it nowhere but the comment.
Every refusal happens before the comment is posted, so a refused close leaves the issue untouched: InvalidInputError for a missing Reason or contradictory options, ClosedError for an issue already closed (its Reason says whether it was completed or dropped), OpenChildrenError for an epic whose sub-issues are still open unless opts.Force, and NotFoundError for a DuplicateOf that names no issue.
The comment and the close are two writes. If the close fails after the comment posted, the error is a PartialCloseError: a retry will comment again.
func (*Tracker) Create ¶
func (t *Tracker) Create(ctx context.Context, req CreateRequest) (CreateResult, error)
Create files one issue conforming to the conventions: exactly one priority and one type label, a template body, and native parent, dependency and discovered-from links.
The whole request is validated before the first write: title, type, priority, areas and body through ValidateTitle, NormalizeAreas and ComposeBody, then every reference by reading it. A refusal therefore leaves the tracker untouched. The writes themselves are multi-step — create, then assignees, blockers and parent — and a failure after the issue exists is a *PartialCreateError naming the created issue, the stage and the edges that landed.
func (*Tracker) CreateEpic ¶
func (t *Tracker) CreateEpic(ctx context.Context, req CreateEpicRequest) (CreateResult, error)
CreateEpic files a parent issue with the cosmetic Epic title prefix, a priority label and the epic label but no type, then attaches its children. The epic label is what keeps a childless epic triaged, listed and unworkable until its first child lands.
Every reference is read and checked before the epic is filed: a missing child, a discovered-from the body names, or a child that already belongs to another epic refuses the call with nothing written. A failure after the epic exists is a *PartialCreateError naming it, the child that failed, and the children already attached.
func (*Tracker) Detail ¶
Detail is the show read: one live issue in any state, with body and recent comments. An epic's view also fetches both states to resolve its children from parent backlinks — complete even when the epic's sub-issue connection was capped — and names the next workable child. Children keep every existing relationship, including an idea attached outside hew; the next-child selector skips ideas, because the epic's sequence is implementation work. An issue number named by the caller is the deliberate retrieval path, so untriaged text is returned here.
func (*Tracker) Edit ¶
func (t *Tracker) Edit(ctx context.Context, req EditRequest) (EditResult, error)
Edit applies a partial edit to one issue. Fields the request leaves unset are left alone; the optional pointer fields carry presence, so an explicitly empty title, body, outcome, priority or type is a refusal rather than an omission.
Every requested change is validated before the first write — the field values, the area names, the parent target, and the closed-target guard — so a refusal changes nothing. Priority and type swaps enforce the conventions' one-label invariant over the whole type vocabulary, idea included; areas are normalized (trimmed, de-duplicated) and may not name a convention label. An edit never touches a claim. A parent move or removal only rewires the edited issue's own parent link: its sub-issues and its old parent's other children stay where they are.
The refusals are typed: InvalidInputError names the request field at fault, ClosedError reports a closed target unless AllowClosed is set, and NotFoundError reports an issue or a parent the tracker does not have. A write that fails after an earlier one landed is a PartialEditError naming the fields applied, the field that failed and the backend cause.
func (*Tracker) Identity ¶
Identity reports the claimant identity claims are made as: the actor given to Open or As on a local tracker, the authenticated login on GitHub.
func (*Tracker) Init ¶
func (t *Tracker) Init(ctx context.Context) (InitResult, error)
Init makes sure an open tracker has the backend furniture its workflows assume. On GitHub that is the convention labels: every missing one is created, and the ones already present are left alone, so a second call changes nothing. The set is conventions.Labels, which model.LabelVocabulary derives from the type vocabulary, so a newly recognized type such as idea is bootstrapped by the same call. The local backend carries its labels in the tracker itself, so a local tracker is already initialized and this reports it unchanged.
A create that fails returns the labels created so far in CreatedLabels; a rerun picks up the ones still missing, because the bootstrap is idempotent. An authentication failure is AuthError.
func (*Tracker) Primer ¶
func (t *Tracker) Primer(ctx context.Context) (PrimerResult, error)
Primer is the session-start read: one fetch of open issues, the ready, in-progress and epic sections, the untriaged count, and every warning the live state carries, together with the backend's convention text. It returns no untriaged title or body.
func (*Tracker) RateLimit ¶
RateLimit reports the budget captured from the last list query, and false when no query has run on this tracker or the backend has no budget. A Tracker is safe for concurrent use, so a caller may read it while other operations run.
func (*Tracker) Release ¶
Release gives up a claim: it clears the in-progress label and every assignee, leaving the issue open and unassigned. The zero ReleaseOptions releases only a claim held solely by the acting identity; opts.Force releases any claim.
The refusals are typed: NotClaimedError for an issue nobody holds (with or without Force), and NotOwnerError when the claim is not solely the acting identity's — which includes a label-only claim and a shared one. A refusal changes nothing. A failure after the first write is a PartialReleaseError, because the claim may then be half cleared.
Where the store can release atomically (the local store), ownership is rechecked and both halves cleared under one lock, so a concurrent forced start's new claim is never cleared by this call's stale read. Elsewhere it is check-then-act.
func (*Tracker) Reopen ¶
func (t *Tracker) Reopen(ctx context.Context, number int, opts ReopenOptions) (ReopenResult, error)
Reopen is Close's inverse: comment opts.Reason on a closed issue, reopen it, and clear the stale claim the close left behind.
Closing comments routinely encode the condition to reopen on, so acting on one keeps close's comment-plus-state-change shape rather than degrading to a bare state flip. There is no retriage: the issue rejoins the read path with the priority, type and area labels it already had.
The claim is the one thing reopen clears. Neither close nor a PR merge removes the in-progress label or the assignee, so most issues closed in the normal workflow still carry the claim that produced the fix; left in place, it makes the claim guard lie about who is working. Whoever wants the work back runs Start.
Reopening an issue that is already open is not an error: the requested state holds, the call reports Reopened false and writes nothing, so an idempotent retry does not look like a failure and no comment documents a reopen that never happened.
The refusals are typed: InvalidInputError for a missing Reason and NotFoundError for an issue the tracker does not have. A failure after the first write is a PartialReopenError whose Stage says what survived.
func (*Tracker) Repo ¶
Repo reports the GitHub repository this tracker works against, as owner/name. It is empty on a local tracker, and on a Tracker wrapped around a store whose repository the caller did not name.
func (*Tracker) Search ¶
func (t *Tracker) Search(ctx context.Context, req SearchRequest) (SearchResult, error)
Search is the dedup read: a repo-scoped text search over open and closed issues, in the backend's relevance order (GitHub's best match, the local store's title-first). Untriaged matches are omitted — Triage's search form is the other half of dedup — so Issues may be shorter than Fetched.
func (*Tracker) Start ¶
func (t *Tracker) Start(ctx context.Context, number int, opts StartOptions) (StartResult, error)
Start claims an issue as the tracker's acting identity: assign that identity and add the in-progress label, swapping the priority label when one was given. The zero StartOptions preserves the existing priority and refuses an existing claim or open blockers.
The refusals are typed: ClosedError and EpicError for a target that cannot be worked, DiscoveryIntentError for an idea claimed without declaring investigation, ClaimedError carrying the claimants and whether the acting identity is one of them, BlockedError carrying the open blockers, and UntriagedError when a claim would need a priority the caller did not give (claiming an untriaged issue is triage). Start claims atomically on a backend that supports it, so simultaneous claims have exactly one winner, and re-reads afterwards where the backend only offers check-then-act.
func (*Tracker) Triage ¶
func (t *Tracker) Triage(ctx context.Context, req TriageRequest) (TriageResult, error)
Triage lists issues missing their priority or type label — the deliberate API that returns untriaged text to a caller that asked for it. With Search empty it is the open queue, oldest first; with Search set it is the untriaged matches among the backend's search results, spanning both states.
func (*Tracker) Unblock ¶
func (t *Tracker) Unblock(ctx context.Context, number int, blockers []int, opts BlockOptions) (UnblockResult, error)
Unblock is Writer.Unblock over the tracker Open returned.
type TriageRequest ¶
type TriageRequest struct {
Search string
// Bodies carries each untriaged issue's body and comments. The zero
// value omits them; the advisory findings are computed from the fetched
// text regardless, so an annotator can leave it unset. `hew triage` sets
// it because its renderers scan the text themselves.
Bodies bool
}
TriageRequest selects the triage view. Empty Search is the open untriaged queue; a non-empty Search is the untriaged half of dedup across both states.
type TriageResult ¶
type TriageResult struct {
Issues []Issue `json:"issues"`
Total int `json:"total"`
Fetched int `json:"fetched"`
TextFindings []TextFinding `json:"textFindings"`
}
TriageResult is a triage listing: the untriaged matches, the completeness counts for a search (the queue form is uncapped, so its Total equals Fetched), and the advisory text findings for each match. Issues carries bodies only when TriageRequest.Bodies asked for them; the findings are computed from the fetched text either way.
func (TriageResult) MarshalJSON ¶
func (r TriageResult) MarshalJSON() ([]byte, error)
MarshalJSON renders the matches and their findings as arrays even when empty.
type UnblockResult ¶
UnblockResult reports what Unblock changed. Removed and Missing are the requested blockers in request order; an empty Removed means the call was a no-op.
func (UnblockResult) MarshalJSON ¶
func (r UnblockResult) MarshalJSON() ([]byte, error)
MarshalJSON renders both blocker sets as arrays even when empty.
type UntriagedError ¶
type UntriagedError struct{ Issue int }
UntriagedError reports a claim on an issue with no priority. Claiming an untriaged issue is triage, so the caller has to supply the priority.
func (*UntriagedError) Error ¶
func (e *UntriagedError) Error() string
type UnverifiableCycleError ¶
UnverifiableCycleError reports a proposed edge whose cycle check could not be completed because blocker connections were capped.
func (*UnverifiableCycleError) Error ¶
func (e *UnverifiableCycleError) Error() string
type Warning ¶
type Warning struct {
Kind WarningKind `json:"kind"`
// Issue names the subject; 0 for a cycle, which spans several.
Issue int `json:"issue"`
// Cycle is the ordered member path for WarnDependencyCycle, ending with
// its first member again.
Cycle []int `json:"cycle"`
// Total and Fetched are the server-side and fetched counts for the
// capped-connection kinds.
Total int `json:"total"`
Fetched int `json:"fetched"`
}
Warning is one completeness or contradiction notice. A snapshot's query methods keep the completeness kinds; Primer keeps every kind.
func (Warning) MarshalJSON ¶
MarshalJSON renders the cycle as an array even when the warning is not one.
type WarningKind ¶
type WarningKind string
WarningKind identifies a warning's cause, so a caller can filter by kind and render its own message without parsing prose.
const ( // WarnMultiPriority reports an issue carrying more than one priority // label; the highest urgency wins. It is a contradiction, so it rides on // a primer's warnings rather than a snapshot query's. WarnMultiPriority WarningKind = "multiple-priority-labels" // WarnMultiType reports more than one type label; the first of // bug|enhancement|task wins. Like the other contradictions, it is // primer-only. WarnMultiType WarningKind = "multiple-type-labels" // WarnInProgressEpic reports an epic carrying the in-progress label. // Epics are containers and are never worked directly, so it is a // primer-only contradiction. WarnInProgressEpic WarningKind = "in-progress-epic" // WarnDependencyCycle reports a blocked-by cycle. A cycle silently // removes all of its members from Ready, so the queue is incomplete. WarnDependencyCycle WarningKind = "dependency-cycle" // WarnSubIssuesCapped reports an epic whose sub-issue connection was // capped: the rollup counts come from the server and stay right, but // Children still reflects parent backlinks over the full fetch. WarnSubIssuesCapped WarningKind = "sub-issues-truncated" // WarnBlockersCapped reports an issue whose blocker connection was // capped: an unseen blocker may make Ready wrong. WarnBlockersCapped WarningKind = "blockers-truncated" )
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer carries the dependency operations over an already-open store. Block and Unblock need neither the backend nor the acting identity, only the store, so Writer is the write-side seam hew's own CLI wraps its resolved store with. External consumers use the same methods on the Tracker Open returns.
func WrapWriter ¶
func WrapWriter(store gh.IssueStore) *Writer
WrapWriter makes a Writer from an already-open store. A consumer outside this module cannot name gh.IssueStore and uses Open instead.
func (*Writer) Block ¶
func (w *Writer) Block(ctx context.Context, number int, blockers []int, opts BlockOptions) (BlockResult, error)
Block adds native dependencies after a transitive client-side cycle check — GitHub itself only rejects self-blocks and direct two-issue cycles. It refuses a closed target unless opts.AllowClosed is set; a closed blocker is refused outright, since closed blockers don't block.
Several blockers are validated together and written only once every one has passed, so a refusal never leaves a half-applied set. Each is checked against the graph as it stands: every new edge starts at issue, so a cycle through two of them would revisit issue and is already a cycle through one.
func (*Writer) Unblock ¶
func (w *Writer) Unblock(ctx context.Context, number int, blockers []int, opts BlockOptions) (UnblockResult, error)
Unblock removes dependencies. It refuses a closed target unless opts.AllowClosed is set. A blocker that is not there is skipped and named rather than failing the call.