workspace

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 26 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 (
	PluginPending   = "pending"
	PluginInstalled = "installed"
	PluginDeclined  = "declined"
)

Plugin request states.

View Source
const FileName = "workspace.json"

FileName is the graph file inside .decsr.

Variables

This section is empty.

Functions

func BuildSplitPrompt

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

BuildSplitPrompt assembles the lead's system prompt.

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 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 Reconcile

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

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

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 SessionsDir added in v0.4.0

func SessionsDir(projectRoot string) string

SessionsDir is <projectRoot>/.decsr/sessions.

Types

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

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"
	EventUsage   EventType = "usage"
	EventDone    EventType = "done"
	EventFailed  EventType = "failed"
)

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 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 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:"-"`
}

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

func (g *Graph) Validate() error

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

type Kind

type Kind string

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

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

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"`
	Files         []string  `json:"files,omitempty"`
	Observed      []string  `json:"observed,omitempty"` // changed on disk by the agent's own tools
	Warnings      []string  `json:"warnings,omitempty"`
	Skills        []string  `json:"skills,omitempty"` // plugin skill ids the lead chose for this node
	Error         string    `json:"error,omitempty"`
	InputTokens   int       `json:"input_tokens,omitempty"`
	OutputTokens  int       `json:"output_tokens,omitempty"`
	Estimated     bool      `json:"estimated,omitempty"`
	StartedAt     time.Time `json:"started_at,omitempty"`
	EndedAt       time.Time `json:"ended_at,omitempty"`
}

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.

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 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
	Warnings []string
}

Result is the outcome of a successful node run.

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
}

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

Jump to

Keyboard shortcuts

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