Documentation
¶
Index ¶
- Constants
- Variables
- func CheckTemplateAgents(cfg *config.Config, spec Spec) error
- func CheckTemplateName(name string) error
- func DeleteWorkflowTemplate(dir, name string) (string, error)
- func GenerateWorkflowInit(kind, dir string) (string, error)
- func IsInvalidTemplate(err error) bool
- func LegacyRunAlwaysWarning(spec Spec) string
- func SaveWorkflowTemplate(dir, name, content string) (string, error)
- func ShadowedTemplateSources(name, projectDir, globalDir string) map[int][]string
- func SpecUsesPush(spec Spec) bool
- func WorkflowInitPath(kind, dir string) string
- func WriteWorkflowInit(kind, dir string, force bool) (string, error)
- type Engine
- func (e *Engine) Advance(wfID string)
- func (e *Engine) AdvanceRunning(ctx context.Context) int
- func (e *Engine) CancelWorkflow(wfID string) error
- func (e *Engine) ExportWorkflow(wfID string) (Spec, bool, bool, error)
- func (e *Engine) GetWorkflow(id string) (jobstore.Workflow, bool, error)
- func (e *Engine) ListWorkflowEvents(wfID string, sinceSeq int64) ([]jobstore.WorkflowEvent, error)
- func (e *Engine) ListWorkflows(status string, limit int) ([]jobstore.Workflow, error)
- func (e *Engine) ListWorkflowsPage(f jobstore.WorkflowListFilter, limit, offset int) ([]jobstore.Workflow, int, error)
- func (e *Engine) PickWorkflowFan(wfID string, stepIndex, fanIndex int) (jobstore.Workflow, error)
- func (e *Engine) RerunWorkflow(wfID, mode, step, callerID string) (jobstore.Workflow, bool, error)
- func (e *Engine) SubmitWorkflow(spec Spec, callerID string) (jobstore.Workflow, error)
- func (e *Engine) SubmitWorkflowChild(spec Spec, callerID, parentID string, parentStep, parentAtt int) (jobstore.Workflow, error)
- func (e *Engine) SubmitWorkflowFromTemplate(spec Spec, callerID, template, templateSource string) (jobstore.Workflow, error)
- func (e *Engine) WorkflowSteps(wfID string) ([]Step, error)
- func (e *Engine) WorkflowTemplateStats(f jobstore.WorkflowListFilter) (map[string]jobstore.TemplateRunStat, error)
- type FanSpec
- type JobOps
- type Spec
- func ParseWorkflowFile(path string) (Spec, error)
- func ResolveBuiltinWorkflowTemplate(name string, vars map[string]string) (Spec, error)
- func ResolveBuiltinWorkflowTemplateIn(lang i18n.Lang, name string, vars map[string]string) (Spec, error)
- func ResolveWorkflowTemplate(name string, vars map[string]string, projectDir, globalDir string) (Spec, error)
- func ResolveWorkflowTemplateIn(lang i18n.Lang, name string, vars map[string]string, ...) (Spec, error)
- func ValidateWorkflowTemplateContent(content string) (Spec, error)
- type Step
- type StepSpec
- type TemplateLastRun
- type TemplateSource
- type TemplateWriteResult
- type WorkflowTemplate
- func BuiltinWorkflowTemplate(name string) (WorkflowTemplate, bool)
- func BuiltinWorkflowTemplateIn(lang i18n.Lang, name string) (WorkflowTemplate, bool)
- func BuiltinWorkflowTemplates() []WorkflowTemplate
- func BuiltinWorkflowTemplatesIn(lang i18n.Lang) []WorkflowTemplate
- func LookupWorkflowTemplates(projectDir, globalDir string) []WorkflowTemplate
- func LookupWorkflowTemplatesIn(lang i18n.Lang, projectDir, globalDir string) []WorkflowTemplate
Constants ¶
const ( // InitVerify is the kind of the check workflow starter. InitVerify = "verify" // InitRelease is the kind of the release workflow starter. InitRelease = "release" )
Workflow init (`gofer wf init verify|release`) writes a starter file into the repository, pre-filled from what the repository actually contains: a Go module becomes `go test` + `go vet` fans, a package.json contributes its test / build / lint scripts, and `.github/workflows` names pre-fill the wait-ci `required` list (design 2026-10-21 §二). The file is a normal project template: the server reads it from the project workspace's `.gofer/workflows`, which is why the generated text ends with the "commit it before the server can read it" reminder.
const ( // RerunModeFailed keeps only the FAILED steps of the original spec (and, inside a // failed fan-out step, only the fans that failed). RerunModeFailed = "failed" // RerunModeFrom keeps the named step and everything after it. RerunModeFrom = "from" )
Rerun modes accepted by `wf rerun` / POST /v1/workflows/{id}/rerun (design §一·7).
Variables ¶
var ( // ErrTemplateNotFound reports a template name that no project, global or builtin // source defines. ErrTemplateNotFound = errors.New("workflow template not found") // ErrTemplateReadOnly reports a change to a builtin template (builtins ship with the // binary; a project or global file must use another name). ErrTemplateReadOnly = errors.New("workflow template is read-only") // ErrInvalidTemplate wraps every rejection of a template body (parse, render, step // field checks), so a caller can tell "your YAML is wrong" from "the write failed". ErrInvalidTemplate = errors.New("invalid workflow template") )
Sentinel errors of the template read / write path. The HTTP layer maps them onto 404 / 409 / 400; anything else is a disk / config failure (500).
var ErrWorkflowFileExists = errors.New("workflow file already exists")
ErrWorkflowFileExists is returned by WriteWorkflowInit when the target file is already there and the caller did not ask to overwrite it.
var TemplateNameRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
TemplateNameRe is the only shape a template name may take: an authored name becomes a file name inside the project's `.gofer/workflows` or the global `<config-dir>/workflows`.
Functions ¶
func CheckTemplateAgents ¶
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.
func CheckTemplateName ¶ added in v0.181.0
CheckTemplateName rejects a name that cannot be used as a template file name (a path separator, `..`, or an empty name).
func DeleteWorkflowTemplate ¶ added in v0.181.0
DeleteWorkflowTemplate removes the file that defines `name` in dir. A name with no file there is ErrTemplateNotFound.
func GenerateWorkflowInit ¶ added in v0.181.0
GenerateWorkflowInit renders the starter file of kind (verify or release) for the repository at dir. The generated text is validated the way a template is (ValidateWorkflowTemplateContent), so `wf init` can never write a file that a run would refuse.
func IsInvalidTemplate ¶ added in v0.181.0
IsInvalidTemplate reports whether err is what the HTTP layer should answer with a 400: an authored template the submit-time checks rejected.
func LegacyRunAlwaysWarning ¶ added in v0.182.0
LegacyRunAlwaysWarning returns a one-line deprecation warning for a spec still using the old `run: always` condition spelling, or "" when it uses `if: always`. The CLI prints it right after parsing a workflow file, so the operator sees which steps to update (the server logs the same warning when the spec is submitted by any path).
func SaveWorkflowTemplate ¶ added in v0.181.0
SaveWorkflowTemplate validates content and writes it as `<dir>/<name>.yaml`. Validation runs before anything touches the disk, so a rejected template leaves no file behind; the write itself goes through a temp file + rename, so a concurrent reader never sees a half-written template. Other extensions of the same name are removed, so the name keeps resolving to the file that was just saved.
func ShadowedTemplateSources ¶ added in v0.181.0
ShadowedTemplateSources returns, for every template location in lookup order, the sources that location hides when it defines `name` (empty when it defines nothing): a project file hides the global file and the builtin of the same name, a global file hides the builtin. It is what makes "save over a builtin name" visible to a caller instead of silent.
func SpecUsesPush ¶ added in v0.181.0
SpecUsesPush reports whether a spec (or any nested sub-workflow) runs a `gofer/push` step. The HTTP entry point uses it to require the `repo.push` permission before a workflow that would push anything is submitted.
func WorkflowInitPath ¶ added in v0.181.0
WorkflowInitPath returns where the starter of kind lives in the repository at dir.
func WriteWorkflowInit ¶ added in v0.181.0
WriteWorkflowInit generates the starter of kind and writes it to the repository at dir. An existing file is left alone (ErrWorkflowFileExists) unless force is set, so a second `wf init` never silently discards the edits an operator made.
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 ¶
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 ¶
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 ⭐节):
- every step-job carries a DETERMINISTIC request_id (stepToRequest) so the C5 unique index lets at most ONE job exist per (step, attempt);
- 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ListWorkflows returns workflow headers, optionally filtered by status, newest first, capped at limit (<=0 => store default). HTTP list path.
func (*Engine) ListWorkflowsPage ¶ added in v0.200.0
func (e *Engine) ListWorkflowsPage(f jobstore.WorkflowListFilter, limit, offset int) ([]jobstore.Workflow, int, error)
ListWorkflowsPage returns one page of workflow headers (status / caller filter) plus the total number of rows the same filter matches. It backs the paged HTTP list (limit / offset / total).
func (*Engine) PickWorkflowFan ¶
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) RerunWorkflow ¶ added in v0.181.0
RerunWorkflow submits a NEW workflow trimmed out of an existing one's spec (design §一·7): mode RerunModeFailed keeps the failed steps (a failed fan-out step keeps only its failed fans), RerunModeFrom keeps step `step` and every later step. The new workflow records the original as rerun_of; the original is never modified (its status, pointer and jobs stay as they are), so its history remains readable.
The trimmed spec is re-submitted through the normal path, so it passes the same admission, per-step 入 and reference checks: a retained step whose ${steps.N.…} reference pointed at a dropped step is rejected rather than run with a broken reference. Variables and `ref:` shas are whatever the stored spec holds (already rendered and resolved at the original submit), so a rerun checks the same commit.
The bool is false when no such workflow exists.
func (*Engine) SubmitWorkflow ¶
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) SubmitWorkflowFromTemplate ¶ added in v0.204.0
func (e *Engine) SubmitWorkflowFromTemplate(spec Spec, callerID, template, templateSource string) (jobstore.Workflow, error)
SubmitWorkflowFromTemplate is SubmitWorkflow for a spec rendered from a named template: it records the template name and where it came from (builtin / global / project) on the execution record, so the workflow list can group runs by template.
func (*Engine) WorkflowSteps ¶
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 comes from the spec, falling back to the step-job's persisted title (a fan job is titled "<step> · <fan>").
func (*Engine) WorkflowTemplateStats ¶ added in v0.204.0
func (e *Engine) WorkflowTemplateStats(f jobstore.WorkflowListFilter) (map[string]jobstore.TemplateRunStat, error)
WorkflowTemplateStats groups the visible runs (per f's caller / project conditions) by the template they were submitted from.
type FanSpec ¶
type FanSpec struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Agent string `json:"agent,omitempty" yaml:"agent,omitempty"`
Runner string `json:"runner,omitempty" yaml:"runner,omitempty"`
Cmd []string `json:"cmd,omitempty" yaml:"cmd,omitempty"`
// Run/Shell are the fan's own multi-line script and its interpreter (see
// StepSpec.Run). A fan that sets neither cmd nor run runs the step's command.
Run string `json:"run,omitempty" yaml:"run,omitempty"`
Shell string `json:"shell,omitempty" yaml:"shell,omitempty"`
Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
Cwd string `json:"cwd,omitempty" yaml:"cwd,omitempty"`
TimeoutSec int `json:"timeout_sec,omitempty" yaml:"timeout_sec,omitempty"`
}
FanSpec overrides the agent and runner for one ordered fan. Runner may be empty to inherit the step runner. Agent may be empty when the fan carries its own Cmd: an exec fan defaults to the built-in exec agent (design §一·2), so one step can fan out per-check commands (`cmd` / `env` / `cwd` / `timeout_sec` each overridable). Name, when set, must be unique within the step and is what ${steps.<step>.<fan name>.<field>} refers to (the positional ${steps.<step>.fK.…} form keeps working).
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"`
// Project is the workflow's default project key: every step whose project_key is
// empty runs there (design §一·1). A template read from a project's
// `.gofer/workflows` defaults to that project.
Project string `json:"project,omitempty" yaml:"project,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 ¶
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 ¶
ResolveBuiltinWorkflowTemplate is ResolveBuiltinWorkflowTemplateIn in the default language.
func ResolveBuiltinWorkflowTemplateIn ¶ added in v0.206.0
func ResolveBuiltinWorkflowTemplateIn(lang i18n.Lang, name string, vars map[string]string) (Spec, error)
ResolveBuiltinWorkflowTemplateIn applies vars/defaults and returns an executable spec whose prompts are in lang.
func ResolveWorkflowTemplate ¶
func ResolveWorkflowTemplate(name string, vars map[string]string, projectDir, globalDir string) (Spec, error)
ResolveWorkflowTemplate is ResolveWorkflowTemplateIn in the default language.
func ResolveWorkflowTemplateIn ¶ added in v0.206.0
func ResolveWorkflowTemplateIn(lang i18n.Lang, name string, vars map[string]string, projectDir, globalDir string) (Spec, error)
ResolveWorkflowTemplateIn applies the documented project, global, then builtin lookup order. Files are YAML workflow specs with the same vars declaration; a builtin template's prompts are in lang (the language of the project whose agents read them).
func ValidateWorkflowTemplateContent ¶ added in v0.181.0
ValidateWorkflowTemplateContent checks a template body the way a run would: the YAML must parse, its variables are rendered from their defaults (a variable without a default renders as a placeholder), the rendered spec must leave no unresolved ${vars.x} and its steps must pass the submit-time fan-out / failure-policy checks. Nothing is executed and nothing is written.
type Step ¶
type Step struct {
StepIndex int `json:"step_index"`
Attempt int `json:"attempt,omitempty"`
FanIndex int `json:"fan_index,omitempty"`
// FanName is the `name` the spec's fan list declares for this fan (linux-race / web
// …), so a fan row shows WHAT it ran instead of repeating the step name
// (gofer-j5xc). Empty for a plain FanOut/Agents step and for a single-job step.
FanName string `json:"fan_name,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"`
// Runner/ExitCode/DurationSec/FailureExcerpt are the result-view columns (design
// §一·6): where the row ran, how it exited, how long it took and why it failed.
// ExitCode is a pointer so a successful exec step still shows "0" while a step
// that never started shows none. FailureExcerpt is the failure-looking lines of
// the job's log tail (at most 20), or the built-in step's error message.
Runner string `json:"runner,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
DurationSec int64 `json:"duration_sec,omitempty"`
FailureExcerpt string `json:"failure_excerpt,omitempty"`
// Cwd is the directory the row actually ran in (the resolved overlay path for the
// step's project, or the temporary ref checkout when Ref is set); Ref is the commit
// the spec asked to check out there. StartedAt/FinishedAt are unix seconds: the
// former is set once the job started, the latter once it reached a terminal state.
Cwd string `json:"cwd,omitempty"`
Ref string `json:"ref,omitempty"`
StartedAt int64 `json:"started_at,omitempty"`
FinishedAt int64 `json:"finished_at,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 is the step command as an argv array (gofer never splits it). Mutually
// exclusive with Run.
Cmd []string `json:"cmd,omitempty" yaml:"cmd,omitempty"`
// Run is the step command as a multi-line SCRIPT (GitHub Actions style), executed by
// Shell. At submit it is converted into Cmd (shell -c <script>), so the wire, the
// worker and the stored spec keep carrying argv only. Mutually exclusive with Cmd.
Run string `json:"run,omitempty" yaml:"run,omitempty"`
// Shell is the interpreter Run is executed by: "" / bash (default) | sh | pwsh |
// python. Only meaningful together with Run.
Shell string `json:"shell,omitempty" yaml:"shell,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"`
// Env is the extra environment for this step's job (design 一·4): it rides
// JobRequest.Env, so it applies on the server's own runner directly and reaches a
// worker as wsproto.Dispatch.env (protocol v26; a job that carries env is refused for
// an older worker rather than run without its variables). Values are stored with the
// job, so they are no place for secrets.
Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
// Ref is the commit a step checks out in a TEMPORARY detached worktree (design 一·3).
// It is resolved to a full sha at submit (so every fan checks the same tree), removed
// when the job ends, and mutually exclusive with Worktree. On a machine whose
// checkout lacks the commit it is fetched from the default remote first.
Ref string `json:"ref,omitempty" yaml:"ref,omitempty"`
// Uses names a built-in step (design §一·5, `gofer/<name>`), with its arguments in
// With: the engine submits an internal `gofer tool step <name>` exec job whose stdin
// is the With JSON and whose last stdout line is the step result (S3).
Uses string `json:"uses,omitempty" yaml:"uses,omitempty"`
With map[string]any `json:"with,omitempty" yaml:"with,omitempty"`
// If changes WHEN a step runs (design §一·8): "" (the default) runs it in chain
// order, "always" runs it even after an earlier failure (fail-fast jumps to the
// if: always steps and runs them in order) without changing the workflow's final
// outcome — a failure before them still fails the whole workflow.
If string `json:"if,omitempty" yaml:"if,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 TemplateLastRun ¶ added in v0.204.0
type TemplateLastRun struct {
ID string `json:"id"`
Status string `json:"status"`
StartedAt int64 `json:"started_at"`
EndedAt int64 `json:"ended_at,omitempty"`
}
TemplateLastRun is the newest execution of a template: its workflow id and status plus the start time and, once it finished, the end time (unix seconds).
type TemplateSource ¶ added in v0.181.0
type TemplateSource struct {
Name string `json:"name"`
Source string `json:"source"` // project | global | builtin
Path string `json:"path,omitempty"`
Content string `json:"content"`
Shadows []string `json:"shadows,omitempty"`
}
TemplateSource is where a template came from and its own text: the answer of GET /v1/workflow-templates/{name}/source. A builtin template has no Path; its Content is the YAML serialisation of the template spec (exactly what saving it under a new name would write).
Shadows lists the sources this definition hides: a project file hides the global file and the builtin of the same name, a global file hides the builtin. Overriding a builtin name is the supported way to replace a builtin template (the builtin itself stays read-only).
func ReadWorkflowTemplateSource ¶ added in v0.181.0
func ReadWorkflowTemplateSource(name, projectDir, globalDir string) (TemplateSource, error)
ReadWorkflowTemplateSource returns the raw text of the named template, resolved in the same order a run uses: project `.gofer/workflows`, global `<config-dir>/workflows`, builtin. A builtin's prompts are in the default language (ReadWorkflowTemplateSourceIn).
func ReadWorkflowTemplateSourceIn ¶ added in v0.206.0
func ReadWorkflowTemplateSourceIn(lang i18n.Lang, name, projectDir, globalDir string) (TemplateSource, error)
ReadWorkflowTemplateSourceIn is ReadWorkflowTemplateSource with the builtin's prompts in lang.
type TemplateWriteResult ¶ added in v0.181.0
type TemplateWriteResult struct {
Name string `json:"name"`
Scope string `json:"scope"` // global | project
Path string `json:"path"`
ContentLength int `json:"content_length,omitempty"`
Uncommitted bool `json:"uncommitted,omitempty"`
CommitCommand string `json:"commit_command,omitempty"`
OverridesBuiltin bool `json:"overrides_builtin,omitempty"`
FallsBackTo string `json:"falls_back_to,omitempty"`
}
TemplateWriteResult describes a saved or deleted template. Uncommitted / CommitCommand are set for a project template: its file lands in the project workspace as an uncommitted change, so the caller is told how to commit it (gofer never commits). OverridesBuiltin marks a save that now hides a builtin template of the same name; FallsBackTo names the source the name resolves to after a delete (global / builtin, empty when nothing is left).
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"`
// Runs and LastRun summarise the executions started from this template (filled by the
// list / show API for the caller's visible runs; never authored). Runs is 0 and LastRun
// nil when there is none.
Runs int `json:"runs" yaml:"-"`
LastRun *TemplateLastRun `json:"last_run,omitempty" yaml:"-"`
}
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 BuiltinWorkflowTemplate ¶ added in v0.181.0
func BuiltinWorkflowTemplate(name string) (WorkflowTemplate, bool)
BuiltinWorkflowTemplate returns the builtin template of that name (prompts in the default language; callers that show or run the prompts use BuiltinWorkflowTemplateIn).
func BuiltinWorkflowTemplateIn ¶ added in v0.206.0
func BuiltinWorkflowTemplateIn(lang i18n.Lang, name string) (WorkflowTemplate, bool)
BuiltinWorkflowTemplateIn returns the builtin template of that name, its prompts in lang.
func BuiltinWorkflowTemplates ¶
func BuiltinWorkflowTemplates() []WorkflowTemplate
BuiltinWorkflowTemplates is BuiltinWorkflowTemplatesIn in the default language, for callers that only need the names, variables and structure.
func BuiltinWorkflowTemplatesIn ¶ added in v0.206.0
func BuiltinWorkflowTemplatesIn(lang i18n.Lang) []WorkflowTemplate
BuiltinWorkflowTemplatesIn 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). The step prompts are written for an agent, in lang (the prompts templates workflow_*); the descriptions and variable docs are English everywhere.
func LookupWorkflowTemplates ¶
func LookupWorkflowTemplates(projectDir, globalDir string) []WorkflowTemplate
LookupWorkflowTemplates is LookupWorkflowTemplatesIn in the default language.
func LookupWorkflowTemplatesIn ¶ added in v0.206.0
func LookupWorkflowTemplatesIn(lang i18n.Lang, projectDir, globalDir string) []WorkflowTemplate
LookupWorkflowTemplatesIn 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. The builtin prompts are in lang.