diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index a2ab73b6f..1648b8f9b 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -154,7 +154,7 @@ "url": "/dev/development/workflows/", "title": "Workflows", "section": "Development", - "body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n" + "body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n" }, { "url": "/dev/prds/01-project-management/", diff --git a/docs/development/workflows.md b/docs/development/workflows.md index 521105be1..e27a43a43 100644 --- a/docs/development/workflows.md +++ b/docs/development/workflows.md @@ -40,6 +40,17 @@ vocabulary it registers, so both must see the same step types. - Examples in `examples/workflows/` are parsed against the registered vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability. +## Enabling and disabling + +The `workflow-enablement` control-plane resource lists, per org, the workflows +that org has disabled; anything unlisted is enabled. Its readers are the +daemon's binding dispatch (a disabled workflow's binding is skipped like an +unarmed one), the dashboard's binding save (refused) and binding list +(`workflow_disabled`), and work requests. A new reader of "may this org run +this workflow" goes through `task.WorkflowEnablement.Enabled`, never a second +list. The dashboard acts in the default org until access resolves a caller's +own. + ## Starting a workflow from chat `task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index f5b5bd844..084d100d3 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -1408,6 +1408,7 @@ func (b *boot) buildDaemon() { KindWorkflows: b.kindWorkflows, LabelWorkflows: b.labelWorkflows, WorkflowDefinitions: b.workflowDefinitions, + WorkflowEnablement: b.controlPlane, Playbooks: b.playbooks, } if identities, ok := b.stateStore.(identity.Repository); ok { diff --git a/internal/app/archieui/degraded_routes_test.go b/internal/app/archieui/degraded_routes_test.go index 47fe0613d..d95d71cf7 100644 --- a/internal/app/archieui/degraded_routes_test.go +++ b/internal/app/archieui/degraded_routes_test.go @@ -87,6 +87,11 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) { name: "workflow registry", method: http.MethodGet, path: "/api/workflows", want: http.StatusOK, emptyJSON: `"definitions":null`, }, + { + name: "workflow enabled toggle", method: http.MethodPut, path: "/api/workflows/implement/enabled", + body: `{"enabled":false}`, + want: http.StatusServiceUnavailable, + }, { name: "dashboard work request", method: http.MethodPost, path: "/api/work-requests", body: `{"repository":"acme/widget","workflow":"implement","title":"do it"}`, diff --git a/internal/app/controlplane/definitions.go b/internal/app/controlplane/definitions.go index dfdc8dce1..5f8ff4833 100644 --- a/internal/app/controlplane/definitions.go +++ b/internal/app/controlplane/definitions.go @@ -8,7 +8,7 @@ import ( // Schemas are not declared here: each Definition names its document type, and // Definition.Descriptor derives the JSON Schema from it (internal/app/controlplane/schema.go). func builtinDefinitions(steps workflow.StepRegistry) []Definition { - definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()} + definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()} definitions = append(definitions, modelDefinitions()...) definitions = append(definitions, operationalDefinitions()...) return definitions diff --git a/internal/app/controlplane/workflow_enablement.go b/internal/app/controlplane/workflow_enablement.go new file mode 100644 index 000000000..cdedee6cb --- /dev/null +++ b/internal/app/controlplane/workflow_enablement.go @@ -0,0 +1,38 @@ +package controlplane + +import ( + "context" + "encoding/json" + + "github.com/samcharles93/archie-core/internal/config" + pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" +) + +const WorkflowEnablementKind = "workflow-enablement" + +func workflowEnablementDefinition() Definition { + return Definition{ + Kind: WorkflowEnablementKind, + Title: "Workflow enablement", + Document: task.WorkflowEnablement{}, + ApplyMode: "live", + Seed: func(config.Config) any { return task.WorkflowEnablement{Orgs: map[org.OrgID]task.OrgWorkflows{}} }, + Validate: func(input []byte) error { + return validateAs(input, func(enablement task.WorkflowEnablement) error { return enablement.Validate() }) + }, + } +} + +// WorkflowEnablement returns which workflows each org has disabled. +func (c *Client) WorkflowEnablement(ctx context.Context) (task.WorkflowEnablement, error) { + response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowEnablementKind}) + if err != nil { + return task.WorkflowEnablement{}, controlplanerpc.ClientError(err) + } + var enablement task.WorkflowEnablement + err = json.Unmarshal(response.Resource.ValueJson, &enablement) + return enablement, err +} diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index f6010bfd1..605d1492d 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -2371,7 +2371,9 @@ type Binding struct { // {"param": name} or {"value": constant} per input. InputsJson string `protobuf:"bytes,14,opt,name=inputs_json,json=inputsJson,proto3" json:"inputs_json,omitempty"` // repo_param names the mapped parameter holding "owner/name". - RepoParam string `protobuf:"bytes,15,opt,name=repo_param,json=repoParam,proto3" json:"repo_param,omitempty"` + RepoParam string `protobuf:"bytes,15,opt,name=repo_param,json=repoParam,proto3" json:"repo_param,omitempty"` + // org_id is the org that owns the binding; it is read-only here. + OrgId string `protobuf:"bytes,16,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2504,6 +2506,13 @@ func (x *Binding) GetRepoParam() string { return "" } +func (x *Binding) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + // Source mirrors internal/domain/source.Source. type Source struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -11854,7 +11863,7 @@ const file_state_v1_state_proto_rawDesc = "" + "matchCount\x12B\n" + "\x0flast_matched_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\rlastMatchedAt\"(\n" + "\x0eBindingMatcher\x12\x16\n" + - "\x06source\x18\x01 \x01(\tR\x06source\"\xd4\x03\n" + + "\x06source\x18\x01 \x01(\tR\x06source\"\xeb\x03\n" + "\aBinding\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x122\n" + @@ -11874,7 +11883,8 @@ const file_state_v1_state_proto_rawDesc = "" + "\vinputs_json\x18\x0e \x01(\tR\n" + "inputsJson\x12\x1d\n" + "\n" + - "repo_param\x18\x0f \x01(\tR\trepoParamJ\x04\b\n" + + "repo_param\x18\x0f \x01(\tR\trepoParam\x12\x15\n" + + "\x06org_id\x18\x10 \x01(\tR\x05orgIdJ\x04\b\n" + "\x10\vR\x06secret\"\xc4\x01\n" + "\x06Source\x12\x12\n" + "\x04path\x18\x01 \x01(\tR\x04path\x12\x18\n" + diff --git a/internal/daemon/binding_target.go b/internal/daemon/binding_target.go index a1b39a0b9..f6b0ef4b1 100644 --- a/internal/daemon/binding_target.go +++ b/internal/daemon/binding_target.go @@ -29,6 +29,15 @@ func (d *Daemon) activeWorkflows(ctx context.Context) (workflow.WorkflowDefiniti return collection, err } +// workflowEnablement returns which workflows each org has disabled; with no +// source wired every workflow is enabled. +func (d *Daemon) workflowEnablement(ctx context.Context) (workflowtask.WorkflowEnablement, error) { + if d.WorkflowEnablement == nil { + return workflowtask.WorkflowEnablement{}, nil + } + return d.WorkflowEnablement.WorkflowEnablement(ctx) +} + // resolveBindingTarget checks a matched binding against the workflow it // targets and resolves the task's repository and inputs. A non-empty reason // means the binding does not dispatch and the reason is recorded on it; ok diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 990d4f567..0d50bc01d 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -250,6 +250,12 @@ type Daemon struct { WorkflowDefinitions interface { WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) } + // WorkflowEnablement supplies which workflows each org has disabled. A + // binding targeting a workflow its org disabled does not dispatch. Nil + // means every workflow is enabled. + WorkflowEnablement interface { + WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) + } // ToolRegistry is the central tool registry, wired by the composition // root. MCP-discovered tools and built-in tools are registered here @@ -667,16 +673,27 @@ func (d *Daemon) dispatchBindings(ctx context.Context) { d.Log.Warn("binding dispatch: workflow definitions unavailable", "error", err) return } + enablement, err := d.workflowEnablement(ctx) + if err != nil { + d.Log.Warn("binding dispatch: workflow enablement unavailable", "error", err) + return + } for _, c := range captures { - armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source) - if err != nil { - d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err) - continue - } - for _, b := range armed { - if !b.Matcher.Matches(c.Source, c.Dispatchable()) { - continue - } + d.dispatchCapture(ctx, c, workflows, enablement) + } +} + +// dispatchCapture offers one capture to every armed binding on its source. A +// disabled workflow's binding is skipped like an unarmed one, so the capture +// waits rather than recording a failure every cycle. +func (d *Daemon) dispatchCapture(ctx context.Context, c storecontract.CapturedEvent, workflows workflow.WorkflowDefinitionCollection, enablement workflowtask.WorkflowEnablement) { + armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source) + if err != nil { + d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err) + return + } + for _, b := range armed { + if b.Matcher.Matches(c.Source, c.Dispatchable()) && enablement.Enabled(b.OrgID, b.Workflow) { d.dispatchOneBinding(ctx, b, c, workflows) } } diff --git a/internal/daemon/dispatch_bindings_test.go b/internal/daemon/dispatch_bindings_test.go index e4bd0fae7..cf9322a64 100644 --- a/internal/daemon/dispatch_bindings_test.go +++ b/internal/daemon/dispatch_bindings_test.go @@ -15,6 +15,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" @@ -422,3 +423,36 @@ func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) { t.Fatalf("binding_dispatches row missing: %v", err) } } + +type staticEnablement struct { + value workflowtask.WorkflowEnablement +} + +func (e staticEnablement) WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) { + return e.value, nil +} + +// A binding whose org disabled its workflow does not dispatch, and the capture +// waits: re-enabling the workflow dispatches it on the next cycle. +func TestDispatchBindingsSkipsWorkflowItsOrgDisabled(t *testing.T) { + s := openDispatchTestStore(t) + mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) + bindingID, _ := seedArmedBinding(t, s, "sentry", mappingID) + seedCapture(t, s, "sentry", true, `{"title":"hello"}`) + stored, err := s.EdaStore.GetBinding(t.Context(), bindingID) + if err != nil { + t.Fatalf("GetBinding: %v", err) + } + + d := newDispatchDaemon(t, s) + var enablement workflowtask.WorkflowEnablement + d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, false)} + d.dispatchBindings(t.Context()) + if tasks, _ := s.Tasks(t.Context(), 10); len(tasks) != 0 { + t.Fatalf("Tasks len = %d, want 0 while the workflow is disabled", len(tasks)) + } + + d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, true)} + d.dispatchBindings(t.Context()) + assertDispatchRecorded(t, s, bindingID) +} diff --git a/internal/domain/binding/binding.go b/internal/domain/binding/binding.go index 87c77e04b..1bc902614 100644 --- a/internal/domain/binding/binding.go +++ b/internal/domain/binding/binding.go @@ -8,6 +8,8 @@ import ( "fmt" "strings" "time" + + "github.com/samcharles93/archie-core/internal/domain/org" ) // Status is the binding lifecycle state. Mirrors telegram's @@ -65,11 +67,14 @@ type Binding struct { // Inputs assigns the workflow's declared inputs, each from a mapped // parameter or a constant; CheckWorkflow checks them when the binding is // saved. - Inputs map[string]InputSource `json:"inputs,omitempty"` - Version int `json:"version"` - Status Status `json:"status"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + Inputs map[string]InputSource `json:"inputs,omitempty"` + // OrgID is the org that owns the binding; the store sets it and a + // binding may target only a workflow that org has enabled. + OrgID org.OrgID `json:"org_id"` + Version int `json:"version"` + Status Status `json:"status"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // Validate checks a binding is well-formed before it is persisted: a diff --git a/internal/domain/workflow/task/enablement.go b/internal/domain/workflow/task/enablement.go new file mode 100644 index 000000000..eb0c314fd --- /dev/null +++ b/internal/domain/workflow/task/enablement.go @@ -0,0 +1,60 @@ +package task + +import ( + "fmt" + "maps" + "slices" + "strings" + + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// WorkflowEnablement is the workflow-enablement resource value: which +// workflows each org has turned off. A workflow is enabled for an org unless +// that org lists it, so a newly shipped or added workflow is enabled +// everywhere until an org disables it. +type WorkflowEnablement struct { + Orgs map[org.OrgID]OrgWorkflows `json:"orgs"` +} + +// OrgWorkflows is one org's workflow state. +type OrgWorkflows struct { + Disabled []string `json:"disabled"` +} + +// Enabled reports whether owner may run workflow. +func (e WorkflowEnablement) Enabled(owner org.OrgID, workflow string) bool { + return !slices.Contains(e.Orgs[owner].Disabled, workflow) +} + +// SetEnabled returns e with workflow enabled or disabled for owner. +func (e WorkflowEnablement) SetEnabled(owner org.OrgID, workflow string, enabled bool) WorkflowEnablement { + orgs := make(map[org.OrgID]OrgWorkflows, len(e.Orgs)+1) + maps.Copy(orgs, e.Orgs) + disabled := slices.DeleteFunc(slices.Clone(orgs[owner].Disabled), func(id string) bool { return id == workflow }) + if !enabled { + disabled = append(disabled, workflow) + } + orgs[owner] = OrgWorkflows{Disabled: disabled} + return WorkflowEnablement{Orgs: orgs} +} + +// Validate rejects blank org or workflow IDs and a workflow listed twice. +func (e WorkflowEnablement) Validate() error { + for owner, state := range e.Orgs { + if strings.TrimSpace(string(owner)) == "" { + return fmt.Errorf("workflow enablement: org ID is required") + } + seen := make(map[string]bool, len(state.Disabled)) + for _, workflow := range state.Disabled { + if strings.TrimSpace(workflow) == "" { + return fmt.Errorf("workflow enablement: org %q: workflow ID is required", owner) + } + if seen[workflow] { + return fmt.Errorf("workflow enablement: org %q lists %q twice", owner, workflow) + } + seen[workflow] = true + } + } + return nil +} diff --git a/internal/domain/workflow/task/enablement_test.go b/internal/domain/workflow/task/enablement_test.go new file mode 100644 index 000000000..1f5c90631 --- /dev/null +++ b/internal/domain/workflow/task/enablement_test.go @@ -0,0 +1,58 @@ +package task + +import ( + "testing" + + "github.com/samcharles93/archie-core/internal/domain/org" +) + +func TestWorkflowEnablementEnabled(t *testing.T) { + enablement := WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{ + "acme": {Disabled: []string{"triage"}}, + }} + cases := []struct { + org org.OrgID + workflow string + want bool + }{ + {"acme", "triage", false}, + {"acme", "implement", true}, + {"other", "triage", true}, + } + for _, c := range cases { + if got := enablement.Enabled(c.org, c.workflow); got != c.want { + t.Errorf("Enabled(%q, %q) = %v, want %v", c.org, c.workflow, got, c.want) + } + } +} + +func TestWorkflowEnablementSetEnabledRoundTrips(t *testing.T) { + var enablement WorkflowEnablement + enablement = enablement.SetEnabled("acme", "triage", false) + enablement = enablement.SetEnabled("acme", "triage", false) + if enablement.Enabled("acme", "triage") || len(enablement.Orgs["acme"].Disabled) != 1 { + t.Fatalf("disable twice: %+v", enablement) + } + enablement = enablement.SetEnabled("acme", "triage", true) + if !enablement.Enabled("acme", "triage") { + t.Fatalf("re-enable: %+v", enablement) + } +} + +func TestWorkflowEnablementValidate(t *testing.T) { + cases := map[string]struct { + enablement WorkflowEnablement + ok bool + }{ + "empty": {WorkflowEnablement{}, true}, + "valid": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{"triage"}}}}, true}, + "blank org": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{" ": {Disabled: []string{"triage"}}}}, false}, + "blank workflow": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{""}}}}, false}, + "duplicate entry": {WorkflowEnablement{Orgs: map[org.OrgID]OrgWorkflows{"acme": {Disabled: []string{"triage", "triage"}}}}, false}, + } + for name, c := range cases { + if err := c.enablement.Validate(); (err == nil) != c.ok { + t.Errorf("%s: Validate() = %v, want ok=%v", name, err, c.ok) + } + } +} diff --git a/internal/infrastructure/postgres/edastore.go b/internal/infrastructure/postgres/edastore.go index ca4c8dccc..686cbb5f6 100644 --- a/internal/infrastructure/postgres/edastore.go +++ b/internal/infrastructure/postgres/edastore.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher" @@ -317,6 +318,7 @@ func bindingValue(r postgresdb.GetBindingRow) (binding.Binding, error) { Repo: r.Repo, RepoParam: r.RepoParam, Inputs: inputs, + OrgID: org.OrgID(r.OrgID), Version: int(r.Version), Status: binding.Status(r.Status), CreatedAt: r.CreatedAt, diff --git a/internal/infrastructure/postgres/postgresdb/edastore.sql.go b/internal/infrastructure/postgres/postgresdb/edastore.sql.go index 7d5478748..af1df8abe 100644 --- a/internal/infrastructure/postgres/postgresdb/edastore.sql.go +++ b/internal/infrastructure/postgres/postgresdb/edastore.sql.go @@ -11,7 +11,7 @@ import ( ) const armedBindingsForSource = `-- name: ArmedBindingsForSource :many -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC ` @@ -30,6 +30,7 @@ type ArmedBindingsForSourceRow struct { Filter string Inputs string RepoParam string + OrgID string } func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) { @@ -56,6 +57,7 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([] &i.Filter, &i.Inputs, &i.RepoParam, + &i.OrgID, ); err != nil { return nil, err } @@ -177,7 +179,7 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve } const getBinding = `-- name: GetBinding :one -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings WHERE id = $1 ` @@ -196,6 +198,7 @@ type GetBindingRow struct { Filter string Inputs string RepoParam string + OrgID string } func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) { @@ -216,6 +219,7 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, err &i.Filter, &i.Inputs, &i.RepoParam, + &i.OrgID, ) return i, err } @@ -524,7 +528,7 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams) } const listBindings = `-- name: ListBindings :many -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings ORDER BY created_at DESC ` @@ -543,6 +547,7 @@ type ListBindingsRow struct { Filter string Inputs string RepoParam string + OrgID string } func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) { @@ -569,6 +574,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) { &i.Filter, &i.Inputs, &i.RepoParam, + &i.OrgID, ); err != nil { return nil, err } diff --git a/internal/infrastructure/postgres/queries/edastore.sql b/internal/infrastructure/postgres/queries/edastore.sql index 77063304c..810149d4d 100644 --- a/internal/infrastructure/postgres/queries/edastore.sql +++ b/internal/infrastructure/postgres/queries/edastore.sql @@ -67,15 +67,15 @@ INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10, $11); -- name: GetBinding :one -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings WHERE id = $1; -- name: ListBindings :many -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings ORDER BY created_at DESC; -- name: ArmedBindingsForSource :many -SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param +SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter, inputs, repo_param, org_id FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC; -- name: UpdateBinding :execrows diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index b14beaf99..0cdc96767 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -246,7 +246,7 @@ func bindingProto(b binding.Binding) *pb.Binding { return &pb.Binding{ Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source}, MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo, - RepoParam: b.RepoParam, InputsJson: bindingInputsJSON(b.Inputs), + RepoParam: b.RepoParam, InputsJson: bindingInputsJSON(b.Inputs), OrgId: string(b.OrgID), Version: int64(b.Version), Status: string(b.Status), CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt), } @@ -263,7 +263,7 @@ func bindingValue(b *pb.Binding) binding.Binding { return binding.Binding{ ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source}, MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo, - RepoParam: b.RepoParam, Inputs: bindingInputsValue(b.InputsJson), + RepoParam: b.RepoParam, Inputs: bindingInputsValue(b.InputsJson), OrgID: org.OrgID(b.OrgId), Version: int(b.Version), Status: binding.Status(b.Status), CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt), } diff --git a/internal/webui/api_binding.go b/internal/webui/api_binding.go index 6aa10c672..cef38f69c 100644 --- a/internal/webui/api_binding.go +++ b/internal/webui/api_binding.go @@ -1,11 +1,13 @@ package webui import ( + "context" "encoding/json" "errors" "net/http" "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) @@ -35,6 +37,9 @@ type bindingRequest struct { type bindingView struct { binding.Binding Unsigned bool `json:"unsigned"` + // WorkflowDisabled marks a binding whose org has disabled the workflow it + // targets; it does not dispatch until the workflow is enabled again. + WorkflowDisabled bool `json:"workflow_disabled"` } func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) { @@ -54,9 +59,15 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) { http.Error(w, "list bindings failed", http.StatusInternalServerError) return } + enablement, _, err := s.workflowEnablement(r.Context()) + if err != nil { + s.Log.Error("workflow enablement", "err", err) + http.Error(w, "list bindings failed", http.StatusInternalServerError) + return + } views := make([]bindingView, 0, len(bindings)) for _, b := range bindings { - views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source]}) + views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow)}) } writeJSON(w, map[string]any{"bindings": views}) } @@ -248,6 +259,15 @@ func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id strin http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest) return binding.Binding{}, false } + enabled, err := s.bindingWorkflowEnabled(r.Context(), id, req.Workflow) + if err != nil { + http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable) + return binding.Binding{}, false + } + if !enabled { + http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict) + return binding.Binding{}, false + } iface, err := task.ParseWorkflowInterface(entry.YAML) if err != nil { http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest) @@ -277,3 +297,20 @@ func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id strin } return b, true } + +// bindingWorkflowEnabled reports whether the org owning binding id (the +// default org for a binding not yet created) has workflow enabled. +func (s *Server) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) { + owner := org.DefaultOrgID + if id != "" { + existing, err := s.Bindings.GetBinding(ctx, id) + if err != nil { + return false, err + } + if existing != nil { + owner = existing.OrgID + } + } + enablement, _, err := s.workflowEnablement(ctx) + return enablement.Enabled(owner, workflow), err +} diff --git a/internal/webui/api_control_plane_test.go b/internal/webui/api_control_plane_test.go index 5573d51a4..6de1d804b 100644 --- a/internal/webui/api_control_plane_test.go +++ b/internal/webui/api_control_plane_test.go @@ -28,13 +28,19 @@ type controlPlaneClientStub struct { entries []*controlpb.AuditEntry watch grpc.ServerStreamingClient[controlpb.WatchResponse] err error + // resources, when set, answers Query per kind and keeps what Command + // writes, falling back to query for a kind it does not hold. + resources map[string]*controlpb.Resource } func (f *controlPlaneClientStub) Catalog(context.Context, *controlpb.CatalogRequest, ...grpc.CallOption) (*controlpb.CatalogResponse, error) { return &controlpb.CatalogResponse{}, f.err } -func (f *controlPlaneClientStub) Query(context.Context, *controlpb.QueryRequest, ...grpc.CallOption) (*controlpb.QueryResponse, error) { +func (f *controlPlaneClientStub) Query(_ context.Context, request *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) { + if resource, ok := f.resources[request.Kind]; ok { + return &controlpb.QueryResponse{Resource: resource}, f.err + } return &controlpb.QueryResponse{Resource: f.query}, f.err } @@ -53,7 +59,11 @@ func (f *controlPlaneClientStub) Command(_ context.Context, request *controlpb.C if f.err != nil { return nil, f.err } - return &controlpb.CommandResponse{Resource: &controlpb.Resource{Kind: request.Kind, Version: 2, ValueJson: request.ValueJson}}, nil + resource := &controlpb.Resource{Kind: request.Kind, Version: request.ExpectedVersion + 1, ValueJson: request.ValueJson} + if f.resources != nil { + f.resources[request.Kind] = resource + } + return &controlpb.CommandResponse{Resource: resource}, nil } func (f *controlPlaneClientStub) Watch(context.Context, *controlpb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[controlpb.WatchResponse], error) { diff --git a/internal/webui/api_workflow_enablement.go b/internal/webui/api_workflow_enablement.go new file mode 100644 index 000000000..dab001e98 --- /dev/null +++ b/internal/webui/api_workflow_enablement.go @@ -0,0 +1,90 @@ +package webui + +import ( + "context" + "encoding/json" + "errors" + "net/http" + + controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" +) + +const workflowEnablementKind = "workflow-enablement" + +// workflowEnablement returns which workflows each org has disabled, and the +// resource version a replacement must name. +func (s *Server) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) { + if s.ControlPlane == nil { + return task.WorkflowEnablement{}, 0, nil + } + response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind}) + if err != nil { + return task.WorkflowEnablement{}, 0, err + } + if response.Resource == nil { + return task.WorkflowEnablement{}, 0, errors.New("workflow enablement missing") + } + var enablement task.WorkflowEnablement + if err := json.Unmarshal(response.Resource.ValueJson, &enablement); err != nil { + return task.WorkflowEnablement{}, 0, err + } + return enablement, response.Resource.Version, nil +} + +type workflowEnabledRequest struct { + Enabled bool `json:"enabled"` +} + +// handleWorkflowEnabled enables or disables a workflow for the dashboard's +// org. Every dashboard caller acts in the default org until access resolves a +// caller's own. +func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { + if !s.authorizeTaskMutation(w, r) { + return + } + if s.ControlPlane == nil { + http.Error(w, "control plane unavailable", http.StatusServiceUnavailable) + return + } + var request workflowEnabledRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + id := r.PathValue("id") + found, err := s.hasWorkflowDefinition(r.Context(), id) + if err != nil { + http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable) + return + } + if !found { + http.Error(w, "workflow not found", http.StatusNotFound) + return + } + enablement, version, err := s.workflowEnablement(r.Context()) + if err != nil { + http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable) + return + } + value, err := json.Marshal(enablement.SetEnabled(org.DefaultOrgID, id, request.Enabled)) + if err != nil { + http.Error(w, "encode workflow enablement", http.StatusInternalServerError) + return + } + audit, err := webAudit() + if err != nil { + http.Error(w, "cannot create request ID", http.StatusInternalServerError) + return + } + if _, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{ + Kind: workflowEnablementKind, Command: "replace", ValueJson: value, + ExpectedVersion: version, Actor: string(audit.ActorID), + Source: audit.Source, RequestId: audit.RequestID, + }); err != nil { + writeControlPlaneError(w, err) + return + } + writeJSON(w, map[string]any{"id": id, "enabled": request.Enabled}) +} diff --git a/internal/webui/api_workflow_enablement_test.go b/internal/webui/api_workflow_enablement_test.go new file mode 100644 index 000000000..adf0166c5 --- /dev/null +++ b/internal/webui/api_workflow_enablement_test.go @@ -0,0 +1,67 @@ +package webui + +import ( + "encoding/json" + "net/http" + "testing" + + controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" +) + +// Disabling a workflow flags the bindings that target it and refuses new +// ones; enabling it again lifts both. +func TestWorkflowDisableFlagsAndRefusesBindings(t *testing.T) { + srv := bindingTestServer(t) + stub, ok := srv.ControlPlane.(*controlPlaneClientStub) + if !ok { + t.Fatal("binding test server has no control-plane stub") + } + stub.resources = map[string]*controlpb.Resource{ + workflowEnablementKind: {Kind: workflowEnablementKind, Version: 1, ValueJson: []byte(`{"orgs":{}}`)}, + } + mappingID := seedMapping(t, srv, "m") + if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID)); w.Code != http.StatusCreated { + t.Fatalf("create status = %d; body = %s", w.Code, w.Body) + } + + setEnabled := func(enabled bool) { + t.Helper() + if w := doJSON(t, srv, http.MethodPut, "/api/workflows/implement/enabled", map[string]any{"enabled": enabled}); w.Code != http.StatusOK { + t.Fatalf("set enabled=%v status = %d; body = %s", enabled, w.Code, w.Body) + } + } + flagged := func() bool { + t.Helper() + w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil) + var body struct { + Bindings []bindingView `json:"bindings"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 1 { + t.Fatalf("list bindings: %v; body = %s", err, w.Body) + } + return body.Bindings[0].WorkflowDisabled + } + + setEnabled(false) + if !flagged() { + t.Fatal("binding targeting a disabled workflow is not flagged") + } + if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusConflict { + t.Fatalf("create against disabled workflow status = %d, want %d", w.Code, http.StatusConflict) + } + + setEnabled(true) + if flagged() { + t.Fatal("binding still flagged after the workflow was enabled") + } + if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusCreated { + t.Fatalf("create after enabling status = %d; body = %s", w.Code, w.Body) + } +} + +func TestWorkflowEnabledRefusesUnknownWorkflow(t *testing.T) { + srv := bindingTestServer(t) + if w := doJSON(t, srv, http.MethodPut, "/api/workflows/missing/enabled", map[string]any{"enabled": false}); w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound) + } +} diff --git a/internal/webui/api_workflows.go b/internal/webui/api_workflows.go index 48c0089df..605b14647 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/api_workflows.go @@ -10,6 +10,7 @@ import ( controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" ) @@ -106,7 +107,19 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"ok": true, "task_id": taskID}) } +// hasWorkflow reports whether workflow id is defined and enabled for the +// default org, the org every dashboard caller acts in until access resolves +// a caller's own. func (s *Server) hasWorkflow(ctx context.Context, id string) (bool, error) { + found, err := s.hasWorkflowDefinition(ctx, id) + if err != nil || !found { + return false, err + } + enablement, _, err := s.workflowEnablement(ctx) + return enablement.Enabled(org.DefaultOrgID, id), err +} + +func (s *Server) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) { _, found, err := s.workflowEntry(ctx, id) return found, err } @@ -147,9 +160,13 @@ func (s *Server) workflowDefinitions(ctx context.Context) ([]task.Definition, er if err != nil { return nil, err } + enablement, _, err := s.workflowEnablement(ctx) + if err != nil { + return nil, err + } definitions := make([]task.Definition, 0, len(collection.Definitions)) for _, entry := range collection.Definitions { - definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: true, Repository: task.RepositoryRequired} + definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.DefaultOrgID, entry.ID), Repository: task.RepositoryRequired} if iface, err := task.ParseWorkflowInterface(entry.YAML); err == nil { definition.Inputs, definition.Repository = iface.Inputs, iface.RepositoryMode() } diff --git a/internal/webui/server.go b/internal/webui/server.go index 483a16fd3..41bb0fef9 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -247,6 +247,7 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/summary", s.handleSummary) mux.HandleFunc("GET /api/setup", s.handleSetup) mux.HandleFunc("GET /api/workflows", s.handleWorkflows) + mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled) mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest) mux.HandleFunc("GET /api/skills", s.handleSkills) mux.HandleFunc("GET /api/curators", s.handleCurators) diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index f6f7749a2..e1ac529f6 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -455,6 +455,8 @@ message Binding { string inputs_json = 14; // repo_param names the mapped parameter holding "owner/name". string repo_param = 15; + // org_id is the org that owns the binding; it is read-only here. + string org_id = 16; } // Source mirrors internal/domain/source.Source. diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index d7e5b1bca..70124f40c 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -2,7 +2,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en `&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,` `)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t
{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t0&&r0&&ne.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?vf+r:void 0})(),Sf=e=>{let{theme:t,classGroups:n}=e;return Cf(n,t)},Cf=(e,t)=>{let n=hf();for(let r in e){let i=e[r];wf(i,n,r,t)}return n},wf=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){Ef(e,t,n);return}if(typeof e==`function`){Df(e,t,n,r);return}Of(e,t,n,r)},Ef=(e,t,n)=>{let r=e===``?t:kf(t,e);r.classGroupId=n},Df=(e,t,n,r)=>{if(Af(e)){wf(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(mf(n,e))},Of=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(gf),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,jf=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Mf=`!`,Nf=`:`,Pf=[],Ff=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),If=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;s{{ selected }}