Documentation
¶
Overview ¶
Package workspace holds the node-workspace graph model, its storage, roles, the task-split prompt/parser and the scheduler.
Index ¶
- Constants
- Variables
- func BudgetReachedMsg(spent, limit float64) string
- func BuildReviewPrompt(in ReviewInput) string
- func BuildSplitPrompt(task string, roles []Role, projectContext string) string
- func CancelSummary(prev string, applied []AppliedProposal) string
- func CompactSummary(prev string, folded []*Node) string
- func CountSessions(projectRoot string) int
- func DeleteSession(projectRoot, id string) error
- func ExecRunner(ctx context.Context, dir, name string, args ...string) (string, error)
- func FindSpecTasks(root, arg string) (string, error)
- func FixExcerpt(failed []*Node, maxChars int) string
- func FixExcerptWith(failed []*Node, maxChars int, detail func(nodeID, actID string) (string, bool)) string
- func HasMergedNode(root, session string) bool
- func IsFixID(id string) bool
- func MaxParallel(cfg config.Config) int
- func MergeSession(root, session string) (string, error)
- func PRBody(s Session) string
- func PRTitle(s Session) string
- func ParseIssueRef(ref string) (source, arg string, err error)
- func Reconcile(g *Graph, cfg config.Config)
- func RemoveSessionWorktrees(root, session string) error
- func ReplyExcerpt(n *Node, prev Attempt, maxChars int, ...) string
- func Sanitize(s string) string
- func SanitizeText(s string) string
- func Save(path string, g *Graph) error
- func SessionBranch(session string) string
- func SessionsDir(projectRoot string) string
- func SpecFeatureName(specText, dirName string) string
- func SpecUntracked(root, dir string) []string
- func SuggestSpecRole(text string, hasQA bool) string
- func TickSpecTask(data []byte, id string) (out []byte, changed bool, err error)
- type AppliedProposal
- type ApplyOptions
- type Attempt
- type Budget
- type Check
- type CmdRunner
- type CostFunc
- type CustomCommand
- type Diff
- type DiffFile
- type DiffLine
- type DiffNote
- type Engine
- func (e *Engine) AcceptSuggestions(defined func(string) bool) int
- func (e *Engine) ActivityDetail(nodeID, activityID string) (string, bool)
- func (e *Engine) AddCIFix(title, desc, role string) string
- func (e *Engine) AddFix(checkID string) (string, error)
- func (e *Engine) AddWork(title, desc, role string, nextID int) (string, int)
- func (e *Engine) ApplyProposals(p []Proposal, opts *ApplyOptions) ([]AppliedProposal, []SkippedProposal)
- func (e *Engine) Assign(id, role string) error
- func (e *Engine) Auto() bool
- func (e *Engine) CheckBudget()
- func (e *Engine) Close()
- func (e *Engine) Done() <-chan struct{}
- func (e *Engine) Events() <-chan Event
- func (e *Engine) Limited() []*Node
- func (e *Engine) PreviewProposals(p []Proposal, opts *ApplyOptions) ([]AppliedProposal, []SkippedProposal)
- func (e *Engine) Replace(mut func(g *Graph)) error
- func (e *Engine) Reply(id, msg string) (ReplyResult, error)
- func (e *Engine) RetryLimited(id string) error
- func (e *Engine) RetryLimitedNow(id string) error
- func (e *Engine) ReviewRounds() int
- func (e *Engine) Run(ctx context.Context, id string) error
- func (e *Engine) RunAll(ctx context.Context)
- func (e *Engine) Running() int
- func (e *Engine) SetBudget(f func() Budget)
- func (e *Engine) SetCost(f CostFunc)
- func (e *Engine) SetSkills(id string, skills []string) error
- func (e *Engine) Snapshot() *Graph
- func (e *Engine) StartReview() int
- func (e *Engine) Stop(id string)
- func (e *Engine) StopAll()
- func (e *Engine) Waiting() []*Node
- func (e *Engine) WillAutoRun(id string) bool
- type Event
- type EventType
- type Executor
- func NewExecutor(root string, cfg config.Config, projectContext string) Executor
- func NewExecutorIsolated(root string, cfg config.Config, projectContext string, ...) Executor
- func NewExecutorWithChecks(root string, cfg config.Config, projectContext string, ...) Executor
- func NewExecutorWithSummary(root string, cfg config.Config, projectContext string, ...) Executor
- type FileStat
- type FixRequest
- type Graph
- func Load(path string) (*Graph, error)
- func ParseSplit(task, output string, roles []Role) (*Graph, error)
- func ParseSplitOpts(task, output string, roles []Role, existing []string, opts SplitOptions) (*Graph, error)
- func ParseSplitWith(task, output string, roles []Role, existing []string) (*Graph, error)
- func Split(ctx context.Context, r runner.LLMRunner, model string, task string, ...) (*Graph, runner.TokenUsage, error)
- func SplitNext(ctx context.Context, r runner.LLMRunner, model string, task string, ...) (*Graph, runner.TokenUsage, error)
- func SplitOpts(ctx context.Context, r runner.LLMRunner, model string, task string, ...) (*Graph, runner.TokenUsage, error)
- func SplitWith(ctx context.Context, r runner.LLMRunner, model string, task string, ...) (*Graph, runner.TokenUsage, error)
- func (g *Graph) AddCIFix(title, desc string) *Node
- func (g *Graph) AddCheck(commands []string) *Node
- func (g *Graph) AddCheckDeferred() *Node
- func (g *Graph) AddFix(checkID, failure string) (*Node, error)
- func (g *Graph) AddFixExcerpt(checkID, failure, excerpt string) (*Node, error)
- func (g *Graph) AddWork(title, desc, role string, nextID int) (*Node, int)
- func (g *Graph) Append(add *Graph, nextID int) (newNext int, idMap map[string]string)
- func (g *Graph) ApplyProposals(p []Proposal, opts *ApplyOptions) (applied []AppliedProposal, skipped []SkippedProposal)
- func (g *Graph) Assigned(n *Node) bool
- func (g *Graph) Blockers(id string) []string
- func (g *Graph) Clone() *Graph
- func (g *Graph) Compact() (folded []*Node)
- func (g *Graph) CountLimited() int
- func (g *Graph) CountWaiting() int
- func (g *Graph) Counts() (todo, running, done, failed int)
- func (g *Graph) Layers() [][]*Node
- func (g *Graph) Node(id string) *Node
- func (g *Graph) PendingPlugins() []PluginRequest
- func (g *Graph) Runnable() []*Node
- func (g *Graph) Sanitize()
- func (g *Graph) SetPluginStatus(name, status string) bool
- func (g *Graph) SpentUSD() float64
- func (g *Graph) UnpricedNodes() []string
- func (g *Graph) Validate() error
- type Hunk
- type Isolator
- func (i *Isolator) Branch() string
- func (i *Isolator) CommitFileEdit(rel string, edit func([]byte) ([]byte, bool, error), msg string) error
- func (i *Isolator) Discard(id string)
- func (i *Isolator) Finish(id, title string) error
- func (i *Isolator) FinishCommit(id, title string) ([]FileStat, string, error)
- func (i *Isolator) FinishStats(id, title string) ([]FileStat, error)
- func (i *Isolator) IntegrationDir() (string, bool)
- func (i *Isolator) IntegrationRoot() (string, error)
- func (i *Isolator) NodeDir(id string) (string, bool)
- func (i *Isolator) Start(id string) (string, []string, error)
- func (i *Isolator) Tracked(rel string) bool
- type Issue
- type IssueRef
- type Kind
- type LimitInfo
- type Line
- type NewRole
- type Node
- type PRClient
- func (c *PRClient) Checks(ctx context.Context, number int) ([]Check, error)
- func (c *PRClient) EnsurePR(ctx context.Context, t PRTarget, sess Session) (PRResult, error)
- func (c *PRClient) HeadSHA(ctx context.Context, number int) (string, error)
- func (c *PRClient) NewFeedback(ctx context.Context, st PRState) ([]ReviewItem, error)
- func (c *PRClient) Poll(ctx context.Context, st PRState) (PRState, PollResult, error)
- func (c *PRClient) Prepare(ctx context.Context) (PRTarget, error)
- func (c *PRClient) Push(ctx context.Context, t PRTarget) error
- type PRConfig
- type PRResult
- type PRState
- type PRTarget
- type PluginRequest
- type PollResult
- type Proposal
- type ReplyResult
- type ReplyState
- type Report
- type Result
- type Review
- type ReviewInput
- type ReviewItem
- type ReviewResult
- type Role
- type Session
- type SessionInfo
- type SkippedProposal
- type SpecFeature
- type SpecImport
- type SpecList
- type SpecRef
- type SpecResult
- type SpecTask
- type SplitOptions
- type Status
Constants ¶
const ( ReportDone = agent.ReportDone ReportBlocked = agent.ReportBlocked ReportQuestion = agent.ReportQuestion )
Report statuses.
const ( PluginPending = "pending" PluginInstalled = "installed" PluginDeclined = "declined" )
Plugin request states.
const ( IsolationWorktree = "worktree" )
Isolation modes of workspace.isolation. "" means auto.
const ( SourceGitHub = "github" SourceBeads = "beads" )
Issue sources.
const ( // MaxReviewRounds is the number of lead reviews per task that start by // themselves. MaxReviewRounds = 5 // MaxProposals is the most proposals one review may apply. MaxProposals = 8 // MaxReviews is how many reviews a session keeps. MaxReviews = 20 // ReviewExcerptChars is the budget of the failure excerpt in the review prompt. ReviewExcerptChars = 6000 )
const ( ActionAdd = "add" ActionChange = "change" ActionCancel = "cancel" )
Proposal actions.
const ( ReviewPending = "pending" ReviewApplied = "applied" ReviewRejected = "rejected" ReviewEmpty = "empty" )
Review states.
const DefaultBudgetWarnPct = 80
DefaultBudgetWarnPct is the warn threshold when none is configured.
const FileName = "workspace.json"
FileName is the graph file inside .decsr.
const FixExcerptChars = 8000
FixExcerptChars is the budget of the "What failed" excerpt in a fix node.
const MaxLimitRetries = 3
MaxLimitRetries is how many automatic retries a limited node gets before it fails with the limit message.
const ReplyContextChars = 8000
ReplyContextChars is the budget of the previous-attempt excerpt in the context of a reply attempt.
Variables ¶
var ( ErrNothingMerged = errors.New("no node of this session has been merged yet") ErrDirtyTree = errors.New("your checkout has uncommitted changes to tracked files: commit or stash them first (the session branch starts from a snapshot of your working tree, so merging it brings those changes back as commits)") )
Errors of MergeSession that the caller shows to the user as they are.
var ( ErrGHMissing = errors.New("the GitHub CLI (gh) is not on PATH: install it from https://cli.github.com") ErrGHAuth = errors.New("gh is not logged in: run `gh auth login`") ErrPRNothingDone = errors.New("no node of this session has been merged yet: run a node first") )
Errors of the pull request preconditions that are shown as they are.
var ErrSpecTaskMissing = errors.New("task not found")
ErrSpecTaskMissing is returned by the tasks.md edit when no open line of the task exists any more.
Functions ¶
func BudgetReachedMsg ¶ added in v0.7.0
BudgetReachedMsg is the message shown when the budget stops new nodes.
func BuildReviewPrompt ¶ added in v0.7.0
func BuildReviewPrompt(in ReviewInput) string
BuildReviewPrompt assembles the lead's system prompt for a review.
func BuildSplitPrompt ¶
BuildSplitPrompt assembles the lead's system prompt.
func CancelSummary ¶ added in v0.7.0
func CancelSummary(prev string, applied []AppliedProposal) string
CancelSummary adds a line "- T5 cancelled by the lead: <reason>" to prev for every cancel among applied.
func CompactSummary ¶ added in v0.4.0
CompactSummary appends one line per folded node to prev: "- T1 <title> [<role>]: <summary, first 400 chars> (files: a, b)". When the result exceeds 12,000 characters the oldest lines are dropped.
func CountSessions ¶ added in v0.4.0
CountSessions is the number of saved sessions of the project: the *.json files in the sessions directory whose name is a valid session ID. Files are not read.
func DeleteSession ¶ added in v0.4.0
DeleteSession removes a saved session.
func ExecRunner ¶ added in v0.7.0
ExecRunner is the real CmdRunner. It never prompts: a missing login or credential is an error, not a hang.
func FindSpecTasks ¶ added in v0.7.0
FindSpecTasks resolves the argument of /import speckit to a tasks.md: a feature directory, a tasks.md, or (empty arg) the most recently modified specs/*/tasks.md under root.
func FixExcerpt ¶ added in v0.7.0
FixExcerpt builds a budgeted excerpt of what failed in the given nodes, for a fix node. See FixExcerptWith.
func FixExcerptWith ¶ added in v0.7.0
func FixExcerptWith(failed []*Node, maxChars int, detail func(nodeID, actID string) (string, bool)) string
FixExcerptWith builds an excerpt of at most maxChars characters from failed nodes, in this priority order until the budget is spent: failing commands with the tail of their output, then other errors (error activities and the node error), then the files touched as one line. Thinking and message items are never included. Where text was cut it says "[… N characters omitted]". When a command output is cut, the end is kept and lines of the cut part that mention an error, failure, panic or exception are kept with two lines of context, in the same budget (see cutKeepingErrors). detail, when not nil, returns the full detail of an activity (kept in memory only); the stored, shorter detail is the fallback.
func HasMergedNode ¶ added in v0.7.0
HasMergedNode reports whether at least one node of the session was merged into the session branch, that is, whether the session changed anything.
func MaxParallel ¶
MaxParallel is the number of nodes that may run at once: the configured value, default 3, clamped to 1..8.
func MergeSession ¶ added in v0.7.0
MergeSession merges the integration branch of a session into the branch checked out in root and removes the session's worktrees. It returns a one-line summary.
func PRBody ¶ added in v0.7.0
PRBody is a plain Markdown summary of the session: task, nodes, what each finished node did and the Build & test result.
func PRTitle ¶ added in v0.7.0
PRTitle is the first line of the session's first task, at most 72 characters.
func ParseIssueRef ¶ added in v0.7.0
ParseIssueRef tells which tracker ref names: digits, "#N" and a GitHub issue URL are GitHub issues, anything else is a bead id.
func RemoveSessionWorktrees ¶ added in v0.7.0
RemoveSessionWorktrees removes every worktree of a session. Branches are kept.
func ReplyExcerpt ¶ added in v0.7.0
func ReplyExcerpt(n *Node, prev Attempt, maxChars int, detail func(nodeID, actID string) (string, bool)) string
ReplyExcerpt builds the account of a previous attempt of node n that is given to the next attempt: at most maxChars characters, in this order until the budget is spent: the summary, the commands (failed ones first) with the tail of their output, the errors, the files touched, then the last assistant message. Reasoning is never included. Where text was cut it says "[… N characters omitted]". detail, when not nil, returns the full detail of an activity (kept in memory only); the stored, shorter detail is the fallback.
func Sanitize ¶ added in v0.4.0
Sanitize is SanitizeText for single-line text: every line break becomes a space.
func SanitizeText ¶ added in v0.4.0
SanitizeText removes terminal escape sequences (CSI, OSC, …) and control characters from untrusted text. Newlines are kept and tabs become spaces.
func SessionBranch ¶ added in v0.7.0
SessionBranch is the integration branch of a session.
func SessionsDir ¶ added in v0.4.0
SessionsDir is <projectRoot>/.decsr/sessions.
func SpecFeatureName ¶ added in v0.7.0
SpecFeatureName is the first heading of spec.md without a "Feature Specification:" prefix, or the feature directory name.
func SpecUntracked ¶ added in v0.7.0
SpecUntracked lists the spec.md, plan.md and tasks.md of the feature directory dir (relative to the project root) that exist but are not tracked by git. It is nil when root is not in a git repository.
func SuggestSpecRole ¶ added in v0.7.0
SuggestSpecRole is "qa" for a task that writes tests when the role exists, else "coder".
func TickSpecTask ¶ added in v0.7.0
TickSpecTask marks a task done in the text of a tasks.md: the first line matching "- [ ] <id>" (any indentation, "-" or "*" bullet) gets "[x]" and nothing else changes, line endings included. changed is false when the task is already done; ErrSpecTaskMissing means no such line.
Types ¶
type AppliedProposal ¶ added in v0.7.0
type AppliedProposal struct {
Proposal
NodeID string `json:"node_id,omitempty"`
Text string `json:"text"`
}
AppliedProposal is a proposal that was (or would be) applied. NodeID is the node it touched or created; Text is one line telling what happened.
type ApplyOptions ¶ added in v0.7.0
type ApplyOptions struct {
// KnownRole reports whether a role is defined. A proposal naming another
// role leaves the node unassigned with that role as its suggestion. Nil
// means no role is defined.
KnownRole func(string) bool
NextID int
}
ApplyOptions tells ApplyProposals which roles exist and where the numbers of new nodes start. NextID is updated to the next free number.
type Attempt ¶ added in v0.7.0
type Attempt struct {
N int `json:"n"`
Reply string `json:"reply,omitempty"` // what started it; "" for the first
Status Status `json:"status"`
StartedAt time.Time `json:"started_at,omitempty"`
EndedAt time.Time `json:"ended_at,omitempty"`
Summary string `json:"summary,omitempty"`
Report *Report `json:"report,omitempty"`
Error string `json:"error,omitempty"`
FileStats []FileStat `json:"file_stats,omitempty"`
Commit string `json:"commit,omitempty"`
Activity []runner.Activity `json:"activity,omitempty"`
ActivityDropped int `json:"activity_dropped,omitempty"`
}
Attempt is one finished attempt of a node, kept when a reply starts the next. Activity is kept for the most recent maxAttemptActivity attempts only.
type Budget ¶ added in v0.7.0
type Budget struct {
LimitUSD float64 // 0 = no budget
WarnPct int // 0 = DefaultBudgetWarnPct
ExtraUSD float64 // known cost outside the nodes, such as the lead's
}
Budget is the spending limit the engine enforces.
type Check ¶ added in v0.7.0
type Check struct {
Name string `json:"name"`
State string `json:"state"`
Bucket string `json:"bucket"` // pass | fail | pending | skipping | cancel
Link string `json:"link"`
}
Check is one CI check of a pull request (gh pr checks --json).
type CmdRunner ¶ added in v0.7.0
CmdRunner runs the program name (gh or git) with args in dir and returns its stdout. On a failure it returns the stdout read so far and an error that carries stderr. Tests replace it with a fake; nothing else talks to GitHub.
type CostFunc ¶ added in v0.7.0
CostFunc prices tokens of one model; known is false when no price is configured for it.
type CustomCommand ¶ added in v0.4.0
type CustomCommand struct {
Name, Description, Body, Source string // Source: "project", "user" or "plugin:<name>"
ArgHint string // shown after the name in the palette
}
CustomCommand is a user-defined /name command read from a markdown file.
func LoadCustomCommands ¶ added in v0.4.0
func LoadCustomCommands(projectRoot string) []CustomCommand
LoadCustomCommands reads the *.md files of <root>/.decsr/commands and then ~/.decsr/commands. A project command wins over a user command of the same name. Files with an invalid name, over 64 KB, empty, not regular (links, directories), containing NUL bytes or unreadable are skipped. Descriptions have terminal escape sequences and control characters removed. The result is sorted by name.
func PluginCommands ¶ added in v0.5.0
func PluginCommands(set plugins.Set) []CustomCommand
PluginCommands returns the commands of the enabled plugins as custom commands named "<plugin>:<command>" with the source "plugin:<plugin>".
func (CustomCommand) Expand ¶ added in v0.4.0
func (c CustomCommand) Expand(args string) string
Expand returns the task text: every $ARGUMENTS in the body replaced by the trimmed args. A body without $ARGUMENTS gets the args appended after a blank line when there are any.
type Diff ¶ added in v0.7.0
Diff is a parsed change set. Note is a dim line to show above it, for example that the diff may include other changes.
func NodeDiff ¶ added in v0.7.0
NodeDiff returns the change a node made. With isolation it is the node's own commit; while the node runs (or kept its worktree after a failed merge) it is the worktree against the point it started from, untracked files included. Without isolation it is the working tree change to the node's files in root, which may include changes of other nodes or of the user.
func SessionDiff ¶ added in v0.7.0
SessionDiff is everything the session branch holds that the current branch of root does not: git diff HEAD...decsr/<session>.
type DiffFile ¶ added in v0.7.0
type DiffFile struct {
Path string
OldPath string
Added int
Removed int
Binary bool
New bool
Deleted bool
Hunks []Hunk
}
DiffFile is the change to one file. OldPath is set only for a rename.
type DiffLine ¶ added in v0.7.0
DiffLine is one line of a hunk. Kind is '+', '-', ' ' or '\\' (the "No newline at end of file" marker). OldNo is 0 for an added line and NewNo is 0 for a removed one.
type DiffNote ¶ added in v0.7.0
type DiffNote struct {
NodeID string `json:"node_id"`
Path string `json:"path"`
Line int `json:"line"`
Side string `json:"side"`
Text string `json:"text"`
}
DiffNote is a review note on one line of a node's diff. Side is "new" for an added or unchanged line (Line is the new file's number) and "old" for a removed one.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine schedules graph nodes onto an Executor, up to maxParallel at once. All graph mutation happens under its mutex; callers read snapshots.
func NewEngineWithSave ¶ added in v0.4.0
NewEngineWithSave creates an engine over g that persists the graph through save after every change. A nil save disables persistence.
func (*Engine) AcceptSuggestions ¶
AcceptSuggestions assigns the suggested role of every unassigned work node whose suggestion is defined. It returns how many nodes were assigned.
func (*Engine) ActivityDetail ¶ added in v0.7.0
ActivityDetail returns the full detail (up to 2000 characters) of one activity item of a node. It is kept in memory only: false after a restart of the program or of the node, or when the item was dropped from the journal.
func (*Engine) AddCIFix ¶ added in v0.7.0
AddCIFix adds a fix node for a failing pull request check or for review comments, assigns role when it is not "", and returns its ID. It works while other nodes run.
func (*Engine) AddWork ¶ added in v0.7.0
AddWork adds a work node T<n> (n at least nextID) with the given title and description, assigns role when it is not "", and returns its ID and the next free number. It works while other nodes run.
func (*Engine) ApplyProposals ¶ added in v0.7.0
func (e *Engine) ApplyProposals(p []Proposal, opts *ApplyOptions) ([]AppliedProposal, []SkippedProposal)
ApplyProposals applies proposals to the live graph and saves it. It works while other nodes run: only nodes that are not running can be touched.
func (*Engine) CheckBudget ¶ added in v0.7.0
func (e *Engine) CheckBudget()
CheckBudget re-evaluates the budget, for spending the engine does not see (the lead) or a changed limit.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops every node (see StopAll) and then closes Done. It is safe to call more than once.
func (*Engine) Done ¶
func (e *Engine) Done() <-chan struct{}
Done is closed by Close; an event pump can stop reading when it fires.
func (*Engine) Limited ¶ added in v0.7.0
Limited returns a snapshot of the nodes that wait for a usage limit.
func (*Engine) PreviewProposals ¶ added in v0.7.0
func (e *Engine) PreviewProposals(p []Proposal, opts *ApplyOptions) ([]AppliedProposal, []SkippedProposal)
PreviewProposals is ApplyProposals on a copy: it changes nothing.
func (*Engine) Replace ¶ added in v0.4.0
Replace runs mut on the live graph under the lock and saves it. It refuses while any node is running.
func (*Engine) Reply ¶ added in v0.7.0
func (e *Engine) Reply(id, msg string) (ReplyResult, error)
Reply sends msg to a work or fix node. A node that is running gets the reply queued: it starts the next attempt as soon as the run ends, however it ends (a stop keeps the reply). A node that is done, failed or waiting keeps its history as an earlier attempt and starts attempt N+1 now, or waits when its dependencies, role, the parallel limit or the budget do not allow it yet. A node that never ran keeps msg as the user's message for its first run. A Build & test node that was done or failed is reset to todo, as AddFix does.
func (*Engine) RetryLimited ¶ added in v0.7.0
RetryLimited starts a limited node again after its limit lifted. It is the automatic retry: it counts toward MaxLimitRetries, and the node fails with the limit message instead of starting once those are used up. It is a retry, not a reply: the attempt number does not change.
func (*Engine) RetryLimitedNow ¶ added in v0.7.0
RetryLimitedNow is the retry the user asks for (r). It does not count toward the automatic retries.
func (*Engine) ReviewRounds ¶ added in v0.7.0
ReviewRounds is the number of lead reviews of the current task.
func (*Engine) RunAll ¶
RunAll turns auto mode on and starts every runnable node, then keeps starting nodes as others finish.
func (*Engine) SetBudget ¶ added in v0.7.0
SetBudget sets the budget the engine reads before it starts a node and when usage changes.
func (*Engine) SetCost ¶ added in v0.7.0
SetCost sets how node usage is priced. Without it no node cost is known.
func (*Engine) SetSkills ¶ added in v0.6.0
SetSkills sets the plugin skills of a todo or failed work node (the role's own skills are not part of the list). Ids that are not well formed are dropped.
func (*Engine) StartReview ¶ added in v0.7.0
StartReview counts a lead review of the current task and returns the number of reviews so far.
func (*Engine) StopAll ¶
func (e *Engine) StopAll()
StopAll turns auto mode off, cancels every running node and waits for the node goroutines to return, for at most 5 seconds: a node that ignores its cancelled context is abandoned and StopAll returns anyway. From the moment it begins, event sends never block (events are dropped when the buffer is full), so it does not depend on anyone reading Events().
func (*Engine) Waiting ¶ added in v0.7.0
Waiting returns a snapshot of the nodes that wait for a reply, in Nodes order. Each node's Report holds the question or the blocked summary.
func (*Engine) WillAutoRun ¶
WillAutoRun reports whether auto mode is on and the node is todo and assigned, so it will start by itself as soon as its dependencies are done.
type Event ¶
type Event struct {
NodeID string
Type EventType
Text string // output chunk, or the error text for EventFailed
// EventUsage: cumulative for the node.
In, Out int
Estimated bool
// Runner and Model of the agent that used the tokens (EventUsage), to
// price them.
Runner, Model string
// Activity is set for EventActivity.
Activity *runner.Activity
// ContextTokens and ContextLimit are set for EventContext.
ContextTokens, ContextLimit int
// ResetAt is set for EventLimited.
ResetAt time.Time
}
Event is a progress notification for one node. NodeID "" is used for engine-level messages (for example a failed save).
type EventType ¶
type EventType string
EventType classifies an Event.
const ( EventStarted EventType = "started" EventOutput EventType = "output" // EventActivity carries a structured agent activity in Event.Activity // (thinking, a command, a file edit, ...). A later activity with the same // ID replaces the earlier one. EventActivity EventType = "activity" EventUsage EventType = "usage" // EventContext reports the size of the prompt a worker is about to get: // Event.ContextTokens (estimated) and Event.ContextLimit (0 = unknown). EventContext EventType = "context" EventDone EventType = "done" // EventWaiting ends a node that reported a question or was blocked, in // place of EventDone. Text is the question (or the blocked summary); the // node's Report holds the details. EventWaiting EventType = "waiting" EventFailed EventType = "failed" // EventLimited ends a node that hit a provider usage limit; it waits to // be retried. Text is the limit message and ResetAt the reset time (zero // when unknown). EventLimited EventType = "limited" // EventBudgetWarn and EventBudgetReached are engine-level (NodeID ""); // Text is the message to show. EventBudgetWarn EventType = "budget_warn" EventBudgetReached EventType = "budget_reached" )
type Executor ¶
type Executor interface {
Run(ctx context.Context, g *Graph, n *Node, emit func(Event)) (Result, error)
}
Executor runs one node. It must return promptly when ctx is cancelled.
func NewExecutor ¶
NewExecutor returns the real Executor: work nodes go through the generic worker, check nodes run their shell commands.
func NewExecutorIsolated ¶ added in v0.7.0
func NewExecutorIsolated(root string, cfg config.Config, projectContext string, checkCommands func() []string, summary func() string, iso *Isolator) Executor
NewExecutorIsolated is NewExecutorWithSummary with an Isolator: each work node runs in its own git worktree and Build & test runs in the integration worktree. A nil iso keeps every node in root.
func NewExecutorWithChecks ¶
func NewExecutorWithChecks(root string, cfg config.Config, projectContext string, checkCommands func() []string) Executor
NewExecutorWithChecks is NewExecutor with a lazy source of check commands: a check node without Commands calls checkCommands when it runs.
func NewExecutorWithSummary ¶ added in v0.4.0
func NewExecutorWithSummary(root string, cfg config.Config, projectContext string, checkCommands func() []string, summary func() string) Executor
NewExecutorWithSummary is NewExecutorWithChecks plus a source of the session summary, which work nodes get as an "Earlier in this session" section.
type FileStat ¶ added in v0.7.0
type FileStat struct {
Path string `json:"path"`
Added int `json:"added,omitempty"`
Removed int `json:"removed,omitempty"`
Binary bool `json:"binary,omitempty"`
New bool `json:"new,omitempty"` // the node created the file
}
FileStat is the change one node made to one file, from git's numstat.
type FixRequest ¶ added in v0.7.0
type FixRequest struct {
Title, Desc string
}
FixRequest is a fix node the loop wants.
type Graph ¶
type Graph struct {
Task string `json:"task"`
Title string `json:"title"`
Nodes []*Node `json:"nodes"`
NewRoles []NewRole `json:"new_roles,omitempty"`
// FixSeq is the highest fix-node number handed out; F<n> is never reused,
// even after Compact removed the earlier fix nodes.
FixSeq int `json:"fix_seq,omitempty"`
// PluginRequests are the plugins the lead asked for, with the answers.
PluginRequests []PluginRequest `json:"plugin_requests,omitempty"`
// SplitWarnings are the notes of the split that produced the graph (an
// unusable skill or plugin dropped). Not saved.
SplitWarnings []string `json:"-"`
// ReviewRounds is the number of lead reviews of the current task; a new
// task, issue or import resets it (Append).
ReviewRounds int `json:"review_rounds,omitempty"`
// RemovedCostUSD is the priced cost of nodes that Compact folded or a lead
// proposal cancelled, so removing a node never lowers the money spent.
RemovedCostUSD float64 `json:"removed_cost_usd,omitempty"`
}
Graph is the whole workspace: the task and its nodes.
func Load ¶
Load reads a graph from path. Nodes saved as running (an interrupted run) come back as todo. A missing file returns os.ErrNotExist unchanged.
func ParseSplit ¶
ParseSplit turns the lead's output into a validated graph. Roles named by the lead become suggestions only; nothing is assigned.
func ParseSplitOpts ¶ added in v0.6.0
func ParseSplitOpts(task, output string, roles []Role, existing []string, opts SplitOptions) (*Graph, error)
ParseSplitOpts is ParseSplitWith with the plugins the lead knew about. The skills of a node are kept when they belong to an enabled plugin or to a catalog plugin the lead asked for under PLUGINS; the others are dropped and reported in Graph.SplitWarnings. PLUGINS entries outside the catalog are dropped too.
func ParseSplitWith ¶ added in v0.4.0
ParseSplitWith is ParseSplit for a follow-up task: a dependency that names one of the existing node IDs (and not one of the new tasks' own keys) is kept as an external dependency and passes validation.
func Split ¶
func Split(ctx context.Context, r runner.LLMRunner, model string, task string, roles []Role, projectContext string, onToken func(string)) (*Graph, runner.TokenUsage, error)
Split asks the lead to split task and parses the answer. When the graph has several nodes and the lead suggested no role at all, it asks once more.
func SplitNext ¶ added in v0.4.0
func SplitNext(ctx context.Context, r runner.LLMRunner, model string, task string, roles []Role, projectContext string, existing []string, next int, onToken func(string)) (*Graph, runner.TokenUsage, error)
SplitNext is SplitWith with an explicit first number for the new sub-tasks (0 = after the highest existing T number).
func SplitOpts ¶ added in v0.6.0
func SplitOpts(ctx context.Context, r runner.LLMRunner, model string, task string, roles []Role, projectContext string, existing []string, next int, opts SplitOptions, onToken func(string)) (*Graph, runner.TokenUsage, error)
SplitOpts is SplitNext with the plugins the lead may use or suggest.
func SplitWith ¶ added in v0.4.0
func SplitWith(ctx context.Context, r runner.LLMRunner, model string, task string, roles []Role, projectContext string, existing []string, onToken func(string)) (*Graph, runner.TokenUsage, error)
SplitWith is Split for a follow-up task: existing lists the IDs already in the graph, which the lead may depend on and must not reuse. New sub-tasks are numbered after the highest existing T number.
func (*Graph) AddCIFix ¶ added in v0.7.0
AddCIFix appends a work node "F<n>" with the given title and description (CI log or review comments) and returns it. It has no dependencies: it works on what is already merged. A Build & test node is reset to todo and made to depend on it, as AddFix does.
func (*Graph) AddCheck ¶
AddCheck appends the CHECK node depending on every other node. It returns nil without change when commands is empty or CHECK already exists.
func (*Graph) AddCheckDeferred ¶
AddCheckDeferred appends the CHECK node without commands; the executor asks for the commands when the node runs. It returns nil when CHECK exists.
func (*Graph) AddFix ¶
AddFix appends a work node "F<n>" that fixes a failed check, resets the check to todo and makes it depend on the new node.
func (*Graph) AddFixExcerpt ¶ added in v0.7.0
AddFixExcerpt is AddFix with an excerpt of what failed (see FixExcerpt) added to the description under "What failed:". An empty excerpt is built from the check node itself.
func (*Graph) AddWork ¶ added in v0.7.0
AddWork appends a work node "T<n>" (n at least nextID and above every T number in g) with no dependencies, assigned to role when it is not "", and returns it with the next free number. A Build & test node that is not running is reset to todo and made to depend on it, as AddCIFix does.
func (*Graph) Append ¶ added in v0.4.0
Append merges the work nodes of add into g under fresh IDs T<n>, T<n+1>, … (n is at least nextID and above every T number already in g), rewrites their dependencies, merges add's new roles and drops add's CHECK. g's CHECK (created when missing) is moved last, depends on every work node, and is reset to todo. It returns the next free number and the old-to-new ID map. add is not modified. A dependency naming one of add's own keys follows the renumbering (also when the key collides with an existing ID); one naming another work node already in g is kept; any other dependency is dropped.
func (*Graph) ApplyProposals ¶ added in v0.7.0
func (g *Graph) ApplyProposals(p []Proposal, opts *ApplyOptions) (applied []AppliedProposal, skipped []SkippedProposal)
ApplyProposals applies the proposals to g in order and returns what was applied and what was skipped, with the reason. Rules: only the first MaxProposals count; a change needs a todo or failed work node; a cancel a todo, failed or waiting work node; an add may depend only on existing nodes; a done, running or CHECK node is never touched. A new node makes CHECK depend on it (and resets CHECK to todo); a cancelled node is removed and its edges are dropped. A changed failed node goes back to todo.
func (*Graph) Assigned ¶
Assigned reports whether a node may run: check nodes always, work nodes once a role is set.
func (*Graph) Blockers ¶
Blockers returns the dependency IDs of id that are not done, in DependsOn order. A dependency that does not exist counts as a blocker.
func (*Graph) Compact ¶ added in v0.4.0
Compact removes done work and fix nodes (CHECK stays) and drops their IDs from the dependencies of the remaining nodes. A done node is folded only when every node that depends on it (the CHECK node aside) is folded too, so unfinished nodes keep the work they need. It returns the removed nodes in Nodes order.
func (*Graph) CountLimited ¶ added in v0.7.0
CountLimited returns how many nodes wait for a usage limit to lift.
func (*Graph) CountWaiting ¶ added in v0.7.0
CountWaiting returns how many nodes are waiting for a reply.
func (*Graph) Layers ¶
Layers groups nodes by dependency depth (1 + the deepest dependency), keeping Nodes order inside a layer. The graph must be acyclic.
func (*Graph) PendingPlugins ¶ added in v0.6.0
func (g *Graph) PendingPlugins() []PluginRequest
PendingPlugins returns the plugin requests nobody answered yet.
func (*Graph) Sanitize ¶ added in v0.4.0
func (g *Graph) Sanitize()
Sanitize removes terminal escape sequences and control characters from the graph title and the node titles and descriptions.
func (*Graph) SetPluginStatus ¶ added in v0.6.0
SetPluginStatus sets the status of the request for name; false when there is none.
func (*Graph) SpentUSD ¶ added in v0.7.0
SpentUSD is the priced cost of the nodes of g, all attempts added up, plus the cost of the nodes that were removed (RemovedCostUSD).
func (*Graph) UnpricedNodes ¶ added in v0.7.0
UnpricedNodes lists the IDs of nodes that used tokens without a known price.
type Isolator ¶ added in v0.7.0
type Isolator struct {
// contains filtered or unexported fields
}
Isolator gives every node of one session its own git worktree and branch and merges finished nodes into the session's integration branch.
func NewIsolator ¶ added in v0.7.0
NewIsolator returns the isolator for a session, or nil when nodes must share the checkout: mode is "shared", git is missing, root is not in a git repository, or the repository has no commit yet.
func (*Isolator) CommitFileEdit ¶ added in v0.7.0
func (i *Isolator) CommitFileEdit(rel string, edit func([]byte) ([]byte, bool, error), msg string) error
CommitFileEdit edits rel (relative to the project root) in the integration worktree and commits it with msg. edit returns the new content and whether it changed anything; without a change nothing is written or committed.
func (*Isolator) Discard ¶ added in v0.7.0
Discard drops the worktree and branch of a node without merging.
func (*Isolator) Finish ¶ added in v0.7.0
Finish commits what the node changed and merges it into the integration branch. On a clean merge the node's worktree and branch are removed. On a conflict the merge is aborted, the branch and worktree stay, and the error names the conflicting files.
func (*Isolator) FinishCommit ¶ added in v0.7.0
FinishCommit is FinishStats that also returns the SHA of the node's commit, which stays reachable through the merge into the integration branch after the node branch is deleted. It is "" when the node changed nothing.
func (*Isolator) FinishStats ¶ added in v0.7.0
FinishStats is Finish that also returns the lines the node added and removed per file; it is empty when the node changed nothing.
func (*Isolator) IntegrationDir ¶ added in v0.7.0
IntegrationDir is the project root inside the integration worktree (the merged result), and whether that worktree exists. Unlike IntegrationRoot it never creates it.
func (*Isolator) IntegrationRoot ¶ added in v0.7.0
IntegrationRoot is the project root inside the integration worktree, where the Build & test check runs. It is created when it does not exist yet.
func (*Isolator) NodeDir ¶ added in v0.7.0
NodeDir is the project root inside a node's worktree, and whether that worktree exists (a running node, or a failed or conflicted one that kept it).
type Issue ¶ added in v0.7.0
type Issue struct {
Source string // "github" | "beads"
// ID is how the issue is named: "#42" for an issue of the current
// repository, "owner/repo#42" for another one, the bead id for beads.
ID string
Title string
Body string
URL string
Labels []string
Closed bool
}
Issue is a task fetched from an issue tracker.
func FetchIssue ¶ added in v0.7.0
FetchIssue loads the issue ref names. root is the project; run is the command runner (nil = ExecRunner).
type IssueRef ¶ added in v0.7.0
type IssueRef struct {
Source string `json:"source"`
ID string `json:"id"`
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
}
IssueRef is what a session remembers about the issue it started from.
type LimitInfo ¶ added in v0.7.0
type LimitInfo struct {
Provider string `json:"provider"`
ResetAt time.Time `json:"reset_at,omitempty"` // zero when the provider gave no reset time
Message string `json:"message,omitempty"`
// Retries counts the automatic retries used so far. It survives the
// attempts of the limit loop and is cleared when a run succeeds or fails
// for another reason, or when the user replies to the node.
Retries int `json:"retries,omitempty"`
}
LimitInfo says that a waiting node stopped because its provider limited usage. The node is retried after ResetAt (see Engine.RetryLimited).
type Line ¶ added in v0.4.0
Line is one transcript entry. Who is "you", "lead", "system" or "error".
type Node ¶
type Node struct {
ID string `json:"id"` // "T1", "T2", …, "CHECK", "F1"
Title string `json:"title"`
Description string `json:"description"`
Kind Kind `json:"kind"`
Role string `json:"role,omitempty"` // assigned role; "" = unassigned
SuggestedRole string `json:"suggested_role,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
Status Status `json:"status"`
Commands []string `json:"commands,omitempty"` // check nodes
Summary string `json:"summary,omitempty"`
Report *Report `json:"report,omitempty"` // the worker's closing report, set when the node ends
Files []string `json:"files,omitempty"`
Observed []string `json:"observed,omitempty"` // changed on disk by the agent's own tools
FileStats []FileStat `json:"file_stats,omitempty"` // lines added and removed per file, set when the node ran in a worktree
Commit string `json:"commit,omitempty"` // the node's own commit when it ran in a worktree; reachable through the session branch
Warnings []string `json:"warnings,omitempty"`
Skills []string `json:"skills,omitempty"` // plugin skill ids the lead chose for this node
Spec *SpecRef `json:"spec,omitempty"` // the Spec Kit task this node was imported from
Error string `json:"error,omitempty"`
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
Estimated bool `json:"estimated,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"` // priced from the configured prices, added up over every attempt; 0 when unknown
CostKnown bool `json:"cost_known,omitempty"` // a price was found for the node's model
StartedAt time.Time `json:"started_at,omitempty"`
EndedAt time.Time `json:"ended_at,omitempty"`
// Activity is the journal of the current attempt: at most maxNodeActivity
// items, each Detail clipped to maxStoredDetail runes. ActivityDropped counts
// the older items that were cut off.
Activity []runner.Activity `json:"activity,omitempty"`
ActivityDropped int `json:"activity_dropped,omitempty"`
// LastActivityAt is the last activity or output of a running node (stall detection).
LastActivityAt time.Time `json:"last_activity_at,omitempty"`
// ContextTokens is the estimated size of the worker prompt; ContextLimit the
// role's context limit, 0 when unknown.
ContextTokens int `json:"context_tokens,omitempty"`
ContextLimit int `json:"context_limit,omitempty"`
// Attempt is the number of the current attempt; 0 and 1 both mean the
// first. A reply (Engine.Reply) starts the next one.
Attempt int `json:"attempt,omitempty"`
// Reply is the user's message that started the current attempt; "" for a
// first attempt that was not started by a reply.
Reply string `json:"reply,omitempty"`
// PendingReply is a reply to a running node, kept until the run ends.
PendingReply string `json:"pending_reply,omitempty"`
// Attempts are the finished earlier attempts, oldest first.
Attempts []Attempt `json:"attempts,omitempty"`
// Limit is set while the node waits for a provider usage limit to lift
// (Status waiting). It tells such a node from one that waits for a reply.
Limit *LimitInfo `json:"limit,omitempty"`
// contains filtered or unexported fields
}
Node is one sub-task in the graph.
func (*Node) AttemptNumber ¶ added in v0.7.0
AttemptNumber is the number of the current attempt (1 for the first).
type PRClient ¶ added in v0.7.0
type PRClient struct {
Root string // the user's checkout
Session string
Cfg PRConfig
Run CmdRunner // nil = ExecRunner
}
PRClient pushes the session branch and talks to GitHub through gh.
func (*PRClient) Checks ¶ added in v0.7.0
Checks lists the checks of a pull request. gh exits non-zero while checks fail or are pending but still prints the JSON, so stdout wins over the exit status; "no checks reported" is an empty list.
func (*PRClient) EnsurePR ¶ added in v0.7.0
EnsurePR pushes the session branch and returns its pull request: the open one when it exists, else a new one built from sess.
func (*PRClient) NewFeedback ¶ added in v0.7.0
NewFeedback returns the line comments and CHANGES_REQUESTED reviews of the pull request that are not in st.SeenComments yet, oldest first.
func (*PRClient) Poll ¶ added in v0.7.0
Poll looks at the checks and the review feedback once. It returns the updated state; the caller saves it and adds the nodes.
type PRConfig ¶ added in v0.7.0
PRConfig is the part of the configuration the loop needs.
func (PRConfig) PollInterval ¶ added in v0.7.0
PollInterval is the polling period: 60 s by default, at least 15 s.
type PRState ¶ added in v0.7.0
type PRState struct {
Number int `json:"number,omitempty"`
URL string `json:"url,omitempty"`
// SeenComments are the review comments and reviews already turned into a
// fix node ("c<id>" and "r<id>").
SeenComments []string `json:"seen_comments,omitempty"`
// CIFixes is the number of CI fix rounds started.
CIFixes int `json:"ci_fixes,omitempty"`
// FixedSHA is the head commit whose failing checks were already handled.
FixedSHA string `json:"fixed_sha,omitempty"`
}
PRState is what a session remembers about its pull request.
type PRTarget ¶ added in v0.7.0
type PRTarget struct {
Base, Remote, Branch string
}
PRTarget is where the session branch goes.
type PluginRequest ¶ added in v0.6.0
type PluginRequest struct {
Name string `json:"name"`
Reason string `json:"reason,omitempty"`
Status string `json:"status"`
}
PluginRequest is a catalog plugin the lead asked for. Status is pending until the user answered, then installed (also for an enabled one) or declined.
type PollResult ¶ added in v0.7.0
type PollResult struct {
HeadSHA string
Passed bool // every check passed (and there is at least one)
Failed []string // names of the failing checks
CIFix *FixRequest // a new CI fix node is due
ReviewFix *FixRequest // a new review fix node is due
Exhausted bool // checks fail on a new head but max_ci_fixes is used up
NoChecks bool // the pull request has no checks at all (yet)
}
PollResult is what one poll found.
type Proposal ¶ added in v0.7.0
type Proposal struct {
Action string `json:"action"`
ID string `json:"id,omitempty"` // change, cancel
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Role string `json:"role,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
// SetDeps is true when the lead gave depends_on, which for a change
// replaces the dependencies (also with an empty list).
SetDeps bool `json:"set_deps,omitempty"`
Reason string `json:"reason,omitempty"` // cancel
}
Proposal is one change the lead suggests to the graph.
type ReplyResult ¶ added in v0.7.0
type ReplyResult struct {
State ReplyState
Attempt int // number of the attempt the reply starts (or will start)
Reason string // why a waiting node does not run yet
}
ReplyResult is the outcome of Engine.Reply.
type ReplyState ¶ added in v0.7.0
type ReplyState int
ReplyState says what a reply did.
const ( // ReplyStarted: a new attempt of the node is running. ReplyStarted ReplyState = iota // ReplyQueued: the node is running; the reply starts a new attempt when // the run ends. ReplyQueued // ReplyWaiting: the node is ready for its new attempt but cannot start yet // (see ReplyResult.Reason); it starts like any todo node. ReplyWaiting )
type Result ¶
type Result struct {
Summary string
Files []string // written from the worker's explicit file blocks
Observed []string // new or changed on disk during the run, by the agent's own tools
// FileStats are the lines added and removed per file; set only when the
// node ran in its own worktree.
FileStats []FileStat
// Commit is the node's own commit; set only when the node ran in its own
// worktree and changed something.
Commit string
Warnings []string
// Report is the worker's closing report; the zero value (no Status) for a
// node that has none, such as Build & test.
Report Report
}
Result is the outcome of a successful node run.
type Review ¶ added in v0.7.0
type Review struct {
Round int `json:"round"`
At time.Time `json:"at"`
Note string `json:"note,omitempty"`
Proposals []Proposal `json:"proposals,omitempty"`
Applied []AppliedProposal `json:"applied,omitempty"`
Skipped []SkippedProposal `json:"skipped,omitempty"`
State string `json:"state"` // pending | applied | rejected | empty
}
Review is one lead review kept in the session.
type ReviewInput ¶ added in v0.7.0
type ReviewInput struct {
Task string
Summary string // the session summary; "" for none
Graph *Graph
Roles []Role
// Detail returns the full detail of an activity (Engine.ActivityDetail); nil
// uses the stored details.
Detail func(nodeID, actID string) (string, bool)
}
ReviewInput is what the lead sees when it reviews a batch.
type ReviewItem ¶ added in v0.7.0
type ReviewItem struct {
Key string // "c<id>" for a line comment, "r<id>" for a review
Text string // "path:line — body" or "review — body"
}
ReviewItem is one piece of review feedback.
type ReviewResult ¶ added in v0.7.0
ReviewResult is what the lead answered.
func ParseReview ¶ added in v0.7.0
func ParseReview(raw string) ReviewResult
ParseReview reads the lead's answer: a JSON object, bare or in a code fence, with "note" and "proposals". An answer that cannot be read gives no proposals and a note saying so.
func RunReview ¶ added in v0.7.0
func RunReview(ctx context.Context, r runner.LLMRunner, model string, in ReviewInput, onToken func(string)) (ReviewResult, runner.TokenUsage, error)
RunReview asks the lead to review the graph and parses the answer. The returned usage is what the call cost.
type Role ¶
type Role struct {
Name string
Description string
Builtin bool
ReadOnly bool // reviews and reports only; never writes files
Agent config.AgentConfig
UserSkills []string // file-based skills (.decsr/skills/<name>.md)
Plugin bool // defined by a plugin agent file, never saved to a config
Prompt string // the role prompt of a plugin role
}
Role is a named agent persona: a description plus the runner settings.
type Session ¶ added in v0.4.0
type Session struct {
ID string `json:"id"` // time-sortable: 20261113-104512-<4 hex>
Title string `json:"title"` // first task's graph title; "" until then
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Transcript []Line `json:"transcript,omitempty"` // capped at 500 lines (oldest dropped)
Summary string `json:"summary,omitempty"` // compacted history
NextID int `json:"next_id,omitempty"` // next T number; never reused
Graph *Graph `json:"graph,omitempty"`
In int `json:"input_tokens,omitempty"` // lead usage for the session
Out int `json:"output_tokens,omitempty"` // lead usage for the session
PR *PRState `json:"pr,omitempty"` // pull request of the session branch
BudgetUSD float64 `json:"budget_usd,omitempty"` // /budget override of workspace.budget_usd; 0 = use the config
Issue *IssueRef `json:"issue,omitempty"` // issue the session was started from
Notes []DiffNote `json:"notes,omitempty"` // review notes on node diffs, not sent yet
Autonomy int `json:"autonomy,omitempty"` // /autonomy override of workspace.autonomy; 0 = use the config
AutoFixes int `json:"auto_fixes,omitempty"` // fix nodes added automatically after a failed Build & test
// Coordinator is the /coordinator override of workspace.coordinator; nil = use the config.
Coordinator *bool `json:"coordinator,omitempty"`
// Reviews are the lead's batch reviews, oldest first, at most MaxReviews.
Reviews []Review `json:"reviews,omitempty"`
// InboxDismissed are the IDs of the inbox info items the user cleared with x.
InboxDismissed []string `json:"inbox_dismissed,omitempty"`
}
Session is one conversation in one project: transcript, running summary and one graph. It is stored in <project>/.decsr/sessions/<id>.json.
func LoadSession ¶ added in v0.4.0
LoadSession reads one session of the project. The graph gets the same checks as Load; nodes saved as running come back as todo.
func MigrateLegacy ¶ added in v0.4.0
MigrateLegacy wraps the old .decsr/workspace.json in a session, saves it and renames the old file to workspace.json.migrated. It returns (nil, nil) when there is no old file or the project already has sessions.
func NewSession ¶ added in v0.4.0
func NewSession() *Session
NewSession returns an empty session with a fresh ID. IDs are unique within the process even when created in the same second.
type SessionInfo ¶ added in v0.4.0
type SessionInfo struct {
ID, Title string
UpdatedAt time.Time
Todo, Running, Done, Failed int
Waiting int
Path string
}
SessionInfo is the listing entry of a saved session.
func ListSessions ¶ added in v0.4.0
func ListSessions(projectRoot string) []SessionInfo
ListSessions returns the project's sessions, newest first. Unreadable or corrupt or oversized (over 8 MB) files and non-session files are skipped.
type SkippedProposal ¶ added in v0.7.0
SkippedProposal is a proposal that is not valid, with the reason.
type SpecFeature ¶ added in v0.7.0
SpecFeature is a feature directory with open tasks, found by DetectSpec.
func DetectSpec ¶ added in v0.7.0
func DetectSpec(root string) (SpecFeature, bool)
DetectSpec finds the most recently modified specs/*/tasks.md under root that has an open task. ok is false when there is none.
type SpecImport ¶ added in v0.7.0
type SpecImport struct {
Feature string // graph title
Dir string // feature dir relative to the project root, slash separated
Tasks string // tasks.md relative to the project root, slash separated; "" = Dir/tasks.md
Phase int // 0 = every phase, else only that phase number
HasQA bool // the qa role is defined; test tasks suggest it
}
SpecImport tells BuildSpecGraph what to import.
type SpecList ¶ added in v0.7.0
type SpecList struct {
Tasks []SpecTask
}
SpecList is a parsed tasks.md.
func ParseSpecKit ¶ added in v0.7.0
ParseSpecKit reads the text of a tasks.md. Tasks before any "##" heading belong to phase 0.
type SpecRef ¶ added in v0.7.0
type SpecRef struct {
File string `json:"file"` // tasks.md relative to the project root, slash separated
TaskID string `json:"task_id"` // "T003"
}
SpecRef names the Spec Kit task a node was imported from.
type SpecResult ¶ added in v0.7.0
type SpecResult struct {
Graph *Graph
Imported int
Skipped int // done tasks left out
Phases int // phases with an imported task
}
SpecResult is the graph with the counts for the chat line.
func BuildSpecGraph ¶ added in v0.7.0
func BuildSpecGraph(list SpecList, o SpecImport) SpecResult
BuildSpecGraph turns the open tasks of list into work nodes T1, T2, … (the session renumbers them on append).
Dependencies: a task depends on every imported task of the previous imported phase; inside a phase a task without [P] depends on the previous task and on the run of [P] tasks right before it, a [P] task on the previous phase only; "(depends on T012)" in the text adds that task when it is imported.
type SpecTask ¶ added in v0.7.0
type SpecTask struct {
ID string // "T001", "" when the line has none
Parallel bool // carries [P]
Story string // "US1", "" when none
Text string // description without the ID and markers
Line string // the task line without checkbox, as written
Done bool
Phase int // the phase number (from "Phase N", else the order)
Name string // the phase heading
Needs []string
}
SpecTask is one task line of a Spec Kit tasks.md.
type SplitOptions ¶ added in v0.6.0
type SplitOptions struct {
Plugins plugins.Set
Catalog []plugins.CatalogEntry
}
SplitOptions tells the lead which plugin skills exist: the installed plugins and the catalog it may suggest from. The zero value offers none.
type Status ¶
type Status string
Status is the lifecycle state of a node.
const ( StatusTodo Status = "todo" StatusRunning Status = "running" StatusDone Status = "done" StatusFailed Status = "failed" // StatusWaiting is a node that ended with a question or a blocked report: // its changes are merged, but it is not done. A reply starts its next attempt. // With Node.Limit set it instead waits for a provider usage limit to lift. StatusWaiting Status = "waiting" )