From 43eb8b24e08e07b943e0b46650affda86aa37a57 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 10 Nov 2026 21:16:24 -0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20workflowmodel:=20lifecycle=20schema?= =?UTF-8?q?,=20compiler,=20hive-default=20generator,=20DeriveFromModel=20(?= =?UTF-8?q?#17620=20P1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extends the v1alpha1 schema with columns, derivation, events, gates, roles, agents, checks, bookkeeping, labels and meta; adds Compile with coded refusals; generates hive-default from the stage table and the engine's expected edges; adds stageengine.DeriveFromModel (builtin delegation + rules evaluator) and Options.Workflow; adds the workflow.enabled flag (default false, no wiring effect yet). The PR stage-golden corpus derives identically under hive-default. Signed-off-by: Andrew Anderson --- changelog.d/added-workflowmodel-compiler.md | 1 + src/docs/design/workflow-models.md | 33 +- src/pkg/config/config.go | 14 +- .../config/testdata/agent_runtime_golden.json | 21 +- src/pkg/stageengine/export_parity_test.go | 44 ++ src/pkg/stageengine/reconciler.go | 24 +- src/pkg/stageengine/workflow.go | 308 ++++++++++++ src/pkg/stageengine/workflow_parity_test.go | 106 ++++ src/pkg/stageengine/workflow_rules_test.go | 208 ++++++++ src/pkg/workflowmodel/compile.go | 469 ++++++++++++++++++ src/pkg/workflowmodel/compile_test.go | 175 +++++++ .../workflowmodel/hivedefault/hivedefault.go | 254 ++++++++++ .../hivedefault/hivedefault_test.go | 151 ++++++ src/pkg/workflowmodel/lifecycle.go | 272 ++++++++++ src/pkg/workflowmodel/model.go | 16 + .../testdata/models/techdocs.json | 79 +++ 16 files changed, 2155 insertions(+), 20 deletions(-) create mode 100644 changelog.d/added-workflowmodel-compiler.md create mode 100644 src/pkg/stageengine/export_parity_test.go create mode 100644 src/pkg/stageengine/workflow.go create mode 100644 src/pkg/stageengine/workflow_parity_test.go create mode 100644 src/pkg/stageengine/workflow_rules_test.go create mode 100644 src/pkg/workflowmodel/compile.go create mode 100644 src/pkg/workflowmodel/compile_test.go create mode 100644 src/pkg/workflowmodel/hivedefault/hivedefault.go create mode 100644 src/pkg/workflowmodel/hivedefault/hivedefault_test.go create mode 100644 src/pkg/workflowmodel/lifecycle.go create mode 100644 src/pkg/workflowmodel/testdata/models/techdocs.json diff --git a/changelog.d/added-workflowmodel-compiler.md b/changelog.d/added-workflowmodel-compiler.md new file mode 100644 index 0000000000..84df9ed9d8 --- /dev/null +++ b/changelog.d/added-workflowmodel-compiler.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 1 ([#17620](https://github.com/hivecommons/hive/issues/17620)): the `workflow.hivecommons.dev/v1alpha1` schema gains the lifecycle half of the RFC — `columns`, `derivation`, `events`, `gates`, `roles`, `agents`, `checks`, `bookkeeping`, `labels`, `meta` and per-state `lifecycle` (column, stage number, item kinds, replies) — and `workflowmodel.Compile` turns a model into a `Profile` or refuses it with coded diagnostics (a non-terminal state with no exit, a gate with no releasing role, an agent-granted state with no human-released gate before a terminal outcome, two events bound to one fact, a state in no or two columns, duplicate stage numbers, an unknown fact or operator). `pkg/workflowmodel/hivedefault` generates the `hive-default` model from the live stage table and the engine's expected-edge table, so the monitor's seven columns and the stage numbers are now a compiled model rather than constants. `stageengine.DeriveFromModel` derives under a compiled profile: `hive-default` declares `derivation: builtin` and delegates to the existing derivers (the whole PR stage-golden corpus and the issue sweep derive identically), custom models declare `derivation: rules` (ordered first-match predicates over the fact vocabulary, uncovered items abstain `workflow: not covered`). New `workflow.enabled` config flag, default false; nothing changes for any hive until a repository is bound (phase 2). diff --git a/src/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index 60358c542f..2a3d679c7c 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -34,7 +34,9 @@ state it fills. One workflow serving several triggers binds to each role its tri | Package | Role | |---|---| -| `pkg/workflowmodel` | types, `Validate`, `Hash`, `HiveDefault`, `Bind`, topological `Levels` | +| `pkg/workflowmodel` | types, `Validate`, `Hash`, `HiveDefault`, `Bind`, topological `Levels`, `Compile` → `Profile` | +| `pkg/workflowmodel/hivedefault` | `Generate()` the `hive-default` model from `stagelabels.Table` + `stageengine.DiagramEdges()`; `Profile()` compiled | +| `pkg/stageengine` (`workflow.go`) | `DeriveFromModel(profile, kind)`: builtin delegation or the rules evaluator; `Options.Workflow` | | `pkg/workflowmodel/githubactions` | `.github/workflows/*.y*ml` → pipelines | | `pkg/workflowmodel/tekton` | Pipeline / PipelineRun / Task (+ Pipelines-as-Code annotations) → pipelines | | `pkg/workflowmodel/ingest` | `Repository(scope, files)`: route files to ingesters, compose, bind | @@ -62,6 +64,35 @@ golden summary per repository; `go test ./pkg/workflowmodel/ingest -update` rewr after an intended change. The full 317-repository CNCF-landscape survey and its collector live outside the repository; the results are on #17620. +## Lifecycle half and the compiler (RFC phase 1) + +The RFC (#17620) asks for one engine that derives under any model. The decision that keeps v5/v6 +byte-identical is that **`hive-default` derivation stays in Go**: `hivedefault.Generate()` builds +the model from the stage table, the engine's expected edges and the monitor's column anchors, and +declares `derivation: builtin`. `stageengine.DeriveFromModel` then delegates to `IssueDeriver` / +`PRDeriver` and only checks coverage — a stage the model has no state for abstains with +`workflow: not covered` instead of writing a label the model does not know. The parity test +(`TestDeriveFromModelHiveDefaultParity`) runs every PR stage golden and an issue sweep through both +and requires identical `Decision`s. + +Custom models declare `derivation: rules`: ordered rules, each a conjunction of predicates over the +fact vocabulary in `workflowmodel.Facts` (`open`, `merged`, `draft`, `labels has stage/*`, +`author.kind is human`, `pr.checks is green`, `pr.review is approved`, `issue.covered`, …); the +first rule whose predicates all hold names the state, and an item no rule matches is not covered. +Rules reach only the facts the engine already computes; no LLM is ever in the derivation path. +`testdata/models/techdocs.json` is the hand-written reference model (cncf/techdocs engagement). + +`Compile` refuses (error diagnostics, no profile): `state-no-exit`, `gate-no-owner`, +`agent-no-human-gate` (every path from an agent-granted state to a terminal outcome must cross a +transition gated by a role with `human: true`; closure edges — the item closed unmerged — are +observations and exempt), `duplicate-event-fact`, `state-no-column` / `unknown-column`, +`duplicate-stage-number`, `unknown-fact` / `bad-op`, `no-rules`, `no-version`. Elements marked +`confidence: inferred` compile with an `inferred-element` warning the editor shows. + +Stage numbers in a model are Hive's label numbers (`stagelabels.Table`) for now, so a bound repo's +labels, tracker anchors and replies keep working; a state whose number does not apply to the item +kind is not covered. Models are whole (no inheritance) through phase 4. + ## Known gaps (phase 1) - Prow (`kubernetes/*`) is a third syntax not read; those repos render the default columns. diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 5229e99df7..f98585c3b4 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -82,8 +82,13 @@ type Config struct { // Dedupe tunes the dedupe lane's follow-through on its checklists. Dedupe DedupeLaneConfig `yaml:"dedupe,omitempty" json:"dedupe,omitempty"` Contribute ContributeConfig `yaml:"contribute,omitempty" json:"contribute,omitempty"` - HiveID string `yaml:"hive_id"` - ACMMLevel *int `yaml:"acmm_level,omitempty" json:"acmm_level"` + // Workflow gates the workflow-model engine (hivecommons/hive#17620). + // Off by default: every repository derives stages with the built-in + // derivers exactly as before. On, repositories bound to a workflow + // model derive through it; unbound repositories are unchanged. + Workflow WorkflowConfig `yaml:"workflow,omitempty" json:"workflow,omitempty"` + HiveID string `yaml:"hive_id"` + ACMMLevel *int `yaml:"acmm_level,omitempty" json:"acmm_level"` // ModelRoles is the named model-roles map (#9722): a small set of names, // each naming a backend, a model and a reasoning effort, referenced as // "@" wherever hive asks for a model (today: agents' model and the @@ -274,6 +279,11 @@ type Config struct { ReviewerAutoscaleActive int `yaml:"-" json:"-"` } +// WorkflowConfig is the `workflow:` block (hivecommons/hive#17620). +type WorkflowConfig struct { + Enabled bool `yaml:"enabled" json:"enabled"` +} + type DataConfig struct { MetricsDir string `yaml:"metrics_dir"` LogsDir string `yaml:"logs_dir"` diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index c86ffdb635..8f6cb5a40a 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -447,8 +447,8 @@ "BaseURL": "", "AppAuthoredPRs": null, "AppSignedCommits": null, - "attention": {}, "notifications": {}, + "attention": {}, "OAuthBaseURLOverride": "", "OAuthAPIURLOverride": "" }, @@ -473,6 +473,7 @@ "Port": 8080, "AuthToken": "", "AgentPollIntervalS": 10, + "matrix": {}, "AuthorizedUsers": null, "AuthorizedUserNames": null, "HubProxied": false, @@ -483,7 +484,6 @@ } }, "issue_bands": {}, - "matrix": {}, "stage_tracker": {} }, "Data": { @@ -686,6 +686,9 @@ "fleet": {}, "dedupe": {}, "contribute": {}, + "workflow": { + "enabled": false + }, "HiveID": "", "acmm_level": null, "advisor": {}, @@ -723,6 +726,13 @@ }, "intent": {}, "sentinel": {}, + "security": {}, + "evidence": { + "complexity": {} + }, + "compliance": { + "posture_checks": {} + }, "escalation": { "email": { "smtp": {}, @@ -734,10 +744,6 @@ "pagerduty": {} } }, - "security": {}, - "evidence": { - "complexity": {} - }, "jev": {}, "runs": { "checkpoints": {}, @@ -776,9 +782,6 @@ "recommendations": {}, "plan_match": {} }, - "compliance": { - "posture_checks": {} - }, "auto_merge": { "bot_takeover": {}, "trusted_authors": {}, diff --git a/src/pkg/stageengine/export_parity_test.go b/src/pkg/stageengine/export_parity_test.go new file mode 100644 index 0000000000..6d30a22fc7 --- /dev/null +++ b/src/pkg/stageengine/export_parity_test.go @@ -0,0 +1,44 @@ +package stageengine + +import ( + "github.com/hivecommons/hive/pkg/claims" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// ParityFacts hands the external parity test (workflow_parity_test.go, +// package stageengine_test — it imports hivedefault, which imports this +// package, so it cannot live here) the Facts corpus the built-in derivers +// are pinned by: every generated PR stage golden plus a sweep of issue +// facts reaching each issue stage. hivecommons/hive#17620. +func ParityFacts() []Facts { + var out []Facts + for _, cases := range generateStageGoldens() { + for _, c := range cases { + _, f := runStageGoldenWithFacts(c.Input) + out = append(out, f) + } + } + pr99 := &Ref{Owner: "acme", Repo: "widgets", Number: 99, Kind: stagelabels.PRItem} + for _, mut := range []func(f *Facts){ + nil, + func(f *Facts) { f.Issue.Bucket = BucketDependencyDashboard; f.Park.NeedsHuman = true }, + func(f *Facts) { f.Issue.TriageAwaiting = "carries needs-triage" }, + func(f *Facts) { + f.Issue.Bucket = BucketClaimed + f.Issue.Claim = &ClaimFact{Holder: "bob", Kind: "human"} + }, + func(f *Facts) { + f.Issue.Bucket = BucketClaimed + f.Issue.Claim = &ClaimFact{Kind: claims.KindAgent, PRStarted: true} + }, + func(f *Facts) { f.Issue.Bucket = BucketCoveredByPR; f.Issue.CoveringPR = pr99 }, + func(f *Facts) { f.Park.NeedsHuman = true }, + func(f *Facts) { f.Park.PossiblyExists = true }, + func(f *Facts) { f.Issue.DiscussionLabel = "proposal" }, + func(f *Facts) { f.Open = false }, + func(f *Facts) { f.Issue.Bucket = BucketFiltered }, + } { + out = append(out, derivedIssueFacts(mut)) + } + return out +} diff --git a/src/pkg/stageengine/reconciler.go b/src/pkg/stageengine/reconciler.go index 3d265e6eb0..769dce85f0 100644 --- a/src/pkg/stageengine/reconciler.go +++ b/src/pkg/stageengine/reconciler.go @@ -10,6 +10,7 @@ import ( "time" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" ) // Transition is what Reconcile reports to its caller and the audit log. @@ -38,14 +39,17 @@ type Reconciler interface { // Options configures New. type Options struct { - Mode Mode - Store *stagelabels.Store // stagelabels.Shared() by default; API unchanged - Writer StageWriter - Issue Deriver // defaults to DeriveIssue - PR Deriver // defaults to DerivePR - Now func() time.Time - Logger *slog.Logger - Metrics Metrics + Mode Mode + Store *stagelabels.Store // stagelabels.Shared() by default; API unchanged + Writer StageWriter + Issue Deriver // defaults to DeriveIssue + PR Deriver // defaults to DerivePR + // Workflow, when set, derives through the compiled workflow model + // (DeriveFromModel) and overrides Issue and PR. hivecommons/hive#17620. + Workflow *workflowmodel.Profile + Now func() time.Time + Logger *slog.Logger + Metrics Metrics } // ErrNoWriter is returned by an enforce-mode Reconcile with no Writer. @@ -73,6 +77,10 @@ func New(o Options) Reconciler { if o.Store == nil { o.Store = stagelabels.Shared() } + if o.Workflow != nil { + o.Issue = DeriveFromModel(o.Workflow, stagelabels.IssueItem) + o.PR = DeriveFromModel(o.Workflow, stagelabels.PRItem) + } if o.Issue == nil { o.Issue = IssueDeriver() } diff --git a/src/pkg/stageengine/workflow.go b/src/pkg/stageengine/workflow.go new file mode 100644 index 0000000000..55f337aff2 --- /dev/null +++ b/src/pkg/stageengine/workflow.go @@ -0,0 +1,308 @@ +package stageengine + +import ( + "fmt" + "strings" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +// DeriveFromModel is the third Deriver (hivecommons/hive#17620 "One +// engine, one writer"): it derives an item's stage under a compiled +// workflow model and produces the same Decision the built-in derivers do, +// so the Reconciler stays the only label writer. +// +// Under derivation mode builtin the built-in deriver for kind decides and +// the model only has to cover the stage it produced; a stage the model has +// no state for is "not covered" and the deriver abstains (fail closed, +// never a silent fall-through). Under mode rules the model's ordered rules +// are evaluated over Facts; the first rule whose predicates all hold names +// the state, and an item no rule matches is not covered. +func DeriveFromModel(p *workflowmodel.Profile, kind stagelabels.Item) Deriver { + if p == nil { + return builtinDeriver(kind) + } + return modelDeriver{p: p, kind: kind, inner: builtinDeriver(kind)} +} + +func builtinDeriver(kind stagelabels.Item) Deriver { + if kind == stagelabels.PRItem { + return prDeriverF + } + return issueDeriverF +} + +type modelDeriver struct { + p *workflowmodel.Profile + kind stagelabels.Item + inner Deriver +} + +func (d modelDeriver) Kind() stagelabels.Item { return d.kind } + +// ReasonNotCovered prefixes every abstention the model forces. +const ReasonNotCovered = "workflow: not covered" + +func (d modelDeriver) Derive(f Facts) Decision { + if f.Ref.Kind != d.kind { + return abstain(reasonKindMismatch) + } + switch d.p.Mode { + case workflowmodel.DerivationBuiltin: + dec := d.inner.Derive(f) + if dec.Abstain || dec.Stage == stagelabels.None { + return dec + } + if _, ok := d.p.StateForNumber(dec.Stage.Number()); !ok { + return abstain(fmt.Sprintf("%s: %s@%s has no state for stage %s", ReasonNotCovered, d.p.Name, d.p.Version, dec.Stage)) + } + return dec + case workflowmodel.DerivationRules: + return d.rules(f) + } + return abstain(fmt.Sprintf("%s: %s@%s has derivation mode %q", ReasonNotCovered, d.p.Name, d.p.Version, d.p.Mode)) +} + +// rules evaluates the profile's rules in order. +func (d modelDeriver) rules(f Facts) Decision { + want := workflowmodel.KindIssue + if d.kind == stagelabels.PRItem { + want = workflowmodel.KindPR + } + for i, r := range d.p.Rules { + if r.Kind != workflowmodel.KindAny && r.Kind != want { + continue + } + if !holdsAll(f, r.When) { + continue + } + id := r.ID + if id == "" { + id = fmt.Sprintf("rules[%d]", i) + } + reason := r.Reason + if reason == "" { + reason = fmt.Sprintf("workflow %s@%s: rule %s", d.p.Name, d.p.Version, id) + } + return d.decisionFor(r.State, reason, f) + } + return abstain(fmt.Sprintf("%s: %s@%s has no rule for this %s", ReasonNotCovered, d.p.Name, d.p.Version, want)) +} + +// decisionFor turns a model state into a Decision: its stage number maps +// to the stage label, a terminal state with no number is Stage None. +func (d modelDeriver) decisionFor(state, reason string, f Facts) Decision { + st := d.p.States[state] + if st == nil { + return abstain(fmt.Sprintf("%s: state %q is not in %s@%s", ReasonNotCovered, state, d.p.Name, d.p.Version)) + } + dec := Decision{Reason: reason, Kind: f.Author.Kind, Role: f.Author.Role} + if st.Lifecycle.Number == 0 { + if d.p.Terminal[state] { + dec.Terminal = true + return dec + } + return abstain(fmt.Sprintf("%s: state %q carries no stage number and is not terminal", ReasonNotCovered, state)) + } + stage, ok := stageByNumber(st.Lifecycle.Number) + if !ok { + return abstain(fmt.Sprintf("%s: state %q stage number %d is not in the stage table", ReasonNotCovered, state, st.Lifecycle.Number)) + } + if !stage.Applies(d.kind) { + return abstain(fmt.Sprintf("%s: state %q stage number %d is not a %s stage", ReasonNotCovered, state, st.Lifecycle.Number, d.kind)) + } + dec.Stage = stage + if f.PR != nil { + dec.DCO = f.PR.DCO + } + return dec +} + +func stageByNumber(n int) (stagelabels.Stage, bool) { + for _, def := range stagelabels.Table { + if def.Number == n { + return def.Stage, true + } + } + return stagelabels.None, false +} + +func holdsAll(f Facts, preds []workflowmodel.Predicate) bool { + for _, p := range preds { + if !holds(f, p) { + return false + } + } + return true +} + +// holds evaluates one predicate from the workflowmodel.Facts vocabulary. +// An unknown fact or a mismatched operator is false: the compiler has +// already refused such a model, so this is defence in depth. +func holds(f Facts, p workflowmodel.Predicate) bool { + switch workflowmodel.Facts[p.Fact] { + case workflowmodel.FactBool: + v, ok := boolFact(f, p.Fact) + if !ok { + return false + } + return (p.Op == workflowmodel.OpTrue) == v + case workflowmodel.FactScalar: + v, ok := scalarFact(f, p.Fact) + if !ok { + return false + } + eq := strings.EqualFold(v, p.Value) + return (p.Op == workflowmodel.OpIs) == eq + case workflowmodel.FactSet: + set, ok := setFact(f, p.Fact) + if !ok { + return false + } + has := false + for _, s := range set { + if matchGlob(p.Value, s) { + has = true + break + } + } + return (p.Op == workflowmodel.OpHas) == has + } + return false +} + +// matchGlob matches value against pattern, where a trailing `*` matches +// any suffix. Comparison is case-insensitive, as labels are. +func matchGlob(pattern, value string) bool { + if strings.HasSuffix(pattern, "*") { + return strings.HasPrefix(strings.ToLower(value), strings.ToLower(strings.TrimSuffix(pattern, "*"))) + } + return strings.EqualFold(pattern, value) +} + +func boolFact(f Facts, name string) (bool, bool) { + switch name { + case "open": + return f.Open, true + case "merged": + return f.Merged, true + case "draft": + return f.Draft, true + case "hold": + return len(f.Park.Holds) > 0, true + case "park": + return f.Park.NeedsHuman || f.Park.DecisionLabel != "" || f.Park.PossiblyExists, true + case "issue.claimed": + return f.Issue != nil && f.Issue.Claim != nil, true + case "issue.covered": + return f.Issue != nil && f.Issue.CoveringPR != nil, true + case "issue.stalled": + return f.Issue != nil && f.Issue.Stalled, true + case "issue.open_children": + return f.Issue != nil && f.Issue.OpenChildren > 0, true + case "pr.changes_requested": + return f.PR != nil && f.PR.ChangesRequested, true + case "pr.conflicting": + return f.PR != nil && f.PR.Conflicting, true + case "pr.head_fresh": + return f.PR != nil && f.PR.HeadFresh, true + } + return false, false +} + +// Scalar fact values. pr.checks: green | red | pending | missing | unknown. +// pr.review: pending | approved | changes_requested | unavailable. +// pr.dco: yes | no | unknown. author.kind: human | hive | clanker | unknown. +func scalarFact(f Facts, name string) (string, bool) { + switch name { + case "origin": + return f.Origin, true + case "author.kind": + return authorKindName(f.Author.Kind), true + case "author.login": + return f.Author.Login, true + case "issue.bucket": + if f.Issue == nil { + return "", true + } + return string(f.Issue.Bucket), true + case "pr.checks": + if f.PR == nil { + return "", true + } + return checksName(f.PR.Checks), true + case "pr.review": + if f.PR == nil { + return "", true + } + return reviewName(f.PR.Review.State), true + case "pr.dco": + if f.PR == nil { + return "", true + } + return dcoName(f.PR.DCO), true + case "pr.base": + if f.PR == nil { + return "", true + } + return f.PR.BaseRef, true + } + return "", false +} + +func setFact(f Facts, name string) ([]string, bool) { + if name == "labels" { + return f.Labels, true + } + return nil, false +} + +func authorKindName(k authorkind.Kind) string { + switch k { + case authorkind.Human: + return "human" + case authorkind.Hive: + return "hive" + case authorkind.Clanker: + return "clanker" + } + return "unknown" +} + +func checksName(c stagelabels.CheckSummary) string { + switch { + case !c.Known: + return "unknown" + case len(c.Red) > 0: + return "red" + case len(c.Missing) > 0: + return "missing" + case c.Pending > 0: + return "pending" + } + return "green" +} + +func reviewName(s stagelabels.VerdictState) string { + switch s { + case stagelabels.VerdictApproved: + return "approved" + case stagelabels.VerdictChangesRequested: + return "changes_requested" + case stagelabels.VerdictUnavailable: + return "unavailable" + } + return "pending" +} + +func dcoName(d stagelabels.DCOState) string { + switch d { + case stagelabels.DCOYes: + return "yes" + case stagelabels.DCONo: + return "no" + } + return "unknown" +} diff --git a/src/pkg/stageengine/workflow_parity_test.go b/src/pkg/stageengine/workflow_parity_test.go new file mode 100644 index 0000000000..a33cfc3825 --- /dev/null +++ b/src/pkg/stageengine/workflow_parity_test.go @@ -0,0 +1,106 @@ +package stageengine_test + +import ( + "reflect" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// TestDeriveFromModelHiveDefaultParity is the RFC's P1 bar +// (hivecommons/hive#17620): under the generated hive-default model every +// Decision is identical to the built-in derivers', across the whole PR +// golden corpus and the issue stage sweep. +func TestDeriveFromModelHiveDefaultParity(t *testing.T) { + p := hivedefault.Profile() + derivers := map[stagelabels.Item][2]stageengine.Deriver{ + stagelabels.IssueItem: {stageengine.IssueDeriver(), stageengine.DeriveFromModel(p, stagelabels.IssueItem)}, + stagelabels.PRItem: {stageengine.PRDeriver(), stageengine.DeriveFromModel(p, stagelabels.PRItem)}, + } + facts := stageengine.ParityFacts() + if len(facts) < 100 { + t.Fatalf("parity corpus has only %d facts", len(facts)) + } + stages := map[stagelabels.Stage]bool{} + for i, f := range facts { + d := derivers[f.Ref.Kind] + want, got := d[0].Derive(f), d[1].Derive(f) + if !reflect.DeepEqual(want, got) { + t.Errorf("facts[%d] %s: built-in %+v, hive-default %+v", i, f.Ref.Key(), want, got) + } + if !want.Abstain && !want.Terminal { + stages[want.Stage] = true + } + } + if len(stages) < 15 { + t.Errorf("corpus reached only %d stages: %v", len(stages), stages) + } +} + +// A nil profile is the built-in deriver, and a model that is missing a +// stage the built-in deriver produced abstains "not covered" rather than +// writing a label the model does not know. +func TestDeriveFromModelCoverage(t *testing.T) { + f := stageengine.ParityFacts()[0] + if f.Ref.Kind != stagelabels.PRItem { + t.Fatalf("expected a PR fixture first, got %s", f.Ref.Kind) + } + nilD := stageengine.DeriveFromModel(nil, stagelabels.PRItem) + if got, want := nilD.Derive(f), stageengine.PRDeriver().Derive(f); !reflect.DeepEqual(got, want) { + t.Fatalf("nil profile: %+v != %+v", got, want) + } + if stageengine.DeriveFromModel(nil, stagelabels.IssueItem).Derive(f).Abstain != true { + t.Fatal("kind mismatch must abstain") + } + + base := stageengine.PRDeriver().Derive(f) + if base.Abstain || base.Terminal { + t.Skipf("first fixture is %+v; coverage case needs a staged PR", base) + } + m := hivedefault.Generate() + drop := hivedefault.StateID(base.Stage) + var kept []workflowmodel.State + for _, s := range m.Spec.States { + if s.ID != drop { + kept = append(kept, s) + } + } + m.Spec.States = kept + var tr []workflowmodel.Transition + for _, x := range m.Spec.Transitions { + if x.From != drop && x.To != drop { + tr = append(tr, x) + } + } + m.Spec.Transitions = tr + for i := range m.Spec.Columns { + var st []string + for _, s := range m.Spec.Columns[i].States { + if s != drop { + st = append(st, s) + } + } + m.Spec.Columns[i].States = st + } + for i := range m.Spec.Agents { + var st []string + for _, s := range m.Spec.Agents[i].States { + if s != drop { + st = append(st, s) + } + } + m.Spec.Agents[i].States = st + } + p, _, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("trimmed model: %v", err) + } + got := stageengine.DeriveFromModel(p, stagelabels.PRItem).Derive(f) + if !got.Abstain || !strings.HasPrefix(got.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("missing state %s: got %+v", drop, got) + } +} diff --git a/src/pkg/stageengine/workflow_rules_test.go b/src/pkg/stageengine/workflow_rules_test.go new file mode 100644 index 0000000000..2af5cfe357 --- /dev/null +++ b/src/pkg/stageengine/workflow_rules_test.go @@ -0,0 +1,208 @@ +package stageengine_test + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +func techdocsProfile(t *testing.T) *workflowmodel.Profile { + t.Helper() + b, err := os.ReadFile("../workflowmodel/testdata/models/techdocs.json") + if err != nil { + t.Fatal(err) + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + p, diags, err := workflowmodel.Compile(&m) + if err != nil { + t.Fatalf("%v %+v", err, diags) + } + return p +} + +func issueFacts(labels ...string) stageengine.Facts { + return stageengine.Facts{ + Ref: stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 1, Kind: stagelabels.IssueItem}, + Open: true, + Labels: labels, + Author: stageengine.AuthorFacts{Kind: authorkind.Human, Login: "nate"}, + Issue: &stageengine.IssueFacts{}, + } +} + +func prFacts(labels ...string) stageengine.Facts { + return stageengine.Facts{ + Ref: stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 2, Kind: stagelabels.PRItem}, + Open: true, + Labels: labels, + Author: stageengine.AuthorFacts{Kind: authorkind.Hive}, + PR: &stageengine.PRFacts{Checks: stagelabels.CheckSummary{Known: true, Total: 2, Green: 2}, DCO: stagelabels.DCOYes}, + } +} + +// TestDeriveFromModelRules walks a TechDocs engagement through the rules +// deriver: ordered first match, kind filtering, glob labels, scalar +// facts, terminal states and the not-covered abstention. +func TestDeriveFromModelRules(t *testing.T) { + p := techdocsProfile(t) + issues := stageengine.DeriveFromModel(p, stagelabels.IssueItem) + prs := stageengine.DeriveFromModel(p, stagelabels.PRItem) + + cases := []struct { + name string + d stageengine.Deriver + f func() stageengine.Facts + stage stagelabels.Stage + term bool + reason string + }{ + {"request filed", issues, func() stageengine.Facts { return issueFacts("techdocs/request") }, stagelabels.Actionable, false, "workflow cncf-techdocs@1: rule requested"}, + {"accepted", issues, func() stageengine.Facts { return issueFacts("techdocs/request", "techdocs/accepted") }, stagelabels.Claimed, false, ""}, + {"analysis posted", issues, func() stageengine.Facts { return issueFacts("techdocs/accepted", "techdocs/analysis") }, stagelabels.IssueNeedsDecision, false, ""}, + {"covered by a draft PR", issues, func() stageengine.Facts { + f := issueFacts("techdocs/analysis") + f.Issue.CoveringPR = &stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 2, Kind: stagelabels.PRItem} + return f + }, stagelabels.CoveredByPR, false, ""}, + {"closed unpublished", issues, func() stageengine.Facts { f := issueFacts("techdocs/request"); f.Open = false; return f }, stagelabels.None, true, "closed without publishing"}, + {"draft PR", prs, func() stageengine.Facts { f := prFacts("techdocs/project-x"); f.Draft = true; return f }, stagelabels.Fixing, false, ""}, + {"ready PR awaits review", prs, func() stageengine.Facts { return prFacts("TechDocs/project-x") }, stagelabels.ReviewPending, false, ""}, + {"approved green PR", prs, func() stageengine.Facts { + f := prFacts("techdocs/project-x") + f.PR.Review.State = stagelabels.VerdictApproved + return f + }, stagelabels.ReadyForHumanMerge, false, ""}, + {"approved but red stays in review", prs, func() stageengine.Facts { + f := prFacts("techdocs/project-x") + f.PR.Review.State = stagelabels.VerdictApproved + f.PR.Checks.Red = []string{"lint"} + return f + }, stagelabels.ReviewPending, false, ""}, + {"merged", prs, func() stageengine.Facts { f := prFacts(); f.Open, f.Merged = false, true; return f }, stagelabels.None, true, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := tc.d.Derive(tc.f()) + if got.Abstain { + t.Fatalf("abstained: %s", got.Reason) + } + if got.Terminal != tc.term || got.Stage != tc.stage { + t.Fatalf("got %+v; want stage %s terminal %v", got, tc.stage, tc.term) + } + if tc.reason != "" && got.Reason != tc.reason { + t.Fatalf("reason %q, want %q", got.Reason, tc.reason) + } + if tc.f().Ref.Kind == stagelabels.PRItem && !tc.term && got.DCO != stagelabels.DCOYes { + t.Fatalf("DCO not carried: %+v", got) + } + }) + } + + t.Run("no rule matches", func(t *testing.T) { + got := issues.Derive(issueFacts("bug")) + if !got.Abstain || !strings.HasPrefix(got.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("%+v", got) + } + }) + t.Run("kind mismatch", func(t *testing.T) { + if got := prs.Derive(issueFacts("techdocs/request")); !got.Abstain { + t.Fatalf("%+v", got) + } + }) + t.Run("stage numbers follow the model", func(t *testing.T) { + if got := issues.Derive(issueFacts("techdocs/request")); got.Stage.Number() != 10 { + t.Fatalf("%+v", got) + } + }) + t.Run("issue-side number on a PR state is not covered", func(t *testing.T) { + q := *p + q.Rules = []workflowmodel.Rule{{State: "requested", When: []workflowmodel.Predicate{{Fact: "open", Op: workflowmodel.OpTrue}}}} + got := stageengine.DeriveFromModel(&q, stagelabels.PRItem).Derive(prFacts()) + if !got.Abstain || !strings.Contains(got.Reason, "not a pr stage") { + t.Fatalf("%+v", got) + } + }) +} + +// Every fact in the vocabulary evaluates; none is silently false because +// the evaluator forgot it. +func TestRulesFactVocabularyIsComplete(t *testing.T) { + p := techdocsProfile(t) + f := prFacts("x/y") + f.PR.Review.State = stagelabels.VerdictChangesRequested + f.PR.BaseRef = "main" + f.PR.ChangesRequested, f.PR.Conflicting, f.PR.HeadFresh = true, true, true + f.Draft, f.Merged = true, true + f.Park.Holds = []string{"hold"} + f.Park.NeedsHuman = true + f.Origin = "origin/scanner" + f.Author.Login = "someone" + fi := issueFacts("x/y") + fi.Issue.Bucket = stageengine.BucketClaimed + fi.Issue.Claim = &stageengine.ClaimFact{} + fi.Issue.CoveringPR = &stageengine.Ref{} + fi.Issue.Stalled = true + fi.Issue.OpenChildren = 1 + + for name, ft := range workflowmodel.Facts { + var pos, neg workflowmodel.Op + value := "" + switch ft { + case workflowmodel.FactBool: + pos, neg = workflowmodel.OpTrue, workflowmodel.OpFalse + case workflowmodel.FactScalar: + pos, neg = workflowmodel.OpIs, workflowmodel.OpNot + value = scalarValue(name) + case workflowmodel.FactSet: + pos, neg = workflowmodel.OpHas, workflowmodel.OpLacks + value = "x/*" + } + facts, state := f, "drafting" + if strings.HasPrefix(name, "issue.") { + facts, state = fi, "requested" + } + rp := *p + rp.Rules = []workflowmodel.Rule{{ID: "t", State: state, When: []workflowmodel.Predicate{{Fact: name, Op: pos, Value: value}}}} + rn := *p + rn.Rules = []workflowmodel.Rule{{ID: "t", State: state, When: []workflowmodel.Predicate{{Fact: name, Op: neg, Value: value}}}} + gp := stageengine.DeriveFromModel(&rp, facts.Ref.Kind).Derive(facts) + gn := stageengine.DeriveFromModel(&rn, facts.Ref.Kind).Derive(facts) + if gp.Abstain == gn.Abstain { + t.Errorf("fact %q: %s → %v, %s → %v (one must match)", name, pos, gp.Abstain, neg, gn.Abstain) + } + if gp.Abstain { + t.Errorf("fact %q: positive predicate %s %q did not hold on %+v", name, pos, value, facts) + } + } +} + +func scalarValue(fact string) string { + switch fact { + case "origin": + return "origin/scanner" + case "author.kind": + return "hive" + case "author.login": + return "someone" + case "issue.bucket": + return string(stageengine.BucketClaimed) + case "pr.checks": + return "green" + case "pr.review": + return "changes_requested" + case "pr.dco": + return "yes" + case "pr.base": + return "main" + } + return "?" +} diff --git a/src/pkg/workflowmodel/compile.go b/src/pkg/workflowmodel/compile.go new file mode 100644 index 0000000000..ce30c1ac6f --- /dev/null +++ b/src/pkg/workflowmodel/compile.go @@ -0,0 +1,469 @@ +package workflowmodel + +import ( + "errors" + "fmt" + "sort" + "strings" +) + +// Diagnostic is one compiler finding. Errors refuse the model; warnings +// are shown in the editor and on the monitor but compile. +type Diagnostic struct { + Code string `json:"code"` + Severity string `json:"severity"` + Subject string `json:"subject,omitempty"` + Detail string `json:"detail"` +} + +// Diagnostic severities. +const ( + DiagError = "error" + DiagWarning = "warning" +) + +// Diagnostic codes. Each is one of the refusals in hivecommons/hive#17620 +// "Deterministic", or a structural check the engine needs. +const ( + CodeNoExit = "state-no-exit" + CodeGateNoOwner = "gate-no-owner" + CodeAgentNoHumanGate = "agent-no-human-gate" + CodeDuplicateEvent = "duplicate-event-fact" + CodeNoColumn = "state-no-column" + CodeUnknownColumn = "unknown-column" + CodeUnknownState = "unknown-state" + CodeColumnEmpty = "column-empty" + CodeNoTerminalColumn = "no-terminal-column" + CodeDuplicateNumber = "duplicate-stage-number" + CodeUnknownFact = "unknown-fact" + CodeBadOp = "bad-op" + CodeNoRules = "no-rules" + CodeBadMode = "bad-derivation-mode" + CodeUnknownRole = "unknown-role" + CodeUnknownGate = "unknown-gate" + CodeUnknownEvent = "unknown-event" + CodeNoVersion = "no-version" + CodeInferred = "inferred-element" +) + +// ErrCompile wraps a compile refused by error diagnostics. +var ErrCompile = errors.New("workflow model does not compile") + +// Profile is a compiled model: what the engine and the monitor consume. +// It is derived, never edited; recompile from the Model instead. +type Profile struct { + Name string `json:"name"` + Version string `json:"version"` + Hash string `json:"hash"` + // Mode is the derivation mode. + Mode DerivationMode `json:"mode"` + // Columns in display order with their states resolved. + Columns []Column `json:"columns"` + // States by id, flattened (regions included). + States map[string]*State `json:"-"` + // ColumnOf maps a state id to its column id. + ColumnOf map[string]string `json:"columnOf"` + // StateOfNumber maps a stage number to the state id that carries it. + StateOfNumber map[int]string `json:"stateOfNumber"` + // Terminal is the set of states in a terminal column or of final type. + Terminal map[string]bool `json:"terminal"` + // Rules are the derivation rules, in evaluation order (rules mode). + Rules []Rule `json:"rules,omitempty"` + // Replies maps a state id to the human-gate verbs it offers. + Replies map[string][]string `json:"replies,omitempty"` + // Labels is the label set to reconcile. + Labels LabelSet `json:"labels,omitzero"` + // Diagnostics are the warnings left after a successful compile. + Diagnostics []Diagnostic `json:"diagnostics,omitempty"` +} + +// Compile validates m, then checks the lifecycle half and builds the +// Profile. Error diagnostics refuse the compile: the returned Profile is +// nil and err wraps ErrCompile; diagnostics are always returned so an +// editor can show them all at once. +func Compile(m *Model) (*Profile, []Diagnostic, error) { + if err := m.Validate(); err != nil { + return nil, []Diagnostic{{Code: "invalid", Severity: DiagError, Detail: err.Error()}}, err + } + c := &compiler{m: m} + c.run() + sort.SliceStable(c.diags, func(i, j int) bool { + if c.diags[i].Severity != c.diags[j].Severity { + return c.diags[i].Severity == DiagError + } + return false + }) + for _, d := range c.diags { + if d.Severity == DiagError { + return nil, c.diags, fmt.Errorf("%w: %s", ErrCompile, summarize(c.diags)) + } + } + c.p.Diagnostics = c.diags + return c.p, c.diags, nil +} + +func summarize(diags []Diagnostic) string { + var parts []string + for _, d := range diags { + if d.Severity != DiagError { + continue + } + if d.Subject != "" { + parts = append(parts, d.Code+" "+d.Subject) + } else { + parts = append(parts, d.Code) + } + } + return strings.Join(parts, "; ") +} + +type compiler struct { + m *Model + p *Profile + diags []Diagnostic +} + +func (c *compiler) errorf(code, subject, format string, a ...any) { + c.diags = append(c.diags, Diagnostic{Code: code, Severity: DiagError, Subject: subject, Detail: fmt.Sprintf(format, a...)}) +} + +func (c *compiler) warnf(code, subject, format string, a ...any) { + c.diags = append(c.diags, Diagnostic{Code: code, Severity: DiagWarning, Subject: subject, Detail: fmt.Sprintf(format, a...)}) +} + +func (c *compiler) run() { + m := c.m + c.p = &Profile{Name: m.Metadata.Name, Version: m.Spec.Meta.Version, Hash: m.Hash(), Mode: m.Spec.Derivation.Mode, States: map[string]*State{}, ColumnOf: map[string]string{}, StateOfNumber: map[int]string{}, Terminal: map[string]bool{}, Replies: map[string][]string{}, Labels: m.Spec.Labels} + if c.p.Version == "" { + c.errorf(CodeNoVersion, "", "spec.meta.version is empty") + } + var flatten func(states []State) + flatten = func(states []State) { + for i := range states { + s := &states[i] + c.p.States[s.ID] = s + flatten(s.Regions) + } + } + flatten(m.Spec.States) + + c.columns() + c.numbers() + c.exits() + c.roles() + c.events() + c.derivation() + c.inferred() +} + +// columns checks every top-level state sits in exactly one column and +// every column names real states; a terminal column must exist. +func (c *compiler) columns() { + m := c.m + cols := map[string]bool{} + terminal := false + for _, col := range m.Spec.Columns { + cols[col.ID] = true + if col.Terminal { + terminal = true + } + if len(col.States) == 0 { + c.errorf(CodeColumnEmpty, col.ID, "column %q collects no state", col.ID) + } + for _, sid := range col.States { + s, ok := c.p.States[sid] + if !ok { + c.errorf(CodeUnknownState, col.ID, "column %q collects unknown state %q", col.ID, sid) + continue + } + if prev, dup := c.p.ColumnOf[sid]; dup && prev != col.ID { + c.errorf(CodeUnknownColumn, sid, "state %q is in columns %q and %q", sid, prev, col.ID) + } + c.p.ColumnOf[sid] = col.ID + if col.Terminal || s.Type == StateFinal { + c.p.Terminal[sid] = true + } + } + } + for _, s := range m.Spec.States { + if s.Lifecycle.Column != "" && !cols[s.Lifecycle.Column] { + c.errorf(CodeUnknownColumn, s.ID, "state %q names column %q, which does not exist", s.ID, s.Lifecycle.Column) + } + if s.Lifecycle.Column != "" && c.p.ColumnOf[s.ID] != "" && c.p.ColumnOf[s.ID] != s.Lifecycle.Column { + c.errorf(CodeUnknownColumn, s.ID, "state %q says column %q but column %q collects it", s.ID, s.Lifecycle.Column, c.p.ColumnOf[s.ID]) + } + if _, ok := c.p.ColumnOf[s.ID]; !ok { + if s.Lifecycle.Column != "" && cols[s.Lifecycle.Column] { + c.p.ColumnOf[s.ID] = s.Lifecycle.Column + continue + } + c.errorf(CodeNoColumn, s.ID, "state %q is not in any column", s.ID) + } + if s.Type == StateFinal { + c.p.Terminal[s.ID] = true + } + } + if len(m.Spec.Columns) > 0 && !terminal { + c.errorf(CodeNoTerminalColumn, "", "no column is terminal") + } + c.p.Columns = append([]Column(nil), m.Spec.Columns...) +} + +// numbers checks stage numbers are unique per item kind. +func (c *compiler) numbers() { + seen := map[string]string{} + for _, s := range c.m.Spec.States { + n := s.Lifecycle.Number + if n == 0 { + continue + } + kinds := s.Lifecycle.Kinds + if len(kinds) == 0 { + kinds = []ItemKind{KindIssue, KindPR} + } + for _, k := range kinds { + key := fmt.Sprintf("%s/%d", k, n) + if prev, dup := seen[key]; dup { + c.errorf(CodeDuplicateNumber, s.ID, "states %q and %q both carry stage number %d for %s", prev, s.ID, n, k) + } + seen[key] = s.ID + } + if _, ok := c.p.StateOfNumber[n]; !ok { + c.p.StateOfNumber[n] = s.ID + } + if len(s.Lifecycle.Replies) > 0 { + c.p.Replies[s.ID] = append([]string(nil), s.Lifecycle.Replies...) + } + } +} + +// exits checks every non-terminal state has a way out. +func (c *compiler) exits() { + out := map[string]bool{} + for _, t := range c.m.Spec.Transitions { + out[t.From] = true + } + for _, s := range c.m.Spec.States { + if c.p.Terminal[s.ID] || out[s.ID] || s.Type == StateParallel { + continue + } + c.errorf(CodeNoExit, s.ID, "state %q is not terminal and has no transition out", s.ID) + } +} + +// roles checks gates name a releasing role and that an agent-granted +// state is followed by a human-released gate on every path out. +func (c *compiler) roles() { + m := c.m + roles := map[string]RoleDef{} + for _, r := range m.Spec.Roles { + roles[r.ID] = r + } + gates := map[string]Gate{} + for _, g := range m.Spec.Gates { + gates[g.ID] = g + if g.ReleasedBy == "" { + c.errorf(CodeGateNoOwner, g.ID, "gate %q has no releasing role", g.ID) + continue + } + if _, ok := roles[g.ReleasedBy]; !ok { + c.errorf(CodeUnknownRole, g.ID, "gate %q is released by unknown role %q", g.ID, g.ReleasedBy) + } + } + for _, t := range m.Spec.Transitions { + if t.GateRef != "" { + if _, ok := gates[t.GateRef]; !ok { + c.errorf(CodeUnknownGate, t.From+"->"+t.To, "transition %s->%s needs unknown gate %q", t.From, t.To, t.GateRef) + } + } + } + for _, e := range m.Spec.Events { + if e.Actor != "" { + if _, ok := roles[e.Actor]; !ok { + c.errorf(CodeUnknownRole, e.ID, "event %q actor %q is not a role", e.ID, e.Actor) + } + } + } + if len(m.Spec.Agents) == 0 { + return + } + humanGate := func(t Transition) bool { + g, ok := gates[t.GateRef] + return ok && roles[g.ReleasedBy].Human + } + // A closure edge (item closed unmerged) is an observation, not an + // outcome an agent can bring about, so it is not a path to inspect. + events := map[string]Event{} + for _, e := range m.Spec.Events { + events[e.ID] = e + } + closure := func(t Transition) bool { + e, ok := events[t.On] + return ok && c.p.Terminal[t.To] && e.Fact.Fact == "open" && e.Fact.Op == OpFalse + } + // adjacency over transitions + next := map[string][]Transition{} + for _, t := range m.Spec.Transitions { + next[t.From] = append(next[t.From], t) + } + for _, a := range m.Spec.Agents { + for _, sid := range a.States { + if _, ok := c.p.States[sid]; !ok { + c.errorf(CodeUnknownState, a.Profile, "agent %q acts in unknown state %q", a.Profile, sid) + continue + } + if !c.humanGateReachable(sid, next, humanGate, closure) { + c.errorf(CodeAgentNoHumanGate, sid, "agent %q acts in %q but no human-released gate follows it before a terminal state", a.Profile, sid) + } + } + } +} + +// humanGateReachable is true when every path from start to a terminal +// state crosses a human-released gate (a path with no such gate is a +// refusal). Cycles without a gate do not count as a path; closure edges +// are skipped. +func (c *compiler) humanGateReachable(start string, next map[string][]Transition, human, skip func(Transition) bool) bool { + var visit func(state string, seen map[string]bool) bool + visit = func(state string, seen map[string]bool) bool { + if c.p.Terminal[state] { + return false // reached terminal without a gate + } + if seen[state] { + return true // cycle: no gate-free path to terminal through here + } + seen[state] = true + defer delete(seen, state) + for _, t := range next[state] { + if human(t) || skip(t) { + continue + } + if !visit(t.To, seen) { + return false + } + } + return true + } + return visit(start, map[string]bool{}) +} + +// events checks no two events bind the same predicate and transitions +// name declared events. +func (c *compiler) events() { + m := c.m + ids := map[string]bool{} + byFact := map[string]string{} + for _, e := range m.Spec.Events { + ids[e.ID] = true + c.predicate(e.ID, e.Fact) + k := e.Fact.Fact + "|" + string(e.Fact.Op) + "|" + e.Fact.Value + if prev, dup := byFact[k]; dup { + c.errorf(CodeDuplicateEvent, e.ID, "events %q and %q both fire on %s %s %s", prev, e.ID, e.Fact.Fact, e.Fact.Op, e.Fact.Value) + } + byFact[k] = e.ID + } + if len(m.Spec.Events) == 0 { + return + } + for _, t := range m.Spec.Transitions { + if t.On != "" && !ids[t.On] { + c.errorf(CodeUnknownEvent, t.From+"->"+t.To, "transition %s->%s fires on undeclared event %q", t.From, t.To, t.On) + } + } + for _, b := range m.Spec.Bookkeeping { + if !ids[b.On] { + c.errorf(CodeUnknownEvent, b.Action, "bookkeeping %q fires on undeclared event %q", b.Action, b.On) + } + } +} + +// predicate checks a predicate against the fact vocabulary. +func (c *compiler) predicate(subject string, p Predicate) { + ft, ok := Facts[p.Fact] + if !ok { + c.errorf(CodeUnknownFact, subject, "fact %q is not in the vocabulary", p.Fact) + return + } + valid := map[FactType][]Op{ + FactBool: {OpTrue, OpFalse}, + FactScalar: {OpIs, OpNot}, + FactSet: {OpHas, OpLacks}, + }[ft] + for _, op := range valid { + if op == p.Op { + if ft != FactBool && p.Value == "" { + c.errorf(CodeBadOp, subject, "fact %q %s needs a value", p.Fact, p.Op) + } + return + } + } + c.errorf(CodeBadOp, subject, "fact %q is %s; operator %q does not apply", p.Fact, ft, p.Op) +} + +// derivation checks the mode and compiles the rules. +func (c *compiler) derivation() { + d := c.m.Spec.Derivation + switch d.Mode { + case DerivationBuiltin: + if len(d.Rules) > 0 { + c.warnf(CodeBadMode, "", "derivation is builtin; %d rules are ignored", len(d.Rules)) + } + case DerivationRules: + if len(d.Rules) == 0 { + c.errorf(CodeNoRules, "", "derivation is rules but spec.derivation.rules is empty") + } + for i, r := range d.Rules { + subject := r.ID + if subject == "" { + subject = fmt.Sprintf("rules[%d]", i) + } + if _, ok := c.p.States[r.State]; !ok { + c.errorf(CodeUnknownState, subject, "rule %s puts items in unknown state %q", subject, r.State) + } + if len(r.When) == 0 { + c.warnf(CodeNoRules, subject, "rule %s has no predicates and matches everything after it is reached", subject) + } + for _, p := range r.When { + c.predicate(subject, p) + } + } + c.p.Rules = append([]Rule(nil), d.Rules...) + default: + c.errorf(CodeBadMode, "", "spec.derivation.mode %q is not builtin or rules", d.Mode) + } +} + +// inferred warns about every element a human has not confirmed. +func (c *compiler) inferred() { + for _, s := range c.m.Spec.States { + if s.Lifecycle.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, s.ID, "state %q is inferred and unconfirmed", s.ID) + } + } + for _, e := range c.m.Spec.Events { + if e.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, e.ID, "event %q is inferred and unconfirmed", e.ID) + } + } + for _, g := range c.m.Spec.Gates { + if g.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, g.ID, "gate %q is inferred and unconfirmed", g.ID) + } + } +} + +// StateForNumber returns the state carrying stage number n, if any. +func (p *Profile) StateForNumber(n int) (string, bool) { + s, ok := p.StateOfNumber[n] + return s, ok +} + +// Column returns the column with id, or nil. +func (p *Profile) Column(id string) *Column { + for i := range p.Columns { + if p.Columns[i].ID == id { + return &p.Columns[i] + } + } + return nil +} diff --git a/src/pkg/workflowmodel/compile_test.go b/src/pkg/workflowmodel/compile_test.go new file mode 100644 index 0000000000..38ee918c6c --- /dev/null +++ b/src/pkg/workflowmodel/compile_test.go @@ -0,0 +1,175 @@ +package workflowmodel + +import ( + "encoding/json" + "os" + "strings" + "testing" +) + +func loadModel(t *testing.T, path string) *Model { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var m Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return &m +} + +func techdocs(t *testing.T) *Model { return loadModel(t, "testdata/models/techdocs.json") } + +func TestCompileTechDocs(t *testing.T) { + p, diags, err := Compile(techdocs(t)) + if err != nil { + t.Fatalf("%v\n%+v", err, diags) + } + if p.Mode != DerivationRules || len(p.Rules) != 9 { + t.Fatalf("mode %s rules %d", p.Mode, len(p.Rules)) + } + if p.ColumnOf["draft-review"] != "writing" || !p.Terminal["published"] || p.Terminal["approved"] { + t.Fatalf("columns %v terminal %v", p.ColumnOf, p.Terminal) + } + if id, ok := p.StateForNumber(45); !ok || id != "analysis-review" { + t.Fatalf("StateForNumber(45) = %q %v", id, ok) + } + if got := p.Replies["draft-review"]; len(got) != 2 { + t.Fatalf("replies %v", got) + } + if p.Hash == "" || p.Version != "1" { + t.Fatalf("hash %q version %q", p.Hash, p.Version) + } + for _, d := range diags { + if d.Severity == DiagError { + t.Errorf("unexpected error diagnostic %+v", d) + } + } +} + +// Each refusal from the RFC's "Deterministic" list, and the structural +// checks around them, produces its code and no Profile. +func TestCompileRefusals(t *testing.T) { + cases := []struct { + name string + mut func(m *Model) + code string + }{ + {"no version", func(m *Model) { m.Spec.Meta.Version = "" }, CodeNoVersion}, + {"state without exit", func(m *Model) { + var tr []Transition + for _, x := range m.Spec.Transitions { + if x.From != "approved" { + tr = append(tr, x) + } + } + m.Spec.Transitions = tr + }, CodeNoExit}, + {"gate without owner", func(m *Model) { m.Spec.Gates[0].ReleasedBy = "" }, CodeGateNoOwner}, + {"gate with unknown role", func(m *Model) { m.Spec.Gates[0].ReleasedBy = "nobody" }, CodeUnknownRole}, + {"agent with no human gate after it", func(m *Model) { + for i := range m.Spec.Roles { + m.Spec.Roles[i].Human = false + } + }, CodeAgentNoHumanGate}, + {"agent in unknown state", func(m *Model) { m.Spec.Agents[0].States = []string{"ghost"} }, CodeUnknownState}, + {"two events on one fact", func(m *Model) { m.Spec.Events[1].Fact = m.Spec.Events[0].Fact }, CodeDuplicateEvent}, + {"state in no column", func(m *Model) { m.Spec.Columns[0].States = []string{"analysing"} }, CodeNoColumn}, + {"state in two columns", func(m *Model) { m.Spec.Columns[0].States = []string{"requested", "analysing"} }, CodeUnknownColumn}, + {"state names a column that does not collect it", func(m *Model) { m.Spec.States[0].Lifecycle.Column = "done" }, CodeUnknownColumn}, + {"column collects unknown state", func(m *Model) { m.Spec.Columns[0].States = append(m.Spec.Columns[0].States, "ghost") }, CodeUnknownState}, + {"empty column", func(m *Model) { m.Spec.Columns = append(m.Spec.Columns, Column{ID: "x", Label: "x"}) }, CodeColumnEmpty}, + {"no terminal column", func(m *Model) { m.Spec.Columns[4].Terminal = false }, CodeNoTerminalColumn}, + {"duplicate stage number", func(m *Model) { m.Spec.States[1].Lifecycle.Number = 10 }, CodeDuplicateNumber}, + {"unknown fact", func(m *Model) { m.Spec.Derivation.Rules[0].When[0].Fact = "weather" }, CodeUnknownFact}, + {"bad operator", func(m *Model) { m.Spec.Derivation.Rules[0].When[0].Op = OpHas }, CodeBadOp}, + {"scalar op without value", func(m *Model) { m.Spec.Derivation.Rules[2].When[0].Value = "" }, CodeBadOp}, + {"rules mode with no rules", func(m *Model) { m.Spec.Derivation.Rules = nil }, CodeNoRules}, + {"rule names unknown state", func(m *Model) { m.Spec.Derivation.Rules[0].State = "ghost" }, CodeUnknownState}, + {"bad derivation mode", func(m *Model) { m.Spec.Derivation.Mode = "oracle" }, CodeBadMode}, + {"transition on undeclared event", func(m *Model) { m.Spec.Transitions[0].On = "thunder" }, CodeUnknownEvent}, + {"transition needs unknown gate", func(m *Model) { m.Spec.Transitions[0].GateRef = "ghost" }, CodeUnknownGate}, + {"event actor is not a role", func(m *Model) { m.Spec.Events[0].Actor = "ghost" }, CodeUnknownRole}, + {"bookkeeping on undeclared event", func(m *Model) { + m.Spec.Bookkeeping = []Effect{{On: "thunder", Action: "comment"}} + }, CodeUnknownEvent}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := techdocs(t) + tc.mut(m) + p, diags, err := Compile(m) + if err == nil || p != nil { + t.Fatalf("compiled; diags %+v", diags) + } + if !strings.Contains(err.Error(), ErrCompile.Error()) { + t.Fatalf("err %v does not wrap ErrCompile", err) + } + found := false + for _, d := range diags { + if d.Code == tc.code && d.Severity == DiagError { + found = true + } + } + if !found { + t.Fatalf("want %s in %+v", tc.code, diags) + } + }) + } +} + +func TestCompileWarnings(t *testing.T) { + m := techdocs(t) + m.Spec.Gates[0].Confidence = ConfidenceInferred + m.Spec.Events[0].Confidence = ConfidenceInferred + p, diags, err := Compile(m) + if err != nil { + t.Fatal(err) + } + n := 0 + for _, d := range diags { + if d.Code == CodeInferred && d.Severity == DiagWarning { + n++ + } + } + if n != 2 || len(p.Diagnostics) != len(diags) { + t.Fatalf("inferred warnings %d; profile carries %d of %d", n, len(p.Diagnostics), len(diags)) + } + + m = techdocs(t) + m.Spec.Derivation.Mode = DerivationBuiltin + if _, diags, err = Compile(m); err != nil { + t.Fatal(err) + } + if len(diags) != 1 || diags[0].Code != CodeBadMode || diags[0].Severity != DiagWarning { + t.Fatalf("builtin with rules: %+v", diags) + } +} + +func TestCompileInvalidModel(t *testing.T) { + m := techdocs(t) + m.Spec.Initial = "ghost" + p, diags, err := Compile(m) + if err == nil || p != nil || len(diags) != 1 || diags[0].Code != "invalid" { + t.Fatalf("%v %+v", err, diags) + } +} + +// A closure edge out of an agent state is an observation, not a way for +// the agent to reach an outcome unsupervised; a merge edge is. +func TestCompileClosureEdgesAreNotAgentPaths(t *testing.T) { + m := techdocs(t) + if _, _, err := Compile(m); err != nil { + t.Fatal(err) + } + m.Spec.Transitions = append(m.Spec.Transitions, Transition{From: "drafting", To: "published", On: "merged"}) + _, diags, err := Compile(m) + if err == nil { + t.Fatal("agent merging its own draft must be refused") + } + if !strings.Contains(err.Error(), CodeAgentNoHumanGate+" drafting") { + t.Fatalf("%v %+v", err, diags) + } +} diff --git a/src/pkg/workflowmodel/hivedefault/hivedefault.go b/src/pkg/workflowmodel/hivedefault/hivedefault.go new file mode 100644 index 0000000000..80f488b950 --- /dev/null +++ b/src/pkg/workflowmodel/hivedefault/hivedefault.go @@ -0,0 +1,254 @@ +// Package hivedefault generates the `hive-default` workflow model: Hive's +// own lifecycle expressed in the workflow-model schema +// (hivecommons/hive#17620). Nothing here is hand-maintained: states come +// from stagelabels.Table, transitions from stageengine.DiagramEdges and +// the columns from the Activity Monitor's layout constants, so the model +// is the schema's conformance test — if it cannot express Hive's graph, +// the schema is not done. +// +// The model declares derivation mode builtin: an item's state is still +// decided by the Go derivers, and DeriveFromModel only checks that what +// they produce is a state the model knows. That is what keeps the stage +// goldens byte-for-byte and the v5/v6 monitor pixel-identical for +// repositories that bind nothing. +package hivedefault + +import ( + "fmt" + "sort" + "strings" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +// Name is the model's metadata.name; Version its spec.meta.version. The +// version is bumped by hand when the generator's output changes shape. +const ( + Name = "hive-default" + Version = "1" +) + +// Column ids. These are the Activity Monitor's columns in order; the +// anchor numbers mirror STAGE_TRACKER_PATH = [0, 10, 20, 30, 50, 80] plus +// the terminal Merged cap (agent-now.js, tracker-motion.js). +const ( + ColumnOpen = "open" + ColumnActionable = "actionable" + ColumnClaimed = "claimed" + ColumnPRInProgress = "pr-in-progress" + ColumnCIReview = "ci-review" + ColumnMergeQueue = "merge-queue" + ColumnMerged = "merged" +) + +// Terminal state ids (no stage label; observed, not written). +const ( + StateOpen = "open" + StateMerged = "merged" + StateClosed = "closed" +) + +// Role ids. +const ( + RoleMaintainer = "maintainer" + RoleAuthor = "author" + RoleReviewSwarm = "review-swarm" + RoleHiveAgent = "hive-agent" + RoleCI = "ci" +) + +// Gate and event ids. +const ( + GateMaintainerDecision = "maintainer-decision" + GateMaintainerApprove = "maintainer-approve" + GateAuthorPush = "author-push" + EventOpened = "opened" + EventMerged = "merged" + EventClosed = "closed" + EventStageChange = "stage-change" +) + +// columnAnchors maps a stage number to the column that lights for it, +// mirroring stageTrackerColumn / tracker-row-anchor.js. Every Table +// number must be here; Generate panics otherwise. +var columnAnchors = map[int]string{ + 10: ColumnActionable, 15: ColumnActionable, 17: ColumnActionable, 18: ColumnActionable, 45: ColumnActionable, + 20: ColumnClaimed, + 30: ColumnPRInProgress, 40: ColumnPRInProgress, + 50: ColumnCIReview, 60: ColumnCIReview, 70: ColumnCIReview, 71: ColumnCIReview, 72: ColumnCIReview, 74: ColumnCIReview, + 80: ColumnMergeQueue, 85: ColumnMergeQueue, 90: ColumnMergeQueue, 95: ColumnMergeQueue, 100: ColumnMergeQueue, +} + +// replies are the human-gate verbs the monitor offers in a stage today +// (tracker-actions.js); declared here so a model can carry its own. +var replies = map[int][]string{ + 15: {"accept-triage", "decide:close-issue"}, + 17: {"decide:approve", "decide:close-superseded"}, + 45: {"decide:delegate", "decide:approve", "decide:direction", "decide:close-superseded", "decide:close-wontfix", "hold"}, + 85: {"decide:delegate", "decide:approve", "decide:direction", "decide:merge-now", "decide:queue-merge", "decide:adopt", "decide:close-superseded", "hold"}, + 90: {"decide:approve", "decide:merge-now"}, +} + +// owner says who moves work out of a stage. +func owner(d stagelabels.Definition) workflowmodel.Owner { + switch d.Stage { + case stagelabels.TriageNeeded, stagelabels.PossiblyExisting, stagelabels.OpenForDiscussion, stagelabels.IssueNeedsDecision, + stagelabels.NeedsDecision, stagelabels.ReadyForHumanMerge, stagelabels.NeedsAuthor, stagelabels.ReturnedToContributor: + return workflowmodel.OwnerHuman + case stagelabels.ReviewPending, stagelabels.Reviewed, stagelabels.AwaitingMergeAdmission, stagelabels.PreMergeSoak, stagelabels.MergeQueue: + return workflowmodel.OwnerExternalService + case stagelabels.CoveredByPR: + return workflowmodel.OwnerExternalObservation + } + return workflowmodel.OwnerRegisteredAgent +} + +// StateID is the model state id for a stage: its slug, suffixed with the +// item kind where two stages share a slug (045 and 085 needs-decision). +func StateID(s stagelabels.Stage) string { + switch s { + case stagelabels.None: + return "" + case stagelabels.IssueNeedsDecision: + return "needs-decision-issue" + case stagelabels.NeedsDecision: + return "needs-decision-pr" + } + return s.Slug() +} + +// Generate builds the hive-default model from the live stage table. +func Generate() *workflowmodel.Model { + m := workflowmodel.New(Name, workflowmodel.Scope{Forge: "github.com", Repository: "*"}) + m.Spec.Meta = workflowmodel.Meta{Version: Version, Author: "hivecommons", Description: "Hive's built-in issue and pull-request lifecycle, generated from the stage table", License: "Apache-2.0", Source: workflowmodel.SourceBuiltIn, Provenance: workflowmodel.ProvenanceBuiltIn} + m.Spec.Initial = StateOpen + m.Spec.Derivation = workflowmodel.Derivation{Mode: workflowmodel.DerivationBuiltin} + m.Spec.Labels.Prefix = stagelabels.Prefix + + order := []workflowmodel.Column{ + {ID: ColumnOpen, Label: "Open", Hint: "Filed; not yet staged", States: []string{StateOpen}}, + {ID: ColumnActionable, Label: "Actionable", Hint: "Triaged or parked on a person"}, + {ID: ColumnClaimed, Label: "Claimed", Hint: "An agent or contributor holds it"}, + {ID: ColumnPRInProgress, Label: "PR in progress", Hint: "A PR is under way or open"}, + {ID: ColumnCIReview, Label: "CI / Review", Hint: "Verdict and checks on the current head"}, + {ID: ColumnMergeQueue, Label: "Merge queue", Hint: "Admitted; waiting on soak, tide or a human merge"}, + {ID: ColumnMerged, Label: "Merged", Hint: "Done", Terminal: true, States: []string{StateMerged, StateClosed}}, + } + cols := map[string]*workflowmodel.Column{} + for i := range order { + cols[order[i].ID] = &order[i] + } + + m.Spec.States = append(m.Spec.States, workflowmodel.State{ID: StateOpen, Label: "Open", Owner: workflowmodel.OwnerExternalObservation, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnOpen}}) + + table := append([]stagelabels.Definition(nil), stagelabels.Table...) + sort.SliceStable(table, func(i, j int) bool { return table[i].Number < table[j].Number }) + for _, d := range table { + id := StateID(d.Stage) + col, ok := columnAnchors[d.Number] + if !ok { + panic(fmt.Sprintf("hivedefault: stage %d has no column anchor", d.Number)) + } + var kinds []workflowmodel.ItemKind + if d.Issue { + kinds = append(kinds, workflowmodel.KindIssue) + } + if d.PR { + kinds = append(kinds, workflowmodel.KindPR) + } + st := workflowmodel.State{ID: id, Label: label(d), Owner: owner(d), Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: col, Number: d.Number, Kinds: kinds, Replies: replies[d.Number]}} + if d.Dwell > 0 { + st.Lifecycle.Waiting = []string{"stalled after " + d.Dwell.String()} + } + m.Spec.States = append(m.Spec.States, st) + cols[col].States = append(cols[col].States, id) + m.Spec.Labels.Entries = append(m.Spec.Labels.Entries, workflowmodel.LabelEntry{Name: d.Stage.Label(), Description: d.Description, State: id}) + } + m.Spec.States = append(m.Spec.States, + workflowmodel.State{ID: StateMerged, Label: "Merged", Owner: workflowmodel.OwnerExternalObservation, Type: workflowmodel.StateFinal, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnMerged, Kinds: []workflowmodel.ItemKind{workflowmodel.KindPR}}}, + workflowmodel.State{ID: StateClosed, Label: "Closed", Owner: workflowmodel.OwnerExternalObservation, Type: workflowmodel.StateFinal, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnMerged}}, + ) + m.Spec.Columns = order + + m.Spec.Roles = []workflowmodel.RoleDef{ + {ID: RoleMaintainer, Label: "Maintainer", Kind: workflowmodel.RolePermission, Params: map[string]string{"permission": "write"}, Human: true}, + {ID: RoleAuthor, Label: "Author", Kind: workflowmodel.RoleAuthorKind, Params: map[string]string{"kind": "human"}, Human: true}, + {ID: RoleReviewSwarm, Label: "Review swarm", Kind: workflowmodel.RoleBot, Params: map[string]string{"login": "hive"}}, + {ID: RoleHiveAgent, Label: "Hive agent", Kind: workflowmodel.RoleBot, Params: map[string]string{"login": "hive"}}, + {ID: RoleCI, Label: "CI", Kind: workflowmodel.RoleBot}, + } + m.Spec.Gates = []workflowmodel.Gate{ + {ID: GateMaintainerDecision, ReleasedBy: RoleMaintainer, Reply: "/hive decision"}, + {ID: GateMaintainerApprove, ReleasedBy: RoleMaintainer, Reply: "/lgtm /approve", Conditions: []workflowmodel.Predicate{{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "green"}}}, + {ID: GateAuthorPush, ReleasedBy: RoleAuthor}, + } + m.Spec.Events = []workflowmodel.Event{ + {ID: EventOpened, Label: "Item opened", Fact: workflowmodel.Predicate{Fact: "open", Op: workflowmodel.OpTrue}}, + {ID: EventMerged, Label: "PR merged", Fact: workflowmodel.Predicate{Fact: "merged", Op: workflowmodel.OpTrue}}, + {ID: EventClosed, Label: "Item closed unmerged", Fact: workflowmodel.Predicate{Fact: "open", Op: workflowmodel.OpFalse}}, + {ID: "claimed", Label: "Claim taken", Fact: workflowmodel.Predicate{Fact: "issue.claimed", Op: workflowmodel.OpTrue}}, + {ID: "covered", Label: "PR covers the issue", Fact: workflowmodel.Predicate{Fact: "issue.covered", Op: workflowmodel.OpTrue}}, + {ID: "checks-green", Label: "Checks green", Fact: workflowmodel.Predicate{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "green"}}, + {ID: "checks-red", Label: "Checks red", Fact: workflowmodel.Predicate{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "red"}}, + {ID: "review-approved", Label: "Verdict approve", Fact: workflowmodel.Predicate{Fact: "pr.review", Op: workflowmodel.OpIs, Value: "approved"}}, + {ID: "changes-requested", Label: "Changes requested", Fact: workflowmodel.Predicate{Fact: "pr.changes_requested", Op: workflowmodel.OpTrue}}, + {ID: "held", Label: "Hold label applied", Fact: workflowmodel.Predicate{Fact: "hold", Op: workflowmodel.OpTrue}}, + {ID: "parked", Label: "Park label applied", Fact: workflowmodel.Predicate{Fact: "park", Op: workflowmodel.OpTrue}}, + {ID: EventStageChange, Label: "Stage re-derived", Fact: workflowmodel.Predicate{Fact: "labels", Op: workflowmodel.OpHas, Value: stagelabels.Prefix + "*"}}, + } + m.Spec.Agents = []workflowmodel.AgentGrant{ + {Profile: "scanner", States: []string{StateID(stagelabels.Actionable), StateID(stagelabels.TriageNeeded), StateID(stagelabels.OpenForDiscussion)}, Produces: []string{"claim"}}, + {Profile: "worker", States: []string{StateID(stagelabels.Claimed), StateID(stagelabels.PRInProgress), StateID(stagelabels.Fixing), StateID(stagelabels.AdoptedByHive)}, Produces: []string{"pull-request", "push"}}, + {Profile: "review-swarm", States: []string{StateID(stagelabels.ReviewPending)}, Produces: []string{"review"}}, + } + + // Transitions from the expected-edge table; gates on the edges a human + // releases. + for _, e := range stageengine.DiagramEdges() { + t := workflowmodel.Transition{From: StateID(e.From), To: StateID(e.To), On: EventStageChange, Note: fmt.Sprintf("%s → %s", e.From, e.To)} + switch { + case e.From == stagelabels.IssueNeedsDecision || e.From == stagelabels.NeedsDecision || e.From == stagelabels.PossiblyExisting: + t.GateRef = GateMaintainerDecision + case e.From == stagelabels.ReadyForHumanMerge && e.To == stagelabels.MergeQueue: + t.GateRef = GateMaintainerApprove + case e.From == stagelabels.NeedsAuthor || e.From == stagelabels.ReturnedToContributor: + t.GateRef = GateAuthorPush + } + m.Spec.Transitions = append(m.Spec.Transitions, t) + } + // Intake and terminal edges, which the diagram draws as [*]. + m.Spec.Transitions = append(m.Spec.Transitions, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.Actionable), On: EventOpened, Note: "triaged intake"}, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.TriageNeeded), On: EventOpened, Note: "reporter-trust gate"}, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.ReviewPending), On: EventOpened, Note: "PR opened"}, + ) + for _, d := range table { + switch d.Stage { + case stagelabels.MergeQueue: + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateMerged, On: EventMerged, GateRef: GateMaintainerApprove, Note: "tide / lane merges"}) + case stagelabels.ReadyForHumanMerge: + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateMerged, On: EventMerged, GateRef: GateMaintainerApprove, Note: "maintainer merges"}) + } + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateClosed, On: EventClosed}) + } + return m +} + +// label is the display label for a stage: its slug, humanised. +func label(d stagelabels.Definition) string { + s := strings.ReplaceAll(d.Slug, "-", " ") + return strings.ToUpper(s[:1]) + s[1:] +} + +// Profile generates and compiles the model. It panics on a compile +// error: the generator and the schema ship together, so a refusal is a +// programming error, not an operator one. +func Profile() *workflowmodel.Profile { + p, diags, err := workflowmodel.Compile(Generate()) + if err != nil { + panic(fmt.Sprintf("hivedefault: %v (%d diagnostics)", err, len(diags))) + } + return p +} diff --git a/src/pkg/workflowmodel/hivedefault/hivedefault_test.go b/src/pkg/workflowmodel/hivedefault/hivedefault_test.go new file mode 100644 index 0000000000..585029e136 --- /dev/null +++ b/src/pkg/workflowmodel/hivedefault/hivedefault_test.go @@ -0,0 +1,151 @@ +package hivedefault + +import ( + "encoding/json" + "testing" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +func TestGenerateCompiles(t *testing.T) { + m := Generate() + if err := m.Validate(); err != nil { + t.Fatal(err) + } + p, diags, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("%v\n%+v", err, diags) + } + if len(diags) != 0 { + t.Errorf("hive-default must compile clean, got %+v", diags) + } + if p.Name != Name || p.Version != Version || p.Mode != workflowmodel.DerivationBuiltin { + t.Fatalf("profile %s@%s mode %s", p.Name, p.Version, p.Mode) + } + if Profile().Hash != p.Hash { + t.Fatal("Profile() is not Generate() compiled") + } +} + +func TestEveryStageIsAState(t *testing.T) { + p := Profile() + ids := map[string]bool{} + for _, d := range stagelabels.Table { + id := StateID(d.Stage) + if ids[id] { + t.Errorf("StateID(%s) = %q collides", d.Stage, id) + } + ids[id] = true + s, ok := p.States[id] + if !ok { + t.Errorf("stage %s has no state %q", d.Stage, id) + continue + } + if s.Lifecycle.Number != d.Number { + t.Errorf("state %q number %d, stage %d", id, s.Lifecycle.Number, d.Number) + } + if got, ok := p.StateForNumber(d.Number); !ok || got != id { + t.Errorf("StateForNumber(%d) = %q %v, want %q", d.Number, got, ok, id) + } + if p.ColumnOf[id] == "" || p.ColumnOf[id] == ColumnOpen || p.ColumnOf[id] == ColumnMerged { + t.Errorf("state %q sits in column %q", id, p.ColumnOf[id]) + } + wantKind := workflowmodel.KindIssue + if d.PR { + wantKind = workflowmodel.KindPR + } + if len(s.Lifecycle.Kinds) != 1 || s.Lifecycle.Kinds[0] != wantKind { + t.Errorf("state %q kinds %v, want [%s]", id, s.Lifecycle.Kinds, wantKind) + } + } + if StateID(stagelabels.IssueNeedsDecision) == StateID(stagelabels.NeedsDecision) { + t.Error("045 and 085 must have distinct state ids") + } +} + +func TestColumnsMatchTheMonitor(t *testing.T) { + p := Profile() + want := []string{ColumnOpen, ColumnActionable, ColumnClaimed, ColumnPRInProgress, ColumnCIReview, ColumnMergeQueue, ColumnMerged} + if len(p.Columns) != len(want) { + t.Fatalf("columns %+v", p.Columns) + } + for i, c := range p.Columns { + if c.ID != want[i] { + t.Errorf("column %d = %q, want %q", i, c.ID, want[i]) + } + if c.Terminal != (c.ID == ColumnMerged) { + t.Errorf("column %q terminal %v", c.ID, c.Terminal) + } + } + // tracker-row-anchor.js: 15/17/18/45 light Actionable, 40 lights PR in + // progress, 6x/7x light CI / Review, 85+ light Merge queue. + for n, col := range map[int]string{10: ColumnActionable, 15: ColumnActionable, 45: ColumnActionable, 20: ColumnClaimed, 30: ColumnPRInProgress, 40: ColumnPRInProgress, 50: ColumnCIReview, 60: ColumnCIReview, 74: ColumnCIReview, 80: ColumnMergeQueue, 85: ColumnMergeQueue, 100: ColumnMergeQueue} { + id, _ := p.StateForNumber(n) + if p.ColumnOf[id] != col { + t.Errorf("stage %d (%s) in %q, want %q", n, id, p.ColumnOf[id], col) + } + } + if !p.Terminal[StateMerged] || !p.Terminal[StateClosed] || p.Terminal[StateOpen] { + t.Errorf("terminal %v", p.Terminal) + } +} + +// The transition graph is the stage engine's expected-edge table plus +// intake and closure: no edge the engine would log as an anomaly. +func TestTransitionsMirrorTheEngine(t *testing.T) { + m := Generate() + have := map[[2]string]bool{} + for _, tr := range m.Spec.Transitions { + have[[2]string{tr.From, tr.To}] = true + } + for _, e := range stageengine.DiagramEdges() { + k := [2]string{StateID(e.From), StateID(e.To)} + if !have[k] { + t.Errorf("engine edge %s -> %s missing from the model", e.From, e.To) + } + } + for _, d := range stagelabels.Table { + id := StateID(d.Stage) + if !have[[2]string{id, StateClosed}] { + t.Errorf("%s has no closure edge", id) + } + } + if !have[[2]string{StateOpen, StateID(stagelabels.Actionable)}] || !have[[2]string{StateOpen, StateID(stagelabels.ReviewPending)}] { + t.Error("intake edges missing") + } +} + +func TestModelRoundTripsJSON(t *testing.T) { + m := Generate() + b, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + var back workflowmodel.Model + if err := json.Unmarshal(b, &back); err != nil { + t.Fatal(err) + } + p1, _, err := workflowmodel.Compile(&back) + if err != nil { + t.Fatal(err) + } + if p1.Hash != Profile().Hash { + t.Fatal("hash changed across a JSON round trip") + } +} + +func TestOwnerAndStateIDHelpers(t *testing.T) { + if StateID(stagelabels.None) != "" { + t.Error("None is not a state") + } + for _, d := range stagelabels.Table { + if owner(d) == "" { + t.Errorf("stage %s has no owner", d.Stage) + } + if label(d) == "" { + t.Errorf("stage %s has no label", d.Stage) + } + } +} diff --git a/src/pkg/workflowmodel/lifecycle.go b/src/pkg/workflowmodel/lifecycle.go new file mode 100644 index 0000000000..d98e937376 --- /dev/null +++ b/src/pkg/workflowmodel/lifecycle.go @@ -0,0 +1,272 @@ +package workflowmodel + +// This file holds the lifecycle half of the schema (hivecommons/hive#17620 +// "The model"): columns, stage numbers, events, gates, roles, agents, +// checks, bookkeeping and labels. The ingest half (pipelines, coverage) is +// in model.go. A model that only carries the ingest half still validates; +// Compile needs the lifecycle half too. + +// Meta describes a model for the library and, later, the marketplace. +type Meta struct { + Version string `json:"version"` + Author string `json:"author,omitempty"` + Description string `json:"description,omitempty"` + License string `json:"license,omitempty"` + Source MetaSource `json:"source,omitempty"` + // Provenance is how much a human has vouched for the model. + Provenance Provenance `json:"provenance,omitempty"` +} + +// MetaSource is where the model came from. +type MetaSource string + +// Sources a model can be ingested from or written by. +const ( + SourceGitHubActions MetaSource = "github-actions" + SourceTekton MetaSource = "tekton" + SourceIssueTemplates MetaSource = "issue-templates" + SourceSpec MetaSource = "spec" + SourceHand MetaSource = "hand" + SourceBuiltIn MetaSource = "built-in" +) + +// Provenance tiers. Ratings and adoption never change a tier; only a +// human review does. +type Provenance string + +// Provenance values. +const ( + ProvenanceBuiltIn Provenance = "built-in" + ProvenanceCurated Provenance = "curated" + ProvenanceIngestedUnreviewed Provenance = "ingested-unreviewed" +) + +// Confidence marks an element a human has not confirmed yet. +type Confidence string + +// Confidence values. The empty value means confirmed (hand-written or +// edited by a person). +const ( + ConfidenceConfirmed Confidence = "" + ConfidenceInferred Confidence = "inferred" +) + +// Citation points at the source paragraph or file an inferred element +// came from. +type Citation struct { + Path string `json:"path"` + Line int `json:"line,omitempty"` + Text string `json:"text,omitempty"` +} + +// Column is one Activity Monitor column; several states may share it. +type Column struct { + ID string `json:"id"` + Label string `json:"label"` + Hint string `json:"hint,omitempty"` + States []string `json:"states"` + Terminal bool `json:"terminal,omitempty"` +} + +// ItemKind is the kind of forge item a state or rule applies to. +type ItemKind string + +// Item kinds. The empty kind means both. +const ( + KindAny ItemKind = "" + KindIssue ItemKind = "issue" + KindPR ItemKind = "pr" +) + +// StateLifecycle is the lifecycle data on a State: where it sits on the +// board, which stage label it maps to and what a row in it may say. +type StateLifecycle struct { + // Column is the Column.ID the state is displayed in. + Column string `json:"column,omitempty"` + // Number is the stage/NNN label number; zero for states that carry + // no label (terminal observation states). + Number int `json:"number,omitempty"` + // Kinds says which item kinds may be in this state. + Kinds []ItemKind `json:"kinds,omitempty"` + // Waiting are the waiting reasons the monitor may show in this state. + Waiting []string `json:"waiting,omitempty"` + // Replies are the human-gate verbs offered in this state + // (decide:approve, release, …). + Replies []string `json:"replies,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// DerivationMode says how an item's state is computed from facts. +type DerivationMode string + +// Derivation modes. Builtin delegates to the hive's Go derivers (the +// hive-default model); Rules evaluates the model's own ordered rules. +const ( + DerivationBuiltin DerivationMode = "builtin" + DerivationRules DerivationMode = "rules" +) + +// Derivation is how the engine maps facts to a state. +type Derivation struct { + Mode DerivationMode `json:"mode"` + Rules []Rule `json:"rules,omitempty"` +} + +// Rule puts an item in State when every predicate holds. Rules are +// evaluated in order, first match wins; an item no rule matches is "not +// covered" and the engine abstains. +type Rule struct { + ID string `json:"id,omitempty"` + Kind ItemKind `json:"kind,omitempty"` + State string `json:"state"` + When []Predicate `json:"when"` + // Reason is the text stored on the record and shown on the monitor. + Reason string `json:"reason,omitempty"` +} + +// Predicate is one test over a fact the engine already has. +type Predicate struct { + Fact string `json:"fact"` + Op Op `json:"op"` + Value string `json:"value,omitempty"` +} + +// Op is a predicate operator. +type Op string + +// Operators. Is/Not compare a scalar fact; Has/Lacks test membership in a +// set fact (labels, checks); True/False test a boolean fact. +const ( + OpIs Op = "is" + OpNot Op = "not" + OpHas Op = "has" + OpLacks Op = "lacks" + OpTrue Op = "true" + OpFalse Op = "false" +) + +// FactType is the shape of a fact in the vocabulary. +type FactType string + +// Fact types. +const ( + FactBool FactType = "bool" + FactScalar FactType = "scalar" + FactSet FactType = "set" +) + +// Facts is the vocabulary a Rule may test. The engine implements every +// entry (pkg/stageengine); the compiler refuses a fact outside it. +var Facts = map[string]FactType{ + "open": FactBool, + "merged": FactBool, + "draft": FactBool, + "labels": FactSet, + "origin": FactScalar, + "author.kind": FactScalar, + "author.login": FactScalar, + "hold": FactBool, + "park": FactBool, + "issue.bucket": FactScalar, + "issue.claimed": FactBool, + "issue.covered": FactBool, + "issue.stalled": FactBool, + "issue.open_children": FactBool, + "pr.checks": FactScalar, + "pr.review": FactScalar, + "pr.changes_requested": FactBool, + "pr.conflicting": FactBool, + "pr.dco": FactScalar, + "pr.head_fresh": FactBool, + "pr.base": FactScalar, +} + +// Event is something that moves work: a fact the engine observes, named +// so transitions and bookkeeping can refer to it. +type Event struct { + ID string `json:"id"` + Label string `json:"label,omitempty"` + // Fact is the predicate that fires the event. Two events may not bind + // the same predicate. + Fact Predicate `json:"fact"` + // Actor is the Role that may cause the event; empty for observations. + Actor string `json:"actor,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// Gate is a condition on a transition released by a role. +type Gate struct { + ID string `json:"id"` + Conditions []Predicate `json:"conditions,omitempty"` + // ReleasedBy is the Role that may release the gate. Required. + ReleasedBy string `json:"releasedBy"` + // Reply is the text posted when the gate is released. + Reply string `json:"reply,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// RoleKind is how a role's members are determined. +type RoleKind string + +// Role kinds. Permission is a repository permission (admin, maintain, +// write); FrozenSet is a set named at an earlier event (the reviewers at +// request time); AuthorKind is authorkind (human, clanker, hive); Bot is a +// named bot login. +const ( + RolePermission RoleKind = "permission" + RoleFrozenSet RoleKind = "frozen-set" + RoleAuthorKind RoleKind = "author-kind" + RoleBot RoleKind = "bot" +) + +// RoleDef is who may fire which events and release which gates. +type RoleDef struct { + ID string `json:"id"` + Label string `json:"label,omitempty"` + Kind RoleKind `json:"kind"` + Params map[string]string `json:"params,omitempty"` + // Human is true for roles a person fills; the compiler needs at least + // one human-released gate after any agent action. + Human bool `json:"human,omitempty"` +} + +// AgentGrant says which agent profile may act in which states. +type AgentGrant struct { + Profile string `json:"profile"` + States []string `json:"states"` + Backend string `json:"backend,omitempty"` + Tools []string `json:"tools,omitempty"` + Produces []string `json:"produces,omitempty"` +} + +// Check is a CI check a gate may require. +type Check struct { + ID string `json:"id"` + Name string `json:"name"` + Required bool `json:"required,omitempty"` + Source string `json:"source,omitempty"` +} + +// Effect is a deterministic bookkeeping action on an event. +type Effect struct { + On string `json:"on"` + Action string `json:"action"` + Params map[string]string `json:"params,omitempty"` +} + +// LabelSet is the label vocabulary reconciled against the repository. +type LabelSet struct { + Prefix string `json:"prefix,omitempty"` + Entries []LabelEntry `json:"entries,omitempty"` +} + +// LabelEntry is one label; State is the state it marks, if any. +type LabelEntry struct { + Name string `json:"name"` + Color string `json:"color,omitempty"` + Description string `json:"description,omitempty"` + State string `json:"state,omitempty"` +} diff --git a/src/pkg/workflowmodel/model.go b/src/pkg/workflowmodel/model.go index 55cd35aa57..7ec6c90386 100644 --- a/src/pkg/workflowmodel/model.go +++ b/src/pkg/workflowmodel/model.go @@ -93,13 +93,23 @@ type Metadata struct { // Spec is the model body: the process graph (states, transitions, guards, // lanes) and the execution graphs (pipelines) bound into it. type Spec struct { + Meta Meta `json:"meta,omitzero"` Scope Scope `json:"scope"` Sources []Source `json:"sources,omitempty"` Initial string `json:"initial"` + Columns []Column `json:"columns,omitempty"` States []State `json:"states"` Transitions []Transition `json:"transitions,omitempty"` Guards []Guard `json:"guards,omitempty"` Lanes []Lane `json:"lanes,omitempty"` + Derivation Derivation `json:"derivation,omitzero"` + Events []Event `json:"events,omitempty"` + Gates []Gate `json:"gates,omitempty"` + Roles []RoleDef `json:"roles,omitempty"` + Agents []AgentGrant `json:"agents,omitempty"` + Checks []Check `json:"checks,omitempty"` + Bookkeeping []Effect `json:"bookkeeping,omitempty"` + Labels LabelSet `json:"labels,omitzero"` Pipelines []Pipeline `json:"pipelines,omitempty"` Coverage Coverage `json:"coverage"` } @@ -131,6 +141,8 @@ type State struct { // Pipelines bound into this state (by Pipeline.ID). Pipelines []string `json:"pipelines,omitempty"` Origin Origin `json:"origin,omitempty"` + // Lifecycle is the board/label half of the state (lifecycle.go). + Lifecycle StateLifecycle `json:"lifecycle,omitzero"` } // Transition moves work between states on an event, if its guard holds. @@ -139,6 +151,10 @@ type Transition struct { To string `json:"to"` On string `json:"on"` GuardRef string `json:"guardRef,omitempty"` + // GateRef is the lifecycle Gate (lifecycle.go) the move needs. + GateRef string `json:"gateRef,omitempty"` + // Note is the human-readable reason for the edge. + Note string `json:"note,omitempty"` } // GuardKind is the family a guard belongs to. diff --git a/src/pkg/workflowmodel/testdata/models/techdocs.json b/src/pkg/workflowmodel/testdata/models/techdocs.json new file mode 100644 index 0000000000..bd1a529d30 --- /dev/null +++ b/src/pkg/workflowmodel/testdata/models/techdocs.json @@ -0,0 +1,79 @@ +{ + "apiVersion": "workflow.hivecommons.dev/v1alpha1", + "kind": "WorkflowModel", + "metadata": {"name": "cncf-techdocs"}, + "spec": { + "meta": {"version": "1", "author": "cncf/techdocs", "description": "Documentation engagement: request, analyse, review, iterate, publish", "source": "written"}, + "scope": {"forge": "github.com", "repository": "cncf/techdocs"}, + "initial": "requested", + "columns": [ + {"id": "requested", "label": "Requested", "states": ["requested"]}, + {"id": "analysis", "label": "Analysis", "states": ["analysing", "analysis-review"]}, + {"id": "writing", "label": "Writing", "states": ["draft-under-way", "drafting", "draft-review"]}, + {"id": "publishing", "label": "Publishing", "states": ["approved"]}, + {"id": "done", "label": "Published", "states": ["published", "withdrawn"], "terminal": true} + ], + "states": [ + {"id": "requested", "label": "Requested", "owner": "human", "lifecycle": {"number": 10, "kinds": ["issue"]}}, + {"id": "analysing", "label": "Analysing", "owner": "registered-agent", "lifecycle": {"number": 20, "kinds": ["issue"], "replies": ["hand back"]}}, + {"id": "analysis-review", "label": "Analysis review", "owner": "human", "lifecycle": {"number": 45, "kinds": ["issue"], "replies": ["approve analysis", "revise"]}}, + {"id": "draft-under-way", "label": "Draft under way", "owner": "registered-agent", "lifecycle": {"number": 40, "kinds": ["issue"]}}, + {"id": "drafting", "label": "Drafting", "owner": "registered-agent", "lifecycle": {"number": 70, "kinds": ["pr"]}}, + {"id": "draft-review", "label": "Draft review", "owner": "human", "lifecycle": {"number": 50, "kinds": ["pr"], "replies": ["approve", "request changes"]}}, + {"id": "approved", "label": "Approved", "owner": "human", "lifecycle": {"number": 90, "kinds": ["pr"]}}, + {"id": "published", "label": "Published", "owner": "external-observation", "type": "final"}, + {"id": "withdrawn", "label": "Withdrawn", "owner": "external-observation", "type": "final"} + ], + "roles": [ + {"id": "techdocs-maintainer", "label": "TechDocs maintainer", "kind": "permission", "params": {"min": "maintain"}, "human": true}, + {"id": "project-maintainer", "label": "Project maintainer", "kind": "frozen-set", "human": true} + ], + "gates": [ + {"id": "analysis-approved", "releasedBy": "techdocs-maintainer", "reply": "approve analysis"}, + {"id": "draft-approved", "releasedBy": "project-maintainer", "reply": "approve"} + ], + "events": [ + {"id": "accepted", "fact": {"fact": "labels", "op": "has", "value": "techdocs/accepted"}, "actor": "techdocs-maintainer"}, + {"id": "analysis-posted", "fact": {"fact": "labels", "op": "has", "value": "techdocs/analysis"}}, + {"id": "draft-opened", "fact": {"fact": "issue.covered", "op": "true"}}, + {"id": "pr-approved", "fact": {"fact": "pr.review", "op": "is", "value": "approved"}}, + {"id": "merged", "fact": {"fact": "merged", "op": "true"}}, + {"id": "closed", "fact": {"fact": "open", "op": "false"}} + ], + "agents": [ + {"profile": "techdocs-analyst", "states": ["analysing"], "produces": ["analysis"]}, + {"profile": "techdocs-writer", "states": ["drafting"], "produces": ["pr"]} + ], + "transitions": [ + {"from": "requested", "to": "analysing", "on": "accepted"}, + {"from": "analysing", "to": "analysis-review", "on": "analysis-posted"}, + {"from": "analysis-review", "to": "analysing", "on": "analysis-posted", "note": "revise"}, + {"from": "analysis-review", "to": "draft-under-way", "on": "draft-opened", "gateRef": "analysis-approved"}, + {"from": "draft-under-way", "to": "published", "on": "merged"}, + {"from": "draft-under-way", "to": "withdrawn", "on": "closed"}, + {"from": "analysis-review", "to": "drafting", "on": "draft-opened", "gateRef": "analysis-approved"}, + {"from": "drafting", "to": "draft-review", "on": "analysis-posted"}, + {"from": "draft-review", "to": "drafting", "on": "analysis-posted"}, + {"from": "draft-review", "to": "approved", "on": "pr-approved", "gateRef": "draft-approved"}, + {"from": "approved", "to": "published", "on": "merged"}, + {"from": "requested", "to": "withdrawn", "on": "closed"}, + {"from": "analysing", "to": "withdrawn", "on": "closed"}, + {"from": "drafting", "to": "withdrawn", "on": "closed"} + ], + "derivation": { + "mode": "rules", + "rules": [ + {"id": "closed", "state": "withdrawn", "when": [{"fact": "open", "op": "false"}, {"fact": "merged", "op": "false"}], "reason": "closed without publishing"}, + {"id": "published", "state": "published", "when": [{"fact": "merged", "op": "true"}]}, + {"id": "approved", "kind": "pr", "state": "approved", "when": [{"fact": "pr.review", "op": "is", "value": "approved"}, {"fact": "pr.checks", "op": "is", "value": "green"}]}, + {"id": "draft-review", "kind": "pr", "state": "draft-review", "when": [{"fact": "draft", "op": "false"}, {"fact": "labels", "op": "has", "value": "techdocs/*"}]}, + {"id": "drafting", "kind": "pr", "state": "drafting", "when": [{"fact": "labels", "op": "has", "value": "techdocs/*"}]}, + {"id": "analysis-review", "kind": "issue", "state": "analysis-review", "when": [{"fact": "labels", "op": "has", "value": "techdocs/analysis"}, {"fact": "issue.covered", "op": "false"}]}, + {"id": "drafting-issue", "kind": "issue", "state": "draft-under-way", "when": [{"fact": "issue.covered", "op": "true"}]}, + {"id": "analysing", "kind": "issue", "state": "analysing", "when": [{"fact": "labels", "op": "has", "value": "techdocs/accepted"}]}, + {"id": "requested", "kind": "issue", "state": "requested", "when": [{"fact": "labels", "op": "has", "value": "techdocs/request"}]} + ] + }, + "coverage": {"files": 0, "parsed": 0} + } +}