beads/internal/httpclient/dependencyeditor.go
Julian Knutsen d15958a5eb
fix(issueops): enforce the dotted-child dependency rule on every leg (#7424)
* fix(issueops): enforce the dotted-child dependency rule on every leg

The refusal of an explicit edge from a dotted-id child to its own ancestor
(bd-abc.1 -> bd-abc; only the parent-child edge to the immediate dotted
parent is allowed) lived only in cmd/bd (isDisallowedHierarchicalDependency).
HTTP dependencies:add, batch:apply dep_add items and `bd create --graph`'s own
edges skipped it.

It is now one library rule, issueops.CheckDottedChildDependency, returning
*issueops.DottedChildDependencyError (unwraps to ErrValidation, same message
the CLI printed):
- ValidateAddDependenciesRequest applies it, so DependencyEditor refuses on
  dolt, embedded, uow and the server behind httpapi (400 invalid_argument);
- both BatchApplier bodies (issueops and uow) apply it to each dep_add item on
  the resolved ids, so a key bound to a minted dotted child is refused too;
- the HTTP client checks it before the dial, as it does self-dependency, so
  the typed error survives the wire.

cmd/bd keeps no copy: single-edge dep add / dep --blocks rely on the role;
bd link (still on the store verb) and the --file bulk reporter call the
library rule. CLI output is byte-identical (checked against origin/main).

Conformance: RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent and
RunBatchApplyRefusesADottedChildGatedOnItsOwnParent wired on dolt, embedded,
uow and http, plus a raw-wire served test past the client check and handler
mapping cases.

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

* fix(batch): refuse a dotted child gated on its own ancestor in bd batch

Review fixup for PR #7424 (iterations 1 and 2).

Major: a bd batch script line `dep add bd-abc.1 bd-abc` still wrote the
edge this PR refuses everywhere else, on both backends. Neither batch
dispatch writes through the DependencyEditor role that enforces the
dotted-child rule: the classic arm calls storage.Transaction.AddDependency
and the proxied arm the unit of work's AddDependencies verb. Both arms now
build the edge with one helper, batchDepAddEdge, which keeps the default
type and the arity and type errors, and asks
publicops.CheckDottedChildDependency the way bd link does. A refused line
rolls the whole batch back.

Tests: TestBatchDepAddEdge (default and explicit types, arity and type
errors, three refusals typed *DottedChildDependencyError matching
ErrValidation, and the immediate parent-child edge allowed), and
TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent (classic
and proxied: the refusal names line 2, rolls back an earlier update line
and writes no edge, and `dep add C P parent-child` still lands exactly
one), registered in the proxied shard manifest. A mutant that drops the
rule from the shared helper fails both; one that bypasses the helper in
the proxied arm alone fails the proxied leg.

Minors:
- For a child whose parent-child edge is already stored (a
  `bd create --parent` child) the rule answers ahead of the hierarchy and
  type conflicts, so an HTTP caller now gets 400 invalid_argument where it
  got 409 dependency_cycle (blocking types) or dependency_exists (any
  other type). Documented in the DependencyEditor role doc, the CHANGELOG
  entry and the httpapi batch-apply test comment, and pinned by a
  stored-hierarchy phase in the DependencyEditor and BatchApplier
  dotted-child conformance contracts on every leg; a mutant that drops the
  rule gets the hierarchy conflict instead (409 dependency_cycle on the
  wire).
- The bd create --graph dry-run note now says the live create may also
  refuse an edge that gates a dotted-id child on its own ancestor.
- The DottedChildDependencyError comment says the message is kept verbatim
  and says "deadlock" whatever the type.

Not changed: bd relate (relates-to does not schedule) and the edges a
create writes with its issue (bd create --deps/--waits-for, and over
HTTP an explicit dotted id with a non-immediate ParentID) still write
through paths that skip the rule. The scheduling shapes need an explicit
dotted id or a grandparent target. Follow-up bd-25s1wh tracks moving the
rule down to the domain/store add verbs, with a structural bypass for
reparent and template edges.

Iteration 2 (minor): the CheckDottedChildDependency doc no longer implies
bd link and bd batch are the only writers outside the roles. It names
bd relate and the create edges as not applying the rule yet and cites
bd-25s1wh.

Complexity (cyclomatic/cognitive): runBatchOp 23/35 -> 21/31,
runBatchOpUOW 28/48 -> 26/44, batchDepAddEdge 5/4. Touching them brings
both pre-existing dispatch switches into the measured set; splitting them
is out of scope here.

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

* docs(issueops,httpapi): document the dotted-child 400 and widen its gap list

Review fixup for PR #7424 (relaunch, iteration 1, minors).

- The OpenAPI spec now describes the wire change this PR makes. The
  dependencies:add and issues:batchApply 400 vocabularies name an edge
  from a dotted-id child to its own ancestor (anything but the
  parent-child edge to its immediate parent; param `edges` and `items`).
  dependencies:add says why that is request-intrinsic, and both 409s say
  it is never dependency_cycle or dependency_exists, even for a child
  whose parent-child edge is stored. Response descriptions only: the
  generated types and the wireshape digest are unchanged (make api-check).
- The CheckDottedChildDependency doc no longer reads as a complete list of
  the writers that skip the rule. Besides bd relate and the create edges
  it names bd duplicate, bd supersede, bd duplicates --auto-merge (its
  related link and its reparenting) and the tracker engine's
  createDependencies, and says the molecule, template and swarm writers
  are unaudited. bd-25s1wh's notes carry the widened scope, including
  `bd duplicate bd-a.1 --of bd-a`.

Declined (nit): unifying the root issueops import alias across the PR's
cmd/bd files. batch.go is the one file that imports both issueops
packages, so one of them needs an alias there; it uses publicops, the
repo's usual alias for the root package, and aliasing the other side
instead would rewrite base-owned lines.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:56:46 +00:00

143 lines
6.1 KiB
Go

// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dependencyeditor.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/issueops"
)
// maxAddDependencyEdges mirrors the wire's own bound (internal/httpapi's
// dependency_edit.go). It is checked HERE as well as there so the refusal names
// the bound instead of arriving as a 400 the user has to decode — and, more
// importantly, so nothing is ever tempted to chunk a larger request: chunking is
// the one path that silently breaks the request's one-transaction,
// one-history-entry contract (L16).
const maxAddDependencyEdges = 100
// httpDependencyEditor serves issueops.DependencyEditor from the two dependency
// custom methods (design D8 row 18).
//
// The role's whole difficulty is its refusal vocabulary, and the wave that
// landed these operations published the typed discriminators this client asked
// for: dependency_cycle carries issue_id/blocker_id/blocker_is_ancestor, so
// *DependencyHierarchyConflictError reconstructs in BOTH polarities with no
// prose parsing, and dependency_exists carries existing_type/requested_type. The
// mapping lives in the wire's problem table; what lives here is the request
// half and the members the wire cannot carry.
type httpDependencyEditor struct {
store *Store
wire WriteWire
}
var _ issueops.DependencyEditor = (*httpDependencyEditor)(nil)
// AddDependencies asserts a set of edges as one server-side transaction.
//
// Atomicity is the SERVER's and stays whole because the request does: the
// operation is all-or-nothing, so a client that split a graph across two
// requests would turn one atomic assertion into two and let a cycle gate that
// can only see one request at a time pass a graph that closes a loop across
// both. Hence the bound below refuses rather than chunks.
func (d *httpDependencyEditor) AddDependencies(ctx context.Context, req issueops.AddDependenciesRequest) (result issueops.AddDependenciesResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError into
// *InexpressibleError so errors.As(err, &unsupported) reaches
// *storage.ErrUnsupported, same as inexpressible does for a read role.
defer func() { err = d.store.inexpressible("DependencyEditor.AddDependencies", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.AddDependenciesResult{}, err
}
if len(req.Edges) == 0 {
return issueops.AddDependenciesResult{}, invalid("a dependency add names no edges")
}
if req.SkipPerEdgeCycleCheck {
return issueops.AddDependenciesResult{}, refuse(encode.OpAddDependencies, "W-AddDependenciesRequest.SkipPerEdgeCycleCheck")
}
if len(req.Edges) > maxAddDependencyEdges {
return issueops.AddDependenciesResult{}, refuse(encode.OpAddDependencies, "L16")
}
edges := make([]apigen.DependencyEdge, 0, len(req.Edges))
for i, edge := range req.Edges {
if err := checkEdge(i, edge); err != nil {
return issueops.AddDependenciesResult{}, err
}
edges = append(edges, apigen.DependencyEdge{
IssueId: edge.IssueID,
DependsOnId: edge.DependsOnID,
Type: string(edge.Type),
})
}
res, err := d.wire.AddDependencies(ctx, apigen.AddDependenciesRequest{Actor: req.Actor, Edges: edges})
if err != nil {
return issueops.AddDependenciesResult{}, err
}
// The response echoes the request in request order, because all-or-nothing
// means it is either every edge or the call failed. Reading it back rather
// than re-echoing the request is what would catch a server that ever
// answered something else.
added := make([]issueops.DependencyEdge, 0, len(res.Added))
for _, edge := range res.Added {
added = append(added, issueops.DependencyEdge{
IssueID: edge.IssueId,
DependsOnID: edge.DependsOnId,
Type: issueops.DependencyType(edge.Type),
})
}
return issueops.AddDependenciesResult{Added: added}, nil
}
// RemoveDependency removes exactly the named edge. A missing edge is Removed
// false with a nil error — a success, not a refusal, and the wire says the same.
func (d *httpDependencyEditor) RemoveDependency(ctx context.Context, req issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) {
if err := requireActor(req.Actor); err != nil {
return issueops.RemoveDependencyResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.RemoveDependencyResult{}, err
}
if err := requireID("depends-on id", req.DependsOnID); err != nil {
return issueops.RemoveDependencyResult{}, err
}
res, err := d.wire.RemoveDependency(ctx, apigen.RemoveDependencyRequest{
Actor: req.Actor,
IssueId: req.IssueID,
DependsOnId: req.DependsOnID,
})
if err != nil {
return issueops.RemoveDependencyResult{}, err
}
return issueops.RemoveDependencyResult{Removed: res.Removed}, nil
}
// checkEdge applies the request-intrinsic refusals before the dial.
//
// The self-dependency check is the one worth naming: the server refuses it too,
// but as a 400 that reaches a client as ErrValidation, while the role's contract
// promises ErrSelfDependency — and that sentinel is one the caller can act on.
// It is decidable from the request alone, so deciding it here loses nothing and
// keeps the vocabulary the role documents.
func checkEdge(i int, edge issueops.DependencyEdge) error {
switch {
case edge.IssueID == "":
return invalid("edges[%d].issue_id is required", i)
case edge.DependsOnID == "":
return invalid("edges[%d].depends_on_id is required", i)
case edge.Type == "":
return invalid("edges[%d].type is required", i)
case edge.IssueID == edge.DependsOnID:
return fmt.Errorf("%s: %w", edge.IssueID, issueops.ErrSelfDependency)
}
// The dotted-id hierarchy rule, for the self-dependency check's reason: the
// server refuses it as a 400 that arrives here as a bare ErrValidation,
// while the role promises the typed *DottedChildDependencyError. It is the
// library's own check, not a restatement.
return issueops.CheckDottedChildDependency(edge.IssueID, edge.DependsOnID, edge.Type)
}