beads/docs/workflows/gates.md
Harry Miller fe5b9d1e0f
fix(formula): reject a waits_for gate with no spawner, and stop reporting invalid formulas as not found (#5761)
* fix(formula): reject a waits_for gate that has no spawner to wait for

waits_for = "all-children" (or "any-children") names no spawner, so
collectDependencies infers one from needs[0] and emits no dependency at
all when the step has no needs. Validation accepted that step, cooking
gave it a gate:all-children label, and the result was a step with zero
dependencies that is ready immediately — a fan-in that silently never
fans in. Only the label survived to suggest otherwise.

Reject it where the intent is still visible, naming both repairs: add
needs, or name the spawner with children-of(step-id), which carries its
own spawner and stays valid without needs. depends_on is deliberately not
accepted as a substitute, because the inference does not read it.

The fan-in example in docs/workflows/gates.md taught exactly the broken
shape — a summarize step with waits_for and no needs — so it is corrected
here alongside, with the spawner step it was missing.

* fix(formula): make a validation failure distinguishable from "not a formula"

Callers that resolve a name as a formula and fall back to a proto/issue
lookup have no way to tell the two apart, so a formula that exists and
does not validate is reported as not found and its real error is thrown
away. The spawnerless waits_for gate rejected above lands in exactly that
path.

ErrVarValidation already exists for the same reason, covering bad --var
values. Give Validate the matching sentinel; the message it produces is
unchanged. Wiring the fallbacks to it is a separate change.

* fix(mol): report an invalid formula instead of calling it not found

pour, wisp, bond and seed resolve a name as a formula first and fall back
to a proto/issue lookup. Any error from the formula path was treated as
"this is not a formula", so a formula that exists and fails validation
came back as "'<name>' not found as formula or proto ID" — with bd
formula list happily showing it. The real error was never printed, and
the advice to run bd formula list confirmed the wrong diagnosis.

Each fallback now reports a validation failure directly, the way it
already does for the bad --var values ErrVarValidation covers. A name
that really is not a formula is unaffected.

* fix(mol bond): make --dry-run validate the formula the real bond validates

resolveOrDescribe resolved a formula name with parser.LoadByName, which
never calls Formula.Validate - LoadByName -> loadFormula -> ParseFile does
not, and only parser.Resolve does. The real bond path
(resolveAndCookFormulaWithVars) calls Resolve, so the dry-run previewed
"will cook as proto" for every formula the real bond rejects, including
for the waits_for-without-a-spawner rule this branch adds. The function's
own comment already promised the opposite.

resolveOrDescribe now resolves before it validates provided vars, which
also means the --var check runs against the merged formula rather than the
unmerged one, so a var declared only in a parent is checked too. The two
error wrappings match the real path's, so the routes produce the same
message rather than merely the same exit code.

TestBdMolBondDryRun_RejectsInvalidFormulaLikeTheRealBond runs both routes
against the same invalid formula and asserts they agree - both fail, both
name waits_for, neither reports it as "not found as issue or formula". It
reproduces the gap against the old code:

    dry-run previewed a bond the real bond rejects:
      A: dryrun-invalid-gate (formula -> will cook as proto)

Also from review:

- validation_sentinel_test.go uses strings.HasPrefix instead of a slice
  that would panic with index-out-of-range rather than failing cleanly if
  the message ever shortened.
- Step.WaitsFor's field doc now states the needs requirement, and
  schema_gen.go is regenerated from it, so the generated schema documents
  the rule the validator enforces. docs/workflows/gates.md already said it.

The condition-filtering follow-up is filed as GH#6437: Validate runs
inside parser.Resolve, before FilterStepsByCondition, so a spawner dropped
by a false condition still reaches collectDependencies as a dangling
reference and is skipped silently - the same zero-dependency gate, past
the new check.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(mol bond): assert the dry-run gap in process, not through a subprocess

The regression test spawned an embedded bd and ran two CLI invocations,
which is the most expensive shape of test in cmd/bd - and cmd/bd already
runs 477s of its 600s budget on the macos runner, so the addition timed
the package out.

The process boundary was never what the test was about. resolveOrDescribe
and resolveOrCookToSubgraph are both reachable directly with a molReader
that answers "no such issue", and GT_ROOT puts a temp formula dir on
formula.DefaultSearchPaths without touching HOME or the working directory.
Same assertion - the two routes agree, both name waits_for, neither
reports an invalid formula as not found - in 0.03s instead of 18s.

Asserting the routes against each other rather than against a literal
message is deliberate: it is what stops a validation rule added later from
re-opening the same gap. The LoadByName control is now explicit too, since
that call still accepting the formula is the reason the bug existed; if it
ever starts validating, the comparison stops distinguishing anything and
the test says so instead of passing quietly.

Second case added while here: the dry-run validated --var values against
the UNMERGED formula, so a constraint declared only in a parent went
unchecked. Resolving first fixes that as well, and an extends chain with
the enum in the parent pins it:

    dry-run accepted a var value the real bond rejects; the enum is
    declared only in the parent (real bond said: formula "dryrun-child":
    variable validation failed:
      - variable "env": value "staging" not in allowed values [dev prod])

Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(changelog): move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(bazel): enumerate the PR's two new test files in go_test srcs

Base added cmd/bd/BUILD.bazel and internal/formula/BUILD.bazel after this
branch's merge base, so the two untagged _test.go files this PR adds were
absent from their go_test srcs lists. Generated by 'make bazel-sync'
(bazel run //:gazelle); no hand edits. A second sync is a no-op.

* docs(formula): correct the waits_for spawner doc and the dry-run parity claim

Maintainer review fixup for the adoption of #5761 (review iteration 1
pre-merge checklist). Wording only -- no control flow changes.

internal/formula/types.go: the new Step.WaitsFor doc said "Requires needs
(or depends_on)", but Formula.Validate receives only step.Needs and cook
infers the spawner solely from Needs[0] (cmd/bd/cook.go:961-962) -- the
DependsOn loop never feeds waitsForSpawnerStepID, and the struct doc's
"merged during cooking" happens after Validate. A depends_on-only bare gate
is therefore correctly rejected: the code and the error message are right,
only the comment was wrong, and it shipped into the generated schema surface
agents read. docs/workflows/gates.md already states it correctly.
Regenerated schema_gen.go with `go generate ./internal/formula/`.

CHANGELOG.md: "so it fails on exactly what the real bond fails on" was an
overclaim. The dry-run now resolves and validates the way the real bond
does, but five later real-path failure surfaces (inline expansions,
expansions, aspect load/type, condition filtering) stay outside the preview.
Named that boundary rather than claiming total parity.

Contributor commits untouched.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:09:59 -07:00

7.5 KiB

title description
Gates Async wait conditions that park a workflow step until the world catches up — a human decision, a timer, or a GitHub run or PR.

Some workflow steps can't proceed on code alone: a release needs CI to go green, a deploy needs a human sign-off, a cleanup should wait 24 hours. A gate is an issue that represents that wait. It blocks a step the same way any blocker does — the step leaves the ready frontier until the gate closes — so agents never need to poll or spin.

How a gate works

A gate is a bead like any other: created open, it blocks its waiters through a normal dependency edge, and the step becomes ready the moment the gate closes. Gates close in one of two ways:

  • Manually — bd gate resolve <gate-id> (human gates always close this way).
  • Via bd gate check — evaluates open timer, GitHub, and bead gates against the real world and closes the ones whose condition is met.
bd gate list                 # open gates
bd gate list --all           # include closed
bd gate show <gate-id>       # details and waiters
bd gate check                # evaluate open gates, close satisfied ones
bd gate check --dry-run      # report without closing
bd gate resolve <gate-id>    # close a gate manually

Gate types

Type Waits for Closed by
human a person's decision bd gate resolve only
timer a duration after gate creation bd gate check once the timeout elapses
gh:run a GitHub Actions workflow to complete successfully bd gate check (uses gh run view)
gh:pr a pull request to merge bd gate check (uses gh pr view)
bead a bead to close — a plain ID names a bead in this rig, the cross-rig form is <rig>:<bead-id> bd gate check for plain local IDs; cross-rig values cannot be checked — resolve those manually

Timeouts use Go duration syntax: 30m, 1h, 24h (there is no d unit — write 24h, not 1d).

GitHub gates use the current Git repository by default. To evaluate a PR or workflow run in another repository, set the gate's string metadata.repo value to OWNER/REPO or HOST/OWNER/REPO. An ad-hoc gh:run/gh:pr gate created with bd gate create inherits a valid metadata.repo value from the issue it blocks; human/timer/bead gates do not, since metadata.repo is unrelated, ordinary metadata for those types. bd gate check rejects malformed repository values instead of falling back to the current repository.

Known limitations: multi-rig and proxied-server topologies

Bead gates and prefix routing (routes.jsonl) do not work in every topology. Three limitations to expect, all tracked in #5861:

  • Cross-rig bead gates never resolve on their own. A <rig>:<bead-id> await value reports cannot be checked (multi-rig routing removed) and stays pending regardless of the awaited bead's status. Close it with bd gate resolve.
  • bd close cannot verify a bead gate in the experimental proxied-server mode. Proxied-server commands never open a local store, so closing the gate refuses with no local store available even when the awaited bead is closed. Run bd gate check, which evaluates bead gates in proxied-server mode and closes the satisfied ones, or bd close --force.
  • Prefix routing cannot open a proxied-server target rig. A routed lookup into a rig that is itself in proxied-server mode fails with proxy server store needs to be uow provider, so an all-proxied shared-server topology cannot resolve routed targets at all.

Gates in formulas

A formula step declares a gate with a [steps.gate] block. When the formula is instantiated, bd creates the gate issue and wires it as a blocker of that step. The schema has five fields: type, id, await_id, timeout, and repo.

This is the release gate from beads' own release formula — the step that waits for the GitHub release workflow:

[[steps]]
id = "wait-for-ci"
title = "Wait for release workflow"

[steps.gate]
type = "gh:run"
id = "release.yml"       # which workflow to watch
timeout = "30m"          # escalate if it takes longer

For a gh:run or gh:pr gate that watches another repository, set repo the same way a metadata.repo value works for an ad-hoc gate — OWNER/REPO or HOST/OWNER/REPO. Malformed values are rejected when the gate is checked:

[[steps]]
id = "wait-for-downstream"
title = "Wait for downstream release"

[steps.gate]
type = "gh:run"
id = "release.yml"
repo = "org/downstream-repo"   # check gh:run against this repo, not the current one

repo accepts a {{var}} placeholder (e.g. repo = "{{gate_repo}}"); for a formula persisted with bd cook --persist, the placeholder is substituted when the proto is later poured with bd mol pour --var gate_repo=..., the same as title, description, and await_id.

bd gate discover (auto-discovery of a gh:run gate's run ID) requires a workflow name hint (await_id/id, not left blank) for a gate targeting another repository — without one, the local commit/branch heuristics that narrow a same-repo match don't apply across repos, so nothing but the workflow name can identify the right run. A cross-repo gate discovery also ignores the local checkout's branch unless --branch is passed explicitly; an auto-detected local branch has no relationship to the target repo's branches.

A human sign-off gate:

[[steps]]
id = "approve-deploy"
title = "Human approves the deploy"

[steps.gate]
type = "human"

And a cooling-off timer:

[[steps]]
id = "wait-24h"
title = "Let the release bake"

[steps.gate]
type = "timer"
timeout = "24h"

Verify what the parser actually understood before pouring — unknown keys in TOML are dropped silently:

bd formula show <formula> --json   # inspect the parsed gate blocks

Creating gates outside formulas

bd gate create attaches a gate to existing work:

# Block bd-abc until a PR merges
bd gate create --type=gh:pr --blocks bd-abc --await-id=42

# Block bd-abc until a human resolves the gate
bd gate create --type=human --blocks bd-abc --reason "Design sign-off"

# Add another waiter to an existing gate
bd gate add-waiter <gate-id> <issue-id>

Fan-in: waiting on other steps

Waiting on other steps is not a gate — it's a dependency. Use needs to fan in on named steps, and waits_for when a step must wait for dynamically-created children:

[[steps]]
id = "merge-results"
title = "Merge results"
needs = ["test-a", "test-b"]     # fan-in on named steps

[[steps]]
id = "fan-out"
title = "Spawn a worker per shard"

[[steps]]
id = "summarize"
title = "Summarize all spawned work"
needs = ["fan-out"]              # the spawner whose children to wait for
waits_for = "all-children"       # or "any-children", or "children-of(fan-out)"

all-children and any-children wait for the children of needs[0], so a step using them must declare needs; children-of(step-id) names the spawner itself and does not. A bare gate with neither is rejected when the formula is cooked, because it would wait for no one.

Working with gated molecules

bd ready --gated        # molecules where a gate just closed (ready to resume)
bd blocked              # what's waiting, and on which gates

Automation patterns: run bd gate check on a schedule (cron, CI, or an orchestrator loop) so timer and GitHub gates close without a human in the loop; keep human gates for the decisions that should never auto-close.