workflow

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 19 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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckTemplateAgents

func CheckTemplateAgents(cfg *config.Config, spec Spec) error

CheckTemplateAgents reports, for a RENDERED template spec, the first step agent the step's project does not allow, naming the agents the project does allow. A built-in template defaults to agents like claude/codex that a project may not open; without this the submit only said "agent X is not allowed" with no way forward. Steps with no project / agent, an unknown project (reported by the normal submit path) and projects with an empty allowlist (everything allowed) are skipped.

Types

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine runs job-chain workflows over the host job service (design §13). All logic is moved verbatim from package job; only the receiver (Service→Engine) and host access (via ops/meta/now/metrics) change.

func NewEngine

func NewEngine(ops JobOps) *Engine

NewEngine binds the engine to a host JobOps (typically *job.Service). meta/metrics are cached (stable); now is the host clock (bound method value, stays live; tests in this package may override e.now directly).

func (*Engine) Advance

func (e *Engine) Advance(wfID string)

Advance advances a workflow when its current step's job reaches a terminal state. It is the串行推进引擎 and is designed to be called MANY times, concurrently, for the same workflow — the finish hook (one call per step-job terminal) AND the sweeper (crash recovery) both invoke it. 幂等 rests on TWO layers (plan ⭐节):

  1. every step-job carries a DETERMINISTIC request_id (stepToRequest) so the C5 unique index lets at most ONE job exist per (step, attempt);
  2. every状态转移 (推进/重试/继续) is one AdvanceStep二元组抢权 — only the winner of the conditional UPDATE on (current_step, step_attempt) proceeds.

step 序号/spec 下标对齐 (核心):wf.CurrentStep is 1-based and points at the active/just-finished step (job step_index == CurrentStep, attempt step_attempt); spec.Steps is 0-based, so the active step is spec.Steps[cur-1] and the NEXT step is spec.Steps[cur] (== 1-based step cur+1). We read (cur,att) FIRST, then抢权, then act on the locally-captured values so the index is unambiguous.

P1 失败分支 (design §6.1, D17): on a non-done terminal step, on_failure decides:

  • retry: schedule attempt+1 with backoff (set next_step_at, NO immediate start — the sweeper starts it once due, request_id兜底 idempotent);
  • continue: skip the failed step, advance to the next;
  • fail/"": v1 fail-fast (the whole workflow fails).

best-effort: failures are logged, never panic; a missed advance is re-tried by the sweeper on its next tick.

func (*Engine) AdvanceRunning

func (e *Engine) AdvanceRunning(ctx context.Context) int

AdvanceRunning is the crash-recovery sweeper body (SR304): it scans running workflows and re-drives Advance for each, picking up any whose current step finished but whose finish-hook advance never ran (process crash / missed goroutine). It is幂等 (advanceWorkflow抢推进权) so re-running it alongside the finish hook is safe — a no-op for workflows still mid-step. It returns the number of running workflows it inspected (for logging). ctx cancellation stops the scan early (serve shutdown).

func (*Engine) CancelWorkflow

func (e *Engine) CancelWorkflow(wfID string) error

CancelWorkflow stops a running workflow: it marks it cancelled (so Advance never starts another step) and cancels the currently-running step's job. It is idempotent and a no-op for an unknown or already-terminal workflow.

Order matters: set cancelled FIRST so any racing Advance (which checks status==running) bails, THEN cancel the active step's job. The cancelled step reaching terminal will fire Advance, but the running-status guard there stops it from starting the next step.

func (*Engine) ExportWorkflow

func (e *Engine) ExportWorkflow(wfID string) (Spec, bool, bool, error)

ExportWorkflow returns a workflow's Spec reconstructed from its persisted spec_json, with all credential-looking values stripped (T4.1, E18 + SR403). The returned spec is a runnable template: re-submit it (POST /v1/workflows / `workflow run`) to reproduce the chain — after filling any redacted secret back in. The bool reports whether anything was redacted (the HTTP/CLI layer surfaces it so the operator knows a placeholder must be replaced). An unknown id returns ok=false.

func (*Engine) GetWorkflow

func (e *Engine) GetWorkflow(id string) (jobstore.Workflow, bool, error)

GetWorkflow returns a workflow header by id (HTTP detail/cancel paths). The bool is false when no such workflow exists. It is a thin pass-through to the metadata store so httpapi never reaches into the unexported store.

func (*Engine) ListWorkflowEvents

func (e *Engine) ListWorkflowEvents(wfID string, sinceSeq int64) ([]jobstore.WorkflowEvent, error)

ListWorkflowEvents returns a workflow's append-only lifecycle events in seq order (P1), forwarding to the metadata store. sinceSeq > 0 returns only events after that cursor (the HTTP ?since incremental path).

func (*Engine) ListWorkflows

func (e *Engine) ListWorkflows(status string, limit int) ([]jobstore.Workflow, error)

ListWorkflows returns workflow headers, optionally filtered by status, newest first, capped at limit (<=0 => store default). HTTP list path.

func (*Engine) PickWorkflowFan

func (e *Engine) PickWorkflowFan(wfID string, stepIndex, fanIndex int) (jobstore.Workflow, error)

PickWorkflowFan records the human choice for a join=pick step and re-drives the normal workflow advance path. The chosen fan must already be terminal; no merge or push is performed here.

func (*Engine) SubmitWorkflow

func (e *Engine) SubmitWorkflow(spec Spec, callerID string) (jobstore.Workflow, error)

SubmitWorkflow validates the spec, persists a running workflow header (current_step=1, total=len(steps)) and starts the FIRST step's job. The remaining steps are started one at a time by Advance as each prior step reaches a terminal state (finish hook + sweeper, all幂等).

Validation: at least one step, and EVERY step must pass the same single-job validate() (project/agent/runner allowlist + exec gate) so a workflow never smuggles a step past单 job 准入 (安全要点). A rejected step fails the whole submit before any DB row / job is created. If step-1's Submit fails, the workflow is marked failed and the error returned.

func (*Engine) SubmitWorkflowChild

func (e *Engine) SubmitWorkflowChild(spec Spec, callerID, parentID string, parentStep, parentAtt int) (jobstore.Workflow, error)

SubmitWorkflowChild submits an inline sub-workflow bound to a parent step (P3, D19). It derives a DETERMINISTIC child workflow id from (parentID, parentStep, parentAtt) so a racing re-submit (finish hook + sweeper both re-driving the same parent step) only ever creates ONE child — the InsertWorkflow on the duplicate id fails (PK collision) and is treated as an idempotent no-op. The attempt segment lets a retried workflow-type step (on_failure=retry) spawn a FRESH child per attempt without colliding with the prior attempt's child. The child inherits the parent's caller_id (D8, quota continuity) and stores parent_workflow_id/parent_step_index so its terminal transition triggers the parent's Advance. Returns the child header (or the already-existing child on a duplicate submit).

func (*Engine) WorkflowSteps

func (e *Engine) WorkflowSteps(wfID string) ([]Step, error)

WorkflowSteps returns the per-step summary for a workflow's detail view, in step order. It reads the started step-jobs (a step not yet reached has no job row, so the list only contains started steps — the chain is strictly serial). The name is recovered from the step-job's persisted request (Title == step name).

type FanSpec

type FanSpec struct {
	Agent  string `json:"agent" yaml:"agent"`
	Runner string `json:"runner,omitempty" yaml:"runner,omitempty"`
}

FanSpec overrides the agent and runner for one ordered fan. Runner may be empty to inherit the step runner; Agent is required when Fan is used.

type JobOps

type JobOps interface {
	Submit(req job.JobRequest) (job.JobResult, error)
	Cancel(id string) error
	Validate(cfg *config.Config, req job.JobRequest, remote bool) (config.ProjectConfig, error)
	Config() *config.Config
	Meta() *jobstore.Store
	Now() time.Time
	Metrics() job.MetricsSink
	// Get / TailLog are the single-job read surface ref resolution needs (refs.go:
	// ${steps.N.result|stdout|...}). They are existing exported job.Service methods
	// pulled into JobOps so the engine resolves a prior step's output through the
	// SAME live-in-memory-then-DB path as before (zero behaviour change); they are
	// not a new capability — refs.go already called s.Get / s.TailLog in package job.
	Get(id string) (job.JobResult, bool)
	TailLog(id string, stream store.Stream, maxBytes int64) ([]byte, error)
	// Wait blocks until a job reaches a terminal state; used only by workflow tests to
	// drain a background step-job before teardown (existing exported job.Service method).
	Wait(id string) (job.JobResult, bool)
}

JobOps is the narrow capability surface the workflow engine needs from the host job service (layering design §13.3). job.Service satisfies it (WS1 accessors).

type Spec

type Spec struct {
	Title  string                    `json:"title,omitempty" yaml:"title,omitempty"`
	Steps  []StepSpec                `json:"steps" yaml:"steps"`
	Vars   map[string]gotemplate.Var `json:"vars,omitempty" yaml:"vars,omitempty"`
	Picked map[int]int               `json:"picked,omitempty" yaml:"-"`
}

Spec is the submitted job-chain: a title + an ordered list of steps run strictly serially (single active step, D1/D10). It is the body of POST /v1/workflows and the parsed yaml workflow file (P3).

func ParseWorkflowFile

func ParseWorkflowFile(path string) (Spec, error)

ParseWorkflowFile reads a workflow file and unmarshals it into a Spec. It accepts THREE input shapes (T4.1 import + T4.2 md-per-step), dispatched by extension/content:

  • .json — a Spec JSON dump (the export round-trip, T4.1);
  • .yaml/.yml (default) — the design §9 yaml (title + steps[] with the StepSpec yaml tags). A step may additionally carry `file: foo.md` to pull its params + prompt from an external md-per-step file (T4.2, resolved relative to the workflow file's directory).

After decode each step's optional `file:` reference is expanded (expandStepMarkdown): the md frontmatter fills the step's fields and the md body becomes its prompt, so a long prompt lives in its own reviewable md file instead of inline yaml. It is extracted so the command and its unit tests share one decoder.

func ResolveBuiltinWorkflowTemplate

func ResolveBuiltinWorkflowTemplate(name string, vars map[string]string) (Spec, error)

ResolveBuiltinWorkflowTemplate applies vars/defaults and returns an executable spec.

func ResolveWorkflowTemplate

func ResolveWorkflowTemplate(name string, vars map[string]string, projectDir, globalDir string) (Spec, error)

ResolveWorkflowTemplate applies the documented project, global, then builtin lookup order. Files are YAML workflow specs with the same vars declaration.

type Step

type Step struct {
	StepIndex      int    `json:"step_index"`
	Attempt        int    `json:"attempt,omitempty"`
	FanIndex       int    `json:"fan_index,omitempty"`
	Name           string `json:"name,omitempty"`
	JobID          string `json:"job_id,omitempty"`
	Status         string `json:"status,omitempty"`
	WorktreeBranch string `json:"worktree_branch,omitempty"`
	Diff           string `json:"diff,omitempty"`
	DiffSummary    string `json:"diff_summary,omitempty"`
	// Join is "pick" for a join=pick fan-out step (empty otherwise); Picked marks the
	// fan the human selected (Z4 compare view).
	Join   string `json:"join,omitempty"`
	Picked bool   `json:"picked,omitempty"`
	// Type/ChildWorkflowID surface a Type=="workflow" sub-workflow step (P3 UI fix):
	// such a step runs no step-job, so it is absent from the job-derived rows — these
	// fields let the chain show it and link into the child workflow's detail.
	Type            string `json:"type,omitempty"`
	ChildWorkflowID string `json:"child_workflow_id,omitempty"`
}

Step is one row of a workflow's step list in the detail response: the 1-based index, the step name (from the job's title / spec name), the step-job id and its current status. job_id/status are empty/"" for a step not yet started. Attempt is the 1-based retry attempt of THIS step-job row (P1): a retried step contributes one row per attempt (each its own job_id), so the detail view shows the full retry history in step+attempt order. FanIndex is the 1-based fan-out parallel index (P2): a fan-out step contributes one row per fan job (each its own job_id), 0 for a single-job step.

type StepSpec

type StepSpec struct {
	Name       string `json:"name,omitempty" yaml:"name,omitempty"`
	ProjectKey string `json:"project_key" yaml:"project_key"`
	Agent      string `json:"agent" yaml:"agent"`
	Runner     string `json:"runner" yaml:"runner"`
	// Agents fans one step out across an ordered list of agent keys. It is mutually
	// exclusive with Fan and takes precedence over legacy numeric FanOut when set.
	Agents []string `json:"agents,omitempty" yaml:"agents,omitempty"`
	// Fan provides per-fan agent/runner overrides. The slice order is the fan index.
	Fan        []FanSpec `json:"fan,omitempty" yaml:"fan,omitempty"`
	Prompt     string    `json:"prompt,omitempty" yaml:"prompt,omitempty"`
	Cmd        []string  `json:"cmd,omitempty" yaml:"cmd,omitempty"`
	Cwd        string    `json:"cwd,omitempty" yaml:"cwd,omitempty"`
	TimeoutSec int       `json:"timeout_sec,omitempty" yaml:"timeout_sec,omitempty"`
	Tags       []string  `json:"tags,omitempty" yaml:"tags,omitempty"`
	// OnFailure is the per-step失败策略 (P1, design §5.1): "" / "fail" keeps v1
	// fail-fast (the whole workflow fails); "continue" skips the failed step and
	// advances to the next; "retry" re-runs the step (bounded by Retry, backoff
	// per job.RetryPolicy.BackoffSec). Zero value ("") == v1 behaviour (D23).
	OnFailure string `json:"on_failure,omitempty" yaml:"on_failure,omitempty"`
	// Retry is the retry policy used when OnFailure=="retry" (P1, design §5.1).
	// nil == no retry (the v1 default); validated at submit (validateRetry).
	Retry *job.RetryPolicy `json:"retry,omitempty" yaml:"retry,omitempty"`
	// FanOut is the per-step parallelism (P2, design §5.1, D14): when >1, the step
	// starts FanOut jobs in parallel (fan_index=1..FanOut) sharing (step_index,attempt),
	// aggregated by Join before the chain advances. 0/1 == a single job == v1 behaviour
	// (D23). Capped at maxFanOut (validateFanout) so a misconfigured spec can not flood
	// the executor; the fan jobs inherit caller_id and are E17 per-caller quota-bound.
	FanOut int `json:"fan_out,omitempty" yaml:"fan_out,omitempty"`
	// Join is the fan-out aggregation policy (P2, design §5.1, D15): "all" (default)
	// succeeds only if every fan job is done; "any" succeeds as soon as one is done;
	// "quorum" succeeds when more than half are done. Empty == "all". Only meaningful
	// when FanOut>1 (validateFanout rejects join on a non-fan step).
	Join string `json:"join,omitempty" yaml:"join,omitempty"`
	// Type is the step kind (P3, design §5.1, D18): "" / "job" (default) runs a single
	// agent/exec job; "workflow" instead submits an INLINE sub-workflow (SubWorkflow)
	// whose terminal state decides this step's outcome. Empty == "job" == v1 behaviour
	// (D23). A workflow-type step is mutually exclusive with fan-out (validateSubworkflow).
	Type string `json:"type,omitempty" yaml:"type,omitempty"`
	// SubWorkflow is the inline child-workflow definition for a Type=="workflow" step
	// (P3, design §5.1, D18). Required (non-empty steps) when Type=="workflow"; must be
	// absent for a job-type step. Each of its steps passes the SAME single-job准入
	// recursively (validateSubworkflow), so nesting never smuggles a step past the
	// allowlist/exec gate (§9 安全). nil for a v1/job step (D23).
	SubWorkflow *Spec `json:"sub_workflow,omitempty" yaml:"sub_workflow,omitempty"`
	// File is a CLI-ONLY md-per-step reference (P4 / T4.2): when set in a workflow yaml
	// file, the CLI loads the named md file (frontmatter→step params, body→prompt) and
	// expands it INTO the other fields before submit. It is `json:"-"` so it never
	// crosses the wire to the server (the server only ever sees the expanded fields), and
	// is absent from a v1 spec (D23). Resolved relative to the workflow file's directory.
	File string `json:"-" yaml:"file,omitempty"`
	// Review overrides the project's require_review default for THIS step
	// (GATE-01 S3): true parks the step's job in needs_review until a human accepts
	// (the chain advances then) or rejects (the step counts as failed, so on_failure
	// applies). It is a pointer so an explicit `review: false` overrides a project
	// that requires review for everything, while nil inherits the project default.
	Review *bool `json:"review,omitempty" yaml:"review,omitempty"`
	// Z1 job options are copied to every generated step job.
	Worktree     bool              `json:"worktree,omitempty" yaml:"worktree,omitempty"`
	WorktreeBase string            `json:"worktree_base,omitempty" yaml:"worktree_base,omitempty"`
	Template     string            `json:"template,omitempty" yaml:"template,omitempty"`
	Vars         map[string]string `json:"vars,omitempty" yaml:"vars,omitempty"`
	ReadOnly     bool              `json:"read_only,omitempty" yaml:"read_only,omitempty"`
	Verify       []string          `json:"verify,omitempty" yaml:"verify,omitempty"`
}

StepSpec is one step of a工作流(job 链): a普通 job request expressed declaratively. It carries the same fields a single job.JobRequest needs (project/agent/runner + prompt/cmd/cwd/timeout/tags). P1 runs each step independently (no cross-step data); P2 adds ${steps.N.field} references resolved before the step starts.

P1 adds per-step失败策略 (design §5.1, D17): OnFailure ∈ ""/fail (v1 fail-fast) | continue (skip a failed step) | retry (re-run with backoff, bounded by Retry). Both fields are omitempty with a zero value == v1 behaviour (OnFailure==""=fail, Retry==nil=no retry), so v1 specs deserialize and run unchanged (D23).

type WorkflowTemplate

type WorkflowTemplate struct {
	Name string `json:"name" yaml:"name"`
	Desc string `json:"desc,omitempty" yaml:"desc,omitempty"`
	// Source is "project", "global" or "builtin" (set by the lookup, not authored).
	Source string `json:"source,omitempty" yaml:"-"`
	Spec   Spec   `json:"spec" yaml:"spec"`
}

WorkflowTemplate is a named, declarative workflow recipe. Builtins are kept as data here so validation and the CLI/API use the exact same source.

func BuiltinWorkflowTemplates

func BuiltinWorkflowTemplates() []WorkflowTemplate

BuiltinWorkflowTemplates returns the first-party recipes. Agents, runner and project are all template variables; an empty runner means "the project default" (the same selection rule as an ordinary job submit).

func LookupWorkflowTemplates

func LookupWorkflowTemplates(projectDir, globalDir string) []WorkflowTemplate

LookupWorkflowTemplates lists the available templates in lookup order (project `.gofer/workflows`, global `<config-dir>/workflows`, builtin); a name found in an earlier source shadows later ones. Unparseable files are skipped.

Jump to

Keyboard shortcuts

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