fix(update): fence unforced --notes overwrites behind --force across all surfaces (#5946)

* fix(update): fence unforced --notes overwrites behind --force across all surfaces

bd update --notes silently replaced existing notes, destroying handoff
history. The contract now refuses an unforced overwrite of non-empty
notes with ErrNotesOverwrite (409 notes_overwrite_refused over HTTP,
force_notes_overwrite to override), enforced inside the mutation
transaction on both the dolt and uow backends, for single updates and
batch apply alike. CAS guards keep precedence: a stale
--if-assignee/--if-status still surfaces as the exit-13 mismatch, on
both backends, before the fence speaks.

CLI: --force and --if-assignee are no longer mutually exclusive (that
exclusion made overwriting under a guard impossible); both update
routes translate the fence's sentinel into the same actionable advice
(--force to overwrite, --append-notes to preserve history), and the
post---force warning is worded as an audit statement. The shipped
plugin skill docs and bd note help now prescribe --append-notes for
handoffs instead of the newly fenced bare --notes.

The fence is the single enforcement point: no client-side pre-read
copies of the rule. Conformance contracts, unit tests for
AuthorizeNotesOverwrite, and embedded/proxied/httpapi regression
coverage included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): exempt explicit clears from the notes fence; share its predicate

CI surfaced three gaps in the fence's reach:

- Clearing notes (--notes "" / patch.notes: "") was refused, diverging
  from every sibling text field's clear and from the backend behavior
  contracts. The fence now targets only its actual footgun — replacing
  non-empty notes with different non-empty content — via a single shared
  predicate, issueops.NotesReplacement, used by both the contract's
  AuthorizeNotesOverwrite and the CLI's warning path, so the two can no
  longer drift. Prose updated to match everywhere the rule is stated
  (ErrNotesOverwrite, ForceNotesOverwrite, OpenAPI spec + regenerated
  types).
- The revision-CAS integration tests' incidental concurrent writes now
  patch design instead of notes, so they no longer depend on notes-fence
  semantics at all.
- The historical-upgrade harness deliberately replaces fixture notes and
  asserts the new value; its two bd update --notes calls now pass
  --force.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): address review — changelog BREAKING entry, problem.go doc block, close-policy-under-guard test

Review follow-ups on #5946 (bee-ghosttrack, MERGE-AFTER-FIXES):

- CHANGELOG: BREAKING entry under [Unreleased] ### Changed for the notes
  fence on both wires (CLI exit 1, HTTP 409 notes_overwrite_refused), with
  the --force / --append-notes migration line. It also names the two
  deliberate edges: the explicit-clear exemption, and --force widening to
  the close-policy half under --if-assignee now that the flag pair is legal.
- problem.go: CodeNotesOverwrite's comment had landed inside
  CodeDependencyCycle's doc block; each const now sits under its own docs.
- assign_fence_embedded_test.go: pin the previously untested close-policy
  half of --force under --if-assignee (refused unforced, authorized forced).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* test(update): align TestWarnNotesReplacement with the post-fence warning copy

The test landed on main after this branch was cut and pins the pre-fence
wording, where the warning fired on any unforced overwrite. Since the fence,
an unforced overwrite is refused outright and warnNotesReplacement fires only
after a forced one — the audit trail for a habitual --force — so the copy it
pins is now '--force replaced existing notes'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* docs(import): record bd import's notes-fence exemption as by-design (GH#6190)

Import consults none of the per-field live-state fences — notes overwrite,
live-claim reassign, close policy — and that is the intended shape, not an
omission: its contract is wholesale row replacement, guarded by its own
staleness check (only strictly-newer rows rewrite local state, --allow-stale
is the single deliberate-overwrite opt-in) and reported field-by-field in
updated_issues. Named in AuthorizeNotesOverwrite's enforcement-boundary
comment and in bd import's help; the published CLI docs pick the help text
up at the next release pin bump.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(update): refuse --notes "" and add --clear-notes; stop --notes help reading as additive

GH#6021: an empty --notes wiped the whole notes field at exit 0 behind the
same ✓ Updated receipt as a successful write — and the empty string is
exactly what a dead command substitution collapses to. The empty value is
now refused on both CLI routes (the accident and the deliberate clear are
the same bytes at the flag layer), and the deliberate clear gets its own
verb, --clear-notes, mutually exclusive with --notes/--append-notes. A verb
rather than the proposed --allow-empty-notes opt-in: what needs authorizing
is an intent, not an input path — --allow-empty-description unblocks
stdin/file plumbing, which notes does not have — and an opt-in passed
habitually would silently disarm the guard while a habitual --clear-notes
fails loudly. --force does not bypass the refusal; the fence's clear
exemption stands, so the verb alone authorizes the erase. The HTTP API is
unchanged: patch.notes "" still clears.

GH#6272: bd update --help called --notes "Additional notes" and the prime
text said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation with the --append-notes contrast at the
point of use, the shared/create help is field-named like --description and
--design, and the prime line points at bd update --append-notes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(bazel): enumerate the PR-new files in cmd/bd and issueops srcs

The base added cmd/bd/BUILD.bazel and internal/storage/issueops/BUILD.bazel
with EXPLICIT srcs lists after this branch was cut, so the three files this
PR adds were never enumerated:

  cmd/bd/update_notes_guard.go        (go_library bd_lib)
  cmd/bd/update_notes_guard_test.go   (go_test bd_test)
  internal/storage/issueops/aggregate_authorize_notes_test.go (go_test)

The go_library omission is a hard build break, not a silent skip:
update.go:215,220 and update_input.go:106,111 are enumerated and call
validateNotesUpdate / clearNotesRequested, so //cmd/bd:bd_lib compiles the
callers without the callee. bazel.yml arms unconditionally for fork PRs
(head.repo.fork == true) and builds //cmd/bd:bd + //cmd/bd:bd_test, so this
reds the lane. make bazel-sync-check cannot see it -- go_srcs.py only
validates the glob-based go_srcs filegroup, never the rule srcs lists.

Generated by make bazel-sync (gazelle), not hand-edited, so the workflow's
own BUILD-files-in-sync drift step agrees byte-for-byte.

* fix(notes): name --clear-notes in bd note's rm guidance, correct the fence boundary comment, pin both request-shape rules

Takes all three non-gating minors from the review. No behavior change: two
prose fixes and two test cases.

1. cmd/bd/note.go's rm|remove|delete branch advised
   `bd update <id> --notes "text" --force` under "To change or clear notes",
   but clearing through --notes is exactly what this PR made impossible --
   validateNotesUpdate refuses an empty value unconditionally and --force does
   not reach it. The branch now names both verbs separately: --notes --force to
   replace, --clear-notes to clear. The edit and update branches speak only of
   replacing and were already correct, so they are untouched.

2. aggregate.go's enforcement-boundary comment claimed the UpdateIssueInTx
   funnel's "one notes-replacing caller is bd edit". Under this PR's own
   NotesReplacement predicate there are at least four more (bd note's
   read-combine-write, bd defer --reason, bd rename and delete-tombstoning's
   mechanical ID rewrites, bd compact's clears). The exemption is still sound --
   every funnel writer derives its new value from the current notes -- so the
   comment now names those CLASSES instead of a single caller, which is the
   claim that is actually true and that a future fence auditor can check.

3. Both branches this PR adds to ValidateUpdateRequest were uncovered: the
   batch apply leg reaches them here and nowhere else, while the single-issue
   HTTP handler's own pre-check returns before storage. Added a sibling table
   (the existing one varies only the patch; these two rules are properties of
   the REQUEST) with a case each. Mutation-checked, disjoint: neutralizing the
   force-without-notes branch reds only the first case, neutralizing the
   notes+append branch reds only the second, and the pre-existing
   canonical-fields table stays green under both.

Not an amend of 5ffcc9c16c: that commit's message states it was generated by
make bazel-sync and not hand-edited, so folding hand-written Go into it would
falsify the claim its own BUILD-files-in-sync argument rests on. No new files,
so the srcs lists it repaired stay correct.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
Isis Anisoptera 2026-10-01 05:02:40 -07:00 • committed by GitHub
commit 45a116d1a7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
52 changed files with 880 additions and 109 deletions

View file

@ -80,7 +80,7 @@ Use `bd update` with flags instead:
bd update <id> --description "new description"
bd update <id> --title "new title"
bd update <id> --design "design notes"
bd update <id> --notes "additional notes"
bd update <id> --append-notes "additional notes" # --notes replaces existing notes and requires --force once notes are set
bd update <id> --acceptance "acceptance criteria"
# Use stdin for descriptions with special characters (backticks, !, nested quotes)

View file

@ -196,7 +196,7 @@ cleanup, and next-session hand-off).
bd update <id> --description "new description"
bd update <id> --title "new title"
bd update <id> --design "design notes"
bd update <id> --notes "additional notes"
bd update <id> --append-notes "additional notes" # --notes replaces existing notes and requires --force once notes are set
bd update <id> --acceptance "acceptance criteria"
```

View file

@ -873,6 +873,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
and the README snippet — so `bd init` and copy-paste do not re-introduce the
prohibition.
- **BREAKING: unforced `bd update --notes` over existing notes is now refused,
not warned** ([#5946](https://github.com/gastownhall/beads/pull/5946)).
Replacing existing non-empty notes with different non-empty content — the
blind clobber that destroys another agent's handoff notes — previously
printed a warning *after* succeeding; it now writes nothing and exits 1. The
same fence turns `PATCH /v0/beads/issues/{id}` and `batch:apply` from 200
into 409 `notes_overwrite_refused` when `patch.notes` would do the same, on
both backends and both batch legs. Migration: pass `--force` (CLI) or
`force_notes_overwrite` (API) to overwrite deliberately — the CLI then
prints the old warning as an audit trail — or preserve history with
`--append-notes` / `bd note`.
Two edges are deliberate. **An explicit clear is never fenced behind
`--force`**: `--notes ""` (or an API patch to the empty string) does not
trip this refusal, because every sibling text field clears the same way,
the pattern the fence exists to stop is an agent writing its own content
over someone else's, and the refusal's advice — force, or append — is
meaningless for a clear. (The CLI gives the clear its own verb,
`--clear-notes` — see the next entry — but never gates it behind
`--force`.) And
**`--force` is no longer mutually exclusive with `--if-assignee`**, since a
guarded notes overwrite has to be able to say both. This widens what
`--force` reaches under the guard: its assignee half stays suppressed (a
transfer under `--if-assignee` authorizes only through the matching CAS,
never the force bypass), but its close-policy half — closing despite open
children or a live blocker — now applies there too, a combination the CLI
previously rejected outright. `bd edit` is unaffected: it pre-fills the
editor with the current notes, a sighted edit rather than a blind clobber.
- **`bd mol bond --ref` no longer deadlocks the molecule it bonds into, and no
longer accepts `--type conditional`.** A `--ref` arm is nested inside its
target and its hierarchical ID records that, so an ordering edge onto the
@ -987,6 +1016,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#6293](https://github.com/gastownhall/beads/pull/6293)). `json: true` in the
config file selects JSON output for `bd preflight`, as it already did
elsewhere; previously only the explicit flag was honored.
- **BREAKING: `bd update --notes ""` is now refused; clear with
`--clear-notes`** ([#6021](https://github.com/gastownhall/beads/issues/6021)).
An empty `--notes` previously wiped the whole notes field at exit 0 behind
the same `✓ Updated` receipt as a successful write — and the empty string
is exactly what a dead command substitution (`--notes "$(cat
missing.txt)"`) collapses to, the accident behind every recorded loss in
the report. At the flag layer the accident and the deliberate clear are the
same bytes, so the empty value is refused unconditionally (exit 1, naming
the alternative) and the deliberate clear gets its own verb: `bd update
<id> --clear-notes`, mutually exclusive with `--notes` and
`--append-notes`. A verb rather than an `--allow-empty-notes` opt-in
because what needs authorizing is an intent, not an input path — the
description guard's `--allow-empty-description` unblocks stdin/file
plumbing, which notes does not have — and because an opt-in passed
habitually would silently disarm the guard, while a habitual
`--clear-notes` fails loudly on the next real update. `--force` does not
bypass the refusal (the overwrite fence answers a different question),
`--append-notes ""` remains a safe no-op, and the HTTP API is unchanged:
`patch.notes: ""` still clears — a JSON payload is a deliberate
construction, not a shell substitution.
- **`--notes` help no longer reads as additive**
([#6272](https://github.com/gastownhall/beads/issues/6272)). `bd update
--help` described `--notes` as "Additional notes" and the `bd prime` text
said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation ("Replace the notes field …") with the
`--append-notes` contrast at the point of use, and the base/create help is
field-named like `--description` and `--design`, implying no merge
behavior.
- **`bd gate check` resolves bead gates whose target lives in a prefix-routed
rig** ([#5859](https://github.com/gastownhall/beads/pull/5859)). After a local
miss, the evaluator follows the target bead ID through `routes.jsonl` and

View file

@ -1479,7 +1479,7 @@ func RunIssueOperationsUpdateWritesEveryScalarPatchField(t *testing.T, ctx conte
{"defer_until", patchedDefer.Format(issueOperationsStoredTimeLayout)},
}
written, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch})
written, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch, ForceNotesOverwrite: true})
if err != nil {
t.Fatalf("full scalar patch on %s: %v", id, err)
}

View file

@ -437,7 +437,7 @@ func RunLifecycleUpdateAppendsNotesWithoutReplacingThem(t *testing.T, ctx contex
replaced, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
Notes: publicops.Field[string]{Set: true, Value: "replaced"},
}})
}, ForceNotesOverwrite: true})
if err != nil {
t.Fatalf("replace notes on %s: %v", id, err)
}

View file

@ -27,7 +27,7 @@ Use `bd update` with flags instead:
bd update <id> --description "new description"
bd update <id> --title "new title"
bd update <id> --design "design notes"
bd update <id> --notes "additional notes"
bd update <id> --append-notes "additional notes" # --notes replaces existing notes and requires --force once notes are set
bd update <id> --acceptance "acceptance criteria"
```

View file

@ -339,6 +339,7 @@ go_library(
"update.go",
"update_description_guard.go",
"update_input.go",
"update_notes_guard.go",
"update_proxied_server.go",
"upgrade.go",
"vc.go",
@ -1171,6 +1172,7 @@ go_test(
"update_lifecycle_test.go",
"update_metadata_test.go",
"update_multi_id_exit_test.go",
"update_notes_guard_test.go",
"update_notes_warning_test.go",
"update_proxied_integration_test.go",
"update_proxied_server_test.go",

View file

@ -163,8 +163,8 @@ func TestReassignFenceCLI(t *testing.T) {
t.Run("if_assignee_transfer_needs_no_force", func(t *testing.T) {
// The holder-aware CAS (bd-wsqvw park transition) names the holder
// explicitly — nothing silent — and --force/--if-assignee are
// mutually exclusive, so the fence must not fire under the guard.
// explicitly — nothing silent — so the fence must not fire under the
// guard, with or without --force.
issue := claimAs(t, "holder")
bdUpdate(t, bd, dir, issue.ID, "--actor", "supervisor", "--if-assignee", "holder", "--assignee", "parked")
if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "parked" {
@ -172,11 +172,43 @@ func TestReassignFenceCLI(t *testing.T) {
}
})
t.Run("force_and_if_assignee_mutually_exclusive", func(t *testing.T) {
t.Run("force_and_if_assignee_combine_via_the_cas", func(t *testing.T) {
// --force and --if-assignee are no longer mutually exclusive at the
// flag level: a caller pairing --notes with --if-assignee needs
// --force to opt into overwriting existing notes, and cobra can no
// longer refuse the combination outright. An assignee edit riding the
// same command still transfers ONLY through the --if-assignee CAS,
// never through --force: runCommandUpdateMutation never asserts
// ForceAssigneeTransfer when ExpectedAssignee is set, so this is the
// SAME guarded park as the case above, --force along for the ride.
issue := claimAs(t, "holder")
out, _ := bdUpdateFailCode(t, bd, dir, issue.ID, "--force", "--if-assignee", "holder", "--assignee", "x")
if !strings.Contains(out, "force") || !strings.Contains(out, "if-assignee") {
t.Errorf("expected flag-exclusion error naming both flags, got:\n%s", out)
bdUpdate(t, bd, dir, issue.ID, "--actor", "supervisor", "--force", "--if-assignee", "holder", "--assignee", "parked")
if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "parked" {
t.Errorf("guarded park should pass with --force along for the ride: assignee=%q, want parked", got.Assignee)
}
})
t.Run("force_with_if_assignee_arms_close_policy", func(t *testing.T) {
// The close-policy half of --force stays armed under --if-assignee:
// only the assignee-transfer half defers to the CAS. A guarded close
// of a parent with an open child was unreachable while cobra rejected
// the flag pair; now it must behave exactly like an unguarded one —
// refused unforced, authorized with --force.
parent := claimAs(t, "holder")
child := bdCreate(t, bd, dir, "Open child", "--type", "task")
bdRunOK(t, bd, dir, "dep", "add", child.ID, parent.ID, "--type", "parent-child")
out, code := bdUpdateFailCode(t, bd, dir, parent.ID, "--actor", "holder", "--if-assignee", "holder", "--status", "closed")
if code != 1 {
t.Errorf("unforced guarded close exit = %d, want 1 (policy refusal, never 13/guard-mismatch)\n%s", code, out)
}
if got := bdShow(t, bd, dir, parent.ID); got.Status != types.StatusInProgress {
t.Errorf("refused close changed the row: status=%s, want in_progress", got.Status)
}
bdUpdate(t, bd, dir, parent.ID, "--actor", "holder", "--force", "--if-assignee", "holder", "--status", "closed")
if got := bdShow(t, bd, dir, parent.ID); got.Status != types.StatusClosed {
t.Errorf("forced guarded close did not apply: status=%s, want closed", got.Status)
}
})

View file

@ -30,7 +30,10 @@ func registerCommonIssueFlags(cmd *cobra.Command) {
cmd.Flags().String("design-file", "", "Read design from file (use - for stdin)")
cmd.MarkFlagsMutuallyExclusive("design", "design-file")
cmd.Flags().String("acceptance", "", "Acceptance criteria")
cmd.Flags().String("notes", "", "Additional notes")
// Field-named like --description and --design — no merge behavior implied
// (GH#6272: "Additional notes" read as additive while update replaces the
// field; update overrides this usage string with the operational contrast).
cmd.Flags().String("notes", "", "Notes")
cmd.Flags().String("append-notes", "", "Append to existing notes (with newline separator)")
cmd.Flags().String("external-ref", "", "External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)")
}

View file

@ -76,6 +76,13 @@ an import is visible. To deliberately restore an older snapshot, pass
--allow-stale, which imports every row even when it overwrites newer
local state.
The staleness guard is import's ONLY overwrite guard: the per-field
fences that bd update enforces (notes overwrite, live-claim reassign,
close policy) do not apply to imported rows. Import replaces rows
wholesale by design — a restore must not fail field-by-field — so
--allow-stale is the single deliberate-overwrite opt-in, and
updated_issues is where to look for what an import rewrote.
Large imports are written in bounded transactions (a few hundred issues
each, with a short pause between commits) with progress on stderr, so
concurrent bd commands keep working while the import runs instead of

View file

@ -67,8 +67,8 @@ See: bd note --help`)
To append a note:
bd note <issue-id> "text"
To change an issue field:
bd update <issue-id> --notes "text"
To replace existing notes (requires --force once notes are set):
bd update <issue-id> --notes "text" --force
See: bd note --help`)
case "rm", "remove", "delete":
@ -77,8 +77,11 @@ See: bd note --help`)
To append a note:
bd note <issue-id> "text"
To change or clear notes:
bd update <issue-id> --notes "text"
To replace notes (requires --force once notes are set):
bd update <issue-id> --notes "text" --force
To clear notes:
bd update <issue-id> --clear-notes
See: bd note --help`, args[0], args[0])
case "update":
@ -87,9 +90,9 @@ See: bd note --help`, args[0], args[0])
To append a note:
bd note <issue-id> "text"
To set or append notes via the long form:
bd update <issue-id> --notes "text"
To append or replace notes via the long form:
bd update <issue-id> --append-notes "text"
bd update <issue-id> --notes "text" --force (replaces; --force needed once notes are set)
See: bd note --help`)
}

View file

@ -1056,7 +1056,7 @@ git status # Check changed files
- ` + "`bd unclaim <id>`" + ` - Release stuck issue (agent crashed)
- ` + "`bd update <id> --assignee=username`" + ` - Assign to someone
- ` + "`bd update <id> --if-assignee=<expected> --assignee=<new>`" + ` - Atomic reassign: applies only if the assignee still matches (--if-status=<expected> guards status; --if-assignee='' requires unassigned). Mismatch exits non-zero with nothing written — never retry blindly
- ` + "`bd update <id> --title/--description/--notes/--design`" + ` - Update fields inline
- ` + "`bd update <id> --title/--description/--design`" + ` - Update fields inline (` + "`--notes`" + ` replaces existing notes and requires ` + "`--force`" + ` once set; prefer ` + "`--append-notes`" + `)
- ` + "`bd close <id>`" + ` - Mark complete
- ` + "`bd close <id1> <id2> ...`" + ` - Close multiple issues at once (more efficient)
- ` + "`bd close <id> --reason=\"explanation\"`" + ` - Close with reason
@ -1079,7 +1079,7 @@ git status # Check changed files
- ` + "`bd create --validate`" + ` - Check description has required sections
- ` + "`bd create --acceptance=\"criteria\"`" + ` - Set acceptance criteria (checked by --validate)
- ` + "`bd create --design=\"decisions\"`" + ` - Record design decisions
- ` + "`bd create --notes=\"context\"`" + ` - Add supplementary notes
- ` + "`bd create --notes=\"context\"`" + ` - Set supplementary notes (add later with ` + "`bd update --append-notes`" + `)
- ` + "`bd config set validation.on-create warn`" + ` - Auto-validate on every create
- ` + "`bd lint`" + ` - Check existing issues for missing sections

View file

@ -369,7 +369,7 @@ func TestProxiedServerServeClose(t *testing.T) {
}
first := revisionOf(t, raw)
status, raw = sp.updateIssueRaw(t, issue.ID, `{"actor":"other-agent","patch":{"notes":"moved"}}`)
status, raw = sp.updateIssueRaw(t, issue.ID, `{"actor":"other-agent","patch":{"design":"moved"}}`)
if status != http.StatusOK {
t.Fatalf("the concurrent write: status = %d, want 200: %s", status, raw)
}

View file

@ -83,7 +83,7 @@ func TestProxiedServerServeDelete(t *testing.T) {
}
first := revisionOf(t, raw)
status, raw = sp.updateIssueRaw(t, issue.ID, `{"actor":"other-agent","patch":{"notes":"moved"}}`)
status, raw = sp.updateIssueRaw(t, issue.ID, `{"actor":"other-agent","patch":{"design":"moved"}}`)
if status != http.StatusOK {
t.Fatalf("the concurrent write: status = %d, want 200: %s", status, raw)
}

View file

@ -43,8 +43,8 @@ func validateIssueClosable(id string, issue *types.Issue, actor string, force bo
// newAssignee may be "" (unassign), which is fenced the same way. Do NOT call
// it when the caller passed an explicit --if-assignee guard: that CAS names
// the holder, so nothing about it is silent, and it is how sanctioned X→Y
// transfers (park) work without --force (--force and --if-assignee are
// mutually exclusive).
// transfers (park) work without needing the fence bypass (under
// --if-assignee, --force never arms the assignee half).
func validateIssueReassignable(id string, issue *types.Issue, actor, newAssignee string, poolAliases func() []string, force bool) error {
return validation.AssigneeNotStolen(actor, newAssignee, poolAliases, force)(id, issue)
}

View file

@ -49,15 +49,21 @@ type commandUpdateMutation struct {
// runCommandUpdateMutation maps a command update into its lifecycle request and
// returns the lifecycle result unchanged. It is the ONE place the command's
// flag semantics become a request — in particular the one --force that means
// two overrides, whose assignee half only applies to an assignee edit.
// three overrides, whose assignee half only applies to an assignee edit and
// whose notes half only applies to a notes edit. The assignee half is never
// set alongside --if-assignee (ExpectedAssignee): the contract rejects that
// combination outright. The notes half carries no such restriction — it is
// deliberately independent of ExpectedAssignee — so --force paired with
// --if-assignee still drives the notes and close-policy halves.
func runCommandUpdateMutation(ctx context.Context, updater commandIssueUpdater, mutation commandUpdateMutation) (issueops.UpdateResult, error) {
return updater.Update(ctx, issueops.UpdateRequest{
Actor: mutation.actor,
IssueID: mutation.issueID,
Patch: mutation.patch,
Claim: mutation.claim,
ForceAssigneeTransfer: mutation.force && mutation.patch.Assignee.Set,
ForceAssigneeTransfer: mutation.force && mutation.patch.Assignee.Set && mutation.expectedAssignee == nil,
ForceClosePolicy: mutation.force,
ForceNotesOverwrite: mutation.force && mutation.patch.Notes.Set,
ExpectedAssignee: mutation.expectedAssignee,
ExpectedStatus: mutation.expectedStatus,
Provenance: mutation.provenance,
@ -206,8 +212,14 @@ pointless).`,
}
if cmd.Flags().Changed("notes") {
notes, _ := cmd.Flags().GetString("notes")
if err := validateNotesUpdate(notes); err != nil {
return HandleErrorRespectJSON("%v", err)
}
updates["notes"] = notes
}
if clearNotesRequested(cmd) {
updates["notes"] = ""
}
if cmd.Flags().Changed("append-notes") {
appendNotes, _ := cmd.Flags().GetString("append-notes")
updates[storageissueops.OpAppendNotes] = appendNotes
@ -376,8 +388,9 @@ pointless).`,
// Get claim flag
claimFlag, _ := cmd.Flags().GetBool("claim")
// --force bypasses the live-claim reassign fence (bd-98s5c); mutually
// exclusive with --if-assignee at the flag-group level.
// --force bypasses the live-claim reassign fence (bd-98s5c) only when
// no --if-assignee guard is present; it also opts into the notes
// overwrite and close-policy bypasses (runCommandUpdateMutation).
forceFlag, _ := cmd.Flags().GetBool("force")
if len(updates) == 0 && !claimFlag {
@ -496,6 +509,8 @@ pointless).`,
}
}
notesOverwritten := replacesExistingNotes(issue.Notes, updates)
// One atomic operation carries the claim, every field edit, the
// label edits, the metadata edits and the reparent. Metadata edits
// (--metadata, --set-metadata, --unset-metadata) and --append-notes
@ -510,8 +525,6 @@ pointless).`,
if clearDeferStatus && issue.Status == types.StatusDeferred {
patch.Status = issueops.Field[issueops.Status]{Set: true, Value: types.StatusOpen}
}
notesOverwritten := replacesExistingNotes(issue.Notes, updates)
ops, err := writeOps(issueStore)
if err != nil {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
@ -537,10 +550,20 @@ pointless).`,
expectedStatus: expectedStatus,
})
if updateErr != nil {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr)
failureText := fmt.Sprintf("updating issue: %v", updateErr)
if errors.Is(updateErr, issueops.ErrNotesOverwrite) {
// The contract's AuthorizeNotesOverwrite fence refused
// inside the mutation transaction. Print the advice, not
// the raw sentinel.
refusal := errNotesOverwriteRefusal(id)
failureText = refusal.Error()
fmt.Fprintf(os.Stderr, "%s\n", refusal)
} else {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr)
}
failures = append(failures, updateIDFailure{
ID: id,
Error: fmt.Sprintf("updating issue: %v", updateErr),
Error: failureText,
GuardMismatch: isGuardMismatch(updateErr),
})
closeIfUnmutated(result)
@ -791,13 +814,29 @@ func parseSetMetadataFlags(flags []string) (map[string]json.RawMessage, error) {
return set, nil
}
// replacesExistingNotes adapts the map-based update fields onto the
// contract's shared fence predicate.
func replacesExistingNotes(existing string, fields map[string]any) bool {
newNotes, replacing := fields["notes"].(string)
return replacing && existing != "" && newNotes != existing
return replacing && issueops.NotesReplacement(existing, newNotes)
}
// errNotesOverwriteRefusal is the user-facing advice both `bd update` routes
// (the embedded path here and the proxied path in update_proxied_server.go)
// print when the contract's AuthorizeNotesOverwrite fence refuses the
// mutation with ErrNotesOverwrite. The fence itself — inside the contract's
// transaction — is the only enforcement point; the CLI merely translates its
// sentinel into this advice.
func errNotesOverwriteRefusal(id string) error {
return fmt.Errorf("%s: --notes would replace existing notes; use --force to overwrite (or --append-notes to preserve history)", id)
}
// warnNotesReplacement fires only after a successful overwrite, which since
// the fence means the caller passed --force: it is the audit trail for a
// habitual --force that never saw the refusal, worded as a statement of what
// happened rather than a repeat of the refusal's advice.
func warnNotesReplacement(id string) {
fmt.Fprintf(os.Stderr, "warning: %s: --notes replaced existing notes (use --append-notes to preserve history)\n", id) //nolint:gosec // G705: stderr, not a browser context
fmt.Fprintf(os.Stderr, "warning: %s: --force replaced existing notes (--append-notes preserves history)\n", id) //nolint:gosec // G705: stderr, not a browser context
}
// ExitGuardMismatch is the exit code when a `bd update` run failed solely
@ -967,8 +1006,11 @@ func init() {
updateCmd.Flags().String("title", "", "New title")
updateCmd.Flags().StringP("type", "t", "", "New type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision")
registerCommonIssueFlags(updateCmd)
updateCmd.Flags().Lookup("notes").Usage = "Additional notes (replaces existing notes; use --append-notes to append)"
updateCmd.Flags().Lookup("notes").Usage = "Replace the notes field (requires --force over existing non-empty notes; --clear-notes clears; --append-notes appends instead)"
updateCmd.Flags().Bool("allow-empty-description", false, "Allow empty description replacement when reading from stdin or file")
updateCmd.Flags().Bool("clear-notes", false, "Clear the notes field (--notes \"\" is refused: an empty value is usually a dead command substitution)")
updateCmd.MarkFlagsMutuallyExclusive("clear-notes", "notes")
updateCmd.MarkFlagsMutuallyExclusive("clear-notes", "append-notes")
updateCmd.Flags().String("spec-id", "", "Link to specification document")
updateCmd.Flags().String("acceptance-criteria", "", "DEPRECATED: use --acceptance")
_ = updateCmd.Flags().MarkHidden("acceptance-criteria") // Only fails if flag missing (caught in tests)
@ -997,16 +1039,17 @@ func init() {
updateCmd.Flags().String("parent", "", "New parent issue ID (reparents the issue, use empty string to remove parent)")
updateCmd.Flags().Bool("claim", false, "Atomically claim the issue (sets assignee to you, status to in_progress; idempotent if already claimed by you; issues assigned to a pool alias listed in the claim.pools config are claimable too)")
// Overrides the live-claim reassign fence (bd-98s5c) and close policy.
updateCmd.Flags().Bool("force", false, "Override two refusals: let -a/--assignee overwrite another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim), and let -s/--status move the issue into closed (or a configured done status) despite open children or a live blocker (same as bd close --force)")
updateCmd.Flags().Bool("force", false, "Override refusals: let -a/--assignee overwrite another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim), let -s/--status move the issue into closed (or a configured done status) despite open children or a live blocker (same as bd close --force), and let --notes overwrite existing non-empty notes (use --append-notes to preserve history instead)")
// Conditional (compare-and-set) update guards (bd-wsqvw)
updateCmd.Flags().String("if-assignee", "", "Apply the update only if the current assignee equals this value (--if-assignee '' requires unassigned); a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim")
updateCmd.Flags().String("if-status", "", "Apply the update only if the current status equals this value; a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim")
// --force (unconditional bypass of the reassign fence) and --if-assignee
// (write only while a specific assignee still holds it) encode
// contradictory intent — same rationale as unclaim's pairing. Rejecting the
// combination stops a script that habitually passes --force from silently
// dropping its --if-assignee guard.
updateCmd.MarkFlagsMutuallyExclusive("force", "if-assignee")
// --force and --if-assignee are NOT mutually exclusive: --force still
// drives the close-policy and notes-overwrite halves (runCommandUpdateMutation),
// and the contract itself refuses ForceAssigneeTransfer alongside
// ExpectedAssignee, so the assignee half is never asserted here. A caller
// combining --notes with --if-assignee could not previously opt into
// overwriting existing notes at all — cobra made --force unpassable
// alongside --if-assignee — which is the footgun this lifts.
updateCmd.Flags().String("session", "", "Claude Code session ID for status=closed (or set CLAUDE_SESSION_ID env var)")
// Time-based scheduling flags (GH#820)
// Examples:

View file

@ -45,6 +45,14 @@ func bdUpdateFail(t *testing.T, bd, dir string, args ...string) string {
return string(out)
}
// wantNotesRefusal is the expected notes-overwrite refusal line, shared by the
// embedded and proxied update tests. Spelled as a literal, not via the
// production errNotesOverwriteRefusal: reusing the constructor would make the
// wording self-verifying.
func wantNotesRefusal(id string) string {
return id + ": --notes would replace existing notes; use --force to overwrite (or --append-notes to preserve history)"
}
// bdUpdateCapture runs "bd update" expecting success, returning stdout and
// stderr separately (stdout may be JSON; warnings must not pollute it).
func bdUpdateCapture(t *testing.T, bd, dir string, args ...string) (stdout, stderr string) {
@ -394,12 +402,26 @@ func TestEmbeddedUpdate(t *testing.T) {
}
})
t.Run("update_notes_overwrite_warns", func(t *testing.T) {
t.Run("update_notes_overwrite_requires_force", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_force_warns", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes warning test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
stdout, stderr := bdUpdateCapture(t, bd, dir, issue.ID, "--notes", "replacement notes")
warning := fmt.Sprintf("warning: %s: --notes replaced existing notes (use --append-notes to preserve history)", issue.ID)
stdout, stderr := bdUpdateCapture(t, bd, dir, issue.ID, "--notes", "replacement notes", "--force")
warning := fmt.Sprintf("warning: %s: --force replaced existing notes (--append-notes preserves history)", issue.ID)
if !strings.Contains(stderr, warning) {
t.Errorf("expected stderr to contain %q, got: %s", warning, stderr)
}
@ -411,6 +433,88 @@ func TestEmbeddedUpdate(t *testing.T) {
}
})
t.Run("update_notes_overwrite_with_if_assignee_requires_force", func(t *testing.T) {
// --force and --if-assignee are no longer mutually exclusive at the
// flag level (that exclusion was the footgun: it made --force
// unpassable alongside --if-assignee, so a caller pairing --notes
// with --if-assignee could not opt into overwriting existing notes at
// all). Without --force the overwrite is still refused.
issue := bdCreate(t, bd, dir, "Notes plus if-assignee test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_if_assignee_and_force_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes plus if-assignee force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
bdUpdate(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes", "--force")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "replacement notes" {
t.Errorf("expected notes %q, got %q", "replacement notes", got.Notes)
}
})
t.Run("update_empty_notes_refused", func(t *testing.T) {
// GH#6021: `--notes ""` is what a dead command substitution collapses
// to, so an unforced wipe must not look like success. The deliberate
// clear has its own verb, --clear-notes.
issue := bdCreate(t, bd, dir, "Notes clear guard test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected refusal naming --clear-notes, got:\n%s", out)
}
// --force opens the overwrite fence, not this guard: the empty value
// stays refused because the bytes still cannot prove intent.
out = bdUpdateFail(t, bd, dir, issue.ID, "--notes", "", "--force")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected forced empty-notes refusal naming --clear-notes, got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_clear_notes_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes deliberate clear test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
// No --force: the fence exempts clears, so the verb alone authorizes
// the erase.
bdUpdate(t, bd, dir, issue.ID, "--clear-notes")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "" {
t.Errorf("expected notes cleared, got %q", got.Notes)
}
})
t.Run("update_clear_notes_conflicts_with_notes_flags", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes clear conflict test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
for _, extra := range [][]string{
{"--notes", "replacement"},
{"--append-notes", "more"},
} {
args := append([]string{issue.ID, "--clear-notes"}, extra...)
out := bdUpdateFail(t, bd, dir, args...)
if !strings.Contains(out, "none of the others can be") {
t.Errorf("expected mutual-exclusion error for %v, got:\n%s", extra, out)
}
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_defer", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Defer test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15")

View file

@ -35,8 +35,9 @@ type updateInput struct {
// guard).
ifAssignee *string
ifStatus *string
// bd-98s5c: --force bypasses the live-claim reassign fence (mutually
// exclusive with --if-assignee at the flag-group level).
// bd-98s5c: --force bypasses the live-claim reassign fence only when no
// --if-assignee guard rides the command; it also opts into the notes
// overwrite and close-policy bypasses (runCommandUpdateMutation).
force bool
}
@ -102,8 +103,14 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, e
}
if cmd.Flags().Changed("notes") {
notes, _ := cmd.Flags().GetString("notes")
if err := validateNotesUpdate(notes); err != nil {
return nil, HandleErrorRespectJSON("%v", err)
}
in.fields["notes"] = notes
}
if clearNotesRequested(cmd) {
in.fields["notes"] = ""
}
if cmd.Flags().Changed("append-notes") {
in.appendNotes, _ = cmd.Flags().GetString("append-notes")
in.hasAppendNotes = true

View file

@ -382,6 +382,12 @@ func TestReplacesExistingNotes(t *testing.T) {
fields: map[string]any{"notes": "unchanged notes"},
want: false,
},
{
name: "explicit clear",
existing: "old notes",
fields: map[string]any{"notes": ""},
want: false,
},
}
for _, tt := range tests {

View file

@ -0,0 +1,35 @@
package main
import (
"fmt"
"github.com/spf13/cobra"
)
// validateNotesUpdate is the GH#6021 guard: `--notes ""` erases the whole
// notes field, and the empty string is exactly what a dead command
// substitution (`--notes "$(cat missing.txt)"`) collapses to — at the flag
// layer the accident and the deliberate clear are the same bytes, so the
// empty value is refused outright and the deliberate clear gets its own verb,
// --clear-notes. That differs from the description guard twice over:
// validateDescriptionUpdate guards only stdin/file input (where emptiness is
// an input-plumbing property and --allow-empty-description unblocks the same
// content flag), while notes has no file/stdin variant — inline is the only
// path, clearing already-empty notes is a no-op, and what needs authorizing
// is an intent, not a pipe. The notes-overwrite fence
// (issueops.NotesReplacement) exempts clears by design and --force does not
// reach here. Called only when --notes was explicitly passed.
func validateNotesUpdate(notes string) error {
if notes != "" {
return nil
}
return fmt.Errorf(`--notes "" would clear the notes field (an empty command substitution is the usual accident); use --clear-notes to clear it deliberately`)
}
// clearNotesRequested reports whether --clear-notes asked for the deliberate
// erase. Combining it with --notes or --append-notes is contradictory and
// refused by cobra's mutual-exclusion registration on the update command.
func clearNotesRequested(cmd *cobra.Command) bool {
clear, _ := cmd.Flags().GetBool("clear-notes")
return clear
}

View file

@ -0,0 +1,40 @@
package main
import (
"strings"
"testing"
)
// TestValidateNotesUpdateRejectsInlineEmpty pins the deliberate contrast with
// the description guard: an inline empty value IS refused here, because a
// dead command substitution reaches the flag layer as exactly that (GH#6021)
// and notes has no stdin/file input to scope the guard to. The refusal must
// name the verb that clears deliberately.
func TestValidateNotesUpdateRejectsInlineEmpty(t *testing.T) {
err := validateNotesUpdate("")
if err == nil {
t.Fatal("expected inline empty notes to be rejected")
}
if !strings.Contains(err.Error(), "--clear-notes") {
t.Fatalf("expected refusal to name --clear-notes, got: %v", err)
}
}
func TestValidateNotesUpdateAllowsNonEmpty(t *testing.T) {
if err := validateNotesUpdate("handoff context"); err != nil {
t.Fatalf("expected non-empty notes to succeed, got: %v", err)
}
}
// TestUpdateRegistersClearNotes guards the wiring: the update command must
// carry the verb the guard's refusal advertises. create does not register it
// — a new issue has no notes to wipe, so `bd create --notes ""` is not the
// GH#6021 hazard.
func TestUpdateRegistersClearNotes(t *testing.T) {
if updateCmd.Flags().Lookup("clear-notes") == nil {
t.Fatal("expected update to register --clear-notes")
}
if createCmd.Flags().Lookup("clear-notes") != nil {
t.Fatal("create registers --clear-notes but has no wipe hazard; move the guard if this is now intended")
}
}

View file

@ -4,17 +4,19 @@ import (
"testing"
)
// TestWarnNotesReplacement is the D2 guard test: a `bd update --notes` that
// replaces a non-empty notes field warns on stderr, naming --append-notes as
// the history-preserving alternative (the warning itself shipped on main via
// #4743). The predicate deciding WHEN the warning fires is covered by
// TestReplacesExistingNotes.
// TestWarnNotesReplacement is the D2 guard test: since the notes-overwrite
// fence, an unforced `bd update --notes` over existing notes is refused
// (errNotesOverwriteRefusal), so this warning fires only after a FORCED
// overwrite succeeded. It is the audit trail for a habitual --force that
// never saw the refusal — a statement of what happened, still naming
// --append-notes as the history-preserving alternative. The predicate
// deciding WHEN it fires is covered by TestReplacesExistingNotes.
func TestWarnNotesReplacement(t *testing.T) {
got := captureStderr(t, func() {
warnNotesReplacement("tc-dg6")
})
want := "warning: tc-dg6: --notes replaced existing notes (use --append-notes to preserve history)\n"
want := "warning: tc-dg6: --force replaced existing notes (--append-notes preserves history)\n"
if got != want {
t.Fatalf("warnNotesReplacement stderr = %q, want %q", got, want)
}

View file

@ -67,15 +67,62 @@ func TestProxiedServerUpdate(t *testing.T) {
}
})
t.Run("notes_overwrite_requires_force", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "unf")
issue := bdProxiedCreate(t, bd, p.dir, "Notes force", "--notes", "original notes")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir,
"update", "--json", issue.ID, "--notes", "replacement notes")
if err == nil {
t.Fatalf("expected --notes overwrite without --force to fail\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(stderr, wantErr) {
t.Errorf("expected stderr to contain %q, got: %s", wantErr, stderr)
}
if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Notes != "original notes" {
t.Errorf("notes: got %q, want %q", got.Notes, "original notes")
}
})
t.Run("notes_overwrite_with_if_assignee_requires_force", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "unfa")
issue := bdProxiedCreate(t, bd, p.dir, "Notes force if-assignee", "--notes", "original notes")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir,
"update", "--json", issue.ID, "--if-assignee", "", "--notes", "replacement notes")
if err == nil {
t.Fatalf("expected --notes overwrite without --force to fail\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(stderr, wantErr) {
t.Errorf("expected stderr to contain %q, got: %s", wantErr, stderr)
}
if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Notes != "original notes" {
t.Errorf("notes: got %q, want %q", got.Notes, "original notes")
}
})
t.Run("notes_overwrite_with_if_assignee_and_force_succeeds", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "unfaf")
issue := bdProxiedCreate(t, bd, p.dir, "Notes force if-assignee force", "--notes", "original notes")
updated := bdProxiedUpdateOne(t, bd, p.dir, issue.ID,
"--if-assignee", "", "--notes", "replacement notes", "--force")
if updated.Notes != "replacement notes" {
t.Errorf("notes: got %q, want %q", updated.Notes, "replacement notes")
}
})
t.Run("notes_overwrite_warns_on_stderr", func(t *testing.T) {
p := bdProxiedInit(t, bd, "unw")
issue := bdProxiedCreate(t, bd, p.dir, "Notes overwrite", "--notes", "original notes")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir,
"update", "--json", issue.ID, "--notes", "replacement notes")
"update", "--json", issue.ID, "--notes", "replacement notes", "--force")
if err != nil {
t.Fatalf("overwrite notes: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
warning := fmt.Sprintf("warning: %s: --notes replaced existing notes (use --append-notes to preserve history)", issue.ID)
warning := fmt.Sprintf("warning: %s: --force replaced existing notes (--append-notes preserves history)", issue.ID)
if !strings.Contains(stderr, warning) {
t.Errorf("expected stderr to contain %q, got: %s", warning, stderr)
}
@ -87,6 +134,30 @@ func TestProxiedServerUpdate(t *testing.T) {
}
})
t.Run("empty_notes_refused_clear_notes_clears", func(t *testing.T) {
// GH#6021 on the proxied route: the empty-notes refusal fires in
// gatherUpdateInput, before any request leaves the CLI, and the
// --clear-notes verb (not --force) authorizes the erase.
t.Parallel()
p := newSharedProxiedProject(t, bd, "unc")
issue := bdProxiedCreate(t, bd, p.dir, "Notes clear guard", "--notes", "original notes")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir,
"update", issue.ID, "--notes", "")
if err == nil {
t.Fatalf("expected --notes \"\" to fail\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
if !strings.Contains(stderr, "--clear-notes") {
t.Errorf("expected stderr to name --clear-notes, got: %s", stderr)
}
if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Notes != "original notes" {
t.Errorf("notes: got %q, want %q", got.Notes, "original notes")
}
updated := bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--clear-notes")
if updated.Notes != "" {
t.Errorf("notes: got %q, want cleared", updated.Notes)
}
})
t.Run("claim_sets_assignee_and_in_progress", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "uc")
@ -946,7 +1017,7 @@ func TestProxiedServerUpdate3(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "un")
issue := bdProxiedCreate(t, bd, p.dir, "Notes test", "--notes", "first")
updated := bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--notes", "replacement")
updated := bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--notes", "replacement", "--force")
if updated.Notes != "replacement" {
t.Errorf("notes: got %q, want %q", updated.Notes, "replacement")
}

View file

@ -259,6 +259,12 @@ func proxiedUpdateFailure(id string, claim bool, err error) *updateIDFailure {
case errors.Is(err, storage.ErrCloseBlocked) && !claim:
fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err)
return &updateIDFailure{ID: id, Error: fmt.Sprintf("%v (use --force to override)", err)}
case errors.Is(err, storage.ErrNotesOverwrite):
// The contract's AuthorizeNotesOverwrite fence refused inside the
// mutation transaction. Print the advice, not the raw sentinel.
refusal := errNotesOverwriteRefusal(id)
fmt.Fprintf(os.Stderr, "%s\n", refusal)
return &updateIDFailure{ID: id, Error: refusal.Error()}
case uow.IsSerializationError(err):
// The contract spent its retry budget losing Dolt's commit-time merge.
// The write did NOT land; fail loudly instead of exiting 0.

View file

@ -674,7 +674,7 @@ type ApplyPatchBody struct {
// `replace` replaces the whole document. Present holding `null`, `{}` or an empty value CLEARS metadata — and clearing STORES THE EMPTY JSON DOCUMENT rather than SQL null, so "created with no metadata" and "given metadata and then cleared" are the same stored value; a reader must treat absent, empty and `{}` as one value on the way out. `merge` must be a nonempty JSON OBJECT and is merged into the current document.
Metadata *ApplyMetadataPatch `json:"metadata,omitempty"`
// Notes Replaces the notes. Mutually exclusive with `append_notes`; sending both is a `400`.
// Notes Replaces the notes. Mutually exclusive with `append_notes`; sending both is a `400`. Replacing EXISTING non-empty notes with different non-empty content is refused with `409 notes_overwrite_refused` unless `force_notes_overwrite` is set; an explicit clear (empty string) is not fenced.
Notes *string `json:"notes,omitempty"`
Owner *string `json:"owner,omitempty"`
Priority *int `json:"priority,omitempty"`
@ -713,6 +713,9 @@ type ApplyUpdateItem struct {
// ForceClosePolicy Bypasses ONLY close policy — the open-children refusal and the live blocker refusal — for a `patch.status` that crosses into the workspace's done category. It has no effect without such a status change, and it never bypasses validation, the preconditions above, or the assignee fence.
ForceClosePolicy *bool `json:"force_close_policy,omitempty"`
// ForceNotesOverwrite Bypasses ONLY the refusal on a `patch.notes` that would replace existing non-empty notes with different non-empty content (an explicit clear is not fenced). It requires `patch.notes` — an item setting it without one is a `400` — and, UNLIKE `force_assignee_transfer`, it has no `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.
ForceNotesOverwrite *bool `json:"force_notes_overwrite,omitempty"`
// Patch The fields an `update` item writes. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug.
//
// It mirrors `IssuePatchBody` member for member and diverges in exactly two places now that `PATCH /v0/beads/issues/{id}` publishes `status`, `assignee` and the same `metadata` algebra.
@ -1393,7 +1396,7 @@ type IssuePatchBody struct {
// `replace` replaces the whole document. Present holding `null`, `{}` or an empty value CLEARS metadata — and clearing STORES THE EMPTY JSON DOCUMENT rather than SQL null, so "created with no metadata" and "given metadata and then cleared" are the same stored value; a reader must treat absent, empty and `{}` as one value on the way out. `merge` must be a nonempty JSON OBJECT and is merged into the current document.
Metadata *ApplyMetadataPatch `json:"metadata,omitempty"`
// Notes Replaces the notes. Mutually exclusive with `append_notes`; sending both is a `400`.
// Notes Replaces the notes. Mutually exclusive with `append_notes`; sending both is a `400`. Replacing EXISTING non-empty notes with different non-empty content is refused with `409 notes_overwrite_refused` unless `force_notes_overwrite` is set; an explicit clear (empty string) is not fenced.
Notes *string `json:"notes,omitempty"`
// ParentId Replaces the issue's parents atomically: a nonempty value makes THAT issue the only parent, and an EMPTY STRING removes every parent-child edge the issue has. Labels are not inherited — that is a create-time choice (`CreateIssueRequest.inherit_labels_from_parent`) and a reparent does not re-run it.
@ -1955,6 +1958,9 @@ type UpdateIssueRequest struct {
// ForceClosePolicy Bypasses ONLY close policy — the open-children refusal and the live blocker refusal — for a `patch.status` that crosses into the workspace's done category. It has no effect without such a status change, and it never bypasses validation, the preconditions above, or the assignee fence.
ForceClosePolicy *bool `json:"force_close_policy,omitempty"`
// ForceNotesOverwrite Bypasses ONLY the refusal on a `patch.notes` that would replace existing non-empty notes with different non-empty content (an explicit clear is not fenced). It requires `patch.notes` — a request setting it without one is a `400` — and, UNLIKE `force_assignee_transfer`, it has no `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.
ForceNotesOverwrite *bool `json:"force_notes_overwrite,omitempty"`
// Patch The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug — except on `updateIssue` beside `claim: true`, where the claim is the write.
//
// This is a deliberate SUBSET of the fields an issue carries; the members it does not spell are future surface rather than oversights, and `updateIssue`'s own description says which and why.

View file

@ -65,7 +65,7 @@ var (
}
applyUpdateItemMembers = []string{
"expected_assignee", "expected_status", "expected_version",
"force_assignee_transfer", "force_close_policy", "patch", "target",
"force_assignee_transfer", "force_close_policy", "force_notes_overwrite", "patch", "target",
}
applyPatchMembers = []string{
"acceptance_criteria", "append_notes", "assignee", "defer_until",
@ -468,6 +468,9 @@ func applyUpdateItem(prefix string, encoded json.RawMessage, raw map[string]json
if wire.ForceAssigneeTransfer != nil {
item.ForceAssigneeTransfer = *wire.ForceAssigneeTransfer
}
if wire.ForceNotesOverwrite != nil {
item.ForceNotesOverwrite = *wire.ForceNotesOverwrite
}
return item, nil
}
@ -990,6 +993,10 @@ func (s *Server) failApplyBatch(w http.ResponseWriter, r *http.Request, request
}
s.fail(w, r, res)
case errors.Is(err, storage.ErrNotesOverwrite):
s.fail(w, r, at(newResult(CodeNotesOverwrite,
"an update's `patch.notes` would replace existing non-empty notes; send `force_notes_overwrite`, or use `patch.append_notes` to preserve history"), "notes"))
case errors.Is(err, issueops.ErrVersionMismatch),
errors.Is(err, issueops.ErrStatusMismatch),
errors.Is(err, issueops.ErrAssigneeMismatch):

View file

@ -74,8 +74,8 @@ func TestApplyBatchForwardsEveryLevelOfTheDocumentedBody(t *testing.T) {
{"kind":"update","update":{
"target":{"key":"root"},
"expected_status":"open","expected_assignee":"bob",
"force_close_policy":true,"force_assignee_transfer":true,
"patch":{"title":"renamed","status":"closed","assignee":"dave","owner":"erin",
"force_close_policy":true,"force_assignee_transfer":true,"force_notes_overwrite":true,
"patch":{"title":"renamed","status":"closed","assignee":"dave","owner":"erin","notes":"replacement",
"labels":{"replace":["a"],"add":["b"],"remove":["c"]},
"metadata":{"set":{"k":null},"unset":["old"]},
"estimated_minutes":null}}},
@ -179,8 +179,12 @@ func TestApplyBatchForwardsEveryLevelOfTheDocumentedBody(t *testing.T) {
if update.ExpectedAssignee == nil || *update.ExpectedAssignee != "bob" {
t.Errorf("update.expected_assignee = %v, want bob", update.ExpectedAssignee)
}
if !update.ForceClosePolicy || !update.ForceAssigneeTransfer {
t.Errorf("update force flags = %v/%v, want both true", update.ForceClosePolicy, update.ForceAssigneeTransfer)
if !update.ForceClosePolicy || !update.ForceAssigneeTransfer || !update.ForceNotesOverwrite {
t.Errorf("update force flags = %v/%v/%v, want all three true",
update.ForceClosePolicy, update.ForceAssigneeTransfer, update.ForceNotesOverwrite)
}
if !update.Patch.Notes.Set || update.Patch.Notes.Value != "replacement" {
t.Errorf("update.patch.notes = %+v, want replacement", update.Patch.Notes)
}
if !update.Patch.Status.Set || string(update.Patch.Status.Value) != "closed" {
t.Errorf("update.patch.status = %+v, want the crossing status this operation publishes", update.Patch.Status)

View file

@ -126,6 +126,16 @@ const (
// fails on state the client cannot see without reading it. That is the
// not_claimable situation and it gets the not_claimable answer.
CodeNotClosable Code = "not_closable"
// CodeNotesOverwrite is a `patch.notes` that would replace existing
// non-empty notes with a different value, refused unless
// `force_notes_overwrite` is set. It is the notes analog of
// CodeAlreadyClaimed: a live-state fence with a force bypass — but unlike
// that fence it carries no compare-and-set alternative and no extension
// member, because there is no observation to attach: the refusal is
// entirely a statement about the request's own two values (the existing
// notes and the patched ones), not about a foreign actor's identity a
// client might need to display.
CodeNotesOverwrite Code = "notes_overwrite_refused"
// 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
@ -251,6 +261,7 @@ var codeStatus = map[Code]int{
CodeAlreadyClaimed: http.StatusConflict,
CodeNotClaimable: http.StatusConflict,
CodeNotClosable: http.StatusConflict,
CodeNotesOverwrite: http.StatusConflict,
CodeNotReleasable: http.StatusConflict,
CodeDependencyCycle: http.StatusConflict,
CodeDependencyExists: http.StatusConflict,
@ -849,7 +860,7 @@ var operationCodes = map[string][]Code{
// with the fence: a refused claim answers as claimIssue does.
OpUpdateIssue: {
CodeInvalidArgument, CodeUnauthenticated, CodeNotFound,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeNotesOverwrite,
CodeNotClaimable, CodeDependencyCycle, CodeDependencyExists,
CodeBusy, CodeDBUnavailable, CodeInternal,
},
@ -911,7 +922,7 @@ var operationCodes = map[string][]Code{
// resource this operation was asked to address.
OpApplyBatch: {
CodeInvalidArgument, CodeUnauthenticated, CodeNotFound,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeAlreadyExists,
CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeNotesOverwrite, CodeAlreadyExists,
CodeDependencyCycle, CodeDependencyExists,
CodeBusy, CodeDBUnavailable, CodeInternal,
},

View file

@ -2422,7 +2422,7 @@ paths:
scheduling cycle, every time.
x-bd-codes:
[already_claimed, dependency_cycle, dependency_exists,
not_claimable, not_closable, precondition_failed]
not_claimable, not_closable, notes_overwrite_refused, precondition_failed]
content:
application/problem+json:
schema:
@ -4029,7 +4029,7 @@ paths:
a malformed request.
x-bd-codes:
[already_claimed, already_exists, dependency_cycle,
dependency_exists, not_closable, precondition_failed]
dependency_exists, not_closable, notes_overwrite_refused, precondition_failed]
content:
application/problem+json:
schema:
@ -9174,6 +9174,18 @@ components:
idempotent and needs no force. It requires `patch.assignee` — a
request setting it without one is a `400` — and it must be false
when `expected_assignee` is sent.
force_notes_overwrite:
type: boolean
default: false
description: >-
Bypasses ONLY the refusal on a `patch.notes` that would replace
existing non-empty notes with different non-empty content (an
explicit clear is not fenced). It requires
`patch.notes` — an item setting it without one is a `400` — and,
UNLIKE `force_assignee_transfer`, it has no `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.
ApplyPatchBody:
type: object
@ -9225,7 +9237,10 @@ components:
type: string
description: >-
Replaces the notes. Mutually exclusive with `append_notes`; sending
both is a `400`.
both is a `400`. Replacing EXISTING non-empty notes with
different non-empty content is refused with `409
notes_overwrite_refused` unless `force_notes_overwrite` is set; an
explicit clear (empty string) is not fenced.
append_notes:
type: string
description: >-
@ -10523,6 +10538,18 @@ components:
idempotent and needs no force. It requires `patch.assignee` — a
request setting it without one is a `400` — and it must be false
when `expected_assignee` is sent.
force_notes_overwrite:
type: boolean
default: false
description: >-
Bypasses ONLY the refusal on a `patch.notes` that would replace
existing non-empty notes with different non-empty content (an
explicit clear is not fenced). It requires
`patch.notes` — a request setting it without one is a `400` —
and, UNLIKE `force_assignee_transfer`, it has no
`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.
IssuePatchBody:
type: object
@ -10565,7 +10592,10 @@ components:
type: string
description: >-
Replaces the notes. Mutually exclusive with `append_notes`; sending
both is a `400`.
both is a `400`. Replacing EXISTING non-empty notes with
different non-empty content is refused with `409
notes_overwrite_refused` unless `force_notes_overwrite` is set; an
explicit clear (empty string) is not fenced.
append_notes:
type: string
description: >-

View file

@ -39,7 +39,7 @@ const (
var (
updateRequestMembers = []string{
"actor", updateClaimMember, "expected_assignee", "expected_status", "expected_version",
"force_assignee_transfer", "force_close_policy", updatePatchMember,
"force_assignee_transfer", "force_close_policy", "force_notes_overwrite", updatePatchMember,
}
issuePatchMembers = []string{
"title", "description", "design", "acceptance_criteria",
@ -177,6 +177,15 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string
if !ok {
return issueops.UpdateRequest{}, false
}
forceNotesOverwrite, ok := s.booleanMember(w, r, members, "force_notes_overwrite")
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"))
return issueops.UpdateRequest{}, false
}
// The role refuses a claim beside the assignee and status guards, and a
// claim beside the forced transfer (ValidateUpdateRequest): the claim is
// its own compare-and-set, with claim-pool eligibility the guards do not
@ -234,6 +243,7 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string
ExpectedAssignee: expectedAssignee,
ForceClosePolicy: forceClosePolicy,
ForceAssigneeTransfer: forceAssigneeTransfer,
ForceNotesOverwrite: forceNotesOverwrite,
Provenance: updateProvenance,
}, true
}
@ -507,15 +517,15 @@ func patchParam(member string) string {
// EVERY 409 BRANCH READS TYPED FIELDS, never prose, and every one of them is
// matched BEFORE the ErrValidation and ErrNotFound arms. That order is the
// whole correctness of this function, and the hazard it avoids is worse than a
// disagreement between backends: NEITHER LEG WRAPS THESE FIVE FAMILIES IN
// disagreement between backends: NEITHER LEG WRAPS THESE SIX FAMILIES IN
// ErrValidation. The store legs return ExecuteUpdate's error through
// runIssueOperationTx unchanged (internal/storage/dolt/issue_operations.go) and
// the unit of work returns ApplyUpdate's unchanged
// (internal/storage/uow/issue_operations.go), so a precondition miss, a close-
// policy refusal, the assignee fence and both graph refusals reach here as bare
// sentinels. Below the ErrValidation arm they would all fall into `!Is(...)`
// and be swallowed into failErr — a generic 500, on BOTH legs, for five
// conditions this document names by code.
// policy refusal, the assignee fence, the notes-overwrite fence and both graph
// refusals reach here as bare sentinels. Below the ErrValidation arm they
// would all fall into `!Is(...)` and be swallowed into failErr — a generic
// 500, on BOTH legs, for six conditions this document names by code.
//
// NEITHER BRANCH QUOTES THE ROLE'S MESSAGE. A refusal from the workspace's
// configured vocabulary arrives as prose about statuses and types, and a
@ -594,6 +604,11 @@ func (s *Server) failUpdate(w http.ResponseWriter, r *http.Request, request issu
}
s.fail(w, r, res)
case errors.Is(err, storage.ErrNotesOverwrite):
s.fail(w, r, named(newResult(CodeNotesOverwrite,
"`patch.notes` would replace existing non-empty notes; send `force_notes_overwrite`, or use `patch.append_notes` to preserve history"),
patchParam("notes")))
case errors.As(err, &typeConflict):
s.fail(w, r, named(newResult(CodeDependencyExists,
"this pair already carries an edge of a different type; remove it before reparenting").

View file

@ -88,7 +88,7 @@ func TestUpdateForwardsEveryDocumentedMember(t *testing.T) {
t.Errorf("the role received actor %q id %q", req.Actor, req.IssueID)
}
// Every precondition and force flag stays zero: unpublished on this surface.
if req.Claim || req.ForceAssigneeTransfer || req.ForceClosePolicy ||
if req.Claim || req.ForceAssigneeTransfer || req.ForceClosePolicy || req.ForceNotesOverwrite ||
req.ExpectedVersion != nil || req.ExpectedAssignee != nil || req.ExpectedStatus != nil {
t.Errorf("the handler published a precondition or force flag: %+v", req)
}
@ -320,6 +320,7 @@ func TestUpdateRejectsTheShapesTheDocumentRefuses(t *testing.T) {
{"unknown metadata member", `{"actor":"alice","patch":{"metadata":{"clear":true}}}`, "patch.metadata.clear"},
{"force_assignee_transfer without an assignee edit", `{"actor":"alice","patch":{"title":"t"},"force_assignee_transfer":true}`, "force_assignee_transfer"},
{"force_assignee_transfer beside expected_assignee", `{"actor":"alice","patch":{"assignee":"bob"},"force_assignee_transfer":true,"expected_assignee":"carol"}`, "force_assignee_transfer"},
{"force_notes_overwrite without a notes edit", `{"actor":"alice","patch":{"title":"t"},"force_notes_overwrite":true}`, "force_notes_overwrite"},
// The guard is a decimal STRING; a bare number is the spelling this
// contract deliberately does not also accept, since a double-based
// client would have rounded it before it ever arrived.
@ -928,6 +929,15 @@ func TestUpdateAnswersThePolicyRefusalsItsMembersEarned(t *testing.T) {
}
},
},
{
name: "notes overwrite refused",
body: `{"actor":"alice","patch":{"notes":"replacement"}}`,
err: fmt.Errorf("update: %w: issue bd-1", storage.ErrNotesOverwrite),
wantStatus: http.StatusConflict,
wantCode: CodeNotesOverwrite,
wantParam: "patch.notes",
check: func(*testing.T, map[string]any) {},
},
{
// THE DEFENSIVE ARM, driven directly because no reparent can reach
// it: CheckBlockingHierarchyInTx probes `blocks` and

View file

@ -121,6 +121,7 @@ go_library(
go_test(
name = "issueops_test",
srcs = [
"aggregate_authorize_notes_test.go",
"aggregate_authorize_transfer_test.go",
"as_of_test.go",
"batch_apply_test.go",

View file

@ -45,7 +45,7 @@ func UpdateFields(patch publicops.IssuePatch) map[string]interface{} {
{patch.Design.Set, "design", patch.Design.Value},
{patch.AcceptanceCriteria.Set, "acceptance_criteria", patch.AcceptanceCriteria.Value},
{patch.Notes.Set, "notes", patch.Notes.Value},
{patch.AppendNotes.Set, "append_notes", patch.AppendNotes.Value},
{patch.AppendNotes.Set, OpAppendNotes, patch.AppendNotes.Value},
{patch.SpecID.Set, "spec_id", patch.SpecID.Value},
{patch.AwaitID.Set, "await_id", patch.AwaitID.Value},
{patch.Status.Set, "status", patch.Status.Value},
@ -76,6 +76,18 @@ func ValidateUpdateRequest(request publicops.UpdateRequest) error {
if request.ForceAssigneeTransfer && (request.Claim || !request.Patch.Assignee.Set || request.ExpectedAssignee != nil) {
return fmt.Errorf("%w: invalid forced assignee transfer", storage.ErrValidation)
}
if request.ForceNotesOverwrite && !request.Patch.Notes.Set {
return fmt.Errorf("%w: invalid forced notes overwrite", storage.ErrValidation)
}
// Checked HERE, ahead of the notes-overwrite fence in ExecuteUpdate: a
// patch setting both Notes and AppendNotes is an invalid REQUEST, not a
// refused overwrite, and must report ErrValidation even when the notes
// fence would independently refuse the same Notes value. The uow backend
// reaches this same check through validateUpdateRequest, which both of
// its update paths run before their own fence calls, for the same reason.
if request.Patch.Notes.Set && request.Patch.AppendNotes.Set {
return fmt.Errorf("%w: cannot combine a notes replacement with %s", storage.ErrValidation, OpAppendNotes)
}
patch := request.Patch
if patch.Title.Set {
if err := types.ValidateIssueTitle(patch.Title.Value); err != nil {
@ -185,6 +197,40 @@ func AuthorizeAssigneeTransfer(ctx context.Context, tx DBTX, before *types.Issue
return AuthorizeAssigneeTransferWithPools(before, request, pools)
}
// AuthorizeNotesOverwrite protects existing non-empty notes from an unforced
// replacement. It refuses when the patch sets Notes to a
// publicops.NotesReplacement of before.Notes (which exempts an explicit
// clear) and request.ForceNotesOverwrite is false.
//
// It applies REGARDLESS of request.ExpectedAssignee, deliberately: unlike the
// assignee fence, there is no compare-and-set that authorizes a notes
// overwrite the way a matching ExpectedAssignee authorizes an assignee
// transfer, so pairing a notes edit with an assignee guard does not exempt it.
// A STALE guard still outranks it, though — both backends check the
// compare-and-set preconditions before calling here, so a mismatch reports as
// the mismatch, never as this refusal.
//
// Enforcement boundary: this fences the issueops-contract surfaces
// (ExecuteUpdate, the uow update and batch legs). The map-based
// UpdateIssueInTx funnel does not consult it, and it has several
// notes-replacing callers, not one. They fall into classes that are all
// sighted or derived rather than blind: editor pre-fill that starts from the
// current notes (`bd edit`), read-combine-write that appends to them
// (`bd note`, `bd defer --reason`), mechanical ID rewrites of existing text
// (`bd rename`, delete-tombstoning), and explicit clears (`bd compact`). Each
// derives its new value from the current notes, so none is the blind clobber
// this fence exists to stop. `bd import` is exempt BY DESIGN (GH#6190), along with every
// other live-state fence: its contract is row replacement, guarded by its own
// staleness check (only strictly-newer rows rewrite local state; deliberate
// overwrites of newer state require --allow-stale) and reported field-by-field
// in updated_issues — the bulk-path analog of this fence's per-field --force.
func AuthorizeNotesOverwrite(before *types.Issue, request publicops.UpdateRequest) error {
if !request.Patch.Notes.Set || !publicops.NotesReplacement(before.Notes, request.Patch.Notes.Value) || request.ForceNotesOverwrite {
return nil
}
return fmt.Errorf("%w: issue %s", storage.ErrNotesOverwrite, before.ID)
}
// 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

@ -0,0 +1,99 @@
package issueops
import (
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// TestAuthorizeNotesOverwrite pins every branch of the notes-overwrite fence.
func TestAuthorizeNotesOverwrite(t *testing.T) {
withNotes := func(notes string) *types.Issue {
return &types.Issue{ID: "bd-1", Notes: notes}
}
notesPatch := func(mutate func(*publicops.UpdateRequest)) publicops.UpdateRequest {
request := publicops.UpdateRequest{
Actor: "actor",
IssueID: "bd-1",
Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "replacement"}},
}
if mutate != nil {
mutate(&request)
}
return request
}
holder := "someone"
cases := []struct {
name string
before *types.Issue
request publicops.UpdateRequest
refuse bool
}{
{
name: "unset notes patch",
before: withNotes("original"),
request: notesPatch(func(r *publicops.UpdateRequest) { r.Patch.Notes = publicops.Field[string]{} }),
},
{
name: "existing notes empty",
before: withNotes(""),
request: notesPatch(nil),
},
{
name: "new value matches existing",
before: withNotes("original"),
request: notesPatch(func(r *publicops.UpdateRequest) { r.Patch.Notes.Value = "original" }),
},
{
// An explicit clear passes unfenced, like every sibling text
// field's clear; the fence targets non-empty replacement content.
name: "explicit clear",
before: withNotes("original"),
request: notesPatch(func(r *publicops.UpdateRequest) { r.Patch.Notes.Value = "" }),
},
{
name: "forced overwrite",
before: withNotes("original"),
request: notesPatch(func(r *publicops.UpdateRequest) { r.ForceNotesOverwrite = true }),
},
{
// Deliberately NOT exempted by ExpectedAssignee, unlike the
// assignee fence: there is no compare-and-set that authorizes a
// notes overwrite, so pairing the two guards does not stand this
// one down.
name: "expected assignee set does not exempt it",
before: withNotes("original"),
request: notesPatch(func(r *publicops.UpdateRequest) { r.ExpectedAssignee = &holder }),
refuse: true,
},
{
name: "unforced overwrite refuses",
before: withNotes("original"),
request: notesPatch(nil),
refuse: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := AuthorizeNotesOverwrite(tc.before, tc.request)
if !tc.refuse {
if err != nil {
t.Fatalf("AuthorizeNotesOverwrite = %v, want nil", err)
}
return
}
if !errors.Is(err, storage.ErrNotesOverwrite) {
t.Fatalf("AuthorizeNotesOverwrite = %v, want ErrNotesOverwrite", err)
}
if !strings.Contains(err.Error(), tc.before.ID) {
t.Errorf("refusal %q omits issue %s", err, tc.before.ID)
}
})
}
}

View file

@ -279,6 +279,7 @@ func (r *applyBatchRun) applyUpdate(ctx context.Context, tx *sql.Tx, index int,
ExpectedAssignee: item.ExpectedAssignee,
ForceClosePolicy: item.ForceClosePolicy,
ForceAssigneeTransfer: item.ForceAssigneeTransfer,
ForceNotesOverwrite: item.ForceNotesOverwrite,
})
if err != nil {
return &publicops.ItemError{Index: index, Kind: publicops.ItemUpdate, Key: item.Target.Key, IssueID: id, Err: err}

View file

@ -169,6 +169,9 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
if err := AuthorizeAssigneeTransfer(ctx, tx, before, attempt); err != nil {
return publicops.UpdateResult{}, nil, err
}
if err := AuthorizeNotesOverwrite(before, attempt); err != nil {
return publicops.UpdateResult{}, nil, err
}
// Every constituent below runs its no-mint variant: one guarded update is
// one caller-visible mutation, and its version is minted exactly once at
// the end, after the last patch, so durable_state carries the final row,

View file

@ -31,6 +31,45 @@ func TestValidateUpdateRequestRejectsInvalidCanonicalFields(t *testing.T) {
}
}
// TestValidateUpdateRequestRejectsInvalidNotesRequestShapes covers the two
// notes rules ValidateUpdateRequest owns that are properties of the REQUEST
// rather than of the patch alone, so they cannot be expressed in the
// patch-only table above. Both are contract-level: the batch apply leg reaches
// them here and nowhere else, and the single-issue HTTP handler's own
// pre-check returns before storage is reached, so without these cases the
// branches backing the published ApplyUpdateItem promise are unexercised.
func TestValidateUpdateRequestRejectsInvalidNotesRequestShapes(t *testing.T) {
for _, tc := range []struct {
name string
request publicops.UpdateRequest
}{
{
name: "forced notes overwrite without a notes value",
request: publicops.UpdateRequest{
Actor: "actor", IssueID: "bd-validate",
ForceNotesOverwrite: true,
},
},
{
name: "notes replacement combined with append",
request: publicops.UpdateRequest{
Actor: "actor", IssueID: "bd-validate",
Patch: publicops.IssuePatch{
Notes: publicops.Field[string]{Set: true, Value: "replacement"},
AppendNotes: publicops.Field[string]{Set: true, Value: "addition"},
},
},
},
} {
t.Run(tc.name, func(t *testing.T) {
err := ValidateUpdateRequest(tc.request)
if !errors.Is(err, storage.ErrValidation) {
t.Fatalf("ValidateUpdateRequest() error = %v, want ErrValidation", err)
}
})
}
}
func TestApplyMetadataPatchRejectsUnsafeKeysAndNullMerge(t *testing.T) {
for _, tc := range []struct {
name string

View file

@ -37,6 +37,7 @@ var (
ErrAlreadyIdentified = issueops.ErrAlreadyIdentified
ErrVersionMismatch = issueops.ErrVersionMismatch
ErrStatusMismatch = issueops.ErrStatusMismatch
ErrNotesOverwrite = issueops.ErrNotesOverwrite
)
// CloseOpenChildrenError reports the issue and open-child count that refused a

View file

@ -241,6 +241,7 @@ func (r *uowApplyRun) applyUpdate(ctx context.Context, index int, item *publicop
ExpectedAssignee: item.ExpectedAssignee,
ForceClosePolicy: item.ForceClosePolicy,
ForceAssigneeTransfer: item.ForceAssigneeTransfer,
ForceNotesOverwrite: item.ForceNotesOverwrite,
}
if err := validateUpdateRequest(request); err != nil {
return itemErr(err)
@ -284,6 +285,9 @@ func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateReq
if err := authorizeAssigneeTransfer(ctx, r.uw, before, request); err != nil {
return publicops.UpdateResult{}, err
}
if err := storageissueops.AuthorizeNotesOverwrite(before, request); err != nil {
return publicops.UpdateResult{}, err
}
}
// ActorMatches (not a verbatim compare, ga-v2k49): see the identical
// comment on issueOperations.Update's claimChanged in issue_operations.go

View file

@ -234,6 +234,9 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe
if err := authorizeAssigneeTransfer(ctx, uw, before, attempt); err != nil {
return publicops.UpdateResult{}, "", err
}
if err := storageissueops.AuthorizeNotesOverwrite(before, attempt); err != nil {
return publicops.UpdateResult{}, "", err
}
}
// ActorMatches (not a verbatim compare, ga-v2k49): a holder re-claiming
// under a respelled identity is a real CAS win one layer down (domain/db's
@ -255,9 +258,13 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe
// updatePreconditionsHold reports whether request's compare-and-set
// preconditions match before — that is, whether ApplyUpdate would get past its
// own guards, leaving the assignee fence as the operative refusal.
// ExpectedAssignee needs no entry here: the fence already stands down whenever
// a caller supplies one.
// own guards, leaving the fences as the operative refusals. ExpectedAssignee
// belongs here since the notes fence arrived: the ASSIGNEE fence stands down
// whenever a caller supplies one, but the notes fence deliberately does not,
// and a stale compare-and-set must outrank it (the dolt leg orders
// CheckExpectedFieldsInTx ahead of AuthorizeNotesOverwrite). The comparison is
// ActorMatches, not verbatim ==, matching CheckExpectedFieldsInTx (ga-wzl83);
// a pointer to "" is a real guard meaning "expected unassigned".
func updatePreconditionsHold(request publicops.UpdateRequest, before *types.Issue) bool {
if request.ExpectedVersion != nil && *request.ExpectedVersion != before.RowVersion {
return false
@ -265,6 +272,9 @@ func updatePreconditionsHold(request publicops.UpdateRequest, before *types.Issu
if request.ExpectedStatus != nil && *request.ExpectedStatus != before.Status {
return false
}
if request.ExpectedAssignee != nil && !storageissueops.ActorMatches(before.Assignee, *request.ExpectedAssignee) {
return false
}
return true
}
@ -312,9 +322,9 @@ func updateSpec(request publicops.UpdateRequest) (domain.UpdateSpec, error) {
setField(fields, "external_ref", patch.ExternalRef)
setField(fields, "due_at", patch.DueAt)
setField(fields, "defer_until", patch.DeferUntil)
if patch.Notes.Set && patch.AppendNotes.Set {
return domain.UpdateSpec{}, validationError(fmt.Errorf("update: notes and append notes cannot both be set"))
}
// Notes+AppendNotes is refused by ValidateUpdateRequest, which both
// callers (issueOperations.Update and the batch applier) run before
// building a spec — no duplicate check here.
setField(fields, "notes", patch.Notes)
if patch.AppendNotes.Set {
fields[storageissueops.OpAppendNotes] = patch.AppendNotes.Value

View file

@ -149,11 +149,13 @@ type UpdateItem struct {
ExpectedVersion *int64
ExpectedStatus *Status
ExpectedAssignee *string
// ForceClosePolicy and ForceAssigneeTransfer are UpdateRequest's, per item,
// with UpdateRequest's rules — including that ForceAssigneeTransfer without
// a Patch.Assignee is invalid.
// ForceClosePolicy, ForceAssigneeTransfer and ForceNotesOverwrite are
// UpdateRequest's, per item, with UpdateRequest's rules — including that
// ForceAssigneeTransfer without a Patch.Assignee, and ForceNotesOverwrite
// without a Patch.Notes, are each invalid.
ForceClosePolicy bool
ForceAssigneeTransfer bool
ForceNotesOverwrite bool
}
// CloseItem closes one existing issue, under CloseRequest's rules.

View file

@ -63,6 +63,32 @@ type ErrUnsupported = beadserrors.ErrUnsupported
// UpdateRequest.ExpectedAssignee.
var ErrAssigneeMismatch = errors.New("assignee mismatch")
// ErrNotesOverwrite is returned when an update's Patch.Notes would replace
// existing non-empty notes with different non-empty content (see
// NotesReplacement) and UpdateRequest.ForceNotesOverwrite is false. It is
// independent of the assignee fence —
// unlike ErrAlreadyClaimed it applies regardless of ExpectedAssignee — because
// there is no compare-and-set that authorizes a notes overwrite the way a
// matching ExpectedAssignee authorizes an assignee transfer. Bypass with
// ForceNotesOverwrite (`bd update --force`); preserve history instead with
// --append-notes.
var ErrNotesOverwrite = errors.New("update would replace existing notes")
// NotesReplacement reports whether proposed would replace existing non-empty
// notes with different non-empty content — the one condition the
// notes-overwrite fence refuses without ForceNotesOverwrite. An explicit
// clear (proposed "") is not a replacement: every sibling text field clears
// the same way, the blind-clobber pattern the fence exists to stop is an
// agent writing its own non-empty content over someone else's, and the
// refusal's advice (force, or append) is meaningless for a clear. The clear
// itself is guarded separately at the CLI flag layer (`--notes ""` is
// refused; `bd update --clear-notes` is the deliberate verb, GH#6021), where
// an accidental empty — a dead command substitution — cannot be told from a
// deliberate one by its bytes; that guard is not this predicate's concern.
func NotesReplacement(existing, proposed string) bool {
return existing != "" && proposed != "" && proposed != existing
}
// ErrNotOwner is returned when an actor tries to release a claim that a
// different actor holds. Releasing another actor's claim requires the force
// escape hatch (ReleaseRequest.Force, `bd unclaim --force`), reserved for

View file

@ -252,6 +252,19 @@ type UpdateRequest struct {
// therefore maps that flag to both fields, conditioning this one on an
// assignee edit.
ForceAssigneeTransfer bool
// ForceNotesOverwrite bypasses only the refusal on a Patch.Notes that is a
// NotesReplacement of the existing notes — replacing non-empty notes with
// different non-empty content; an explicit clear is not fenced. The zero
// value enforces the fence. It has no effect without such a Patch.Notes edit, and
// a request that sets it with no Patch.Notes is invalid. It is independent
// of ForceAssigneeTransfer and ForceClosePolicy — neither bypasses this, nor
// does this bypass either of them — and, deliberately, of ExpectedAssignee
// too: a caller pairing a notes edit with an assignee compare-and-set still
// needs this bit to overwrite notes, and setting it never touches the
// assignee guard. A command adapter with a single --force flag therefore
// maps that flag to all three fields, conditioning this one on a
// Patch.Notes edit.
ForceNotesOverwrite bool
// ForceClosePolicy bypasses only close policy — the open-children refusal
// and the live-direct-blocker refusal — for a Patch.Status that crosses into
// the done category. The zero value enforces the policy. It has no effect

View file

@ -83,7 +83,7 @@ bd dep add implementation setup # ✓ CORRECT
When Claude's context gets compacted, conversation history is lost but bd state survives. Write notes as if explaining to a future Claude with zero context:
```bash
bd update issue-123 --notes "COMPLETED: JWT auth with RS256
bd update issue-123 --append-notes "COMPLETED: JWT auth with RS256
KEY DECISION: RS256 over HS256 for key rotation
IN PROGRESS: Password reset flow
NEXT: Implement rate limiting"

View file

@ -51,7 +51,7 @@ How bd-issue-tracking integrates with TodoWrite, writing-plans, and other skills
**Corresponding bead notes (persistent context):**
```bash
bd update issue-123 --notes "COMPLETED: Login endpoint with bcrypt password
bd update issue-123 --append-notes "COMPLETED: Login endpoint with bcrypt password
hashing (12 rounds). KEY DECISION: Using JWT tokens (not sessions) for stateless
auth - simplifies horizontal scaling. IN PROGRESS: Session middleware implementation.
NEXT: Need user input on token expiry time (1hr vs 24hr trade-off)."
@ -105,7 +105,7 @@ TodoWrite:
**End of Session 1**:
```bash
# Update bd with outcomes
bd update oauth-1 --notes "COMPLETED: Researched OAuth2 refresh flow. Decided on 7-day refresh tokens.
bd update oauth-1 --append-notes "COMPLETED: Researched OAuth2 refresh flow. Decided on 7-day refresh tokens.
KEY DECISION: RS256 over HS256 (enables key rotation per security review).
IN PROGRESS: Need to set up test OAuth provider.
NEXT: Configure test provider, then implement token endpoint."
@ -128,7 +128,7 @@ TodoWrite:
# Work proceeds...
# Update bd at milestone
bd update oauth-1 --notes "COMPLETED: Test provider configured, token endpoint implemented.
bd update oauth-1 --append-notes "COMPLETED: Test provider configured, token endpoint implemented.
TESTS: 5 passing (token generation, validation, expiry).
IN PROGRESS: Adding refresh token rotation.
NEXT: Implement rotation, add rate limiting, security review."
@ -236,7 +236,7 @@ git commit -m "feat: add token refresh endpoint"
**Example bd notes after using detailed plan:**
```bash
bd update oauth-5 --notes "COMPLETED: Token refresh endpoint (5 tasks from plan: endpoint + rotation + tests)
bd update oauth-5 --append-notes "COMPLETED: Token refresh endpoint (5 tasks from plan: endpoint + rotation + tests)
KEY DECISION: 7-day refresh tokens (vs 30-day) - reduces risk of token theft
TESTS: All 12 tests passing (auth, rotation, expiry, error handling)"
```
@ -277,7 +277,7 @@ TESTS: All 12 tests passing (auth, rotation, expiry, error handling)"
3. Update bd notes at milestones:
```bash
bd update strat-1 --notes "COMPLETED: Research phase (reviewed 5 competitor docs, 3 internal reports)
bd update strat-1 --append-notes "COMPLETED: Research phase (reviewed 5 competitor docs, 3 internal reports)
KEY DECISION: Focus on market expansion over cost optimization per exec input
IN PROGRESS: Drafting recommendations section
NEXT: Get exec review of draft recommendations before finalizing"

View file

@ -54,7 +54,7 @@ For complex technical features spanning multiple sessions, enhance notes field w
### Example pattern:
```markdown
bd update issue-9 --notes "IMPLEMENTATION GUIDE:
bd update issue-9 --append-notes "IMPLEMENTATION GUIDE:
WORKING CODE: service.about().get(fields='importFormats')
Returns: dict with 49 entries like {'text/markdown': [...]}
OUTPUT FORMAT: # Drive Import Formats (markdown with categorized list)

View file

@ -39,7 +39,7 @@ NEXT: Need user input on budget constraints before finalizing recommendations"
3. Work on tasks, mark TodoWrite items completed
4. At milestone, update bd notes:
```bash
bd update bd-42 --notes "COMPLETED: Cost-benefit analysis drafted.
bd update bd-42 --append-notes "COMPLETED: Cost-benefit analysis drafted.
KEY DECISION: User confirmed $50k budget cap - ruled out enterprise options.
IN PROGRESS: Finalizing recommendations (Posthog + custom ETL).
NEXT: Get user review of draft before closing issue."
@ -179,14 +179,14 @@ bd update auth-5 --claim
**Hit a blocker**:
```bash
bd update auth-5 --status blocked --notes "BLOCKER: Need OAuth client ID from product team. Emailed Jane on 2025-10-23."
bd update auth-5 --status blocked --append-notes "BLOCKER: Need OAuth client ID from product team. Emailed Jane on 2025-10-23."
# Switch to different issue or create new work
```
**Unblocking**:
```bash
# Once blocker resolved
bd update auth-5 --status in_progress --notes "UNBLOCKED: Received OAuth credentials. Resuming implementation."
bd update auth-5 --status in_progress --append-notes "UNBLOCKED: Received OAuth credentials. Resuming implementation."
```
**Completing**:
@ -286,7 +286,7 @@ bd close task-123 --reason "Implemented feature X"
**Detailed closure** (complex work):
```bash
# Update notes with final state
bd update task-123 --notes "COMPLETED: OAuth refresh with 7-day rotation
bd update task-123 --append-notes "COMPLETED: OAuth refresh with 7-day rotation
KEY DECISION: RS256 over HS256 per security review
TESTS: 12 tests passing (auth, rotation, expiry, errors)
FOLLOW-UP: Filed perf-99 for token cleanup job"
@ -297,11 +297,11 @@ bd close task-123 --reason "Implemented OAuth refresh token rotation with rate l
### Documenting Resolution (Outcome vs Design)
For issues where the outcome differed from initial design, use `--notes` to document what actually happened:
For issues where the outcome differed from initial design, use `--append-notes` to document what actually happened:
```bash
# Initial design was hypothesis - document actual outcome in notes
bd update bug-456 --notes "RESOLUTION: Not a bug - behavior is correct per OAuth spec. Documentation was unclear. Filed docs-789 to clarify auth flow in user guide."
bd update bug-456 --append-notes "RESOLUTION: Not a bug - behavior is correct per OAuth spec. Documentation was unclear. Filed docs-789 to clarify auth flow in user guide."
bd close bug-456 --reason "Resolved: documentation issue, not bug"
```
@ -331,7 +331,7 @@ bd close auth-5 --reason "OAuth refresh implemented. Discovered perf optimizatio
| Pattern | When to Use | Key Command | Preserves |
|---------|-------------|-------------|-----------|
| **Knowledge Work** | Long-running research, writing | `bd update --notes` | Context across sessions |
| **Knowledge Work** | Long-running research, writing | `bd update --append-notes` | Context across sessions |
| **Side Quest** | Discovered during other work | `bd dep add --type discovered-from` | Relationship to original |
| **Multi-Session Resume** | Returning after time away | `bd ready`, `bd show` | Full project state |
| **Status Transitions** | Tracking work state | `bd update --status` | Current state |

View file

@ -66,7 +66,7 @@ After Compaction:
**Good note (enables recovery):**
```
bd update issue-42 --notes "COMPLETED: User authentication - added JWT token
bd update issue-42 --append-notes "COMPLETED: User authentication - added JWT token
generation with 1hr expiry, implemented refresh token endpoint using rotating
tokens pattern. IN PROGRESS: Password reset flow. Email service integration
working. NEXT: Need to add rate limiting to reset endpoint (currently unlimited
@ -76,7 +76,7 @@ recommendations, tech lead concerned about response time but benchmarks show <10
**Bad note (insufficient for recovery):**
```
bd update issue-42 --notes "Working on auth feature. Made some progress.
bd update issue-42 --append-notes "Working on auth feature. Made some progress.
More to do later."
```
@ -342,7 +342,7 @@ Session End Handoff:
- [ ] Prompt user: "We just completed X and started Y on <issue-id>.
Should I update the beads notes for next session?"
- [ ] If yes, suggest command:
bd update <issue-id> --notes "COMPLETED: X. IN PROGRESS: Y. NEXT: Z"
bd update <issue-id> --append-notes "COMPLETED: X. IN PROGRESS: Y. NEXT: Z"
- [ ] User reviews and confirms
- [ ] Claude executes the update
- [ ] Notes saved for next session's resumption
@ -404,7 +404,7 @@ User Tips:
**At End of Session 1:**
```bash
bd update workspace-mcp-server-2 --notes "COMPLETED: Set up skeleton with Docs
bd update workspace-mcp-server-2 --append-notes "COMPLETED: Set up skeleton with Docs
API connection verified. Markdown parsing logic 80% done (handles *, _ modifiers).
IN PROGRESS: Testing edge cases for nested formatting. NEXT: Implement
batchUpdate call structure for text insertion. REFERENCE: Reference pattern at

View file

@ -1007,7 +1007,9 @@ verify_post_bridge_semantics() {
local version="$1" kind="$2" task blocker task_after ready
task=$(sed -n '1p' "$workspace/fixture-ids")
blocker=$(sed -n '2p' "$workspace/fixture-ids")
run_in_workspace "$candidate" update "$task" --notes 'Post-upgrade bridge mutation persisted.' >/dev/null ||
# --force: the fixture task carries historical notes, and the candidate now
# fences an unforced non-empty replacement; the replacement is the point here.
run_in_workspace "$candidate" update "$task" --notes 'Post-upgrade bridge mutation persisted.' --force >/dev/null ||
die "$version: candidate mutation failed after explicit bridge"
task_after=$(run_in_workspace "$candidate" show "$task" --json --include-comments) ||
die "$version: candidate could not reopen bridged data"
@ -1043,7 +1045,8 @@ run_embedded_dolt_upgrade() {
fi
[ "$(sha256_file "$metadata")" = "$metadata_sha" ] || die "$version: candidate startup rewrote metadata"
task=$(sed -n '1p' "$workspace/fixture-ids")
run_in_workspace "$candidate" update "$task" --notes 'Post-upgrade direct mutation persisted.' >/dev/null ||
# --force: same fence as verify_post_bridge_semantics — the fixture task has notes.
run_in_workspace "$candidate" update "$task" --notes 'Post-upgrade direct mutation persisted.' --force >/dev/null ||
die "$version: candidate mutation failed after direct upgrade"
task_after=$(run_in_workspace "$candidate" show "$task" --json --include-comments) ||
die "$version: candidate could not reopen mutated data"

View file

@ -589,7 +589,7 @@ func TestProtocol_NotesAppendVsOverwrite(t *testing.T) {
t.Errorf("notes should be 'Original', got: %v", data[0]["notes"])
}
w.run("update", a, "--notes", "Replaced")
w.run("update", a, "--notes", "Replaced", "--force")
data = parseJSON(t, w.run("show", a, "--json"))
if data[0]["notes"] != "Replaced" {
t.Errorf("notes should be 'Replaced', got: %v", data[0]["notes"])

View file

@ -474,10 +474,25 @@ func (w *workspace) showJSONForSnapshot(id string) string {
return w.run(args...)
}
func (w *workspace) supportsStreamedShowPayloads() bool {
// isCandidate reports whether this workspace runs the candidate binary rather
// than the pinned baseline. Intent-named feature gates below delegate here so
// candidate detection lives in one place.
func (w *workspace) isCandidate() bool {
return candidateBin != "" && w.bdPath == candidateBin
}
func (w *workspace) supportsStreamedShowPayloads() bool {
return w.isCandidate()
}
// requiresNotesOverwriteForce reports whether this binary refuses `update
// --notes` over existing notes without --force. The pinned baseline predates
// both the refusal and the flag (its update has no --force at all), so shared
// scenarios pass --force only to the candidate.
func (w *workspace) requiresNotesOverwriteForce() bool {
return w.isCandidate()
}
// export returns a JSONL snapshot of the workspace. This replaces the removed
// bd export command with list+show based snapshots. Filter args (e.g.,
// "--status", "open") are translated to bd list flags.

View file

@ -1069,7 +1069,11 @@ func TestNotesOverwriteSemantics(t *testing.T) {
compareExports(t, func(w *workspace) {
id := w.create("--title", "Notes overwrite test", "--type", "task",
"--notes", "Original notes content")
w.run("update", id, "--notes", "Completely replaced notes")
args := []string{"update", id, "--notes", "Completely replaced notes"}
if w.requiresNotesOverwriteForce() {
args = append(args, "--force")
}
w.run(args...)
w.run("update", id, "--title", "Notes overwrite test (updated)")
})
}