workspace

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package workspace holds the node-workspace graph model, its storage, roles, the task-split prompt/parser and the scheduler.

Index

Constants

View Source
const (
	ReportDone     = agent.ReportDone
	ReportBlocked  = agent.ReportBlocked
	ReportQuestion = agent.ReportQuestion
)

Report statuses.

View Source
const (
	PluginPending   = "pending"
	PluginInstalled = "installed"
	PluginDeclined  = "declined"
)

Plugin request states.

View Source
const (
	IsolationWorktree = "worktree"
	IsolationShared   = "shared"
)

Isolation modes of workspace.isolation. "" means auto.

View Source
const (
	SourceGitHub = "github"
	SourceBeads  = "beads"
)

Issue sources.

View Source
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
)
View Source
const (
	ActionAdd    = "add"
	ActionChange = "change"
	ActionCancel = "cancel"
)

Proposal actions.

View Source
const (
	ReviewPending  = "pending"
	ReviewApplied  = "applied"
	ReviewRejected = "rejected"
	ReviewEmpty    = "empty"
)

Review states.

View Source
const DefaultBudgetWarnPct = 80

DefaultBudgetWarnPct is the warn threshold when none is configured.

View Source
const FileName = "workspace.json"

FileName is the graph file inside .decsr.

View Source
const FixExcerptChars = 8000

FixExcerptChars is the budget of the "What failed" excerpt in a fix node.

View Source
const MaxLimitRetries = 3

MaxLimitRetries is how many automatic retries a limited node gets before it fails with the limit message.

View Source
const ReplyContextChars = 8000

ReplyContextChars is the budget of the previous-attempt excerpt in the context of a reply attempt.

Variables

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

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

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

func BudgetReachedMsg(spent, limit float64) string

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

func BuildSplitPrompt(task string, roles []Role, projectContext string) string

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

func CompactSummary(prev string, folded []*Node) string

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

func CountSessions(projectRoot string) int

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

func DeleteSession(projectRoot, id string) error

DeleteSession removes a saved session.

func ExecRunner added in v0.7.0

func ExecRunner(ctx context.Context, dir, name string, args ...string) (string, error)

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

func FindSpecTasks(root, arg string) (string, error)

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

func FixExcerpt(failed []*Node, maxChars int) string

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

func HasMergedNode(root, session string) bool

HasMergedNode reports whether at least one node of the session was merged into the session branch, that is, whether the session changed anything.

func IsFixID added in v0.7.0

func IsFixID(id string) bool

IsFixID reports whether id is the ID of a fix node ("F" and digits).

func MaxParallel

func MaxParallel(cfg config.Config) int

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

func MergeSession(root, session string) (string, error)

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

func PRBody(s Session) string

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

func PRTitle(s Session) string

PRTitle is the first line of the session's first task, at most 72 characters.

func ParseIssueRef added in v0.7.0

func ParseIssueRef(ref string) (source, arg string, err error)

ParseIssueRef tells which tracker ref names: digits, "#N" and a GitHub issue URL are GitHub issues, anything else is a bead id.

func Reconcile

func Reconcile(g *Graph, cfg config.Config)

Reconcile clears the assigned role of nodes whose role no longer exists.

func RemoveSessionWorktrees added in v0.7.0

func RemoveSessionWorktrees(root, session string) error

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

func Sanitize(s string) string

Sanitize is SanitizeText for single-line text: every line break becomes a space.

func SanitizeText added in v0.4.0

func SanitizeText(s string) string

SanitizeText removes terminal escape sequences (CSI, OSC, …) and control characters from untrusted text. Newlines are kept and tabs become spaces.

func Save

func Save(path string, g *Graph) error

Save writes g to path atomically (temp file, then rename) with mode 0o600.

func SessionBranch added in v0.7.0

func SessionBranch(session string) string

SessionBranch is the integration branch of a session.

func SessionsDir added in v0.4.0

func SessionsDir(projectRoot string) string

SessionsDir is <projectRoot>/.decsr/sessions.

func SpecFeatureName added in v0.7.0

func SpecFeatureName(specText, dirName string) string

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

func SpecUntracked(root, dir string) []string

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

func SuggestSpecRole(text string, hasQA bool) string

SuggestSpecRole is "qa" for a task that writes tests when the role exists, else "coder".

func TickSpecTask added in v0.7.0

func TickSpecTask(data []byte, id string) (out []byte, changed bool, err error)

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.

func (Budget) WarnShare added in v0.7.0

func (b Budget) WarnShare() int

WarnShare is the warn threshold as a percentage, defaulted.

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

type CmdRunner func(ctx context.Context, dir, name string, args ...string) (string, error)

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

type CostFunc func(runner, model string, in, out int) (usd float64, known bool)

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

type Diff struct {
	Files []DiffFile
	Note  string
}

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

func NodeDiff(root string, n *Node, iso *Isolator) (Diff, error)

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

func SessionDiff(root, session string) (Diff, error)

SessionDiff is everything the session branch holds that the current branch of root does not: git diff HEAD...decsr/<session>.

func (Diff) Totals added in v0.7.0

func (d Diff) Totals() (added, removed int)

Totals is the lines added and removed over all files.

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.

func ParseDiff added in v0.7.0

func ParseDiff(text string) []DiffFile

ParseDiff parses unified diff text (git diff or git show output).

type DiffLine added in v0.7.0

type DiffLine struct {
	Kind  byte
	OldNo int
	NewNo int
	Text  string
}

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 NewEngine

func NewEngine(g *Graph, ex Executor, maxParallel int, savePath string) *Engine

NewEngine creates an engine over g. savePath "" disables persistence.

func NewEngineWithSave added in v0.4.0

func NewEngineWithSave(g *Graph, ex Executor, maxParallel int, save func(*Graph) error) *Engine

NewEngineWithSave creates an engine over g that persists the graph through save after every change. A nil save disables persistence.

func (*Engine) AcceptSuggestions

func (e *Engine) AcceptSuggestions(defined func(string) bool) int

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

func (e *Engine) ActivityDetail(nodeID, activityID string) (string, bool)

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

func (e *Engine) AddCIFix(title, desc, role string) string

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

func (e *Engine) AddFix(checkID string) (string, error)

AddFix adds a fix node for a failed check node and returns its ID.

func (*Engine) AddWork added in v0.7.0

func (e *Engine) AddWork(title, desc, role string, nextID int) (string, int)

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

func (e *Engine) Assign(id, role string) error

Assign sets the role of a todo or failed work node. "" unassigns.

func (*Engine) Auto

func (e *Engine) Auto() bool

Auto reports whether auto mode is on.

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

func (e *Engine) Events() <-chan Event

Events returns the event stream. It is never closed.

func (*Engine) Limited added in v0.7.0

func (e *Engine) Limited() []*Node

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

func (e *Engine) Replace(mut func(g *Graph)) error

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

func (e *Engine) RetryLimited(id string) error

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

func (e *Engine) RetryLimitedNow(id string) error

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

func (e *Engine) ReviewRounds() int

ReviewRounds is the number of lead reviews of the current task.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, id string) error

Run starts one node now.

func (*Engine) RunAll

func (e *Engine) RunAll(ctx context.Context)

RunAll turns auto mode on and starts every runnable node, then keeps starting nodes as others finish.

func (*Engine) Running

func (e *Engine) Running() int

Running returns the number of nodes currently running.

func (*Engine) SetBudget added in v0.7.0

func (e *Engine) SetBudget(f func() Budget)

SetBudget sets the budget the engine reads before it starts a node and when usage changes.

func (*Engine) SetCost added in v0.7.0

func (e *Engine) SetCost(f CostFunc)

SetCost sets how node usage is priced. Without it no node cost is known.

func (*Engine) SetSkills added in v0.6.0

func (e *Engine) SetSkills(id string, skills []string) error

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

func (e *Engine) Snapshot() *Graph

Snapshot returns a deep copy of the graph.

func (*Engine) StartReview added in v0.7.0

func (e *Engine) StartReview() int

StartReview counts a lead review of the current task and returns the number of reviews so far.

func (*Engine) Stop

func (e *Engine) Stop(id string)

Stop cancels one running node; it ends failed with Error "stopped".

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

func (e *Engine) Waiting() []*Node

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

func (e *Engine) WillAutoRun(id string) bool

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

func NewExecutor(root string, cfg config.Config, projectContext string) Executor

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

func Load(path string) (*Graph, error)

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

func ParseSplit(task, output string, roles []Role) (*Graph, error)

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

func ParseSplitWith(task, output string, roles []Role, existing []string) (*Graph, error)

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

func (g *Graph) AddCIFix(title, desc string) *Node

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

func (g *Graph) AddCheck(commands []string) *Node

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

func (g *Graph) AddCheckDeferred() *Node

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

func (g *Graph) AddFix(checkID, failure string) (*Node, error)

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

func (g *Graph) AddFixExcerpt(checkID, failure, excerpt string) (*Node, error)

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

func (g *Graph) AddWork(title, desc, role string, nextID int) (*Node, int)

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

func (g *Graph) Append(add *Graph, nextID int) (newNext int, idMap map[string]string)

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

func (g *Graph) Assigned(n *Node) bool

Assigned reports whether a node may run: check nodes always, work nodes once a role is set.

func (*Graph) Blockers

func (g *Graph) Blockers(id string) []string

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

func (g *Graph) Clone() *Graph

Clone returns a deep copy.

func (*Graph) Compact added in v0.4.0

func (g *Graph) Compact() (folded []*Node)

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

func (g *Graph) CountLimited() int

CountLimited returns how many nodes wait for a usage limit to lift.

func (*Graph) CountWaiting added in v0.7.0

func (g *Graph) CountWaiting() int

CountWaiting returns how many nodes are waiting for a reply.

func (*Graph) Counts

func (g *Graph) Counts() (todo, running, done, failed int)

Counts returns how many nodes are in each status.

func (*Graph) Layers

func (g *Graph) Layers() [][]*Node

Layers groups nodes by dependency depth (1 + the deepest dependency), keeping Nodes order inside a layer. The graph must be acyclic.

func (*Graph) Node

func (g *Graph) Node(id string) *Node

Node returns the node with the given ID, or nil.

func (*Graph) PendingPlugins added in v0.6.0

func (g *Graph) PendingPlugins() []PluginRequest

PendingPlugins returns the plugin requests nobody answered yet.

func (*Graph) Runnable

func (g *Graph) Runnable() []*Node

Runnable returns the todo, assigned, unblocked nodes in Nodes order.

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

func (g *Graph) SetPluginStatus(name, status string) bool

SetPluginStatus sets the status of the request for name; false when there is none.

func (*Graph) SpentUSD added in v0.7.0

func (g *Graph) SpentUSD() float64

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

func (g *Graph) UnpricedNodes() []string

UnpricedNodes lists the IDs of nodes that used tokens without a known price.

func (*Graph) Validate

func (g *Graph) Validate() error

Validate checks unique non-empty IDs, existing dependencies, no self dependency and no cycle.

type Hunk added in v0.7.0

type Hunk struct {
	Header string
	Lines  []DiffLine
}

Hunk is one "@@" block.

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

func NewIsolator(root, session, mode string) *Isolator

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) Branch added in v0.7.0

func (i *Isolator) Branch() string

Branch is the integration branch of the session.

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

func (i *Isolator) Discard(id string)

Discard drops the worktree and branch of a node without merging.

func (*Isolator) Finish added in v0.7.0

func (i *Isolator) Finish(id, title string) error

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

func (i *Isolator) FinishCommit(id, title string) ([]FileStat, string, error)

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

func (i *Isolator) FinishStats(id, title string) ([]FileStat, error)

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

func (i *Isolator) IntegrationDir() (string, bool)

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

func (i *Isolator) IntegrationRoot() (string, error)

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

func (i *Isolator) NodeDir(id string) (string, bool)

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

func (*Isolator) Start added in v0.7.0

func (i *Isolator) Start(id string) (string, []string, error)

Start creates the worktree of a node from the current integration tip and returns the project root inside it, plus warnings to show (once). A stale worktree or branch of the node from an earlier run is replaced.

func (*Isolator) Tracked added in v0.7.0

func (i *Isolator) Tracked(rel string) bool

Tracked reports whether rel (relative to the project root) is tracked by git.

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

func FetchIssue(ctx context.Context, root, ref string, run CmdRunner) (Issue, error)

FetchIssue loads the issue ref names. root is the project; run is the command runner (nil = ExecRunner).

func (Issue) Ref added in v0.7.0

func (i Issue) Ref() *IssueRef

Ref is the part of the issue a session keeps.

func (Issue) Summary added in v0.7.0

func (i Issue) Summary() string

Summary is the one-line form: "Issue #42: Fix flaky login test".

func (Issue) Task added in v0.7.0

func (i Issue) Task() string

Task is the text sent to the lead.

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 Kind

type Kind string

Kind distinguishes LLM work nodes from the build/test check node.

const (
	KindWork  Kind = "work"
	KindCheck Kind = "check"
)

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

type Line struct {
	Who  string    `json:"who"`
	Text string    `json:"text"`
	At   time.Time `json:"at"`
}

Line is one transcript entry. Who is "you", "lead", "system" or "error".

type NewRole

type NewRole struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

NewRole is a role the lead proposed that is not defined yet.

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

func (n *Node) AllFiles() []string

AllFiles is Files followed by the Observed paths not already in Files.

func (*Node) AttemptNumber added in v0.7.0

func (n *Node) AttemptNumber() int

AttemptNumber is the number of the current attempt (1 for the first).

func (*Node) Limited added in v0.7.0

func (n *Node) Limited() bool

Limited reports whether n is a waiting node that hit a usage limit (as opposed to one that waits for an answer).

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

func (c *PRClient) Checks(ctx context.Context, number int) ([]Check, error)

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

func (c *PRClient) EnsurePR(ctx context.Context, t PRTarget, sess Session) (PRResult, error)

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) HeadSHA added in v0.7.0

func (c *PRClient) HeadSHA(ctx context.Context, number int) (string, error)

HeadSHA is the head commit of the pull request.

func (*PRClient) NewFeedback added in v0.7.0

func (c *PRClient) NewFeedback(ctx context.Context, st PRState) ([]ReviewItem, error)

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

func (c *PRClient) Poll(ctx context.Context, st PRState) (PRState, PollResult, error)

Poll looks at the checks and the review feedback once. It returns the updated state; the caller saves it and adds the nodes.

func (*PRClient) Prepare added in v0.7.0

func (c *PRClient) Prepare(ctx context.Context) (PRTarget, error)

Prepare checks what /pr needs and returns the target: a merged node, a logged-in gh, the remote and a base branch that differs from the session branch. "Isolation active" and "no node running" are the caller's checks.

func (*PRClient) Push added in v0.7.0

func (c *PRClient) Push(ctx context.Context, t PRTarget) error

Push publishes the session branch. It never forces: the branch only gains merge commits, so a rejected push means someone else pushed to it, and their commits must not be overwritten.

type PRConfig added in v0.7.0

type PRConfig struct {
	Base, Remote string
	PollSeconds  int
	MaxCIFixes   int
}

PRConfig is the part of the configuration the loop needs.

func (PRConfig) MaxFixes added in v0.7.0

func (c PRConfig) MaxFixes() int

MaxFixes is the number of CI fix rounds allowed.

func (PRConfig) PollInterval added in v0.7.0

func (c PRConfig) PollInterval() time.Duration

PollInterval is the polling period: 60 s by default, at least 15 s.

type PRResult added in v0.7.0

type PRResult struct {
	State   PRState
	Created bool
}

PRResult is the outcome of EnsurePR.

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 Report added in v0.7.0

type Report = agent.Report

Report is the structured end of a worker's reply (see agent.Report).

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

type ReviewResult struct {
	Note      string
	Proposals []Proposal
}

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.

func FindRole

func FindRole(cfg config.Config, name string) (Role, bool)

FindRole looks a role up by name.

func Roles

func Roles(cfg config.Config) []Role

Roles returns the built-in roles in config.BuiltinRoles order, then custom roles sorted by name, then plugin roles ("<plugin>:<agent>") sorted by name. A custom role without runner/model inherits the pm role's runner, model and effort.

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

func LoadSession(projectRoot, id string) (*Session, error)

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

func MigrateLegacy(projectRoot string) (*Session, error)

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.

func (*Session) AddLine added in v0.4.0

func (s *Session) AddLine(who, text string)

AddLine appends a transcript line, dropping the oldest beyond 500.

func (*Session) Save added in v0.4.0

func (s *Session) Save(projectRoot string) error

Save writes the session atomically with mode 0o600 and sets UpdatedAt.

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

type SkippedProposal struct {
	Proposal
	Reason string `json:"skip_reason"`
}

SkippedProposal is a proposal that is not valid, with the reason.

type SpecFeature added in v0.7.0

type SpecFeature struct {
	Dir  string // "specs/003-login"
	Open int    // open tasks
}

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

func ParseSpecKit(text string) SpecList

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

Jump to

Keyboard shortcuts

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