Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-workflow-model-reply-verbs-item-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Workflow models: a bound model's `/hive <verb>` replies now follow the item's current model state, so they work on PRs and on issues that are not parked, not only on parked issues. Off the parked path a reply applies only the label the model maps to it and is answered in one comment; no park label is touched, and unbound repositories and `hive-default` behave as before (#18357).
24 changes: 4 additions & 20 deletions src/pkg/github/issue_model_reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,9 @@ func (c *Client) applyIssueModelReply(ctx context.Context, owner, repo string, n
if err := c.clearIssueParkingLabels(ctx, owner, repo, number, labels, actor, needsHuman.lift); err != nil {
return IssueUnparkEvent{}, err
}
applied := ""
if eff.Label != "" && !labelPresent(labels, eff.Label) {
if _, _, err := c.client.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{eff.Label}); err != nil { // writeback:solicited a maintainer answered the gate with this model verb (comment or dashboard)
return IssueUnparkEvent{}, fmt.Errorf("adding %s to %s/%s#%d: %w", eff.Label, owner, repo, number, err)
}
c.recordWriteAudit(AuditActionHiveLabelApplied, hiveWriteMeta(),
WriteTarget{Repo: owner + "/" + repo, Number: number}, "label", eff.Label, "reply", eff.Verb)
applied = eff.Label
applied, err := c.applyModelReplyLabel(ctx, owner, repo, number, labels, eff)
if err != nil {
return IssueUnparkEvent{}, err
}
decision := eff.Verb
if t := strings.TrimSpace(text); t != "" {
Expand All @@ -126,18 +121,7 @@ func (c *Client) applyIssueModelReply(ctx context.Context, owner, repo string, n
// same sentence as a built-in decision so the `Decision:` round-trip the
// decision history reads is unchanged, then says what the model did with it.
func renderModelReplyAccepted(actor, decision string, eff workflowmodel.ReplyEffect, applied string, needsHuman bool, outcome unparkNeedsHumanOutcome) string {
b := renderUnparkAcceptedReply(actor, decision, needsHuman, outcome)
var tail strings.Builder
fmt.Fprintf(&tail, "\n\nWorkflow reply `%s`", eff.Verb)
switch {
case eff.To != "" && applied != "":
fmt.Fprintf(&tail, " moves the item from `%s` to `%s`; `%s` applied.", eff.From, eff.To, applied)
case eff.To != "":
fmt.Fprintf(&tail, " moves the item from `%s` to `%s`; the model maps no label to that state, so the reply is recorded here only.", eff.From, eff.To)
default:
tail.WriteString(" is recorded; the model declares no transition for it.")
}
return b + tail.String()
return renderUnparkAcceptedReply(actor, decision, needsHuman, outcome) + modelReplyEffectSentence(eff, applied)
}

// RecordOperatorIssueModelReply is RecordOperatorIssueDecision for a model
Expand Down
24 changes: 23 additions & 1 deletion src/pkg/github/issue_unpark_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,14 @@ type IssueUnparkSweepResult struct {
// completed (hivecommons/dibs#459); Decision carries the note after the
// command, if any.
Closed []IssueUnparkEvent
// ModelReplies lists the bound workflow model's reply verbs answered on
// items off the parked-issue path — PRs and issues that are not parked
// (hivecommons/hive#18357). Parked issues report theirs in Unparked.
ModelReplies []IssueUnparkEvent
}

func (r *IssueUnparkSweepResult) actions() int {
return len(r.Unparked) + r.Replies + len(r.LabelApproved) + len(r.PRDecisions) + len(r.Closed)
return len(r.Unparked) + r.Replies + len(r.LabelApproved) + len(r.PRDecisions) + len(r.Closed) + len(r.ModelReplies)
}

// SweepIssueUnparkCommands lets a maintainer re-queue a parked issue with a
Expand Down Expand Up @@ -332,6 +336,24 @@ func (c *Client) SweepIssueUnparkCommands(ctx context.Context, opts IssueUnparkS
c.logger.Warn("unpark sweep skipped attention commands", "repo", repo, "item", issue.GetNumber(), "error", err)
}
labels := issueLabelNames(issue.Labels)
// A bound model's reply verbs follow the item's current model
// state (hivecommons/hive#18357): on a PR or an issue that is not
// parked, a `/hive <verb>` the state offers is answered here.
// Parked issues keep the path below, which also clears their
// park labels.
if issue.IsPullRequest() || !hasIssueParkingLabel(labels) {
acted, err := c.tryItemModelReply(ctx, repo, owner, repoName, issue, cutoff, profile, result)
if err != nil {
if c.logger != nil {
c.logger.Warn("unpark sweep skipped workflow model reply", "repo", repo, "item", issue.GetNumber(), "error", err)
}
result.Skipped++
continue
}
if acted {
continue
}
}
if issue.IsPullRequest() {
// `/hive approve` on any PR gets an acknowledgement or an
// explanation of why the lane cannot use it
Expand Down
151 changes: 151 additions & 0 deletions src/pkg/github/item_model_reply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package github

import (
"context"
"fmt"
"strings"
"time"

gh "github.com/google/go-github/v72/github"

"github.com/hivecommons/hive/pkg/stagelabels"
"github.com/hivecommons/hive/pkg/workflowmodel"
)

// Model reply verbs outside the parked-issue path (hivecommons/hive#18357).
//
// A bound workflow model declares its reply verbs per state, and its state
// numbers are the stage numbers items carry (stageengine.DeriveForRepo), so
// a verb belongs to wherever the item currently sits — a PR at review, an
// issue being worked — not only to an issue parked on a person. The parked
// path (tryUnparkIssue) still owns parked issues, because a reply there also
// clears the hive's park labels; this path answers every other item whose
// current model state offers verbs, and changes only what the model maps the
// reply to.

// tryItemModelReply answers the newest eligible model reply on an item that
// is not on the parked-issue path: the label the model maps to the reply's
// transition (if any) is applied and the reply is answered in one comment.
// Nothing else is touched — no park label is cleared and no built-in
// command is consumed — so an unbound repository, the hive-default model or
// a state without verbs costs no API call and behaves exactly as before.
func (c *Client) tryItemModelReply(ctx context.Context, displayRepo, owner, repo string, issue *gh.Issue, cutoff time.Time, profile *workflowmodel.Profile, result *IssueUnparkSweepResult) (bool, error) {
verbs := issueModelReplyVerbs(profile, issue)
if len(verbs) == 0 {
return false, nil
}
number := issue.GetNumber()
comments, err := c.listIssueComments(ctx, owner, repo, number)
if err != nil {
return false, err
}
candidate, command, err := c.eligibleModelReplyCommand(ctx, owner, repo, comments, c.answeredUnparkCommentIDs(comments), cutoff, verbs)
if err != nil || candidate == nil {
return false, err
}
labels := issueLabelNames(issue.Labels)
eff, ok := profile.ReplyForNumber(stagelabels.Current(labels).Number(), command.Verb)
if !ok {
return false, nil
}
actor := safeGetLogin(candidate.GetUser())
applied, err := c.applyModelReplyLabel(ctx, owner, repo, number, labels, eff)
if err != nil {
return false, err
}
decision := eff.Verb
if t := strings.TrimSpace(command.DecisionText()); t != "" {
decision += ": " + t
}
if err := c.postUnparkReply(ctx, owner, repo, number, candidate.GetID(), renderItemModelReplyAccepted(actor, decision, eff, applied)); err != nil {
return false, err
}
event := IssueUnparkEvent{Repo: displayRepo, Number: number, Actor: actor, Decision: decision, CommentURL: candidate.GetHTMLURL()}
result.ModelReplies = append(result.ModelReplies, event)
if c.logger != nil {
c.logger.Info("workflow model reply recorded", "repo", displayRepo, "item", number, "pr", issue.IsPullRequest(), "actor", actor, "reply", eff.Verb, "to", eff.To, "label", applied)
}
return true, nil
}

// eligibleModelReplyCommand is eligibleUnparkCommand restricted to the
// model's reply verbs: only a `/hive <verb>` for the item's current state is
// a candidate, so built-in commands and prose assent off the parked path are
// left to the handlers that already own them. An answered model reply is a
// watermark — nothing older is replayed.
func (c *Client) eligibleModelReplyCommand(ctx context.Context, owner, repo string, comments []*gh.IssueComment, answered map[int64]bool, cutoff time.Time, verbs []string) (*gh.IssueComment, unparkCommand, error) {
checked := 0
for i := len(comments) - 1; i >= 0 && checked < unparkCandidateLimit; i-- {
cm := comments[i]
if cm == nil {
continue
}
cmd, isReply := parseModelReplyCommand(cm.GetBody(), verbs)
if answered[cm.GetID()] {
if isReply {
break
}
continue
}
if !isReply {
continue
}
created := cm.GetCreatedAt().Time
if created.Before(cutoff) {
continue
}
// An edit to an existing comment is not a new instruction.
if updated := cm.GetUpdatedAt().Time; updated.After(created) {
continue
}
if !c.isHumanAuthor(cm.GetUser()) || isHiveSelfDecisionComment(cm.GetBody()) {
continue
}
checked++
allowed, err := c.commenterMayUnpark(ctx, owner, repo, safeGetLogin(cm.GetUser()), false)
if err != nil {
return nil, unparkCommand{}, err
}
if !allowed {
continue
}
return cm, cmd, nil
}
return nil, unparkCommand{}, nil
}

// applyModelReplyLabel adds the label the model maps to eff, unless the item
// already wears it, and returns the label applied ("" for none).
func (c *Client) applyModelReplyLabel(ctx context.Context, owner, repo string, number int, labels []string, eff workflowmodel.ReplyEffect) (string, error) {
if eff.Label == "" || labelPresent(labels, eff.Label) {
return "", nil
}
if _, _, err := c.client.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{eff.Label}); err != nil { // writeback:solicited a maintainer answered the gate with this model verb (comment or dashboard)
return "", fmt.Errorf("adding %s to %s/%s#%d: %w", eff.Label, owner, repo, number, err)
}
c.recordWriteAudit(AuditActionHiveLabelApplied, hiveWriteMeta(),
WriteTarget{Repo: owner + "/" + repo, Number: number}, "label", eff.Label, "reply", eff.Verb)
return eff.Label, nil
}

// renderItemModelReplyAccepted is the reply to a model verb off the parked
// path. It keeps the `Decision:` sentence shape of the parked reply but does
// not claim an un-park, since nothing was parked.
func renderItemModelReplyAccepted(actor, decision string, eff workflowmodel.ReplyEffect, applied string) string {
return fmt.Sprintf("Recorded for @%s. Decision: %s.%s", actor, decision, modelReplyEffectSentence(eff, applied))
}

// modelReplyEffectSentence says what the model did with a reply.
func modelReplyEffectSentence(eff workflowmodel.ReplyEffect, applied string) string {
var tail strings.Builder
fmt.Fprintf(&tail, "\n\nWorkflow reply `%s`", eff.Verb)
switch {
case eff.To != "" && applied != "":
fmt.Fprintf(&tail, " moves the item from `%s` to `%s`; `%s` applied.", eff.From, eff.To, applied)
case eff.To != "":
fmt.Fprintf(&tail, " moves the item from `%s` to `%s`; the model maps no label to that state, so the reply is recorded here only.", eff.From, eff.To)
default:
tail.WriteString(" is recorded; the model declares no transition for it.")
}
return tail.String()
}
118 changes: 118 additions & 0 deletions src/pkg/github/item_model_reply_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package github

import (
"context"
"encoding/json"
"os"
"strings"
"testing"

"github.com/hivecommons/hive/pkg/stagelabels"
"github.com/hivecommons/hive/pkg/workflowmodel"
)

// techdocsPRReplyProfile is the techdocs test model with a label mapped to
// the PR state `approved`, so `approve` at draft-review (PR stage 050) both
// moves the item and applies a label.
func techdocsPRReplyProfile(t *testing.T) *workflowmodel.Profile {
t.Helper()
b, err := os.ReadFile("../workflowmodel/testdata/models/techdocs.json")
if err != nil {
t.Fatal(err)
}
var m workflowmodel.Model
if err := json.Unmarshal(b, &m); err != nil {
t.Fatal(err)
}
m.Spec.Labels = workflowmodel.LabelSet{Prefix: "docs", Entries: []workflowmodel.LabelEntry{{Name: "docs/090-approved", State: "approved"}}}
p, _, err := workflowmodel.Compile(&m)
if err != nil {
t.Fatal(err)
}
return p
}

func TestSweepModelReplyOnPullRequestState(t *testing.T) {
pr := unparkWireIssue{
Number: 12,
Title: "docs draft",
User: wireUser{Login: "author"},
Labels: []wireLabel{{Name: stagelabels.ReviewPending.Label()}},
Comments: []unparkWireComment{humanComment(21, "maintainer", "/hive approve ship it")},
PullRequest: &unparkWirePRLink{URL: "https://example.test/pulls/12"},
}
server, rec := newUnparkServer(t, "org", "repo", []unparkWireIssue{pr}, map[string]string{"maintainer": "write"})
c := newTestClient(t, server, "org", []string{"repo"})
p := techdocsPRReplyProfile(t)

result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{
WorkflowFor: func(string, string) *workflowmodel.Profile { return p },
})
if err != nil {
t.Fatalf("sweep: %v", err)
}
if got := strings.Join(rec.added[12], ","); got != "docs/090-approved" {
t.Fatalf("expected the mapped model label added to PR 12, got %v", rec.added[12])
}
if len(result.ModelReplies) != 1 || result.ModelReplies[0].Number != 12 || result.ModelReplies[0].Decision != "approve: ship it" {
t.Fatalf("expected the model reply on PR 12 recorded, got %+v", result.ModelReplies)
}
if len(result.Unparked) != 0 {
t.Fatalf("a PR reply is not an un-park: %+v", result.Unparked)
}
if len(rec.removed[12]) != 0 {
t.Fatalf("a model reply off the parked path must remove nothing, got %v", rec.removed[12])
}
joined := strings.Join(rec.posted[12], "\n")
if !strings.Contains(joined, "Workflow reply `approve` moves the item from `draft-review` to `approved`; `docs/090-approved` applied.") {
t.Fatalf("reply = %v", rec.posted[12])
}
if !strings.Contains(joined, unparkReplyMarkerPrefix+"21 -->") || strings.Contains(joined, "Un-parked") {
t.Fatalf("reply must answer comment 21 without claiming an un-park, got %v", rec.posted[12])
}
}

func TestSweepModelReplyOnUnparkedIssueFollowsCurrentState(t *testing.T) {
// The issue sits at 020 (analysing), which is not parked; its verb
// records only. Issue 9 sits there too but replies with a verb only
// 045 offers.
issue := parkedIssue(8)
issue.Labels = []wireLabel{{Name: stagelabels.Claimed.Label()}}
issue.Comments = []unparkWireComment{humanComment(31, "maintainer", "/hive hand back over to docs team")}
other := parkedIssue(9, humanComment(41, "maintainer", "/hive revise"))
other.Labels = []wireLabel{{Name: stagelabels.Claimed.Label()}}
server, rec := newUnparkServer(t, "org", "repo", []unparkWireIssue{issue, other}, map[string]string{"maintainer": "write"})
c := newTestClient(t, server, "org", []string{"repo"})
p := techdocsReplyProfile(t)

result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{
WorkflowFor: func(string, string) *workflowmodel.Profile { return p },
})
if err != nil {
t.Fatalf("sweep: %v", err)
}
if len(result.ModelReplies) != 1 || result.ModelReplies[0].Number != 8 || result.ModelReplies[0].Decision != "hand back: over to docs team" {
t.Fatalf("expected issue 8's reply recorded, got %+v", result.ModelReplies)
}
joined := strings.Join(rec.posted[8], "\n")
if !strings.Contains(joined, "Recorded for @maintainer. Decision: hand back: over to docs team.") || !strings.Contains(joined, "Workflow reply `hand back` is recorded; the model declares no transition for it.") {
t.Fatalf("reply = %v", rec.posted[8])
}
if len(rec.added[8])+len(rec.removed[8]) != 0 {
t.Fatalf("a record-only reply changes no labels, got added=%v removed=%v", rec.added[8], rec.removed[8])
}
if len(rec.posted[9])+len(rec.added[9]) != 0 {
t.Fatalf("a verb the current state does not offer must be ignored, got posted=%v added=%v", rec.posted[9], rec.added[9])
}

// Unbound: the same comment is no command at all.
server2, rec2 := newUnparkServer(t, "org", "repo", []unparkWireIssue{issue}, map[string]string{"maintainer": "write"})
c2 := newTestClient(t, server2, "org", []string{"repo"})
result, err = c2.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{})
if err != nil {
t.Fatalf("unbound sweep: %v", err)
}
if len(result.ModelReplies) != 0 || len(rec2.posted[8]) != 0 {
t.Fatalf("unbound repo must not answer a model verb: %+v posted=%v", result.ModelReplies, rec2.posted[8])
}
}
Loading