Commit graph

5 commits

Author SHA1 Message Date
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
Julian Knutsen
2ec0b2f072
feat(purge): live-dependent protection, --wisps-plane selector, hour-precision --older-than, --limit (#6883)
* feat(purge): live-dependent protection, --wisps-plane selector, hour-precision --older-than

An orchestrator's wisp retention step deletes every closed row in the
wisps table older than N hours, except a closed wisp that an
open/hooked/in_progress wisp depends on through parent-child, tracks or
blocks. `bd purge` could not express that: it selected the ephemeral
TIER (so closed --no-history beads, which live in the wisps table, were
left behind), it deleted a closed molecule root whose step was still
open, and it floored --older-than hours to whole days (36h swept rows
24h old). All three land together so `bd purge --wisps-plane
--older-than 168h --force` covers that step.

Live-dependent protection (issueops.SweepRequest.ProtectLiveDependents,
SweepSkips.LiveDependent): a candidate is held back when a live row
depends on it through a SweepLiveDependentEdgeTypes edge (parent-child,
tracks, blocks), read from both dependency tables. "Live" is the same
not-done set the reference scan uses, custom statuses included, so it
is a superset of open/hooked/in_progress. `bd purge` always asks for it
(no opt-out: removing live work's root is `bd delete`'s job); `bd prune`
does not. Reported as live_dependent_skipped in --json.

Wisps-plane selector (issueops.SweepWispsPlane, `--wisps-plane`): the
candidates are every closed row in the wisps TABLE, whatever its
ephemeral/no_history/wisp_type values, via a new single-plane search
(issueops.SearchWispsPlaneInTx) that the store backends call directly
and the unit-of-work provider reaches through
IssueUseCase.SearchWispsPlane, so embedded, server and proxied share one
body. It reaches durable-tier (no-history) rows, so it carries the
durable tier's require-a-filter gate.

--older-than (purge and prune): day values keep their meaning (7, 7d,
2w); anything else is a Go duration taken exactly (36h, 168h, 90m).

Tests: three new Sweeper contract cases (wisps plane clears the whole
table, wisps plane requires a filter, protects live dependents) run on
dolt, embeddeddolt and the uow provider; workapi unit tests; a CLI
retention scenario run in embedded, shared proxied and managed-local
proxied modes (fails against origin/main); TestParseOlderThan.

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

* test(uow): classify IssueUseCase.SearchWispsPlane as a read in the notifying parity partition

TestRecordingIssueUseCaseCoversItsSurface requires every IssueUseCase
method to be either wrapped by the notifying decorator or exempted with
the reason it fires no hook. SearchWispsPlane reads state and changes
none, like SearchIssues beside it.

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

* fix(purge): refuse out-of-range --older-than; add --limit for bounded drains; cross-plane protection test

Review follow-ups on #6883.

--older-than: a day count past what a time.Duration holds (213504d,
30501w) used to wrap silently — 213504d became 25m26s, which on a
destructive command selected almost every closed row. It is now refused
as out of range; ParseDuration already refused oversized h/m/s values.

--limit N (issueops.SweepRequest.Limit, SweepResult.Remaining): one
purge deletes at most N rows, oldest closed_at first (then id), after
every protection, and reports the rest. --json adds remaining and
has_more when --limit is given. At ~15ms/row on the proxied path a
single unbounded sweep of a large backlog can outlive a caller's
deadline, roll back, and never clear; a bounded loop cannot. Negative
limits are ErrValidation at the role and refused at the CLI.

Tests: TestParseOlderThan out-of-range rows; contract cases
LimitTakesTheOldestClosedFirst and ProtectsLiveDependentsAcrossPlanes
(a live issues-table bead depending on a closed wisp via parent-child,
tracks and blocks keeps it) on dolt, embeddeddolt and uow; workapi
units for the ordering and the negative-limit refusal; the CLI
retention scenario now drains with --limit 1 and checks the overflow
refusal. CHANGELOG notes that sub-day Nh values used to round UP to a
day (12h is now taken exactly) and lists the protection under Changed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 00:57:24 -07:00
Julian Knutsen
25b055e038
Pin the is_blocked invariant as a postcondition of the roles that maintain it (#5436)
is_blocked is derived AND persisted. Three deduplication slices independently
flagged it: contract cases read the raw column as a precondition, one calling
that read load-bearing, but nothing pinned that the recompute itself is correct.

13 cases across five role contracts, wired at all three legs.

Not its own role, deliberately. The recompute fails the repo's role test — no
caller asks it as a question and no accessor reaches it. BlockedRecomputer is
the separate repair verb, already pinned. And role-ifying it would not close the
gap: it would contract-test a body shared verbatim by every mode, and would
still pass on a backend that never denormalized on write. The divergence surface
is per-role WIRING, hand-mirrored between issueops/ and domain/db/, and only
role cases run that wiring on all three legs.

The promise existed nowhere a contract could cite. It is now
issueops.BlockedStateInvariant, cited by symbol rather than line, stating the
predicate, the local-write clause (settled for every AFFECTED row inside the
mutating transaction — affected is not just the named row), the merge clause,
and the non-perturbation clauses.

One of this programme's cannot-fail tests was this very column: seeded to 1 with
no blocker edge, so the guard short-circuited and it could never fail on its own
term. The shared kit forecloses that structurally. No hook writes the flag —
every state is built through role verbs. watchFlip fails the test if the
pre-value already equals the value being asserted. Every case carries a
non-flipping control. Blocked preconditions pin the flag AND the edge facts.

Review then proved a stated clause had no case at all: deleting the crossing row
from its own affected set left Close, Reopen and Update-crossing all green,
because every fixture happened to make the crossing row unblocked and no fixture
hung a child off the row being closed. That regression strands a stale flag no
verb can repair. Now covered by a forced close of a row that is itself blocked
and carries a child, both subjects flipping.

Review also caught, and CI caught, a case asserting the claimed row was
untouched when a claim writes that row by design — it passed locally only
because updated_at is DATETIME at second precision. Narrowed to what the verb
actually promises, and the remaining flag control verified to still redden.

Recorded, not fixed: conditional-blocks edges are accepted by the probe but
never seeded; waits-for gates are pinned only on the add side; wisp-blocker
deletion is unpinned.
2026-08-08 11:23:34 -07:00
CI Bot
927f943572 feat(issueops): name the two dependency-endpoint refusals (bd-yby99.9)
DependencyEditor.AddDependencies refuses an edge whose SOURCE names no row,
and one whose TARGET names no row this database can see the absence of. Every
other refusal the role can raise hands a caller something to branch on —
ErrSelfDependency, ErrDependencyCycle, *DependencyTypeConflictError,
*DependencyHierarchyConflictError — and these two handed back "an error", with
different text on each backend. A programmatic consumer could not tell a ghost
endpoint from an infrastructure failure, and the role's own doc said so rather
than promising the anonymity would last.

Both now carry an identity: ErrDependencySourceNotFound and
ErrDependencyTargetNotFound, wrapped by a *DependencyEndpointNotFoundError that
names the refused edge and which of its endpoints was absent. Two sentinels
rather than one because the two are separate answers — a ghost source is always
a bad id, while a target is refused only where this database would have held
it. What is NOT refused is unchanged: an "external:" reference and another
repository's id are still stored as external targets.

The store-backed body and the cross-tier target precheck mint the refusal where
they already read the row. The domain repository has no such read: it learns of
the absence from a foreign-key violation, so it reads both endpoints back on
the transaction that refused, only on the refusal path, and never downgrades
the refusal to a probe's failure. Taking the identity out of the driver's
constraint name would have been the thing a typed refusal exists to avoid. One
user-visible consequence: the proxied-server path now renders "issue <id> not
found" where it used to render a raw foreign-key violation, which is what the
embedded path has always said.

The guarded create classifies the new type where it classified the raw
foreign-key signal, so a missing dependency, parent or waits-for target is
still ErrValidation wrapping ErrNotFound on every backend.

RemoveDependency is deliberately untouched. A removal that finds no edge is
Removed false with a nil error, so there is no refusal there to name.

The shared contract asserts the sentinel and the typed fields for each endpoint
in TWO POSITIONS: alone in a request, and mid-batch where the refusal competes
with the rollback of an edge already written, the half that also reads the
graph back at zero edges. Both cases were verified red on all three backends
before the production change — "issue <id> not found" untyped on the two store
paths, "Error 1452 ... Foreign key violation" on the unit-of-work path.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of CI Bot

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 19:45:54 +00:00
Julian Knutsen
d801ec43dc
feat(issueops): put every issue capability behind one library surface
Beads had two implementations of most issue verbs: one for the direct route
(the CLI talking to a store it opened itself) and one for the proxied-server
route (the CLI talking through a unit of work over a running Dolt server).
They drifted — different commit messages, different transaction boundaries,
different refusals, occasionally different answers.

Seven role interfaces now live in the leaf package issueops: Lifecycle,
Reader, ReadyClaimer, BatchCloser, DependencyEditor, Commenter and Relations.
Each is reached only through a store accessor, never a constructor, because
the accessor is where the hook and telemetry decorators add their layers.
Three implementations back every role — dolt, embeddeddolt, and the
unit-of-work provider the proxied route uses. Both routes call the same role
for close, dep add/remove/list, comment, ready --claim and update.

A depguard rule (httpapi-domain-boundary) denies internal/storage/domain from
internal/httpapi, so a handler cannot reach uw.IssueUseCase() past the roles
and open a second front door one lint-clean commit at a time.

Behaviour users will notice, all in the CHANGELOG:
  - bd close a b c is one Dolt commit, not three, and --claim-next moved
    inside that transaction so it fires only when something landed
  - the open-children guard moved into the transaction and its hand-rolled
    cmd/bd copy is gone, removing a read-then-write window that made
    bd close <child> <parent> depend on argument order
  - bd dep add --file honours deferred version commit
  - embedded bd comment writes the role's message and author
  - dep verb commit messages are the role's on the direct route

Wisp-sourced dependency edges are restored. Moving bd dep add onto the role
had pinned an edge's SOURCE to the issues plane, and the two routes did not
even fail alike: direct refused with "issue <id> not found", proxied threw an
fk_dep_issue violation. The comment justifying the pin claimed the issues
plane was "the only one its unit-of-work sibling can reach" — that was false;
domain.DependencyUseCase declared a full set of wisp twins with no production
caller. All three implementations now route per edge by the edge's own
source. A mixed request stays one transaction: parent-child-first ordering
and the whole-graph cycle gate span both planes, and a refusal rolls back
both. Behind the role, three bulk add verbs collapsed into one source-routed
AddDependencies, so no plane-pinned variant is left to reach for by mistake.

Six Provenance fields with no production caller were deleted rather than
wired — CloseRequest, CloseBatchRequest, ClaimNextRequest, AddCommentRequest,
AddDependenciesRequest, RemoveDependencyRequest. Each role already composes an
id-bearing message, so a caller could only restate the default and make it
unreachable from production. Two are not caller-settable even in principle:
CloseBatchCommitMessage names what LANDED and ClaimNextCommitMessage names the
id the claim WON. UpdateRequest and ReopenRequest keep theirs; commit messages
users see are unchanged.

Verified: build, vet and gofmt clean; golangci-lint 0 issues; protocol corpus
byte-identical under BEADS_PROTOCOL_REQUIRE_DOLT=1; all twelve
DependencyEditor conformance wirings green (four contract functions against
each implementation); TestEmbeddedDepAddWispSource runs bd dep add <wisp-id>
at the front door and was demonstrated RED against the pinned routing first.
Three internal/storage/dolt failures reproduce on pristine origin/main.

Known gaps are enumerated in the PR description rather than left to be found:
comment listing is on no role, bd dep tree and bd dep cycles have no role,
bd create and bd reopen are on Lifecycle only on the direct route, per-edge
line attribution is lost in bd dep add --file, multi-store bd close
--claim-next rides only the first store's batch, and the is_blocked staging gap
(bd-2y9ke, predates this change). Seven of the eight role interfaces now have a
shared conformance contract in backend/conformance, run at all three
implementations; main's Claimer, added in parallel by #5334, is the eighth and
has none yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 12:27:56 -07:00