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>
This commit is contained in:
Julian Knutsen 2026-10-09 16:25:37 +00:00 • committed by GitHub
commit f21e3a80f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
54 changed files with 1038 additions and 73 deletions

View file

@ -204,6 +204,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
ones cannot fork.
### Fixed
- **An update of a template is now refused for every caller, not only
`bd update`.** The template guard used to be a pre-read in `cmd/bd`, so an
update through `bd serve` (`PATCH /v0/beads/issues/{id}`), an `update` item
of `issues:batchApply`, or a library caller of `issueops.Lifecycle.Update` or
`BatchApplier` edited a template that `bd update` refused. It now lives in
the role, in the update's own transaction, on every backend: any update
naming a template refuses with `*issueops.TemplateReadOnlyError` (matching
`ErrTemplateReadOnly`), whatever its patch and force flags, after the
compare-and-set guards. Over HTTP it is `409` `template_read_only`, and the
client rebuilds the same typed error. HTTP and library callers that edited
templates are now refused (pour the template instead) unless they set the
new `UpdateRequest.AllowTemplate` (`allow_template` on the PATCH body), which
stands the guard down for that one request. `bd update`, `bd assign` and the
proxied `bd tag` print the same line as before; `bd label` and
`bd set-state` set `AllowTemplate` and keep editing templates as they always
have. A batch create that makes a template and splices its metadata still
lands: the splice finishes the create. Version skew: a new `bd` against an
older `bd serve` (no `issues.update.allowTemplate` token in the handshake)
refuses a single template update itself before dialing, and never sends
`allow_template` to it. A batch `update` item gets no such check (its target
resolves on the server), so through an older `bd serve` it still edits a
template. An older `bd label` or `bd set-state` against a new `bd serve`
cannot send `allow_template`, so it now gets `409` `template_read_only` on a
template; upgrade the client. Not yet moved: `bd comment`, `bd note`,
`bd priority` and `bd tag` still refuse templates with their own pre-read in
`cmd/bd` (their direct-route writes do not go through `Lifecycle.Update`), so
for those four the guard lives only in the CLI. Claim, reopen, `:casMetadata`
and the served `addComment` have no template check at all yet (bd-jkp9v3):
`POST /v0/beads/issues/{id}:claim` (`issueops.Claimer`) still claims a
template that a `PATCH` with `claim: true` refuses. Close's guards move to
the role in their own change (#7425).
- **PRs based on `hotfix/**` branches now run full CI, not just
cross-version historical smokes and triage labeling.** `pr.yml`,
`pr-risk.yml`, `conformance.yml`, `cross-version-smoke.yml` and

View file

@ -2492,3 +2492,72 @@ func batchApplyHistoryMatching(t *testing.T, ctx context.Context, fixture BatchA
}
return count
}
// RunBatchApplyUpdateItemsRefuseATemplate pins that an update item answers to
// Lifecycle.Update's template guard: an item targeting a template refuses with
// an *ItemError carrying *TemplateReadOnlyError, whatever force flags it
// carries, and the request is all or nothing, so the create ahead of it does
// not land and the template is untouched.
func RunBatchApplyUpdateItemsRefuseATemplate(t *testing.T, ctx context.Context, fixture BatchApplyFixture) {
t.Helper()
template := fixture.IssuePrefix + "-tmplupd-template"
bystander := fixture.IssuePrefix + "-tmplupd-bystander"
seeded := batchApplyIssue(template, "a template")
seeded.IsTemplate = true
if err := fixture.CreateIssue(ctx, seeded, "seed"); err != nil {
t.Fatalf("seed %s: %v", template, err)
}
update := batchApplyUpdate(publicops.Ref{ID: template}, publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "edited"},
Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusClosed},
})
update.Update.ForceClosePolicy = true
_, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{
Actor: "apply-writer",
ForceIDPrefix: true,
Items: []publicops.ApplyItem{
batchApplyCreate("bystander", batchApplyIssue(bystander, "must not land beside a refusal")),
update,
},
})
var itemErr *publicops.ItemError
if !errors.As(err, &itemErr) {
t.Fatalf("an update item on template %s: error = %v, want an *ItemError", template, err)
}
if itemErr.Kind != publicops.ItemUpdate || itemErr.Index != 1 {
t.Errorf("ItemError = %#v, want the update item at index 1", itemErr)
}
var refusal *publicops.TemplateReadOnlyError
if !errors.As(err, &refusal) || refusal.IssueID != template {
t.Errorf("update item on template = %v, want *TemplateReadOnlyError naming %s", err, template)
}
assertBatchApplyRowCount(t, ctx, fixture, "issues", bystander, 0)
if got := batchApplyColumn(t, ctx, fixture, "title", template); got != "a template" {
t.Errorf("%s title after the refusal = %q, want it untouched", template, got)
}
if got := batchApplyColumn(t, ctx, fixture, "status", template); got != string(types.StatusOpen) {
t.Errorf("%s status after the refusal = %q, want it untouched", template, got)
}
}
// RunBatchApplySplicesTheMetadataOfATemplateItCreates is the template guard's
// boundary: the one write a template legitimately takes inside a batch is a
// CREATE item that makes it and asks for a metadata splice. The splice runs as
// an update of the row the request itself is creating, after every id exists,
// and it must land — the template is being written, not modified — so a guard
// placed where the splice reaches it would refuse a template's own creation.
func RunBatchApplySplicesTheMetadataOfATemplateItCreates(t *testing.T, ctx context.Context, fixture BatchApplyFixture) {
t.Helper()
created := fixture.IssuePrefix + "-tmplsplice-created"
fresh := batchApplyIssue(created, "a template this request creates")
fresh.IsTemplate = true
item := batchApplyCreate("created", fresh)
item.Create.MetadataRefs = map[string]publicops.Ref{"gc.self": {Key: "created"}}
batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{
Actor: "apply-writer", ForceIDPrefix: true, Items: []publicops.ApplyItem{item},
})
if _, ok := batchApplyMetadataKey(t, ctx, fixture, created, "gc.self"); !ok {
t.Errorf("%s carries no gc.self key: the splice that finishes a template's own create must land", created)
}
}

View file

@ -2519,3 +2519,134 @@ func lifecycleUpdateHasEdge(dependencies []*types.Dependency, wantTarget string)
}
return false
}
// RunLifecycleUpdateRefusesATemplate pins Lifecycle.Update's template guard:
// templates are read-only, so EVERY update naming one refuses with
// *TemplateReadOnlyError — a field edit, a label edit, a claim, a status
// crossing — whatever force flags ride along, and nothing is written. It is the
// guard `bd update` used to apply as a CLI pre-read, which left bd serve and
// library callers editing templates bd refused.
//
// The refusal is asserted at the level a caller acts on — the typed error, its
// sentinel and the sentence bd prints, read off the typed error because a
// served refusal wraps it — and the row is read back to prove nothing moved.
// Two controls: the same patches land on an ordinary sibling, so the guard is
// not refusing the patch shapes; and a stale ExpectedVersion on the template
// still reports the mismatch, so the guard runs after the compare-and-set
// preconditions like every other update fence.
func RunLifecycleUpdateRefusesATemplate(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
template := fixture.IssuePrefix + "-lut-template"
sibling := fixture.IssuePrefix + "-lut-sibling"
for _, issue := range []*types.Issue{
{ID: template, IsTemplate: true},
{ID: sibling},
} {
issue.Title, issue.Status, issue.Priority, issue.IssueType = issue.ID, types.StatusOpen, 2, types.TypeTask
if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", issue.ID, err)
}
}
before, err := fixture.GetIssue(ctx, template)
if err != nil {
t.Fatalf("read seeded template %s: %v", template, err)
}
requests := []struct {
name string
request publicops.UpdateRequest
}{
{name: "field edit", request: publicops.UpdateRequest{
Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "edited"}},
}},
{name: "label edit", request: publicops.UpdateRequest{
Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lut-tag"}}},
}},
{name: "claim", request: publicops.UpdateRequest{Claim: true}},
{name: "forced status crossing", request: publicops.UpdateRequest{
Patch: publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusClosed}},
ForceClosePolicy: true,
}},
{name: "forced assignee transfer", request: publicops.UpdateRequest{
Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "someone"}},
ForceAssigneeTransfer: true,
}},
}
for _, tc := range requests {
request := tc.request
request.Actor, request.IssueID = "writer", template
_, err := fixture.Lifecycle.Update(ctx, request)
var refusal *publicops.TemplateReadOnlyError
if !errors.As(err, &refusal) {
t.Fatalf("%s on template %s: err = %v, want *TemplateReadOnlyError", tc.name, template, err)
}
if refusal.IssueID != template || !errors.Is(err, publicops.ErrTemplateReadOnly) {
t.Errorf("%s refusal = %#v (%v), want IssueID %q matching ErrTemplateReadOnly", tc.name, refusal, err, template)
}
if want := "cannot modify template " + template + ": templates are read-only; use 'bd mol pour' to create a work item"; refusal.Error() != want {
t.Errorf("%s refusal reads %q, want %q", tc.name, refusal.Error(), want)
}
after, err := fixture.GetIssue(ctx, template)
if err != nil {
t.Fatalf("read template %s after the %s refusal: %v", template, tc.name, err)
}
if after.RowVersion != before.RowVersion || after.Title != before.Title || after.Status != before.Status ||
after.Assignee != before.Assignee || len(after.Labels) != len(before.Labels) {
t.Errorf("template %s after the %s refusal = %+v, want it unchanged from %+v", template, tc.name, after, before)
}
control := tc.request
control.Actor, control.IssueID = "writer", sibling
if _, err := fixture.Lifecycle.Update(ctx, control); err != nil {
t.Errorf("%s on the ordinary sibling %s: %v, want it to land", tc.name, sibling, err)
}
}
stale := before.RowVersion + 1
_, err = fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "writer", IssueID: template, ExpectedVersion: &stale,
Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "edited"}},
})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Errorf("stale-guarded update of template %s: err = %v, want ErrVersionMismatch ahead of the template guard", template, err)
}
}
// RunLifecycleUpdateAllowTemplateEditsATemplate pins the template guard's one
// stand-down: an update with AllowTemplate — what bd label and bd set-state
// send, since they have always edited templates — lands on a template, and
// only that request is waived (the same patch without it still refuses).
func RunLifecycleUpdateAllowTemplateEditsATemplate(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
template := fixture.IssuePrefix + "-lua-template"
issue := &types.Issue{ID: template, Title: template, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, IsTemplate: true}
if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", template, err)
}
result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "writer", IssueID: template, AllowTemplate: true,
Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lua-tag"}}},
})
if err != nil {
t.Fatalf("AllowTemplate label edit on template %s: %v, want it to land", template, err)
}
if !result.Changed || result.Issue == nil || !lifecycleUpdateHasLabel(result.Issue.Labels, "lua-tag") {
t.Errorf("AllowTemplate label edit on template %s = %+v, want a change carrying lua-tag", template, result)
}
after, err := fixture.GetIssue(ctx, template)
if err != nil {
t.Fatalf("read template %s: %v", template, err)
}
if !after.IsTemplate {
t.Errorf("template %s is no longer a template after an AllowTemplate edit", template)
}
_, err = fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "writer", IssueID: template,
Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lua-other"}}},
})
if !errors.Is(err, publicops.ErrTemplateReadOnly) {
t.Errorf("the same edit without AllowTemplate: err = %v, want ErrTemplateReadOnly", err)
}
}

View file

@ -58,6 +58,8 @@ var roleContractCases = []roleContract{
RunBatchApplyReplayMintsANewSetOfRows,
RunBatchApplyDoesNotMutateTheCallerRequest,
RunBatchApplyRefusesAnUnusableRequest,
RunBatchApplyUpdateItemsRefuseATemplate,
RunBatchApplySplicesTheMetadataOfATemplateItCreates,
),
roleCases("BatchCloser", "BatchCloser()", oncePerRole,
@ -479,6 +481,8 @@ var roleContractCases = []roleContract{
RunLifecycleUpdateParentIDReplacesEveryParent,
RunLifecycleUpdatePersistentPreservesUnversionedClass,
RunLifecycleUpdateProvenanceLabelsHistory,
RunLifecycleUpdateRefusesATemplate,
RunLifecycleUpdateAllowTemplateEditsATemplate,
),
roleCases("Memories", "Memories()", oncePerRole,

View file

@ -1227,6 +1227,7 @@ go_test(
"update_proxied_integration_test.go",
"update_proxied_server_test.go",
"update_stray_positional_test.go",
"update_template_refusal_test.go",
"user_config_path_windows_test.go",
"utils_unit_test.go",
"vc_embedded_test.go",

View file

@ -75,9 +75,8 @@ Examples:
issueStore := result.Store
if err := validateIssueUpdatable(id, result.Issue); err != nil {
return HandleErrorRespectJSON("%s", err)
}
// The template guard is the role's (issueops.Lifecycle.Update); its
// refusal is printed below as this command always printed it.
// bd-98s5c: bd assign is shorthand for an unguarded assignee update —
// same live-claim fence as bd update -a. mc-zndi7.74: skipped when this
@ -118,6 +117,9 @@ Examples:
return reported
}
}
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
return HandleErrorRespectJSON("%s", refusal)
}
return HandleErrorRespectJSON("updating %s: %v", id, err)
}

View file

@ -105,7 +105,9 @@ func resolveLabelTarget(ctx context.Context, id string) (string, error) {
// commits them together, so the N calls collapse back to one transaction and
// one history entry with no new role and no new request type. It is not in this
// slice because it needs a cmd/bd accessor of its own and because its end gate
// runs a hierarchy and cycle walk a label-only request has no use for.
// runs a hierarchy and cycle walk a label-only request has no use for. It also
// needs a template stand-down first: UpdateItem has no AllowTemplate, so an
// ItemUpdate refuses the templates this function edits today (bd-jkp9v3).
func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, operation string) error {
lifecycle, err := openIssueLifecycle()
if err != nil {
@ -168,6 +170,9 @@ func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, ope
Actor: currentActor(),
IssueID: issueID,
Patch: patch,
// bd label has always edited templates; the role's template
// guard stands down for it (issueops.UpdateRequest.AllowTemplate).
AllowTemplate: true,
})
if uerr != nil {
gerund := labelOperationGerund(operation)
@ -364,6 +369,8 @@ func removeLabelsByPrefix(ctx context.Context, issueIDs []string, prefix string,
Actor: currentActor(),
IssueID: target.issueID,
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Remove: target.labels}},
// As above: bd label edits templates by design.
AllowTemplate: true,
})
if uerr != nil {
return HandleErrorRespectJSON("label removing (prefix): %s: %v", target.issueID, uerr)

View file

@ -7,9 +7,13 @@ import (
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
)
// bdLabel runs "bd label" with the given args and returns stdout.
@ -99,6 +103,28 @@ func bdLabelListAllJSON(t *testing.T, bd, dir string) []map[string]interface{} {
return results
}
// markIssueTemplate makes an existing issue a template (is_template = 1) with
// raw SQL and commits it, so a test can put a template in front of the CLI
// without cooking a formula.
func markIssueTemplate(t *testing.T, beadsDir, database, issueID string) {
t.Helper()
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), filepath.Join(beadsDir, "embeddeddolt"), database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
res, err := db.ExecContext(t.Context(), "UPDATE issues SET is_template = 1 WHERE id = ?", issueID)
if err != nil {
t.Fatalf("mark %s a template: %v", issueID, err)
}
if n, err := res.RowsAffected(); err != nil || n != 1 {
t.Fatalf("mark %s a template: %d rows affected (err %v), want 1", issueID, n, err)
}
if _, err := db.ExecContext(t.Context(), "CALL DOLT_COMMIT('-Am', 'test: mark a template')"); err != nil {
t.Fatalf("commit the template mark: %v", err)
}
}
// TestEmbeddedLabelAddRemove was split from TestEmbeddedLabel (originally
// ~360s, measured under --config=embedded) into 3 top-level tests over
// disjoint subtest groups, for CI shard balance (see
@ -361,7 +387,7 @@ func TestEmbeddedLabelEditReports(t *testing.T) {
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tl")
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "tl")
// Two issues carrying DIFFERENT matching sets: the report is per issue and
// each issue's set is resolved from its own labels, so a refactor that
@ -614,6 +640,50 @@ func TestEmbeddedLabelEditReports(t *testing.T) {
}
}
})
// A template is read-only to an update — issueops.Lifecycle.Update refuses
// it on every route — but bd label and bd set-state edit templates by
// design: they set UpdateRequest.AllowTemplate. One template pins both
// sides end to end. The stand-down verbs are checked with t.Errorf rather
// than a fatal helper, so a lost AllowTemplate names every verb that lost
// it.
t.Run("template_label_edits_pass_update_and_assign_refuse", func(t *testing.T) {
tpl := bdCreate(t, bd, dir, "Template under edit", "--type", "task",
"--label", "pool:refused:reason-a")
markIssueTemplate(t, beadsDir, "tl", tpl.ID)
for _, args := range [][]string{
{"label", "add", tpl.ID, "tpl-added"},
{"label", "remove", tpl.ID, "--prefix", "pool:refused:"},
{"set-state", tpl.ID, "phase=planning"},
} {
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
if out, err := cmd.CombinedOutput(); err != nil {
t.Errorf("bd %s on a template: %v\n%s", strings.Join(args, " "), err, out)
}
}
labels := bdLabelListJSON(t, bd, dir, tpl.ID)
slices.Sort(labels)
if want := []string{"phase:planning", "tpl-added"}; !slices.Equal(labels, want) {
t.Errorf("template labels after label add, label remove --prefix and set-state = %v, want %v", labels, want)
}
want := "cannot modify template " + tpl.ID + ": templates are read-only; use 'bd mol pour' to create a work item"
for _, args := range [][]string{
{"update", tpl.ID, "--title", "Edited template"},
{"assign", tpl.ID, "someone-else"},
} {
if out, code := bdRunFailCode(t, bd, dir, args...); code != 1 || !strings.Contains(out, want) {
t.Errorf("bd %s on a template: exit %d, output:\n%s\nwant exit 1 and %q", strings.Join(args, " "), code, out, want)
}
}
if got := bdShow(t, bd, dir, tpl.ID); got.Title != "Template under edit" || got.Assignee != "" || !got.IsTemplate {
t.Errorf("the refused update and assign changed the template: title=%q assignee=%q is_template=%v",
got.Title, got.Assignee, got.IsTemplate)
}
})
}
// TestEmbeddedLabelPropagateRename was split from TestEmbeddedLabel

View file

@ -5,6 +5,9 @@ package main
import (
"context"
"encoding/json"
"errors"
"os/exec"
"slices"
"sort"
"strings"
"testing"
@ -581,4 +584,53 @@ func TestProxiedServerLabelC(t *testing.T) {
t.Errorf("labels (permanent) count = %d, want 0 — propagated wisp label must not leak into the permanent table", permCount)
}
})
// The proxied twin of TestEmbeddedLabelEditReports'
// template_label_edits_pass_update_and_assign_refuse, over the unit-of-work
// leg: bd label and bd set-state stand the template guard down
// (UpdateRequest.AllowTemplate), bd update and bd assign are refused with
// the CLI's sentence and exit 1.
t.Run("template_label_edits_pass_update_and_assign_refuse", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "lt")
tpl := bdProxiedCreate(t, bd, p.dir, "Template under edit", "--type", "task",
"--label", "pool:refused:reason-a")
res, err := openProxiedDB(t, p).Exec("UPDATE issues SET is_template = 1 WHERE id = ?", tpl.ID)
if err != nil {
t.Fatalf("mark %s a template: %v", tpl.ID, err)
}
if n, err := res.RowsAffected(); err != nil || n != 1 {
t.Fatalf("mark %s a template: %d rows affected (err %v), want 1", tpl.ID, n, err)
}
for _, args := range [][]string{
{"label", "add", tpl.ID, "tpl-added"},
{"label", "remove", tpl.ID, "--prefix", "pool:refused:"},
{"set-state", tpl.ID, "phase=planning"},
} {
if stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, args...); err != nil {
t.Errorf("bd %s on a template: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout, stderr)
}
}
if got, want := bdProxiedLabelListJSON(t, bd, p.dir, tpl.ID), []string{"phase:planning", "tpl-added"}; !slices.Equal(got, want) {
t.Errorf("template labels after label add, label remove --prefix and set-state = %v, want %v", got, want)
}
want := "cannot modify template " + tpl.ID + ": templates are read-only; use 'bd mol pour' to create a work item"
for _, args := range [][]string{
{"update", tpl.ID, "--title", "Edited template"},
{"assign", tpl.ID, "someone-else"},
} {
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, args...)
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 || !strings.Contains(stdout+stderr, want) {
t.Errorf("bd %s on a template: err %v\nstdout:\n%s\nstderr:\n%s\nwant exit 1 and %q",
strings.Join(args, " "), err, stdout, stderr, want)
}
}
if got := bdProxiedShow(t, bd, p.dir, tpl.ID); got.Title != "Template under edit" || got.Assignee != "" || !got.IsTemplate {
t.Errorf("the refused update and assign changed the template: title=%q assignee=%q is_template=%v",
got.Title, got.Assignee, got.IsTemplate)
}
})
}

View file

@ -205,7 +205,10 @@ func runLabelPropagateProxiedServer(ctx context.Context, args []string) error {
// 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.
// (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 {

View file

@ -87,9 +87,8 @@ func proxiedAssign(ctx context.Context, id, assignee string, force bool, ifRevis
if rerr != nil {
return struct{}{}, fmt.Errorf("resolving %s: %w", id, rerr)
}
if verr := validateIssueUpdatable(id, current); verr != nil {
return struct{}{}, verr
}
// The template guard is the role's, enforced by the Lifecycle.Update
// below; runAssignProxiedServer prints its refusal as before.
// mc-zndi7.74: skipped when this pre-read is already stale against an
// active --if-revision guard, so a lost race reports precondition_failed
// from the guarded write below instead of this policy refusal — see
@ -137,6 +136,9 @@ func runAssignProxiedServer(ctx context.Context, args []string, force bool, ifRe
return reported
}
}
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
err = refusal
}
return HandleErrorRespectJSON("assign %s: %v", id, err)
}
if jsonOutput {
@ -211,10 +213,10 @@ func runNoteProxiedServer(ctx context.Context, id, noteText string) error {
// UpdateRequest.IssuePlaneOnly stays false, so the role resolves the plane
// inside its own transaction and there is no boolean here to get backwards.
//
// The two reads it still makes are front-door work rather than plumbing.
// issueops.Reader.Get supplies the issue the template guard needs — the roles
// have no opinion about templates, and the direct route refuses one — and the
// role takes an exact id by contract, which Get's issue-then-wisp lookup is.
// The read it still makes is front-door work rather than plumbing: the role
// takes an exact id by contract, and issueops.Reader.Get's issue-then-wisp
// lookup supplies one. The template guard is the role's: Lifecycle.Update
// refuses a template inside its own transaction.
// The label arrives already normalized: tag.go does that before choosing a
// route, so this path and the direct one cannot disagree about what was stored.
func runTagProxiedServer(ctx context.Context, id, label string) error {
@ -229,9 +231,8 @@ func runTagProxiedServer(ctx context.Context, id, label string) error {
if err != nil {
return HandleErrorRespectJSON("tag %s: resolving %s: %v", id, id, err)
}
if verr := validateIssueUpdatable(id, &details.Issue); verr != nil {
return HandleErrorRespectJSON("tag %s: %v", id, verr)
}
// The template guard is the role's, enforced by the Lifecycle.Update
// below, whose refusal prints as this route always printed it.
lifecycle, err := openIssueLifecycle()
if err != nil {
@ -250,6 +251,9 @@ func runTagProxiedServer(ctx context.Context, id, label string) error {
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Add: []string{label}}},
})
if err != nil {
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
err = refusal
}
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
commandDidWrite.Store(true)

View file

@ -11,6 +11,13 @@ import (
)
// validateIssueUpdatable checks if an issue can be updated.
//
// It is the CLI-only template guard that bd comment, bd note, bd priority and
// bd tag (and the proxied comment and mutate routes) still run as a pre-read:
// their writes do not go through issueops.Lifecycle.Update, whose role rule
// (storage issueops.AuthorizeTemplateUpdate) guards bd update and bd assign on
// every route. Until those commands move onto the role, this is their only
// guard.
// Uses the centralized validation package for consistency.
func validateIssueUpdatable(id string, issue *types.Issue) error {
// Note: We use NotTemplate() directly instead of ForUpdate() to maintain

View file

@ -260,6 +260,9 @@ func runSetState(ctx context.Context, issueID, dimension, newValue, reason strin
Add: []string{newLabel},
Remove: removeStateLabel(oldLabel),
}},
// bd set-state has always edited templates; the role's template guard
// stands down for it (issueops.UpdateRequest.AllowTemplate).
AllowTemplate: true,
}); err != nil {
return HandleErrorRespectJSON("setting %s: %v", dimension, err)
}

View file

@ -493,12 +493,9 @@ pointless).`,
issue := result.Issue
issueStore := result.Store
if err := validateIssueUpdatable(id, issue); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
recordFailure(id, err.Error())
closeIfUnmutated(result)
continue
}
// The template guard is the role's (issueops.Lifecycle.Update),
// enforced inside the mutation on every route; its refusal is
// printed below as the line this command always printed.
// bd-98s5c: an unguarded assignee update must not silently
// overwrite another actor's live claim. Skipped under
@ -577,7 +574,10 @@ pointless).`,
}
}
failureText := fmt.Sprintf("updating issue: %v", updateErr)
if errors.Is(updateErr, issueops.ErrNotesOverwrite) {
if refusal, ok := templateReadOnlyRefusal(id, updateErr); ok {
failureText = refusal.Error()
fmt.Fprintf(os.Stderr, "%s\n", refusal)
} else if errors.Is(updateErr, issueops.ErrNotesOverwrite) {
// The contract's AuthorizeNotesOverwrite fence refused
// inside the mutation transaction. Print the advice, not
// the raw sentinel.
@ -1117,3 +1117,16 @@ func init() {
updateCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(updateCmd)
}
// templateReadOnlyRefusal reports whether err is the update role's template
// refusal (issueops.Lifecycle.Update, any route) and, when it is, returns it
// spelled against id — the argument as the caller typed it, which is what this
// CLI's template sentence has always named. It is found with errors.Is because
// the refusal may arrive wrapped by the unit of work or inside the served
// problem envelope.
func templateReadOnlyRefusal(id string, err error) (error, bool) {
if !errors.Is(err, issueops.ErrTemplateReadOnly) {
return nil, false
}
return &issueops.TemplateReadOnlyError{IssueID: id}, true
}

View file

@ -87,11 +87,12 @@ func proxiedIssueLifecycle() (issueops.Lifecycle, error) {
// applyUpdateProxiedOne applies one issue's update — plain or --claim —
// through issueops.Lifecycle. What stays here is this surface's own protocol:
// the template guard, the advisory reassign pre-read, the per-id failure
// taxonomy the multi-id batch needs and the notes-overwrite warning. Hooks are
// NOT among them: they fire from the write plumbing now (the notifying provider
// wired in main.go), which is what makes an update fire the same events here as
// it does on the embedded path.
// the advisory reassign pre-read, the per-id failure taxonomy the multi-id
// batch needs (a template refusal is one of its verdicts; the guard itself is
// the role's) and the notes-overwrite warning. Hooks are NOT among them: they
// fire from the write plumbing now (the notifying provider wired in main.go),
// which is what makes an update fire the same events here as it does on the
// embedded path.
//
// Provenance carries the commit message this path has always written, so `bd
// dolt log` reads the same after the move as before it. The plane is
@ -189,13 +190,12 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
}
// proxiedUpdateTarget reads the row an update is about through the query role,
// for the things the mutation's own result cannot answer: whether the target is
// a template, whether an unguarded assignee edit is about to take the issue
// from a live foreign holder, whether --notes is about to replace existing
// notes, and whether --defer="" should also clear a deferred status. It no
// longer reads the pre-state to decide a hook: a status-crossing update fires
// on_update and nothing else, from the plumbing, exactly as it does on the
// embedded path.
// for the things the mutation's own result cannot answer: whether an unguarded
// assignee edit is about to take the issue from a live foreign holder, whether
// --notes is about to replace existing notes, and whether --defer="" should
// also clear a deferred status. It no longer reads the pre-state to decide a
// hook: a status-crossing update fires on_update and nothing else, from the
// plumbing, exactly as it does on the embedded path.
func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure) {
rd, err := proxiedIssueReader()
if err != nil {
@ -212,10 +212,8 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type
return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}
}
current := &details.Issue
if err := validateIssueUpdatable(id, current); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return nil, &updateIDFailure{ID: id, Error: err.Error()}
}
// The template guard is the role's, enforced inside the mutation;
// proxiedUpdateFailure prints its refusal as this route always did.
// bd-98s5c: an unguarded assignee update must not silently overwrite
// another actor's live claim. Skipped under --if-assignee, whose CAS names
// the holder explicitly (park stays possible without --force), and under
@ -266,6 +264,10 @@ func proxiedClaimPoolAliases(ctx context.Context) func() []string {
// longer owns, so both now read as the generic update failure. The id still
// fails, loudly and non-zero.
func proxiedUpdateFailure(id string, claim bool, err error) *updateIDFailure {
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
fmt.Fprintf(os.Stderr, "%s\n", refusal)
return &updateIDFailure{ID: id, Error: refusal.Error()}
}
switch {
case errors.Is(err, storage.ErrNotFound):
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)

View file

@ -0,0 +1,35 @@
package main
import (
"errors"
"fmt"
"testing"
"github.com/steveyegge/beads/issueops"
)
// TestTemplateReadOnlyRefusalKeepsTheCLISentence pins what `bd update`,
// `bd assign` and the proxied `bd tag` print now that the template guard is the
// role's: the sentence they printed when it was a CLI pre-read, naming the id
// as the caller typed it — however the refusal travelled (bare from the store,
// wrapped by the unit of work, or rebuilt by the served client against the
// resolved id).
func TestTemplateReadOnlyRefusalKeepsTheCLISentence(t *testing.T) {
const typed = "tp-ab"
want := "cannot modify template " + typed + ": templates are read-only; use 'bd mol pour' to create a work item"
for name, err := range map[string]error{
"bare": &issueops.TemplateReadOnlyError{IssueID: "tp-abc123"},
"wrapped": fmt.Errorf("update tp-abc123: %w", &issueops.TemplateReadOnlyError{IssueID: "tp-abc123"}),
} {
refusal, ok := templateReadOnlyRefusal(typed, err)
if !ok {
t.Fatalf("%s: templateReadOnlyRefusal did not recognize %v", name, err)
}
if refusal.Error() != want {
t.Errorf("%s: refusal reads %q, want %q", name, refusal.Error(), want)
}
}
if _, ok := templateReadOnlyRefusal(typed, errors.New("something else")); ok {
t.Errorf("an unrelated error was taken for the template refusal")
}
}

View file

@ -106,6 +106,7 @@ go_test(
"sweep_test.go",
"timed_provider_binding_test.go",
"tree_test.go",
"update_template_test.go",
"update_test.go",
"wire_bijection_test.go",
"wire_revision_test.go",

View file

@ -1047,7 +1047,7 @@ type ContextResponse struct {
// OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required.
BeadsDir *string `json:"beads_dir,omitempty"`
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
//
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
Capabilities []string `json:"capabilities"`
@ -1607,7 +1607,7 @@ type Problem struct {
// IT IS OPTIONAL. A refusal that could not name its blockers omits it and keeps the generic `detail`; absence means "this refusal did not name them", never "nothing blocks it". Re-read the issue's dependencies then.
Blockers *[]Blocker `json:"blockers,omitempty"`
// Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `unauthenticated` (401, only on a server configured with a token file), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault).
// Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `unauthenticated` (401, only on a server configured with a token file), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), `template_read_only` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault).
Code string `json:"code"`
// DeclaredLater With `invalid_argument` on a batch operation whose items may name each other: whether the unresolvable key IS declared by the request, at a LATER index.
@ -2096,6 +2096,9 @@ type UpdateIssueRequest struct {
// Actor Who is editing the issue. `ClaimRequest.actor`'s rules exactly: the server trims it, then refuses an empty result, anything longer than 256 BYTES (the `maxLength` above counts characters — the byte limit is the binding one), and any control character including newline. The value reaches the history entry's attribution and the storage commit message, so an unvalidated newline would forge audit-trail lines.
Actor string `json:"actor"`
// AllowTemplate The caller edits a template deliberately, so the template read-only refusal (`409 template_read_only`) stands down for this request. `bd label` and `bd set-state` send it: they have always written to templates. It bypasses nothing else, and has no effect on an issue that is not a template. Advertised by the `issues.update.allowTemplate` capability token; a server that predates the member refuses it as an unknown parameter, and such a server never applies the template guard either.
AllowTemplate *bool `json:"allow_template,omitempty"`
// Claim Claims the issue for `actor` in the same transaction as `patch`: `bd update <id> --claim`, served by the same role. The claim sets `assignee` to `actor` and `status` to `in_progress`, then the patch applies, so a `patch.assignee` or `patch.status` overrides the claim's value. Eligibility is `{id}:claim`'s: a claimable status, and unassigned, already held by `actor`, or held by a configured claim pool. Held by `actor` and `in_progress` already is an idempotent success. A refusal is `409 already_claimed` or `409 not_claimable` naming `claim`, and writes nothing — the patch included. With `claim: true` the `patch` may be empty. It must not be combined with `expected_assignee`, `expected_status` or `force_assignee_transfer`; a request that does is a `400` naming `claim`.
Claim *bool `json:"claim,omitempty"`

View file

@ -1054,6 +1054,11 @@ func (s *Server) failApplyBatch(w http.ResponseWriter, r *http.Request, request
s.fail(w, r, at(closeBlockedResult(err,
"an item closes a blocked issue", "clear the blocker, or send the item's force flag"), ""))
// An update item naming a template: the shared mapping plus the item
// members.
case errors.Is(err, issueops.ErrTemplateReadOnly):
s.fail(w, r, at(ClassifyError(err), ""))
case errors.Is(err, storage.ErrAlreadyClaimed):
res := at(newResult(CodeAlreadyClaimed,
"an update transfers work away from a live foreign owner; send `force_assignee_transfer`, or guard with `expected_assignee`"), "assignee")

View file

@ -136,6 +136,16 @@ const (
// notes and the patched ones), not about a foreign actor's identity a
// client might need to display.
CodeNotesOverwrite Code = "notes_overwrite_refused"
// CodeTemplateReadOnly is a guarded mutation that names a template;
// operationCodes lists the operations that answer it, and not every verb
// guards templates yet (bd-jkp9v3). Templates are read-only — work comes
// out of one by pouring it, which creates new issues — so no force flag
// waives it: the same request refuses for as long as the row is a
// template. The one stand-down is updateIssue's `allow_template`, a
// deliberate template edit (bd label, bd set-state).
// A 409 for CodeNotClosable's reason: the body is well-formed and the
// STATE of the named row refuses it.
CodeTemplateReadOnly Code = "template_read_only"
// CodeDependencyCycle covers BOTH never-makes-progress refusals a requested
// edge set can earn: a scheduling cycle, and a blocking edge against the
// issue's own ancestor or descendant. They are one code because they have
@ -262,6 +272,7 @@ var codeStatus = map[Code]int{
CodeNotClaimable: http.StatusConflict,
CodeNotClosable: http.StatusConflict,
CodeNotesOverwrite: http.StatusConflict,
CodeTemplateReadOnly: http.StatusConflict,
CodeNotReleasable: http.StatusConflict,
CodeDependencyCycle: http.StatusConflict,
CodeDependencyExists: http.StatusConflict,
@ -897,9 +908,14 @@ var operationCodes = map[string][]Code{
//
// not_claimable arrived with `claim`, beside the already_claimed it shares
// with the fence: a refused claim answers as claimIssue does.
//
// template_read_only is the role refusing an update of a template:
// templates are read-only, no force flag waives it, and only
// `allow_template` stands it down.
OpUpdateIssue: {
CodeInvalidArgument, CodeUnauthenticated, CodeNotFound,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeNotesOverwrite,
CodeTemplateReadOnly,
CodeNotClaimable, CodeDependencyCycle, CodeDependencyExists,
CodeBusy, CodeDBUnavailable, CodeInternal,
},
@ -962,6 +978,7 @@ var operationCodes = map[string][]Code{
OpApplyBatch: {
CodeInvalidArgument, CodeUnauthenticated, CodeNotFound,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeNotesOverwrite, CodeAlreadyExists,
CodeTemplateReadOnly,
CodeDependencyCycle, CodeDependencyExists,
CodeBusy, CodeDBUnavailable, CodeInternal,
},
@ -1543,6 +1560,11 @@ func ClassifyError(err error) Result {
case errors.Is(err, issueops.ErrCloseBlocked):
return closeBlockedResult(err, "issue is blocked", "clear the blocker or close with force")
// The detail is this server's own words rather than the role's message,
// for the reason Problem.detail gives.
case errors.Is(err, issueops.ErrTemplateReadOnly):
return newResult(CodeTemplateReadOnly, "this issue is a template, and templates are read-only; pour it to create work")
case errors.Is(err, ErrBusy):
res := newResult(CodeBusy, "")
res.RetryAfterSeconds = retryAfterSaturation

View file

@ -161,6 +161,19 @@ const CapIssuesSweepLimit = "issues.sweep.limit"
// predate it; it refuses locally before the dial when the token is absent.
const CapBatchApplyDepAddLineage = "issues.batchApply.depAddLineage"
// CapIssuesUpdateAllowTemplate is the behavior capability that advertises
// two things together: updateIssue enforces the role's template read-only
// refusal, and UpdateIssueRequest's `allow_template` member (update.go) stands
// it down for one request (the caller edits a template deliberately). An
// older server predating this token answers the member with
// `400 invalid_argument`/`unknown_parameter` and applies no template guard,
// so a client that does not see the token refuses a template update itself
// before the dial and sends the request without the member. That fallback
// covers updateIssue only: an applyBatch `update` item gets no client-side
// check (its target resolves on the server), so through an older server it
// still edits a template (bd-jkp9v3).
const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate"
// customMethodTarget splits the custom method off the segment the router
// matched, and reports the row that claims it.
//
@ -922,7 +935,7 @@ func (r route) specPathOf() string {
var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapIssuesListSort, CapIssuesCountScope,
CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit,
CapBatchApplyDepAddLineage,
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate,
}
// Capabilities lists what this build advertises in ContextResponse.capabilities:

View file

@ -637,7 +637,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
// oracle rather than a second call to the code under test.
want = append(want, "project.enforce", "issues.batchApplyLarge", "issues.list.sort", "issues.count.scope",
"issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit",
"issues.batchApply.depAddLineage")
"issues.batchApply.depAddLineage", "issues.update.allowTemplate")
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)

View file

@ -2501,10 +2501,11 @@ paths:
'409':
description: >-
The request is well-formed and the STATE refuses it, and NOTHING WAS
WRITTEN. Six codes, each inherited from the operation that already
publishes it rather than minted here, and described in the
paragraphs below — `dependency_cycle` and `dependency_exists` share
one, because they are one member reaching the graph.
WRITTEN. Eight codes, described in the paragraphs below; all but
`template_read_only` are inherited from the operation that already
publishes them rather than minted here, and `dependency_cycle` and
`dependency_exists` share one paragraph, because they are one member
reaching the graph.
`already_claimed` and `not_claimable` with `param: "claim"` are a
@ -2557,9 +2558,18 @@ paths:
both of which write blocking edges and do carry it: this operation
publishes no member that writes one. What you get here is the plain
scheduling cycle, every time.
`template_read_only` is an update of a template. Templates are
read-only — work comes out of one by pouring it — so every update
naming one refuses, whatever the patch and force flags, unless it
sets `allow_template` (a deliberate template edit).
It is checked after the guards above, so a stale guard still answers
`precondition_failed`.
x-bd-codes:
[already_claimed, dependency_cycle, dependency_exists,
not_claimable, not_closable, notes_overwrite_refused, precondition_failed]
not_claimable, not_closable, notes_overwrite_refused, precondition_failed,
template_read_only]
content:
application/problem+json:
schema:
@ -4328,6 +4338,11 @@ paths:
per-item bypasses, and a forced item never earns this.
`template_read_only` is an `update` item whose target is a
template, exactly as `PATCH /v0/beads/issues/{id}` answers it; no
item member bypasses it.
`already_claimed` is the assignee fence: an `update` whose
`patch.assignee` transfers work away from a live foreign in-progress
owner. `update.force_assignee_transfer` is the bypass, and
@ -4357,7 +4372,8 @@ paths:
a malformed request.
x-bd-codes:
[already_claimed, already_exists, dependency_cycle,
dependency_exists, not_closable, notes_overwrite_refused, precondition_failed]
dependency_exists, not_closable, notes_overwrite_refused, precondition_failed,
template_read_only]
content:
application/problem+json:
schema:
@ -8065,7 +8081,11 @@ components:
`issues.batchApply.depAddLineage`, which announces that a
`dep_add` item on `POST /v0/beads/issues:batchApply` accepts
`has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than
a `400` naming the member unknown. The
a `400` naming the member unknown, and
`issues.update.allowTemplate`, which announces that
`PATCH /v0/beads/issues/{id}` accepts `allow_template` (see
`UpdateIssueRequest`) rather than a `400` naming the member
unknown. The
list grows additively, and an operation never appears here unless
it is fully implemented. This is how a client checks for an
operation or a behavior — never the version string.
@ -11597,6 +11617,18 @@ components:
`expected_assignee` exemption: there is no compare-and-set that
authorizes a notes overwrite, so combining the two is legal and
each answers its own question.
allow_template:
type: boolean
default: false
description: >-
The caller edits a template deliberately, so the template read-only
refusal (`409 template_read_only`) stands down for this request.
`bd label` and `bd set-state` send it: they have always written to
templates. It bypasses nothing else, and has no effect on an issue
that is not a template. Advertised by the
`issues.update.allowTemplate` capability token; a server that
predates the member refuses it as an unknown parameter, and such a
server never applies the template guard either.
IssuePatchBody:
type: object
@ -12153,6 +12185,7 @@ components:
configured with a token file), `not_found` (404),
`already_claimed` (409), `not_claimable` (409),
`not_closable` (409), `not_releasable` (409),
`template_read_only` (409),
`dependency_cycle` (409), `dependency_exists` (409),
`already_exists` (409), `precondition_failed` (409),
`events_journal_disabled` (409), `events_journal_truncated` (410),

View file

@ -39,7 +39,8 @@ const (
var (
updateRequestMembers = []string{
"actor", updateClaimMember, "expected_assignee", "expected_status", "expected_version",
"force_assignee_transfer", "force_close_policy", "force_notes_overwrite", updatePatchMember,
"force_assignee_transfer", "force_close_policy", "force_notes_overwrite", "allow_template",
updatePatchMember,
}
issuePatchMembers = []string{
"title", "description", "design", "acceptance_criteria",
@ -181,6 +182,12 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string
if !ok {
return issueops.UpdateRequest{}, false
}
// allow_template is passed through: the role owns the template guard and
// what standing it down means.
allowTemplate, ok := s.booleanMember(w, r, members, "allow_template")
if !ok {
return issueops.UpdateRequest{}, false
}
if forceNotesOverwrite && !patch.Notes.Set {
s.fail(w, r, InvalidArgument("force_notes_overwrite", ReasonInvalidValue,
"`force_notes_overwrite` bypasses the fence on a NOTES REPLACEMENT; send `patch.notes` with it"))
@ -244,6 +251,7 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string
ForceClosePolicy: forceClosePolicy,
ForceAssigneeTransfer: forceAssigneeTransfer,
ForceNotesOverwrite: forceNotesOverwrite,
AllowTemplate: allowTemplate,
Provenance: updateProvenance,
}, true
}

View file

@ -0,0 +1,107 @@
package httpapi
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/steveyegge/beads/issueops"
)
// The template guard is the ROLE's (issueops.Lifecycle.Update, and the batch
// applier's update items, which share its body), so these cases drive a fake
// role that refuses the way the real one does and pin what the wire makes of
// it. The real role behind a real server is the served leg of the conformance
// contracts (internal/httpclient: TestServedLifecycleUpdateRefusesATemplate and
// TestServedBatchApplyUpdateItemsRefuseATemplate), which also proves the client
// rebuilds the typed error.
// templateRefusal is the refusal as a unit-of-work backend returns it: wrapped,
// so the mapping has to find it by type rather than by being handed the value.
func templateRefusal() error {
return fmt.Errorf("update bd-1: %w", &issueops.TemplateReadOnlyError{IssueID: "bd-1"})
}
func assertTemplateDetailIsOurs(t *testing.T, detail any) {
t.Helper()
text, _ := detail.(string)
if text == "" || strings.Contains(text, "cannot modify template") {
t.Errorf("detail = %q, want this server's own sentence rather than the role's", text)
}
}
func TestUpdateOfATemplateIsATypedConflict(t *testing.T) {
lifecycle := &roleLifecycle{updateErr: templateRefusal()}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"title":"edited"},"force_close_policy":true}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeTemplateReadOnly) {
t.Errorf("code = %v, want %s", body["code"], CodeTemplateReadOnly)
}
assertTemplateDetailIsOurs(t, body["detail"])
// The handler decides nothing: the request reached the role whole, force
// flag included, and the refusal is the role's.
if got := lifecycle.updateRequests(); len(got) != 1 || !got[0].ForceClosePolicy {
t.Fatalf("the role received %+v, want one request carrying ForceClosePolicy", got)
}
}
func TestApplyBatchUpdateItemOnATemplateIsATypedConflict(t *testing.T) {
applier := &roleBatchApplier{err: itemErr(1, issueops.ItemUpdate, "", "bd-1", templateRefusal())}
ts := newApplyBatchServer(t, applier)
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeTemplateReadOnly) {
t.Errorf("code = %v, want %s", body["code"], CodeTemplateReadOnly)
}
if body["item_index"] != float64(1) || body["item_kind"] != "update" || body["item_issue_id"] != "bd-1" {
t.Errorf("item members = %v/%v/%v, want 1/update/bd-1", body["item_index"], body["item_kind"], body["item_issue_id"])
}
assertTemplateDetailIsOurs(t, body["detail"])
}
// TestUpdateCarriesAllowTemplateToTheRole pins that `allow_template` is decoded
// onto the role request and nothing else: the role owns what it waives.
func TestUpdateCarriesAllowTemplateToTheRole(t *testing.T) {
for _, tc := range []struct {
body string
want bool
}{
{`{"actor":"alice","patch":{"title":"edited"},"allow_template":true}`, true},
{`{"actor":"alice","patch":{"title":"edited"},"allow_template":false}`, false},
{`{"actor":"alice","patch":{"title":"edited"}}`, false},
} {
lifecycle := &roleLifecycle{updateResult: issueops.UpdateResult{Issue: updatedIssue("bd-1"), Changed: true}}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, tc.body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("%s: status = %d, want 200: %s", tc.body, resp.StatusCode, readAll(t, resp))
}
_ = resp.Body.Close()
got := lifecycle.updateRequests()
if len(got) != 1 || got[0].AllowTemplate != tc.want {
t.Errorf("%s: the role received %+v, want AllowTemplate=%v", tc.body, got, tc.want)
}
}
}
func TestUpdateRefusesANonBooleanAllowTemplate(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"title":"edited"},"allow_template":"yes"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.updateRequests(); len(got) != 0 {
t.Errorf("the role was reached with %+v", got)
}
}

View file

@ -4781,6 +4781,12 @@
"type": "string",
"required": true
},
{
"schema": "UpdateIssueRequest",
"member": "allow_template",
"type": "boolean",
"required": false
},
{
"schema": "UpdateIssueRequest",
"member": "claim",

View file

@ -15,6 +15,7 @@ import (
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
@ -330,6 +331,11 @@ func (l *httpLifecycle) Update(ctx context.Context, req issueops.UpdateRequest)
return issueops.UpdateResult{}, invalid("update names no field to write")
}
req, err = l.applyTemplateGuardForServer(ctx, req)
if err != nil {
return issueops.UpdateResult{}, err
}
res, err := l.wire.UpdateIssue(ctx, req.IssueID, req.Actor, patch, updateGuards(req), updateFlags(req))
if err != nil {
if req.Claim && isClaimOnlyUpdate(req) && serverPredatesUpdateClaim(err) {
@ -384,6 +390,7 @@ func updateFlags(req issueops.UpdateRequest) wire.UpdateFlags {
ForceAssigneeTransfer: req.ForceAssigneeTransfer,
ForceClosePolicy: req.ForceClosePolicy,
ForceNotesOverwrite: req.ForceNotesOverwrite,
AllowTemplate: req.AllowTemplate,
}
}
@ -406,6 +413,38 @@ func serverPredatesUpdateClaim(err error) bool {
problem.Param == "claim"
}
// applyTemplateGuardForServer decides, BEFORE the dial and from the cached
// handshake, how the template read-only guard (storage
// issueops.AuthorizeTemplateUpdate) reaches the server this request goes to.
//
// A server advertising wire.CapIssuesUpdateAllowTemplate enforces the guard in
// the update's own transaction and accepts `allow_template`, so req goes out
// as is. A server without the token predates both: it would edit a template
// for any caller, and it refuses `allow_template` as an unknown parameter. So
// against it the client runs the same rule itself, on a pre-read of the row —
// the refusal `bd update` and `bd assign` always made before dialing — and
// clears AllowTemplate, which that server has no guard to stand down. A row
// the pre-read cannot find goes out unchanged: the server's own not-found
// answer is the one to report.
func (l *httpLifecycle) applyTemplateGuardForServer(ctx context.Context, req issueops.UpdateRequest) (issueops.UpdateRequest, error) {
snap, err := l.store.snapshot(ctx)
if err != nil {
return req, err
}
if snap != nil && slices.Contains(snap.Capabilities, wire.CapIssuesUpdateAllowTemplate) {
return req, nil
}
if req.AllowTemplate {
req.AllowTemplate = false
return req, nil
}
before, err := l.store.GetIssue(ctx, req.IssueID)
if err != nil {
return req, err
}
return req, storageops.AuthorizeTemplateUpdate(before, req)
}
// Close dials POST issues/{id}:close.
func (l *httpLifecycle) Close(ctx context.Context, req issueops.CloseRequest) (issueops.CloseResult, error) {
if err := requireActor(req.Actor); err != nil {
@ -625,6 +664,7 @@ func isClaimOnlyUpdate(req issueops.UpdateRequest) bool {
!req.ForceAssigneeTransfer &&
!req.ForceClosePolicy &&
!req.ForceNotesOverwrite &&
!req.AllowTemplate &&
!req.IssuePlaneOnly &&
req.Provenance == "" &&
req.ExpectedVersion == nil &&

View file

@ -247,6 +247,20 @@ func TestServedBatchApplyRefusesAnUnusableRequest(t *testing.T) {
conformance.RunBatchApplyRefusesAnUnusableRequest(t, t.Context(), newServedBatchApplyFixture(t, "hba26"))
}
func TestServedBatchApplyUpdateItemsRefuseATemplate(t *testing.T) {
conformance.RunBatchApplyUpdateItemsRefuseATemplate(t, t.Context(), newServedBatchApplyFixture(t, "hbatu"))
}
// TestServedBatchApplySplicesTheMetadataOfATemplateItCreates is PARKED: a create
// item cannot make a template over the v0 wire (ApplyCreateItem publishes no
// is_template member), so the client refuses the plan before the splice could
// be reached. The served update guard itself is pinned by the case above.
func TestServedBatchApplySplicesTheMetadataOfATemplateItCreates(t *testing.T) {
skipKnownDivergence(t, "W-CreateItem.Issue", parkBead,
"ApplyCreateItem publishes no is_template member, so a plan that creates a template is refused client-side")
conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, t.Context(), newServedBatchApplyFixture(t, "hbats"))
}
// TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed wires the dep_add
// HasSpawner/ThreadID lineage conformance case onto the http leg (S5): a
// served default Config always advertises CapBatchApplyDepAddLineage (it is

View file

@ -762,6 +762,19 @@ func TestServedLifecycleUpdateProvenanceLabelsHistory(t *testing.T) {
conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, t.Context(), newServedUpdateFixture(t, "hlpv"))
}
// TestServedLifecycleUpdateRefusesATemplate is the served leg of the template
// guard: bd serve refuses with template_read_only and the client rebuilds the
// typed error — sentence included — the embedded store returns.
func TestServedLifecycleUpdateRefusesATemplate(t *testing.T) {
conformance.RunLifecycleUpdateRefusesATemplate(t, t.Context(), newServedUpdateFixture(t, "hlut"))
}
// TestServedLifecycleUpdateAllowTemplateEditsATemplate is the served leg of
// the guard's stand-down: allow_template rides the wire and the role honours it.
func TestServedLifecycleUpdateAllowTemplateEditsATemplate(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, t.Context(), newServedUpdateFixture(t, "hlua"))
}
func TestServedLifecycleUpdateRefusesUnknownIDsAndActorlessRequests(t *testing.T) {
conformance.RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests(t, t.Context(), newServedUpdateFixture(t, "hluu"))
}

View file

@ -209,6 +209,18 @@ const CapSweepLimit = "issues.sweep.limit"
// asked to carry against an older server.
const CapBatchApplyDepAddLineage = "issues.batchApply.depAddLineage"
// CapIssuesUpdateAllowTemplate is the behavior capability announcing that
// updateIssue enforces the template read-only guard and accepts
// `allow_template` to stand it down, spelled exactly as httpapi's constant of
// the same name. Lifecycle.Update reads it from the cached handshake before
// the dial (applyTemplateGuardForServer): against a server without it, which
// predates the guard, the client refuses a template update itself on a
// pre-read and never sends `allow_template`. BatchApplier does not read it:
// an applyBatch `update` item gets no client-side check (its target resolves
// on the server), so through an older server it still edits a template
// (bd-jkp9v3).
const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate"
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
// that the ready, claim and close operations of this server apply bd's
// external-dependency policy themselves, spelled exactly as httpapi's constant
@ -349,7 +361,7 @@ func (e *WireRevisionSkewError) Unwrap() error { return ErrWireRevisionSkew }
var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope,
CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit,
CapBatchApplyDepAddLineage,
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate,
}
// CapabilityFor reports the capability token gating op, and whether op is on

View file

@ -638,6 +638,13 @@ var codeSentinel = map[string]func(*ProblemError, target) error{
// sentinel callers already switch on locally.]
"notes_overwrite_refused": func(*ProblemError, target) error { return issueops.ErrNotesOverwrite },
// The template guard, rebuilt whole so a caller reads the same typed error
// — and the same message — the embedded store returns. The row comes from
// the request or, on a batch, from `item_issue_id`.
"template_read_only": func(e *ProblemError, t target) error {
return &issueops.TemplateReadOnlyError{IssueID: refusedIssueID(e, t)}
},
// The same rule again: `issue_id` present means the edge named the issue's
// own ancestor or descendant, absent means a plain scheduling cycle. The
// three hierarchy members travel together and rebuild the typed error whole

View file

@ -196,11 +196,11 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
if !slices.Equal(behaviorCapabilities, []string{
httpapi.CapProjectEnforce, httpapi.CapBatchApplyLarge, httpapi.CapIssuesListSort, httpapi.CapIssuesCountScope,
httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit,
httpapi.CapBatchApplyDepAddLineage,
httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate,
}) {
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit and "+
"issues.batchApply.depAddLineage tokens", behaviorCapabilities)
"issues.batchApply.depAddLineage and issues.update.allowTemplate tokens", behaviorCapabilities)
}
}

View file

@ -228,7 +228,7 @@ type updateBody struct {
Actor string `json:"actor"`
Patch map[string]any `json:"patch"`
UpdateGuards
// The four UpdateFlags, each sent only when true (setItemBool's
// The five UpdateFlags, each sent only when true (setItemBool's
// convention: an explicit false is the default said twice). Absent is
// what an older server that predates a member reads correctly, which is
// what lets a request that sets none of them reach a server that knows
@ -237,15 +237,16 @@ type updateBody struct {
ForceAssigneeTransfer *bool `json:"force_assignee_transfer,omitempty"`
ForceClosePolicy *bool `json:"force_close_policy,omitempty"`
ForceNotesOverwrite *bool `json:"force_notes_overwrite,omitempty"`
AllowTemplate *bool `json:"allow_template,omitempty"`
}
// UpdateFlags are updateIssue's four top-level booleans: the claim, and the
// three force overrides. UpdateIssueRequest publishes all four
// (internal/httpapi/apigen's generated type) and none is a GUARD — none carries
// a comparison value, unlike every member UpdateGuards holds — so they travel
// as their own struct rather than joining that one.
// UpdateFlags are updateIssue's five top-level booleans: the claim, the three
// force overrides and the template stand-down. UpdateIssueRequest publishes all
// five (internal/httpapi/apigen's generated type) and none is a GUARD — none
// carries a comparison value, unlike every member UpdateGuards holds — so they
// travel as their own struct rather than joining that one.
//
// It is a struct rather than four arguments for UpdateGuards' reason: four
// It is a struct rather than five arguments for UpdateGuards' reason: five
// positional booleans side by side are the shape a caller transposes, and a
// transposed force flag is a bypass nobody asked for.
type UpdateFlags struct {
@ -268,6 +269,9 @@ type UpdateFlags struct {
// replace existing non-empty notes with different non-empty content. The
// server requires patch.notes beside it.
ForceNotesOverwrite bool
// AllowTemplate stands the template read-only refusal down for this
// request (bd label, bd set-state edit templates by design).
AllowTemplate bool
}
// UpdateIssue patches one issue. It is the only PATCH on this surface: the
@ -291,6 +295,7 @@ func (c *Client) UpdateIssue(ctx context.Context, id, actor string, patch map[st
ForceAssigneeTransfer: trueOrAbsent(flags.ForceAssigneeTransfer),
ForceClosePolicy: trueOrAbsent(flags.ForceClosePolicy),
ForceNotesOverwrite: trueOrAbsent(flags.ForceNotesOverwrite),
AllowTemplate: trueOrAbsent(flags.AllowTemplate),
}
r := Request{Op: OpUpdateIssue, Method: http.MethodPatch, Path: path, Body: body, IssueID: id}
if err := c.dispatch(ctx, r, &out); err != nil {

View file

@ -262,6 +262,8 @@ func writeShapes() []writeShape {
"ForceAssigneeTransfer": member("force_assignee_transfer"),
"ForceClosePolicy": member("force_close_policy"),
"Claim": member("claim"),
// The template guard's stand-down (bd label, bd set-state).
"AllowTemplate": member("allow_template"),
},
},
{

View file

@ -383,7 +383,13 @@ func (s *stubWire) ListReadyWork(_ context.Context, _ url.Values) (*apigen.Ready
func stubStore(t *testing.T, w *stubWire) *Store {
t.Helper()
return New(testTarget(t), w, &apigen.ContextResponse{BdVersion: "1.2.3"})
// A current server: it advertises issues.update.allowTemplate, so
// Lifecycle.Update leaves the template guard to it and pre-reads nothing.
// TestUpdateTemplateGuardAgainstAServerThatPredatesIt covers the older one.
return New(testTarget(t), w, &apigen.ContextResponse{
BdVersion: "1.2.3",
Capabilities: []string{wire.CapIssuesUpdateAllowTemplate},
})
}
func set[T any](v T) issueops.Field[T] { return issueops.Field[T]{Set: true, Value: v} }
@ -951,6 +957,12 @@ func TestUpdateSendsEachFlagOnlyWhenRequested(t *testing.T) {
want: wire.UpdateFlags{ForceClosePolicy: true},
wantPatch: map[string]any{"status": string(issueops.StatusClosed)},
},
{
name: "allow template",
req: issueops.UpdateRequest{Patch: notes, AllowTemplate: true},
want: wire.UpdateFlags{AllowTemplate: true},
wantPatch: map[string]any{"notes": "replacement notes"},
},
{
name: "a claim alone sends the empty patch",
req: issueops.UpdateRequest{Claim: true},
@ -1812,3 +1824,89 @@ func TestWriteAccessorsRefuseWithoutATransport(t *testing.T) {
t.Errorf("CloseIssue without a transport = %v, want ErrNoTransport", err)
}
}
// templateServerWire is a stubWire whose generic read half answers getIssue
// with row (nil: not found), recording the read in the same call log as the
// writes, so a test can see whether a pre-read ran and whether it ran BEFORE
// updateIssue — or instead of it.
type templateServerWire struct {
*stubWire
row *types.Issue
}
func (w *templateServerWire) Preflight(context.Context, string) error { return nil }
func (w *templateServerWire) Do(_ context.Context, req wire.Request, out any) error {
if req.Op != wire.OpGetIssue {
return fmt.Errorf("templateServerWire: unexpected generic dispatch %q", req.Op)
}
w.calls = append(w.calls, "getIssue:"+req.IssueID)
if w.row == nil {
return fmt.Errorf("no issue %s: %w", req.IssueID, issueops.ErrNotFound)
}
*out.(*types.IssueDetails) = types.IssueDetails{Issue: *w.row, Revision: "1"}
return nil
}
// TestUpdateTemplateGuardAgainstAServerThatPredatesIt is a NEW client against an
// OLD server: a handshake without issues.update.allowTemplate is a server that
// applies no template guard and refuses `allow_template` as unknown. The client
// decides from the cached handshake, before the dial: it refuses a template
// update itself on a pre-read (the refusal bd update always made), never sends
// `allow_template` to it, and against a server that DOES advertise the token
// it neither pre-reads nor drops the member.
func TestUpdateTemplateGuardAgainstAServerThatPredatesIt(t *testing.T) {
template := &types.Issue{ID: "bd-1", Title: "tmpl", IsTemplate: true}
plain := &types.Issue{ID: "bd-1", Title: "work"}
for _, tc := range []struct {
name string
guarded bool // the handshake advertises the token
row *types.Issue
allow bool
wantCalls []string
wantRefused bool
wantFlag bool
}{
{name: "old server: a template update is refused before the dial", row: template,
wantCalls: []string{"getIssue:bd-1"}, wantRefused: true},
{name: "old server: a plain row goes out after the pre-read", row: plain,
wantCalls: []string{"getIssue:bd-1", "updateIssue:bd-1"}},
{name: "old server: a row the pre-read cannot find goes out for the server to answer", row: nil,
wantCalls: []string{"getIssue:bd-1", "updateIssue:bd-1"}},
{name: "old server: allow_template is not sent and no pre-read runs", row: template, allow: true,
wantCalls: []string{"updateIssue:bd-1"}},
{name: "guarded server: no pre-read, the server owns the refusal", guarded: true, row: template,
wantCalls: []string{"updateIssue:bd-1"}},
{name: "guarded server: allow_template rides the wire", guarded: true, row: template, allow: true,
wantCalls: []string{"updateIssue:bd-1"}, wantFlag: true},
} {
t.Run(tc.name, func(t *testing.T) {
w := &templateServerWire{stubWire: &stubWire{update: &apigen.UpdateIssueResponse{Revision: "3"}}, row: tc.row}
snap := &apigen.ContextResponse{BdVersion: "1.2.3"}
if tc.guarded {
snap.Capabilities = []string{wire.CapIssuesUpdateAllowTemplate}
}
lifecycle, err := New(testTarget(t), w, snap).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
_, err = lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "writer", IssueID: "bd-1", AllowTemplate: tc.allow,
Patch: issueops.IssuePatch{Title: set("t")},
})
var refusal *issueops.TemplateReadOnlyError
if got := errors.As(err, &refusal); got != tc.wantRefused {
t.Fatalf("Update err = %v, want a TemplateReadOnlyError: %v", err, tc.wantRefused)
}
if !tc.wantRefused && err != nil {
t.Fatalf("Update: %v", err)
}
if !reflect.DeepEqual(w.calls, tc.wantCalls) {
t.Errorf("calls = %v, want %v", w.calls, tc.wantCalls)
}
if !tc.wantRefused && w.lastFlags.AllowTemplate != tc.wantFlag {
t.Errorf("sent allow_template = %v, want %v", w.lastFlags.AllowTemplate, tc.wantFlag)
}
})
}
}

View file

@ -255,6 +255,16 @@ func TestBatchApplyContract(t *testing.T) {
defer cancel()
conformance.RunBatchApplyRefusesAnUnusableRequest(t, ctx, fixture)
})
t.Run("UpdateItemsRefuseATemplate", func(t *testing.T) {
ctx, cancel := testContext(t)
defer cancel()
conformance.RunBatchApplyUpdateItemsRefuseATemplate(t, ctx, fixture)
})
t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) {
ctx, cancel := testContext(t)
defer cancel()
conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture)
})
}
// newDoltBatchApplyFixture composes the frozen role kit with this backend's

View file

@ -90,6 +90,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ProvenanceLabelsHistory", func(t *testing.T) {
conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture)
})
t.Run("RefusesATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusesATemplate(t, ctx, fixture)
})
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
}
func newDoltLifecycleUpdateFixture(t *testing.T, prefix string) (conformance.LifecycleUpdateFixture, context.Context, func()) {

View file

@ -187,6 +187,12 @@ func TestBatchApplyContract(t *testing.T) {
t.Run("RefusesAnUnusableRequest", func(t *testing.T) {
conformance.RunBatchApplyRefusesAnUnusableRequest(t, ctx, fixture)
})
t.Run("UpdateItemsRefuseATemplate", func(t *testing.T) {
conformance.RunBatchApplyUpdateItemsRefuseATemplate(t, ctx, fixture)
})
t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) {
conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture)
})
}
// newEmbeddedBatchApplyFixture composes the frozen role kit with this backend's

View file

@ -91,6 +91,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ProvenanceLabelsHistory", func(t *testing.T) {
conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture)
})
t.Run("RefusesATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusesATemplate(t, ctx, fixture)
})
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
}
func newEmbeddedLifecycleUpdateFixture(t *testing.T, te *testEnv, prefix string) conformance.LifecycleUpdateFixture {

View file

@ -231,6 +231,29 @@ func AuthorizeNotesOverwrite(before *types.Issue, request publicops.UpdateReques
return fmt.Errorf("%w: issue %s", storage.ErrNotesOverwrite, before.ID)
}
// AuthorizeTemplateUpdate refuses an update of a template with
// *publicops.TemplateReadOnlyError. Templates are read-only — work comes out of
// one by pouring it — so every update naming one refuses, whatever its patch
// and whatever force flags it carries: no force flag waives it (only the
// caller's explicit AllowTemplate does).
//
// It is the guard `bd update` (and assign, and the proxied mutations) used to
// apply as a pre-read in cmd/bd, which left bd serve, BatchApplier update items
// and library callers writing to templates bd refused. It sits beside the
// other update fences and is called from the same three places — ExecuteUpdate,
// and the unit-of-work update and batch legs — over the same-transaction
// pre-image, after the compare-and-set preconditions, so a stale guard still
// reports as the mismatch.
//
// request.AllowTemplate is the caller saying it edits a template deliberately
// (bd label, bd set-state); the guard stands down for that request only.
func AuthorizeTemplateUpdate(before *types.Issue, request publicops.UpdateRequest) error {
if before != nil && before.IsTemplate && !request.AllowTemplate {
return &publicops.TemplateReadOnlyError{IssueID: before.ID}
}
return nil
}
// ApplyMetadataPatch returns the canonical metadata value and whether it changes.
func ApplyMetadataPatch(current json.RawMessage, patch publicops.MetadataPatch) (json.RawMessage, bool, error) {
if !patch.Replace.Set && !patch.Merge.Set && len(patch.Set) == 0 && len(patch.Unset) == 0 {

View file

@ -481,11 +481,13 @@ func (r *applyBatchRun) spliceMetadataRefs(ctx context.Context, tx *sql.Tx) erro
return err
}
id := r.result.Items[index].IssueID
updated, tables, err := ExecuteUpdate(ctx, tx, publicops.UpdateRequest{
// Unguarded for templates: the splice finishes this request's own
// create, so a template it creates is not being modified.
updated, tables, err := executeUpdate(ctx, tx, publicops.UpdateRequest{
Actor: r.plan.Actor,
IssueID: id,
Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: set}},
})
}, false)
if err != nil {
return &publicops.ItemError{
Index: index, Kind: publicops.ItemCreate, Key: item.Create.Key, IssueID: id, Err: err,

View file

@ -136,6 +136,15 @@ func skippedDependencyError(skipped []skippedDependency) error {
// ExecuteUpdate applies a guarded update in tx and reports durable tables changed.
func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequest) (publicops.UpdateResult, ChangedTables, error) {
return executeUpdate(ctx, tx, request, true)
}
// executeUpdate is ExecuteUpdate with the template guard made optional, for the
// one caller that is not an update of an existing row: the batch apply's
// metadata splice, which finishes a CREATE item of the same request — a
// template the request itself is creating is still being written, not
// modified.
func executeUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequest, guardTemplate bool) (publicops.UpdateResult, ChangedTables, error) {
attempt := CloneUpdateRequest(request)
if attempt.Actor == "" || attempt.IssueID == "" {
return publicops.UpdateResult{}, nil, fmt.Errorf("%w: update requires actor and issue ID", storage.ErrValidation)
@ -171,6 +180,11 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
} else if err := CheckExpectedFieldsInTx(ctx, tx, attempt.IssueID, attempt.ExpectedAssignee, nil); err != nil {
return publicops.UpdateResult{}, nil, err
}
if guardTemplate {
if err := AuthorizeTemplateUpdate(before, attempt); err != nil {
return publicops.UpdateResult{}, nil, err
}
}
if err := AuthorizeAssigneeTransfer(ctx, tx, before, attempt); err != nil {
return publicops.UpdateResult{}, nil, err
}

View file

@ -76,8 +76,10 @@ func versionMintEdges(fns map[string]*journalscan.FuncInfo) func(*journalscan.Fu
// its own RecordVersionInTx: nothing it calls with the gate off can carry it
// on its behalf. TestCompositeMutationsCarryTheirOwnMint is what turns
// reviewer Probe 2 (delete ExecuteUpdate's final mint block) into a failure.
// ExecuteUpdate's body is executeUpdate (ExecuteUpdate is it with the template
// guard on), so the composite named here is the body that carries the mint.
var versionCompositeMutations = []string{
"ExecuteUpdate",
"executeUpdate",
"applyLabelPatch",
"applyParentPatch",
}

View file

@ -310,7 +310,7 @@ func (r *uowApplyRun) applyUpdate(ctx context.Context, index int, item *publicop
if err := validateUpdateRequest(request); err != nil {
return itemErr(err)
}
updated, err := r.runUpdate(ctx, request)
updated, err := r.runUpdate(ctx, request, true)
if err != nil {
return itemErr(err)
}
@ -332,7 +332,10 @@ func (r *uowApplyRun) applyUpdate(ctx context.Context, index int, item *publicop
// change. ga-v2k49 is a concrete instance of that drift: claimChanged's actor
// comparison here and there diverged (one verbatim, one not) until both were
// found and fixed independently.
func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateRequest) (publicops.UpdateResult, error) {
//
// guardTemplate is false only for the metadata splice, which finishes a create
// item of this request rather than modifying an existing row.
func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateRequest, guardTemplate bool) (publicops.UpdateResult, error) {
spec, err := updateSpec(request)
if err != nil {
return publicops.UpdateResult{}, validationError(err)
@ -346,6 +349,11 @@ func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateReq
return publicops.UpdateResult{}, err
}
if updatePreconditionsHold(request, before) {
if guardTemplate {
if err := storageissueops.AuthorizeTemplateUpdate(before, request); err != nil {
return publicops.UpdateResult{}, err
}
}
if err := authorizeAssigneeTransfer(ctx, r.uw, before, request); err != nil {
return publicops.UpdateResult{}, err
}
@ -527,11 +535,13 @@ func (r *uowApplyRun) spliceMetadataRefs(ctx context.Context) error {
return err
}
id := r.result.Items[index].IssueID
// Unguarded for templates, as the store-backed splice is: it finishes
// this request's own create.
updated, err := r.runUpdate(ctx, publicops.UpdateRequest{
Actor: r.plan.Actor,
IssueID: id,
Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: set}},
})
}, false)
if err != nil {
return &publicops.ItemError{Index: index, Kind: publicops.ItemCreate, Key: item.Create.Key, IssueID: id, Err: err}
}

View file

@ -157,6 +157,12 @@ func TestBatchApplyContract(t *testing.T) {
t.Run("RefusesAnUnusableRequest", func(t *testing.T) {
conformance.RunBatchApplyRefusesAnUnusableRequest(t, ctx, fixture)
})
t.Run("UpdateItemsRefuseATemplate", func(t *testing.T) {
conformance.RunBatchApplyUpdateItemsRefuseATemplate(t, ctx, fixture)
})
t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) {
conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture)
})
}
func newUOWBatchApplyFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchApplyFixture {

View file

@ -231,6 +231,9 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe
// version and status before authorizing, so when one is stale the fence
// stands down and ApplyUpdate reports the mismatch instead.
if updatePreconditionsHold(attempt, before) {
if err := storageissueops.AuthorizeTemplateUpdate(before, attempt); err != nil {
return publicops.UpdateResult{}, "", err
}
if err := authorizeAssigneeTransfer(ctx, uw, before, attempt); err != nil {
return publicops.UpdateResult{}, "", err
}

View file

@ -289,7 +289,7 @@ func TestBatchRunUpdateIdempotentClaimAcrossSpellingReportsNoChange(t *testing.T
result, err := run.runUpdate(context.Background(), publicops.UpdateRequest{
Actor: "gastown.mayor", IssueID: "bd-1", Claim: true,
})
}, true)
if err != nil {
t.Fatalf("runUpdate: %v, want success (same identity, different separator spelling)", err)
}
@ -307,7 +307,7 @@ func TestBatchRunUpdateClaimByGenuinelyDifferentIdentityReportsAChange(t *testin
result, err := run.runUpdate(context.Background(), publicops.UpdateRequest{
Actor: "gastown.dog-3", IssueID: "bd-1", Claim: true,
})
}, true)
if err != nil {
t.Fatalf("runUpdate: %v", err)
}

View file

@ -92,6 +92,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ProvenanceLabelsHistory", func(t *testing.T) {
conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture)
})
t.Run("RefusesATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusesATemplate(t, ctx, fixture)
})
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
}
func newUOWLifecycleUpdateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleUpdateFixture {

View file

@ -13,6 +13,7 @@ go_library(
"//internal/config",
"//internal/types",
"//internal/utils",
"//issueops",
],
)

View file

@ -6,6 +6,7 @@ import (
"strings"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// IssueValidator validates an issue and returns an error if validation fails.
@ -43,7 +44,7 @@ func NotTemplate() IssueValidator {
return nil // Let Exists() handle nil check if needed
}
if issue.IsTemplate {
return fmt.Errorf("cannot modify template %s: templates are read-only; use 'bd mol pour' to create a work item", id)
return &issueops.TemplateReadOnlyError{IssueID: id}
}
return nil
}

View file

@ -33,6 +33,7 @@ go_library(
"releaser.go",
"statsreporter.go",
"sweeper.go",
"template_errors.go",
"treewalker.go",
"versionreconciler.go",
"workspaceconfig.go",

View file

@ -104,7 +104,9 @@ type CreateItem struct {
// UpdateItem patches one existing issue, under UpdateRequest's rules.
type UpdateItem struct {
// Target names the issue to patch and must resolve BACKWARD — see Ref.
// Target names the issue to patch and must resolve BACKWARD — see Ref. A
// template target refuses with *TemplateReadOnlyError, exactly as
// Lifecycle.Update does: templates are read-only.
Target Ref
// Patch is the edit, read exactly as UpdateRequest.Patch is — including
// that Patch.Labels is the whole LabelPatch, so a label REMOVAL is

View file

@ -273,6 +273,14 @@ type UpdateRequest struct {
// It is the update-side spelling of CloseRequest.Force; a command adapter
// that maps one flag to both spells both.
ForceClosePolicy bool
// AllowTemplate says the caller edits a template deliberately, so the
// template read-only refusal (*TemplateReadOnlyError) stands down for this
// request. bd label and bd set-state set it to keep their pre-guard
// behavior: they have always written to templates. The zero value
// enforces the guard. It bypasses nothing else — validation, the
// preconditions, the assignee and notes fences and close policy still
// apply — and has no effect on an issue that is not a template.
AllowTemplate bool
// The three Expected* guards below are this package's FOUNDING spelling of
// the compare-and-set family, and the family's rules are stated once, at
// length, on DeleteRequest.ExpectedVersion (deleter.go) and
@ -478,7 +486,12 @@ type Lifecycle interface {
// returns ErrCloseBlocked, both without mutation. ForceClosePolicy bypasses
// those two refusals and nothing else. A Claim that loses its
// compare-and-set returns *ClaimConflictError carrying the state that beat
// it. A refusal or validation error leaves persistent state unchanged.
// it. An update of a template returns *TemplateReadOnlyError whatever its
// patch and force flags, unless it sets AllowTemplate — templates are
// read-only — checked after the
// compare-and-set preconditions, so a stale guard still reports the
// mismatch. A refusal or validation error leaves persistent state
// unchanged.
Update(context.Context, UpdateRequest) (UpdateResult, error)
// Close validates guards and commits the complete request as one atomic
// mutation. It moves the issue to literal StatusClosed, including from a

View file

@ -0,0 +1,30 @@
package issueops
import (
"errors"
"fmt"
)
// ErrTemplateReadOnly is returned when a mutation that guards templates names
// one. Every update does (Lifecycle.Update, a BatchApplier update item); not
// every verb does yet (bd-jkp9v3). Templates are read-only: the way to get
// work out of one is to pour it (`bd mol pour`), which creates new issues and
// leaves the template untouched. There is no force bypass — no Force flag
// waives it; only an update that sets UpdateRequest.AllowTemplate (bd label,
// bd set-state) is let through.
var ErrTemplateReadOnly = errors.New("templates are read-only")
// TemplateReadOnlyError reports the template a mutation was refused for. Its
// message is the sentence `bd` has always printed for the refusal, so a caller
// that renders err.Error() reads the same line whichever backend refused.
type TemplateReadOnlyError struct {
// IssueID names the template that refused the mutation.
IssueID string
}
func (e *TemplateReadOnlyError) Error() string {
return fmt.Sprintf("cannot modify template %s: templates are read-only; use 'bd mol pour' to create a work item", e.IssueID)
}
// Unwrap makes TemplateReadOnlyError match ErrTemplateReadOnly.
func (e *TemplateReadOnlyError) Unwrap() error { return ErrTemplateReadOnly }