* fix(metadata): restore v1.2.2 scalar typing for --set-metadata values8ebd53e88moved the CLI's metadata-edit helpers into internal/storage/metadata.go and, in the move, replaced v1.2.2's toJSONValue inference with a MetadataEditValue that always json.Marshals the value as a string. The intent was GH#4146 (a numeric-looking id or a version like "1e3" came back as a JSON number, breaking map[string]string Go consumers), but it silently changed the shipped CLI contract: `bd update --set-metadata k=5` started storing "5" instead of 5. That regression shipped only in the deprecated/superseded v1.2.1, never in v1.2.2, and 1.3.0 would freeze it. Restore v1.2.2's inference body-for-body inside MetadataEditValue, so the parity claim stays checkable against `git show v1.2.2:cmd/bd/update.go`: "null" is JSON null, "true"/"false" are booleans, a spelling that scans as a float AND is valid JSON on its own is emitted as that literal (5 -> 5, 1e3 -> 1e3, 0.50 -> 0.50, while 05, +5 and NaN stay strings), and everything else is a string. Every --set-metadata caller funnels through this one function: embedded (cmd/bd/update.go -> storage.ApplyMetadataEdits), proxied (parseSetMetadataFlags) and the update executor's []string path. GH#4146's concern is served by the explicitly typed routes, which are untouched: --metadata / --metadata-json on the CLI (MergeMetadataJSON) and the typed set map on the HTTP/Go path (applyTypedMetadataEdits). No data migration: a "5" written by an in-window build is indistinguishable from a string a user set intentionally through the typed paths, so normalizing stored metadata would corrupt intended data. Re-running the same --set-metadata k=5 retypes any given key. Tests: new table in internal/storage/metadata_edit_value_test.go pinning the v1.2.2 matrix plus an ApplyMetadataEdits end-to-end; the tests that pinned the string-always behavior are flipped (domain/db mergeops suite, update_lifecycle patch mapping, cmd/bd toJSONValue table) and the embedded + proxied CLI suites now assert a stored JSON number. The contract corpus is regenerated: its update/list/ready goldens run `--set-metadata phase=2`, so `"phase": "2"` becomes `"phase": 2` and nothing else moves. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(create): echo full-precision timestamps from bd create, not the DATETIME(0) re-readb92442d1arouted `bd create` through issueops.Lifecycle, whose executors build their result by re-reading the row they just wrote (HydrateIssueOperationResult -> GetIssueInTx). created_at/updated_at are DATETIME(0) columns, so that snapshot comes back at whole-second precision and cmd/bd/create.go echoes it. v1.2.2 returned the caller's own in-memory struct, which PrepareIssueForInsert stamps with time.Now().UTC() including nanoseconds, so `bd create --json` used to print e.g. 2026-08-28T12:34:56.789012345Z. Agents that create several issues in a burst order them by exactly that fraction; rounded to the second they all tie. Restore the echo with OverlayCreateTimestamps: after hydration, put back the created_at/updated_at (and closed_at, when the write set one) the INSERT actually sent. Everything else on the snapshot stays DB-truth, which is the facade's contract — only create, and only these fields. Applied at every create body, not just the two the CLI reaches: issueops.ExecuteCreate and ExecuteCreateBatch behind the dolt and embedded-dolt stores, and the unit-of-work provider's own Create, CreateBatch and batch-apply create item, which is what the proxied server and POST /v0/beads/issues run on. Fixing only the shared executors would have left the two bodies disagreeing about the same promise. What is NOT changed, because it is not a regression: `bd show --json` and `bd list --json` answered whole seconds in v1.2.2 too — they read the column — and update/close/reopen re-read after writing there as well. Widening the columns to DATETIME(6) would give reads sub-second times too, but that is a schema migration on user Dolt DBs and touches paths that deliberately compare at second precision; it is a 1.4 change. The accepted skew, which predates this and stays: the engine ROUNDS to the column rather than truncating, so a later read of the same row can sit up to half a second either side of the create echo. Tests: two new conformance cases, run on all three backends — RunLifecycleCreateEchoesSubSecondTimestamps (a caller-supplied nanosecond stamp must survive to the result exactly; the auto-stamped arm stays a bounded smoke check, since requiring a non-zero fraction off the clock is flaky by a billionth) and RunBatchCreatorEchoesSubSecondTimestamps (per item, since both bodies build the result one snapshot at a time). Plus a cmd/bd embedded test asserting `bd create --json` prints a fractional part, and one httpapi assertion that the wire does not round the role's snapshot on the way out. All four fail on the pre-fix tree. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(httpapi,types)!: revision / expected_version tokens are opaque JSON strings The optimistic-concurrency token is minted by freshRowLock over the FULL int64 range (crypto-random, non-zero) and published on the wire as a JSON number: `revision` on responses, `expected_version` on guarded requests. A JSON number does not survive a consumer that decodes into an IEEE-754 double — JavaScript's JSON.parse, Go's `any`, Python's `float`, jq. Live tokens run past 5e17, where a double's ulp is already 64, so such a client reads back a value NEAR the token, echoes that as its guard, and earns a 409 against a row nobody else touched. The spec already carried "DECODE IT AS A 64-BIT INTEGER" paragraphs telling clients to work around this; that is a workaround for a wire type that should not have been a number. Emit and accept the token as a decimal STRING instead. It is documented as opaque and EQUALITY-ONLY — compare it, never order or interpret it — and a string round-trips exactly in every JSON consumer. It also leaves a future backend free to mint a token that is not an int64 at all. Internals are untouched: freshRowLock, the row_lock BIGINT column, its migration, types.Issue.RowVersion and the ExpectedVersion *int64 guards on the issueops requests all stay int64. Only the wire projection moves, through the one spelling of the encoding — types.RevisionToken and types.ParseRevisionToken. STRICT STRING ONLY, with no transitional number-or-string acceptance. This API already refuses unknown members by name and keeps one spelling of the guard, and a number is precisely the shape a double-based client has already rounded before it left the client — accepting it would preserve the defect. A numeric guard is a 400 naming the member. Chosen over clamping freshRowLock to 53 bits: a clamp does not fix rows already minted with full-range tokens by in-window builds, so a JS consumer reading one still rounds past 2^53 — repairing that would need a row_lock normalization sweep over issues and wisps, a migration days before a tag. Surface: types.IssueDetails.Revision (what `bd show --json` prints and GET /v0/beads/issues/{id} returns), the five hand-assigned httpapi response fields, applyVersionGuardMember (now the reader for the batch update item too, ahead of its typed decode, so a mistyped token still earns a 400 naming the member), Problem.expected_version, and 14 OpenAPI members regenerated through `make api-gen`. actual_version goes with them — it is documented as "the `revision` the row was found holding", so leaving it an integer would make the expected/actual pair disagree about its own type; it is declared but never populated, so nothing changes behaviorally. Nothing shipped in a tagged release ever carried this member: v1.2.2 has no internal/httpapi at all and no `revision` anywhere on the wire, so the whole surface is in-window and can still be changed compatibly. Legacy migration-0054 rows read as the string "0" with the same CAS semantics. Corpus goldens are UNCHANGED: the canonicalizer already replaced any `revision` value with the string "<REVISION>" whatever its JSON type. Tests: types-level pins that the marshaled member matches `"revision": "-?\d+"` and that RevisionToken/ParseRevisionToken round-trip MinInt64, MaxInt64 and 2^53+1, plus a JS-realistic decode of 2^53+1 with a float64 control proving the token really is one a number would corrupt; httpapi refusal tests for a numeric guard on update, close, reopen, delete and both batch item kinds; a 409 echo asserted as the string; and the proxied serve integration tests now splice the response's own token back in verbatim rather than re-rendering a parsed one. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
271 lines
12 KiB
Go
271 lines
12 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
const (
|
|
// releaseExpectedAssigneeMember is the compare-and-set guard on the holder.
|
|
// It is named the way updateIssue names its own guard, because it is the
|
|
// same guard — but it does NOT admit the empty string, which is the one
|
|
// place the two disagree. See its schema.
|
|
releaseExpectedAssigneeMember = "expected_assignee"
|
|
// releaseForceMember is the ownership-fence bypass.
|
|
releaseForceMember = "force"
|
|
)
|
|
|
|
// releaseRequestMembers is the document's member list for ReleaseIssueRequest.
|
|
// The schema is additionalProperties: false, so anything else is refused BY
|
|
// NAME, the posture every body on this surface takes.
|
|
var releaseRequestMembers = []string{claimActorMember, releaseExpectedAssigneeMember, releaseForceMember}
|
|
|
|
// handleRelease gives back the claim on one issue: the claim's inverse, and the
|
|
// verb `bd unclaim` spells.
|
|
//
|
|
// It carries the claim's posture verbatim. The actor is caller-ASSERTED
|
|
// provenance and not authenticated identity; hooks do not fire and the
|
|
// per-command auto-commit machinery does not run. The only durable effect is
|
|
// the single storage commit the role makes inside its own transaction.
|
|
//
|
|
// THE ACTOR IS ALSO THE OWNERSHIP FENCE'S SUBJECT here, which it is on no other
|
|
// operation: a release carrying neither guard nor force succeeds only while the
|
|
// actor is the holder. That is not authorization: the actor is not the
|
|
// authenticated principal even where a bearer is required, because the token a
|
|
// deployment configures is shared and admits a client to the whole surface. It
|
|
// is the anti-yank guard the claim gets from refusing a foreign holder, pointed
|
|
// the other way, and it is the role's rather than this handler's.
|
|
//
|
|
// PLANES, as for close and reopen and unlike the claim: the id resolves across
|
|
// both. A wisp can hold a claim, so an operation that refused to release one
|
|
// would strand an ephemeral row owned by an agent that is gone.
|
|
func (s *Server) handleRelease(w http.ResponseWriter, r *http.Request) {
|
|
// The custom-method dispatcher split the id off the segment and bounded it
|
|
// before this handler was chosen at all; see customMethodTarget.
|
|
id := r.PathValue(customMethodIDValue)
|
|
if !s.requireNoQuery(w, r) {
|
|
return
|
|
}
|
|
if !s.requireJSONContent(w, r) {
|
|
return
|
|
}
|
|
request, ok := s.releaseRequest(w, r, id)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
releaser, err := s.releaser(r)
|
|
if err != nil {
|
|
s.failRelease(w, r, request, err)
|
|
return
|
|
}
|
|
result, err := releaser.Release(r.Context(), request)
|
|
if err != nil {
|
|
s.failRelease(w, r, request, err)
|
|
return
|
|
}
|
|
// `changed` is the role's own, and it is true on every answer that reaches
|
|
// here: the role refuses every shape that would not write. It is published
|
|
// because claimIssue and updateIssue publish the same fact, and it is the
|
|
// negative space that answers "where is the already_released member" —
|
|
// there is none, and the document says why.
|
|
//
|
|
// `revision` is the row's post-write concurrency token, read off the same
|
|
// snapshot rather than computed. A release REMINTS it, so this member is
|
|
// the only way a caller composing a following `expected_version` stays in
|
|
// step; types.Issue.RowVersion is `json:"-"`, so the issue body cannot
|
|
// carry it.
|
|
writeJSON(w, apigen.ReleaseIssueResponse{
|
|
Issue: *result.Issue,
|
|
Changed: result.Changed,
|
|
Revision: types.RevisionToken(result.Issue.RowVersion),
|
|
})
|
|
}
|
|
|
|
// releaseRequest decodes and validates the body, and reports whether the
|
|
// request may proceed. Every refusal here happens BEFORE any database work.
|
|
//
|
|
// The two guard members are validated AGAINST EACH OTHER at the edge, not only
|
|
// individually, because the role refuses the pair and the caller deserves to
|
|
// learn that from a 400 naming a member rather than from a generic refusal that
|
|
// cost two round trips.
|
|
func (s *Server) releaseRequest(w http.ResponseWriter, r *http.Request, id string) (issueops.ReleaseRequest, bool) {
|
|
members, res := decodeJSONObjectBody(w, r)
|
|
if res != nil {
|
|
s.fail(w, r, *res)
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
if offender, unknown := unknownMember(members, releaseRequestMembers); unknown {
|
|
s.failUnknownMember(w, r, offender, releaseRequestMembers)
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
|
|
actor, ok := s.bodyActor(w, r, members)
|
|
if !ok {
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
expected, ok := s.releaseExpectedAssignee(w, r, members)
|
|
if !ok {
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
force, ok := s.booleanMember(w, r, members, releaseForceMember)
|
|
if !ok {
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
// The pair the role refuses, refused here by name. They are answers to the
|
|
// same question and they disagree — the guard says "only if X still holds
|
|
// it" and force says "whoever holds it" — so honoring either would be this
|
|
// server picking which half of the request the caller meant.
|
|
//
|
|
// It names `force`, the member that is redundant given the guard, so a
|
|
// caller that added a belt-and-braces flag learns which one to drop.
|
|
if force && expected != nil {
|
|
s.fail(w, r, InvalidArgument(releaseForceMember, ReasonInvalidValue,
|
|
"`"+releaseForceMember+"` and `"+releaseExpectedAssigneeMember+"` disagree about which claim to release; send one"))
|
|
return issueops.ReleaseRequest{}, false
|
|
}
|
|
|
|
return issueops.ReleaseRequest{
|
|
Actor: actor,
|
|
IssueID: id,
|
|
ExpectedAssignee: expected,
|
|
Force: force,
|
|
}, true
|
|
}
|
|
|
|
// releaseExpectedAssignee reads the optional compare-and-set guard.
|
|
//
|
|
// ABSENT AND ONLY ABSENT selects the unconditional path, so this answers a
|
|
// POINTER: the role models "do not check" as nil and this member has no other
|
|
// spelling for it. Explicit `null` is a 400 rather than a second spelling of
|
|
// absent, the rule every optional member on this surface follows.
|
|
//
|
|
// THE EMPTY STRING IS A 400 — the one place this member disagrees with
|
|
// updateIssue's `expected_assignee`, where an empty string is a real guard
|
|
// meaning "expected unassigned". "Release a row nobody holds" describes no
|
|
// release, so the role refuses it and this refuses it at the edge, where the
|
|
// 400 can name the member. Emptiness is judged AFTER trimming, matching the
|
|
// role, and the value is passed on UNTRIMMED, also matching the role: a padded
|
|
// expectation must lose every time rather than intermittently.
|
|
//
|
|
// It is not length- or pattern-checked the way an actor is. This value is
|
|
// COMPARED and never stored, so a value no assignee column could hold simply
|
|
// cannot match, and refusing it here would be a refusal the role does not have.
|
|
func (s *Server) releaseExpectedAssignee(w http.ResponseWriter, r *http.Request, members map[string]json.RawMessage) (*string, bool) {
|
|
raw, present := members[releaseExpectedAssigneeMember]
|
|
if !present {
|
|
return nil, true
|
|
}
|
|
refuse := func(detail string) (*string, bool) {
|
|
s.fail(w, r, InvalidArgument(releaseExpectedAssigneeMember, ReasonInvalidValue, detail))
|
|
return nil, false
|
|
}
|
|
var value *string
|
|
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
|
return refuse("`" + releaseExpectedAssigneeMember + "` must be a string")
|
|
}
|
|
if strings.TrimSpace(*value) == "" {
|
|
return refuse("`" + releaseExpectedAssigneeMember + "` is empty after trimming; omit it to release whatever claim is there, " +
|
|
"or read the row if you meant to assert that nobody holds it")
|
|
}
|
|
return value, true
|
|
}
|
|
|
|
// failRelease answers a failed release, mapping the role's TYPED refusals onto
|
|
// the frozen codes.
|
|
//
|
|
// EVERY 409 BRANCH IS MATCHED BEFORE THE ErrValidation AND ErrNotFound ARMS,
|
|
// and that order is the whole correctness of this function — failUpdate's
|
|
// hazard, in a sharper form. None of the four refusals below is wrapped in
|
|
// ErrValidation by any leg: ReleaseIssueInTx returns its two classifications
|
|
// bare and passes the raw seam's two through unchanged, and all three database
|
|
// legs reach that one function. Below a generic arm they would fall into
|
|
// failErr and be answered 500 — on every leg, for four conditions this document
|
|
// names by code.
|
|
//
|
|
// NO BRANCH QUOTES THE ROLE'S MESSAGE. Every one of these refusals formats its
|
|
// observation into prose — the holder it found, the status it saw — and this
|
|
// surface publishes typed members or nothing. Three of the four have nothing
|
|
// typed to publish, so they publish nothing; see the codes' own docs. The real
|
|
// error goes to the log with the request id.
|
|
func (s *Server) failRelease(w http.ResponseWriter, r *http.Request, request issueops.ReleaseRequest, err error) {
|
|
// The 4xx path does not log by default, so the refusals whose real reason
|
|
// the response replaces with the server's own words are recorded here.
|
|
refused := func() {
|
|
s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error())
|
|
}
|
|
|
|
switch {
|
|
// THE GUARD, and it is matched first because it is the only refusal here
|
|
// with a member to carry. `expected_assignee` is the REQUEST's value and
|
|
// there is no `actual_assignee` beside it: the refusal rolled its
|
|
// transaction back, and the role carries the holder it observed in prose
|
|
// only — no ClaimConflictError equivalent exists for this sentinel. That is
|
|
// updateIssue's rule for the same guard, unchanged.
|
|
case errors.Is(err, issueops.ErrAssigneeMismatch):
|
|
res := PreconditionFailed()
|
|
res.Problem.Param = releaseGuardParam()
|
|
if request.ExpectedAssignee != nil {
|
|
res = res.WithExpectedAssignee(*request.ExpectedAssignee)
|
|
}
|
|
s.fail(w, r, res)
|
|
|
|
// THE OWNERSHIP FENCE, answered with the code updateIssue already gives the
|
|
// same situation: a live foreign owner refusing a write, with a force
|
|
// bypass and a name-the-holder bypass. No `assignee` member, for the reason
|
|
// that operation states — the fence refuses without naming the holder, so
|
|
// absence means "re-read the row" and never "nobody holds it".
|
|
case errors.Is(err, issueops.ErrNotOwner):
|
|
s.fail(w, r, newResult(CodeAlreadyClaimed,
|
|
"this issue is held by another actor; send `"+releaseForceMember+"`, or name the holder in `"+
|
|
releaseExpectedAssigneeMember+"`"))
|
|
|
|
// THE ROW REFUSING TO PRODUCE A RELEASE AT ALL, under one code and with no
|
|
// member telling the two conditions apart. Neither sentinel carries a typed
|
|
// observation, and this surface does not scrape prose to invent one; the
|
|
// code's own doc carries the analysis, including why splitting later is the
|
|
// direction that stays open.
|
|
//
|
|
// The detail names both conditions rather than guessing between them, so a
|
|
// human reading a `bd unclaim` failure is not told a closed issue is
|
|
// unclaimed or the reverse.
|
|
case errors.Is(err, issueops.ErrNotClaimed), errors.Is(err, issueops.ErrNotReleasable):
|
|
refused()
|
|
s.fail(w, r, newResult(CodeNotReleasable,
|
|
"this issue holds no claim, or its status is neither `open` nor `in_progress`; nothing was written. "+
|
|
"Read the row rather than assuming the claim is gone: a status this workspace configured can refuse a "+
|
|
"release while the row is still assigned"))
|
|
|
|
case errors.Is(err, storage.ErrNotFound):
|
|
s.fail(w, r, NotFound())
|
|
|
|
case !errors.Is(err, storage.ErrValidation):
|
|
s.failErr(w, r, err)
|
|
|
|
// DEFENSIVE. Every request-validation refusal the role has is refused at the
|
|
// edge above — an empty actor, a blank guard, force beside the guard — and
|
|
// the dispatcher guarantees a non-empty id, so nothing should reach this.
|
|
// It stays because the alternative if that ever stops being true is a 500
|
|
// for a request the caller could have fixed.
|
|
default:
|
|
refused()
|
|
s.fail(w, r, InvalidArgument("", ReasonInvalidValue,
|
|
"the request was refused by this workspace's own validation; nothing was written"))
|
|
}
|
|
}
|
|
|
|
// releaseGuardParam names the guard member on a `precondition_failed`, so a
|
|
// client reads one member to find the offending input whichever way the request
|
|
// was refused. It is a function for updateGuardParam's reason: `param` is a
|
|
// pointer on the envelope and a package-level address would be shared state.
|
|
func releaseGuardParam() *string {
|
|
member := releaseExpectedAssigneeMember
|
|
return &member
|
|
}
|