* Retire the last three wisp-switch call sites, and open the label guard on the whole package (ga-2ltro.12)
ga-26w10 deleted a four-way switch over (add|remove) x (wisp|durable) from
`bd label` and lint the door shut behind it. THE SWITCH SURVIVED AT THREE MORE
SITES, and the rule that was supposed to stop the next one could not see two of
them. This retires all three and makes the rule package-wide.
`bd tag`'s proxied route (cmd/bd/mutate_proxied_server.go) reached
uw.LabelUseCase() through proxiedMutateIssue, whose callback signature hands out
a unit of work AND an isWisp boolean — an invitation to pick a plane, which the
tag callback accepted. It now builds one IssuePatch and hands it to
issueops.Lifecycle.Update. IssuePlaneOnly stays false, so the role resolves the
plane inside its own transaction; TestProxiedServerTag/tag_wisp_routes_to_wisp_labels,
which asserts at the SQL table that a wisp's label lands in wisp_labels and the
durable table stays empty, passes through the role with no branch in the
command. It went red on the pre-fix tree under the boolean flipped backwards,
which is the mutation this exists to kill and which is no longer expressible.
THE MOLECULE PORT'S LABEL WRITE IS GONE RATHER THAN RE-ROUTED, and that is the
stronger fix. molWriter had an AddLabel verb with exactly one caller —
bondProtoProtoInto, labelling a compound it had just created — and two
implementations that each resolved the plane AGAIN by a DIFFERENT predicate:
storeMolWriter deferred to the storage layer's isActiveWisp, uowMolWriter
consulted a cache filled from IssueUseCase().GetWisp. Two predicates for one
fact is how a row and its labels come apart. The label now travels in
compound.Labels, so the create that decides the row's table places the label
too, and AddLabel is deleted from the interface and both implementations. The
disagreement is unrepresentable, not merely unlikely.
Worth stating plainly for the reviewer: uowMolWriter.AddLabel's WISP branch was
unreachable. Its only caller labels a durable epic it just created, so the cache
answers false every time. That is why this site had no end-to-end mutation to
run and why the new test is a unit test with a recording writer: it pins that
the create carries the label, which is the property that makes the branch
unnecessary rather than merely unused.
`bd set-state` had the switch FOUR times — the label read, the event create, the
old-label remove and the new-label add — and a second implementation of the whole
command in cmd/bd/state_proxied_server.go that no longer exists. All three verbs
now have ONE body each, on both routes, ending at issueops.Reader.Get and
issueops.Lifecycle:
- the label READ is Reader.Get's already-hydrated, already-sorted Labels, so
there is no label-shaped read here at all — the same move ga-26w10 made for
`bd label list`;
- the dimension SWAP is one IssuePatch carrying Add and Remove together;
- the EVENT is one Lifecycle.Create with ParentID, which mints the same
hierarchical child id and writes the parent edge atomically.
FOUR DELTAS, none of them absorbed.
THE DIRECT ROUTE'S DELTA IS THE EVENT'S PLANE, AND ONLY THAT. An earlier draft
of this message claimed the direct route "read no state and wrote its label into
the wrong table" for a wisp. That was reasoned, not measured, and it is FALSE:
store.GetLabels, AddLabel and RemoveLabel all reach issueops.*InTx with an EMPTY
table name, which routes by IsActiveWispInTx, and utils.ResolvePartialID
resolves through the wisp-inclusive search. Measured at the parent commit,
`bd set-state <wisp> patrol=muted` on the direct route resolves, swaps the
label, and `bd state <wisp> patrol` reads back "muted".
What the parent DID get wrong is the EVENT. It created the state-change bead
with store.CreateIssue and no wisp flag, so an ephemeral subject got a DURABLE
event child, and the parent edge was a second unguarded write across the two
planes. Measured on both sides of this commit, same wisp, same command:
parent event ms-wisp-865.1, no `ephemeral` field -> durable
this event ms-wisp-859.1, `"ephemeral": true` -> the subject's own plane
so a wisp's state history now dies with the wisp instead of outliving it in the
durable table, and its parent edge is written inside the guarded create rather
than beside it.
That correction is the finding, not the footnote: this commit's own brief is
MEASURED, NOT REASONED ABOUT, and the sentence that broke the rule was in the
commit message. The rule covers the artifact too.
A FAILED REMOVAL NO LONGER PASSES SILENTLY — with one half still open. Both
retired routes warned and carried on when the remove failed, leaving the issue
holding two values for one dimension, which findStateLabel then resolves by
whichever the label read returns first. A store-level failure now fails the
command, because the remove and the add are one guarded update.
WHAT THAT DOES NOT CLOSE, stated because the first draft of this line
overclaimed it as "the dimension has one value or nothing was written": the
CONCURRENT swap. Two racing `bd set-state <id> dim=...` calls both read the same
old label, each patch removes a label the other already removed — a no-op, not a
conflict — and both adds land, so the dimension ends with TWO values. A patch is
atomic for ONE writer; it is not a fence. ExpectedVersion cannot supply one
either, because label writes deliberately do not remint RowVersion. The race is
pre-existing, is not made worse here, and is filed as ga-dle5g.
The proxied route LOSES ONE TRANSACTION. Its event and its label swap used to
commit together; they are now two role calls. The direct route was never atomic
at all (four unguarded writes), so this is a net gain there and a stated cost
here, and it is the same trade ga-26w10 took for the same reason. The event's
plane is the subject's own retention mode copied onto the child rather than
chosen, and it is CHECKED: a guarded create refuses a parent edge it cannot
write, so an event that disagreed with its subject's plane fails loudly instead
of landing in the wrong table.
DOLT HISTORY ATTRIBUTION MOVES, which is cosmetic and is said anyway because an
unstated delta is how the two corrections above came to be needed. The role
composes its own version-commit message, so `bd tag` and `bd set-state` write
"bd: update <id>" where they used to write "bd: tag <id>" and
"bd: set-state <id>". `bd dolt log` still names the issue; it no longer names
the verb. Nothing greps for those strings in this tree.
THE FORBIDIGO RULE IS NOW PACKAGE-WIDE ACROSS cmd/bd. It was narrowed by a
path-except to cmd/bd/label.go on the argument that holding an unmigrated
command to a rule written for a migration it had not had would be a lint waived
on sight. What that missed is that the waiver was INVISIBLE — a file outside the
exemption got no marker, no reason and no diff — so the three commands still
hand-rolling the switch looked exactly like the files with nothing to declare.
Two of them were additionally exempted by `path:`-only holes written for the
FILTER rule, which silently open every forbidigo rule for their files:
mol_port.go by the mol_ hole and export_source.go by the bulk-movement one.
EVERY HOLE IN THAT FAMILY IS `text:`-SCOPED NOW, not just those two. Scoping
only the holes that covered a violation TODAY was the same reasoning error as
the paragraphs above — it sized the guard by where the calls are rather than by
where the next one may be WRITTEN — and a review probe proved it with two dodges
that both passed: a neutrally-named helper dropped into the ado/gitlab/jira/
linear hole, and that helper handing the RAW use case back to a NEW file, which
then needs no import and never spells the accessor. Both are caught now, the
second one twice (the return type and the call), and both were re-confirmed to
PASS with the hole unscoped, so the fix is the scope and not a coincidence. The
`_test\.go` exemption stays unscoped on purpose: `run: tests: false` means
forbidigo never analyzes a test file, so scoping it would assert nothing.
MEASURED, NOT REASONED ABOUT. Before: 27 LabelUseCase call sites in 8 non-test
files. After: 15 in 6, every one carrying //nolint:forbidigo and the reason that
site is not a role's question, and they add up: five in-transaction port reads
(mol_port.go), two alternate-view reads (show_proxied_server.go), two bulk
relation loads (export_source.go), two label-vocabulary reads and two
label-propagate WRITES (label_proxied_server.go), one in-transaction command
read (close_proxied_server.go) and one dry-run preview read
(create_proxied_server.go). 5+2+2+2+2+1+1 = 15. The propagate pair are the
acknowledged carve-out and the only survivors that write; each site names its
follow-up, and propagate's is issueops.BatchApplier.ApplyBatch, blocked on a
cmd/bd accessor.
Both halves verified by mutation, one bypass each. A scratch
uw.LabelUseCase().AddLabel() planted in cmd/bd/state.go — reached through
proxiedOpenReadUOW, so the file imports neither internal/storage/uow nor
internal/storage/domain and depguard is blind to it — is caught by forbidigo. A
scratch uow import in the same file is caught by depguard, which cmd/bd/state.go
now joins: it is the second entry on that list because its three verbs really
have migrated, so the rule pins something that happened.
The depguard prose said the forbidigo rule was "scoped to this same file" and
the exclusions block said its label narrowing cost "a `text:` on ONE of the
per-path holes". Both are now what they are: package-wide, and three.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bound the union legs, and stop letting SQL page a sort it cannot order (ga-2ltro.7)
The two residues the #5476 review deferred, and they turned out to be one rule
observed from both ends: A WINDOW IS ONLY EVER PUSHED UNDER AN ORDER THE QUERY
CAN EXPRESS.
F4 — THE LEGS CARRY THE WINDOW NOW. buildUnionSubquery emitted no bound on
either side of the UNION ALL; only the outer query had one, so both planes were
read in full to deliver a page. Measured on a seeded two-plane store, a
four-row page with twenty matching rows per plane: each leg returned 20 rows,
40 scanned to deliver 4. Each leg now carries the outer clause VERBATIM plus the
deepest row index the outer query can reach, and returns 5 — the bound plus its
probe row — for 10 scanned instead of 40.
EACH LEG IS PARENTHESIZED NOW, and that is load-bearing rather than cosmetic: a
leg carrying its own ORDER BY and LIMIT inside a bare `leg UNION ALL leg` is a
SYNTAX ERROR, the engine reading the trailing clause as the union's own. The
first cut of this change shipped without the parentheses and `bd search` failed
outright — caught by CI, not by the leg probe below, because that probe executes
each subquery STANDALONE where the same string is perfectly legal. A test that
measures the part is not evidence about the whole, so there is now a case that
runs the composed query on both twins across six shapes (ordered, offset, text
term, default order, unbounded, Go-side), and it goes red on the un-parenthesized
form with the exact engine error.
Reusing the outer ORDER BY string rather than rebuilding it is what makes the
bound safe: unionOrderBySQL names `id` and the `sort_*` aliases, both of which
every leg already projects, so one string is valid in both positions and a leg
cannot come to rest in a different order than the one the outer query is about
to cut against. The pushdown is sound because the order is TOTAL — every clause
sqlbuild renders ends in `id ASC` — so a row in the union's top-N is in its own
leg's top-N, there being nothing else it could be behind. legLimit is the bound
PLUS any offset the engine carries, because those are rows the outer query reads
and discards; an offset this package keeps for itself is already inside the
bound.
F5 — AND THE OTHER HALF IS WHY THE LEGS GET NOTHING UNDER `--sort id`. That key
is the one sqlbuild renders no ORDER BY for, so the query ran
`SELECT id, src FROM (leg UNION ALL leg) merged LIMIT n` — a LIMIT with no
ordering anywhere in the statement. A LIMIT without an ORDER BY does not return
the first n rows, it returns n rows.
MEASURED, and it is worse than "arbitrary". On a store with 12 durable and 12
ephemeral beads whose ids interleave, `--sort id --limit 5` answered
[000 002 004 006 008]: five durable rows, and not one wisp. The Go-side sort
then put them in perfect order, which is why this reads as a correct page — the
ORDER was right and the MEMBERSHIP silently excluded an entire plane.
Two changes close it, and both are needed:
- searchWindowFor pushes NO page bound for a Go-side sort, which is the same
answer internal/workapi.SQLLimit gives the reader role for the same reason.
The CAP is not waived with it: maxRows still sizes a bound, so an unordered
scan too large to hold answers ErrTooManyRows rather than reading the
workspace.
- idSrcPage.sortGoSide establishes the order before finishWindow trims. This
is the union seam's copy of issueops.sortMergedResults and exists for the
identical reason that one gives: a concatenation trimmed without a re-sort
keeps an arbitrary prefix. The id is already on the ref, so no row has to be
hydrated to be placed.
THE LIVE CALLER IS `bd query`, NOT `bd list`, and the review's note undersized
it. `bd list` is protected by workapi.SQLLimit and the wire's list endpoint pins
"created" — but workapi.BuildQueryPlan pushes SortBy and Limit straight onto the
filter for any filter-expressible query with no such guard, DefaultQueryLimit
means a limit is ALWAYS set, and "id" is in both the CLI's and the HTTP
endpoint's accepted sort keys. So `bd query '<expr>' --sort id` and
GET /v0/beads/issues/query?sort=id reached this on the DEFAULT path, on a wire
the review recorded as safe. BuildQueryPlan's own comment justifies the pushdown
by promising "the page is the first N in the requested order on every backend";
that was true of every key except the one IsGoSideSort names. Both twins are
covered — the counts twin is the one those callers reach.
TWO THINGS THIS DOES NOT FIX, named rather than left for the next reader.
The per-table seam (internal/storage/issueops) bounds each leg with
EffectiveSearchLimit under the same absent ORDER BY, so it picks an arbitrary
subset per leg before sortMergedResults runs; and sqlbuild.Less ignores sortDesc
for "id", so a reversed id page there keeps the byte-FIRST rows. sortGoSide
honors sortDesc rather than mirroring that.
Costs, stated. A caller combining `--sort id` with a small limit and no cap now
reads every matching row where it used to read limit+1. It read the wrong ones,
and the reader role has always paid this price on the same query.
Also folded in, both comment-only and both named by the review: count.go cited
`bd doctor --check=cross-table`, a selector that does not exist (the flag takes
artifacts, conventions, pollution and validate; the cross-table check runs in
the default sweep), and scanIDSrcPage claimed the shadowed durable row is
dropped "wherever it sits" when the drop only ever reached the scanned window —
a distinction this change sharpens, since the legs are now bounded.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
389 lines
11 KiB
Go
389 lines
11 KiB
Go
// Package main implements the bd CLI state management commands.
|
|
// These commands provide convenient access to the labels-as-state pattern
|
|
// documented in docs/core-concepts/labels.md.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// resolveStateTarget reads one issue's detail view for the state commands, on
|
|
// whichever route this invocation is on.
|
|
//
|
|
// STATE IS LABELS, so this is the same two moves `bd label list` makes after
|
|
// ga-26w10: resolve the positional argument to the exact id the roles take,
|
|
// then ask issueops.Reader for the detail view, whose Labels are already
|
|
// hydrated and already sorted. There is no label-shaped read here and no plane
|
|
// to choose — Reader.Get's issue-then-wisp lookup finds an ephemeral row on its
|
|
// own, which is how the DIRECT route acquires wisp support it never had: it
|
|
// used to call store.GetLabels, which only ever reads the durable table.
|
|
//
|
|
// Resolution stays a front-door job, and stays shared with `bd label`:
|
|
// GetRequest.ID is exact by contract, so the partial-id affordance the direct
|
|
// route offers cannot live below this line.
|
|
func resolveStateTarget(ctx context.Context, issueID string) (*issueops.IssueDetails, error) {
|
|
fullID, err := resolveLabelTarget(ctx, issueID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reader, err := openIssueReader()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
details, err := reader.Get(ctx, issueops.GetRequest{ID: fullID})
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
return nil, errors.New("not found")
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return details, nil
|
|
}
|
|
|
|
var stateCmd = &cobra.Command{
|
|
Use: "state <issue-id> <dimension>",
|
|
GroupID: "issues",
|
|
Short: "Query the current value of a state dimension",
|
|
Long: `Query the current value of a state dimension from an issue's labels.
|
|
|
|
State labels follow the convention <dimension>:<value>, for example:
|
|
patrol:active
|
|
mode:degraded
|
|
health:healthy
|
|
|
|
This command extracts the value for a given dimension.
|
|
|
|
Examples:
|
|
bd state witness-abc patrol # Output: active
|
|
bd state witness-abc mode # Output: normal
|
|
bd state witness-abc health # Output: healthy`,
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("state")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
return runState(rootCtx, args[0], args[1])
|
|
},
|
|
}
|
|
|
|
func runState(ctx context.Context, issueID, dimension string) error {
|
|
details, err := resolveStateTarget(ctx, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
|
}
|
|
|
|
value, _ := findStateLabel(details.Labels, dimension)
|
|
|
|
if jsonOutput {
|
|
result := map[string]interface{}{
|
|
"issue_id": details.ID,
|
|
"dimension": dimension,
|
|
"value": value,
|
|
}
|
|
if value == "" {
|
|
result["value"] = nil
|
|
}
|
|
return outputJSON(result)
|
|
}
|
|
|
|
if value == "" {
|
|
fmt.Printf("(no %s state set)\n", dimension)
|
|
} else {
|
|
fmt.Println(value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var setStateCmd = &cobra.Command{
|
|
Use: "set-state <issue-id> <dimension>=<value>",
|
|
GroupID: "issues",
|
|
Short: "Set operational state (creates event + updates label)",
|
|
Long: `Atomically set operational state on an issue.
|
|
|
|
This command:
|
|
1. Creates an event bead recording the state change (source of truth)
|
|
2. Removes any existing label for the dimension
|
|
3. Adds the new dimension:value label (fast lookup cache)
|
|
|
|
State labels follow the convention <dimension>:<value>, for example:
|
|
patrol:active, patrol:muted
|
|
mode:normal, mode:degraded
|
|
health:healthy, health:failing
|
|
|
|
Examples:
|
|
bd set-state agent-abc patrol=muted --reason "Investigating stuck worker"
|
|
bd set-state agent-abc mode=degraded --reason "High error rate detected"
|
|
bd set-state agent-abc health=healthy
|
|
|
|
The --reason flag provides context for the event bead (recommended).`,
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("set-state")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
issueID := args[0]
|
|
stateSpec := args[1]
|
|
|
|
parts := strings.SplitN(stateSpec, "=", 2)
|
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
|
return HandleErrorRespectJSON("invalid state format %q, expected <dimension>=<value>", stateSpec)
|
|
}
|
|
dimension := parts[0]
|
|
newValue := parts[1]
|
|
|
|
reason, _ := cmd.Flags().GetString("reason")
|
|
|
|
CheckReadonly("set-state")
|
|
|
|
return runSetState(rootCtx, issueID, dimension, newValue, reason)
|
|
},
|
|
}
|
|
|
|
func runSetState(ctx context.Context, issueID, dimension, newValue, reason string) error {
|
|
details, err := resolveStateTarget(ctx, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
|
}
|
|
fullID := details.ID
|
|
|
|
oldValue, found := findStateLabel(details.Labels, dimension)
|
|
oldLabel := ""
|
|
if found {
|
|
oldLabel = dimension + ":" + oldValue
|
|
}
|
|
|
|
newLabel := dimension + ":" + newValue
|
|
|
|
if oldLabel == newLabel {
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"issue_id": fullID,
|
|
"dimension": dimension,
|
|
"value": newValue,
|
|
"changed": false,
|
|
})
|
|
}
|
|
fmt.Printf("(no change: %s already set to %s)\n", dimension, newValue)
|
|
return nil
|
|
}
|
|
|
|
eventTitle := fmt.Sprintf("State change: %s → %s", dimension, newValue)
|
|
eventDesc := ""
|
|
if oldValue != "" {
|
|
eventDesc = fmt.Sprintf("Changed %s from %s to %s", dimension, oldValue, newValue)
|
|
} else {
|
|
eventDesc = fmt.Sprintf("Set %s to %s", dimension, newValue)
|
|
}
|
|
if reason != "" {
|
|
eventDesc += "\n\nReason: " + reason
|
|
}
|
|
|
|
lifecycle, err := openIssueLifecycle()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// The role commits its own Dolt version inside the storage layer, so
|
|
// `--dolt-auto-commit batch` is deferred on the CONTEXT rather than by
|
|
// blanking a commit message — see applyLabelEdit in cmd/bd/label.go.
|
|
ctx, err = issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
// THE EVENT IS CREATED IN THE PLANE ITS SUBJECT LIVES IN, and the role
|
|
// is what makes that a copied fact instead of a chosen one. The
|
|
// retired proxied route branched here between IssueUseCase().CreateWisp
|
|
// and CreateIssue; the retired direct route branched not at all and put
|
|
// every event in the durable table, so a wisp's state history landed
|
|
// beside issues that outlive it. Carrying the subject's own retention
|
|
// mode onto the event says the SAME thing to both routes, and it is
|
|
// checked rather than trusted: a guarded create refuses a parent edge it
|
|
// could not write, so an event that disagreed with its subject's plane
|
|
// fails the command instead of silently landing in the wrong table.
|
|
created, err := lifecycle.Create(ctx, issueops.CreateRequest{
|
|
Actor: actor,
|
|
Issue: &types.Issue{
|
|
Title: eventTitle,
|
|
Description: eventDesc,
|
|
Status: types.StatusClosed,
|
|
Priority: 4,
|
|
IssueType: types.TypeEvent,
|
|
CreatedBy: getActorWithGit(),
|
|
Ephemeral: details.Ephemeral,
|
|
NoHistory: details.NoHistory,
|
|
},
|
|
ParentID: fullID,
|
|
})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("creating event: %v", err)
|
|
}
|
|
commandDidWrite.Store(true)
|
|
eventID := created.Issue.ID
|
|
|
|
// ONE PATCH SWAPS THE DIMENSION. Both retired routes removed the old
|
|
// label and added the new one as two writes, and both treated a failed
|
|
// removal as a warning — which leaves an issue carrying two values for
|
|
// one dimension, a state findStateLabel resolves by whichever the label
|
|
// read happens to return first. A LabelPatch applies Add and Remove in
|
|
// one guarded update, so the dimension has one value or the command
|
|
// failed. The plane needs no branch: IssuePlaneOnly stays false and the
|
|
// role resolves it inside its own transaction.
|
|
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
|
|
Actor: actor,
|
|
IssueID: fullID,
|
|
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{
|
|
Add: []string{newLabel},
|
|
Remove: removeStateLabel(oldLabel),
|
|
}},
|
|
}); err != nil {
|
|
return HandleErrorRespectJSON("setting %s: %v", dimension, err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
result := map[string]interface{}{
|
|
"issue_id": fullID,
|
|
"dimension": dimension,
|
|
"old_value": oldValue,
|
|
"new_value": newValue,
|
|
"event_id": eventID,
|
|
"changed": true,
|
|
}
|
|
if oldValue == "" {
|
|
result["old_value"] = nil
|
|
}
|
|
return outputJSON(result)
|
|
}
|
|
|
|
fmt.Printf("%s Set %s = %s on %s\n", ui.RenderPass("✓"), dimension, newValue, fullID)
|
|
if oldValue != "" {
|
|
fmt.Printf(" Previous: %s\n", oldValue)
|
|
}
|
|
fmt.Printf(" Event: %s\n", eventID)
|
|
return nil
|
|
}
|
|
|
|
// stateListCmd lists all state dimensions on an issue
|
|
var stateListCmd = &cobra.Command{
|
|
Use: "list <issue-id>",
|
|
Short: "List all state dimensions on an issue",
|
|
Long: `List all state labels (dimension:value format) on an issue.
|
|
|
|
This filters labels to only show those following the state convention.
|
|
|
|
Example:
|
|
bd state list witness-abc
|
|
# Output:
|
|
# patrol: active
|
|
# mode: normal
|
|
# health: healthy`,
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("state-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
return runStateList(rootCtx, args[0])
|
|
},
|
|
}
|
|
|
|
func runStateList(ctx context.Context, issueID string) error {
|
|
details, err := resolveStateTarget(ctx, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
|
}
|
|
fullID := details.ID
|
|
|
|
states := collectStateLabels(details.Labels)
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"issue_id": fullID,
|
|
"states": states,
|
|
})
|
|
}
|
|
|
|
if len(states) == 0 {
|
|
fmt.Printf("\n%s has no state labels\n", fullID)
|
|
return nil
|
|
}
|
|
|
|
fmt.Printf("\n%s State for %s:\n", ui.RenderAccent("📊"), fullID)
|
|
for dimension, value := range states {
|
|
fmt.Printf(" %s: %s\n", dimension, value)
|
|
}
|
|
fmt.Println()
|
|
return nil
|
|
}
|
|
|
|
func init() {
|
|
// set-state flags
|
|
setStateCmd.Flags().String("reason", "", "Reason for the state change (recorded in event)")
|
|
|
|
// Add subcommands
|
|
stateCmd.AddCommand(stateListCmd)
|
|
|
|
rootCmd.AddCommand(stateCmd)
|
|
rootCmd.AddCommand(setStateCmd)
|
|
}
|
|
|
|
// Ensure ctx is available
|
|
var _ context.Context = rootCtx
|
|
|
|
func findStateLabel(labels []string, dimension string) (string, bool) {
|
|
prefix := dimension + ":"
|
|
for _, label := range labels {
|
|
if strings.HasPrefix(label, prefix) {
|
|
return strings.TrimPrefix(label, prefix), true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// removeStateLabel is the Remove member of the dimension swap: the old label
|
|
// when there was one, and nothing when the dimension is being set for the
|
|
// first time. A nil slice rather than a one-entry slice holding "" matters —
|
|
// LabelPatch drops an empty entry, so both spell "remove nothing", but only
|
|
// one of them says so.
|
|
func removeStateLabel(oldLabel string) []string {
|
|
if oldLabel == "" {
|
|
return nil
|
|
}
|
|
return []string{oldLabel}
|
|
}
|
|
|
|
func collectStateLabels(labels []string) map[string]string {
|
|
states := make(map[string]string)
|
|
for _, label := range labels {
|
|
if index := strings.Index(label, ":"); index > 0 {
|
|
states[label[:index]] = label[index+1:]
|
|
}
|
|
}
|
|
return states
|
|
}
|