beads/cmd/bd/label_proxied_server.go
Julian Knutsen f21e3a80f7
fix(issueops): templates are read-only on every update leg (#7427)
* fix(issueops): enforce the template read-only update guard on every leg

The refusal of an update to a template (validateIssueUpdatable) lived only
in cmd/bd as a pre-read, so PATCH /v0/beads/issues/{id}, batch:apply update
items and library callers of Lifecycle.Update / BatchApplier edited
templates that `bd update` refused.

It is now one role rule, storage issueops.AuthorizeTemplateUpdate, returning
*issueops.TemplateReadOnlyError (matches ErrTemplateReadOnly; the message is
the sentence bd always printed). It runs in the update's own transaction,
after the compare-and-set preconditions (a stale guard still reports the
mismatch), and no force flag waives it:
- ExecuteUpdate (dolt, embedded) and the uow Update and batch update legs;
- the batch apply metadata splice that finishes a create item stays
  unguarded on both bodies (a template the request creates is not modified);
- httpapi maps it to 409 template_read_only on updateIssue and applyBatch
  (spec x-bd-codes and descriptions updated, apigen regenerated) and the
  client rebuilds the typed error.

UpdateRequest.AllowTemplate stands the guard down for one request: the
caller edits a template deliberately. bd label (add, remove, remove-prefix)
and bd set-state set it, so they keep editing templates on every route, as
on origin/main. Over HTTP it is the optional `allow_template` member of the
PATCH body, advertised by the issues.update.allowTemplate behavior token,
which also says the server enforces the guard. httpclient Lifecycle.Update
decides from the cached handshake before the dial: against a server without
the token (no guard, no member) it runs the same rule
(AuthorizeTemplateUpdate) on a pre-read and never sends allow_template, so a
new bd against an older bd serve still refuses template updates.

cmd/bd: bd update, bd assign and the proxied assign/tag drop their pre-read
and print the role's refusal with the same line and exit code.

Conformance: RunLifecycleUpdateRefusesATemplate,
RunLifecycleUpdateAllowTemplateEditsATemplate,
RunBatchApplyUpdateItemsRefuseATemplate and
RunBatchApplySplicesTheMetadataOfATemplateItCreates on dolt, embedded, uow
and http (the http splice case is parked: the v0 create item has no
is_template member), plus handler and CLI rendering tests, and
TestUpdateTemplateGuardAgainstAServerThatPredatesIt (new client, handshake
without the token: refused before the dial, allow_template not sent).

Skew note (CHANGELOG): an older bd label / bd set-state against a new server
cannot send allow_template and now gets 409 template_read_only on a template.
bd comment, note, priority and tag keep their CLI-only pre-read guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(issueops): scope template read-only docs to updates, test label stand-down

Review fixups for PR 7427 (adopt-pr review loop, iteration 1):

- Contract: the role guard covers updates, not every mutation. The
  CHANGELOG headline, ErrTemplateReadOnly and CodeTemplateReadOnly now
  say so, and "Not yet moved" names claim, reopen, :casMetadata and the
  served addComment, which have no template check yet (a PATCH with
  claim: true refuses a template that POST :claim still claims). Close
  is #7425's. Follow-up: bd-jkp9v3.
- Skew: the CapIssuesUpdateAllowTemplate client fallback covers
  updateIssue only. A batch update item gets no client-side check, so
  through an older bd serve it still edits a template; the CHANGELOG
  and both capability docs say so.
- Tests: a template row now goes through the CLI on both tiers
  (TestEmbeddedLabelEditReports, TestProxiedServerLabelC). bd label add,
  bd label remove --prefix and bd set-state edit it (AllowTemplate);
  bd update --title and bd assign exit 1 with the template sentence and
  leave it unchanged. Mutants: dropping AllowTemplate from label.go and
  state.go reds the three edits on both tiers; disabling
  AuthorizeTemplateUpdate reds update and assign on both tiers.
- Stale comments: runTagProxiedServer, applyUpdateProxiedOne,
  proxiedUpdateTarget, UpdateFlags (five booleans, not four) and the
  ItemUpdate notes in applyLabelEdit and bd label propagate's proxied
  route (UpdateItem has no AllowTemplate).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:25:37 +00:00

253 lines
8.9 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/workapi"
)
// resolveLabelTargetProxied is `bd label`'s exact-id lookup on the
// proxied-server route: the same issue-then-wisp resolution
// workapi.GetIssueOrWisp gives every other proxied front door, with not-found
// normalized to the shape the direct route's resolver produces.
//
// It is what is LEFT of this route's label plumbing. The four-way
// wisp-by-operation switch that used to live here, and the read that used to
// ask a label use case for one issue's labels, are gone: both routes now end at
// issueops.Lifecycle and issueops.Reader, which resolve the plane themselves
// inside their own transaction. Only the resolution stays, because the roles
// take an exact id by contract.
func resolveLabelTargetProxied(ctx context.Context, id string) (string, error) {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return "", err
}
defer uw.Close(ctx)
issue, _, rerr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id)
if errors.Is(rerr, storage.ErrNotFound) {
return "", errors.New("not found")
}
if rerr != nil {
return "", rerr
}
return issue.ID, nil
}
func runLabelListAllProxiedServer(ctx context.Context) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
var permIDs, wispIDs []string
for _, issue := range page.Items {
if issue.Ephemeral {
wispIDs = append(wispIDs, issue.ID)
} else {
permIDs = append(permIDs, issue.ID)
}
}
labelCounts := make(map[string]int)
accumulate := func(byIssue map[string][]string) {
for _, labels := range byIssue {
for _, label := range labels {
labelCounts[label]++
}
}
}
// THE QUESTION HAS NO ROLE, which is the reason ga-26w10 left `list-all`
// behind and the reason it is still here: no issueops surface answers
// "every distinct label in this workspace, with a count". Reader.Get is one
// detail view per call, so asking it would be one round trip per bead to
// build a histogram. A label-vocabulary role is the follow-up
// (ga-2ltro.12).
if len(permIDs) > 0 {
byIssue, err := uw.LabelUseCase().GetLabelsForIssues(ctx, permIDs) //nolint:forbidigo // label histogram; no role answers the workspace's label vocabulary
if err != nil {
return HandleErrorRespectJSON("getting labels: %v", err)
}
accumulate(byIssue)
}
if len(wispIDs) > 0 {
byWisp, err := uw.LabelUseCase().GetLabelsForWisps(ctx, wispIDs) //nolint:forbidigo // label histogram; see GetLabelsForIssues above
if err != nil {
return HandleErrorRespectJSON("getting labels: %v", err)
}
accumulate(byWisp)
}
type labelInfo struct {
Label string `json:"label"`
Count int `json:"count"`
}
if len(labelCounts) == 0 {
if jsonOutput {
return outputJSON([]labelInfo{})
}
fmt.Println("\nNo labels found in database")
return nil
}
labels := make([]string, 0, len(labelCounts))
for label := range labelCounts {
labels = append(labels, label)
}
sort.Strings(labels)
if jsonOutput {
result := make([]labelInfo, 0, len(labels))
for _, label := range labels {
result = append(result, labelInfo{Label: label, Count: labelCounts[label]})
}
return outputJSON(result)
}
fmt.Printf("\n%s All labels (%d unique):\n", ui.RenderAccent("🏷"), len(labels))
maxLen := 0
for _, label := range labels {
if len(label) > maxLen {
maxLen = len(label)
}
}
for _, label := range labels {
padding := strings.Repeat(" ", maxLen-len(label))
fmt.Printf(" %s%s (%d issues)\n", label, padding, labelCounts[label])
}
fmt.Println()
return nil
}
// runLabelRenameProxiedServer is the proxied-server counterpart of
// DoltStore/EmbeddedDoltStore.RenameLabel. It calls the same
// domain.LabelUseCase.RenameLabel every proxied write reaches through
// uw.LabelUseCase(), which in turn delegates to issueops.RenameLabelInTx -
// the identical merge semantics, same-name refusal and one EventLabelRenamed
// per touched issue that the direct route produces. A prior version of this
// route fanned each issue out into a per-issue AddLabel-then-RemoveLabel
// pair, journaling label_added/label_removed instead of label_renamed; that
// divergence is what this delegation replaces.
func runLabelRenameProxiedServer(ctx context.Context, oldLabel, newLabel string) (renamed, merged int, err error) {
if uowProvider == nil {
return 0, 0, HandleError("proxied-server UOW provider not initialized")
}
err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
var rerr error
renamed, merged, _, rerr = uw.LabelUseCase().RenameLabel(ctx, oldLabel, newLabel, currentActor()) //nolint:forbidigo // bulk rename; no role serves it, and Patch.Labels would reintroduce the per-issue add/remove event divergence this delegation replaced
if rerr != nil {
return "", fmt.Errorf("rename label '%s' -> '%s': %w", oldLabel, newLabel, rerr)
}
if renamed == 0 {
return "", nil
}
return fmt.Sprintf("bd: label rename '%s' -> '%s' (%d issues)", oldLabel, newLabel, renamed), nil
})
return renamed, merged, err
}
func runLabelPropagateProxiedServer(ctx context.Context, args []string) error {
label := strings.TrimSpace(args[1])
if label == "" {
return HandleErrorRespectJSON("label cannot be empty")
}
if strings.HasPrefix(label, "provides:") {
return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:"))
}
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
var (
children []*types.Issue
parentID string
)
err := uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
parent, _, rerr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), args[0])
if errors.Is(rerr, storage.ErrNotFound) {
return "", fmt.Errorf("resolving parent %q: not found", args[0])
}
if rerr != nil {
return "", fmt.Errorf("resolving parent %q: %w", args[0], rerr)
}
parentID = parent.ID
page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{ParentID: &parentID})
if err != nil {
return "", fmt.Errorf("searching children of %s: %w", parentID, err)
}
children = page.Items
if len(children) == 0 {
return "", nil
}
// THE ONE SURVIVING WISP SWITCH, and it is named rather than hidden.
// This is the same four-way shape ga-26w10 deleted from `bd label` and
// ga-2ltro.12 deleted from `bd tag`, `bd set-state` and the molecule
// port — the branch a front door can get backwards and put a wisp's
// label in the durable table. It survives because propagate is a search
// plus a fan-out that must land as ONE transaction over N children, and
// a per-child Lifecycle.Update is N transactions: the atomicity this
// command has today would be the price of the migration. The shape that
// keeps both is issueops.BatchApplier.ApplyBatch with one ItemUpdate per
// child carrying this same label patch, and it is blocked on a cmd/bd
// accessor for that role. That is the follow-up this waiver names
// (ga-2ltro.12); it is the last one on this list that WRITES. It also
// needs a template stand-down first: UpdateItem has no AllowTemplate, so
// an ItemUpdate refuses the template children this loop labels today
// (bd-jkp9v3).
for _, child := range children {
var e error
if child.Ephemeral {
e = uw.LabelUseCase().AddWispLabel(ctx, child.ID, label, currentActor()) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
} else {
e = uw.LabelUseCase().AddLabel(ctx, child.ID, label, currentActor()) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
}
if e != nil {
return "", fmt.Errorf("add label '%s' on %s: %w", label, child.ID, e)
}
}
return fmt.Sprintf("bd: propagate label '%s' from %s to %d children", label, parentID, len(children)), nil
})
if err != nil {
return HandleErrorRespectJSON("label propagate: %v", err)
}
if len(children) == 0 {
if jsonOutput {
return outputJSON([]map[string]interface{}{})
}
fmt.Printf("No children found for %s\n", parentID)
return nil
}
commandDidWrite.Store(true)
if jsonOutput {
results := make([]map[string]interface{}, 0, len(children))
for _, child := range children {
results = append(results, map[string]interface{}{
"status": "propagated",
"issue_id": child.ID,
"label": label,
})
}
return outputJSON(results)
}
for _, child := range children {
fmt.Printf("%s Propagated label '%s' to %s\n", ui.RenderPass("✓"), label, child.ID)
}
return nil
}