From 71f27700baac01c406d876ee4044c12d20fca601 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 11 Nov 2026 08:08:03 -0700 Subject: [PATCH 1/5] Workflow models: simulate endpoint with rule trace Add POST /api/workflows/{name}/{version}/simulate. It loads a stored model, compiles it, converts a JSON Facts mirror into stageengine.Facts and runs the same deriver the engine uses, returning the decision (state, column, stage, reason) and a per-rule trace from the new stageengine.Explain. repo+number without facts best-effort fills from the forge and reports which facts were filled vs unknown. Refs hivecommons/hive#17620 Signed-off-by: Andrew Anderson --- dashboard/openapi.json | 320 ++++++++++++ src/cmd/hive/main.go | 3 + src/pkg/dashboard/api_workflows.go | 1 + src/pkg/dashboard/api_workflows_simulate.go | 469 ++++++++++++++++++ .../dashboard/api_workflows_simulate_test.go | 225 +++++++++ src/pkg/dashboard/deps.go | 5 + src/pkg/github/workflow_item.go | 74 +++ src/pkg/stageengine/simulate.go | 73 +++ src/pkg/stageengine/workflow.go | 166 +++++++ src/pkg/stageengine/workflow_explain_test.go | 79 +++ 10 files changed, 1415 insertions(+) create mode 100644 src/pkg/dashboard/api_workflows_simulate.go create mode 100644 src/pkg/dashboard/api_workflows_simulate_test.go create mode 100644 src/pkg/github/workflow_item.go create mode 100644 src/pkg/stageengine/simulate.go create mode 100644 src/pkg/stageengine/workflow_explain_test.go diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 4c1db74093..abb90f57ab 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -35898,6 +35898,70 @@ } } }, + "/api/workflows/{name}/{version}/simulate": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Simulate an issue or PR against a workflow model", + "description": "Derives the state a stored model would put an item in, using the same stageengine Facts the engine uses, and returns a per-rule trace explaining why. Send `facts` directly, or `repo`+`number` to best-effort fill them from the forge (the response lists which facts were filled and which stay unknown). Read-only; RFC phase 3c of the workflow-models RFC.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowSimulateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Decision, trace and normalized facts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowSimulateResult" + } + } + } + }, + "400": { + "description": "Malformed body, unknown kind, or kind does not match the fetched item" + }, + "404": { + "description": "Not found" + }, + "422": { + "description": "Model does not compile, or no forge client is wired for repo+number fill" + }, + "502": { + "description": "Forge fetch failed" + }, + "503": { + "description": "No workflow store" + } + } + } + }, "/api/workflows/ingest": { "post": { "tags": [ @@ -36323,6 +36387,262 @@ } } }, + "WorkflowSimulateRequest": { + "type": "object", + "description": "Either `facts` (with `kind`) or `repo`+`number` must be given. When both are present `facts` wins and `repo`/`number` only seed the item reference.", + "properties": { + "kind": { + "type": "string", + "enum": [ + "issue", + "pr" + ] + }, + "repo": { + "type": "string", + "description": "owner/repo" + }, + "number": { + "type": "integer" + }, + "facts": { + "$ref": "#/components/schemas/WorkflowSimulateFacts" + } + } + }, + "WorkflowSimulateFacts": { + "type": "object", + "description": "JSON mirror of stageengine.Facts. Enumerations are the engine's name helpers: author.kind hive|clanker|human|unknown; pr.checks green|red|pending|none|unknown; pr.review approved|changes_requested|pending|unavailable|requires_human; pr.dco yes|no|unknown.", + "properties": { + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, + "open": { + "type": "boolean" + }, + "merged": { + "type": "boolean" + }, + "draft": { + "type": "boolean" + }, + "origin": { + "type": "string" + }, + "author": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "selfAuthored": { + "type": "boolean" + }, + "role": { + "type": "string" + } + } + }, + "park": { + "type": "object", + "properties": { + "holds": { + "type": "array", + "items": { + "type": "string" + } + }, + "needsHuman": { + "type": "boolean" + }, + "decisionLabel": { + "type": "string" + }, + "possiblyExists": { + "type": "boolean" + }, + "sentinel": { + "type": "boolean" + }, + "humanOnlyReason": { + "type": "string" + }, + "approvedDirection": { + "type": "boolean" + }, + "decisionQuestion": { + "type": "string" + }, + "decisionSuperseded": { + "type": "boolean" + } + } + }, + "issue": { + "type": "object", + "additionalProperties": true, + "properties": { + "bucket": { + "type": "string" + } + } + }, + "pr": { + "type": "object", + "additionalProperties": true, + "properties": { + "checks": { + "type": "string" + }, + "review": { + "type": "string" + }, + "dco": { + "type": "string" + }, + "conflicting": { + "type": "boolean" + }, + "changesRequested": { + "type": "boolean" + }, + "humanApprover": { + "type": "boolean" + }, + "lane": { + "type": "object", + "properties": { + "lane": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + } + } + } + } + }, + "WorkflowSimulateResult": { + "type": "object", + "properties": { + "decision": { + "type": "object", + "properties": { + "state": { + "type": "string" + }, + "column": { + "type": "string" + }, + "stage": { + "type": "integer" + }, + "label": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "abstain": { + "type": "boolean" + }, + "covered": { + "type": "boolean" + }, + "terminal": { + "type": "boolean" + } + } + }, + "trace": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "state": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "evaluated": { + "type": "boolean" + }, + "matched": { + "type": "boolean" + }, + "skipped": { + "type": "string" + }, + "builtin": { + "type": "boolean" + }, + "reason": { + "type": "string" + }, + "predicates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "fact": { + "type": "string" + }, + "op": { + "type": "string" + }, + "value": { + "type": "string" + }, + "holds": { + "type": "boolean" + }, + "known": { + "type": "boolean" + }, + "actual": { + "type": "string" + } + } + } + } + } + } + }, + "facts": { + "$ref": "#/components/schemas/WorkflowSimulateFacts" + }, + "filled": { + "type": "array", + "items": { + "type": "string" + } + }, + "unknown": { + "type": "array", + "items": { + "type": "string" + } + }, + "notes": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, "WorkflowBinding": { "type": "object", "properties": { diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 33a3ce9ea3..f9cc3d6e82 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1091,6 +1091,9 @@ func (b *boot) wireBootClosures() { Config: b.cfg, WorkflowStore: wfstore.Open(wfstore.Root(b.cfg.Data.WorkflowsDir)), WorkflowRepoFiles: workflowRepoFiles(func() *github.Client { return b.ghClient }), + WorkflowItemSnapshot: func(ctx context.Context, repo string, number int) (github.WorkflowItemSnapshot, error) { + return b.ghClient.WorkflowItemSnapshot(ctx, repo, number) + }, AgentMgr: b.agentMgr, CruxRuntimeHealth: cruxRuntimeHealthFunc(b.cruxSupervision), // Provider gateways (#5565 slice 3): concrete openrouter/watsonx/ diff --git a/src/pkg/dashboard/api_workflows.go b/src/pkg/dashboard/api_workflows.go index c503cc7c42..9d45dc69c4 100644 --- a/src/pkg/dashboard/api_workflows.go +++ b/src/pkg/dashboard/api_workflows.go @@ -27,6 +27,7 @@ func (s *Server) registerWorkflowRoutes() { s.mux.HandleFunc("PUT /api/workflows/{name}/{version}", s.handleWorkflowSave) s.mux.HandleFunc("DELETE /api/workflows/{name}/{version}", s.handleWorkflowDelete) s.registerWorkflowVersionRoutes() + s.mux.HandleFunc("POST /api/workflows/{name}/{version}/simulate", s.handleWorkflowSimulate) } func (s *Server) workflowStore(w http.ResponseWriter) *wfstore.Store { diff --git a/src/pkg/dashboard/api_workflows_simulate.go b/src/pkg/dashboard/api_workflows_simulate.go new file mode 100644 index 0000000000..b68b3e754c --- /dev/null +++ b/src/pkg/dashboard/api_workflows_simulate.go @@ -0,0 +1,469 @@ +package dashboard + +import ( + "context" + "fmt" + "net/http" + "sort" + "strings" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +// Workflow-model simulate (hivecommons/hive#17620, RFC phase 3c): "paste or +// pick a real issue/PR and see which state the model puts it in and why, +// using the same Facts the engine would use". Read-only, open to any +// dashboard user like GET on the model. + +// workflowSimulateTimeout bounds the forge reads behind a repo+number fill. +const workflowSimulateTimeout = 30 * time.Second + +// workflowSimulateRequest is the body of POST .../simulate. Facts is the +// JSON mirror of stageengine.Facts; when it is absent and Repo+Number are +// set the handler fills what one forge read can tell and marks the rest +// unknown. When both are present Facts wins and the forge is not read. +type workflowSimulateRequest struct { + Kind string `json:"kind"` + Facts *SimulateFacts `json:"facts,omitempty"` + Repo string `json:"repo,omitempty"` + Number int `json:"number,omitempty"` +} + +// SimulateFacts is the wire form of stageengine.Facts. Every field is +// optional; the zero value is a closed, unlabeled item by an unknown +// author with no kind-specific evidence. Scalar enumerations use the +// rules-vocabulary spellings (author.kind, pr.checks, pr.review, pr.dco in +// pkg/workflowmodel.Facts) so what the operator types is what a rule tests. +type SimulateFacts struct { + Labels []string `json:"labels"` + Open bool `json:"open"` + Merged bool `json:"merged"` + Draft bool `json:"draft"` + Author SimulateAuthor `json:"author"` + Park SimulatePark `json:"park"` + Origin string `json:"origin,omitempty"` + Issue *SimulateIssueFacts `json:"issue,omitempty"` + PR *SimulatePRFacts `json:"pr,omitempty"` +} + +// SimulateAuthor mirrors stageengine.AuthorFacts. +type SimulateAuthor struct { + Login string `json:"login,omitempty"` + Kind string `json:"kind,omitempty"` // hive | clanker | human | unknown + SelfAuthored bool `json:"selfAuthored,omitempty"` + Role string `json:"role,omitempty"` // trusted | contributor | newcomer | untrusted | "" +} + +// SimulatePark mirrors stageengine.ParkFacts. +type SimulatePark struct { + Holds []string `json:"holds,omitempty"` + NeedsHuman bool `json:"needsHuman,omitempty"` + DecisionLabel string `json:"decisionLabel,omitempty"` + PossiblyExists bool `json:"possiblyExists,omitempty"` + Sentinel bool `json:"sentinel,omitempty"` + HumanOnlyReason string `json:"humanOnlyReason,omitempty"` + ApprovedDirection bool `json:"approvedDirection,omitempty"` + DecisionQuestion string `json:"decisionQuestion,omitempty"` + DecisionSuperseded bool `json:"decisionSuperseded,omitempty"` +} + +// SimulateIssueFacts mirrors the issue-side stageengine.IssueFacts the +// derivers and the rules vocabulary read. +type SimulateIssueFacts struct { + Bucket string `json:"bucket,omitempty"` // actionable | claimed | in_progress | claimed_by_pr | filtered | reporter_triage + FilteredReason string `json:"filteredReason,omitempty"` + Claimed bool `json:"claimed,omitempty"` + ClaimHolder string `json:"claimHolder,omitempty"` + ClaimPRStarted bool `json:"claimPRStarted,omitempty"` + LikelyDone bool `json:"likelyDone,omitempty"` + Stalled bool `json:"stalled,omitempty"` + CoveringPR int `json:"coveringPR,omitempty"` + CoveringPRStage int `json:"coveringPRStage,omitempty"` + OpenChildren int `json:"openChildren,omitempty"` + HoldLabel string `json:"holdLabel,omitempty"` + BlockedReason string `json:"blockedReason,omitempty"` + NeedsHumanLabel string `json:"needsHumanLabel,omitempty"` + Blocker string `json:"blocker,omitempty"` + ApprovedDirectionLabel string `json:"approvedDirectionLabel,omitempty"` + UmbrellaLabel string `json:"umbrellaLabel,omitempty"` + DiscussionLabel string `json:"discussionLabel,omitempty"` + TriageAwaiting string `json:"triageAwaiting,omitempty"` + TriageAwaitingLabel string `json:"triageAwaitingLabel,omitempty"` +} + +// SimulatePRFacts mirrors the PR-side stageengine.PRFacts the derivers and +// the rules vocabulary read. Lane is optional; without one the built-in +// deriver is fed stageengine.SimulatedLane and the response says so. +type SimulatePRFacts struct { + HeadSHA string `json:"headSHA,omitempty"` + HeadFresh bool `json:"headFresh,omitempty"` + BaseRef string `json:"baseRef,omitempty"` + Conflicting bool `json:"conflicting,omitempty"` + ChangesRequested bool `json:"changesRequested,omitempty"` + Checks string `json:"checks,omitempty"` // green | red | pending | missing | unknown + Review string `json:"review,omitempty"` // pending | approved | changes_requested | requires_human | unavailable + DCO string `json:"dco,omitempty"` // yes | no | unknown + DCOGate bool `json:"dcoGate,omitempty"` + HumanApprover string `json:"humanApprover,omitempty"` + Lane *SimulateLane `json:"lane,omitempty"` +} + +// SimulateLane is one automerge lane opinion (stageengine.LaneFact). +type SimulateLane struct { + Lane string `json:"lane"` + Reason string `json:"reason,omitempty"` +} + +// SimulateDecision is the wire form of the stageengine.Decision. +type SimulateDecision struct { + State string `json:"state"` + Column string `json:"column"` + Stage int `json:"stage"` + Label string `json:"label"` + Reason string `json:"reason"` + Abstain bool `json:"abstain"` + Covered bool `json:"covered"` + Terminal bool `json:"terminal"` +} + +// SimulateResponse is the body of a 200 from .../simulate. +type SimulateResponse struct { + Decision SimulateDecision `json:"decision"` + Trace []stageengine.RuleTrace `json:"trace"` + Facts SimulateFacts `json:"facts"` + Filled []string `json:"filled"` + Unknown []string `json:"unknown"` + Notes []string `json:"notes,omitempty"` +} + +func (s *Server) handleWorkflowSimulate(w http.ResponseWriter, r *http.Request) { + st := s.workflowStore(w) + if st == nil { + return + } + var req workflowSimulateRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + req.Kind = strings.ToLower(strings.TrimSpace(req.Kind)) + req.Repo = strings.TrimSpace(req.Repo) + m, _, err := st.Get(r.PathValue("name"), r.PathValue("version")) + if err != nil { + workflowStoreError(w, err) + return + } + profile, diags, cerr := workflowmodel.Compile(m) + if cerr != nil { + jsonError(w, fmt.Sprintf("%s@%s does not compile: %d diagnostics", m.Metadata.Name, m.Spec.Meta.Version, len(diags)), http.StatusUnprocessableEntity) + return + } + + var filled, unknown, notes []string + facts := req.Facts + if facts == nil { + if req.Repo == "" || req.Number <= 0 { + jsonError(w, "set facts, or repo (owner/repo) and number to fetch them", http.StatusBadRequest) + return + } + if !strings.Contains(req.Repo, "/") { + jsonError(w, "repo must be owner/repo", http.StatusBadRequest) + return + } + if s.deps == nil || s.deps.WorkflowItemSnapshot == nil { + jsonError(w, "fetching an item needs a forge client; set facts by hand instead", http.StatusUnprocessableEntity) + return + } + ctx, cancel := context.WithTimeout(r.Context(), workflowSimulateTimeout) + defer cancel() + snap, err := s.deps.WorkflowItemSnapshot(ctx, req.Repo, req.Number) + if err != nil { + jsonError(w, fmt.Sprintf("fetch %s#%d: %v", req.Repo, req.Number, err), http.StatusBadGateway) + return + } + if req.Kind == "" { + req.Kind = snap.Kind + } else if req.Kind != snap.Kind { + jsonError(w, fmt.Sprintf("%s#%d is a %s, not a %s", req.Repo, req.Number, snap.Kind, req.Kind), http.StatusBadRequest) + return + } + facts, filled, unknown = simulateFactsFromSnapshot(snap) + } else if req.Kind == "" { + jsonError(w, "kind must be issue or pr", http.StatusBadRequest) + return + } + + owner, repo := "sim", "sim" + if i := strings.IndexByte(req.Repo, '/'); i > 0 { + owner, repo = req.Repo[:i], req.Repo[i+1:] + } + ref, err := stageengine.SimulateRef(req.Kind, owner, repo, req.Number) + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + norm := normalizeSimulateFacts(req.Kind, *facts) + ef := norm.toEngine(ref) + if ref.Kind == stagelabels.PRItem && len(ef.PR.Lanes) == 0 { + lane := stageengine.SimulatedLane(ef) + ef.PR.Lanes = []stageengine.LaneFact{lane} + norm.PR.Lane = &SimulateLane{Lane: lane.Lane, Reason: lane.Reason} + notes = append(notes, fmt.Sprintf("no lane observation supplied; simulated lane %s with reason %q from the head facts", lane.Lane, lane.Reason)) + } + dec, trace := stageengine.Explain(profile, ref.Kind, ef) + if trace == nil { + trace = []stageengine.RuleTrace{} + } + if filled == nil { + filled = []string{} + } + if unknown == nil { + unknown = []string{} + } + jsonResponse(w, SimulateResponse{ + Decision: simulateDecision(profile, dec), + Trace: trace, + Facts: norm, + Filled: filled, + Unknown: unknown, + Notes: notes, + }) +} + +// simulateDecision maps the engine's Decision onto the profile: the state +// that carries the stage number and its column. +func simulateDecision(p *workflowmodel.Profile, d stageengine.Decision) SimulateDecision { + out := SimulateDecision{Reason: d.Reason, Abstain: d.Abstain, Terminal: d.Terminal} + if d.Abstain { + out.Covered = !strings.HasPrefix(d.Reason, stageengine.ReasonNotCovered) + return out + } + out.Covered = true + if d.Stage != stagelabels.None { + out.Stage = d.Stage.Number() + out.Label = d.Stage.Label() + if st, ok := p.StateForNumber(out.Stage); ok { + out.State = st + out.Column = p.ColumnOf[st] + } + } + return out +} + +// simulateFactsFromSnapshot fills a SimulateFacts from one forge read and +// names what it could and could not fill. +func simulateFactsFromSnapshot(snap ghpkg.WorkflowItemSnapshot) (*SimulateFacts, []string, []string) { + f := &SimulateFacts{Labels: snap.Labels, Open: snap.Open, Merged: snap.Merged, Draft: snap.Draft} + if f.Labels == nil { + f.Labels = []string{} + } + f.Author.Login = snap.Author + f.Author.Kind = "unknown" + f.Author.Role = stagelabels.RoleOf(snap.Labels).String() + f.Park.Holds = stagelabels.Holds(snap.Labels) + f.Park.NeedsHuman = hasLabelFold(snap.Labels, stageengine.NeedsHumanLabel) + f.Origin = originLabel(snap.Labels) + filled := []string{"labels", "open", "author.login", "author.role", "park.holds", "park.needsHuman", "origin"} + unknown := []string{"author.kind"} + if snap.Kind == "pr" { + f.PR = &SimulatePRFacts{HeadSHA: snap.HeadSHA, BaseRef: snap.BaseRef, Review: "pending", DCO: "unknown", Checks: "unknown"} + filled = append(filled, "merged", "draft", "pr.headSHA", "pr.baseRef") + if snap.ConflictKnown { + f.PR.Conflicting = snap.Conflicting + filled = append(filled, "pr.conflicting") + } else { + unknown = append(unknown, "pr.conflicting") + } + if snap.ChecksKnown { + f.PR.Checks = stageengine.ChecksName(stagelabels.CheckSummary{Known: true, Total: snap.Checks.Total, Green: snap.Checks.Green, Pending: snap.Checks.Pending, Red: snap.Checks.Red}) + switch snap.Checks.DCO { + case 1: + f.PR.DCO = "yes" + case -1: + f.PR.DCO = "no" + } + filled = append(filled, "pr.checks", "pr.dco") + } else { + unknown = append(unknown, "pr.checks", "pr.dco") + } + unknown = append(unknown, "pr.review", "pr.changesRequested", "pr.lane") + } else { + f.Issue = &SimulateIssueFacts{Bucket: "actionable"} + if !snap.Open { + f.Issue.Bucket = "" + } + unknown = append(unknown, "issue.bucket", "issue.claimed", "issue.coveringPR", "issue.stalled") + } + sort.Strings(unknown) + return f, filled, unknown +} + +func hasLabelFold(labels []string, want string) bool { + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), want) { + return true + } + } + return false +} + +func originLabel(labels []string) string { + for _, l := range labels { + if strings.HasPrefix(strings.ToLower(l), "origin/") { + return l + } + } + return "" +} + +// normalizeSimulateFacts fills the kind-specific pointer the deriver +// needs, lower-cases the enumerations and drops the other kind's evidence. +func normalizeSimulateFacts(kind string, f SimulateFacts) SimulateFacts { + if f.Labels == nil { + f.Labels = []string{} + } + f.Author.Kind = stageengine.AuthorKindName(stageengine.ParseAuthorKind(f.Author.Kind)) + f.Author.Role = strings.ToLower(strings.TrimSpace(f.Author.Role)) + if f.Park.Holds == nil { + f.Park.Holds = stagelabels.Holds(f.Labels) + } + if kind == "pr" { + f.Issue = nil + if f.PR == nil { + f.PR = &SimulatePRFacts{} + } + f.PR.Checks = stageengine.ChecksName(stageengine.ParseChecks(f.PR.Checks)) + f.PR.Review = simulateReviewName(f.PR.Review) + f.PR.DCO = stageengine.DCOName(stageengine.ParseDCO(f.PR.DCO)) + } else { + f.PR = nil + if f.Issue == nil { + f.Issue = &SimulateIssueFacts{} + } + f.Issue.Bucket = strings.ToLower(strings.TrimSpace(f.Issue.Bucket)) + } + return f +} + +// simulateReviewName keeps requires_human distinct (stageengine.ReviewName +// folds it into pending for the rules vocabulary, but the built-in deriver +// parks on it). +func simulateReviewName(s string) string { + st := stageengine.ParseReview(s) + if st == stagelabels.VerdictRequiresHuman { + return "requires_human" + } + return stageengine.ReviewName(st) +} + +func simulateRole(s string) stagelabels.Role { + for _, r := range []stagelabels.Role{stagelabels.RoleTrusted, stagelabels.RoleContributor, stagelabels.RoleNewcomer, stagelabels.RoleUntrusted} { + if r.String() == s { + return r + } + } + return stagelabels.RoleNone +} + +// toEngine converts the wire facts into the Facts the deriver reads. +func (f SimulateFacts) toEngine(ref stageengine.Ref) stageengine.Facts { + out := stageengine.Facts{ + Ref: ref, + ObservedAt: time.Now().UTC(), + Labels: append([]string(nil), f.Labels...), + Open: f.Open, + Merged: f.Merged, + Draft: f.Draft, + Origin: f.Origin, + Author: stageengine.AuthorFacts{ + Login: f.Author.Login, + Kind: stageengine.ParseAuthorKind(f.Author.Kind), + SelfAuthored: f.Author.SelfAuthored, + Role: simulateRole(f.Author.Role), + }, + Park: stageengine.ParkFacts{ + Holds: append([]string(nil), f.Park.Holds...), + NeedsHuman: f.Park.NeedsHuman, + DecisionLabel: f.Park.DecisionLabel, + PossiblyExists: f.Park.PossiblyExists, + Sentinel: f.Park.Sentinel, + HumanOnlyReason: f.Park.HumanOnlyReason, + ApprovedDirection: f.Park.ApprovedDirection, + DecisionQuestion: f.Park.DecisionQuestion, + DecisionSuperseded: f.Park.DecisionSuperseded, + }, + } + if f.Issue != nil { + is := &stageengine.IssueFacts{ + Bucket: stageengine.IssueBucket(f.Issue.Bucket), + FilteredReason: f.Issue.FilteredReason, + LikelyDone: f.Issue.LikelyDone, + Stalled: f.Issue.Stalled, + OpenChildren: f.Issue.OpenChildren, + HoldLabel: f.Issue.HoldLabel, + BlockedReason: f.Issue.BlockedReason, + NeedsHumanLabel: f.Issue.NeedsHumanLabel, + Blocker: f.Issue.Blocker, + ApprovedDirectionLabel: f.Issue.ApprovedDirectionLabel, + UmbrellaLabel: f.Issue.UmbrellaLabel, + DiscussionLabel: f.Issue.DiscussionLabel, + TriageAwaiting: f.Issue.TriageAwaiting, + TriageAwaitingLabel: f.Issue.TriageAwaitingLabel, + } + if f.Issue.Claimed || f.Issue.ClaimHolder != "" { + is.Claim = &stageengine.ClaimFact{Holder: f.Issue.ClaimHolder, PRStarted: f.Issue.ClaimPRStarted} + } + if f.Issue.CoveringPR > 0 { + is.CoveringPR = &stageengine.Ref{Owner: ref.Owner, Repo: ref.Repo, Number: f.Issue.CoveringPR, Kind: stagelabels.PRItem} + if st, ok := stageByNumberForSimulate(f.Issue.CoveringPRStage); ok { + is.CoveringPRStage = st + } + } + out.Issue = is + } + if f.PR != nil { + review := stageengine.ParseReview(f.PR.Review) + pr := &stageengine.PRFacts{ + HeadSHA: f.PR.HeadSHA, + HeadFresh: f.PR.HeadFresh, + BaseRef: f.PR.BaseRef, + Conflicting: f.PR.Conflicting, + ChangesRequested: f.PR.ChangesRequested || review == stagelabels.VerdictChangesRequested, + Checks: stageengine.ParseChecks(f.PR.Checks), + DCO: stageengine.ParseDCO(f.PR.DCO), + DCOGate: f.PR.DCOGate, + Review: stageengine.ReviewFacts{State: review, HumanApprover: f.PR.HumanApprover}, + } + // The built-in deriver reads the raw verdict string behind the + // folded state (VerdictBlocks / VerdictNeedsHuman), so spell it. + switch review { + case stagelabels.VerdictApproved: + pr.Review.VerdictKnown, pr.Review.Verdict = true, "approve" + case stagelabels.VerdictChangesRequested: + pr.Review.VerdictKnown, pr.Review.Verdict = true, "changes_requested" + case stagelabels.VerdictRequiresHuman: + pr.Review.VerdictKnown, pr.Review.Verdict = true, "requires_human" + } + if f.PR.Lane != nil && f.PR.Lane.Lane != "" { + pr.Lanes = []stageengine.LaneFact{{Lane: f.PR.Lane.Lane, Reason: f.PR.Lane.Reason, Role: out.Author.Role, Merged: f.Merged}} + } + out.PR = pr + } + return out +} + +func stageByNumberForSimulate(n int) (stagelabels.Stage, bool) { + if n <= 0 { + return stagelabels.None, false + } + for _, def := range stagelabels.Table { + if def.Number == n { + return def.Stage, true + } + } + return stagelabels.None, false +} diff --git a/src/pkg/dashboard/api_workflows_simulate_test.go b/src/pkg/dashboard/api_workflows_simulate_test.go new file mode 100644 index 0000000000..4d59fc0799 --- /dev/null +++ b/src/pkg/dashboard/api_workflows_simulate_test.go @@ -0,0 +1,225 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine" +) + +func simulateCall(t *testing.T, s *Server, path string, body any) (int, SimulateResponse, string) { + t.Helper() + rec := wfReq(s, http.MethodPost, path, body, false) + var out SimulateResponse + if rec.Code == http.StatusOK { + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v\n%s", err, rec.Body) + } + } + return rec.Code, out, rec.Body.String() +} + +// hive-default (derivation builtin): a green, approved PR by a trusted +// author derives the built-in 080 and the trace is the single builtin +// entry naming the state and column the profile puts it in. +func TestWorkflowSimulateHiveDefaultPR(t *testing.T) { + s := workflowTestServer(t, true) + code, out, raw := simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{ + "kind": "pr", "repo": "myorg/repo1", "number": 7, + "facts": map[string]any{ + "labels": []string{"role/trusted"}, "open": true, + "author": map[string]any{"login": "andy", "kind": "human", "role": "trusted"}, + "pr": map[string]any{"checks": "green", "review": "approved", "dco": "yes"}, + }, + }) + if code != http.StatusOK { + t.Fatalf("%d %s", code, raw) + } + d := out.Decision + if d.Abstain || !d.Covered || d.Stage != 80 || d.State != "awaiting-merge-admission" || d.Column == "" || !strings.HasPrefix(d.Label, "stage/080") { + t.Fatalf("decision %+v", d) + } + if len(out.Trace) != 1 || !out.Trace[0].Builtin || !out.Trace[0].Matched || out.Trace[0].State != d.State { + t.Fatalf("trace %+v", out.Trace) + } + if out.Facts.PR == nil || out.Facts.PR.Lane == nil || out.Facts.PR.Lane.Lane != "trusted-author" || len(out.Notes) != 1 { + t.Fatalf("simulated lane not reported: %+v notes=%v", out.Facts.PR, out.Notes) + } + if out.Facts.Issue != nil || out.Facts.PR.Review != "approved" || out.Facts.Author.Kind != "human" { + t.Fatalf("facts not normalized: %+v", out.Facts) + } + + // Red CI on the hive's own PR is the fixing stage. + code, out, raw = simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{ + "kind": "pr", + "facts": map[string]any{"open": true, "author": map[string]any{"kind": "hive", "selfAuthored": true, "role": "trusted"}, "pr": map[string]any{"checks": "red"}}, + }) + if code != http.StatusOK || out.Decision.Stage != 70 { + t.Fatalf("%d %+v %s", code, out.Decision, raw) + } + + // An issue needs no PR evidence. + code, out, raw = simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{ + "kind": "issue", "facts": map[string]any{"open": true, "author": map[string]any{"kind": "human"}, "issue": map[string]any{"bucket": "actionable"}}, + }) + if code != http.StatusOK || out.Decision.Stage != 10 || out.Decision.State != "actionable" { + t.Fatalf("%d %+v %s", code, out.Decision, raw) + } +} + +// A rules model: the trace lists every rule in order, marks the first +// match, shows each predicate's verdict and actual value, and leaves the +// rules after the match unevaluated. +func TestWorkflowSimulateRulesTrace(t *testing.T) { + s := workflowTestServer(t, true) + if rec := wfReq(s, http.MethodPost, "/api/workflows", techdocsModel(t), true); rec.Code != http.StatusCreated { + t.Fatalf("save: %d %s", rec.Code, rec.Body) + } + code, out, raw := simulateCall(t, s, "/api/workflows/cncf-techdocs/1/simulate", map[string]any{ + "kind": "issue", + "facts": map[string]any{ + "labels": []string{"techdocs/request", "techdocs/accepted"}, "open": true, + "author": map[string]any{"login": "nate", "kind": "human"}, + }, + }) + if code != http.StatusOK { + t.Fatalf("%d %s", code, raw) + } + if out.Decision.Abstain || out.Decision.Stage != 20 || out.Decision.Column == "" { + t.Fatalf("decision %+v", out.Decision) + } + var matched, afterMatch int + seenMatch := false + for _, tr := range out.Trace { + if tr.Builtin { + t.Fatalf("rules trace has a builtin entry: %+v", tr) + } + if tr.Matched { + matched++ + seenMatch = true + if tr.State != out.Decision.State { + t.Fatalf("matched rule %s names %s, decision %s", tr.ID, tr.State, out.Decision.State) + } + for _, p := range tr.Predicates { + if !p.Holds || !p.Known || p.Fact == "" || p.Op == "" { + t.Fatalf("matched rule has a failing/unknown predicate: %+v", p) + } + } + continue + } + if seenMatch { + afterMatch++ + if tr.Evaluated || len(tr.Predicates) != 0 { + t.Fatalf("rule after the match was evaluated: %+v", tr) + } + } else if tr.Evaluated { + failing := 0 + for _, p := range tr.Predicates { + if !p.Holds { + failing++ + } + } + if failing == 0 { + t.Fatalf("evaluated, unmatched rule has no failing predicate: %+v", tr) + } + } + } + if matched != 1 || afterMatch == 0 { + t.Fatalf("matched=%d afterMatch=%d trace=%+v", matched, afterMatch, out.Trace) + } + + // Uncovered facts abstain with the not-covered reason. + code, out, raw = simulateCall(t, s, "/api/workflows/cncf-techdocs/1/simulate", map[string]any{ + "kind": "issue", "facts": map[string]any{"labels": []string{"bug"}, "open": true}, + }) + if code != http.StatusOK || !out.Decision.Abstain || out.Decision.Covered || !strings.HasPrefix(out.Decision.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("%d %+v %s", code, out.Decision, raw) + } + for _, tr := range out.Trace { + if tr.Matched { + t.Fatalf("uncovered run has a matched rule: %+v", tr) + } + } +} + +func TestWorkflowSimulateErrors(t *testing.T) { + s := workflowTestServer(t, true) + for _, c := range []struct { + name string + path string + body any + code int + }{ + {"bad kind", "/api/workflows/hive-default/1/simulate", map[string]any{"kind": "epic", "facts": map[string]any{}}, http.StatusBadRequest}, + {"no kind", "/api/workflows/hive-default/1/simulate", map[string]any{"facts": map[string]any{}}, http.StatusBadRequest}, + {"bad json", "/api/workflows/hive-default/1/simulate", "{", http.StatusBadRequest}, + {"unknown model", "/api/workflows/nope/1/simulate", map[string]any{"kind": "pr", "facts": map[string]any{}}, http.StatusNotFound}, + {"neither facts nor item", "/api/workflows/hive-default/1/simulate", map[string]any{"kind": "pr"}, http.StatusBadRequest}, + {"item without forge client", "/api/workflows/hive-default/1/simulate", map[string]any{"kind": "pr", "repo": "myorg/repo1", "number": 3}, http.StatusUnprocessableEntity}, + } { + if code, _, raw := simulateCall(t, s, c.path, c.body); code != c.code { + t.Errorf("%s: %d want %d: %s", c.name, code, c.code, raw) + } + } + if rec := wfReq(workflowTestServer(t, false), http.MethodPost, "/api/workflows/hive-default/1/simulate", map[string]any{"kind": "pr", "facts": map[string]any{}}, false); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("no store: %d", rec.Code) + } +} + +// repo+number without facts fills from the forge snapshot and reports +// what was filled and what stays unknown; the kind comes from the item. +func TestWorkflowSimulateFetchesItem(t *testing.T) { + s := workflowTestServer(t, true) + var asked string + s.deps.WorkflowItemSnapshot = func(_ context.Context, repo string, number int) (ghpkg.WorkflowItemSnapshot, error) { + asked = repo + "#" + string(rune('0'+number)) + if number == 9 { + return ghpkg.WorkflowItemSnapshot{}, errors.New("boom") + } + return ghpkg.WorkflowItemSnapshot{ + Kind: "pr", Labels: []string{"role/untrusted", "hold", "origin/scanner"}, Open: true, Author: "nate", + HeadSHA: "abc", BaseRef: "main", ConflictKnown: true, + Checks: ghpkg.CommitChecksSummary{Total: 2, Green: 2, DCO: 1}, ChecksKnown: true, + }, nil + } + code, out, raw := simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{"repo": "myorg/repo1", "number": 4}) + if code != http.StatusOK { + t.Fatalf("%d %s", code, raw) + } + if asked != "myorg/repo1#4" { + t.Fatalf("asked %q", asked) + } + f := out.Facts + if f.PR == nil || f.Issue != nil || f.PR.Checks != "green" || f.PR.DCO != "yes" || f.PR.Review != "pending" || f.Author.Role != "untrusted" || f.Author.Login != "nate" || f.Origin != "origin/scanner" { + t.Fatalf("facts %+v pr=%+v", f, f.PR) + } + if len(f.Park.Holds) != 1 || f.Park.Holds[0] != "hold" { + t.Fatalf("holds %v", f.Park.Holds) + } + has := func(list []string, want string) bool { + for _, s := range list { + if s == want { + return true + } + } + return false + } + if !has(out.Filled, "pr.checks") || !has(out.Filled, "labels") || !has(out.Unknown, "pr.review") || !has(out.Unknown, "author.kind") || has(out.Unknown, "pr.conflicting") { + t.Fatalf("filled=%v unknown=%v", out.Filled, out.Unknown) + } + if out.Decision.Abstain { + t.Fatalf("decision %+v", out.Decision) + } + + if code, _, raw := simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{"kind": "issue", "repo": "myorg/repo1", "number": 4}); code != http.StatusBadRequest || !strings.Contains(raw, "is a pr") { + t.Fatalf("kind mismatch: %d %s", code, raw) + } + if code, _, _ := simulateCall(t, s, "/api/workflows/hive-default/1/simulate", map[string]any{"repo": "myorg/repo1", "number": 9}); code != http.StatusBadGateway { + t.Fatalf("forge error: %d", code) + } +} diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index 1a52a3fd65..b142e3df11 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -44,6 +44,11 @@ type Dependencies struct { // files (repo-relative slash path -> contents) and the ref read, for // POST /api/workflows/ingest. Nil disables ingest from a repository. WorkflowRepoFiles func(ctx context.Context, repo string) (files map[string][]byte, ref string, err error) + // WorkflowItemSnapshot reads one issue or PR head-level for + // POST /api/workflows/{name}/{version}/simulate (RFC #17620 phase 3c) + // so the operator can simulate a real item. Nil disables the fetch; the + // handler then answers 422 and the form still accepts hand-set facts. + WorkflowItemSnapshot func(ctx context.Context, repo string, number int) (ghpkg.WorkflowItemSnapshot, error) // AgentMgr is the agent runtime (hivecommons/hive#13536). The dashboard // programs against the crux.Runtime surface, not *agent.Manager; tests that // need manager-only seams unwrap it with agentManager. diff --git a/src/pkg/github/workflow_item.go b/src/pkg/github/workflow_item.go new file mode 100644 index 0000000000..d00fb15c77 --- /dev/null +++ b/src/pkg/github/workflow_item.go @@ -0,0 +1,74 @@ +package github + +import ( + "context" + "fmt" + "strings" +) + +// WorkflowItemSnapshot is the head-level view of one issue or pull request +// the workflow simulate API (RFC hivecommons/hive#17620 phase 3c) fills +// its Facts from: what one issues GET and, for a PR, one pulls GET plus +// the head's check summary say. Nothing the hive derives (lanes, claims, +// buckets) is here; the simulate response marks those unknown. +type WorkflowItemSnapshot struct { + Kind string // "issue" | "pr" + Labels []string + Open bool + Merged bool + Draft bool + Author string + // PR-only; zero on an issue. + HeadSHA string + BaseRef string + // Conflicting is set when GitHub reports the head as not mergeable + // (mergeable_state dirty). ConflictKnown is false while GitHub is still + // computing mergeability. + Conflicting, ConflictKnown bool + // Checks is the head's gating-check digest; ChecksKnown is false when + // the head could not be read. + Checks CommitChecksSummary + ChecksKnown bool +} + +// WorkflowItemSnapshot reads repo#number read-only for the simulate API. +func (c *Client) WorkflowItemSnapshot(ctx context.Context, repo string, number int) (WorkflowItemSnapshot, error) { + if c == nil || c.client == nil { + return WorkflowItemSnapshot{}, ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + issue, _, err := c.client.Issues.Get(WithRESTCaller(ctx, "hive:workflow_simulate"), owner, repoName, number) + if err != nil { + return WorkflowItemSnapshot{}, fmt.Errorf("reading %s#%d: %w", repo, number, err) + } + snap := WorkflowItemSnapshot{Kind: "issue", Open: strings.EqualFold(issue.GetState(), "open"), Author: safeGetLogin(issue.GetUser())} + for _, l := range issue.Labels { + if name := l.GetName(); name != "" { + snap.Labels = append(snap.Labels, name) + } + } + if !issue.IsPullRequest() { + return snap, nil + } + snap.Kind = "pr" + pr, _, err := c.client.PullRequests.Get(WithRESTCaller(ctx, "hive:workflow_simulate"), owner, repoName, number) + if err != nil { + return WorkflowItemSnapshot{}, fmt.Errorf("reading PR %s#%d: %w", repo, number, err) + } + c.storePRDetail(owner+"/"+repoName, number, pr) + snap.Open = strings.EqualFold(pr.GetState(), "open") + snap.Merged = pr.GetMerged() || !pr.GetMergedAt().IsZero() + snap.Draft = pr.GetDraft() + snap.HeadSHA = pr.GetHead().GetSHA() + snap.BaseRef = prBaseRef(pr) + if ms := pr.GetMergeableState(); ms != "" && ms != "unknown" { + snap.ConflictKnown = true + snap.Conflicting = ms == "dirty" + } + if snap.Open && snap.HeadSHA != "" { + if sum, err := SummarizeCommitChecks(ctx, c.client, owner, repoName, snap.HeadSHA); err == nil { + snap.Checks, snap.ChecksKnown = sum, true + } + } + return snap, nil +} diff --git a/src/pkg/stageengine/simulate.go b/src/pkg/stageengine/simulate.go new file mode 100644 index 0000000000..c6e9a0559f --- /dev/null +++ b/src/pkg/stageengine/simulate.go @@ -0,0 +1,73 @@ +package stageengine + +import ( + "fmt" + + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// SimulatedLane is the one lane observation a simulated PR carries when +// the caller supplied none (RFC #17620 phase 3c). The built-in PR deriver +// classifies from the automerge lanes' reason strings, which a hand-built +// Facts has no source for; this derives the reason a lane would most +// plausibly have recorded from the head-level facts, so hive-default can +// be simulated without a live sweep. The result is a best effort, never a +// substitute for the lanes: the simulate API marks it in the response. +func SimulatedLane(f Facts) LaneFact { + lane := prstage.StageLaneContributor + switch { + case f.Author.SelfAuthored: + lane = prstage.StageLaneSelf + case f.Author.Role == stagelabels.RoleTrusted: + lane = prstage.StageLaneTrusted + } + l := LaneFact{Lane: lane, Role: f.Author.Role} + pr := f.PR + if pr == nil { + pr = &PRFacts{} + } + switch { + case f.Merged: + l.Merged = true + case !f.Open: + l.Reason = "closed" + case f.Draft: + l.Reason = "draft" + case pr.Conflicting: + l.Reason = "conflicting" + case pr.ChangesRequested: + l.Reason = "changes-requested" + case len(f.Park.Holds) > 0: + l.Reason = "held" + case f.Park.NeedsHuman: + l.Reason = "label:needs-human" + case pr.Checks.Known && len(pr.Checks.Red) > 0: + l.Reason = "check-failing:" + pr.Checks.Red[0] + case !pr.Checks.Known || pr.Checks.Pending > 0: + l.Reason = "check-pending" + case pr.Review.State == stagelabels.VerdictPending || pr.Review.State == stagelabels.VerdictUnavailable: + l.Reason = prstage.ContributorLaneReasonNoVerdict + case f.Author.Role == stagelabels.RoleUntrusted || f.Author.Role == stagelabels.RoleNewcomer: + // Green and reviewed, but the lane cannot vouch for the author: a + // person's merge click is all that is missing (090 candidate). + l.Reason = "untrusted-author-role" + } + return l +} + +// SimulateRef builds the Ref a simulation derives under: kind is "issue" +// or "pr"; repo is owner/repo (any shape is accepted, the deriver only +// reads the kind); number may be zero. +func SimulateRef(kind, owner, repo string, number int) (Ref, error) { + var k stagelabels.Item + switch kind { + case "issue": + k = stagelabels.IssueItem + case "pr": + k = stagelabels.PRItem + default: + return Ref{}, fmt.Errorf("kind must be issue or pr, got %q", kind) + } + return Ref{Owner: owner, Repo: repo, Number: number, Kind: k}, nil +} diff --git a/src/pkg/stageengine/workflow.go b/src/pkg/stageengine/workflow.go index 5807d69ebd..6c60ae830e 100644 --- a/src/pkg/stageengine/workflow.go +++ b/src/pkg/stageengine/workflow.go @@ -2,6 +2,7 @@ package stageengine import ( "fmt" + "strconv" "strings" "sync" @@ -335,3 +336,168 @@ func dcoName(d stagelabels.DCOState) string { } return "unknown" } + +// RuleTrace is one rule's evaluation in an Explain run, in rule order. +// Rules after the first match are listed with Evaluated false so the +// operator sees the whole model, not just the part that fired. A builtin +// derivation yields a single trace with Builtin set. +type RuleTrace struct { + ID string `json:"id"` + State string `json:"state"` + Kind string `json:"kind,omitempty"` + Evaluated bool `json:"evaluated"` + Matched bool `json:"matched"` + Skipped string `json:"skipped,omitempty"` + Builtin bool `json:"builtin,omitempty"` + Reason string `json:"reason,omitempty"` + Predicates []PredicateTrace `json:"predicates,omitempty"` +} + +// PredicateTrace is one predicate's verdict: Holds is the evaluator's +// answer, Known is false when the fact is outside the vocabulary (the +// compiler refuses such a model, so this is defence in depth), and Actual +// is the fact's value as the evaluator saw it (scalar and bool facts). +type PredicateTrace struct { + Fact string `json:"fact"` + Op string `json:"op"` + Value string `json:"value,omitempty"` + Holds bool `json:"holds"` + Known bool `json:"known"` + Actual string `json:"actual,omitempty"` +} + +// Explain derives f under p exactly as DeriveFromModel does and also +// returns the rule-by-rule trace of how it got there (RFC #17620 phase 3c +// "simulate"). The Decision is identical to DeriveFromModel(p, kind).Derive(f). +func Explain(p *workflowmodel.Profile, kind stagelabels.Item, f Facts) (Decision, []RuleTrace) { + d := DeriveFromModel(p, kind) + dec := d.Derive(f) + md, ok := d.(modelDeriver) + if !ok || f.Ref.Kind != kind { + return dec, nil + } + if md.p.Mode != workflowmodel.DerivationRules { + tr := RuleTrace{Builtin: true, Evaluated: true, Matched: !dec.Abstain, Reason: dec.Reason} + if !dec.Abstain && dec.Stage != stagelabels.None { + tr.State, _ = md.p.StateForNumber(dec.Stage.Number()) + } + return dec, []RuleTrace{tr} + } + want := workflowmodel.KindIssue + if kind == stagelabels.PRItem { + want = workflowmodel.KindPR + } + traces := make([]RuleTrace, 0, len(md.p.Rules)) + matched := false + for i, r := range md.p.Rules { + id := r.ID + if id == "" { + id = fmt.Sprintf("rules[%d]", i) + } + tr := RuleTrace{ID: id, State: r.State, Kind: string(r.Kind), Reason: r.Reason} + switch { + case matched: + case r.Kind != workflowmodel.KindAny && r.Kind != want: + tr.Skipped = fmt.Sprintf("rule is for %s items", r.Kind) + default: + tr.Evaluated = true + tr.Matched = true + for _, pr := range r.When { + pt := explainPredicate(f, pr) + if !pt.Holds { + tr.Matched = false + } + tr.Predicates = append(tr.Predicates, pt) + } + if tr.Matched { + matched = true + } + } + traces = append(traces, tr) + } + return dec, traces +} + +func explainPredicate(f Facts, p workflowmodel.Predicate) PredicateTrace { + pt := PredicateTrace{Fact: p.Fact, Op: string(p.Op), Value: p.Value, Holds: holds(f, p)} + switch workflowmodel.Facts[p.Fact] { + case workflowmodel.FactBool: + if v, ok := boolFact(f, p.Fact); ok { + pt.Known, pt.Actual = true, strconv.FormatBool(v) + } + case workflowmodel.FactScalar: + if v, ok := scalarFact(f, p.Fact); ok { + pt.Known, pt.Actual = true, v + } + case workflowmodel.FactSet: + if v, ok := setFact(f, p.Fact); ok { + pt.Known, pt.Actual = true, strings.Join(v, " ") + } + } + return pt +} + +// AuthorKindName, ChecksName, ReviewName and DCOName are the scalar fact +// spellings the rules vocabulary uses (author.kind, pr.checks, pr.review, +// pr.dco); the Parse* helpers invert them for callers that build Facts from +// text, such as the simulate API. +func AuthorKindName(k authorkind.Kind) string { return authorKindName(k) } +func ChecksName(c stagelabels.CheckSummary) string { return checksName(c) } +func ReviewName(s stagelabels.VerdictState) string { return reviewName(s) } +func DCOName(d stagelabels.DCOState) string { return dcoName(d) } + +// ParseAuthorKind inverts AuthorKindName; anything else is Unknown. +func ParseAuthorKind(s string) authorkind.Kind { + switch strings.ToLower(strings.TrimSpace(s)) { + case "human": + return authorkind.Human + case "hive": + return authorkind.Hive + case "clanker": + return authorkind.Clanker + } + return authorkind.Unknown +} + +// ParseChecks inverts ChecksName into a minimal CheckSummary: green is one +// passing check, red one failing check named "ci", pending one queued +// check, unknown (or "") an unread head. +func ParseChecks(s string) stagelabels.CheckSummary { + switch strings.ToLower(strings.TrimSpace(s)) { + case "green": + return stagelabels.CheckSummary{Known: true, Total: 1, Green: 1} + case "red": + return stagelabels.CheckSummary{Known: true, Total: 1, Red: []string{"ci"}} + case "pending": + return stagelabels.CheckSummary{Known: true, Total: 1, Pending: 1} + case "missing", "none": + return stagelabels.CheckSummary{Known: true} + } + return stagelabels.CheckSummary{} +} + +// ParseReview inverts ReviewName; anything else is pending. +func ParseReview(s string) stagelabels.VerdictState { + switch strings.ToLower(strings.TrimSpace(s)) { + case "approved": + return stagelabels.VerdictApproved + case "changes_requested": + return stagelabels.VerdictChangesRequested + case "unavailable": + return stagelabels.VerdictUnavailable + case "requires_human": + return stagelabels.VerdictRequiresHuman + } + return stagelabels.VerdictPending +} + +// ParseDCO inverts DCOName; anything else is unknown. +func ParseDCO(s string) stagelabels.DCOState { + switch strings.ToLower(strings.TrimSpace(s)) { + case "yes": + return stagelabels.DCOYes + case "no": + return stagelabels.DCONo + } + return stagelabels.DCOUnknown +} diff --git a/src/pkg/stageengine/workflow_explain_test.go b/src/pkg/stageengine/workflow_explain_test.go new file mode 100644 index 0000000000..3d5b059045 --- /dev/null +++ b/src/pkg/stageengine/workflow_explain_test.go @@ -0,0 +1,79 @@ +package stageengine_test + +import ( + "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" +) + +// Explain agrees with Derive and records the ordered rule walk: kind +// mismatches are skipped, the first match stops evaluation, predicates +// carry their verdicts, and the uncovered walk has no match at all. +func TestExplainRulesTrace(t *testing.T) { + p := techdocsProfile(t) + f := issueFacts("techdocs/request") + want := stageengine.DeriveFromModel(p, stagelabels.IssueItem).Derive(f) + got, trace := stageengine.Explain(p, stagelabels.IssueItem, f) + if got.Stage != want.Stage || got.Abstain != want.Abstain || got.Reason != want.Reason || got.Abstain { + t.Fatalf("explain %+v derive %+v", got, want) + } + if len(trace) != len(p.Rules) { + t.Fatalf("trace has %d entries for %d rules", len(trace), len(p.Rules)) + } + matched := -1 + for i, tr := range trace { + if tr.Builtin { + t.Fatalf("builtin entry in rules trace: %+v", tr) + } + if tr.Skipped != "" && tr.Evaluated { + t.Fatalf("skipped rule was evaluated: %+v", tr) + } + if tr.Matched { + if matched >= 0 { + t.Fatalf("second match at %d (first %d)", i, matched) + } + matched = i + if st, _ := p.StateForNumber(got.Stage.Number()); tr.State != p.Rules[i].State || st != tr.State { + t.Fatalf("matched rule %+v for decision %+v", tr, got) + } + for _, pr := range tr.Predicates { + if !pr.Holds || !pr.Known { + t.Fatalf("matched predicate does not hold: %+v", pr) + } + } + } else if matched >= 0 && tr.Evaluated { + t.Fatalf("rule %d evaluated after the match at %d", i, matched) + } + } + if matched < 0 { + t.Fatal("no matched rule") + } + + dec, trace := stageengine.Explain(p, stagelabels.IssueItem, issueFacts("bug")) + if !dec.Abstain || !strings.HasPrefix(dec.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("uncovered %+v", dec) + } + for _, tr := range trace { + if tr.Matched { + t.Fatalf("uncovered walk matched %+v", tr) + } + } +} + +func TestExplainBuiltinTrace(t *testing.T) { + p, _, err := workflowmodel.Compile(hivedefault.Generate()) + if err != nil { + t.Fatal(err) + } + f := issueFacts("stage/010-actionable") + f.Issue.Bucket = stageengine.BucketActionable + dec, trace := stageengine.Explain(p, stagelabels.IssueItem, f) + st, _ := p.StateForNumber(dec.Stage.Number()) + if dec.Abstain || len(trace) != 1 || !trace[0].Builtin || !trace[0].Matched || trace[0].State != st || st == "" { + t.Fatalf("decision %+v trace %+v", dec, trace) + } +} From dc9dc79ac640d1b8f6763ea05629343da09c7b0d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 11 Nov 2026 08:12:42 -0700 Subject: [PATCH 2/5] Workflow models: Simulate panel on the model detail view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Workflows → model detail grows a Simulate section: pick a real owner/repo#N to fetch its facts, or describe one with a form generated from WF_SIM_FIELDS, then Run to see the decision chip (state · column · stage · reason), the ordered rule trace with the matched rule highlighted and each predicate's verdict, and the resulting state marked in the diagram. Refs hivecommons/hive#17620 Signed-off-by: Andrew Anderson --- .../dashboard/static-src/css/workflows.css | 30 ++ .../static-src/js/config-workflows-library.js | 260 +++++++++++++++- src/pkg/dashboard/static/index.html | 290 +++++++++++++++++- .../dashboard/workflows_library_ui_test.go | 2 +- .../dashboard/workflows_simulate_ui_test.go | 150 +++++++++ 5 files changed, 725 insertions(+), 7 deletions(-) create mode 100644 src/pkg/dashboard/workflows_simulate_ui_test.go diff --git a/src/pkg/dashboard/static-src/css/workflows.css b/src/pkg/dashboard/static-src/css/workflows.css index 8dde110de8..020cf4b6db 100644 --- a/src/pkg/dashboard/static-src/css/workflows.css +++ b/src/pkg/dashboard/static-src/css/workflows.css @@ -46,3 +46,33 @@ .wf-ingest-result { margin-top: var(--sp-5); border-top: var(--line-width) solid var(--border); padding-top: var(--sp-4); } .wf-ingest-result h4 { margin: var(--sp-5) var(--sp-0) var(--sp-2); font-size: var(--fs-base); } .wf-ingest-summary { font-size: var(--fs-sm); display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } + + /* Simulate panel (RFC phase 3c) */ + .wf-sim > summary { cursor: pointer; list-style: none; } + .wf-sim > summary h4 { display: inline; margin: var(--sp-0); } + .wf-sim > summary::before { content: '▸'; display: inline-block; width: var(--sp-4); color: var(--muted); } + .wf-sim[open] > summary::before { content: '▾'; } + .wf-sim-pick { display: flex; align-items: flex-end; gap: var(--sp-3); flex-wrap: wrap; } + .wf-sim-pick .config-field { flex: 1 1 16rem; margin: var(--sp-0); } + .wf-sim-kinds { display: flex; gap: var(--sp-5); margin: var(--sp-3) var(--sp-0); font-size: var(--fs-sm); } + .wf-sim-kind { display: inline-flex; align-items: center; gap: var(--sp-2); cursor: pointer; } + .wf-sim-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: var(--sp-3) var(--sp-4); font-size: var(--fs-sm); } + .wf-sim-form .config-field { margin: var(--sp-0); } + .wf-sim-check { display: flex; align-items: center; gap: var(--sp-2); align-self: end; } + .wf-sim-result { margin-top: var(--sp-4); border-top: 1px solid var(--line-strong); padding-top: var(--sp-4); } + .wf-sim-decision { font-size: var(--fs-base); display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; } + .wf-sim-chip { display: inline-block; padding: var(--sp-1) var(--sp-3); border-radius: var(--r-pill); font-weight: 700; font-size: var(--fs-sm); } + .wf-sim-chip-state { background: var(--status-ok); color: var(--panel); } + .wf-sim-chip-abstain { background: var(--status-warn); color: var(--panel); } + .wf-sim-chip-none { background: var(--muted); color: var(--panel); } + .wf-sim-sep { color: var(--muted); } + .wf-sim-trace { margin: var(--sp-3) var(--sp-0) var(--sp-0); padding-left: var(--sp-6); font-size: var(--fs-sm); } + .wf-sim-rule { padding: var(--sp-1) var(--sp-2); border-radius: var(--r-sm); } + .wf-sim-rule.matched { background: var(--bg-soft); border-left: 3px solid var(--status-ok); } + .wf-sim-rule.unevaluated, .wf-sim-rule.skipped { color: var(--muted); } + .wf-sim-preds { list-style: none; margin: var(--sp-1) var(--sp-0) var(--sp-0); padding-left: var(--sp-4); font-size: var(--fs-xs); } + .wf-sim-ok { color: var(--status-ok); font-weight: 700; } + .wf-sim-fail { color: var(--status-error); font-weight: 700; } + .wf-sim-unknown { color: var(--status-warn); font-weight: 700; } + .wf-sim-fill { margin-top: var(--sp-3); color: var(--text); } + .wf-dg-state.simulated .wf-dg-chip { stroke: var(--status-ok); stroke-width: 3; } diff --git a/src/pkg/dashboard/static-src/js/config-workflows-library.js b/src/pkg/dashboard/static-src/js/config-workflows-library.js index 7f97f30781..cc8ba8476e 100644 --- a/src/pkg/dashboard/static-src/js/config-workflows-library.js +++ b/src/pkg/dashboard/static-src/js/config-workflows-library.js @@ -18,8 +18,40 @@ 'ingested-unreviewed': 'ingested · unreviewed', }; const WF_DIAGRAM = { colW: 172, colGap: 28, chipH: 30, chipGap: 10, headH: 30, pad: 14, textPad: 10, maxLabel: 22 }; + // Simulate (RFC phase 3c): the facts form is generated from this table + // so the HTML builder, the form reader and the node tests share one + // source of truth. `path` is the dotted key inside the simulate facts + // DTO; `kind` restricts a field to issues or PRs; enumerations mirror + // the stageengine name helpers the API parses. + const WF_SIM_KINDS = ['issue', 'pr']; + const WF_SIM_FIELDS = [ + { path: 'labels', label: 'Labels', type: 'list', hint: 'space or comma separated' }, + { path: 'open', label: 'Open', type: 'bool' }, + { path: 'merged', label: 'Merged', type: 'bool', kind: 'pr' }, + { path: 'draft', label: 'Draft', type: 'bool', kind: 'pr' }, + { path: 'author.login', label: 'Author', type: 'text' }, + { path: 'author.kind', label: 'Author kind', type: 'select', options: ['human', 'hive', 'clanker', 'unknown'] }, + { path: 'author.role', label: 'Author role', type: 'select', options: ['', 'trusted', 'contributor', 'newcomer', 'untrusted'] }, + { path: 'author.selfAuthored', label: 'Self-authored (hive\u2019s own PR)', type: 'bool', kind: 'pr' }, + { path: 'issue.bucket', label: 'Issue bucket', type: 'select', kind: 'issue', options: ['', 'actionable', 'claimed', 'in_progress', 'claimed_by_pr', 'filtered', 'reporter_triage'] }, + { path: 'pr.checks', label: 'Checks', type: 'select', kind: 'pr', options: ['unknown', 'green', 'red', 'pending'] }, + { path: 'pr.review', label: 'Review', type: 'select', kind: 'pr', options: ['pending', 'approved', 'changes_requested', 'requires_human', 'unavailable'] }, + { path: 'pr.dco', label: 'DCO', type: 'select', kind: 'pr', options: ['unknown', 'yes', 'no'] }, + { path: 'pr.conflicting', label: 'Merge conflict', type: 'bool', kind: 'pr' }, + { path: 'park.holds', label: 'Hold labels', type: 'list', hint: 'blank = derived from labels' }, + { path: 'park.needsHuman', label: 'Needs human', type: 'bool' }, + ]; + function wfSimDefaultFacts() { + return { labels: [], open: true, merged: false, draft: false, origin: '', + author: { login: '', kind: 'human', selfAuthored: false, role: '' }, + park: { holds: null, needsHuman: false }, + issue: { bucket: '' }, + pr: { checks: 'unknown', review: 'pending', dco: 'unknown', conflicting: false } }; + } + function wfSimDefaultState() { return { kind: 'pr', repo: '', facts: wfSimDefaultFacts(), result: null, error: '', busy: false, open: false }; } const _wfLib = { view: 'library', selected: null, detail: null, detailError: '', loadingKey: '', pending: null, - ingest: { repo: '', name: '', busy: false, result: null, error: '' } }; + ingest: { repo: '', name: '', busy: false, result: null, error: '' }, + sim: wfSimDefaultState() }; function wfProvenanceOf(entry) { if (!entry) return 'local'; @@ -180,8 +212,9 @@ ).join('') + ''; } - function renderWorkflowDetail(detail, bindings, owner) { + function renderWorkflowDetail(detail, bindings, owner, sim) { const e = detail.entry || {}, m = detail.model || {}, p = detail.profile || null; + if (sim === undefined) sim = _wfLib.sim; const key = e.name + '@' + e.version; const bound = wfBoundRepos(bindings, e.name, e.version); const meta = (m.spec && m.spec.meta) || {}; @@ -212,13 +245,233 @@ '
' + facts.map(([k, v]) => `
${k}
${v}
`).join('') + '
' + '

Columns and states

' + '

Left to right as the Activity Monitor draws them. Arrows are the model\'s transitions; hover one for its event. Dashed states were inferred by ingest and have not been confirmed by a human.

' + - '
' + workflowDiagramSvg(m, p) + '
' + + '
' + wfSimMarkDiagram(workflowDiagramSvg(m, p), sim && sim.result) + '
' + + renderWorkflowSimulate(sim, owner) + '

Diagnostics

' + renderWorkflowDiagnostics(e.diagnostics || (p && p.diagnostics)) + (citations.length ? '

Citations

    ' + citations.slice(0, 40).map(c => `
  • ${esc(c.path || '')}${c.line ? ':' + esc(String(c.line)) : ''}${c.note ? ` ${esc(c.note)}` : ''}
  • `).join('') + (citations.length > 40 ? `
  • … ${citations.length - 40} more
  • ` : '') + '
' : '') + '
Model JSON
' + esc(JSON.stringify(m, null, 2)) + '
' + ''; } + // --- Simulate ----------------------------------------------------------- + + function wfSimGet(obj, path) { + return path.split('.').reduce((o, k) => (o && o[k] !== undefined && o[k] !== null) ? o[k] : undefined, obj); + } + + function wfSimSetPath(obj, path, value) { + const keys = path.split('.'); + let cur = obj; + keys.slice(0, -1).forEach(k => { if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {}; cur = cur[k]; }); + cur[keys[keys.length - 1]] = value; + return obj; + } + + function wfSimSplitList(raw) { + return String(raw || '').split(/[\s,]+/).map(s => s.trim()).filter(Boolean); + } + + // wfSimFieldsFor returns the form fields that apply to a kind. + function wfSimFieldsFor(kind) { + return WF_SIM_FIELDS.filter(f => !f.kind || f.kind === kind); + } + + // wfSimFormFromFacts maps facts to the raw form value of one field: + // strings for text/select, booleans for bool, a joined string for lists. + function wfSimFormFromFacts(facts, field) { + const v = wfSimGet(facts || {}, field.path); + if (field.type === 'bool') return !!v; + if (field.type === 'list') return Array.isArray(v) ? v.join(' ') : String(v || ''); + return v === undefined ? (field.options ? field.options[0] : '') : String(v); + } + + // wfSimFactsFromForm folds raw form values back into a facts object. + // `read(field)` returns the raw value for a field (DOM value / checked + // in the page, a plain lookup in tests); fields it returns undefined + // for keep their current value. + function wfSimFactsFromForm(facts, kind, read) { + const out = JSON.parse(JSON.stringify(facts || wfSimDefaultFacts())); + wfSimFieldsFor(kind).forEach(f => { + const raw = read(f); + if (raw === undefined) return; + let v; + if (f.type === 'bool') v = !!raw; + else if (f.type === 'list') v = wfSimSplitList(raw); + else v = String(raw == null ? '' : raw).trim(); + if (f.path === 'park.holds' && v.length === 0) v = null; + wfSimSetPath(out, f.path, v); + }); + return out; + } + + function wfSimParseItem(raw) { + const m = /^\s*(?:https?:\/\/[^/]+\/)?([^/\s#]+)\/([^/\s#]+?)(?:\/(?:issues|pull)\/|#)(\d+)\s*$/.exec(String(raw || '')); + return m ? { repo: m[1] + '/' + m[2], number: parseInt(m[3], 10) } : null; + } + + function wfSimFieldHtml(field, facts, disabled) { + const id = 'wf-sim-' + field.path.replace(/\./g, '-'); + const val = wfSimFormFromFacts(facts, field); + const common = `id="${id}" data-sim-field="${esc(field.path)}" ${disabled}`; + let input; + if (field.type === 'bool') { + input = ``; + return ``; + } + if (field.type === 'select') { + input = `'; + } else { + input = ``; + } + return ``; + } + + function renderWorkflowSimulate(state, owner) { + const st = state || _wfLib.sim; + const kind = WF_SIM_KINDS.indexOf(st.kind) >= 0 ? st.kind : 'pr'; + const disabled = st.busy ? 'disabled' : ''; + const kinds = WF_SIM_KINDS.map(k => + ``).join(''); + const fields = wfSimFieldsFor(kind).map(f => wfSimFieldHtml(f, st.facts, disabled)).join(''); + return '
' + + '

Simulate

' + + '

Paste a real issue or PR, or describe one, and see which state this model puts it in and why — the same facts the engine would use. This is the confidence check before binding; nothing is written.

' + + '
' + + `` + + `` + + '
' + + '
' + kinds + '
' + + '
' + fields + '
' + + `
` + + (st.error ? `

${esc(st.error)}

` : '') + + (st.result ? renderWorkflowSimulateResult(st.result) : '') + + '
'; + } + + function wfSimVerdict(p) { + if (!p.known) return '?'; + return p.holds ? '✓' : '✗'; + } + + function renderWorkflowSimulateResult(result) { + const r = result || {}, d = r.decision || {}; + const stage = d.stage ? 'stage/' + String(d.stage).padStart(3, '0') : ''; + let chip; + if (d.abstain && !d.covered) chip = `Not covered ${esc(d.reason || '')}`; + else if (d.abstain) chip = `Abstain ${esc(d.reason || '')}`; + else if (!d.state) chip = `No stage ${esc(d.reason || '')}`; + else chip = `${esc(d.state)}` + + (d.column ? ` · ${esc(d.column)}` : '') + + (stage ? ` · ${esc(stage)}` : '') + + (d.reason ? ` · ${esc(d.reason)}` : ''); + const trace = Array.isArray(r.trace) ? r.trace : []; + const items = trace.map(t => { + const cls = t.matched ? 'matched' : (t.skipped ? 'skipped' : (t.evaluated ? 'missed' : 'unevaluated')); + const head = t.builtin + ? `${esc(t.state || '—')} built-in deriver${t.reason ? ' · ' + esc(t.reason) : ''}` + : `${esc(t.id || '')} → ${esc(t.state || '')}` + + (t.skipped ? ` skipped: ${esc(t.skipped)}` : '') + + (!t.evaluated && !t.skipped ? ' not evaluated' : ''); + const preds = (t.predicates || []).map(p => + `
  • ${esc(p.fact)} ${esc(p.op)} ${esc(p.value || '')} → ${wfSimVerdict(p)}` + + (p.actual ? ` (${esc(p.actual)})` : '') + '
  • ').join(''); + return `
  • ${head}${preds ? '
      ' + preds + '
    ' : ''}
  • `; + }).join(''); + const fill = []; + if (Array.isArray(r.filled) && r.filled.length) fill.push('fetched: ' + r.filled.map(esc).join(', ')); + if (Array.isArray(r.unknown) && r.unknown.length) fill.push('unknown, defaulted: ' + r.unknown.map(esc).join(', ')); + (r.notes || []).forEach(n => fill.push(esc(n))); + return '
    ' + + '
    ' + chip + '
    ' + + (items ? '
      ' + items + '
    ' : '') + + (fill.length ? '

    ' + fill.join('
    ') + '

    ' : '') + + '
    '; + } + + // wfSimMarkDiagram tags the simulated state's chip in the diagram SVG. + function wfSimMarkDiagram(svg, result) { + const id = result && result.decision && result.decision.state; + if (!id) return svg; + const marker = 'data-state="' + esc(id) + '"'; + return svg.split(marker).map((part, i, all) => { + if (i === all.length - 1) return part; + return part.replace(/class="([^"]*)"\s*$/, 'class="$1 simulated" '); + }).join(marker); + } + + function wfSimSet(field, value) { + const st = _wfLib.sim; + st.open = true; + if (field === 'kind') { st.kind = WF_SIM_KINDS.indexOf(value) >= 0 ? value : 'pr'; st.result = null; st.error = ''; wfLibRerender(); return; } + if (field === 'repo') { st.repo = String(value || ''); return; } + const def = WF_SIM_FIELDS.find(f => f.path === field); + if (!def) return; + st.facts = wfSimFactsFromForm(st.facts, st.kind, f => f.path === field ? value : undefined); + } + + function wfSimReadForm() { + const st = _wfLib.sim; + st.open = true; + const repoEl = document.getElementById('wf-sim-repo'); + if (repoEl) st.repo = repoEl.value.trim(); + st.facts = wfSimFactsFromForm(st.facts, st.kind, f => { + const el = document.querySelector('[data-sim-field="' + f.path + '"]'); + if (!el) return undefined; + return f.type === 'bool' ? el.checked : el.value; + }); + } + + async function wfSimCall(body) { + const st = _wfLib.sim, e = (_wfLib.detail && _wfLib.detail.entry) || {}; + if (!e.name) { st.error = 'Open a model first.'; wfLibRerender(); return null; } + st.busy = true; st.error = ''; wfLibRerender(); + try { + const res = await fetch('/api/workflows/' + encodeURIComponent(e.name) + '/' + encodeURIComponent(e.version) + '/simulate', + { method: 'POST', headers: _inceptionAuthHeaders(), body: JSON.stringify(body) }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + return await res.json(); + } catch (err) { + st.error = 'Simulate failed: ' + err.message; + st.result = null; + return null; + } finally { + st.busy = false; + } + } + + // wfSimFetch fills the facts form from a real item so the operator can + // tweak them before running; the fetched facts are also run as-is. + async function wfSimFetch() { + const st = _wfLib.sim; + wfSimReadForm(); + const item = wfSimParseItem(st.repo); + if (!item) { st.error = 'Enter an item as owner/repo#123.'; st.result = null; wfLibRerender(); return; } + const out = await wfSimCall({ repo: item.repo, number: item.number }); + if (out) { + if (out.facts) { + st.facts = Object.assign(wfSimDefaultFacts(), out.facts); + if (!st.facts.pr) st.facts.pr = wfSimDefaultFacts().pr; + if (!st.facts.issue) st.facts.issue = wfSimDefaultFacts().issue; + } + if (out.facts && out.facts.pr && !out.facts.issue) st.kind = 'pr'; + else if (out.facts && out.facts.issue) st.kind = 'issue'; + st.result = out; + } + wfLibRerender(); + } + + async function wfSimRun() { + const st = _wfLib.sim; + wfSimReadForm(); + const body = { kind: st.kind, facts: st.facts }; + const item = wfSimParseItem(st.repo); + if (item) { body.repo = item.repo; body.number = item.number; } + const out = await wfSimCall(body); + if (out) st.result = out; + wfLibRerender(); + } + function wfRepoChoices() { const d = (_configState && _configState.data) || {}; const org = String(d.org || '').trim(); @@ -306,6 +559,7 @@ async function wfLibOpen(name, version) { const key = name + '@' + version; _wfLib.view = 'detail'; _wfLib.detail = null; _wfLib.detailError = ''; _wfLib.loadingKey = key; _wfLib.selected = key; + _wfLib.sim.result = null; _wfLib.sim.error = ''; wfLibRerender(); try { const res = await fetch('/api/workflows/' + encodeURIComponent(name) + '/' + encodeURIComponent(version), { headers: _inceptionAuthHeaders() }); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index cb0f7c2a1a..d8848b8653 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -5093,6 +5093,36 @@ .wf-ingest-result { margin-top: var(--sp-5); border-top: var(--line-width) solid var(--border); padding-top: var(--sp-4); } .wf-ingest-result h4 { margin: var(--sp-5) var(--sp-0) var(--sp-2); font-size: var(--fs-base); } .wf-ingest-summary { font-size: var(--fs-sm); display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } + + /* Simulate panel (RFC phase 3c) */ + .wf-sim > summary { cursor: pointer; list-style: none; } + .wf-sim > summary h4 { display: inline; margin: var(--sp-0); } + .wf-sim > summary::before { content: '▸'; display: inline-block; width: var(--sp-4); color: var(--muted); } + .wf-sim[open] > summary::before { content: '▾'; } + .wf-sim-pick { display: flex; align-items: flex-end; gap: var(--sp-3); flex-wrap: wrap; } + .wf-sim-pick .config-field { flex: 1 1 16rem; margin: var(--sp-0); } + .wf-sim-kinds { display: flex; gap: var(--sp-5); margin: var(--sp-3) var(--sp-0); font-size: var(--fs-sm); } + .wf-sim-kind { display: inline-flex; align-items: center; gap: var(--sp-2); cursor: pointer; } + .wf-sim-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: var(--sp-3) var(--sp-4); font-size: var(--fs-sm); } + .wf-sim-form .config-field { margin: var(--sp-0); } + .wf-sim-check { display: flex; align-items: center; gap: var(--sp-2); align-self: end; } + .wf-sim-result { margin-top: var(--sp-4); border-top: 1px solid var(--line-strong); padding-top: var(--sp-4); } + .wf-sim-decision { font-size: var(--fs-base); display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; } + .wf-sim-chip { display: inline-block; padding: var(--sp-1) var(--sp-3); border-radius: var(--r-pill); font-weight: 700; font-size: var(--fs-sm); } + .wf-sim-chip-state { background: var(--status-ok); color: var(--panel); } + .wf-sim-chip-abstain { background: var(--status-warn); color: var(--panel); } + .wf-sim-chip-none { background: var(--muted); color: var(--panel); } + .wf-sim-sep { color: var(--muted); } + .wf-sim-trace { margin: var(--sp-3) var(--sp-0) var(--sp-0); padding-left: var(--sp-6); font-size: var(--fs-sm); } + .wf-sim-rule { padding: var(--sp-1) var(--sp-2); border-radius: var(--r-sm); } + .wf-sim-rule.matched { background: var(--bg-soft); border-left: 3px solid var(--status-ok); } + .wf-sim-rule.unevaluated, .wf-sim-rule.skipped { color: var(--muted); } + .wf-sim-preds { list-style: none; margin: var(--sp-1) var(--sp-0) var(--sp-0); padding-left: var(--sp-4); font-size: var(--fs-xs); } + .wf-sim-ok { color: var(--status-ok); font-weight: 700; } + .wf-sim-fail { color: var(--status-error); font-weight: 700; } + .wf-sim-unknown { color: var(--status-warn); font-weight: 700; } + .wf-sim-fill { margin-top: var(--sp-3); color: var(--text); } + .wf-dg-state.simulated .wf-dg-chip { stroke: var(--status-ok); stroke-width: 3; } /* Hive Chat Panel */ .hive-chat-fab { position: fixed; bottom: 24px; right: 24px; z-index: 9000; @@ -62583,8 +62613,40 @@

    Agent Watchdog

    'ingested-unreviewed': 'ingested · unreviewed', }; const WF_DIAGRAM = { colW: 172, colGap: 28, chipH: 30, chipGap: 10, headH: 30, pad: 14, textPad: 10, maxLabel: 22 }; + // Simulate (RFC phase 3c): the facts form is generated from this table + // so the HTML builder, the form reader and the node tests share one + // source of truth. `path` is the dotted key inside the simulate facts + // DTO; `kind` restricts a field to issues or PRs; enumerations mirror + // the stageengine name helpers the API parses. + const WF_SIM_KINDS = ['issue', 'pr']; + const WF_SIM_FIELDS = [ + { path: 'labels', label: 'Labels', type: 'list', hint: 'space or comma separated' }, + { path: 'open', label: 'Open', type: 'bool' }, + { path: 'merged', label: 'Merged', type: 'bool', kind: 'pr' }, + { path: 'draft', label: 'Draft', type: 'bool', kind: 'pr' }, + { path: 'author.login', label: 'Author', type: 'text' }, + { path: 'author.kind', label: 'Author kind', type: 'select', options: ['human', 'hive', 'clanker', 'unknown'] }, + { path: 'author.role', label: 'Author role', type: 'select', options: ['', 'trusted', 'contributor', 'newcomer', 'untrusted'] }, + { path: 'author.selfAuthored', label: 'Self-authored (hive\u2019s own PR)', type: 'bool', kind: 'pr' }, + { path: 'issue.bucket', label: 'Issue bucket', type: 'select', kind: 'issue', options: ['', 'actionable', 'claimed', 'in_progress', 'claimed_by_pr', 'filtered', 'reporter_triage'] }, + { path: 'pr.checks', label: 'Checks', type: 'select', kind: 'pr', options: ['unknown', 'green', 'red', 'pending'] }, + { path: 'pr.review', label: 'Review', type: 'select', kind: 'pr', options: ['pending', 'approved', 'changes_requested', 'requires_human', 'unavailable'] }, + { path: 'pr.dco', label: 'DCO', type: 'select', kind: 'pr', options: ['unknown', 'yes', 'no'] }, + { path: 'pr.conflicting', label: 'Merge conflict', type: 'bool', kind: 'pr' }, + { path: 'park.holds', label: 'Hold labels', type: 'list', hint: 'blank = derived from labels' }, + { path: 'park.needsHuman', label: 'Needs human', type: 'bool' }, + ]; + function wfSimDefaultFacts() { + return { labels: [], open: true, merged: false, draft: false, origin: '', + author: { login: '', kind: 'human', selfAuthored: false, role: '' }, + park: { holds: null, needsHuman: false }, + issue: { bucket: '' }, + pr: { checks: 'unknown', review: 'pending', dco: 'unknown', conflicting: false } }; + } + function wfSimDefaultState() { return { kind: 'pr', repo: '', facts: wfSimDefaultFacts(), result: null, error: '', busy: false, open: false }; } const _wfLib = { view: 'library', selected: null, detail: null, detailError: '', loadingKey: '', pending: null, - ingest: { repo: '', name: '', busy: false, result: null, error: '' } }; + ingest: { repo: '', name: '', busy: false, result: null, error: '' }, + sim: wfSimDefaultState() }; function wfProvenanceOf(entry) { if (!entry) return 'local'; @@ -62745,8 +62807,9 @@

    Agent Watchdog

    ).join('') + ''; } - function renderWorkflowDetail(detail, bindings, owner) { + function renderWorkflowDetail(detail, bindings, owner, sim) { const e = detail.entry || {}, m = detail.model || {}, p = detail.profile || null; + if (sim === undefined) sim = _wfLib.sim; const key = e.name + '@' + e.version; const bound = wfBoundRepos(bindings, e.name, e.version); const meta = (m.spec && m.spec.meta) || {}; @@ -62777,13 +62840,233 @@

    Agent Watchdog

    '
    ' + facts.map(([k, v]) => `
    ${k}
    ${v}
    `).join('') + '
    ' + '

    Columns and states

    ' + '

    Left to right as the Activity Monitor draws them. Arrows are the model\'s transitions; hover one for its event. Dashed states were inferred by ingest and have not been confirmed by a human.

    ' + - '
    ' + workflowDiagramSvg(m, p) + '
    ' + + '
    ' + wfSimMarkDiagram(workflowDiagramSvg(m, p), sim && sim.result) + '
    ' + + renderWorkflowSimulate(sim, owner) + '

    Diagnostics

    ' + renderWorkflowDiagnostics(e.diagnostics || (p && p.diagnostics)) + (citations.length ? '

    Citations

      ' + citations.slice(0, 40).map(c => `
    • ${esc(c.path || '')}${c.line ? ':' + esc(String(c.line)) : ''}${c.note ? ` ${esc(c.note)}` : ''}
    • `).join('') + (citations.length > 40 ? `
    • … ${citations.length - 40} more
    • ` : '') + '
    ' : '') + '
    Model JSON
    ' + esc(JSON.stringify(m, null, 2)) + '
    ' + ''; } + // --- Simulate ----------------------------------------------------------- + + function wfSimGet(obj, path) { + return path.split('.').reduce((o, k) => (o && o[k] !== undefined && o[k] !== null) ? o[k] : undefined, obj); + } + + function wfSimSetPath(obj, path, value) { + const keys = path.split('.'); + let cur = obj; + keys.slice(0, -1).forEach(k => { if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {}; cur = cur[k]; }); + cur[keys[keys.length - 1]] = value; + return obj; + } + + function wfSimSplitList(raw) { + return String(raw || '').split(/[\s,]+/).map(s => s.trim()).filter(Boolean); + } + + // wfSimFieldsFor returns the form fields that apply to a kind. + function wfSimFieldsFor(kind) { + return WF_SIM_FIELDS.filter(f => !f.kind || f.kind === kind); + } + + // wfSimFormFromFacts maps facts to the raw form value of one field: + // strings for text/select, booleans for bool, a joined string for lists. + function wfSimFormFromFacts(facts, field) { + const v = wfSimGet(facts || {}, field.path); + if (field.type === 'bool') return !!v; + if (field.type === 'list') return Array.isArray(v) ? v.join(' ') : String(v || ''); + return v === undefined ? (field.options ? field.options[0] : '') : String(v); + } + + // wfSimFactsFromForm folds raw form values back into a facts object. + // `read(field)` returns the raw value for a field (DOM value / checked + // in the page, a plain lookup in tests); fields it returns undefined + // for keep their current value. + function wfSimFactsFromForm(facts, kind, read) { + const out = JSON.parse(JSON.stringify(facts || wfSimDefaultFacts())); + wfSimFieldsFor(kind).forEach(f => { + const raw = read(f); + if (raw === undefined) return; + let v; + if (f.type === 'bool') v = !!raw; + else if (f.type === 'list') v = wfSimSplitList(raw); + else v = String(raw == null ? '' : raw).trim(); + if (f.path === 'park.holds' && v.length === 0) v = null; + wfSimSetPath(out, f.path, v); + }); + return out; + } + + function wfSimParseItem(raw) { + const m = /^\s*(?:https?:\/\/[^/]+\/)?([^/\s#]+)\/([^/\s#]+?)(?:\/(?:issues|pull)\/|#)(\d+)\s*$/.exec(String(raw || '')); + return m ? { repo: m[1] + '/' + m[2], number: parseInt(m[3], 10) } : null; + } + + function wfSimFieldHtml(field, facts, disabled) { + const id = 'wf-sim-' + field.path.replace(/\./g, '-'); + const val = wfSimFormFromFacts(facts, field); + const common = `id="${id}" data-sim-field="${esc(field.path)}" ${disabled}`; + let input; + if (field.type === 'bool') { + input = ``; + return ``; + } + if (field.type === 'select') { + input = `'; + } else { + input = ``; + } + return ``; + } + + function renderWorkflowSimulate(state, owner) { + const st = state || _wfLib.sim; + const kind = WF_SIM_KINDS.indexOf(st.kind) >= 0 ? st.kind : 'pr'; + const disabled = st.busy ? 'disabled' : ''; + const kinds = WF_SIM_KINDS.map(k => + ``).join(''); + const fields = wfSimFieldsFor(kind).map(f => wfSimFieldHtml(f, st.facts, disabled)).join(''); + return '
    ' + + '

    Simulate

    ' + + '

    Paste a real issue or PR, or describe one, and see which state this model puts it in and why — the same facts the engine would use. This is the confidence check before binding; nothing is written.

    ' + + '
    ' + + `` + + `` + + '
    ' + + '
    ' + kinds + '
    ' + + '
    ' + fields + '
    ' + + `
    ` + + (st.error ? `

    ${esc(st.error)}

    ` : '') + + (st.result ? renderWorkflowSimulateResult(st.result) : '') + + '
    '; + } + + function wfSimVerdict(p) { + if (!p.known) return '?'; + return p.holds ? '✓' : '✗'; + } + + function renderWorkflowSimulateResult(result) { + const r = result || {}, d = r.decision || {}; + const stage = d.stage ? 'stage/' + String(d.stage).padStart(3, '0') : ''; + let chip; + if (d.abstain && !d.covered) chip = `Not covered ${esc(d.reason || '')}`; + else if (d.abstain) chip = `Abstain ${esc(d.reason || '')}`; + else if (!d.state) chip = `No stage ${esc(d.reason || '')}`; + else chip = `${esc(d.state)}` + + (d.column ? ` · ${esc(d.column)}` : '') + + (stage ? ` · ${esc(stage)}` : '') + + (d.reason ? ` · ${esc(d.reason)}` : ''); + const trace = Array.isArray(r.trace) ? r.trace : []; + const items = trace.map(t => { + const cls = t.matched ? 'matched' : (t.skipped ? 'skipped' : (t.evaluated ? 'missed' : 'unevaluated')); + const head = t.builtin + ? `${esc(t.state || '—')} built-in deriver${t.reason ? ' · ' + esc(t.reason) : ''}` + : `${esc(t.id || '')} → ${esc(t.state || '')}` + + (t.skipped ? ` skipped: ${esc(t.skipped)}` : '') + + (!t.evaluated && !t.skipped ? ' not evaluated' : ''); + const preds = (t.predicates || []).map(p => + `
  • ${esc(p.fact)} ${esc(p.op)} ${esc(p.value || '')} → ${wfSimVerdict(p)}` + + (p.actual ? ` (${esc(p.actual)})` : '') + '
  • ').join(''); + return `
  • ${head}${preds ? '
      ' + preds + '
    ' : ''}
  • `; + }).join(''); + const fill = []; + if (Array.isArray(r.filled) && r.filled.length) fill.push('fetched: ' + r.filled.map(esc).join(', ')); + if (Array.isArray(r.unknown) && r.unknown.length) fill.push('unknown, defaulted: ' + r.unknown.map(esc).join(', ')); + (r.notes || []).forEach(n => fill.push(esc(n))); + return '
    ' + + '
    ' + chip + '
    ' + + (items ? '
      ' + items + '
    ' : '') + + (fill.length ? '

    ' + fill.join('
    ') + '

    ' : '') + + '
    '; + } + + // wfSimMarkDiagram tags the simulated state's chip in the diagram SVG. + function wfSimMarkDiagram(svg, result) { + const id = result && result.decision && result.decision.state; + if (!id) return svg; + const marker = 'data-state="' + esc(id) + '"'; + return svg.split(marker).map((part, i, all) => { + if (i === all.length - 1) return part; + return part.replace(/class="([^"]*)"\s*$/, 'class="$1 simulated" '); + }).join(marker); + } + + function wfSimSet(field, value) { + const st = _wfLib.sim; + st.open = true; + if (field === 'kind') { st.kind = WF_SIM_KINDS.indexOf(value) >= 0 ? value : 'pr'; st.result = null; st.error = ''; wfLibRerender(); return; } + if (field === 'repo') { st.repo = String(value || ''); return; } + const def = WF_SIM_FIELDS.find(f => f.path === field); + if (!def) return; + st.facts = wfSimFactsFromForm(st.facts, st.kind, f => f.path === field ? value : undefined); + } + + function wfSimReadForm() { + const st = _wfLib.sim; + st.open = true; + const repoEl = document.getElementById('wf-sim-repo'); + if (repoEl) st.repo = repoEl.value.trim(); + st.facts = wfSimFactsFromForm(st.facts, st.kind, f => { + const el = document.querySelector('[data-sim-field="' + f.path + '"]'); + if (!el) return undefined; + return f.type === 'bool' ? el.checked : el.value; + }); + } + + async function wfSimCall(body) { + const st = _wfLib.sim, e = (_wfLib.detail && _wfLib.detail.entry) || {}; + if (!e.name) { st.error = 'Open a model first.'; wfLibRerender(); return null; } + st.busy = true; st.error = ''; wfLibRerender(); + try { + const res = await fetch('/api/workflows/' + encodeURIComponent(e.name) + '/' + encodeURIComponent(e.version) + '/simulate', + { method: 'POST', headers: _inceptionAuthHeaders(), body: JSON.stringify(body) }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + return await res.json(); + } catch (err) { + st.error = 'Simulate failed: ' + err.message; + st.result = null; + return null; + } finally { + st.busy = false; + } + } + + // wfSimFetch fills the facts form from a real item so the operator can + // tweak them before running; the fetched facts are also run as-is. + async function wfSimFetch() { + const st = _wfLib.sim; + wfSimReadForm(); + const item = wfSimParseItem(st.repo); + if (!item) { st.error = 'Enter an item as owner/repo#123.'; st.result = null; wfLibRerender(); return; } + const out = await wfSimCall({ repo: item.repo, number: item.number }); + if (out) { + if (out.facts) { + st.facts = Object.assign(wfSimDefaultFacts(), out.facts); + if (!st.facts.pr) st.facts.pr = wfSimDefaultFacts().pr; + if (!st.facts.issue) st.facts.issue = wfSimDefaultFacts().issue; + } + if (out.facts && out.facts.pr && !out.facts.issue) st.kind = 'pr'; + else if (out.facts && out.facts.issue) st.kind = 'issue'; + st.result = out; + } + wfLibRerender(); + } + + async function wfSimRun() { + const st = _wfLib.sim; + wfSimReadForm(); + const body = { kind: st.kind, facts: st.facts }; + const item = wfSimParseItem(st.repo); + if (item) { body.repo = item.repo; body.number = item.number; } + const out = await wfSimCall(body); + if (out) st.result = out; + wfLibRerender(); + } + function wfRepoChoices() { const d = (_configState && _configState.data) || {}; const org = String(d.org || '').trim(); @@ -62871,6 +63154,7 @@

    Agent Watchdog

    async function wfLibOpen(name, version) { const key = name + '@' + version; _wfLib.view = 'detail'; _wfLib.detail = null; _wfLib.detailError = ''; _wfLib.loadingKey = key; _wfLib.selected = key; + _wfLib.sim.result = null; _wfLib.sim.error = ''; wfLibRerender(); try { const res = await fetch('/api/workflows/' + encodeURIComponent(name) + '/' + encodeURIComponent(version), { headers: _inceptionAuthHeaders() }); diff --git a/src/pkg/dashboard/workflows_library_ui_test.go b/src/pkg/dashboard/workflows_library_ui_test.go index 9bd6bfbc6f..87cb95b424 100644 --- a/src/pkg/dashboard/workflows_library_ui_test.go +++ b/src/pkg/dashboard/workflows_library_ui_test.go @@ -18,7 +18,7 @@ func TestWorkflowsLibraryTabWiring(t *testing.T) { `case 'Workflows': return renderGovWorkflows();`, `function renderGovWorkflows()`, `function renderWorkflowLibraryRows(workflows, bindings, owner)`, - `function renderWorkflowDetail(detail, bindings, owner)`, + `function renderWorkflowDetail(detail, bindings, owner, sim)`, `function workflowDiagramSvg(model, profile)`, `function renderWorkflowIngest(state, owner)`, `function openWorkflowLibraryEntry(name, version)`, diff --git a/src/pkg/dashboard/workflows_simulate_ui_test.go b/src/pkg/dashboard/workflows_simulate_ui_test.go new file mode 100644 index 0000000000..679fd1de25 --- /dev/null +++ b/src/pkg/dashboard/workflows_simulate_ui_test.go @@ -0,0 +1,150 @@ +package dashboard + +import ( + "os/exec" + "strings" + "testing" +) + +// TestWorkflowsSimulateWiring pins the RFC phase-3c surface +// (hivecommons/hive#17620): the detail view grows a Simulate panel whose +// form is generated from WF_SIM_FIELDS, posts to the simulate endpoint, +// and marks the resulting state in the diagram. +func TestWorkflowsSimulateWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `const WF_SIM_FIELDS = [`, + `function renderWorkflowSimulate(state, owner)`, + `function renderWorkflowSimulateResult(result)`, + `function wfSimFactsFromForm(facts, kind, read)`, + `function wfSimFormFromFacts(facts, field)`, + `function wfSimMarkDiagram(svg, result)`, + `function wfSimSet(field, value)`, + `async function wfSimFetch()`, + `async function wfSimRun()`, + `+ '/simulate',`, + `renderWorkflowSimulate(sim, owner)`, + `data-action="wfSimRun"`, + `data-action="wfSimFetch"`, + `.wf-dg-state.simulated .wf-dg-chip {`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing Simulate wiring %q", want) + } + } +} + +func jsConst(t *testing.T, html, name, end string) string { + t.Helper() + start := strings.Index(html, "const "+name+" = ") + if start < 0 { + t.Fatalf("index.html does not define %s", name) + } + stop := strings.Index(html[start:], end) + if stop < 0 { + t.Fatalf("%s has no terminator %q", name, end) + } + return html[start:start+stop+len(end)] + "\n" +} + +// Pure renderers under node: the form renders only the fields for the +// chosen kind and round-trips facts; the result renders the decision +// chip, highlights the matched rule and shows each predicate's verdict; +// abstentions read "Not covered"; the diagram marks the simulated state. +func TestWorkflowsSimulateNode(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed") + } + html := indexHTML(t) + script := `const assert = require('assert'); +function esc(s) { return String(s).replace(/&/g, '&').replace(/ f.path), issueFields = wfSimFieldsFor('issue').map(f => f.path); +assert.ok(prFields.includes('pr.checks') && !prFields.includes('issue.bucket')); +assert.ok(issueFields.includes('issue.bucket') && !issueFields.includes('pr.checks') && !issueFields.includes('draft')); + +const facts = { labels: ['role/trusted', 'bug'], open: true, draft: false, author: { login: 'andy', kind: 'human', role: 'trusted', selfAuthored: false }, + park: { holds: null, needsHuman: true }, issue: { bucket: '' }, pr: { checks: 'green', review: 'approved', dco: 'yes', conflicting: false } }; +const state = { kind: 'pr', repo: 'cncf/techdocs#12', facts: facts, result: null, error: '', busy: false, open: false }; +const form = renderWorkflowSimulate(state, true); +assert.ok(form.includes('data-section="workflows-simulate"') && !/]*\sopen/.test(form), 'closed until used'); +assert.ok(form.includes('data-sim-field="pr.checks"') && !form.includes('data-sim-field="issue.bucket"'), 'PR form has no issue fields'); +assert.ok(/