diff --git a/changelog.d/added-workflowmodel-simulate.md b/changelog.d/added-workflowmodel-simulate.md new file mode 100644 index 0000000000..2c7bc52bef --- /dev/null +++ b/changelog.d/added-workflowmodel-simulate.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 3c ([#17620](https://github.com/hivecommons/hive/issues/17620)): simulate an issue or PR against a model before binding it. New read-only `POST /api/workflows/{name}/{version}/simulate` takes `{kind, facts}` (a JSON mirror of the engine's `Facts`) or `{repo, number}` to best-effort fill the facts from the forge (the response lists what was fetched and what stayed unknown), runs the stored model's deriver through the new `stageengine.Explain`, and returns the decision (state, column, stage label, reason, covered/abstain) with a per-rule trace — every rule in order, the first match highlighted, each predicate's holds/known verdict — or a single built-in entry for `derivation: builtin` models. Settings → Workflows → model detail grows a **Simulate** panel: pick `owner/repo#123` and Fetch facts, or describe the item in a form, Run, and the matched state lights up in the diagram. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index d4fae455f6..7c7b0f487c 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -35655,6 +35655,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": [ @@ -36162,6 +36226,262 @@ "$ref": "#/components/schemas/WorkflowEntry" } } + }, + "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" + } + } + } } } } 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/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index 1cbe3dae53..6f9e2df209 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -183,3 +183,78 @@ The tab never binds: binding stays on Settings → Repos so the per-repository d to the repository's other policy. The Activity Monitor's model badge deep-links here via `openWorkflowLibraryEntry(name, version)`. Every HTML builder is a pure function of its inputs so `workflows_library_ui_test.go` runs them under node without a DOM. Editing is phase 4. + +## Simulate (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" — the operator's confidence check before binding. Nothing is +written; any logged-in role may simulate. + +`POST /api/workflows/{name}/{version}/simulate` takes + +```json +{ "kind": "issue" | "pr", "facts": { ...SimulateFacts... }, "repo": "owner/repo", "number": 123 } +``` + +`facts` is a lowerCamel JSON mirror of `stageengine.Facts` (`SimulateFacts` in +`pkg/dashboard/api_workflows_simulate.go`): `labels`, `open`, `merged`, `draft`, `origin`, +`author{login,kind,selfAuthored,role}`, `park{holds,needsHuman,…}`, `issue{bucket,…}` and +`pr{checks,review,dco,conflicting,changesRequested,humanApprover,lane,…}`. Enumerations use the +engine's name helpers so a response can be pasted back as a request: `author.kind` +hive|clanker|human|unknown, `pr.checks` green|red|pending|unknown, `pr.review` +approved|changes_requested|pending|unavailable|requires_human, `pr.dco` yes|no|unknown +(`stageengine.ParseAuthorKind/ParseChecks/ParseReview/ParseDCO` are the inverses of the name +helpers). `park.holds` left null is derived from the labels with `stagelabels.Holds`. + +The handler loads and compiles the stored model exactly as `GET` does, converts the facts, and +calls `stageengine.Explain(profile, kind, facts)`, which returns the same `Decision` as +`DeriveFromModel(...).Derive` plus a trace: + +```json +{ + "decision": { "state": "accepted", "column": "Accepted", "stage": 20, "label": "stage/020-accepted", + "reason": "rule accepted", "abstain": false, "covered": true, "terminal": false }, + "trace": [ { "id": "requested", "state": "requested", "evaluated": true, "matched": false, + "predicates": [ { "fact": "label", "op": "has", "value": "techdocs/request", "holds": true, "known": true }, + { "fact": "label", "op": "not", "value": "techdocs/accepted", "holds": false, "known": true, "actual": "techdocs/accepted" } ] }, + { "id": "accepted", "state": "accepted", "evaluated": true, "matched": true, "predicates": [ … ] }, + { "id": "pr-review", "state": "review", "kind": "pr", "evaluated": false, "matched": false, "skipped": "kind pr" }, + { "id": "later", "state": "done", "evaluated": false, "matched": false } ], + "facts": { …normalized echo… }, "filled": [], "unknown": [], "notes": [] +} +``` + +Trace semantics: for `derivation: rules` every rule appears in order; rules for the other item +kind are `skipped`; rules are `evaluated` until the first `matched` one, each with its predicates' +`holds`/`known` verdicts and the actual value when it differs; rules after the match are listed +with `evaluated: false`. The uncovered case has no matched rule and the decision carries +`abstain: true, covered: false, reason "workflow: not covered…"`. For `derivation: builtin` +(hive-default and ingested models) the trace is a single `{builtin: true, state, reason}` entry, +because the built-in derivers are not rule lists. `column` is looked up from the profile and +`stage` from the state's `lifecycle.number`; a built-in decision of Stage None (for example a +draft PR) returns `covered: true` with an empty `state` and the deriver's reason. + +Built-in PR derivation reads lane facts the engine's lane observers normally supply. When the +request carries no `pr.lane`, `stageengine.SimulatedLane` synthesizes one from the other facts +(self-authored / trusted-author / contributor lane; reason from merged, closed, draft, conflict, +changes requested, holds, needs-human, red or pending checks, missing review, untrusted role) and +the response says so in `notes`. Give `pr.lane{lane,reason}` explicitly to override it. + +Best-effort fill: `repo` + `number` without `facts` fetches the item through the hive's GitHub +client (`github.Client.WorkflowItemSnapshot`: the issue, the PR when it is one, its mergeable +state and the head commit's check summary) and fills `labels`, `open`, `merged`, `draft`, +`author.login`, `author.role` (from `role/*` labels), `park.holds`, `origin`, and for PRs +`pr.checks`, `pr.dco`, `pr.conflicting`, `pr.headSHA`, `pr.baseRef`. `filled` lists what came +from the forge and `unknown` what stayed at its default — `author.kind`, `pr.review`, +`issue.bucket` and the claim/covering-PR facts need the engine's own observers and are not +fetched; edit them in the form before running. `kind` may be omitted and is taken from the item; +a mismatch is a 400. Without a wired GitHub client the endpoint answers 422 rather than guessing. + +The UI (`renderWorkflowSimulate`, `renderWorkflowSimulateResult` in +`config-workflows-library.js`) lives in a collapsed **Simulate** section of the model detail page: +a `owner/repo#123` picker with Fetch facts, an issue/PR radio, and a facts form generated from the +declarative `WF_SIM_FIELDS` table (so the builder, the form reader and +`workflows_simulate_ui_test.go` share one definition). Run posts the form, shows the decision chip +(state · column · stage · reason or **Not covered**), the trace as an ordered list with the +matched rule highlighted and each predicate as `fact op value → ✓/✗/?`, and +`wfSimMarkDiagram` tags the resulting state's chip in the diagram (`.wf-dg-state.simulated`). diff --git a/src/pkg/dashboard/api_workflows.go b/src/pkg/dashboard/api_workflows.go index c1065c0952..7cff0d7dfe 100644 --- a/src/pkg/dashboard/api_workflows.go +++ b/src/pkg/dashboard/api_workflows.go @@ -26,6 +26,7 @@ func (s *Server) registerWorkflowRoutes() { s.mux.HandleFunc("GET /api/workflows/{name}/{version}", s.handleWorkflowGet) s.mux.HandleFunc("PUT /api/workflows/{name}/{version}", s.handleWorkflowSave) s.mux.HandleFunc("DELETE /api/workflows/{name}/{version}", s.handleWorkflowDelete) + 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..20ae4760ce --- /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/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 @@ '
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.
' + - '' + esc(JSON.stringify(m, null, 2)) + '
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.
' + + '${esc(st.error)}
` : '') + + (st.result ? renderWorkflowSimulateResult(st.result) : '') + + '' + fill.join('
') + '
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.
' + - '' + esc(JSON.stringify(m, null, 2)) + '
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.
' + + '${esc(st.error)}
` : '') + + (st.result ? renderWorkflowSimulateResult(st.result) : '') + + '' + fill.join('
') + '