From fbb7bb33160aa80e0a1b4920ba6be0a6abe7010e Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 11:04:41 +0100 Subject: [PATCH 1/6] feat: show the plan that a building block run waits to have approved 'meshstack buildingblockrun plan ' follows the waiting run's predecessor to the detect run, prints its logs as text and names it, so that an agent no longer reads the plan from the logs JSON of the run before. Co-Authored-By: Claude Opus 5.5 --- cmd/buildingblock/approve_run.go | 12 +-- .../approve_run_internal_test.go | 15 ++++ cmd/buildingblockrun/buildingblockrun.go | 1 + cmd/buildingblockrun/plan.go | 83 +++++++++++++++++++ skills/meshstack-cli/SKILL.md | 7 +- 5 files changed, 104 insertions(+), 14 deletions(-) create mode 100644 cmd/buildingblockrun/plan.go diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index 27fe7385..ef1156be 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -64,17 +64,7 @@ func (a runAction) approve(ctx context.Context) error { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - if run.Links.Predecessor == nil { - return fmt.Errorf("run %s is waiting for approval, but meshStack does not say which run created its plan", run.Metadata.Uuid) - } - plan, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) - if err != nil { - return err - } - if plan.Links.DownloadLogs == nil { - return fmt.Errorf("cannot read the logs of run %s, which created the plan for run %s", plan.Metadata.Uuid, run.Metadata.Uuid) - } - logs, err := a.meshStack.BuildingBlockRunAction.ReadLogs(ctx, *plan.Links.DownloadLogs) + plan, logs, err := buildingblockrun.ReadPlan(ctx, a.meshStack, run) if err != nil { return err } diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index b4b9e60d..6c791d06 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" + "github.com/meshcloud/meshstack-cli/internal/logs" "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" "github.com/meshcloud/meshstack-cli/internal/testutil/testlogin" ) @@ -79,6 +81,19 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { assert.Empty(t, server.TakeRequests()) }) + t.Run("bbrun plan prints the plan of the waiting run and names the detect run", func(t *testing.T) { + testlogin.LoggedInTo(t, server.URL) + captured := logs.Capture(t) + cmd := buildingblockrun.New() + var stdout bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetArgs([]string{"plan", waitingRun}) + + require.NoError(t, cmd.ExecuteContext(t.Context())) + assert.Equal(t, "Plan: SUCCEEDED\nPlan | + resource \"x\" will be created\n", stdout.String()) + assert.Contains(t, captured.String(), "from the detect run "+planRun) + }) + t.Run("a plan that is not approved stays waiting", func(t *testing.T) { action, asked := newTestRunAction(t, server, "n\n") diff --git a/cmd/buildingblockrun/buildingblockrun.go b/cmd/buildingblockrun/buildingblockrun.go index 38afd40b..c6b66740 100644 --- a/cmd/buildingblockrun/buildingblockrun.go +++ b/cmd/buildingblockrun/buildingblockrun.go @@ -22,6 +22,7 @@ func New() *cobra.Command { cmd.AddCommand(newList()) cmd.AddCommand(newLogs()) + cmd.AddCommand(newPlan()) return cmd } diff --git a/cmd/buildingblockrun/plan.go b/cmd/buildingblockrun/plan.go new file mode 100644 index 00000000..9b9756f5 --- /dev/null +++ b/cmd/buildingblockrun/plan.go @@ -0,0 +1,83 @@ +package buildingblockrun + +import ( + "context" + "encoding/json/v2" + "fmt" + "log/slog" + "uuid" + + "github.com/spf13/cobra" + + "github.com/meshcloud/meshstack-cli/client" + "github.com/meshcloud/meshstack-cli/cmd/internal" +) + +func newPlan() *cobra.Command { + var runUuid uuid.UUID + + return &cobra.Command{ + Use: "plan ", + Short: "Show the plan that a building block run is waiting to have approved", + Long: `Show the plan that a building block run is waiting to have approved, as text. + +A run that waits for approval has no logs of its own. Its plan is in the logs of the run before it, the detect run, which planned the changes. The command prints the logs of the detect run and names it. Give the waiting run by its uuid; 'meshstack buildingblock list' shows it as status.latestRunUuid of a building block whose status.action is APPROVE_RUN. + +'meshstack buildingblock approve-run ' shows the same plan and asks you to approve it.`, + Example: ` meshstack buildingblockrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c + meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep 'Plan:'`, + Args: internal.UuidArg(&runUuid), + RunE: func(cmd *cobra.Command, _ []string) error { + ctx := cmd.Context() + meshStack, err := internal.ResolveClient(ctx) + if err != nil { + return err + } + run, err := ReadRun(ctx, meshStack, runUuid) + if err != nil { + return err + } + detectRun, logs, err := ReadPlan(ctx, meshStack, run) + if err != nil { + return err + } + if err = WriteLogs(cmd.OutOrStdout(), logs); err != nil { + return err + } + if run.Links.Approve == nil { + slog.InfoContext(ctx, fmt.Sprintf("This is the plan from the detect run %s. Run %s is not waiting for approval, or you are not allowed to approve it.", + detectRun.Metadata.Uuid, runUuid)) + return nil + } + slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. Approve it with 'meshstack buildingblock approve-run %s'", + runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid)) + return nil + }, + } +} + +func ReadRun(ctx context.Context, meshStack client.Client, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { + var run client.MeshBuildingBlockRun + raw, err := meshStack.Raw.Get[client.MeshBuildingBlockRun](ctx, runUuid) + if err != nil { + return run, err + } + return run, json.Unmarshal(raw, &run) +} + +// ReadPlan reads the detect run that planned run, and its logs, which hold the plan that run is +// waiting to have approved. +func ReadPlan(ctx context.Context, meshStack client.Client, run client.MeshBuildingBlockRun) (client.MeshBuildingBlockRun, client.MeshBuildingBlockRunLogs, error) { + if run.Links.Predecessor == nil { + return client.MeshBuildingBlockRun{}, client.MeshBuildingBlockRunLogs{}, fmt.Errorf("meshStack does not say which run planned run %s", run.Metadata.Uuid) + } + detectRun, err := meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) + if err != nil { + return detectRun, client.MeshBuildingBlockRunLogs{}, err + } + if detectRun.Links.DownloadLogs == nil { + return detectRun, client.MeshBuildingBlockRunLogs{}, fmt.Errorf("cannot read the logs of the detect run %s, which planned run %s", detectRun.Metadata.Uuid, run.Metadata.Uuid) + } + logs, err := meshStack.BuildingBlockRunAction.ReadLogs(ctx, *detectRun.Links.DownloadLogs) + return detectRun, logs, err +} diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index 18e40ee1..cdaf8f1e 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -34,6 +34,7 @@ skill and the help disagree, trust the help. | `meshstack buildingblockdefinitionversion list --definition ` | `bbdv` | the versions of one definition | | `meshstack buildingblockrun list [--building-block ]` | `bbrun` | runs, newest first | | `meshstack buildingblockrun logs ` | `bbrun` | the steps of one run, with their output | +| `meshstack buildingblockrun plan ` | `bbrun` | the plan that a run waits to have approved | | `meshstack eventlog list` | | event logs, newest first | | `meshstack api [-X method] [--request-json file\|-]` | | any meshStack API call, with this login | | `meshstack api-docs [] [--describe ]` | | what the API docs say about a request | @@ -325,11 +326,11 @@ Every call starts a run, so trigger once and then wait. A definition with `approvalPolicies` does not apply a gated change straight away. meshStack first runs a **preflight**: a dry run, listed with `spec.behavior == "DETECT"`. The `APPLY` run after it waits, with the block's action `APPROVE_RUN`, until someone approves it in meshPanel. The approver sees the -preflight's plan, so read it yourself before you ask for the approval: +preflight's plan, so read it yourself before you ask for the approval. `bbrun plan` takes the waiting +run, the block's `status.latestRunUuid`, and prints the plan of the preflight before it: ```sh -meshstack bbrun logs -o ndjson | - jq -r '.steps[].systemMessage // ""' | +meshstack bbrun plan | grep -E "will be (created|destroyed|updated|replaced)|must be replaced|Plan:" ``` From 36ba02629072fb8607b40acdc12d7b1641bad75d Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 11:06:19 +0100 Subject: [PATCH 2/6] feat: approve a building block run without a terminal 'meshstack buildingblock approve-run --detect-run ' approves the plan of the detect run that 'meshstack buildingblockrun plan' named, without asking. It still approves only that plan: if meshStack has planned the run again since, the approval fails. Co-Authored-By: Claude Opus 5.5 --- cmd/buildingblock/abort_run.go | 2 +- cmd/buildingblock/approve_run.go | 64 ++++++++++++------- .../approve_run_internal_test.go | 20 ++++-- cmd/buildingblock/buildingblock.go | 9 +-- cmd/buildingblockrun/plan.go | 6 +- skills/meshstack-cli/SKILL.md | 9 ++- 6 files changed, 75 insertions(+), 35 deletions(-) diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 4798b138..83ca18c7 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -32,7 +32,7 @@ The command shows the run and asks you to confirm, so it needs a terminal. After Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, false) if err != nil { return err } diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index ef1156be..4590fd14 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -20,6 +20,7 @@ func newApproveRun() *cobra.Command { var ( output internal.OutputFlag buildingBlockUuid uuid.UUID + detectRun uuid.UUID ) cmd := &cobra.Command{ @@ -29,26 +30,32 @@ func newApproveRun() *cobra.Command { The command shows the plan and asks you to approve it, so it needs a terminal. It approves exactly the plan it showed. If meshStack planned the run again in the meantime, the approval fails, and you can run the command again to review the new plan. +Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first. Then pass the uuid of the detect run that it names with --` + detectRunFlagName + `. The command approves the plan without asking, and fails if meshStack has planned the run again since. + A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the approval, the command prints the building block.`, Example: ` meshstack buildingblock approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 - meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, + meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --detect-run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, detectRun != uuid.Nil()) if err != nil { return err } - return action.approve(ctx) + return action.approve(ctx, detectRun) }, } output.RegisterForItem(cmd.Flags()) + cmd.Flags().Var((*internal.UuidFlag)(&detectRun), detectRunFlagName, "approve the plan of the detect run with this uuid without asking") return cmd } -func (a runAction) approve(ctx context.Context) error { +const detectRunFlagName = "detect-run" + +// approve asks to approve the plan unless the caller passes the detect run whose plan it reviewed. +func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { return err @@ -64,37 +71,50 @@ func (a runAction) approve(ctx context.Context) error { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - plan, logs, err := buildingblockrun.ReadPlan(ctx, a.meshStack, run) + plan, reviewAgain := detectRun.String(), fmt.Sprintf("Review the new plan with 'meshstack buildingblockrun plan %s'", run.Metadata.Uuid) + if detectRun == uuid.Nil() { + if plan, err = a.confirmPlan(ctx, run); err != nil || plan == "" { + return err + } + reviewAgain = "Run the command again to review the new plan" + } + err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan) + if httpErr, ok := errors.AsType[client.HttpError](err); ok { + switch httpErr.StatusCode { + case gohttp.StatusConflict: + return fmt.Errorf("the plan of run %s changed after you saw it. %s", run.Metadata.Uuid, reviewAgain) + case gohttp.StatusBadRequest: + return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) + } + } if err != nil { return err } + return a.report(ctx, fmt.Sprintf("Approved the plan of run %s.", run.Metadata.Uuid)) +} + +// confirmPlan shows the plan that run waits to have approved, and returns its detect run if the +// user approves it. +func (a runAction) confirmPlan(ctx context.Context, run client.MeshBuildingBlockRun) (string, error) { + plan, logs, err := buildingblockrun.ReadPlan(ctx, a.meshStack, run) + if err != nil { + return "", err + } var shown bytes.Buffer if err = buildingblockrun.WriteLogs(&shown, logs); err != nil { - return err + return "", err } if err = a.prompt.Printf("Run %d of building block %q is waiting for approval of the plan from run %s:\n\n%s\n", run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, plan.Metadata.Uuid, shown.String()); err != nil { - return err + return "", err } approved, err := a.prompt.Confirm(ctx, "Approve this plan?") if err != nil { - return err + return "", err } if !approved { slog.InfoContext(ctx, fmt.Sprintf("Did not approve run %s.", run.Metadata.Uuid)) - return nil - } - err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan.Metadata.Uuid) - if httpErr, ok := errors.AsType[client.HttpError](err); ok { - switch httpErr.StatusCode { - case gohttp.StatusConflict: - return fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid) - case gohttp.StatusBadRequest: - return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) - } + return "", nil } - if err != nil { - return err - } - return a.report(ctx, fmt.Sprintf("Approved the plan of run %s.", run.Metadata.Uuid)) + return plan.Metadata.Uuid, nil } diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index 6c791d06..0d926898 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -77,7 +77,7 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { cmd.SetErr(io.Discard) cmd.SetArgs([]string{"approve-run", buildingBlockUuid}) - require.EqualError(t, cmd.ExecuteContext(t.Context()), "approve-run needs a terminal, because it asks you to confirm") + require.EqualError(t, cmd.ExecuteContext(t.Context()), "approve-run needs a terminal, because it asks you to confirm. 'buildingblock approve-run --help' shows how to run it without a terminal") assert.Empty(t, server.TakeRequests()) }) @@ -97,7 +97,7 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { t.Run("a plan that is not approved stays waiting", func(t *testing.T) { action, asked := newTestRunAction(t, server, "n\n") - require.NoError(t, action.approve(t.Context())) + require.NoError(t, action.approve(t.Context(), uuid.Nil())) assert.Contains(t, asked.String(), `Plan | + resource "x" will be created`) assert.True(t, strings.HasSuffix(asked.String(), "Approve this plan? [y/N]: "), asked.String()) assert.Empty(t, approvals) @@ -106,15 +106,27 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { t.Run("an approval names the run whose plan was shown", func(t *testing.T) { action, _ := newTestRunAction(t, server, "y\n") - require.NoError(t, action.approve(t.Context())) + require.NoError(t, action.approve(t.Context(), uuid.Nil())) require.Len(t, approvals, 1) assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[0]) }) + t.Run("without a terminal, --detect-run approves the plan of that run without asking", func(t *testing.T) { + testlogin.LoggedInTo(t, server.URL) + cmd := New() + cmd.SetIn(strings.NewReader("")) + cmd.SetOut(io.Discard) + cmd.SetArgs([]string{"approve-run", buildingBlockUuid, "--detect-run", planRun}) + + require.NoError(t, cmd.ExecuteContext(t.Context())) + require.Len(t, approvals, 2) + assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[1]) + }) + t.Run("a plan that changed after it was shown has to be reviewed again", func(t *testing.T) { approveAnswer = gohttp.StatusConflict action, _ := newTestRunAction(t, server, "y\n") - require.EqualError(t, action.approve(t.Context()), "the plan of run "+waitingRun+" changed after you saw it. Run the command again to review the new plan") + require.EqualError(t, action.approve(t.Context(), uuid.Nil()), "the plan of run "+waitingRun+" changed after you saw it. Run the command again to review the new plan") }) } diff --git a/cmd/buildingblock/buildingblock.go b/cmd/buildingblock/buildingblock.go index 084fd853..c415daf5 100644 --- a/cmd/buildingblock/buildingblock.go +++ b/cmd/buildingblock/buildingblock.go @@ -49,11 +49,12 @@ type runAction struct { format internal.OutputFormat } -func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat) (runAction, error) { +// newRunAction needs a terminal to ask for a confirmation unless the caller has confirmed already, +// by naming the plan or the run it decided on, so that the command never acts on one it did not see. +func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat, confirmed bool) (runAction, error) { p := prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()) - // A script cannot approve or abort: the decision belongs to a person who saw the run. - if !p.UsesTerminal() { - return runAction{}, fmt.Errorf("%s needs a terminal, because it asks you to confirm", cmd.Name()) + if !confirmed && !p.UsesTerminal() { + return runAction{}, fmt.Errorf("%s needs a terminal, because it asks you to confirm. '%s --help' shows how to run it without a terminal", cmd.Name(), cmd.CommandPath()) } meshStack, err := internal.ResolveClient(cmd.Context()) if err != nil { diff --git a/cmd/buildingblockrun/plan.go b/cmd/buildingblockrun/plan.go index 9b9756f5..957ab22b 100644 --- a/cmd/buildingblockrun/plan.go +++ b/cmd/buildingblockrun/plan.go @@ -23,7 +23,7 @@ func newPlan() *cobra.Command { A run that waits for approval has no logs of its own. Its plan is in the logs of the run before it, the detect run, which planned the changes. The command prints the logs of the detect run and names it. Give the waiting run by its uuid; 'meshstack buildingblock list' shows it as status.latestRunUuid of a building block whose status.action is APPROVE_RUN. -'meshstack buildingblock approve-run ' shows the same plan and asks you to approve it.`, +To approve the plan without a terminal, pass the uuid of the detect run to 'meshstack buildingblock approve-run --detect-run '. The approval fails if meshStack has planned the run again in the meantime.`, Example: ` meshstack buildingblockrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep 'Plan:'`, Args: internal.UuidArg(&runUuid), @@ -49,8 +49,8 @@ A run that waits for approval has no logs of its own. Its plan is in the logs of detectRun.Metadata.Uuid, runUuid)) return nil } - slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. Approve it with 'meshstack buildingblock approve-run %s'", - runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid)) + slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. Approve it with 'meshstack buildingblock approve-run %s --detect-run %s'", + runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid, detectRun.Metadata.Uuid)) return nil }, } diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index cdaf8f1e..8fa42e8f 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -334,7 +334,14 @@ meshstack bbrun plan | grep -E "will be (created|destroyed|updated|replaced)|must be replaced|Plan:" ``` -Report the `Plan:` line and anything unexpected, and hand the user a deep link (below). A +Report the `Plan:` line and anything unexpected, and hand the user a deep link (below). If the user +asks you to approve it, pass the detect run that `bbrun plan` names. The approval fails if meshStack +has planned the run again since: + +```sh +meshstack bb approve-run --detect-run +``` + A Terraform apply that updates such a block ends with the provider warning `Building block run is waiting for input or approval` — that is the gate, not an error. From 938fece8800af5d13c39e3e98b93c775b6127694 Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 11:06:58 +0100 Subject: [PATCH 3/6] feat: abort a building block run without a terminal 'meshstack buildingblock abort-run --run ' aborts that run of the building block without asking, so that a script can reject a stale waiting run without the raw abort request. Co-Authored-By: Claude Opus 5.5 --- cmd/buildingblock/abort_run.go | 63 +++++++++++++------- cmd/buildingblock/abort_run_internal_test.go | 36 +++++++++++ skills/meshstack-cli/SKILL.md | 6 ++ 3 files changed, 84 insertions(+), 21 deletions(-) create mode 100644 cmd/buildingblock/abort_run_internal_test.go diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 83ca18c7..1900dec9 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" + "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" ) @@ -19,6 +20,7 @@ func newAbortRun() *cobra.Command { var ( output internal.OutputFlag buildingBlockUuid uuid.UUID + runUuid uuid.UUID ) cmd := &cobra.Command{ @@ -26,35 +28,37 @@ func newAbortRun() *cobra.Command { Short: "Abort the latest run of a building block", Long: `Abort the latest run of a building block, or its dry run if the dry run is newer. -The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block.`, +The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block. + +Without a terminal, pass the uuid of the run to abort with --` + runFlagName + `; 'meshstack buildingblockrun list --building-block ' shows it. The command then aborts that run of the building block without asking, also if it is not the latest run.`, Example: ` meshstack buildingblock abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 - meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, + meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format, false) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, runUuid != uuid.Nil()) if err != nil { return err } - return action.abort(ctx) + return action.abort(ctx, runUuid) }, } output.RegisterForItem(cmd.Flags()) + cmd.Flags().Var((*internal.UuidFlag)(&runUuid), runFlagName, "abort the run with this uuid without asking") return cmd } -func (a runAction) abort(ctx context.Context) error { +const runFlagName = "run" + +// abort asks to abort the latest run unless the caller passes the run it decided on. +func (a runAction) abort(ctx context.Context, runUuid uuid.UUID) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { return err } - latest := cmp.Or(block.Links.LatestDryRun, block.Links.LatestRun) - if latest == nil { - return fmt.Errorf("building block %s has no run to abort", a.buildingBlockUuid) - } - run, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *latest) + run, err := a.runToAbort(ctx, block, runUuid) if err != nil { return err } @@ -62,17 +66,19 @@ func (a runAction) abort(ctx context.Context) error { return fmt.Errorf("run %s of building block %s (action %s) has the status %s and cannot be aborted, or you are not allowed to abort it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action, run.Status) } - if err = a.prompt.Printf("Run %d of building block %q is a %s run with the status %s. The building block has the action %s.\n", - run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, run.Spec.Behavior, run.Status, block.Status.Action); err != nil { - return err - } - confirmed, err := a.prompt.Confirm(ctx, "Abort this run?") - if err != nil { - return err - } - if !confirmed { - slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) - return nil + if runUuid == uuid.Nil() { + if err = a.prompt.Printf("Run %d of building block %q is a %s run with the status %s. The building block has the action %s.\n", + run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, run.Spec.Behavior, run.Status, block.Status.Action); err != nil { + return err + } + var confirmed bool + if confirmed, err = a.prompt.Confirm(ctx, "Abort this run?"); err != nil { + return err + } + if !confirmed { + slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) + return nil + } } err = a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { @@ -83,3 +89,18 @@ func (a runAction) abort(ctx context.Context) error { } return a.report(ctx, fmt.Sprintf("Asked meshStack to abort run %s.", run.Metadata.Uuid)) } + +func (a runAction) runToAbort(ctx context.Context, block linkedBuildingBlock, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { + if runUuid != uuid.Nil() { + run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) + if err == nil && run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { + err = fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) + } + return run, err + } + latest := cmp.Or(block.Links.LatestDryRun, block.Links.LatestRun) + if latest == nil { + return client.MeshBuildingBlockRun{}, fmt.Errorf("building block %s has no run to abort", a.buildingBlockUuid) + } + return a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *latest) +} diff --git a/cmd/buildingblock/abort_run_internal_test.go b/cmd/buildingblock/abort_run_internal_test.go new file mode 100644 index 00000000..44a399fc --- /dev/null +++ b/cmd/buildingblock/abort_run_internal_test.go @@ -0,0 +1,36 @@ +package buildingblock + +import ( + "io" + gohttp "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" + "github.com/meshcloud/meshstack-cli/internal/testutil/testlogin" +) + +func TestAbortRunWithoutATerminalAbortsTheRunItIsGiven(t *testing.T) { + const staleRun = "a0000000-0000-4000-8000-000000000003" + server := fakemeshstack.Start(t, fakemeshstack.Options{ + BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}}`)}, + BuildingBlockRuns: []any{meshObject(t, `{"metadata": {"uuid": "`+staleRun+`"}, "status": "IN_PROGRESS", `+ + `"spec": {"buildingBlock": {"uuid": "`+buildingBlockUuid+`"}}, "_links": {"abort": {"href": "`+runsPath+staleRun+`/abort"}}}`)}, + }) + aborted := 0 + server.Route("POST "+runsPath+staleRun+"/abort", func(w gohttp.ResponseWriter, _ *gohttp.Request) { + aborted++ + w.WriteHeader(gohttp.StatusAccepted) + }) + testlogin.LoggedInTo(t, server.URL) + cmd := New() + cmd.SetIn(strings.NewReader("")) + cmd.SetOut(io.Discard) + cmd.SetArgs([]string{"abort-run", buildingBlockUuid, "--run", staleRun}) + + require.NoError(t, cmd.ExecuteContext(t.Context())) + assert.Equal(t, 1, aborted) +} diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index 8fa42e8f..b74d59b7 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -340,6 +340,12 @@ has planned the run again since: ```sh meshstack bb approve-run --detect-run +``` + +To reject a waiting run instead, abort it by its uuid: + +```sh +meshstack bb abort-run --run ``` A Terraform apply that updates such a block ends with the provider warning `Building block run is From b2b823a9cef892211470efe280f2d70bd6644629 Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 11:07:20 +0100 Subject: [PATCH 4/6] feat: name the waiting and the detect run when a wait stops for approval 'meshstack buildingblock wait' and 'trigger-run --wait' now name the run that waits for approval and the detect run whose plan it waits on, and point to 'meshstack buildingblockrun plan'. Co-Authored-By: Claude Opus 5.5 --- cmd/buildingblock/wait_test.go | 6 +++--- cmd/internal/buildingblock/run_wait.go | 3 +++ skills/meshstack-cli/SKILL.md | 4 +++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cmd/buildingblock/wait_test.go b/cmd/buildingblock/wait_test.go index 2202cb49..64de535c 100644 --- a/cmd/buildingblock/wait_test.go +++ b/cmd/buildingblock/wait_test.go @@ -57,9 +57,9 @@ func TestWaitFailsOnAnOutcomeThatNeedsSomeoneToAct(t *testing.T) { assert.Contains(t, stdout, `"action": "REVIEW_ERRORS"`, "the building block still goes to stdout") }) - t.Run("a run that waits for approval fails the wait", func(t *testing.T) { - current.Store(new(buildingBlockWithRun("APPROVE_RUN", "run-2"))) + t.Run("a run that waits for approval fails the wait and names the waiting and the detect run", func(t *testing.T) { + current.Store(new(strings.Replace(buildingBlockWithRun("APPROVE_RUN", "run-2"), `"latestRunUuid"`, `"latestDryRunUuid": "run-1", "latestRunUuid"`, 1))) _, err := run(before, "wait", waitedBuildingBlock, "--before=-") - require.ErrorContains(t, err, "is paused at action APPROVE_RUN") + require.ErrorContains(t, err, "run run-2 of building block "+waitedBuildingBlock+" is waiting for approval of the plan from the detect run run-1") }) } diff --git a/cmd/internal/buildingblock/run_wait.go b/cmd/internal/buildingblock/run_wait.go index 57ec7780..3013d63d 100644 --- a/cmd/internal/buildingblock/run_wait.go +++ b/cmd/internal/buildingblock/run_wait.go @@ -74,6 +74,9 @@ func (w RunWait) Outcome(block *client.MeshBuildingBlockV2) error { return w.StartFailure(block) case status.RunFailed(): err = fmt.Errorf("the run of building block %s ended with action %s", w.buildingBlockUuid, status.Action) + case status.Action == client.BuildingBlockActionApproveRun: + err = fmt.Errorf("run %s of building block %s is waiting for approval of the plan from the detect run %s. Review the plan with 'meshstack buildingblockrun plan %s'", + status.GetLatestRunUuid(), w.buildingBlockUuid, status.GetLatestDryRunUuid(), status.GetLatestRunUuid()) case status.IsWaitingForInput(): err = fmt.Errorf("the run of building block %s is paused at action %s and continues only after someone acts on it", w.buildingBlockUuid, status.Action) } diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index b74d59b7..9e0363e2 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -380,7 +380,9 @@ meshstack api -X PUT /api/meshobjects/meshbuildingblocks/ --request-json b meshstack bb wait --before=- ``` -Both fail, and name the action, when the run failed or waits for a person or a dependency. +Both fail, and name the action, when the run failed or waits for a person or a dependency. When the +run waits for approval, they name the waiting run and the detect run that planned it: see +[Approval gates and preflight runs](#approval-gates-and-preflight-runs). A block that deletes itself at the end of its run, like a starterkit, is gone before `bb wait` can read the outcome. Poll its runs instead: `meshstack bbrun list --building-block --workspace From c2fb05314652824633c41c034b6810d9ada59e03 Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 15:35:39 +0100 Subject: [PATCH 5/6] fix: correct the messages and tests of the approval commands A review of the pull request found these: - 'bb wait' and 'trigger-run --wait' named an empty detect run at APPROVE_RUN, because meshStack sends status.latestDryRunUuid as null while the waiting run is the newest run. They name the action again and point to 'bbrun plan ', which finds the detect run. - 'approve-run --detect-run': the 409 message no longer says the plan changed when the caller named the wrong detect run, and it says that the user has to see a new plan. The command prints how to follow the approved run. - 'abort-run --run' no longer reads the building block first, and its tests cover a run in progress, a run that cannot be aborted and a run of another building block. - 'bbrun plan': the error for a run without a predecessor says which run to give, the approve hint asks for the user's go-ahead, and the documented grep skips the step status lines. - The meshstack-cli skill describes how to wait after an approval, asks for the user's go-ahead before an approval or an abort, no longer leaves a stray line behind the abort example, and lists the two commands in its table. Co-Authored-By: Claude Sonnet 5.5 --- cmd/buildingblock/abort_run.go | 77 +++++++++++-------- cmd/buildingblock/abort_run_internal_test.go | 74 ++++++++++++++---- cmd/buildingblock/approve_run.go | 21 +++-- .../approve_run_internal_test.go | 18 +++++ cmd/buildingblock/buildingblock.go | 5 +- cmd/buildingblock/wait_test.go | 7 +- cmd/buildingblockrun/plan.go | 14 ++-- cmd/internal/buildingblock/run_wait.go | 9 ++- skills/meshstack-cli/SKILL.md | 49 ++++++++---- 9 files changed, 192 insertions(+), 82 deletions(-) diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 1900dec9..1c94e619 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -30,17 +30,21 @@ func newAbortRun() *cobra.Command { The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block. -Without a terminal, pass the uuid of the run to abort with --` + runFlagName + `; 'meshstack buildingblockrun list --building-block ' shows it. The command then aborts that run of the building block without asking, also if it is not the latest run.`, +Without a terminal, pass the uuid of the run to abort with --` + runFlagName + `; 'meshstack buildingblockrun list --building-block ' shows it. The command aborts that run of the building block without asking. The run can wait for approval or be in progress, and it does not have to be the latest run. A run that is already applying changes may leave them half done.`, Example: ` meshstack buildingblock abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format, runUuid != uuid.Nil()) + named := runUuid != uuid.Nil() + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, named) if err != nil { return err } - return action.abort(ctx, runUuid) + if named { + return action.abortNamedRun(ctx, runUuid) + } + return action.abort(ctx) }, } @@ -52,13 +56,16 @@ Without a terminal, pass the uuid of the run to abort with --` + runFlagName + ` const runFlagName = "run" -// abort asks to abort the latest run unless the caller passes the run it decided on. -func (a runAction) abort(ctx context.Context, runUuid uuid.UUID) error { +func (a runAction) abort(ctx context.Context) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { return err } - run, err := a.runToAbort(ctx, block, runUuid) + latest := cmp.Or(block.Links.LatestDryRun, block.Links.LatestRun) + if latest == nil { + return fmt.Errorf("building block %s has no run to abort", a.buildingBlockUuid) + } + run, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *latest) if err != nil { return err } @@ -66,41 +73,43 @@ func (a runAction) abort(ctx context.Context, runUuid uuid.UUID) error { return fmt.Errorf("run %s of building block %s (action %s) has the status %s and cannot be aborted, or you are not allowed to abort it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action, run.Status) } - if runUuid == uuid.Nil() { - if err = a.prompt.Printf("Run %d of building block %q is a %s run with the status %s. The building block has the action %s.\n", - run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, run.Spec.Behavior, run.Status, block.Status.Action); err != nil { - return err - } - var confirmed bool - if confirmed, err = a.prompt.Confirm(ctx, "Abort this run?"); err != nil { - return err - } - if !confirmed { - slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) - return nil - } + if err = a.prompt.Printf("Run %d of building block %q is a %s run with the status %s. The building block has the action %s.\n", + run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, run.Spec.Behavior, run.Status, block.Status.Action); err != nil { + return err } - err = a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) - if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { - return fmt.Errorf("run %s can no longer be aborted", run.Metadata.Uuid) + confirmed, err := a.prompt.Confirm(ctx, "Abort this run?") + if err != nil { + return err } + if !confirmed { + slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) + return nil + } + return a.sendAbort(ctx, run) +} + +func (a runAction) abortNamedRun(ctx context.Context, runUuid uuid.UUID) error { + run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) if err != nil { return err } - return a.report(ctx, fmt.Sprintf("Asked meshStack to abort run %s.", run.Metadata.Uuid)) + if run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { + return fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) + } + if run.Links.Abort == nil { + return fmt.Errorf("run %s of building block %s has the status %s and cannot be aborted, or you are not allowed to abort it", + runUuid, a.buildingBlockUuid, run.Status) + } + return a.sendAbort(ctx, run) } -func (a runAction) runToAbort(ctx context.Context, block linkedBuildingBlock, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { - if runUuid != uuid.Nil() { - run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) - if err == nil && run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { - err = fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) - } - return run, err +func (a runAction) sendAbort(ctx context.Context, run client.MeshBuildingBlockRun) error { + err := a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) + if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { + return fmt.Errorf("run %s can no longer be aborted", run.Metadata.Uuid) } - latest := cmp.Or(block.Links.LatestDryRun, block.Links.LatestRun) - if latest == nil { - return client.MeshBuildingBlockRun{}, fmt.Errorf("building block %s has no run to abort", a.buildingBlockUuid) + if err != nil { + return err } - return a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *latest) + return a.report(ctx, fmt.Sprintf("Asked meshStack to abort run %s.", run.Metadata.Uuid)) } diff --git a/cmd/buildingblock/abort_run_internal_test.go b/cmd/buildingblock/abort_run_internal_test.go index 44a399fc..7b122d84 100644 --- a/cmd/buildingblock/abort_run_internal_test.go +++ b/cmd/buildingblock/abort_run_internal_test.go @@ -14,23 +14,69 @@ import ( ) func TestAbortRunWithoutATerminalAbortsTheRunItIsGiven(t *testing.T) { - const staleRun = "a0000000-0000-4000-8000-000000000003" + const ( + waitingRun = "a0000000-0000-4000-8000-000000000003" + inProgressRun = "a0000000-0000-4000-8000-000000000004" + finishedRun = "a0000000-0000-4000-8000-000000000005" + runOfOtherBlock = "a0000000-0000-4000-8000-000000000006" + otherBuildingBlock = "b1d2c3e4-0000-4000-8000-000000000009" + ) + runWithLinks := func(runUuid, ofBuildingBlock, status string, linkNames ...string) any { + var links []string + for _, name := range linkNames { + links = append(links, `"`+name+`": {"href": "`+runsPath+runUuid+`/`+name+`"}`) + } + return meshObject(t, `{"metadata": {"uuid": "`+runUuid+`"}, "status": "`+status+`", `+ + `"spec": {"buildingBlock": {"uuid": "`+ofBuildingBlock+`"}}, "_links": {`+strings.Join(links, ", ")+`}}`) + } server := fakemeshstack.Start(t, fakemeshstack.Options{ BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}}`)}, - BuildingBlockRuns: []any{meshObject(t, `{"metadata": {"uuid": "`+staleRun+`"}, "status": "IN_PROGRESS", `+ - `"spec": {"buildingBlock": {"uuid": "`+buildingBlockUuid+`"}}, "_links": {"abort": {"href": "`+runsPath+staleRun+`/abort"}}}`)}, - }) - aborted := 0 - server.Route("POST "+runsPath+staleRun+"/abort", func(w gohttp.ResponseWriter, _ *gohttp.Request) { - aborted++ - w.WriteHeader(gohttp.StatusAccepted) + BuildingBlockRuns: []any{ + runWithLinks(waitingRun, buildingBlockUuid, "IN_PROGRESS", "approve", "abort"), + runWithLinks(inProgressRun, buildingBlockUuid, "IN_PROGRESS", "abort"), + runWithLinks(finishedRun, buildingBlockUuid, "SUCCEEDED"), + runWithLinks(runOfOtherBlock, otherBuildingBlock, "IN_PROGRESS", "abort"), + }, }) + var aborted []string + for _, runUuid := range []string{waitingRun, inProgressRun, runOfOtherBlock} { + server.Route("POST "+runsPath+runUuid+"/abort", func(w gohttp.ResponseWriter, _ *gohttp.Request) { + aborted = append(aborted, runUuid) + w.WriteHeader(gohttp.StatusAccepted) + }) + } testlogin.LoggedInTo(t, server.URL) - cmd := New() - cmd.SetIn(strings.NewReader("")) - cmd.SetOut(io.Discard) - cmd.SetArgs([]string{"abort-run", buildingBlockUuid, "--run", staleRun}) + abortRun := func(stdin string, args ...string) error { + cmd := New() + cmd.SetIn(strings.NewReader(stdin)) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs(append([]string{"abort-run", buildingBlockUuid}, args...)) + return cmd.ExecuteContext(t.Context()) + } + + t.Run("without a terminal and without --run, nothing is asked and nothing is aborted", func(t *testing.T) { + require.EqualError(t, abortRun("y\n"), "abort-run needs a terminal, because it asks you to confirm. 'buildingblock abort-run --help' shows how to run it without a terminal") + assert.Empty(t, server.TakeRequests()) + }) + + t.Run("--run aborts a run that waits for approval", func(t *testing.T) { + require.NoError(t, abortRun("", "--run", waitingRun)) + assert.Equal(t, []string{waitingRun}, aborted) + }) - require.NoError(t, cmd.ExecuteContext(t.Context())) - assert.Equal(t, 1, aborted) + t.Run("--run aborts a run that is in progress", func(t *testing.T) { + require.NoError(t, abortRun("", "--run", inProgressRun)) + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) + + t.Run("--run does not abort a run that cannot be aborted", func(t *testing.T) { + require.ErrorContains(t, abortRun("", "--run", finishedRun), "has the status SUCCEEDED and cannot be aborted") + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) + + t.Run("--run does not abort a run of another building block", func(t *testing.T) { + require.ErrorContains(t, abortRun("", "--run", runOfOtherBlock), "belongs to building block "+otherBuildingBlock) + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) } diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index 4590fd14..532c77e6 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -30,7 +30,7 @@ func newApproveRun() *cobra.Command { The command shows the plan and asks you to approve it, so it needs a terminal. It approves exactly the plan it showed. If meshStack planned the run again in the meantime, the approval fails, and you can run the command again to review the new plan. -Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first. Then pass the uuid of the detect run that it names with --` + detectRunFlagName + `. The command approves the plan without asking, and fails if meshStack has planned the run again since. +Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first, and approve it only if the user allows it. Then pass the uuid of the detect run that this command prints with --` + detectRunFlagName + `. The command approves that plan without asking. If meshStack has planned the run again since, the approval fails, and the user has to see the new plan before you approve it. A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the approval, the command prints the building block.`, Example: ` meshstack buildingblock approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 @@ -54,7 +54,6 @@ A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock const detectRunFlagName = "detect-run" -// approve asks to approve the plan unless the caller passes the detect run whose plan it reviewed. func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { @@ -71,18 +70,17 @@ func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - plan, reviewAgain := detectRun.String(), fmt.Sprintf("Review the new plan with 'meshstack buildingblockrun plan %s'", run.Metadata.Uuid) + plan := detectRun.String() if detectRun == uuid.Nil() { if plan, err = a.confirmPlan(ctx, run); err != nil || plan == "" { return err } - reviewAgain = "Run the command again to review the new plan" } err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan) if httpErr, ok := errors.AsType[client.HttpError](err); ok { switch httpErr.StatusCode { case gohttp.StatusConflict: - return fmt.Errorf("the plan of run %s changed after you saw it. %s", run.Metadata.Uuid, reviewAgain) + return planChanged(run, detectRun) case gohttp.StatusBadRequest: return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) } @@ -90,7 +88,18 @@ func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { if err != nil { return err } - return a.report(ctx, fmt.Sprintf("Approved the plan of run %s.", run.Metadata.Uuid)) + return a.report(ctx, fmt.Sprintf("Approved the plan of run %s. Follow the run with 'meshstack buildingblockrun logs %s --follow'.", run.Metadata.Uuid, run.Metadata.Uuid)) +} + +// planChanged explains the 409 of meshStack, which it sends for any plan that is not the one the run +// waits for now. A caller that named the detect run may also have named the wrong one. +func planChanged(run client.MeshBuildingBlockRun, detectRun uuid.UUID) error { + if detectRun == uuid.Nil() { + return fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid) + } + return fmt.Errorf("run %s waits for another plan than the one of detect run %s: meshStack planned the run again, or that is not its detect run. "+ + "An earlier go-ahead does not count for the new plan. Show the user the plan from 'meshstack buildingblockrun plan %s', and approve it only if the user allows it", + run.Metadata.Uuid, detectRun, run.Metadata.Uuid) } // confirmPlan shows the plan that run waits to have approved, and returns its detect run if the diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index 0d926898..21b2e390 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -92,6 +92,7 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { require.NoError(t, cmd.ExecuteContext(t.Context())) assert.Equal(t, "Plan: SUCCEEDED\nPlan | + resource \"x\" will be created\n", stdout.String()) assert.Contains(t, captured.String(), "from the detect run "+planRun) + assert.Contains(t, captured.String(), "approve-run "+buildingBlockUuid+" --detect-run "+planRun+"'") }) t.Run("a plan that is not approved stays waiting", func(t *testing.T) { @@ -123,6 +124,23 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[1]) }) + t.Run("--detect-run of another plan is refused, and the user has to see the plan", func(t *testing.T) { + const otherRun = "a0000000-0000-4000-8000-000000000009" + approveAnswer = gohttp.StatusConflict + testlogin.LoggedInTo(t, server.URL) + cmd := New() + cmd.SetIn(strings.NewReader("")) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs([]string{"approve-run", buildingBlockUuid, "--detect-run", otherRun}) + + err := cmd.ExecuteContext(t.Context()) + require.ErrorContains(t, err, "run "+waitingRun+" waits for another plan than the one of detect run "+otherRun) + require.ErrorContains(t, err, "Show the user the plan from 'meshstack buildingblockrun plan "+waitingRun+"'") + require.Len(t, approvals, 3) + assert.JSONEq(t, `{"predecessorRunUuid": "`+otherRun+`"}`, approvals[2]) + }) + t.Run("a plan that changed after it was shown has to be reviewed again", func(t *testing.T) { approveAnswer = gohttp.StatusConflict action, _ := newTestRunAction(t, server, "y\n") diff --git a/cmd/buildingblock/buildingblock.go b/cmd/buildingblock/buildingblock.go index c415daf5..edda7666 100644 --- a/cmd/buildingblock/buildingblock.go +++ b/cmd/buildingblock/buildingblock.go @@ -49,8 +49,9 @@ type runAction struct { format internal.OutputFormat } -// newRunAction needs a terminal to ask for a confirmation unless the caller has confirmed already, -// by naming the plan or the run it decided on, so that the command never acts on one it did not see. +// newRunAction needs a terminal to ask for a confirmation, unless the caller names the plan to approve +// or the run to abort. A name binds the command to that plan or run, but does not show that anyone +// has reviewed it. func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat, confirmed bool) (runAction, error) { p := prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()) if !confirmed && !p.UsesTerminal() { diff --git a/cmd/buildingblock/wait_test.go b/cmd/buildingblock/wait_test.go index 64de535c..4dda1220 100644 --- a/cmd/buildingblock/wait_test.go +++ b/cmd/buildingblock/wait_test.go @@ -57,9 +57,10 @@ func TestWaitFailsOnAnOutcomeThatNeedsSomeoneToAct(t *testing.T) { assert.Contains(t, stdout, `"action": "REVIEW_ERRORS"`, "the building block still goes to stdout") }) - t.Run("a run that waits for approval fails the wait and names the waiting and the detect run", func(t *testing.T) { - current.Store(new(strings.Replace(buildingBlockWithRun("APPROVE_RUN", "run-2"), `"latestRunUuid"`, `"latestDryRunUuid": "run-1", "latestRunUuid"`, 1))) + t.Run("a run that waits for approval fails the wait with its action and points to its plan", func(t *testing.T) { + current.Store(new(buildingBlockWithRun("APPROVE_RUN", "run-2"))) _, err := run(before, "wait", waitedBuildingBlock, "--before=-") - require.ErrorContains(t, err, "run run-2 of building block "+waitedBuildingBlock+" is waiting for approval of the plan from the detect run run-1") + require.ErrorContains(t, err, "is paused at action APPROVE_RUN") + require.ErrorContains(t, err, "meshstack buildingblockrun plan run-2") }) } diff --git a/cmd/buildingblockrun/plan.go b/cmd/buildingblockrun/plan.go index 957ab22b..cd41c8d9 100644 --- a/cmd/buildingblockrun/plan.go +++ b/cmd/buildingblockrun/plan.go @@ -21,11 +21,13 @@ func newPlan() *cobra.Command { Short: "Show the plan that a building block run is waiting to have approved", Long: `Show the plan that a building block run is waiting to have approved, as text. -A run that waits for approval has no logs of its own. Its plan is in the logs of the run before it, the detect run, which planned the changes. The command prints the logs of the detect run and names it. Give the waiting run by its uuid; 'meshstack buildingblock list' shows it as status.latestRunUuid of a building block whose status.action is APPROVE_RUN. +A run that waits for approval has no logs of its own. Its plan is in the logs of the run before it, the detect run, which planned the changes. The command prints the logs of the detect run, and a line with the uuid of the detect run. Give the waiting run by its uuid; 'meshstack buildingblock list' shows it as status.latestRunUuid of a building block whose status.action is APPROVE_RUN. -To approve the plan without a terminal, pass the uuid of the detect run to 'meshstack buildingblock approve-run --detect-run '. The approval fails if meshStack has planned the run again in the meantime.`, +The command prints a line ': ' for each step, and the lines of a step's messages after ' |'. Filter on '|' to read only the messages. + +To approve the plan without a terminal, pass the uuid of the detect run to 'meshstack buildingblock approve-run --detect-run ', and approve only if the user allows it. The approval fails if meshStack has planned the run again in the meantime.`, Example: ` meshstack buildingblockrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c - meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep 'Plan:'`, + meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep '| Plan:'`, Args: internal.UuidArg(&runUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() @@ -49,7 +51,7 @@ To approve the plan without a terminal, pass the uuid of the detect run to 'mesh detectRun.Metadata.Uuid, runUuid)) return nil } - slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. Approve it with 'meshstack buildingblock approve-run %s --detect-run %s'", + slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. If the user allows it, approve the plan with 'meshstack buildingblock approve-run %s --detect-run %s'", runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid, detectRun.Metadata.Uuid)) return nil }, @@ -69,7 +71,9 @@ func ReadRun(ctx context.Context, meshStack client.Client, runUuid uuid.UUID) (c // waiting to have approved. func ReadPlan(ctx context.Context, meshStack client.Client, run client.MeshBuildingBlockRun) (client.MeshBuildingBlockRun, client.MeshBuildingBlockRunLogs, error) { if run.Links.Predecessor == nil { - return client.MeshBuildingBlockRun{}, client.MeshBuildingBlockRunLogs{}, fmt.Errorf("meshStack does not say which run planned run %s", run.Metadata.Uuid) + return client.MeshBuildingBlockRun{}, client.MeshBuildingBlockRunLogs{}, fmt.Errorf( + "run %s has no predecessor, so no plan waits for its approval. Give the run that waits for approval: the status.latestRunUuid of a building block whose status.action is APPROVE_RUN", + run.Metadata.Uuid) } detectRun, err := meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) if err != nil { diff --git a/cmd/internal/buildingblock/run_wait.go b/cmd/internal/buildingblock/run_wait.go index 3013d63d..405c6b08 100644 --- a/cmd/internal/buildingblock/run_wait.go +++ b/cmd/internal/buildingblock/run_wait.go @@ -74,11 +74,14 @@ func (w RunWait) Outcome(block *client.MeshBuildingBlockV2) error { return w.StartFailure(block) case status.RunFailed(): err = fmt.Errorf("the run of building block %s ended with action %s", w.buildingBlockUuid, status.Action) - case status.Action == client.BuildingBlockActionApproveRun: - err = fmt.Errorf("run %s of building block %s is waiting for approval of the plan from the detect run %s. Review the plan with 'meshstack buildingblockrun plan %s'", - status.GetLatestRunUuid(), w.buildingBlockUuid, status.GetLatestDryRunUuid(), status.GetLatestRunUuid()) case status.IsWaitingForInput(): err = fmt.Errorf("the run of building block %s is paused at action %s and continues only after someone acts on it", w.buildingBlockUuid, status.Action) + if status.Action == client.BuildingBlockActionApproveRun { + // status.latestDryRunUuid is null here, because the waiting run is newer than its detect run. + // 'bbrun plan' finds the detect run through the waiting run's predecessor. + waiting := status.GetLatestRunUuid() + err = fmt.Errorf("%w. Run %s waits for approval: review its plan with 'meshstack buildingblockrun plan %s'", err, waiting, waiting) + } } return withMeshPanelLink(err, block) } diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index 9e0363e2..eb33b4b0 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -6,8 +6,8 @@ description: > (metadata/spec/status) that makes filtering cheap, and `meshstack api` / `api-docs` for everything the other commands do not cover. Use when asked to list, inspect or debug workspaces, building blocks, building block definitions or building block runs, to report on the health of - the building blocks a platform team provides, to trigger or wait for a run, or to order a - building block. + the building blocks a platform team provides, to trigger or wait for a run, to review and approve + a run that waits for approval, to abort a run, or to order a building block. --- # meshStack CLI @@ -29,6 +29,8 @@ skill and the help disagree, trust the help. | `meshstack buildingblock list` | `bb` | building blocks (deployed instances), newest first | | `meshstack buildingblock trigger-run ` | `bb` | starts a run of one block | | `meshstack buildingblock wait --before ` | `bb` | waits until the run of one block has ended | +| `meshstack buildingblock approve-run --detect-run ` | `bb` | approves the plan that `bbrun plan` shows, once the user allows it | +| `meshstack buildingblock abort-run --run ` | `bb` | aborts one run of a block, also one in progress | | `meshstack buildingblock tfstate` | `bb` | reads and writes the OpenTofu state of one block | | `meshstack buildingblockdefinition list` | `bbd` | definitions — what platform teams offer | | `meshstack buildingblockdefinitionversion list --definition ` | `bbdv` | the versions of one definition | @@ -318,38 +320,55 @@ meshstack bb trigger-run -o ndjson | jq -r '.status.latestRunUuid' It waits until meshStack has started the run, and prints the block; `status.latestRunUuid` names the new run. It never approves: when the definition gates manual triggers (`spec.approvalPolicies.manualTriggers`), meshStack starts a preflight run, which -`status.latestDryRunUuid` names, and the run after it waits until a person approves it in meshPanel. +`status.latestDryRunUuid` names at first, and the run after it waits until a person approves it, in +meshPanel or with `bb approve-run` (see +[Approval gates and preflight runs](#approval-gates-and-preflight-runs)). Every call starts a run, so trigger once and then wait. ## Approval gates and preflight runs A definition with `approvalPolicies` does not apply a gated change straight away. meshStack first runs a **preflight**: a dry run, listed with `spec.behavior == "DETECT"`. The `APPLY` run after it -waits, with the block's action `APPROVE_RUN`, until someone approves it in meshPanel. The approver sees the -preflight's plan, so read it yourself before you ask for the approval. `bbrun plan` takes the waiting -run, the block's `status.latestRunUuid`, and prints the plan of the preflight before it: +waits, with the block's action `APPROVE_RUN`, until someone approves it in meshPanel or with +`bb approve-run`. The approver sees the preflight's plan, so read it yourself before you ask for the +approval. `bbrun plan` takes the waiting run, the block's `status.latestRunUuid`, and prints the plan +of the preflight before it. The command prints a line `: ` for each step and the lines +of a step's messages after ` |`, so filter on the bar: ```sh meshstack bbrun plan | - grep -E "will be (created|destroyed|updated|replaced)|must be replaced|Plan:" + grep -E '\| .*(will be (created|destroyed|updated|replaced)|must be replaced|Plan:)' ``` -Report the `Plan:` line and anything unexpected, and hand the user a deep link (below). If the user -asks you to approve it, pass the detect run that `bbrun plan` names. The approval fails if meshStack -has planned the run again since: +Report the `Plan:` line and anything unexpected, and hand the user a deep link (below). A +Terraform apply that updates such a block ends with the provider warning `Building block run is +waiting for input or approval` — that is the gate, not an error. + +Approve the run only if the user allows it for this plan. Then pass the detect run that `bbrun plan` +prints. The approval fails if meshStack has planned the run again since. The plan has changed then: +show the user the new plan, and approve only if they allow it again. ```sh meshstack bb approve-run --detect-run ``` -To reject a waiting run instead, abort it by its uuid: +The command prints the block as it reads it right after the approval, which is no `--before` for +`bb wait`. To wait for the approved run, follow its logs. The command exits with status 0 if the run +succeeded: + +```sh +meshstack bbrun logs --follow +``` + +To reject a waiting run instead, if the user asks you to, abort it by its uuid. The command does not +ask, and it aborts a run in any state: if someone approved the run since you read the block, the +apply in progress stops, and its changes can stay half done. So read the block again just before, +and abort only if its `status.action` is still `APPROVE_RUN`. The same command aborts a run in +progress, if the user asks you to: ```sh meshstack bb abort-run --run ``` - A -Terraform apply that updates such a block ends with the provider warning `Building block run is -waiting for input or approval` — that is the gate, not an error. ## Linking into meshPanel @@ -381,7 +400,7 @@ meshstack api -X PUT /api/meshobjects/meshbuildingblocks/ --request-json b ``` Both fail, and name the action, when the run failed or waits for a person or a dependency. When the -run waits for approval, they name the waiting run and the detect run that planned it: see +run waits for approval, they also point to `bbrun plan` for the waiting run: see [Approval gates and preflight runs](#approval-gates-and-preflight-runs). A block that deletes itself at the end of its run, like a starterkit, is gone before `bb wait` can From 44399e2db3a80d95393198968c5fedc2e5fbf5a0 Mon Sep 17 00:00:00 2001 From: Jo Schwandke Date: Fri, 13 Nov 2026 16:53:10 +0100 Subject: [PATCH 6/6] feat: name the run of approve-run with --run, as abort-run does 'approve-run' without a terminal takes the run to approve with --run, together with --detect-run for the plan the caller reviewed, so that both commands name the run they act on the same way. The two flags belong together. - Both commands read the named run, check that it belongs to the building block, and act on it. 'approve-run' refuses a run that does not wait for approval any more, and no longer reads the building block first. - Both commands detect the flag with Flags().Changed, so an all-zero uuid is not taken for a missing flag. - 'bbrun plan', the help texts and the skill show the new command line. - The tests cover the flag pair, a run that does not wait for approval and a run of another building block. Co-Authored-By: Claude Sonnet 5.5 --- cmd/buildingblock/abort_run.go | 10 +-- cmd/buildingblock/approve_run.go | 60 +++++++++++------ .../approve_run_internal_test.go | 66 +++++++++++++------ cmd/buildingblock/buildingblock.go | 15 +++++ cmd/buildingblockrun/plan.go | 6 +- skills/meshstack-cli/SKILL.md | 10 +-- 6 files changed, 111 insertions(+), 56 deletions(-) diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 1c94e619..4c3d295a 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -12,7 +12,6 @@ import ( "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" - "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" ) @@ -36,7 +35,7 @@ Without a terminal, pass the uuid of the run to abort with --` + runFlagName + ` Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - named := runUuid != uuid.Nil() + named := cmd.Flags().Changed(runFlagName) action, err := newRunAction(cmd, buildingBlockUuid, output.Format, named) if err != nil { return err @@ -54,8 +53,6 @@ Without a terminal, pass the uuid of the run to abort with --` + runFlagName + ` return cmd } -const runFlagName = "run" - func (a runAction) abort(ctx context.Context) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { @@ -89,13 +86,10 @@ func (a runAction) abort(ctx context.Context) error { } func (a runAction) abortNamedRun(ctx context.Context, runUuid uuid.UUID) error { - run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) + run, err := a.readNamedRun(ctx, runUuid) if err != nil { return err } - if run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { - return fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) - } if run.Links.Abort == nil { return fmt.Errorf("run %s of building block %s has the status %s and cannot be aborted, or you are not allowed to abort it", runUuid, a.buildingBlockUuid, run.Status) diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index 532c77e6..cdd06400 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -20,6 +20,7 @@ func newApproveRun() *cobra.Command { var ( output internal.OutputFlag buildingBlockUuid uuid.UUID + runUuid uuid.UUID detectRun uuid.UUID ) @@ -30,31 +31,37 @@ func newApproveRun() *cobra.Command { The command shows the plan and asks you to approve it, so it needs a terminal. It approves exactly the plan it showed. If meshStack planned the run again in the meantime, the approval fails, and you can run the command again to review the new plan. -Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first, and approve it only if the user allows it. Then pass the uuid of the detect run that this command prints with --` + detectRunFlagName + `. The command approves that plan without asking. If meshStack has planned the run again since, the approval fails, and the user has to see the new plan before you approve it. +Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first, and approve it only if the user allows it. Then pass the uuid of that run with --` + runFlagName + ` and the uuid of the detect run that 'meshstack buildingblockrun plan' prints with --` + detectRunFlagName + `. The command approves that plan of that run without asking. If meshStack has planned the run again since, the approval fails, and the user has to see the new plan before you approve it. A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the approval, the command prints the building block.`, Example: ` meshstack buildingblock approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 - meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --detect-run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c`, + meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c --detect-run 2c8d1e4f-6a7b-4c3d-8e9f-0a1b2c3d4e5f`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format, detectRun != uuid.Nil()) + named := cmd.Flags().Changed(runFlagName) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, named) if err != nil { return err } - return action.approve(ctx, detectRun) + if named { + return action.approveNamedRun(ctx, runUuid, detectRun) + } + return action.approve(ctx) }, } output.RegisterForItem(cmd.Flags()) - cmd.Flags().Var((*internal.UuidFlag)(&detectRun), detectRunFlagName, "approve the plan of the detect run with this uuid without asking") + cmd.Flags().Var((*internal.UuidFlag)(&runUuid), runFlagName, "approve the run with this uuid without asking, together with --"+detectRunFlagName) + cmd.Flags().Var((*internal.UuidFlag)(&detectRun), detectRunFlagName, "approve the plan of the detect run with this uuid, together with --"+runFlagName) + cmd.MarkFlagsRequiredTogether(runFlagName, detectRunFlagName) return cmd } const detectRunFlagName = "detect-run" -func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { +func (a runAction) approve(ctx context.Context) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { return err @@ -70,17 +77,35 @@ func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - plan := detectRun.String() - if detectRun == uuid.Nil() { - if plan, err = a.confirmPlan(ctx, run); err != nil || plan == "" { - return err - } + plan, err := a.confirmPlan(ctx, run) + if err != nil || plan == "" { + return err } - err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan) + return a.sendApproval(ctx, run, plan, + fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid)) +} + +func (a runAction) approveNamedRun(ctx context.Context, runUuid, detectRun uuid.UUID) error { + run, err := a.readNamedRun(ctx, runUuid) + if err != nil { + return err + } + if run.Links.Approve == nil { + return fmt.Errorf("run %s of building block %s is not waiting for approval, or you are not allowed to approve it. 'meshstack buildingblock list' shows the run that waits as status.latestRunUuid of a building block whose status.action is APPROVE_RUN", + runUuid, a.buildingBlockUuid) + } + return a.sendApproval(ctx, run, detectRun.String(), plansDiffer(run, detectRun)) +} + +// sendApproval approves the plan of the detect run plan for run, and prints the building block. +// changed is the error for the 409 of meshStack, which it sends for any plan that is not the one +// the run waits for now. +func (a runAction) sendApproval(ctx context.Context, run client.MeshBuildingBlockRun, plan string, changed error) error { + err := a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan) if httpErr, ok := errors.AsType[client.HttpError](err); ok { switch httpErr.StatusCode { case gohttp.StatusConflict: - return planChanged(run, detectRun) + return changed case gohttp.StatusBadRequest: return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) } @@ -91,12 +116,9 @@ func (a runAction) approve(ctx context.Context, detectRun uuid.UUID) error { return a.report(ctx, fmt.Sprintf("Approved the plan of run %s. Follow the run with 'meshstack buildingblockrun logs %s --follow'.", run.Metadata.Uuid, run.Metadata.Uuid)) } -// planChanged explains the 409 of meshStack, which it sends for any plan that is not the one the run -// waits for now. A caller that named the detect run may also have named the wrong one. -func planChanged(run client.MeshBuildingBlockRun, detectRun uuid.UUID) error { - if detectRun == uuid.Nil() { - return fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid) - } +// plansDiffer is the error for the 409 of a caller that named the detect run: meshStack planned the +// run again, or the caller named a detect run that is not the one of the run. +func plansDiffer(run client.MeshBuildingBlockRun, detectRun uuid.UUID) error { return fmt.Errorf("run %s waits for another plan than the one of detect run %s: meshStack planned the run again, or that is not its detect run. "+ "An earlier go-ahead does not count for the new plan. Show the user the plan from 'meshstack buildingblockrun plan %s', and approve it only if the user allows it", run.Metadata.Uuid, detectRun, run.Metadata.Uuid) diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index 21b2e390..9c91c991 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -47,8 +47,12 @@ func newTestRunAction(t *testing.T, server *fakemeshstack.Server, answers string func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { const ( - waitingRun = "a0000000-0000-4000-8000-000000000002" - planRun = "a0000000-0000-4000-8000-000000000001" + waitingRun = "a0000000-0000-4000-8000-000000000002" + planRun = "a0000000-0000-4000-8000-000000000001" + otherPlan = "a0000000-0000-4000-8000-000000000009" + approvedRun = "a0000000-0000-4000-8000-000000000007" + runOfOtherBlock = "a0000000-0000-4000-8000-000000000008" + otherBuildingBlock = "b1d2c3e4-0000-4000-8000-000000000009" ) run := meshObject(t, `{"metadata": {"uuid": "`+waitingRun+`"}, "status": "IN_PROGRESS", `+ `"spec": {"runNumber": 2, "behavior": "APPLY", "buildingBlock": {"uuid": "`+buildingBlockUuid+`", "spec": {"displayName": "my-block"}}}, `+ @@ -56,8 +60,14 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { server := fakemeshstack.Start(t, fakemeshstack.Options{ BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}, `+ `"_links": {"latestRun": {"href": "`+runsPath+waitingRun+`"}}}`)}, - BuildingBlockRuns: []any{run, meshObject(t, `{"metadata": {"uuid": "`+planRun+`"}, "status": "SUCCEEDED", `+ - `"_links": {"downloadLogs": {"href": "`+runsPath+planRun+`/logs"}}}`)}, + BuildingBlockRuns: []any{ + run, meshObject(t, `{"metadata": {"uuid": "`+planRun+`"}, "status": "SUCCEEDED", `+ + `"_links": {"downloadLogs": {"href": "`+runsPath+planRun+`/logs"}}}`), + meshObject(t, `{"metadata": {"uuid": "`+approvedRun+`"}, "status": "IN_PROGRESS", `+ + `"spec": {"buildingBlock": {"uuid": "`+buildingBlockUuid+`"}}, "_links": {}}`), + meshObject(t, `{"metadata": {"uuid": "`+runOfOtherBlock+`"}, "status": "IN_PROGRESS", `+ + `"spec": {"buildingBlock": {"uuid": "`+otherBuildingBlock+`"}}, "_links": {"approve": {"href": "`+runsPath+runOfOtherBlock+`/approve"}}}`), + }, }) server.Route("GET "+runsPath+planRun+"/logs", func(w gohttp.ResponseWriter, _ *gohttp.Request) { _, _ = io.WriteString(w, `{"steps": [{"displayName": "Plan", "status": "SUCCEEDED", "userMessage": "+ resource \"x\" will be created"}]}`) @@ -92,13 +102,13 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { require.NoError(t, cmd.ExecuteContext(t.Context())) assert.Equal(t, "Plan: SUCCEEDED\nPlan | + resource \"x\" will be created\n", stdout.String()) assert.Contains(t, captured.String(), "from the detect run "+planRun) - assert.Contains(t, captured.String(), "approve-run "+buildingBlockUuid+" --detect-run "+planRun+"'") + assert.Contains(t, captured.String(), "approve-run "+buildingBlockUuid+" --run "+waitingRun+" --detect-run "+planRun+"'") }) t.Run("a plan that is not approved stays waiting", func(t *testing.T) { action, asked := newTestRunAction(t, server, "n\n") - require.NoError(t, action.approve(t.Context(), uuid.Nil())) + require.NoError(t, action.approve(t.Context())) assert.Contains(t, asked.String(), `Plan | + resource "x" will be created`) assert.True(t, strings.HasSuffix(asked.String(), "Approve this plan? [y/N]: "), asked.String()) assert.Empty(t, approvals) @@ -107,44 +117,58 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { t.Run("an approval names the run whose plan was shown", func(t *testing.T) { action, _ := newTestRunAction(t, server, "y\n") - require.NoError(t, action.approve(t.Context(), uuid.Nil())) + require.NoError(t, action.approve(t.Context())) require.Len(t, approvals, 1) assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[0]) }) - t.Run("without a terminal, --detect-run approves the plan of that run without asking", func(t *testing.T) { + approveWithoutATerminal := func(t *testing.T, args ...string) error { + t.Helper() testlogin.LoggedInTo(t, server.URL) cmd := New() cmd.SetIn(strings.NewReader("")) cmd.SetOut(io.Discard) - cmd.SetArgs([]string{"approve-run", buildingBlockUuid, "--detect-run", planRun}) + cmd.SetErr(io.Discard) + cmd.SetArgs(append([]string{"approve-run", buildingBlockUuid}, args...)) + return cmd.ExecuteContext(t.Context()) + } - require.NoError(t, cmd.ExecuteContext(t.Context())) + t.Run("without a terminal, --run and --detect-run approve the plan of that run without asking", func(t *testing.T) { + require.NoError(t, approveWithoutATerminal(t, "--run", waitingRun, "--detect-run", planRun)) require.Len(t, approvals, 2) assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[1]) }) + t.Run("--run and --detect-run belong together", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", waitingRun), "must all be set") + require.ErrorContains(t, approveWithoutATerminal(t, "--detect-run", planRun), "must all be set") + assert.Len(t, approvals, 2) + }) + + t.Run("--run of a run that does not wait for approval is refused", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", approvedRun, "--detect-run", planRun), "is not waiting for approval") + assert.Len(t, approvals, 2) + }) + + t.Run("--run of a run of another building block is refused", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", runOfOtherBlock, "--detect-run", planRun), "belongs to building block "+otherBuildingBlock) + assert.Len(t, approvals, 2) + }) + t.Run("--detect-run of another plan is refused, and the user has to see the plan", func(t *testing.T) { - const otherRun = "a0000000-0000-4000-8000-000000000009" approveAnswer = gohttp.StatusConflict - testlogin.LoggedInTo(t, server.URL) - cmd := New() - cmd.SetIn(strings.NewReader("")) - cmd.SetOut(io.Discard) - cmd.SetErr(io.Discard) - cmd.SetArgs([]string{"approve-run", buildingBlockUuid, "--detect-run", otherRun}) - err := cmd.ExecuteContext(t.Context()) - require.ErrorContains(t, err, "run "+waitingRun+" waits for another plan than the one of detect run "+otherRun) + err := approveWithoutATerminal(t, "--run", waitingRun, "--detect-run", otherPlan) + require.ErrorContains(t, err, "run "+waitingRun+" waits for another plan than the one of detect run "+otherPlan) require.ErrorContains(t, err, "Show the user the plan from 'meshstack buildingblockrun plan "+waitingRun+"'") require.Len(t, approvals, 3) - assert.JSONEq(t, `{"predecessorRunUuid": "`+otherRun+`"}`, approvals[2]) + assert.JSONEq(t, `{"predecessorRunUuid": "`+otherPlan+`"}`, approvals[2]) }) t.Run("a plan that changed after it was shown has to be reviewed again", func(t *testing.T) { approveAnswer = gohttp.StatusConflict action, _ := newTestRunAction(t, server, "y\n") - require.EqualError(t, action.approve(t.Context(), uuid.Nil()), "the plan of run "+waitingRun+" changed after you saw it. Run the command again to review the new plan") + require.EqualError(t, action.approve(t.Context()), "the plan of run "+waitingRun+" changed after you saw it. Run the command again to review the new plan") }) } diff --git a/cmd/buildingblock/buildingblock.go b/cmd/buildingblock/buildingblock.go index edda7666..56730938 100644 --- a/cmd/buildingblock/buildingblock.go +++ b/cmd/buildingblock/buildingblock.go @@ -13,6 +13,7 @@ import ( "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/cmd/buildingblock/tfstate" + "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" ) @@ -78,6 +79,20 @@ func (a runAction) readBuildingBlock(ctx context.Context) (jsontext.Value, linke return raw, block, json.Unmarshal(raw, &block) } +const runFlagName = "run" + +// readNamedRun reads the run that the caller names with --run, which has to belong to the building block. +func (a runAction) readNamedRun(ctx context.Context, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { + run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) + if err != nil { + return run, err + } + if run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { + return run, fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) + } + return run, nil +} + // report reads the building block again and writes it, because a run hides the actions // APPROVE_RUN and REVIEW_ABORTED_RUN that only the building block shows. func (a runAction) report(ctx context.Context, done string) error { diff --git a/cmd/buildingblockrun/plan.go b/cmd/buildingblockrun/plan.go index cd41c8d9..60c63343 100644 --- a/cmd/buildingblockrun/plan.go +++ b/cmd/buildingblockrun/plan.go @@ -25,7 +25,7 @@ A run that waits for approval has no logs of its own. Its plan is in the logs of The command prints a line ': ' for each step, and the lines of a step's messages after ' |'. Filter on '|' to read only the messages. -To approve the plan without a terminal, pass the uuid of the detect run to 'meshstack buildingblock approve-run --detect-run ', and approve only if the user allows it. The approval fails if meshStack has planned the run again in the meantime.`, +To approve the plan without a terminal, pass the uuid of this run and the uuid of the detect run to 'meshstack buildingblock approve-run --run --detect-run ', and approve only if the user allows it. The approval fails if meshStack has planned the run again in the meantime.`, Example: ` meshstack buildingblockrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep '| Plan:'`, Args: internal.UuidArg(&runUuid), @@ -51,8 +51,8 @@ To approve the plan without a terminal, pass the uuid of the detect run to 'mesh detectRun.Metadata.Uuid, runUuid)) return nil } - slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. If the user allows it, approve the plan with 'meshstack buildingblock approve-run %s --detect-run %s'", - runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid, detectRun.Metadata.Uuid)) + slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. If the user allows it, approve the plan with 'meshstack buildingblock approve-run %s --run %s --detect-run %s'", + runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid, runUuid, detectRun.Metadata.Uuid)) return nil }, } diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index eb33b4b0..4ef32a75 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -29,7 +29,7 @@ skill and the help disagree, trust the help. | `meshstack buildingblock list` | `bb` | building blocks (deployed instances), newest first | | `meshstack buildingblock trigger-run ` | `bb` | starts a run of one block | | `meshstack buildingblock wait --before ` | `bb` | waits until the run of one block has ended | -| `meshstack buildingblock approve-run --detect-run ` | `bb` | approves the plan that `bbrun plan` shows, once the user allows it | +| `meshstack buildingblock approve-run --run --detect-run ` | `bb` | approves the plan that `bbrun plan` shows, once the user allows it | | `meshstack buildingblock abort-run --run ` | `bb` | aborts one run of a block, also one in progress | | `meshstack buildingblock tfstate` | `bb` | reads and writes the OpenTofu state of one block | | `meshstack buildingblockdefinition list` | `bbd` | definitions — what platform teams offer | @@ -344,12 +344,12 @@ Report the `Plan:` line and anything unexpected, and hand the user a deep link ( Terraform apply that updates such a block ends with the provider warning `Building block run is waiting for input or approval` — that is the gate, not an error. -Approve the run only if the user allows it for this plan. Then pass the detect run that `bbrun plan` -prints. The approval fails if meshStack has planned the run again since. The plan has changed then: -show the user the new plan, and approve only if they allow it again. +Approve the run only if the user allows it for this plan. Then pass the waiting run and the detect +run that `bbrun plan` prints. The approval fails if meshStack has planned the run again since. The +plan has changed then: show the user the new plan, and approve only if they allow it again. ```sh -meshstack bb approve-run --detect-run +meshstack bb approve-run --run --detect-run ``` The command prints the block as it reads it right after the approval, which is no `--before` for