feat(workflow): retries, parallel branches, review steps; every shipped workflow is YAML and the per-workflow step types are gone

This commit is contained in:
sam committed 2026-10-05 00:10:04 +11:00
1 parent ef538f0c6c
commit 9bd95c9238
12 files changed
+545 -341

No files matched your search

+15 -167
View File
@@ -2,7 +2,6 @@ package workflow
import (
"bytes"
"context"
"crypto/sha256"
"embed"
"encoding/hex"
@@ -10,8 +9,6 @@ import (
"fmt"
"io/fs"
"path"
"slices"
"sort"
"strings"
"gopkg.in/yaml.v3"
@@ -44,13 +41,25 @@ func NeedsRepository(stepType string) bool { return !repoFreeStepTypes[stepType]
type StepRecord struct {
// ID names the step so later steps can reference its result.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
Type string `yaml:"type" json:"type"`
Type string `yaml:"type,omitempty" json:"type,omitempty"`
Settings yaml.Node `yaml:"settings,omitempty" json:"-"`
// When skips the step unless the condition holds: a reference that must
// be truthy, negated with !, or compared with == or != to a literal.
When string `yaml:"when,omitempty" json:"when,omitempty"`
// OnFailure is "park" (the default) or "continue".
OnFailure string `yaml:"on_failure,omitempty" json:"on_failure,omitempty"`
// Retry runs a failed step again before on_failure applies.
Retry *RetryPolicy `yaml:"retry,omitempty" json:"retry,omitempty"`
// Parallel makes this step a set of named branches that run at the same
// time instead of a typed step. Each branch is a list of steps.
Parallel map[string][]StepRecord `yaml:"parallel,omitempty" json:"parallel,omitempty"`
}
// RetryPolicy is how often a failed step runs again, and how long it waits
// between attempts.
type RetryPolicy struct {
Attempts int `yaml:"attempts" json:"attempts"`
Backoff string `yaml:"backoff,omitempty" json:"backoff,omitempty"`
}
const onFailureContinue = "continue"
@@ -80,92 +89,13 @@ func ParseDefinition(src string, registry StepRegistry) (YAMLDefinition, error)
mode := definition.RepositoryMode()
earlier := map[string]bool{}
for i, step := range definition.Steps {
if err := checkStep(step, mode, earlier, registry); err != nil {
if err := checkStep(step, mode, earlier, registry, false); err != nil {
return YAMLDefinition{}, fmt.Errorf("workflow %q step %d: %w", definition.ID, i+1, err)
}
if step.ID != "" {
earlier[step.ID] = true
}
}
return definition, nil
}
// checkStep validates one step against the vocabulary and the steps before it.
func checkStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry) error {
if err := checkStepID(step.ID, earlier); err != nil {
return err
}
if step.OnFailure != "" && step.OnFailure != "park" && step.OnFailure != onFailureContinue {
return fmt.Errorf("on_failure is park or continue, not %q", step.OnFailure)
}
factory, ok := registry[step.Type]
if !ok {
return fmt.Errorf("unknown type %q", step.Type)
}
if mode != task.RepositoryRequired && NeedsRepository(step.Type) {
return fmt.Errorf("%q needs a repository, but the workflow's repository is %s", step.Type, mode)
}
if err := checkReferences(step.Settings, earlier); err != nil {
return err
}
if step.When != "" {
c, err := parseCondition(step.When)
if err != nil {
return err
}
if err := checkReference(c.path, earlier); err != nil {
return fmt.Errorf("when: %w", err)
}
}
if _, err := factory(step.Settings); err != nil {
return fmt.Errorf("%q settings: %w", step.Type, err)
}
return nil
}
// Compile resolves a validated YAML definition to executable stages.
func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error) {
stages := make([]Stage, 0, len(definition.Steps))
for _, step := range definition.Steps {
factory, ok := registry[step.Type]
if !ok {
return Workflow{}, fmt.Errorf("unknown workflow step type %q", step.Type)
}
stage, err := factory(step.Settings)
if err != nil {
return Workflow{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
}
stages = append(stages, compiledStep(step, stage.Name, factory))
}
return Workflow{Name: definition.ID, Stages: stages, Interface: definition.WorkflowInterface}, nil
}
// compiledStep builds the step's stage at run time from its settings with
// every reference resolved, and records what it leaves for later steps.
func compiledStep(step StepRecord, name string, factory StepFactory) Stage {
// ParseDefinition has already refused a condition that does not parse.
when, _ := parseCondition(step.When)
return Stage{Name: name, ContinueOnFailure: step.OnFailure == onFailureContinue, Run: func(ctx context.Context, tc *TaskContext) error {
tc.stepResult = StepResult{}
if step.When != "" && !when.holds(tc) {
tc.Log.Info("step skipped", "when", step.When)
return nil
}
stage, err := factory(renderSettings(step.Settings, tc))
if err != nil {
return fmt.Errorf("step %q settings: %w", step.Type, err)
}
err = stage.Run(ctx, tc)
if step.ID != "" {
if tc.stepResults == nil {
tc.stepResults = map[string]StepResult{}
}
tc.stepResults[step.ID] = tc.stepResult
}
return err
}}
}
// ParseAndCompile validates and compiles one definition in a single operation.
func ParseAndCompile(src string, registry StepRegistry) (Workflow, error) {
definition, err := ParseDefinition(src, registry)
@@ -242,72 +172,9 @@ func DecodeDefinitionCollection(value []byte, registry StepRegistry) (WorkflowDe
return collection, nil
}
func noSettingsFactory(stage Stage) StepFactory {
return func(settings yaml.Node) (Stage, error) {
if settings.Kind != 0 {
var value map[string]any
if err := settings.Decode(&value); err != nil {
return Stage{}, err
}
if len(value) != 0 {
return Stage{}, fmt.Errorf("step type accepts no settings")
}
}
return stage, nil
}
}
// retiredSteps are step types no shipped workflow uses that still resolve, as
// inert stages, so stored definitions naming them keep parsing.
var retiredSteps = map[string]Stage{
// The remediate workflow's in-container resume stage moved to daemon
// preparation; see retiredResumeStep.
"remediate.resume": retiredResumeStep(),
}
// BuiltinStepRegistry exposes every shipped stage as a typed, non-interpreted step.
func BuiltinStepRegistry() StepRegistry {
registry := StepRegistry{}
for id, wf := range legacyBuiltinWorkflows() {
for _, stage := range wf.Stages {
registry[id+"."+stage.Name] = noSettingsFactory(stage)
}
}
for name, stage := range retiredSteps {
registry[name] = noSettingsFactory(stage)
}
return registry
}
// ShippedDefinitions returns the restorable factory definitions.
func ShippedDefinitions() WorkflowDefinitionCollection {
workflows := legacyBuiltinWorkflows()
ids := make([]string, 0, len(workflows))
for id := range workflows {
ids = append(ids, id)
}
sort.Strings(ids)
collection := WorkflowDefinitionCollection{Definitions: shippedYAML()}
for _, id := range ids {
wf := workflows[id]
var builder strings.Builder
fmt.Fprintf(&builder, "id: %s\nsteps:\n", id)
for _, stage := range wf.Stages {
fmt.Fprintf(&builder, " - type: %s.%s\n", id, stage.Name)
}
// Only pr-review declares inputs today; every other builtin's
// generated YAML stays byte-identical to before this field existed.
if len(wf.Interface.Inputs) > 0 {
builder.WriteString("inputs:\n")
for _, name := range sortedInputNames(wf.Interface.Inputs) {
spec := wf.Interface.Inputs[name]
fmt.Fprintf(&builder, " %s:\n type: %s\n required: %t\n", name, spec.Type, spec.Required)
}
}
collection.Definitions = append(collection.Definitions, WorkflowDefinitionEntry{ID: id, YAML: builder.String()})
}
slices.SortFunc(collection.Definitions, func(a, b WorkflowDefinitionEntry) int { return strings.Compare(a.ID, b.ID) })
return collection
return WorkflowDefinitionCollection{Definitions: shippedYAML()}
}
//go:embed shipped/*.yaml
@@ -327,22 +194,3 @@ func shippedYAML() []WorkflowDefinitionEntry {
}
return entries
}
// sortedInputNames returns a Workflow.Interface's declared input names in a
// deterministic order, so the generated YAML (and its digest) never depends
// on map iteration order.
func sortedInputNames(inputs map[string]task.InputSpec) []string {
names := make([]string, 0, len(inputs))
for name := range inputs {
names = append(names, name)
}
sort.Strings(names)
return names
}
func legacyBuiltinWorkflows() Registry {
return Registry{
"remediate": Remediate(),
"pr-review": PRReview(),
}
}
@@ -120,23 +120,6 @@ func skipPhase(tc *TaskContext, phase string) {
// never has more than three lenses to begin with.
const prReviewConcurrency = 8
// PRReview is the pull request reviewer, a fixed pipeline of stages. The
// precision gate and operator approval are optional, each behind its own
// config flag.
func PRReview() Workflow {
return Workflow{
Name: "pr-review",
// pr_number is required so a binding or chat task must name a pull request.
Interface: task.WorkflowInterface{
Inputs: map[string]task.InputSpec{
"pr_number": {Type: "number", Required: true},
"depth": {Type: "string"},
},
},
Stages: prReviewStandaloneStages(),
}
}
// prReviewDecisionStages are the review stages without the operator gate, so
// the implement workflow can run them before opening its PR.
func prReviewDecisionStages() []Stage {
-116
View File
@@ -6,8 +6,6 @@ import (
"errors"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
)
// ErrNoReviewPayload is returned when a remediate run starts on a task that
@@ -110,13 +108,6 @@ func orUnknown(s string) string {
// other clipped park reasons in this package.
const remediationRoundCapBytes = 2000
// retiredResumeStep is an inert stage kept so stored definitions that name it
// still parse. The daemon now positions the worktree before the container
// starts.
func retiredResumeStep() Stage {
return Stage{Name: "resume", Run: func(context.Context, *TaskContext) error { return nil }}
}
// StageRemediationRoundCap parks the task with a comment once
// Task.RemediationRounds reaches the cap; otherwise it counts the round.
func StageRemediationRoundCap() Stage {
@@ -145,45 +136,6 @@ func postRemediationComment(ctx context.Context, tc *TaskContext, body string) {
}
}
// remediateMission builds the builder agent's mission from the task's
// decoded review unit, stashing it on tc.reviewUnit so later stages
// (commit-push, reply) don't re-decode the payload. StageCheckReviewPayload
// already guarantees the payload decodes before this stage runs.
func remediateMission(tc *TaskContext) string {
unit, _ := DecodeReviewUnit(tc.Task.ReviewPayload)
tc.reviewUnit = unit
return fmt.Sprintf(
"Address the review comments below on pull request #%d for %s with the smallest change that "+
"satisfies them, then run the gate.\n\n%s\n\n"+
"Do not run git -- the orchestrator commits and pushes for you. When done, call finish with "+
"status \"passed\" and a summary written for the human who will read your reply: what changed and "+
"why. If nothing here actually requires a code change, call finish with status \"passed\" and say "+
"so in the summary.",
tc.Task.PRNumber, tc.Repo.FullName(), renderReviewUnitMission(unit),
)
}
// remediateBuildStage runs the builder agent against the task's review
// unit. StageCheckReviewPayload runs first, so a decode failure parks the
// run before the builder ever sees an empty mission.
func remediateBuildStage() Stage {
return AgentStage{
Name: "remediate-build",
Role: "builder",
Gate: func(tc *TaskContext) agentrun.Gate {
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
},
Mission: remediateMission,
OnResult: func(tc *TaskContext, res agentrun.Result) error {
tc.BuildSummary = res.Summary
if res.Status == agentrun.StatusPassed && len(res.Changes) == 0 {
tc.BuildNoChanges = true
}
return nil
},
}.Stage()
}
// StageCheckReviewPayload fails the run before any worktree or agent work
// starts if the task's review payload cannot be decoded -- a dispatch bug
// upstream, not something a builder run can recover from.
@@ -193,71 +145,3 @@ func StageCheckReviewPayload() Stage {
return err
}}
}
// StageRemediationCommitPush commits and pushes the remediation to the PR
// branch. No changes is a normal outcome.
func StageRemediationCommitPush() Stage {
return Stage{Name: "remediate-commit-push", Run: func(ctx context.Context, tc *TaskContext) error {
if tc.BuildNoChanges {
return nil
}
changed, err := tc.Trees.CommitAll(ctx, tc.Dir, remediationCommitMessage(tc))
if err != nil {
return err
}
if !changed {
return nil
}
if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil {
return err
}
tc.captureChanges(ctx, capturedAfterCommitPush)
return nil
}}
}
func remediationCommitMessage(tc *TaskContext) string {
return fmt.Sprintf("fix: address review feedback (archie)%s", commitIssueReference("Refs", tc.Task))
}
// StageRemediationReply replies to the review this run addressed, then
// returns the task to pr_open and clears the consumed review payload so a
// later crash-and-resume cannot reprocess it. It is the workflow's only
// terminal stage: it always sets Outcome, so it always ends the run.
func StageRemediationReply() Stage {
return Stage{Name: "remediate-reply", Run: func(ctx context.Context, tc *TaskContext) error {
summary := tc.BuildSummary
if tc.BuildNoChanges {
summary = "Reviewed -- no code change was required."
}
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RemediationRounds)
if id, ok := tc.reviewUnit.replyTarget(); ok {
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
}
} else {
postRemediationComment(ctx, tc, reply)
}
tc.Task.ReviewPayload = ""
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RemediationRounds)}
return nil
}}
}
// Remediate runs one remediation round on an open archie-owned pull request in
// response to a review, reusing the task's worktree and branch.
func Remediate() Workflow {
return Workflow{
Name: "remediate",
Stages: []Stage{
StageCheckReviewPayload(),
StageRemediationRoundCap(),
StagePrepareWorktreeOnBranch(),
remediateBuildStage(),
StageRemediationCommitPush(),
StageRemediationReply(),
},
}
}
+92
View File
@@ -0,0 +1,92 @@
package workflow
import (
"context"
"fmt"
"strings"
"gopkg.in/yaml.v3"
)
// Review step types: reviewing a pull request, and answering a review of
// archie's own.
const (
ReviewPRStepName = "review.pr"
ReviewRoundStepName = "review.start-round"
ReviewReplyStepName = "review.reply"
)
// ReviewStepTypes contributes the review step types.
func ReviewStepTypes() []StepType {
return []StepType{
{Name: ReviewPRStepName, Factory: newReviewPRStage},
{Name: ReviewRoundStepName, Factory: newReviewRoundStage},
{Name: ReviewReplyStepName, Factory: newReviewReplyStage},
}
}
// newReviewPRStage runs the whole review pipeline on the task's pull request:
// intake, anatomy, lenses, review, precision gate, verification, coverage,
// synthesis, operator approval, merge gate and output. Its phases share
// private state, so they run as one step.
func newReviewPRStage(yaml.Node) (Stage, error) {
phases := prReviewStandaloneStages()
return Stage{Name: ReviewPRStepName, Run: func(ctx context.Context, tc *TaskContext) error {
for _, phase := range phases {
if err := phase.Run(ctx, tc); err != nil {
return fmt.Errorf("%s (%s): %w", ReviewPRStepName, phase.Name, err)
}
if tc.Outcome.Status != "" {
return nil
}
}
return nil
}}, nil
}
// newReviewRoundStage opens one remediation round: it refuses a review
// payload that does not decode, parks with a PR comment once the repository's
// round cap is reached, and otherwise counts the round.
func newReviewRoundStage(yaml.Node) (Stage, error) {
check, roundCap := StageCheckReviewPayload(), StageRemediationRoundCap()
return Stage{Name: ReviewRoundStepName, Run: func(ctx context.Context, tc *TaskContext) error {
if err := check.Run(ctx, tc); err != nil {
return err
}
if err := roundCap.Run(ctx, tc); err != nil {
return err
}
tc.reviewUnit, _ = DecodeReviewUnit(tc.Task.ReviewPayload)
return nil
}}, nil
}
type reviewReplySettings struct {
Body string `yaml:"body"`
}
// newReviewReplyStage answers the review this round addressed, in its own
// thread when it has one, clears the consumed payload so a resumed run cannot
// address it twice, and returns the task to pr_open.
func newReviewReplyStage(settings yaml.Node) (Stage, error) {
var s reviewReplySettings
if err := decodeSettings(ReviewReplyStepName, settings, &s); err != nil {
return Stage{}, err
}
if strings.TrimSpace(s.Body) == "" {
return Stage{}, fmt.Errorf("%s: settings.body is required", ReviewReplyStepName)
}
return Stage{Name: ReviewReplyStepName, Run: func(ctx context.Context, tc *TaskContext) error {
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", s.Body, tc.Task.RemediationRounds)
if id, ok := tc.reviewUnit.replyTarget(); ok {
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
}
} else {
postRemediationComment(ctx, tc, reply)
}
tc.Task.ReviewPayload = ""
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RemediationRounds)}
return nil
}}, nil
}
@@ -0,0 +1,10 @@
id: pr-review
inputs:
pr_number:
type: number
required: true
depth:
type: string
required: false
steps:
- type: review.pr
@@ -0,0 +1,25 @@
id: remediate
steps:
- type: review.start-round
- type: repo.prepare
settings:
branch: task
- id: build
type: agent.run
settings:
gate: repository
mission: |
Address the review comments below on pull request #{{ task.pr }} for {{ task.repository }} with the smallest change that satisfies them, then run the gate.
{{ task.review }}
Do not run git: the orchestrator commits and pushes for you. When done, call finish with status "passed" and a summary written for the human who will read your reply: what changed and why. If nothing here actually requires a code change, call finish with status "passed" and say so in the summary.
- type: repo.commit
settings:
message: "fix: address review feedback (archie)"
reference: Refs
push: true
if_empty: skip
- type: review.reply
settings:
body: "{{ steps.build.summary }}"
+307
View File
@@ -0,0 +1,307 @@
package workflow
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/domain/stableid"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
const maxRetryAttempts = 10
// checkStep validates one step against the vocabulary and the steps before
// it, and adds the ids it declares to earlier.
func checkStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
if err := checkStepID(step.ID, earlier); err != nil {
return err
}
if err := checkStepControls(step, earlier); err != nil {
return err
}
if step.Parallel != nil {
if err := checkParallel(step, mode, earlier, registry, inBranch); err != nil {
return err
}
} else if err := checkTypedStep(step, mode, earlier, registry, inBranch); err != nil {
return err
}
if step.ID != "" {
earlier[step.ID] = true
}
return nil
}
// checkStepControls validates the settings every step carries: when,
// on_failure and retry.
func checkStepControls(step StepRecord, earlier map[string]bool) error {
if step.OnFailure != "" && step.OnFailure != "park" && step.OnFailure != onFailureContinue {
return fmt.Errorf("on_failure is park or continue, not %q", step.OnFailure)
}
if step.Retry != nil {
if step.Retry.Attempts < 1 || step.Retry.Attempts > maxRetryAttempts {
return fmt.Errorf("retry.attempts is 1 to %d, not %d", maxRetryAttempts, step.Retry.Attempts)
}
if _, err := retryBackoff(step.Retry); err != nil {
return err
}
}
if step.When == "" {
return nil
}
c, err := parseCondition(step.When)
if err != nil {
return err
}
if err := checkReference(c.path, earlier); err != nil {
return fmt.Errorf("when: %w", err)
}
return nil
}
func checkTypedStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
factory, ok := registry[step.Type]
if !ok {
return fmt.Errorf("unknown type %q", step.Type)
}
if mode != task.RepositoryRequired && NeedsRepository(step.Type) {
return fmt.Errorf("%q needs a repository, but the workflow's repository is %s", step.Type, mode)
}
if inBranch && !parallelSafe(step) {
return fmt.Errorf("%q cannot run in a parallel branch: branches share the worktree, so only read-only agent.run and workflow.call steps may run there", step.Type)
}
if err := checkReferences(step.Settings, earlier); err != nil {
return err
}
if _, err := factory(step.Settings); err != nil {
return fmt.Errorf("%q settings: %w", step.Type, err)
}
return nil
}
// checkParallel validates each branch on its own: a branch sees the steps
// before the parallel step and its own earlier steps, never a sibling's.
// Every branch's ids are visible after the parallel step.
func checkParallel(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
switch {
case step.Type != "" || step.Settings.Kind != 0:
return errors.New("a parallel step has branches, not a type or settings")
case inBranch:
return errors.New("parallel steps do not nest")
case len(step.Parallel) < 2:
return errors.New("parallel needs at least two branches")
}
declared := map[string]bool{}
for _, name := range slices.Sorted(maps.Keys(step.Parallel)) {
if !stableid.Valid(name) {
return fmt.Errorf("branch name %q is not a stable identifier", name)
}
branch := step.Parallel[name]
if len(branch) == 0 {
return fmt.Errorf("branch %q has no steps", name)
}
seen := maps.Clone(earlier)
for i, branchStep := range branch {
if declared[branchStep.ID] {
return fmt.Errorf("branch %q step %d: step id %q is declared twice", name, i+1, branchStep.ID)
}
if err := checkStep(branchStep, mode, seen, registry, true); err != nil {
return fmt.Errorf("branch %q step %d: %w", name, i+1, err)
}
if branchStep.ID != "" {
declared[branchStep.ID] = true
}
}
}
maps.Copy(earlier, declared)
return nil
}
// parallelSafe reports whether a step may run beside others in one worktree.
func parallelSafe(step StepRecord) bool {
switch step.Type {
case WorkflowCallStepName:
return true
case AgentRunStepName:
var s agentRunSettings
return step.Settings.Decode(&s) == nil && s.ReadOnly
}
return false
}
func retryBackoff(policy *RetryPolicy) (time.Duration, error) {
if policy == nil || policy.Backoff == "" {
return 0, nil
}
backoff, err := time.ParseDuration(policy.Backoff)
if err != nil || backoff < 0 {
return 0, fmt.Errorf("retry.backoff %q is not a duration", policy.Backoff)
}
return backoff, nil
}
// Compile resolves a validated YAML definition to executable stages.
func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error) {
stages := make([]Stage, 0, len(definition.Steps))
for _, step := range definition.Steps {
stage, err := compileStep(step, registry)
if err != nil {
return Workflow{}, err
}
stages = append(stages, stage)
}
return Workflow{Name: definition.ID, Stages: stages, Interface: definition.WorkflowInterface}, nil
}
func compileStep(step StepRecord, registry StepRegistry) (Stage, error) {
if step.Parallel != nil {
return compileParallel(step, registry)
}
factory, ok := registry[step.Type]
if !ok {
return Stage{}, fmt.Errorf("unknown workflow step type %q", step.Type)
}
if _, err := factory(step.Settings); err != nil {
return Stage{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
}
// Settings are built per run, with every reference resolved.
return wrapStep(step, step.Type, func(ctx context.Context, tc *TaskContext) error {
stage, err := factory(renderSettings(step.Settings, tc))
if err != nil {
return fmt.Errorf("step %q settings: %w", step.Type, err)
}
return stage.Run(ctx, tc)
}), nil
}
// wrapStep applies the controls every step shares around its body: when,
// retry, and recording its result under its id.
func wrapStep(step StepRecord, name string, body func(context.Context, *TaskContext) error) Stage {
if step.ID != "" {
name = step.ID
}
// ParseDefinition has already refused a condition or backoff that does
// not parse.
when, _ := parseCondition(step.When)
backoff, _ := retryBackoff(step.Retry)
attempts := 1
if step.Retry != nil {
attempts = step.Retry.Attempts
}
return Stage{Name: name, ContinueOnFailure: step.OnFailure == onFailureContinue, Run: func(ctx context.Context, tc *TaskContext) error {
tc.stepResult = StepResult{}
if step.When != "" && !when.holds(tc) {
tc.Log.Info("step skipped", "step", name, "when", step.When)
return nil
}
err := runAttempts(ctx, tc, name, attempts, backoff, body)
if step.ID != "" {
if tc.stepResults == nil {
tc.stepResults = map[string]StepResult{}
}
tc.stepResults[step.ID] = tc.stepResult
}
return err
}}
}
func runAttempts(ctx context.Context, tc *TaskContext, name string, attempts int, backoff time.Duration, body func(context.Context, *TaskContext) error) error {
var err error
for attempt := 1; attempt <= attempts; attempt++ {
if err = body(ctx, tc); err == nil || attempt == attempts {
return err
}
tc.Log.Warn("step failed; retrying", "step", name, "attempt", attempt, "of", attempts, "err", err)
select {
case <-ctx.Done():
return err
case <-time.After(backoff):
}
}
return err
}
// compileParallel runs each branch in its own copy of the task context, then
// folds the branches' results, usage and first outcome back into the run.
func compileParallel(step StepRecord, registry StepRegistry) (Stage, error) {
names := slices.Sorted(maps.Keys(step.Parallel))
branches := make([][]Stage, len(names))
for i, name := range names {
for _, branchStep := range step.Parallel[name] {
stage, err := compileStep(branchStep, registry)
if err != nil {
return Stage{}, fmt.Errorf("branch %q: %w", name, err)
}
branches[i] = append(branches[i], stage)
}
}
return wrapStep(step, "parallel", func(ctx context.Context, tc *TaskContext) error {
clones := make([]*TaskContext, len(branches))
errs := make([]error, len(branches))
var wg sync.WaitGroup
for i := range branches {
clones[i] = tc.branch(names[i])
wg.Go(func() { errs[i] = runBranch(ctx, clones[i], branches[i]) })
}
wg.Wait()
for i, clone := range clones {
tc.join(clone)
if errs[i] != nil {
errs[i] = fmt.Errorf("branch %q: %w", names[i], errs[i])
}
}
return errors.Join(errs...)
}), nil
}
func runBranch(ctx context.Context, tc *TaskContext, stages []Stage) error {
for _, stage := range stages {
if err := stage.Run(ctx, tc); err != nil && !stage.ContinueOnFailure {
return err
}
if tc.Outcome.Status != "" {
return nil
}
}
return nil
}
// branch is a copy of the run's context for one parallel branch. The task is
// copied too, with its usage counters zeroed, so join can add what the branch
// spent without the branches racing on one task.
func (tc *TaskContext) branch(name string) *TaskContext {
clone := *tc
taskCopy := *tc.Task
taskCopy.TokensUsed, taskCopy.Iterations = 0, 0
clone.Task = &taskCopy
clone.RunUsage = agentrun.Usage{}
clone.Outcome = Outcome{}
clone.stepResults = maps.Clone(tc.stepResults)
clone.Log = tc.Log.With("branch", name)
return &clone
}
// join folds a finished branch back into the run: its step results, what it
// spent, and its outcome when the run has none yet.
func (tc *TaskContext) join(branch *TaskContext) {
for id, result := range branch.stepResults {
if _, ok := tc.stepResults[id]; !ok {
if tc.stepResults == nil {
tc.stepResults = map[string]StepResult{}
}
tc.stepResults[id] = result
}
}
tc.Task.TokensUsed += branch.Task.TokensUsed
tc.Task.Iterations += branch.Task.Iterations
accumulateUsage(&tc.RunUsage, branch.RunUsage)
if tc.Outcome.Status == "" {
tc.Outcome = branch.Outcome
}
}
+12 -2
View File
@@ -63,7 +63,7 @@ func checkReference(path string, earlier map[string]bool) error {
return fmt.Errorf("reference {{ %s }} must start with task, inputs or steps", path)
}
var taskFields = map[string]bool{"plan": true, "title": true, "body": true, "prompt": true, "repository": true, "kind": true, "issue": true, "pr": true}
var taskFields = map[string]bool{"review": true, "plan": true, "title": true, "body": true, "prompt": true, "repository": true, "kind": true, "issue": true, "pr": true}
// renderSettings returns a copy of settings with every reference replaced by
// its value in this run. A reference to an absent value renders empty: a
@@ -90,7 +90,7 @@ func referenceScope(tc *TaskContext) map[string]any {
maps.Copy(inputs, t.Inputs)
return map[string]any{
"task": map[string]any{
"plan": approvedPlan(t), "title": t.Title, "body": t.Body, "prompt": taskPromptBlock(t),
"review": reviewMission(t), "plan": approvedPlan(t), "title": t.Title, "body": t.Body, "prompt": taskPromptBlock(t),
"repository": tc.Repo.FullName(), "kind": taskKind(t),
"issue": t.IssueNumber, "pr": t.PRNumber,
},
@@ -166,3 +166,13 @@ func approvedPlan(t *Task) string {
}
return "<approved_prd>\n" + t.Plan + "\n</approved_prd>"
}
// reviewMission is the review a remediation round addresses, as the builder
// reads it.
func reviewMission(t *Task) string {
unit, err := DecodeReviewUnit(t.ReviewPayload)
if err != nil || t.ReviewPayload == "" {
return ""
}
return renderReviewUnitMission(unit)
}
@@ -73,6 +73,50 @@ steps:
`,
wantErr: `when: reference {{ steps.later.result.fit }}: no earlier step has id "later"`,
},
{
name: "a branch cannot read a sibling branch",
yaml: `id: w
repository: none
steps:
- parallel:
a: [{id: x, type: agent.run, settings: {mission: m, read_only: true}}]
b: [{type: agent.run, settings: {mission: "{{ steps.x.summary }}", read_only: true}}]
`,
wantErr: `branch "b" step 1: reference {{ steps.x.summary }}: no earlier step has id "x"`,
},
{
name: "a branch step must not write the worktree",
yaml: `id: w
repository: none
steps:
- parallel:
a: [{type: agent.run, settings: {mission: m}}]
b: [{type: agent.run, settings: {mission: m, read_only: true}}]
`,
wantErr: "cannot run in a parallel branch",
},
{
name: "every branch result is visible after the parallel step",
yaml: `id: w
repository: none
steps:
- parallel:
a: [{id: plan, type: agent.run, settings: {mission: m, read_only: true}}]
b: [{id: other, type: agent.run, settings: {mission: m, read_only: true}}]
- type: agent.run
settings: {mission: "build {{ steps.plan.summary }} / {{ steps.plan.result.verdict }} / {{ steps.plan.result.missing }}"}
`,
rendered: "build the plan / go / ",
},
{
name: "retry attempts are bounded",
yaml: `id: w
repository: none
steps:
- {type: workflow.finish, retry: {attempts: 50}}
`,
wantErr: "retry.attempts is 1 to 10",
},
{
name: "on_failure takes park or continue",
yaml: `id: w
@@ -4,26 +4,16 @@ package workflowsteps
import (
"fmt"
"maps"
"slices"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// shippedStages provides every stage of the shipped workflows as a step
// type.
type shippedStages struct{}
// reviewSteps provides the pull request review and remediation step types.
type reviewSteps struct{}
func (shippedStages) Name() string { return "shipped" }
func (reviewSteps) Name() string { return "review" }
func (shippedStages) StepTypes() []workflow.StepType {
registry := workflow.BuiltinStepRegistry()
stepTypes := make([]workflow.StepType, 0, len(registry))
for _, name := range slices.Sorted(maps.Keys(registry)) {
stepTypes = append(stepTypes, workflow.StepType{Name: name, Factory: registry[name]})
}
return stepTypes
}
func (reviewSteps) StepTypes() []workflow.StepType { return workflow.ReviewStepTypes() }
// repoHooks provides the gate.diff-rules step type.
type repoHooks struct{}
@@ -74,7 +64,7 @@ func (controlSteps) StepTypes() []workflow.StepType { return workflow.ControlSte
// Providers returns the step-type providers to register.
func Providers() []workflow.StepTypeProvider {
return []workflow.StepTypeProvider{shippedStages{}, repoHooks{}, eventSteps{}, commandSteps{}, repositorySteps{}, controlSteps{}}
return []workflow.StepTypeProvider{reviewSteps{}, repoHooks{}, eventSteps{}, commandSteps{}, repositorySteps{}, controlSteps{}}
}
// NewManager returns a new manager with Providers registered.
+4 -4
View File
@@ -18,7 +18,7 @@ Defaulting to \`null\`.`),null)}function zS(e){return LS(e)&&!Number.isNaN(e)&&e
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=qE(c),u=e+1<n.length?qE(n[e+1]):null;if(l&&u&&JE(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=qE(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>GE(e)),rows:r.map(e=>e.map(e=>GE(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:GE(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:GE(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function qE(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function JE(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var YE={class:`[overflow-wrap:anywhere]`},XE={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},ZE={class:`font-mono text-[0.85em]`},QE={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},$E={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},eD={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},tD={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},nD={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},rD={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},iD={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},aD={key:8,class:`mb-2.5 last:mb-0`},oD=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>KE(t.text));return(e,t)=>(L(),R(`div`,YE,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,XE,[B(`code`,ZE,D(e.code),1)])):e.kind===`table`?(L(),R(`table`,QE,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(UE,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(UE,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,$E,[V(UE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,eD,[V(UE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,tD,[V(UE,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,nD,[V(UE,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,rD,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(UE,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,iD,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(UE,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,aD,[V(UE,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),sD={class:`truncate`},cD=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=pa(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[V(k(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,sD,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),lD={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},uD={class:`font-semibold text-foreground`},dD={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},fD=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(cD,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,lD,[V(k(of),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,uD,D(n.value),1),r.value?(L(),R(`code`,dD,D(r.value),1)):U(``,!0),B(`span`,{class:E(k(K)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),pD={key:0,class:`mb-2 grid gap-0.5 text-xs`},mD={key:1,class:`mb-2 flex flex-wrap gap-1.5`},hD={key:3,class:`whitespace-pre-wrap`},gD=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:E(k(K)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,pD,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(fD,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.media.length?(L(),R(`div`,mD,[(L(!0),R(I,null,P(e.media,(e,t)=>(L(),z(IE,{key:t,attachment:e},null,8,[`attachment`]))),128))])):U(``,!0),e.assistant?(L(),z(oD,{key:2,text:e.text},null,8,[`text`])):(L(),R(`div`,hD,D(e.text),1)),F(t.$slots,`default`)],2)],2))}}),_D={class:`w-full self-center justify-self-center py-6 text-center`},vD={class:`grid gap-2`},yD=[`onClick`],bD=M({__name:`ChatEmptyState`,emits:[`proLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>HM?`${n.slice(0,HM).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var WM=[`title`],GM=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>gM(n.event)),a=G(()=>UM(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?wj(n.event.at):`—`);return(e,t)=>(L(),z(k(BM),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[uu(cu(o,[`prevent`]),[`enter`]),uu(cu(o,[`prevent`]),[`space`])]},{default:A(()=>[V(k(Q),{class:`font-medium`},{default:A(()=>[H(D(n.event.kind||n.event.type||`event`),1)]),_:1}),V(k(Q),{class:`font-mono`},{default:A(()=>[H(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,WM)]),_:1}),V(k(Q),null,{default:A(()=>[H(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),KM=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function qM(e){return(Number(e?.task_id)||0)>0}function JM(e,t){return t===`tasks`?qM(e):t!==`system`||!qM(e)}function YM(e,t){return e.filter(e=>JM(e,t))}function XM(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function ZM(e,t){return`${e}:${t??0}`}function QM(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=ZM(UM(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var $M={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},eN={class:`max-h-[28rem] overflow-y-auto`},tN=[`aria-expanded`,`aria-label`,`onClick`],nN=[`title`],rN=M({__name:`LiveActivityCard`,setup(e){let t=UD(),{activity:n,streamKind:r,streamState:i}=id(DA()),a=O(`all`),o=G(()=>YM(n.value,a.value)),s=G(()=>XM(o.value.length,a.value)),c=nn(new Set),l=G(()=>QM(o.value));function u(e){c.has(e)?c.delete(e):c.add(e)}function d(e){return c.has(e.key)}function f(e){return UM(e.representative)}function p(e){return e.representative.at?wj(e.representative.at):`—`}function m(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(k(_j),null,{default:A(()=>[V(k(Sj),null,{default:A(()=>[V(k(Cj),null,{default:A(()=>[...t[1]||=[H(`Live activity`,-1)]]),_:1}),V(k(vj),{class:`flex items-center gap-2`},{default:A(()=>[V(k(IM),{modelValue:a.value,"onUpdate:modelValue":t[0]||=e=>a.value=e,label:`Filter activity`,options:k(KM)},null,8,[`modelValue`,`options`]),V(k(mj),{variant:k(r)},{default:A(()=>[H(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(k(yj),null,{default:A(()=>[B(`div`,$M,[B(`div`,eN,[V(k(RM),null,{default:A(()=>[V(k(VM),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[V(k(BM),null,{default:A(()=>[V(k($),null,{default:A(()=>[...t[2]||=[H(`Event`,-1)]]),_:1}),V(k($),null,{default:A(()=>[...t[3]||=[H(`Task`,-1)]]),_:1}),V(k($),null,{default:A(()=>[...t[4]||=[H(`Detail`,-1)]]),_:1}),V(k($),null,{default:A(()=>[...t[5]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(k(zM),null,{default:A(()=>[o.value.length?U(``,!0):(L(),z(k(BM),{key:0},{default:A(()=>[V(k(Q),{colspan:`4`},{default:A(()=>[V(k(oj),null,{default:A(()=>[V(k(lj),null,{default:A(()=>[V(k(fj),null,{default:A(()=>[H(D(s.value),1)]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),o.value.length?(L(!0),R(I,{key:1},P(l.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(GM,{key:0,event:e.representative,onOpen:m},null,8,[`event`])):(L(),R(I,{key:1},[V(k(BM),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&m(e.taskID),onKeydown:[uu(cu(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`enter`]),uu(cu(t=>e.taskID>0&&m(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[V(k(Q),{class:`font-medium`},{default:A(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":d(e),"aria-label":`${d(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:cu(t=>u(e.key),[`stop`])},[d(e)?(L(),z(k(Cd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+D(e.label)+` `,1),V(k(mj),{variant:`idle`},{default:A(()=>[H(`×`+D(e.count),1)]),_:2},1024)],8,tN)]),_:2},1024),V(k(Q),{class:`font-mono`},{default:A(()=>[H(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[B(`span`,{class:`block truncate`,title:f(e).truncated?f(e).full:void 0},D(f(e).text),9,nN)]),_:2},1024),V(k(Q),null,{default:A(()=>[H(D(p(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),d(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(GM,{key:`${e.key}:${n}`,event:t,onOpen: Line truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function bP(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function xP(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function SP(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function CP(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var wP=O([]),TP=O([]),EP=O(!0),DP=O(null),OP=O(null),kP=O(!1),AP=O(null);async function jP(){try{let e=await q.eventTypes();EP.value=e.enabled!==!1,wP.value=e.event_types||[],TP.value=e.proposals||[],DP.value=null}catch(e){DP.value=e.message||String(e)}}function MP(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function NP(e){AP.value=null,OP.value=e}function PP(e){let t=HP.value.find(t=>String(t.id)===e.sample_id);NP({mode:`proposal`,id:null,source:e.source,name:``,rule:MP(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function FP(e=``){NP({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function IP(e){NP({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:MP(e.rule),headersText:``,body:``,exampleHeaders:{}})}function LP(){OP.value=null}async function RP(){let e=OP.value;if(e){kP.value=!0;try{if(e.mode===`edit`&&e.id)await q.eventTypeUpdate(e.id,{name:e.name,rule:CP(e.rule)});else{let t=e.mode===`paste`?yP(e.headersText):e.exampleHeaders;await q.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:CP(e.rule),example:{headers:t,body:e.body}})}OP.value=null,await jP()}catch(e){AP.value=e.message||String(e)}finally{kP.value=!1}}}var zP=O(null);async function BP(){let e=zP.value;if(zP.value=null,e)try{await q.eventTypeDelete(e.id),await jP()}catch(e){DP.value=e.message||String(e)}}var VP=100,HP=O([]),UP=O(!0),WP=O(null),GP=O(!0),KP=O(null);async function qP(){try{let e=await q.captures(VP);UP.value=e.enabled!==!1,HP.value=e.captures||[],WP.value=null}catch(e){WP.value=e.message||String(e)}finally{GP.value=!1}}function JP(e){let t=HP.value.find(t=>t.id===e);return t&&(KP.value=t),!!t}function YP(){HP.value.length&&(KP.value=HP.value[0])}function XP(){OA(`captures`,()=>{qP(),jP()})}var ZP=`archie.theme`,QP=`archie.density`,$P=`archie.motion`,eF=`archie.tooltips`;function tF(e,t,n){try{let r=localStorage.getItem(e);return t.includes(r)?r:n}catch{return n}}function nF(e,t){try{localStorage.setItem(e,t)}catch{}}function rF(e){if(e!==`system`)return e;try{return matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}catch{return`dark`}}var iF=rd(`appearance`,()=>{let e=O(tF(ZP,[`system`,`dark`,`light`],`dark`)),t=O(tF(QP,[`comfortable`,`compact`],`comfortable`)),n=O(tF($P,[`system`,`reduced`],`system`)),r=O(tF(eF,[`on`,`off`],`on`)===`on`),i=!1;function a(){document.documentElement.dataset.theme=rF(e.value)}function o(t){e.value=t,a(),nF(ZP,t)}function s(e){t.value=e,document.documentElement.dataset.density=e,nF(QP,e)}function c(e){n.value=e,document.documentElement.dataset.motion=e,nF($P,e)}function l(e){r.value=e,nF(eF,e?`on`:`off`)}function u(){if(!i){i=!0,a(),document.documentElement.dataset.density=t.value,document.documentElement.dataset.motion=n.value;try{matchMedia(`(prefers-color-scheme: dark)`).addEventListener(`change`,()=>{e.value===`system`&&a()})}catch{}}}return{theme:e,density:t,motion:n,tooltipsEnabled:r,initialize:u,setTheme:o,setDensity:s,setMotion:c,setTooltips:l}}),aF=M({__name:`Tooltip`,props:{defaultOpen:{type:Boolean},open:{type:Boolean},delayDuration:{},disableHoverableContent:{type:Boolean},disableClosingTrigger:{type:Boolean},disabled:{type:Boolean},ignoreNonKeyboardFocus:{type:Boolean}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=yg(n,t),{tooltipsEnabled:i}=id(iF());return(e,t)=>(L(),z(k(pw),W({"data-slot":`tooltip`},k(r),{disabled:n.disabled||!k(i)}),{default:A(t=>[F(e.$slots,`default`,Ce(Es(t)))]),_:3},16,[`disabled`]))}}),oF=M({inheritAttrs:!1,__name:`TooltipContent`,props:{forceMount:{type:Boolean},ariaLabel:{},asChild:{type:Boolean},as:{},side:{},sideOffset:{default:0},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean},positionStrategy:{},updatePositionStrategy:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`escapeKeyDown`,`pointerDownOutside`],setup(e,{emit:t}){let n=e,r=t,i=yg(Nw(n,`class`),r);return(e,t)=>(L(),z(k(_w),null,{default:A( Line truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function bP(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function xP(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function SP(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function CP(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var wP=O([]),TP=O([]),EP=O(!0),DP=O(null),OP=O(null),kP=O(!1),AP=O(null);async function jP(){try{let e=await q.eventTypes();EP.value=e.enabled!==!1,wP.value=e.event_types||[],TP.value=e.proposals||[],DP.value=null}catch(e){DP.value=e.message||String(e)}}function MP(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function NP(e){AP.value=null,OP.value=e}function PP(e){let t=HP.value.find(t=>String(t.id)===e.sample_id);NP({mode:`proposal`,id:null,source:e.source,name:``,rule:MP(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function FP(e=``){NP({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function IP(e){NP({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:MP(e.rule),headersText:``,body:``,exampleHeaders:{}})}function LP(){OP.value=null}async function RP(){let e=OP.value;if(e){kP.value=!0;try{if(e.mode===`edit`&&e.id)await q.eventTypeUpdate(e.id,{name:e.name,rule:CP(e.rule)});else{let t=e.mode===`paste`?yP(e.headersText):e.exampleHeaders;await q.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:CP(e.rule),example:{headers:t,body:e.body}})}OP.value=null,await jP()}catch(e){AP.value=e.message||String(e)}finally{kP.value=!1}}}var zP=O(null);async function BP(){let e=zP.value;if(zP.value=null,e)try{await q.eventTypeDelete(e.id),await jP()}catch(e){DP.value=e.message||String(e)}}var VP=100,HP=O([]),UP=O(!0),WP=O(null),GP=O(!0),KP=O(null);async function qP(){try{let e=await q.captures(VP);UP.value=e.enabled!==!1,HP.value=e.captures||[],WP.value=null}catch(e){WP.value=e.message||String(e)}finally{GP.value=!1}}function JP(e){let t=HP.value.find(t=>t.id===e);return t&&(KP.value=t),!!t}function YP(){HP.value.length&&(KP.value=HP.value[0])}function XP(){OA(`captures`,()=>{qP(),jP()})}var ZP=`archie.theme`,QP=`archie.density`,$P=`archie.motion`,eF=`archie.tooltips`;function tF(e,t,n){try{let r=localStorage.getItem(e);return t.includes(r)?r:n}catch{return n}}function nF(e,t){try{localStorage.setItem(e,t)}catch{}}function rF(e){if(e!==`system`)return e;try{return matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}catch{return`dark`}}var iF=rd(`appearance`,()=>{let e=O(tF(ZP,[`system`,`dark`,`light`],`dark`)),t=O(tF(QP,[`comfortable`,`compact`],`comfortable`)),n=O(tF($P,[`system`,`reduced`],`system`)),r=O(tF(eF,[`on`,`off`],`on`)===`on`),i=!1;function a(){document.documentElement.dataset.theme=rF(e.value)}function o(t){e.value=t,a(),nF(ZP,t)}function s(e){t.value=e,document.documentElement.dataset.density=e,nF(QP,e)}function c(e){n.value=e,document.documentElement.dataset.motion=e,nF($P,e)}function l(e){r.value=e,nF(eF,e?`on`:`off`)}function u(){if(!i){i=!0,a(),document.documentElement.dataset.density=t.value,document.documentElement.dataset.motion=n.value;try{matchMedia(`(prefers-color-scheme: dark)`).addEventListener(`change`,()=>{e.value===`system`&&a()})}catch{}}}return{theme:e,density:t,motion:n,tooltipsEnabled:r,initialize:u,setTheme:o,setDensity:s,setMotion:c,setTooltips:l}}),aF=M({__name:`Tooltip`,props:{defaultOpen:{type:Boolean},open:{type:Boolean},delayDuration:{},disableHoverableContent:{type:Boolean},disableClosingTrigger:{type:Boolean},disabled:{type:Boolean},ignoreNonKeyboardFocus:{type:Boolean}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=yg(n,t),{tooltipsEnabled:i}=id(iF());return(e,t)=>(L(),z(k(pw),W({"data-slot":`tooltip`},k(r),{disabled:n.disabled||!k(i)}),{default:A(t=>[F(e.$slots,`default`,Ce(Es(t)))]),_:3},16,[`disabled`]))}}),oF=M({inheritAttrs:!1,__name:`TooltipContent`,props:{forceMount:{type:Boolean},ariaLabel:{},asChild:{type:Boolean},as:{},side:{},sideOffset:{default:0},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean},positionStrategy:{},updatePositionStrategy:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`escapeKeyDown`,`pointerDownOutside`],setup(e,{emit:t}){let n=e,r=t,i=yg(Nw(n,`class`),r);return(e,t)=>(L(),z(k(_w),null,{default:A( Line truncated
`)}};dJ.defaultYaml={explicit:!1,version:`1.2`},dJ.defaultTags={"!!":`tag:yaml.org,2002:`};function fJ(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function pJ(e){let t=new Set;return iJ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function mJ(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function hJ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=pJ(e);let a=mJ(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(Xq(t.node)||Qq(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function gJ(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=gJ(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=gJ(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=gJ(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=gJ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function _J(e,t,n){if(Array.isArray(e))return e.map((e,t)=>_J(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!eJ(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var vJ=class{constructor(e){Object.defineProperty(this,Gq,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!qq(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=_J(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?gJ(i,{"":o},``,o):o}},yJ=class extends vJ{constructor(e){super(zq),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],iJ(e,{Node:(e,t)=>{(Kq(t)||eJ(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(_J(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=bJ(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(fJ(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function bJ(e,t,n){if(Kq(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Qq(t)){let r=0;for(let i of t.items){let t=bJ(e,i,n);t>r&&(r=t)}return r}if(Yq(t)){let r=bJ(e,t.key,n),i=bJ(e,t.value,n);return Math.max(r,i)}return 1}var xJ=e=>!e||typeof e!=`function`&&typeof e!=`object`,SJ=class extends vJ{constructor(e){super(Uq),this.value=e}toJSON(e,t){return t?.keep?this.value:_J(this.value,e,t)}toString(){return String(this.value)}};SJ.BLOCK_FOLDED=`BLOCK_FOLDED`,SJ.BLOCK_LITERAL=`BLOCK_LITERAL`,SJ.PLAIN=`PLAIN`,SJ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,SJ.QUOTE_SINGLE=`QUOTE_SINGLE`;var CJ=`tag:yaml.org,2002:`;function wJ(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function TJ(e,t,n){if(qq(e)&&(e=e.contents),$q(e))return e;if(Yq(e)){let t=n.schema[Vq].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new yJ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=CJ+t.slice(2));let l=wJ(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new SJ(e);return c&&(c.node=t),t Line truncated
`)?AJ(n,t):n.includes(`
`)?`
@@ -122,6 +122,6 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){wZ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(yZ(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=CZ(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(yZ(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(xZ(t.key)&&!yZ(t.sep,`newline`)){let e=CZ(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):yZ(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!yZ(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){wZ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||yZ(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.ite Line truncated
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=CZ(SZ(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=CZ(SZ(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function DZ(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new vZ||null,prettyErrors:t}}function OZ(e,t={}){let{lineCounter:n,prettyErrors:r}=DZ(t),i=new EZ(n?.addNewLine),a=new iZ(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new bX(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(SX(e,n)),o.warnings.forEach(SX(e,n))),o}function kZ(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function AZ(e,t=[]){let n=OZ(e),r=n.errors[0];if(r)return{ok:!1,message:zZ(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!BZ(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,message:`workflow id is required`};let o=i.steps;if(o==null||o===``)return{ok:!1,message:`workflow ${a} has no steps`};if(!Array.isArray(o))return{ok:!1,message:`workflow ${a}: steps must be a list`};if(!o.length)return{ok:!1,message:`workflow ${a} has no steps`};let s=new Map(t.map(e=>[e.name,e])),c=typeof i.repository==`string`&&i.repository.trim()?i.repository.trim():`required`,l=[];for(let[e,t]of o.entries()){if(!BZ(t)||!VZ(t.type))return{ok:!1,message:`workflow ${a} step ${e+1} needs a type`};let n=t.type.trim(),r=s.get(n);if(s.size&&!r)return{ok:!1,message:`workflow ${a} step ${e+1}: unknown step type "${n}"`};if(r?.needs_repository&&c!==`required`)return{ok:!1,message:`workflow ${a} step ${e+1}: "${n}" needs a repository, but the workflow's repository is ${c}`};l.push({index:e+1,type:n})}return{ok:!0,id:a,steps:l}}function jZ(e){switch(e){case`key`:return`text-fg-muted`;case`string`:return`text-ok`;case`comment`:case`punct`:return`text-fg-subtle`;default:return`text-foreground`}}function MZ(e){return e.split(`
`).map((e,t)=>({number:t+1,text:e,tokens:FZ(e)}))}var NZ=/^(\s*)(-\s+)?/,PZ=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function FZ(e){let{code:t,comment:n}=IZ(e),r=LZ(t);return n&&r.push({text:n,kind:`comment`}),r}function IZ(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t){r===t&&(t=``);continue}if(r===`"`||r===`'`){t=r;continue}if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function LZ(e){if(!e)return[];let t=[],n=NZ.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=PZ.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...RZ(i[4]??``)]):[...t,...RZ(r)]}function RZ(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function zZ(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function BZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VZ(e){return typeof e==`string`&&e.trim()!==``}var HZ={class:`space-y-1.5`},UZ={class:`space-y-1.5`},WZ={class:`flex h-9 flex-nowrap items-center gap-1.5 overflow-hidden`,role:`list`,"aria-label":`Steps`},GZ=[`title`],KZ={key:1,class:`text-xs text-fg-subtle`},qZ={class:`space-y-1.5`},JZ={class:`flex items-baseline gap-2`},YZ={class:`relative overflow-hidden rounded-lg border border-input font-mono text-[13px] leading-6 focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50`},XZ={"aria-hidden":`true`,class:`pointer-events-none absolute inset-y-0 left-0 w-11 select-none overflow-hidden border-r border-border bg-secondary/40 py-3 text-right`},ZZ={"aria-hidden":`true`,class:`pointer-events-none absolute inset-0 overflow-hidden py-3 pr-3 pl-14 break-words whitespace-pre-wrap`},QZ={key:0,class:`text-sm`},$Z={class:`cursor-pointer text-fg-subtle`},eQ={class:`mt-2 flex flex-wrap gap-1.5`,"aria-label":`Step types`},tQ=[`title`],nQ={key:0,class:`text-fg-subtle`},rQ={key:1,class:`text-sm text-danger`,role:`alert`},iQ={class:`flex flex-wrap items-center gap-2 border-t border-border pt-4`},aQ={key:0,class:`mr-auto font-mono text-xs text-fg-subtle`},oQ=M({__name:`WorkflowEditor`,props:{selected:{required:!0},selectedModifiers:{}},emits:[`update:selected`],setup(e){let t=JA(),n=G(()=>t.stateFor(`workflow-definitions`)),r=G(()=>n.value.resource?.value??{definitions:[]}),i=G(()=>t.shippedWorkflows()),a=so(e,`selected`),o=O(``),s=O(``),c=O(``),l=G(()=>i.value.definitions.find(e=>e.id===o.value));function u(e){let t=r.value.definitions.find(t=>t.id===e);o.value=t?.id??e,s.value=t?.yaml??`id: ${e}\nsteps:\n - type: `,c.value=``}j(a,u,{immediate:!0}),j(r,()=>{s.value||u(a.value)});async function d(e){return c.value=``,t.replace(`workflow-definitions`,e)}async function f(){let e=o.value.trim();if(!e){c.value=`Workflow ID is required.`;return}let t=a.value,n=r.value;t&&t!==e&&(n=KA(n,t)),await d(GA(n,{id:e,yaml:s.value}))&&(a.value=e)}async function p(){a.value&&await d(KA(r.value,a.value))&&(a.value=``,o.value=``,s.value=``)}async function m(){l.value&&await d(GA(r.value,UA(l.value)))}let h=G(()=>t.stepTypes()),g=G(()=>AZ(s.value,h.value)),_=G(()=>g.value.ok?g.value.steps:[]),v=G(()=>MZ(s.value)),y=O(0);function b(e){y.value=e.target.scrollTop}return(e,t)=>(L(),R(`form`,{class:`space-y-4`,onSubmit:cu(f,[`prevent`])},[B(`div`,HZ,[V(k(hT),{for:`workflow-id`},{default:A(()=>[...t[2]||=[H(`ID`,-1)]]),_:1}),V(k(Z),{id:`workflow-id`,modelValue:o.value,"onUpdate:modelValue":t[0]||=e=>o.value=e,name:`workflow-id`,required:``,autocomplete:`off`,class:`max-w-sm font-mono`},null,8,[`modelValue`])]),B(`div`,UZ,[t[3]||=B(`span`,{class:`text-sm leading-none font-medium`},`Steps`,-1),B(`div`,WZ,[_.value.length?(L(!0),R(I,{key:0},P(_.value,(e,t)=>(L(),R(I,{key:e.index},[B(`span`,{role:`listitem`,class:`shrink-0 rounded border border-border bg-secondary px-2 py-0.5 font-mono text-xs`,title:e.type},D(e.type),9,GZ),t<_.value.length-1?(L(),z(k(vd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`,"aria-hidden":`true`})):U(``,!0)],64))),128)):(L(),R(`span`,KZ,`No steps yet`))])]),B(`div`,qZ,[B(`div`,JZ,[V(k(hT),{for:`workflow-yaml`},{default:A(()=>[...t[4]||=[H(`YAML`,-1)]]),_:1}),B(`span`,{class:E([`ml-auto text-xs`,g.value.ok?`text-ok`:`text-danger`]),role:`status`},D(g.value.ok?`✓`:`✕`)+` `+D(k(kZ)(g.value)),3)]),B(`div`,YZ,[B(`div`,XZ,[B(`div`,{style:ve(`transform:translateY(${-y.value}px)`)},[(L(!0),R(I,null,P(v.value,e=>(L(),R(`div`,{key:e.number,class:`min-h-6 pr-2 text-fg-subtle`},D(e.number),1))),128))],4)]),B(`div`,ZZ,[B(`div`,{style:ve(`transform:translateY(${-y.value}px)`)},[(L(!0),R(I,null,P(v.value,e=>(L(),R(`div`,{key:e.number,class:`min-h-6`},[(L(!0),R(I,null,P(e.tokens,(e,t)=>(L(),R(`span`,{key:t,class:E(k(jZ)(e.kind))},D(e.text),3))),128))]))),128))],4)]),V(k(ET),{id:`workflow-yaml`,modelValue:s.value,"onUpdate:modelValue":t[1]||=e=>s.value=e,name:`workflow-yaml`,required:``,class:`relative min-h-96 resize-y rounded-none border-0 bg-transparent py-3 pr-3 pl-14 text-[13px] leading-6 text-transparent caret-foreground shadow-none md:text-[13px] focus-visible:ring-0`,spellcheck:`false`,onScroll:b},null,8,[`modelValue`])])]),h.value.length?(L(),R(`details`,QZ,[B(`summary`,$Z,`Step types (`+D(h.value.length)+`)`,1),B(`ul`,eQ,[(L(!0),R(I,null,P(h.value,e=>(L(),R(`li`,{key:e.name,class:`rounded border border-border bg-secondary px-2 py-0.5 font-mono text-xs`,title:e.needs_repository?`Needs a repository`:`Runs without a repository`},[H(D(e.name),1),e.needs_repository?U(``,!0):(L(),R(`span`,nQ,` · no repo`))],8,tQ))),128))])])):U(``,!0),c.value||n.value.error?(L(),R(`p`,rQ,D(c.value||n.value.error),1)):U(``,!0),B(`div`,iQ,[n.value.resource?(L(),R(`span`,aQ,`Version `+D(n.value.resource.version),1)):U(``,!0),a.value?(L(),z(k(X),{key:1,type:`button`,variant:`ghost`,class:`text-danger`,onClick:p},{default:A(()=>[V(k(ef)), Line truncated
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=CZ(SZ(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=CZ(SZ(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function DZ(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new vZ||null,prettyErrors:t}}function OZ(e,t={}){let{lineCounter:n,prettyErrors:r}=DZ(t),i=new EZ(n?.addNewLine),a=new iZ(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new bX(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(SX(e,n)),o.warnings.forEach(SX(e,n))),o}function kZ(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function AZ(e,t=[]){let n=OZ(e),r=n.errors[0];if(r)return{ok:!1,message:BZ(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!VZ(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,message:`workflow id is required`};let o=i.steps;if(o==null||o===``)return{ok:!1,message:`workflow ${a} has no steps`};if(!Array.isArray(o))return{ok:!1,message:`workflow ${a}: steps must be a list`};if(!o.length)return{ok:!1,message:`workflow ${a} has no steps`};let s=new Map(t.map(e=>[e.name,e])),c=typeof i.repository==`string`&&i.repository.trim()?i.repository.trim():`required`,l=[];for(let[e,t]of o.entries()){let n=`workflow ${a} step ${e+1}`;if(VZ(t)&&VZ(t.parallel)){for(let[e,r]of Object.entries(t.parallel)){if(!Array.isArray(r)||!r.length)return{ok:!1,message:`${n}: branch ${e} needs a list of steps`};for(let[t,i]of r.entries()){let r=jZ(i,`${n} branch ${e} step ${t+1}`,s,c);if(r)return{ok:!1,message:r}}}l.push({index:e+1,type:`parallel`});continue}let r=jZ(t,n,s,c);if(r)return{ok:!1,message:r};l.push({index:e+1,type:t.type.trim()})}return{ok:!0,id:a,steps:l}}function jZ(e,t,n,r){if(!VZ(e)||!HZ(e.type))return`${t} needs a type`;let i=e.type.trim(),a=n.get(i);return n.size&&!a?`${t}: unknown step type "${i}"`:a?.needs_repository&&r!==`required`?`${t}: "${i}" needs a repository, but the workflow's repository is ${r}`:``}function MZ(e){switch(e){case`key`:return`text-fg-muted`;case`string`:return`text-ok`;case`comment`:case`punct`:return`text-fg-subtle`;default:return`text-foreground`}}function NZ(e){return e.split(`
`).map((e,t)=>({number:t+1,text:e,tokens:IZ(e)}))}var PZ=/^(\s*)(-\s+)?/,FZ=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function IZ(e){let{code:t,comment:n}=LZ(e),r=RZ(t);return n&&r.push({text:n,kind:`comment`}),r}function LZ(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t){r===t&&(t=``);continue}if(r===`"`||r===`'`){t=r;continue}if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function RZ(e){if(!e)return[];let t=[],n=PZ.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=FZ.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...zZ(i[4]??``)]):[...t,...zZ(r)]}function zZ(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function BZ(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function VZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HZ(e){return typeof e==`string`&&e.trim()!==``}var UZ={class:`space-y-1.5`},WZ={class:`space-y-1.5`},GZ={class:`flex h-9 flex-nowrap items-center gap-1.5 overflow-hidden`,role:`list`,"aria-label":`Steps`},KZ=[`title`],qZ={key:1,class:`text-xs text-fg-subtle`},JZ={class:`space-y-1.5`},YZ={class:`flex items-baseline gap-2`},XZ={class:`relative overflow-hidden rounded-lg border border-input font-mono text-[13px] leading-6 focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50`},ZZ={"aria-hidden":`true`,class:`pointer-events-none absolute inset-y-0 left-0 w-11 select-none overflow-hidden border-r border-border bg-secondary/40 py-3 text-right`},QZ={"aria-hidden":`true`,class:`pointer-events-none absolute inset-0 overflow-hidden py-3 pr-3 pl-14 break-words whitespace-pre-wrap`},$Z={key:0,class:`text-sm`},eQ={class:`cursor-pointer text-fg-subtle`},tQ={class:`mt-2 flex flex-wrap gap-1.5`,"aria-label":`Step types`},nQ=[`title`],rQ={key:0,class:`text-fg-subtle`},iQ={key:1,class:`text-sm text-danger`,role:`alert`},aQ={class:`flex flex-wrap items-center gap-2 border-t border-border pt-4`},oQ={key:0,class:`mr-auto font-mono text-xs text-fg-subtle`},sQ=M({__name:`WorkflowEditor`,props:{selected:{required:!0},selectedModifiers:{}},emits:[`update:selected`],setup(e){let t=JA(),n=G(()=>t.stateFor(`workflow-definitions`)),r=G(()=>n.value.resource?.value??{definitions:[]}),i=G(()=>t.shippedWorkflows()),a=so(e,`selected`),o=O(``),s=O(``),c=O(``),l=G(()=>i.value.definitions.find(e=>e.id===o.value));function u(e){let t=r.value.definitions.find(t=>t.id===e);o.value=t?.id??e,s.value=t?.yaml??`id: ${e}\nsteps:\n - type: `,c.value=``}j(a,u,{immediate:!0}),j(r,()=>{s.value||u(a.value)});async function d(e){return c.value=``,t.replace(`workflow-definitions`,e)}async function f(){let e=o.value.trim();if(!e){c.value=`Workflow ID is required.`;return}let t=a.value,n=r.value;t&&t!==e&&(n=KA(n,t)),await d(GA(n,{id:e,yaml:s.value}))&&(a.value=e)}async function p(){a.value&&await d(KA(r.value,a.value))&&(a.value=``,o.value=``,s.value=``)}async function m(){l.value&&await d(GA(r.value,UA(l.value)))}let h=G(()=>t.stepTypes()),g=G(()=>AZ(s.value,h.value)),_=G(()=>g.value.ok?g.value.steps:[]),v=G(()=>NZ(s.value)),y=O(0);function b(e){y.value=e.target.scrollTop}return(e,t)=>(L(),R(`form`,{class:`space-y-4`,onSubmit:cu(f,[`prevent`])},[B(`div`,UZ,[V(k(hT),{for:`workflow-id`},{default:A(()=>[...t[2]||=[H(`ID`,-1)]]),_:1}),V(k(Z),{id:`workflow-id`,modelValue:o.value,"onUpdate:modelValue":t[0]||=e=>o.value=e,name:`workflow-id`,required:``,autocomplete:`off`,class:`max-w-sm font-mono`},null,8,[`modelValue`])]),B(`div`,WZ,[t[3]||=B(`span`,{class:`text-sm leading-none font-medium`},`Steps`,-1),B(`div`,GZ,[_.value.length?(L(!0),R(I,{key:0},P(_.value,(e,t)=>(L(),R(I,{key:e.index},[B(`span`,{role:`listitem`,class:`shrink-0 rounded border border-border bg-secondary px-2 py-0.5 font-mono text-xs`,title:e.type},D(e.type),9,KZ),t<_.value.length-1?(L(),z(k(vd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`,"aria-hidden":`true`})):U(``,!0)],64))),128)):(L(),R(`span`,qZ,`No steps yet`))])]),B(`div`,JZ,[B(`div`,YZ,[V(k(hT),{for:`workflow-yaml`},{default:A(()=>[...t[4]||=[H(`YAML`,-1)]]),_:1}),B(`span`,{class:E([`ml-auto text-xs`,g.value.ok?`text-ok`:`text-danger`]),role:`status`},D(g.value.ok?`✓`:`✕`)+` `+D(k(kZ)(g.value)),3)]),B(`div`,XZ,[B(`div`,ZZ,[B(`div`,{style:ve(`transform:translateY(${-y.value}px)`)},[(L(!0),R(I,null,P(v.value,e=>(L(),R(`div`,{key:e.number,class:`min-h-6 pr-2 text-fg-subtle`},D(e.number),1))),128))],4)]),B(`div`,QZ,[B(`div`,{style:ve(`transform:translateY(${-y.value}px)`)},[(L(!0),R(I,null,P(v.value,e=>(L(),R(`div`,{key:e.number,class:`min-h-6`},[(L(!0),R(I,null,P(e.tokens,(e,t)=>(L(),R(`span`,{key:t,class:E(k(MZ)(e.kind))},D(e.text),3))),128))]))),128))],4)]),V(k(ET),{id:`workflow-yaml`,modelValue:s.value,"onUpdate:modelValue":t[1]||=e=>s.value=e,name:`workflow-yaml`,required:``,class:`relative min-h-96 resize-y rounded-none border-0 bg-transparent py-3 pr-3 pl-14 text-[13px] leading-6 text-transparent caret-foreground shadow-none md:text-[13px] focus-visible:ring-0`,spellcheck:`false`,onScroll:b},null,8,[`modelValue`])])]),h.value.length?(L(),R(`details`,$Z,[B(`summary`,eQ,`Step types (`+D(h.value.length)+`)`,1),B(`ul`,tQ,[(L(!0),R(I,null,P(h.value,e=>(L(),R(`li`,{key:e.name,class:`rounded border border-border bg-secondary px-2 py-0.5 font-mono text-xs`,title:e.needs_repository?`Needs a repository`:`Runs without a repository`},[H(D(e.name),1),e.needs_repository?U(``,!0):(L(),R(`span`,rQ,` · no repo`))],8,nQ))),128))])])):U(``,!0),c.value||n.value.error?(L(),R(`p`,iQ,D(c.value||n.value.error),1)):U(``,!0),B(`div`,aQ,[n.value.resource?(L(),R(`span`,oQ,`Version `+D(n.value.resource.version),1)):U(``,!0),a.value?(L(),z(k(X),{key:1,type:`button`,variant:`ghost`,class:`text-danger`,onClick:p},{default:A(()=>[V(k(ef)), Line truncated
+31 -20
View File
@@ -71,31 +71,42 @@ export function parseWorkflowYaml(
: "required";
const chips: WorkflowStepChip[] = [];
for (const [i, step] of steps.entries()) {
if (!isMapping(step) || !isNonEmptyString(step.type)) {
return {
ok: false,
message: `workflow ${id} step ${i + 1} needs a type`,
};
const where = `workflow ${id} step ${i + 1}`;
if (isMapping(step) && isMapping(step.parallel)) {
for (const [branch, branchSteps] of Object.entries(step.parallel)) {
if (!Array.isArray(branchSteps) || !branchSteps.length)
return { ok: false, message: `${where}: branch ${branch} needs a list of steps` };
for (const [j, branchStep] of branchSteps.entries()) {
const problem = checkStepType(branchStep, `${where} branch ${branch} step ${j + 1}`, known, repository);
if (problem) return { ok: false, message: problem };
}
}
chips.push({ index: i + 1, type: "parallel" });
continue;
}
const type = step.type.trim();
const info = known.get(type);
if (known.size && !info) {
return {
ok: false,
message: `workflow ${id} step ${i + 1}: unknown step type "${type}"`,
};
}
if (info?.needs_repository && repository !== "required") {
return {
ok: false,
message: `workflow ${id} step ${i + 1}: "${type}" needs a repository, but the workflow's repository is ${repository}`,
};
}
chips.push({ index: i + 1, type });
const problem = checkStepType(step, where, known, repository);
if (problem) return { ok: false, message: problem };
chips.push({ index: i + 1, type: (step as { type: string }).type.trim() });
}
return { ok: true, id, steps: chips };
}
/** What is wrong with one typed step, or "" when nothing the page can see. */
function checkStepType(
step: unknown,
where: string,
known: Map<string, StepTypeInfo>,
repository: string,
): string {
if (!isMapping(step) || !isNonEmptyString(step.type)) return `${where} needs a type`;
const type = step.type.trim();
const info = known.get(type);
if (known.size && !info) return `${where}: unknown step type "${type}"`;
if (info?.needs_repository && repository !== "required")
return `${where}: "${type}" needs a repository, but the workflow's repository is ${repository}`;
return "";
}
// --- the editor's own rendering ---------------------------------------------
//
// Light syntax colouring, not a parse: every character of the source comes back