diff --git a/changelog.d/added-workflow-model-dispatch-targets.md b/changelog.d/added-workflow-model-dispatch-targets.md new file mode 100644 index 0000000000..cae227fe17 --- /dev/null +++ b/changelog.d/added-workflow-model-dispatch-targets.md @@ -0,0 +1 @@ +- Workflow models resolve where each agent profile takes over an item (`spec.agents[].dispatch`, or by convention the grant's first state, on entry or on the gate reply for a reviewing profile), and `workflow.dispatch.profiles..agent` maps a profile to a hive agent (default: an agent named after the profile, else a writer, docs or feature agent); the curated TechDocs model hands Accepted to `techdocs-drafter` and `/verify` to `techdocs-verifier`. diff --git a/src/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index e3a58f6e1e..87e7b04e54 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -646,6 +646,67 @@ three places, all for a repository bound to a non-default model only: still declares them; labels a model dropped *before* this change shipped are never reclaimed automatically. +## Agent dispatch + +A model's agent grants (`spec.agents`) say which profile may act in which states. The compiler +also resolves where the hive **hands an item to** a profile, and the compiled `Profile` carries +the result as `dispatch` (state id → `DispatchTarget`, `pkg/workflowmodel/dispatch.go`) next to +the grants themselves (`agents`). + +**Where and when.** A grant may declare it: + +```yaml +agents: +- profile: techdocs-verifier + states: [drafting] + produces: [comment] + dispatch: + states: [drafting] # subset of states; [] = never dispatch automatically + reply: /verify # empty: once on entering the state + instructions: Post the fact-check report as one PR comment. +``` + +Without a `dispatch` block the convention applies: the grant's **first** state is its entry +state. A profile that produces a pull request or a push is dispatched once on entering it. A +profile that produces neither (a verifier, a reviewer) is dispatched on the reply that releases +the gate out of its entry state into a non-terminal state, when the state declares that reply. +For the curated `cncf-techdocs-assessment` model this gives, with no new field: + +| State | Profile | Trigger | +|-------|---------|---------| +| `accepted` (issue) | `techdocs-drafter` | on entry (`triage/accepted`, no covering PR) | +| `drafting` (PR) | `techdocs-verifier` | the reviewer's `/verify` | + +Two profiles dispatched in one state, or a dispatch state outside the grant, refuse the compile +(`duplicate-dispatch`, `unknown-state`); a dispatch reply the state does not declare is a +`dispatch-reply-undeclared` warning. The built-in `hive-default` model never dispatches: its +grants describe the fleet that already runs it. + +**Deliverable.** For a profile that produces a pull request, the target also names the +deliverable: the first pull-request state among the grant's later states, with the labels and +draft flag that state's first derivation rule requires (TechDocs: a draft PR labeled +`Docs analysis`, landing in `drafting`). The dispatch prompt asks for exactly that. + +**Who fills a profile.** A model names roles; a hive names agents. `workflow.dispatch` maps one +to the other (`config.WorkflowDispatchAgent`): + +```yaml +workflow: + dispatch: + enabled: true # default; dispatch also needs workflow.enabled + profiles: + techdocs-drafter: + agent: writer # default below + prompt_template: "" # default: the built-in prompt + techdocs-verifier: + disabled: true # never dispatch automatically +``` + +An unset `agent` resolves to an enabled agent named after the profile, else the first enabled +agent (by name) whose role is `writer`, then `docs`, then `feature`. A configured agent that does +not exist or is disabled fills nothing: a typo never falls back to another agent. Replica +overlays are never chosen; the base agent is kicked. + ## Ingest from cluster and from written specs (RFC phase 6) Two more ways into a draft model, beside the repository ingest of phase 3a. Both end in the diff --git a/src/hive.yaml.example b/src/hive.yaml.example index b18b7fbf83..fc70536843 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -1337,3 +1337,11 @@ data: # workflow: # enabled: false # false (default): bindings are columns only # label_gc: true # delete labels a previous binding provisioned once nothing wears them +# dispatch: # hand model states to agents (docs/design/workflow-models.md#agent-dispatch) +# enabled: true # default; also needs enabled: true above +# profiles: +# techdocs-drafter: +# agent: writer # default: an agent named after the profile, else role writer, docs, feature +# prompt_template: "" # default: the built-in dispatch prompt +# techdocs-verifier: +# disabled: false # true: never dispatch automatically (Send to … still works) diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index f4eafb9d67..f3a2478fa3 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -310,6 +310,9 @@ type WorkflowConfig struct { // Marketplace configures the spoke's view of the hub workflow catalogue // (hivecommons/hive#17620 phase 7). Marketplace MarketplaceConfig `yaml:"marketplace,omitempty" json:"marketplace,omitempty"` + // Dispatch maps a bound model's agent profiles to hive agents + // (workflow_dispatch.go). + Dispatch WorkflowDispatchConfig `yaml:"dispatch,omitempty" json:"dispatch,omitzero"` } // LabelGCEnabled is the effective workflow.label_gc (default true). diff --git a/src/pkg/config/workflow_dispatch.go b/src/pkg/config/workflow_dispatch.go new file mode 100644 index 0000000000..5fb64e1941 --- /dev/null +++ b/src/pkg/config/workflow_dispatch.go @@ -0,0 +1,110 @@ +package config + +import ( + "sort" + "strings" +) + +// WorkflowDispatchConfig is the `workflow.dispatch:` block: which hive agent +// fills each agent profile a bound workflow model hands items to +// (workflowmodel.DispatchTarget), and the prompt it is kicked with. +// +// workflow: +// dispatch: +// enabled: true # default +// profiles: +// techdocs-drafter: +// agent: writer # default: an agent named after the profile, else writer/docs/feature +// prompt_template: "" # default: the built-in dispatch prompt +// techdocs-verifier: +// disabled: true # never dispatch this profile automatically +type WorkflowDispatchConfig struct { + // Enabled turns automatic dispatch on. Nil means true: a model that + // declares a dispatch target and a fleet with an agent to fill it + // dispatches out of the box. Dispatch also needs workflow.enabled. + Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` + // Profiles maps a model profile name to its hive-side settings. + Profiles map[string]WorkflowDispatchProfile `yaml:"profiles,omitempty" json:"profiles,omitempty"` +} + +// WorkflowDispatchProfile is one profile's hive-side dispatch settings. +type WorkflowDispatchProfile struct { + // Agent is the hive agent the profile is handed to. Empty resolves by + // default (WorkflowDispatchAgent). + Agent string `yaml:"agent,omitempty" json:"agent,omitempty"` + // PromptTemplate replaces the built-in dispatch prompt. ${VAR} + // placeholders are expanded (docs/design/workflow-models.md lists them). + PromptTemplate string `yaml:"prompt_template,omitempty" json:"prompt_template,omitempty"` + // Disabled keeps the profile from being dispatched automatically; the + // dashboard's owner-only "Send to " still works. + Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"` +} + +// DefaultWorkflowDispatchRoles are the agent roles a profile with no +// configured agent falls back to, in preference order. +var DefaultWorkflowDispatchRoles = []string{"writer", "docs", "feature"} + +// DispatchEnabled is the effective workflow.dispatch.enabled (default true). +func (c WorkflowDispatchConfig) DispatchEnabled() bool { + return c.Enabled == nil || *c.Enabled +} + +// Profile returns the settings for a model profile (zero when unset). +func (c WorkflowDispatchConfig) Profile(name string) WorkflowDispatchProfile { + if c.Profiles == nil { + return WorkflowDispatchProfile{} + } + return c.Profiles[strings.TrimSpace(name)] +} + +// WorkflowDispatchAgent resolves the hive agent that fills a model profile: +// the configured workflow.dispatch.profiles..agent when it names an +// enabled agent; else an enabled agent named after the profile; else the +// first enabled agent (by name) whose role is the earliest of +// DefaultWorkflowDispatchRoles. Replica overlays are never chosen: the base +// agent is the one kicked. ok is false when nothing fills the profile, the +// profile is disabled, or a configured agent does not exist (a typo never +// falls back to another agent). +func (c *Config) WorkflowDispatchAgent(profile string) (agent string, ok bool) { + if c == nil { + return "", false + } + profile = strings.TrimSpace(profile) + if profile == "" { + return "", false + } + set := c.Workflow.Dispatch.Profile(profile) + if set.Disabled { + return "", false + } + usable := func(name string) bool { + a, exists := c.Agents[name] + return exists && a.Enabled && a.ReplicaOf == "" + } + if want := strings.TrimSpace(set.Agent); want != "" { + return want, usable(want) + } + if usable(profile) { + return profile, true + } + names := make([]string, 0, len(c.Agents)) + for name := range c.Agents { + names = append(names, name) + } + sort.Strings(names) + for _, role := range DefaultWorkflowDispatchRoles { + for _, name := range names { + if !usable(name) { + continue + } + r := c.Agents[name].Role + if r == "" { + r = name + } + if strings.EqualFold(r, role) { + return name, true + } + } + } + return "", false +} diff --git a/src/pkg/config/workflow_dispatch_test.go b/src/pkg/config/workflow_dispatch_test.go new file mode 100644 index 0000000000..72eb548279 --- /dev/null +++ b/src/pkg/config/workflow_dispatch_test.go @@ -0,0 +1,66 @@ +package config + +import "testing" + +func TestWorkflowDispatchAgent(t *testing.T) { + off := false + base := func() *Config { + c := &Config{} + c.Agents = map[string]AgentConfig{ + "scanner": {Enabled: true, Role: "scanner"}, + "zed": {Enabled: true, Role: "feature"}, + "alpha": {Enabled: true, Role: "feature"}, + "alpha-2": {Enabled: true, Role: "feature", ReplicaOf: "alpha"}, + "scribe": {Enabled: false, Role: "writer"}, + "architect": {Enabled: true}, + } + return c + } + cases := []struct { + name string + mut func(c *Config) + profile string + want string + ok bool + }{ + {"role fallback picks the first feature agent by name", nil, "techdocs-drafter", "alpha", true}, + {"a disabled writer is skipped", nil, "techdocs-drafter", "alpha", true}, + {"enabled writer outranks feature", func(c *Config) { c.Agents["scribe"] = AgentConfig{Enabled: true, Role: "writer"} }, "techdocs-drafter", "scribe", true}, + {"agent named after the profile", func(c *Config) { c.Agents["techdocs-drafter"] = AgentConfig{Enabled: true} }, "techdocs-drafter", "techdocs-drafter", true}, + {"configured agent wins", func(c *Config) { + c.Workflow.Dispatch.Profiles = map[string]WorkflowDispatchProfile{"techdocs-drafter": {Agent: "architect"}} + }, "techdocs-drafter", "architect", true}, + {"configured typo never falls back", func(c *Config) { + c.Workflow.Dispatch.Profiles = map[string]WorkflowDispatchProfile{"techdocs-drafter": {Agent: "nobody"}} + }, "techdocs-drafter", "nobody", false}, + {"disabled profile", func(c *Config) { + c.Workflow.Dispatch.Profiles = map[string]WorkflowDispatchProfile{"techdocs-verifier": {Disabled: true}} + }, "techdocs-verifier", "", false}, + {"no agent fills it", func(c *Config) { + c.Agents = map[string]AgentConfig{"scanner": {Enabled: true, Role: "scanner"}} + }, "techdocs-drafter", "", false}, + {"empty profile", nil, "", "", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := base() + if tc.mut != nil { + tc.mut(c) + } + got, ok := c.WorkflowDispatchAgent(tc.profile) + if got != tc.want || ok != tc.ok { + t.Fatalf("WorkflowDispatchAgent(%q) = %q %v; want %q %v", tc.profile, got, ok, tc.want, tc.ok) + } + }) + } + var nilCfg *Config + if _, ok := nilCfg.WorkflowDispatchAgent("x"); ok { + t.Fatal("nil config resolved an agent") + } + if !(WorkflowDispatchConfig{}).DispatchEnabled() { + t.Fatal("dispatch must default on") + } + if (WorkflowDispatchConfig{Enabled: &off}).DispatchEnabled() { + t.Fatal("enabled: false must turn dispatch off") + } +} diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 356c1c2fd1..dc0ee40bf5 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -630,6 +630,10 @@ project.workflow_bindings[].repo # see project.workflow_bindings[].name project.workflow_bindings[].version # see project.workflow_bindings[].name project.remote_write_identity # Settings control lands in the follow-up PR for #18516 workflow.label_gc # operator safety knob for model-label garbage collection on rebind; yaml-only, no Settings control planned (RFC #17620) +workflow.dispatch.enabled # workflow-model agent dispatch kill switch; yaml-only (cncf/techdocs#395) +workflow.dispatch.profiles..agent # which hive agent fills a model profile; yaml-only (cncf/techdocs#395) +workflow.dispatch.profiles..prompt_template # see workflow.dispatch.profiles..agent +workflow.dispatch.profiles..disabled # see workflow.dispatch.profiles..agent inbox.sources[] # which voice connector types feed the Inbox; defaults to every configured plaud/wisprflow connector, yaml-only (Inbox RFC) inbox.rules[].source # auto-routing rules are edited as whole rows in Inbox → Auto-routing via POST /api/inbox/settings, not leaf-path controls (Inbox RFC) inbox.rules[].title_prefix # see inbox.rules[].source diff --git a/src/pkg/hub/marketplace/curated/curated_test.go b/src/pkg/hub/marketplace/curated/curated_test.go index 975017449d..62c80b99ad 100644 --- a/src/pkg/hub/marketplace/curated/curated_test.go +++ b/src/pkg/hub/marketplace/curated/curated_test.go @@ -274,3 +274,27 @@ func TestEntriesSorted(t *testing.T) { } } } + +// TestTechDocsDispatch pins the agent hand-off the hive derives from the +// curated model without any new field (cncf/techdocs#395): the drafter is +// dispatched once when a request is Accepted and must open a draft PR +// labeled Docs analysis; the verifier runs on the reviewer's /verify in +// Drafting. +func TestTechDocsDispatch(t *testing.T) { + p := techdocs(t) + d, ok := p.DispatchFor("accepted") + if !ok || d.Profile != "techdocs-drafter" || d.Reply != "" || !d.AppliesTo(workflowmodel.KindIssue) { + t.Fatalf("accepted dispatch = %+v %v", d, ok) + } + want := &workflowmodel.Deliverable{State: "drafting", Draft: true, Labels: []string{"Docs analysis"}} + if !reflect.DeepEqual(d.Deliverable, want) { + t.Fatalf("drafter deliverable %+v want %+v", d.Deliverable, want) + } + v, ok := p.DispatchFor("drafting") + if !ok || v.Profile != "techdocs-verifier" || v.Reply != "/verify" || !v.AppliesTo(workflowmodel.KindPR) || v.Deliverable != nil { + t.Fatalf("drafting dispatch = %+v %v", v, ok) + } + if len(p.Dispatch) != 2 { + t.Fatalf("dispatch targets %+v", p.Dispatch) + } +} diff --git a/src/pkg/workflowmodel/compile.go b/src/pkg/workflowmodel/compile.go index f01d6190c5..7aa211bccd 100644 --- a/src/pkg/workflowmodel/compile.go +++ b/src/pkg/workflowmodel/compile.go @@ -44,6 +44,10 @@ const ( CodeUnknownEvent = "unknown-event" CodeNoVersion = "no-version" CodeInferred = "inferred-element" + // CodeDuplicateDispatch refuses two profiles dispatched in one state; + // CodeDispatchReply warns that a dispatch reply is not a state reply. + CodeDuplicateDispatch = "duplicate-dispatch" + CodeDispatchReply = "dispatch-reply-undeclared" ) // ErrCompile wraps a compile refused by error diagnostics. @@ -84,6 +88,12 @@ type Profile struct { Replies map[string][]string `json:"replies,omitempty"` // Labels is the label set to reconcile. Labels LabelSet `json:"labels,omitzero"` + // Agents are the model's agent grants, as declared. + Agents []AgentGrant `json:"agents,omitempty"` + // Dispatch maps a state id to the profile the hive hands items in that + // state to (dispatch.go). Empty for hive-default and for a model with + // no agent grants. + Dispatch map[string]DispatchTarget `json:"dispatch,omitempty"` // Diagnostics are the warnings left after a successful compile. Diagnostics []Diagnostic `json:"diagnostics,omitempty"` // replyEffects maps state id → NormalizeReply(verb) → the transition @@ -189,6 +199,7 @@ func (c *compiler) run() { c.roles() c.events() c.derivation() + c.dispatch() c.inferred() } diff --git a/src/pkg/workflowmodel/dispatch.go b/src/pkg/workflowmodel/dispatch.go new file mode 100644 index 0000000000..8ffe525b67 --- /dev/null +++ b/src/pkg/workflowmodel/dispatch.go @@ -0,0 +1,265 @@ +package workflowmodel + +import ( + "strings" +) + +// Agent dispatch (hivecommons/hive#17620 follow-up, cncf/techdocs#395). +// +// A model's agent grants (spec.agents) name the profiles that may act in +// which states. The compiler resolves, for each grant, the states in which +// the hive hands an item to that profile and what starts each hand-off: +// +// - explicit: the grant's dispatch block (states, reply, instructions); +// - convention, when the grant has no dispatch block: the grant's FIRST +// state is its entry state. A profile that produces a pull request or a +// push is dispatched once on entering it (the TechDocs drafter on +// Accepted). A profile that produces neither (a verifier, a reviewer) +// is dispatched on the reply that releases the gate out of its entry +// state into a non-terminal state, when that state declares the reply +// (the TechDocs verifier on `/verify` in Drafting). +// +// The compiled Profile carries the result as Dispatch (state id → +// DispatchTarget). Which hive agent fills a profile is the hive's +// configuration (config.WorkflowConfig.Dispatch), not the model's: a model +// names roles, a hive names agents. The built-in hive-default model never +// dispatches; its grants describe the fleet that already runs it. + +// hiveDefaultModelName is the built-in model (hivedefault.Name), whose +// grants are descriptive only. +const hiveDefaultModelName = "hive-default" + +// DispatchTarget is one state in which the hive hands an item to a profile. +type DispatchTarget struct { + // Profile is the agent grant's profile name. + Profile string `json:"profile"` + // State is the model state id the target applies to. + State string `json:"state"` + // StateLabel is the state's display label. + StateLabel string `json:"stateLabel,omitempty"` + // Kinds are the item kinds the state applies to (empty: both). + Kinds []ItemKind `json:"kinds,omitempty"` + // Reply, when set, is the human reply that starts each pass; empty + // dispatches once on entering the state. + Reply string `json:"reply,omitempty"` + // Explicit is true when the grant declared a dispatch block; false when + // the convention resolved the target. + Explicit bool `json:"explicit,omitempty"` + // Tools and Produces are the grant's, for the prompt. + Tools []string `json:"tools,omitempty"` + Produces []string `json:"produces,omitempty"` + // Instructions is the state's guidance for the profile: the grant's + // dispatch instructions, the state's waiting reasons and its column + // hint, in that order. + Instructions []string `json:"instructions,omitempty"` + // Deliverable is the pull request the profile is expected to open, when + // it produces one and a later grant state is a pull-request state. + Deliverable *Deliverable `json:"deliverable,omitempty"` +} + +// Deliverable is the pull request a dispatched profile opens: the model +// state it should land in and the labels and draft flag that state's +// derivation rule requires. +type Deliverable struct { + State string `json:"state"` + Draft bool `json:"draft,omitempty"` + Labels []string `json:"labels,omitempty"` +} + +// AppliesTo reports whether the target's state applies to items of kind. +func (t DispatchTarget) AppliesTo(kind ItemKind) bool { + if len(t.Kinds) == 0 { + return true + } + for _, k := range t.Kinds { + if k == kind { + return true + } + } + return false +} + +// DispatchFor returns the dispatch target for state, if the model hands +// items in that state to a profile. +func (p *Profile) DispatchFor(state string) (DispatchTarget, bool) { + if p == nil || p.Dispatch == nil || state == "" { + return DispatchTarget{}, false + } + t, ok := p.Dispatch[state] + return t, ok +} + +// Dispatches reports whether the profile hands any state to an agent. +func (p *Profile) Dispatches() bool { return p != nil && len(p.Dispatch) > 0 } + +// producesChange reports whether a grant's outputs include a pull request +// or a push: such a profile is dispatched on entry by convention. +func producesChange(produces []string) bool { + for _, p := range produces { + switch strings.ToLower(strings.TrimSpace(p)) { + case "pull-request", "pr", "push": + return true + } + } + return false +} + +// dispatch resolves every grant's dispatch targets onto the profile. +func (c *compiler) dispatch() { + m := c.m + c.p.Agents = append([]AgentGrant(nil), m.Spec.Agents...) + if m.Metadata.Name == hiveDefaultModelName || len(m.Spec.Agents) == 0 { + return + } + gates := map[string]Gate{} + for _, g := range m.Spec.Gates { + gates[g.ID] = g + } + for _, a := range m.Spec.Agents { + if len(a.States) == 0 { + continue + } + grantStates := map[string]bool{} + for _, s := range a.States { + grantStates[s] = true + } + var states []string + reply, explicit, instr := "", a.Dispatch != nil, "" + if explicit { + for _, s := range a.Dispatch.States { + if !grantStates[s] { + c.errorf(CodeUnknownState, a.Profile, "agent %q dispatches in %q, which is not one of its states", a.Profile, s) + continue + } + states = append(states, s) + } + reply, instr = strings.TrimSpace(a.Dispatch.Reply), strings.TrimSpace(a.Dispatch.Instructions) + } else { + entry := a.States[0] + if _, ok := c.p.States[entry]; !ok { + continue // roles() already refused the unknown state + } + states = []string{entry} + if !producesChange(a.Produces) { + reply = c.exitGateReply(entry, gates) + } + } + for _, sid := range states { + st, ok := c.p.States[sid] + if !ok { + continue + } + if prev, dup := c.p.Dispatch[sid]; dup { + c.errorf(CodeDuplicateDispatch, sid, "state %q is dispatched to both %q and %q", sid, prev.Profile, a.Profile) + continue + } + if reply != "" && !stateDeclaresReply(st, reply) { + c.warnf(CodeDispatchReply, sid, "agent %q is dispatched on %q, which state %q does not declare as a reply", a.Profile, reply, sid) + } + t := DispatchTarget{ + Profile: a.Profile, + State: sid, + StateLabel: st.Label, + Kinds: append([]ItemKind(nil), st.Lifecycle.Kinds...), + Reply: reply, + Explicit: explicit, + Tools: append([]string(nil), a.Tools...), + Produces: append([]string(nil), a.Produces...), + } + if instr != "" { + t.Instructions = append(t.Instructions, instr) + } + t.Instructions = append(t.Instructions, st.Lifecycle.Waiting...) + if col := c.p.Column(c.p.ColumnOf[sid]); col != nil && col.Hint != "" { + t.Instructions = append(t.Instructions, col.Hint) + } + if producesChange(a.Produces) { + t.Deliverable = c.deliverable(a.States, sid) + } + if c.p.Dispatch == nil { + c.p.Dispatch = map[string]DispatchTarget{} + } + c.p.Dispatch[sid] = t + } + } +} + +// exitGateReply is the reply of the first human gate on a transition out +// of state into a non-terminal state, when state declares that reply; "" +// when there is none. It is what a reviewing profile waits for. +func (c *compiler) exitGateReply(state string, gates map[string]Gate) string { + st := c.p.States[state] + for _, t := range c.m.Spec.Transitions { + if t.From != state || t.GateRef == "" || c.p.Terminal[t.To] { + continue + } + g, ok := gates[t.GateRef] + if !ok || strings.TrimSpace(g.Reply) == "" { + continue + } + if stateDeclaresReply(st, g.Reply) { + return strings.TrimSpace(g.Reply) + } + } + return "" +} + +// stateDeclaresReply reports whether st offers reply (NormalizeReply-equal, +// a leading slash ignored). +func stateDeclaresReply(st *State, reply string) bool { + if st == nil { + return false + } + want := NormalizeReply(strings.TrimPrefix(strings.TrimSpace(reply), "/")) + for _, r := range st.Lifecycle.Replies { + if NormalizeReply(strings.TrimPrefix(strings.TrimSpace(r), "/")) == want { + return true + } + } + return false +} + +// deliverable is the first pull-request state among the grant's states +// after from, with the labels and draft flag its first derivation rule +// requires. Nil when the grant names no pull-request state. +func (c *compiler) deliverable(grantStates []string, from string) *Deliverable { + for _, sid := range grantStates { + if sid == from { + continue + } + st := c.p.States[sid] + if st == nil || !stateKind(st, KindPR) { + continue + } + d := &Deliverable{State: sid} + for _, r := range c.m.Spec.Derivation.Rules { + if r.State != sid || (r.Kind != KindPR && r.Kind != KindAny) { + continue + } + for _, pred := range r.When { + switch { + case pred.Fact == "draft" && pred.Op == OpTrue: + d.Draft = true + case pred.Fact == "labels" && pred.Op == OpHas && pred.Value != "" && !strings.ContainsAny(pred.Value, "*?["): + d.Labels = append(d.Labels, pred.Value) + } + } + break + } + return d + } + return nil +} + +// stateKind reports whether st applies to items of kind (no kinds: both). +func stateKind(st *State, kind ItemKind) bool { + if len(st.Lifecycle.Kinds) == 0 { + return true + } + for _, k := range st.Lifecycle.Kinds { + if k == kind { + return true + } + } + return false +} diff --git a/src/pkg/workflowmodel/dispatch_test.go b/src/pkg/workflowmodel/dispatch_test.go new file mode 100644 index 0000000000..8deec5a9cf --- /dev/null +++ b/src/pkg/workflowmodel/dispatch_test.go @@ -0,0 +1,143 @@ +package workflowmodel + +import ( + "reflect" + "testing" +) + +// The convention: a grant's first state is its entry state; a profile that +// produces neither a pull request nor a push and has no gated exit reply is +// still dispatched on entry. +func TestDispatchConvention(t *testing.T) { + p, _, err := Compile(techdocs(t)) + if err != nil { + t.Fatal(err) + } + if len(p.Agents) != 2 { + t.Fatalf("agents %+v", p.Agents) + } + a, ok := p.DispatchFor("analysing") + if !ok || a.Profile != "techdocs-analyst" || a.Reply != "" || a.Explicit || a.Deliverable != nil { + t.Fatalf("analysing dispatch = %+v %v", a, ok) + } + if !a.AppliesTo(KindIssue) || a.AppliesTo(KindPR) { + t.Fatalf("analysing kinds %v", a.Kinds) + } + w, ok := p.DispatchFor("drafting") + if !ok || w.Profile != "techdocs-writer" || w.Reply != "" { + t.Fatalf("drafting dispatch = %+v %v", w, ok) + } + if _, ok := p.DispatchFor("analysis-review"); ok { + t.Fatal("a human state must not dispatch") + } + if !p.Dispatches() { + t.Fatal("Dispatches() false") + } +} + +// A reviewing profile (no pull request) is dispatched on the reply that +// releases its entry state's gate into a non-terminal state. +func TestDispatchReviewerWaitsForGateReply(t *testing.T) { + m := techdocs(t) + m.Spec.Agents = []AgentGrant{{Profile: "checker", States: []string{"draft-review"}, Produces: []string{"comment"}}} + p, diags, err := Compile(m) + if err != nil { + t.Fatalf("%v %+v", err, diags) + } + d, ok := p.DispatchFor("draft-review") + if !ok || d.Reply != "approve" { + t.Fatalf("draft-review dispatch = %+v %v", d, ok) + } +} + +func TestDispatchExplicit(t *testing.T) { + m := techdocs(t) + m.Spec.Agents[1].Dispatch = &AgentDispatch{States: []string{"drafting"}, Reply: "approve", Instructions: "Open a draft PR."} + p, diags, err := Compile(m) + if err != nil { + t.Fatalf("%v %+v", err, diags) + } + d, ok := p.DispatchFor("drafting") + if !ok || !d.Explicit || d.Reply != "approve" || len(d.Instructions) == 0 || d.Instructions[0] != "Open a draft PR." { + t.Fatalf("drafting dispatch = %+v %v", d, ok) + } + found := false + for _, dg := range diags { + if dg.Code == CodeDispatchReply && dg.Subject == "drafting" { + found = true + } + } + if !found { + t.Fatalf("want %s warning for an undeclared reply, got %+v", CodeDispatchReply, diags) + } + + // An empty explicit block turns dispatch off for the grant. + m = techdocs(t) + m.Spec.Agents[1].Dispatch = &AgentDispatch{} + p, _, err = Compile(m) + if err != nil { + t.Fatal(err) + } + if _, ok := p.DispatchFor("drafting"); ok { + t.Fatal("empty dispatch block must not dispatch") + } +} + +func TestDispatchRefusals(t *testing.T) { + m := techdocs(t) + m.Spec.Agents[0].Dispatch = &AgentDispatch{States: []string{"drafting"}} + if _, diags, err := Compile(m); err == nil || !hasCode(diags, CodeUnknownState) { + t.Fatalf("dispatch outside the grant: err=%v diags=%+v", err, diags) + } + m = techdocs(t) + m.Spec.Agents[0].States = []string{"analysing", "drafting"} + m.Spec.Agents[0].Dispatch = &AgentDispatch{States: []string{"drafting"}} + if _, diags, err := Compile(m); err == nil || !hasCode(diags, CodeDuplicateDispatch) { + t.Fatalf("two profiles in one state: err=%v diags=%+v", err, diags) + } +} + +func TestDispatchDeliverable(t *testing.T) { + m := techdocs(t) + m.Spec.Agents = []AgentGrant{{Profile: "drafter", States: []string{"analysing", "drafting"}, Produces: []string{"pull-request"}}} + m.Spec.Derivation.Rules = append([]Rule{{ID: "d", Kind: KindPR, State: "drafting", When: []Predicate{ + {Fact: "draft", Op: OpTrue}, {Fact: "labels", Op: OpHas, Value: "docs"}, {Fact: "labels", Op: OpHas, Value: "phase/*"}, + }}}, m.Spec.Derivation.Rules...) + p, diags, err := Compile(m) + if err != nil { + t.Fatalf("%v %+v", err, diags) + } + d, ok := p.DispatchFor("analysing") + if !ok || d.Deliverable == nil { + t.Fatalf("dispatch %+v %v", d, ok) + } + want := &Deliverable{State: "drafting", Draft: true, Labels: []string{"docs"}} + if !reflect.DeepEqual(d.Deliverable, want) { + t.Fatalf("deliverable %+v want %+v", d.Deliverable, want) + } +} + +func TestDispatchNeverForHiveDefault(t *testing.T) { + m := techdocs(t) + m.Metadata.Name = hiveDefaultModelName + p, _, err := Compile(m) + if err != nil { + t.Fatal(err) + } + if p.Dispatches() { + t.Fatalf("hive-default dispatches %+v", p.Dispatch) + } + var nilProfile *Profile + if _, ok := nilProfile.DispatchFor("x"); ok || nilProfile.Dispatches() { + t.Fatal("nil profile dispatches") + } +} + +func hasCode(diags []Diagnostic, code string) bool { + for _, d := range diags { + if d.Code == code { + return true + } + } + return false +} diff --git a/src/pkg/workflowmodel/lifecycle.go b/src/pkg/workflowmodel/lifecycle.go index ef3c1db93d..ac57a6383a 100644 --- a/src/pkg/workflowmodel/lifecycle.go +++ b/src/pkg/workflowmodel/lifecycle.go @@ -258,6 +258,24 @@ type AgentGrant struct { Backend string `json:"backend,omitempty"` Tools []string `json:"tools,omitempty"` Produces []string `json:"produces,omitempty"` + // Dispatch says where and when the hive hands an item to this profile + // (dispatch.go). Nil applies the convention: the grant's first state, + // on entry, or on the state's exit-gate reply for a profile that + // produces no pull request. + Dispatch *AgentDispatch `json:"dispatch,omitempty"` +} + +// AgentDispatch is an explicit dispatch rule for one agent grant. +type AgentDispatch struct { + // States are the grant states in which the hive hands the item to the + // profile. Each must be one of the grant's states. Empty means none: + // the profile is never dispatched automatically. + States []string `json:"states,omitempty"` + // Reply is the human reply that starts each pass (the verifier runs on + // `/verify`); empty dispatches once on entering the state. + Reply string `json:"reply,omitempty"` + // Instructions are appended to the dispatch prompt verbatim. + Instructions string `json:"instructions,omitempty"` } // CheckKind is how a check is satisfied.