workflow

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 16 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

Policy cache and last-known-good resolution (实施计划 M3.5, 方案 §5.3).

Every resolve re-validates the current policy file. A successful parse refreshes the project-local last-known-good snapshot (.devsys/.cache/workflows/<id>.md); a failing parse falls back to it so read paths keep working while dispatch is blocked on the configuration error.

Declarative condition evaluation for workflow transitions (方案 §5.3, 实施计划 M3.6). Conditions are parsed and validated at policy load time against a fixed field whitelist; evaluation is a pure function over Facts. There are no free variables, no compound expressions and no code: an unknown field or operator is a policy error, not a runtime surprise.

Package workflow parses and validates project workflow policy files (.devsys/workflows/<id>.md: YAML front matter plus a prompt body, 方案 §5.3, 实施计划 M3.1).

Parsing is strict and located: structural, type, required and cross-reference defects are collected with file, line, field and reason — the rendering internal/config established for managed files — and a file with any error-severity issue yields no policy. Unknown keys are recorded as warnings instead of errors so a policy written for a newer build stays loadable (实施计划 M3.1: 记录但不崩).

Step selection for workflow instances (方案 §5.3, 实施计划 M3.6): the candidates out of the current step with their condition outcomes, in declaration order. Pure functions over a parsed Policy and Facts.

Index

Constants

View Source
const (
	SourceCurrent       = "current"
	SourceLastKnownGood = "last-known-good"
)

Resolution sources.

View Source
const (
	OpEqual    = "=="
	OpNotEqual = "!="
	OpLess     = "<"
	OpGreater  = ">"
	OpIn       = "in"
	OpExists   = "exists"
)

Condition operators.

Variables

This section is empty.

Functions

func ExpandEnv

func ExpandEnv(raw string, lookup func(string) (string, bool)) (string, error)

ExpandEnv resolves $NAME and ${NAME} references in raw at use time. Every reference must resolve; undefined names fail with a classified error listing them — a missing secret is never silently expanded to "". $$ is a literal dollar, and a $ before a non-name character (e.g. "$5") stays literal. Callers must not persist the resolved values (方案 §5.3: 密钥不落盘).

func Parse

func Parse(rel string, data []byte) (*Policy, []Issue)

Parse parses one policy file. rel is the slash-separated path below .devsys/ (used for reporting and to require id == basename). A policy is returned only when no error-severity issue was found; warnings accompany a valid policy.

func Render

func Render(body string, vars map[string]string) (string, error)

Render expands {{name}} references in body. Whitespace inside the braces is allowed ({{ workitem.id }}); names are dot-separated identifiers. Every reference must resolve: missing names fail with a classified error listing them, and never render as empty strings. Malformed brace structure is a syntax error. On failure the partial output is discarded.

Types

type Concurrency

type Concurrency struct {
	Global    int
	PerStatus map[string]int
}

Concurrency caps concurrent execution (方案 §5.3).

type Condition

type Condition struct {
	Field string
	Op    string
	// Literals are the compared values: exactly one for == != < >, one or
	// more for in.
	Literals []string
	// Text is the original expression, kept for reporting.
	Text string
}

Condition is one parsed, load-validated transition condition.

func (*Condition) Eval

func (c *Condition) Eval(f Facts) bool

Eval reports whether the condition holds for facts.

type Facts

type Facts struct {
	ID                  string
	Status              string
	Type                string
	Priority            int
	ClarificationNeeded bool
	ApprovalRequired    bool
	ParentID            string
}

Facts is the whitelisted work item fact set conditions evaluate against.

func FactsOf

func FactsOf(wi *domain.WorkItem) Facts

FactsOf projects a work item onto the condition fact set.

type FileResult

type FileResult struct {
	// File is the slash-separated path below .devsys/, e.g.
	// "workflows/quick-fix.md".
	File string `json:"file"`
	// Policy is non-nil only when the file parsed without error-severity
	// issues.
	Policy *Policy `json:"-"`
	// Issues are the located errors and warnings this file produced.
	Issues []Issue `json:"issues,omitempty"`
}

FileResult is the outcome for one entry below .devsys/workflows/.

func Load

func Load(root string) []FileResult

Load reads and validates every policy under .devsys/workflows/ below root. It reads plainly — no lock, no recovery, no writes — so it also works on state write commands must refuse (same contract as config.Diagnose). Entries are returned in file name order; non-.md entries are reported as warnings, not failures.

type Gate

type Gate struct {
	RequireArtifacts    []string
	RequireMinArtifacts int
	RequireComment      bool
	RequireApproval     bool
}

Gate is the stage gate for one work item status (方案 §4.7).

type GateEvidence

type GateEvidence struct {
	// ArtifactNames are the names of artifacts related to the work item.
	ArtifactNames []string
	// CommentCount is the number of comment events on the work item.
	CommentCount int
	// ApprovalReady reports that an approved, unconsumed approval exists for
	// the stage. Until M3.7 wires the lookup it stays false, so a gate that
	// requires approval fails closed (审批前不放行).
	ApprovalReady bool
	// ApprovalNote explains a missing approval when the application layer can
	// (today: the previous approval was invalidated by 方案 §4.9). It is
	// appended to the unmet-requirement text and never changes the verdict.
	ApprovalNote string
}

GateEvidence is the evidence a stage gate consumes (方案 §4.7). The application layer collects it; approvals are wired by M3.7.

type GateResult

type GateResult struct {
	Stage string
	// Checked is false when the policy declares no gate for the stage.
	Checked bool
	// Exempt is true when the stage is listed in gates.exempt_stages.
	Exempt bool
	// Allowed is the overall outcome; when false, Missing lists every unmet
	// requirement in declaration order.
	Allowed bool
	Missing []string
}

GateResult is the outcome of checking one stage gate.

type Gates

type Gates struct {
	ExemptStages []string
	Stages       map[string]Gate
}

Gates is the gates section: statuses exempt from gate checks plus per-status gates.

type Hook

type Hook struct {
	Command        string
	TimeoutSeconds int
}

Hook is one workspace lifecycle hook command (方案 §4.8).

type Input

type Input struct {
	Required []string
	Optional []string
}

Input lists the context a policy expects when a work item starts (方案 §5.3).

type Issue

type Issue struct {
	File     string   `json:"file"`
	Line     int      `json:"line,omitempty"`
	Field    string   `json:"field,omitempty"`
	Reason   string   `json:"reason"`
	Severity Severity `json:"severity"`
}

Issue is one located defect or recorded observation in a policy file.

func (Issue) String

func (i Issue) String() string

String renders the location as `file[:line][: field]: reason`, matching the config.Problem rendering.

type Limits

type Limits struct {
	MaxAttempts           int
	RunTimeoutSeconds     int
	StallThresholdSeconds int
	BackoffMaxSeconds     int
}

Limits carries attempt and stagnation bounds (方案 §4.8/§5.3).

type Policy

type Policy struct {
	// File is the slash-separated path below .devsys/ (e.g.
	// "workflows/quick-fix.md").
	File string

	ID      string
	Name    string
	Version int

	Input           Input
	Steps           []Step
	Transitions     []Transition
	ApprovalPoints  []string
	CompletionRules []string
	Gates           Gates
	Hooks           map[string]Hook
	Concurrency     Concurrency
	Limits          Limits
	QualityGate     QualityGate
	// OnReject is "block" or "regress:<status>"; it defaults to "block" (§4.9).
	OnReject string

	// Body is the prompt template below the front matter, verbatim.
	Body string
}

Policy is one parsed and validated workflow policy.

func (*Policy) CheckGate

func (p *Policy) CheckGate(stage string, ev GateEvidence) GateResult

CheckGate evaluates the gate guarding entry into stage (方案 §4.7: a gate declares what must exist before a work item advances into that status). Stages listed in gates.exempt_stages are allowed without checks, as are stages without a declared gate. The check never fails open: every unmet requirement is reported.

func (*Policy) NextStep

func (p *Policy) NextStep(step string, facts Facts) (StepCandidate, bool)

NextStep returns the first satisfied candidate in declaration order.

func (*Policy) QualityGateBlocks

func (p *Policy) QualityGateBlocks(res QualityResult) bool

QualityGateBlocks reports whether the score is below the policy's declared threshold. An absent quality_gate leaves MinScore at zero, which never blocks.

func (*Policy) Render

func (p *Policy) Render(vars map[string]string) (string, error)

Render expands the policy's prompt template with vars (实施计划 M3.2).

func (*Policy) StepByID

func (p *Policy) StepByID(id string) (Step, bool)

StepByID returns the declared step with the given id.

func (*Policy) StepCandidates

func (p *Policy) StepCandidates(step string, facts Facts) []StepCandidate

StepCandidates lists every declared transition out of step, in declaration order, with its condition evaluated against facts. Unconditional edges are always satisfied.

type QualityGate

type QualityGate struct {
	MinScore int
}

QualityGate is the deterministic claim-time quality threshold (方案 §4.7).

type QualityInput

type QualityInput struct {
	Title              string
	Description        string
	AcceptanceCriteria []string
}

QualityInput is the claim-time evidence the deterministic quality gate scores (方案 §4.7). Scoring uses length, structure and language markers only — never a model call.

type QualityResult

type QualityResult struct {
	Score        int
	Improvements []string
}

QualityResult is the deterministic quality score with the scored-zero components named as improvements.

func ScoreQuality

func ScoreQuality(in QualityInput) QualityResult

ScoreQuality computes the claim-time quality score (0..100) from title, description and acceptance criteria. Every component is a deterministic text measure; the improvements list names the components that scored zero so a blocked claim can tell the caller what to add.

type RenderError

type RenderError struct {
	Kind RenderErrorKind `json:"kind"`
	// Variables are the missing names (unknown_variable, env_undefined),
	// unique and sorted.
	Variables []string `json:"variables,omitempty"`
	// Line is the 1-based line inside the rendered template (template_syntax,
	// 0 when not applicable).
	Line   int    `json:"line,omitempty"`
	Reason string `json:"reason"`
}

RenderError is the structured, classified failure of Render or ExpandEnv.

func (*RenderError) Error

func (e *RenderError) Error() string

type RenderErrorKind

type RenderErrorKind string

RenderErrorKind classifies a template or environment-reference failure (实施计划 M3.2: 渲染失败的错误分类). Callers branch on Kind with errors.As.

const (
	// RenderUnknownVariables: the template references names that were not
	// supplied. Rendering never substitutes an empty string for them.
	RenderUnknownVariables RenderErrorKind = "unknown_variable"
	// RenderSyntax: the template or environment reference is structurally
	// invalid.
	RenderSyntax RenderErrorKind = "template_syntax"
	// RenderEnvUndefined: an environment reference did not resolve.
	RenderEnvUndefined RenderErrorKind = "env_undefined"
)

type Resolution

type Resolution struct {
	ID     string
	Policy *Policy
	// Source is SourceCurrent or SourceLastKnownGood.
	Source string
	// Issue describes why the current file could not be used; nil when the
	// current file was valid.
	Issue *Issue
}

Resolution is what a policy read produced.

func Resolve

func Resolve(ctx context.Context, root, id string) (Resolution, error)

Resolve reads one policy for a consumer. The current file is parsed on every call (no mtime trust): success refreshes the last-known-good snapshot; failure falls back to the snapshot and reports the current failure. Without a usable snapshot both paths fail closed.

type Severity

type Severity string

Severity classifies one parsing issue.

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
)

type Step

type Step struct {
	ID       string
	Type     string
	Required bool
	// Status is the work item status required on entering the step; empty when
	// the step does not declare one (§5.3 附加规则).
	Status string
}

Step is one declared workflow step.

type StepCandidate

type StepCandidate struct {
	To        string `json:"to"`
	When      string `json:"when,omitempty"`
	Satisfied bool   `json:"satisfied"`
}

StepCandidate is one transition out of the current step.

type Transition

type Transition struct {
	From string
	To   string // a step id or "done"
	When string // declarative condition; empty means unconditional
	// Cond is the parsed, load-validated condition; nil when When is empty.
	Cond *Condition
}

Transition is one declared edge between steps.

Jump to

Keyboard shortcuts

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