beads/internal/httpapi/tree.go
CI Bot 67d38d2620 Trim this series' comments toward the repo's own density
Ten agents over 216 files, one directory-balanced group each, working to a
rubric that named what to cut (duplication narration, restatement of the next
line, the governing rule echoed in every command file, throat-clearing) and
what to keep (traps, invariants, security, tracker ids, behaviour changes, and
the "why a naive simplification destroys this assertion" rationale).

Net 1,523 lines. Density against this repo's own per-directory norm on main:

  cmd/bd              33.6% -> 27.3%   (main 10.7%)
  internal/storage    26.1% -> 23.1%   (main 14.1%)
  backend/conformance 34.0% -> 29.6%   (main 22.8%)
  internal/httpapi    30.9% -> 27.8%   (main 30.6%, now below)
  overall             34.7% -> 31.6%

Every agent landed at 18-25% rather than the 30% asked for, and every one gave
the same reason independently: what remained was on the keep list. Ten separate
judgements agreeing is the most useful result here — the prose is dense, but it
is mostly load-bearing, and the shortfall is the honest answer rather than a
failure to try.

TWO REVERTS, both to protect something worth more than the lines.

issueops/ is back to its pre-trim state, giving up 610 lines. The conformance
contracts cite the leaf docs BY LINE — "pins treewalker.go:52-66" — 155 times.
Trimming the cited files silently repointed those at whatever text moved into
those numbers, across agent boundaries so no agent could see it. A semantic
remapper recovered 141 of them, but 23 needed judgement and several landed on
struct fields. The leaf docs are the spec the contracts are written against;
they are the one place in this change where dense prose IS the deliverable, and
keeping them stable is worth more than the 610 lines. tree_walker_contract.go
and version_reconciler_contract.go went back for the same reason: an agent had
deleted a paragraph containing a citation, so positional restoration could not
align them.

After the reverts, exactly 5 citations point into a still-trimmed file and 2 of
those are weak — both in cmd/bd/config_guard_test.go, which this series never
touched and whose citations were already wrong on main (init.go:361 pointed at
a closing brace; the guard it names is at init.go:1499).

VERIFICATION. A guard strips every comment and all whitespace from each of the
193 modified files at HEAD and in the worktree and requires the two to be
byte-identical, so a code change cannot hide in a comment diff. It handles `//`
inside string and raw-string literals, and was tested against a deliberate code
change before being trusted. gofmt clean, go build, go vet, golangci-lint 0
issues, and the two AST-based tests that PARSE trimmed files — the timed
provider binding pin over claim.go and the serve database-source gate over
serve.go — both pass.

One real defect found while trimming: checkDatabaseSource's doc block ran into
`// sourceRoles is ...` with no blank line, so godoc attached thirty-one lines
of the wrong prose to func sourceRoles and left checkDatabaseSource
undocumented. Fixed by separating them.
2026-08-06 08:06:59 +00:00

132 lines
4.8 KiB
Go

package httpapi
import (
"errors"
"net/http"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// defaultTreeDepth is the document's `max_depth` default, and it is the CLI's
// too (`bd dep tree --max-depth`, 50).
//
// It is a FRONT-DOOR default rather than a role default on purpose: the role
// refuses a zero depth outright, because an uninitialized recursive walk must
// not mean "walk the whole graph".
const defaultTreeDepth = 50
// handleDependencyTree answers GET /v0/beads/dependencies/tree.
//
// No graph is walked, no depth counted, no visited set kept, no `both` merge
// performed and no status prune applied: all of that is inside
// issueops.TreeWalker, which `bd dep tree` reaches through the same accessor. A
// handler that merged the two directions for itself would be a second
// definition of what `direction=both` means.
//
// The element type is an ALIAS of types.TreeNode — the same struct the CLI's
// --json marshals — so there is no second wire struct here and there must never
// be one.
func (s *Server) handleDependencyTree(w http.ResponseWriter, r *http.Request) {
q := newQuery(r.URL.Query())
req := issueops.WalkTreeRequest{
RootID: q.str("root_id"),
Direction: issueops.TreeDirection(q.oneOf("direction", string(issueops.TreeDown),
string(issueops.TreeDown), string(issueops.TreeUp), string(issueops.TreeBoth))),
MaxDepth: defaultTreeDepth,
Status: types.Status(q.str("status")),
}
if depth := q.integer("max_depth"); depth != nil {
req.MaxDepth = *depth
}
if !s.acceptQuery(w, r, q) {
return
}
// `root_id` is required by the document, and its absence is refused HERE
// rather than left to the role: a missing required parameter and one sent
// empty are the same fact on the wire, and naming the parameter is worth
// more than forwarding the role's prose.
if req.RootID == "" {
requestInfo(r.Context()).refuse("root_id")
s.fail(w, r, InvalidArgument("root_id", ReasonInvalidValue, "root_id is required and must be an exact issue id"))
return
}
walker, err := s.treeWalker(r)
if err != nil {
s.failErr(w, r, err)
return
}
result, err := walker.WalkTree(r.Context(), req)
if err != nil {
s.failTreeWalkErr(w, r, err, req)
return
}
writeJSON(w, apigen.DependencyTreePage{
Items: wireTreeNodes(result.Nodes),
// Always false: this operation takes no limit, so nothing truncates the
// answer — `max_depth` bounds the DESCENT instead. Emitted rather than
// omitted so a client never has to tell "not truncated" from "this
// server does not say".
HasMore: false,
})
}
// failTreeWalkErr answers a failed walk.
//
// The role's request-validation refusals are the caller's own input and reach
// the client as the 400 they are; an absent root is the 404 it is; everything
// else keeps going through the one mapping in problem.go.
//
// The 400 names `direction` or `max_depth` rather than always naming the same
// parameter, because `param` is what a client dispatches on and the two have
// different recoveries. Which one comes from the REQUEST the handler still
// holds: only a non-positive depth can have produced a depth refusal, and only
// a value outside the closed set a direction one.
//
// The handler could almost have caught both itself — q.oneOf already refuses an
// unknown direction — but the role is the definition of the vocabulary, and
// this mapping is what makes a refusal from BELOW the handler arrive attributed
// rather than as an unattributed 400.
func (s *Server) failTreeWalkErr(w http.ResponseWriter, r *http.Request, err error, req issueops.WalkTreeRequest) {
switch {
case errors.Is(err, storage.ErrNotFound):
s.fail(w, r, NotFound())
case errors.Is(err, issueops.ErrValidation):
param := "root_id"
switch {
case req.MaxDepth < 1:
param = "max_depth"
case req.Direction != issueops.TreeDown && req.Direction != issueops.TreeUp &&
req.Direction != issueops.TreeBoth:
param = "direction"
}
requestInfo(r.Context()).refuse(param)
s.fail(w, r, InvalidArgument(param, ReasonInvalidValue, err.Error()))
default:
s.failErr(w, r, err)
}
}
// wireTreeNodes projects the role's flat node list onto the generated envelope's
// element type, which is an ALIAS of the canonical struct — so this dereferences
// pointers and does nothing else.
//
// It exists for the one thing that is not free: the document says `items` is an
// empty array and never null. Making that guarantee here means the wire promise
// does not depend on the role keeping its own.
func wireTreeNodes(nodes []*issueops.TreeNode) []apigen.TreeNode {
out := make([]apigen.TreeNode, 0, len(nodes))
for _, node := range nodes {
if node == nil {
continue
}
out = append(out, *node)
}
return out
}