test(proxy): harden history and remote front doors (#6293)

* test(proxy): harden history and remote front doors

* fix(proxy): preserve ready claim and compact refusal contracts

* fix(proxy): validate ready claim row caps preprovider

* fix(proxy): key capability front door on command paths

Review fixes for the proxied-server capability front door.

Blocking: validateProxyCapabilitiesBeforeProvider keyed on cobra's leaf
Name(), and `bd ready` and `bd mol ready --gated` share the leaf name
"ready". The max-rows refusal written for the former also refused the
latter for anyone with BEADS_MAX_ROWS exported — a proxy-supported
command that has no --max-rows flag to refuse. Every branch and both
policy tables now key on proxyCommandPath (the path below the root),
with an explicit "mol ready" row saying so. The compact refusal moves
from "compact" to "admin compact" for the same reason: root `bd compact`
is a different command with its own proxied route, and its message now
names `bd admin compact --dolt` rather than a `compact --dolt` that the
root command has no flag for.

Blocking: the allow path had no coverage, and it is the direction that
needs it — a refusal that stops firing degrades to the older late
failure, but one that fires too widely breaks a working command at the
front door where nothing catches it. Added a real-command-tree allow
table (a parentless cobra command has no path and matches no rule, which
is how a synthetic test tree reports success for a refusal that never
fired), a drift guard that every table key names a command that exists,
and an e2e allow matrix running the proxy-supported set against a live
managed-local proxied project, once clean and once under
BEADS_MAX_ROWS=5. `bd ready` under that cap is in the same table as the
control: it must still refuse.

Row cap resolved once on the proxied claim path, via resolveMaxRowsQuiet
rather than by hoisting the claim early-return above resolveMaxRows. The
duplicate line is the malformed-BEADS_MAX_ROWS advisory, which is a side
effect of resolving; the front door now resolves silently and the
command body stays the sole warner, so the message appears exactly where
it did before the front door existed. Hoisting would have moved the
`--max-rows -1` usage rejection back behind provider construction and
regressed TestReadyClaimValidatesMaxRowsBeforeProvider, which this PR
added.

Also folded in, all in-theme:

- ProxyOutcomeNA asserts clean (it states the command lacks the flag,
  which is nothing to refuse), and a rule carrying neither code nor
  message falls back to a generic one instead of rendering as a bare
  "Error: " with exit 1.
- The list/--repo row said notApplicable(); list_proxied_server.go
  refuses it. A policy table that contradicts the command is worse than
  a missing row.
- preflight binds --json to &jsonOutput like every other command's local
  --json. commandJSONFlagChanged suppresses the config-driven default
  whenever a local --json is set, so an unbound flag left
  `bd preflight --json` with jsonOutput=false.
- Deleted the proxied no-op in doctor.go. "doctor" is in the refusal
  table now, so the front door returns exit 1 before RunE ever runs.
  CHANGELOG records that flip (exit 0 with a stderr note becomes exit 1
  with proxy.doctor.unsupported) and that --json refusals are strict
  JSON on stdout.
- Deleted the dead tail block in validateProxyMaintenanceBeforeProvider:
  it could only run for a space-free path, which the table lookup above
  it had already handled.
- TestHistoryDirectOnlyRefusalContract iterates its own expectation
  table, so all 13 declared rows are asserted rather than 11.

- HandleProxyCapabilityError(nil) returns nil. Every AssertProxy* allow
  path returns nil and this wraps that return value directly, so the
  natural way to add the next rule -- a bare
  `return HandleProxyCapabilityError(AssertProxy...(...))` with no
  preceding `if` -- would have rendered an allowed capability as
  "Error: <nil>" with exit 1. Latent today: all five nil-capable call
  sites are guarded by conditions whose rules resolve to refused().
- The third front-door branch, the skipsStoreInit route into
  validateProxyMaintenanceBeforeProvider, keys on proxyCommandPath like
  the other two, and "doctor" joins the path list in
  TestProxyFrontDoorBranchesUseRealCommandPaths so the drift guard
  covers all three. It returns unconditionally, so a future
  `bd <parent> doctor` matching on the leaf name would have taken nil
  back from the now path-keyed validator and returned early past
  guardLegacyNoStoreCommand and getDoltAutoCommitMode.

* test: make direct and proxied history ordering fixtures deterministic

Assign distinct fixture timestamps and assert the expected newest-first sequence so same-second writes cannot make SQL/proxy parity flaky.

Agent: Codex (unknown model, unknown reasoning)

* test(proxy): expect scoped admin compact refusal

Agent: Codex (unknown model, unknown reasoning)

* fix(proxy): restore typed refusals and settle the ready --claim contract

Maintainer review fixes for #6293.

Major: `bd list --repo` under --proxied-server was the one live refusal this
PR converted from a typed ProxyCapabilityError to a bare errors.New. The
pre-provider gate covers `create` only, so runListProxiedServer is list's sole
enforcement point: --json got prose on stderr instead of
{"code":"proxy.repo.unsupported",...,"mutates":false} on stdout, while the PR
simultaneously added a "list"/ProxyCapRepo policy row that no non-test call
site could reach. The call site is typed again and keyed on the command path,
which makes that row the single source of the message. list.go's wrapper now
passes an already-rendered exitError through instead of re-wrapping it, so the
typed refusal no longer picks up a trailing "Error: exit code 1".

Major: the front door's new --claim early return contradicted ready.go, which
is untouched and still refuses any positive cap "including on --claim" -- so
the bypass never let a claim through. It only moved the refusal after provider
setup and, with max_rows.go downgraded to HandleErrorRespectJSON, stripped the
stable code: `bd ready --max-rows 5 --json` answered proxy.max_rows.unsupported
while `bd ready --claim --max-rows 5 --json` answered a bare {"error":...}. One
refusal, two shapes, selected by an unrelated flag. Settled toward the
documented contract, and toward the pre-existing
TestReadyRefusesMaxRowsUnderProxiedServerOnClaim which already pinned it:
--claim is not exempt. The early return is gone and
rejectResolvedMaxRowsUnderProxiedServer is typed again, so the front door and
its backstop in ready.go render identically. The claim path keeps what it
gained -- a malformed or negative value is still rejected before any provider
work, resolved quietly so the advisory still prints exactly once. The three
comments that disagreed about this contract now agree.

Also folded in, all in-theme:

- The create/show proxied fallbacks are typed again and marked as the dead
  defensive paths they are. Same downgrade, shadowed by the gate rather than
  live, so nothing failed when the contract left them.
- compact.go's dead fallback carries the gate's corrected wording
  ("bd admin compact --dolt"), and the table comment no longer asserts the
  message did not change in the same hunk that changed it.
- The "mol ready" row's comment says what the row is -- a documentation pin.
  Path keying is the guard it was crediting itself for.
- Tests: the strict-JSON shape (code/mutates/exit) of the list --repo refusal,
  claim-and-bulk parity plus the backstop for the max-rows refusal, and
  preflight's --json binding in both directions -- including the config half
  end-to-end, since flag.Value.Set never sets Changed and the config default
  only lands inside refreshBoundCommandConfig.
- CHANGELOG: #5859 sits in exactly one section again (it is not an ancestor of
  v1.3.0), plus an [Unreleased] entry for this PR's own user-visible deltas,
  including the bd preflight json-config change.

---------

Co-authored-by: CI Bot <ci@beads.test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-09-23 03:19:22 -07:00 • committed by GitHub
commit 6f8d153417
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 1054 additions and 101 deletions

View file

@ -133,16 +133,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`backend_managed` is false on external proxied topologies, where the dolt
server is not bd's process to report on.
- **`bd mol ready --gated` no longer refuses under `--proxied-server` when
`BEADS_MAX_ROWS` is set**
([#6293](https://github.com/gastownhall/beads/pull/6293)). The proxied
capability front door keyed its rules on cobra's leaf name, and `bd ready`
and `bd mol ready --gated` share the leaf "ready", so the row cap refusal
written for the former also refused the latter — a proxy-supported command
with no `--max-rows` flag to refuse. Rules are keyed on the full command
path now.
### Changed
- **Proxied-server refusals now say *why* they refuse.** The JSON a refused
command prints gains a `reason` field next to the existing `code`, `error`
and `mutates`: `design` for a refusal that is expected to stay (shared
history, multi-repo routing, destructive admin, strict `--readonly`) and
`unimplemented` for a capability gap with a named owner. Every existing code,
message and exit status is unchanged, and `reason` is absent on refusals that
report a runtime state rather than a policy, so existing consumers are
unaffected. The policy behind it moved into one registry
`unimplemented` for a capability gap with a named owner. Adding `reason` left
every existing code, message and exit status as it was, and `reason` is absent
on refusals that report a runtime state rather than a policy, so existing
consumers are unaffected. The policy behind it moved into one registry
(`cmd/bd/capability_registry.go`) that every command must appear in.
- **A command with no proxied-server route now fails with a typed error**
(`proxy.store.unrouted`) instead of the bare string `proxy server store
@ -158,6 +167,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
instead of the message followed by `Error: exit code 1` and the full usage
text. Exit statuses are unchanged; this applies on every topology.
- **Proxied `--repo` and row-cap refusals are typed again**
([#6293](https://github.com/gastownhall/beads/pull/6293)). `bd list --repo`
under `--proxied-server` answers `--json` with the stable
`{"code": "proxy.repo.unsupported", …, "mutates": false}` on stdout rather
than prose on stderr, and `bd ready --claim --max-rows N` refuses with the
same `proxy.max_rows.unsupported` shape as `bd ready --max-rows N`: `--claim`
does not exempt a row cap the proxied route cannot enforce either way.
- **The proxied `bd admin compact` refusal names the command it means**
([#6293](https://github.com/gastownhall/beads/pull/6293)). The message is now
"only 'bd admin compact --dolt' is supported in proxied-server mode"; it read
"only 'compact --dolt'", which names the root `bd compact` — a different
command, with no `--dolt` flag and its own proxied route. Scripts matching
the old text need updating.
- **`bd preflight` honors the `json` config default**
([#6293](https://github.com/gastownhall/beads/pull/6293)). Its `--json` flag
is bound to the same global every sibling command binds, so `json: true` in
the config file now selects JSON output for `bd preflight` as it already did
elsewhere. Previously only the explicit flag was honored — and, because an
unbound flag reports as unset, `bd preflight --json` did not reach every
JSON-aware renderer.
- **`bd gate check` resolves bead gates whose target lives in a prefix-routed
rig** ([#5859](https://github.com/gastownhall/beads/pull/5859)). After a local
miss, the evaluator follows the target bead ID through `routes.jsonl` and
@ -475,6 +504,22 @@ which dumps the entire release history.)
`BD_ALLOW_REMOTE_MIGRATE=1` in scripted use. Reads keep working on the
current schema meanwhile. Embedded (single-user) databases still
auto-migrate silently, unchanged. (#5920)
- **Commands that cannot work under `--proxied-server` now refuse before any
provider opens** ([#6293](https://github.com/gastownhall/beads/pull/6293)).
`bd doctor`, `bd backup`, `bd restore`, `bd diff`, `bd migrate`, `bd branch`,
`bd conflicts`, `bd vc`, `bd federation`, `bd repo`, `bd flatten`, `bd sync`,
`bd dolt push|pull|commit`, `bd dolt remote add|list|reset-data`, and
`bd admin compact` without `--dolt` return a typed refusal carrying a stable
code (`proxy.doctor.unsupported` and friends) instead of failing partway
through, or silently doing nothing. Two changes worth planning for:
- `bd doctor` under `--proxied-server` used to print a note to stderr and
exit **0**; it now exits **1** with `proxy.doctor.unsupported`. A script
that treated bare `bd doctor` as a no-op in this mode needs to stop calling
it, or tolerate the non-zero status.
- Under `--json`, a refusal is strict JSON on **stdout**
(`{"code": …, "error": …, "mutates": false}`) rather than prose on stderr,
so a wrapper parsing stdout gets a machine-readable answer and
`"mutates": false` states that the refusal touched nothing.
- The smart migration gate's "auto-migrate as safe first-mover" and
auto-fast-forward arms are now embedded-only. On a shared server the gate

View file

@ -394,8 +394,12 @@ var proxyCapabilityRegistry = []capabilityRow{
// the --dolt arm has a proxied route (runCompactDoltProxiedServer). The
// --dolt arm is decided by flag VALUE, so the gate keeps a value-aware
// branch for it and lands here when the flag is off.
// The wording names the real command path. "compact --dolt" reads as the
// root `bd compact`, a different command with no --dolt flag and its own
// proxied route; compact.go's RunE fallback carries the same corrected
// string so the gate and the fallback cannot drift apart.
refusedPath("admin compact", "proxy.compact.unsupported", ProxyReasonUnimplemented, trackLongTail).
withMessage("only 'compact --dolt' is supported in proxied-server mode"),
withMessage("only 'bd admin compact --dolt' is supported in proxied-server mode"),
// `bd restore` recovers a COMPACTED ISSUE's original text, not a backup —
// the backup verb is `bd backup restore`. Its snapshot read is ordinary
// CRUD; only its fallback path (reconstructing from Dolt history when no
@ -580,8 +584,18 @@ func capabilityRowFor(cmd *cobra.Command) (capabilityRow, bool) {
}
// commandRegistryPath is the registry key for a command: its full path with the
// root name removed, for example "dolt remote add".
// root name removed, for example "dolt remote add", "ready" for `bd ready`, and
// "" for the bare root.
//
// Both halves of the front door key on this rather than on cobra's Name(),
// which is only the leaf: two commands in different subtrees can share one, and
// `bd ready` and `bd mol ready --gated` do. A Name()-keyed rule silently applies
// to both, so a refusal written for one command lands on an unrelated command
// that no policy row authorizes.
func commandRegistryPath(cmd *cobra.Command) string {
if cmd == nil {
return ""
}
return strings.TrimSpace(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name()))
}

View file

@ -2,6 +2,8 @@ package main
import (
"encoding/json"
"maps"
"slices"
"strings"
"testing"
@ -59,7 +61,10 @@ func TestHistoryDirectOnlyRefusalContract(t *testing.T) {
oldProvider := uowProvider
oldJSON := jsonOutput
t.Cleanup(func() { uowProvider = oldProvider; jsonOutput = oldJSON })
for _, path := range []string{"branch", "conflicts", "repo", "federation", "vc", "flatten", "dolt push", "dolt pull", "dolt commit", "dolt remote add", "sync"} {
// Driven off the expectation table itself: a second hand-written path list
// let "dolt remote list" and "dolt remote reset-data" sit in `expected`
// while nothing asserted them, which reads as coverage that is not there.
for _, path := range slices.Sorted(maps.Keys(expected)) {
parts := strings.Split(path, " ")
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: parts[0]}

View file

@ -177,7 +177,7 @@ var inlineProxiedRefusal = regexp.MustCompile(`HandleErrorRespectJSON\("([^"]*pr
// proxied mode without being a capability refusal at all. Keeping both explicit
// is what lets the scan below be exhaustive rather than best-effort.
var inlineProxiedMessages = map[string]string{
"only 'compact --dolt' is supported in proxied-server mode": "admin compact",
"only 'bd admin compact --dolt' is supported in proxied-server mode": "admin compact",
// Not a refusal: --database is the flag that only MAKES SENSE on a proxied
// workspace, so this fires on the direct topologies.
"--database (or a --db value naming a database) is only supported in proxied-server mode": "",

View file

@ -87,7 +87,10 @@ Examples:
if compactDolt {
return runCompactDoltProxiedServer(rootCtx)
}
return HandleErrorRespectJSON("only 'compact --dolt' is supported in proxied-server mode")
// Same string the "admin compact" refusal row carries; the
// pre-provider gate short-circuits this path, so the two are kept
// identical rather than left to drift.
return HandleErrorRespectJSON("only 'bd admin compact --dolt' is supported in proxied-server mode")
}
// Block mutating operations in embedded mode; allow --stats, --analyze, --dry-run read-only paths.
if !compactStats && !compactAnalyze && !compactDryRun {

View file

@ -30,7 +30,11 @@ func resolveProxiedCustomTypes(dbTypes []string) []string {
func runCreateProxiedServer(cmd *cobra.Command, ctx context.Context, in createInput) error {
if in.repoOverrideSet {
return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapRepo))
// Defense in depth: validateProxyCapabilitiesBeforeProvider already
// refuses `create --repo` before this route is reachable. Typed anyway,
// so the day a command slips past the gate the refusal is still the
// same shape rather than silently degrading to prose.
return HandleProxyCapabilityError(AssertProxyCommandCapability("create", ProxyModeProxied, ProxyCapRepo))
}
switch {
case in.graphFile != "":

View file

@ -221,11 +221,6 @@ Examples:
return HandleError("%v", err)
}
if usesProxiedServer() {
fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.")
return nil
}
if doctorFix && isOrchestratorRoot(absPath) {
return HandleErrorWithHint(
"refusing to run 'bd doctor --fix' at orchestrator workspace root",

View file

@ -95,7 +95,15 @@ func buildJSONCapabilityError(e *ProxyCapabilityError) interface{} {
// HandleProxyCapabilityError renders a stable capability refusal while
// preserving the normal text/JSON front-door conventions.
//
// The allow path of every AssertProxy*Capability returns nil, and this wraps
// that return value directly, so nil must pass through: without the fast path
// errors.As(nil, ...) is false and an allowed capability would render as
// "Error: <nil>" with exit 1 at a front door nothing downstream catches.
func HandleProxyCapabilityError(err error) error {
if err == nil {
return nil
}
var capErr *ProxyCapabilityError
if !errors.As(err, &capErr) {
return HandleErrorRespectJSON("%v", err)

View file

@ -3,10 +3,16 @@
package main
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
@ -42,7 +48,7 @@ func TestHistoryRemoteRefusalFrontDoorMatrix(t *testing.T) {
requireProxiedServerEnv(t)
upstream := testutil.StartIsolatedDoltContainerHandle(t)
socket := filepath.Join(t.TempDir(), "dolt.sock")
bridge := startOutageBridge(t, socket, upstream.Port, true)
bridge := startHistoryUnixBridge(t, socket, upstream.Port)
t.Cleanup(func() { _ = bridge.Process.Kill() })
return bdProxiedInit(t, bd, "hm_unix", "--proxied-server-external-socket-path", socket)
}},
@ -54,8 +60,17 @@ func TestHistoryRemoteRefusalFrontDoorMatrix(t *testing.T) {
}{
{"branch", "proxy.branch.unsupported", "branch is not supported in proxied-server mode", []string{"branch", "feature"}},
{"conflicts list", "proxy.conflicts.unsupported", "conflicts list is not supported in proxied-server mode", []string{"conflicts", "list"}},
{"conflicts show", "proxy.conflicts.unsupported", "conflicts show is not supported in proxied-server mode", []string{"conflicts", "show"}},
{"conflicts resolve", "proxy.conflicts.unsupported", "conflicts resolve is not supported in proxied-server mode", []string{"conflicts", "resolve", "--all", "--ours"}},
{"repo add", "proxy.repo.unsupported", "repo add is not supported in proxied-server mode", []string{"repo", "add", "."}},
{"repo remove", "proxy.repo.unsupported", "repo remove is not supported in proxied-server mode", []string{"repo", "remove", "."}},
{"repo list", "proxy.repo.unsupported", "repo list is not supported in proxied-server mode", []string{"repo", "list"}},
{"repo sync", "proxy.repo.unsupported", "repo sync is not supported in proxied-server mode", []string{"repo", "sync"}},
{"federation sync", "proxy.federation.unsupported", "federation sync is not supported in proxied-server mode", []string{"federation", "sync"}},
{"federation status", "proxy.federation.unsupported", "federation status is not supported in proxied-server mode", []string{"federation", "status"}},
{"federation add-peer", "proxy.federation.unsupported", "federation add-peer is not supported in proxied-server mode", []string{"federation", "add-peer", "peer", "https://example.invalid/peer"}},
{"federation remove-peer", "proxy.federation.unsupported", "federation remove-peer is not supported in proxied-server mode", []string{"federation", "remove-peer", "peer"}},
{"federation list-peers", "proxy.federation.unsupported", "federation list-peers is not supported in proxied-server mode", []string{"federation", "list-peers"}},
{"vc merge", "proxy.vc.unsupported", "vc merge is not supported in proxied-server mode", []string{"vc", "merge", "feature"}},
{"vc commit", "proxy.vc.unsupported", "vc commit is not supported in proxied-server mode", []string{"vc", "commit"}},
{"flatten", "proxy.flatten.unsupported", "flatten is not supported in proxied-server mode", []string{"flatten"}},
@ -66,13 +81,16 @@ func TestHistoryRemoteRefusalFrontDoorMatrix(t *testing.T) {
{"dolt remote list", "proxy.dolt_remote.unsupported", "dolt remote list is not supported in proxied-server mode", []string{"dolt", "remote", "list"}},
{"dolt remote reset-data", "proxy.dolt_remote.unsupported", "dolt remote reset-data is not supported in proxied-server mode", []string{"dolt", "remote", "reset-data", "backup"}},
{"sync", "proxy.sync.unsupported", "sync is not supported in proxied-server mode", []string{"sync"}},
// Keyed on the path "admin compact", not the leaf name "compact":
// root `bd compact` is a different command that is proxy-supported.
{"admin compact", "proxy.compact.unsupported", "only 'bd admin compact --dolt' is supported in proxied-server mode", []string{"admin", "compact", "--stats"}},
}
for _, f := range fixtures {
t.Run(f.name, func(t *testing.T) {
p := f.make(t)
bdProxiedCreate(t, bd, p.dir, "matrix sentinel")
_ = proxy.Shutdown(p.proxyRoot)
before := snapshotHistoryArtifacts(t, p)
before := snapshotHistoryState(t, bd, p)
for _, tc := range commands {
t.Run(tc.name, func(t *testing.T) {
// Put the global flag before the subcommand. A few nested
@ -87,19 +105,20 @@ func TestHistoryRemoteRefusalFrontDoorMatrix(t *testing.T) {
Error string `json:"error"`
Mutates bool `json:"mutates"`
}
if jsonErr := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &got); jsonErr == nil {
if got.Code != tc.code || got.Error != tc.message || got.Mutates {
t.Fatalf("refusal=%+v, want code=%q error=%q mutates=false", got, tc.code, tc.message)
}
} else if strings.TrimSpace(stderr) != "Error: "+tc.message {
// Some nested commands render the same typed refusal through
// the text path before config-backed JSON is applied.
t.Fatalf("refusal JSON=%v stdout=%q stderr=%q", jsonErr, stdout, stderr)
if jsonErr := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &got); jsonErr != nil {
t.Fatalf("refusal must be strict JSON: %v stdout=%q stderr=%q", jsonErr, stdout, stderr)
}
if got.Code != tc.code || got.Error != tc.message || got.Mutates {
t.Fatalf("refusal=%+v, want code=%q error=%q mutates=false", got, tc.code, tc.message)
}
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 {
t.Fatalf("exit=%v, want 1", err)
}
if _, statErr := os.Stat(filepath.Join(p.proxyRoot, proxy.PIDFileName)); statErr == nil {
t.Fatal("provider proxy started for direct-only refusal")
}
after := snapshotHistoryArtifacts(t, p)
after := snapshotHistoryState(t, bd, p)
if string(before) != string(after) {
t.Fatal("durable artifacts changed during refusal")
}
@ -109,6 +128,72 @@ func TestHistoryRemoteRefusalFrontDoorMatrix(t *testing.T) {
}
}
// TestHistoryRemoteAllowPathFrontDoorMatrix is the allow-path complement of the
// refusal matrix above, and it is the direction that needed the coverage. A
// refusal that stops firing degrades to the older, opaque late failure; a
// refusal that fires too widely breaks a command that works, and does it at the
// front door where there is no fallback. That is what the leaf-name keying did
// to `bd mol ready --gated`, which is proxy-supported, has no --max-rows flag,
// and shares its leaf name with `bd ready` — so it refused to run for anyone
// with BEADS_MAX_ROWS exported.
//
// Each command runs twice: once with a clean environment and once under
// BEADS_MAX_ROWS=5, because the cap is the input that turned the front door
// from a no-op into a refusal.
func TestHistoryRemoteAllowPathFrontDoorMatrix(t *testing.T) {
bd := buildEmbeddedBD(t)
requireManagedLocalProxiedEnv(t)
p := bdManagedLocalInit(t, bd, "hm_allow", 5*time.Minute)
sentinel := bdProxiedCreate(t, bd, p.dir, "allow-path sentinel")
commands := []struct {
name string
args []string
// capRefused marks the commands whose row cap is genuinely unsupported
// under --proxied-server, so an active cap must still be refused rather
// than silently ignored. Every other row must survive the same cap.
capRefused bool
}{
{name: "mol ready --gated", args: []string{"mol", "ready", "--gated"}},
{name: "ready", args: []string{"ready"}, capRefused: true},
{name: "list", args: []string{"list"}},
{name: "dep tree", args: []string{"dep", "tree", sentinel.ID}},
}
for _, env := range []struct {
name string
extras []string
}{
{name: "clean"},
{name: "capped", extras: []string{"BEADS_MAX_ROWS=5"}},
} {
t.Run(env.name, func(t *testing.T) {
for _, tc := range commands {
t.Run(tc.name, func(t *testing.T) {
stdout, stderr, err := bdProxiedRunBuffersWithEnv(t, bd, p.dir, env.extras, tc.args...)
refusal := "is not supported in proxied-server mode"
if tc.capRefused && len(env.extras) > 0 {
if err == nil {
t.Fatalf("bd %s ignored an unsupported row cap; want a refusal\nstdout=%s", strings.Join(tc.args, " "), stdout)
}
if !strings.Contains(stderr+stdout, refusal) {
t.Fatalf("bd %s failed without the cap refusal: %v\nstdout=%s\nstderr=%s",
strings.Join(tc.args, " "), err, stdout, stderr)
}
return
}
if err != nil {
t.Fatalf("bd %s was refused on the allow path: %v\nstdout=%s\nstderr=%s",
strings.Join(tc.args, " "), err, stdout, stderr)
}
if strings.Contains(stderr, refusal) {
t.Fatalf("bd %s printed a proxied refusal while exiting 0: stderr=%q",
strings.Join(tc.args, " "), stderr)
}
})
}
})
}
}
func snapshotHistoryArtifacts(t *testing.T, p proxiedProject) []byte {
t.Helper()
var out []byte
@ -126,6 +211,130 @@ func snapshotHistoryArtifacts(t *testing.T, p proxiedProject) []byte {
return out
}
func snapshotHistoryState(t *testing.T, bd string, p proxiedProject) []byte {
t.Helper()
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "--json", "list")
if err != nil {
t.Fatalf("snapshot list failed: %v\nstdout=%s\nstderr=%s", err, stdout, stderr)
}
start := strings.Index(stdout, "[")
if start < 0 {
t.Fatalf("snapshot list did not return a JSON array: %q", stdout)
}
var rows any
if err := json.Unmarshal([]byte(stdout[start:]), &rows); err != nil {
t.Fatalf("snapshot list JSON: %v\n%s", err, stdout)
}
canonical, err := json.Marshal(rows)
if err != nil {
t.Fatalf("canonicalize issue rows: %v", err)
}
if err := proxy.Shutdown(p.proxyRoot); err != nil {
t.Fatalf("shutdown proxy after snapshot: %v", err)
}
return append(snapshotHistoryArtifacts(t, p), canonical...)
}
type directHistoryProject struct {
dir string
beadsDir string
database string
port int
env []string
}
func newDirectHistoryProject(t *testing.T, bd, prefix string) directHistoryProject {
t.Helper()
port := sharedProxiedServerPort(t)
dir := t.TempDir()
initGitRepoAt(t, dir)
beadsDir := filepath.Join(dir, ".beads")
database := uniqueProxiedDatabase()
env := historyCleanEnv(dir)
args := []string{
"init", "--backend", "dolt", "--server", "--external",
"--server-host", "127.0.0.1", "--server-port", strconv.Itoa(port),
"--database", database, "--prefix", prefix, "--quiet", "--non-interactive",
"--skip-hooks", "--skip-agents",
}
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = env
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("direct Dolt init failed: %v\n%s", err, out)
}
t.Cleanup(func() { dropTestDatabase(database, port) })
return directHistoryProject{dir: dir, beadsDir: beadsDir, database: database, port: port, env: env}
}
func historyCleanEnv(home string) []string {
env := make([]string, 0, len(os.Environ())+5)
for _, value := range os.Environ() {
if !strings.HasPrefix(value, "BEADS_") {
env = append(env, value)
}
}
return append(env,
"HOME="+home,
"BEADS_NO_DAEMON=1",
"BD_DISABLE_METRICS=1",
"BD_DISABLE_EVENT_FLUSH=1",
)
}
func runDirectHistory(t *testing.T, bd string, p directHistoryProject, args ...string) (string, string, error) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = p.dir
cmd.Env = p.env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}
func openDirectHistoryDB(t *testing.T, p directHistoryProject) *sql.DB {
t.Helper()
dsn := fmt.Sprintf("root:@tcp(127.0.0.1:%d)/%s?multiStatements=true&parseTime=true", p.port, p.database)
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatalf("sql.Open direct Dolt: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
t.Fatalf("ping direct Dolt: %v", err)
}
return db
}
func startHistoryUnixBridge(t *testing.T, endpoint, upstreamPort string) *exec.Cmd {
t.Helper()
if _, err := exec.LookPath("socat"); err != nil {
t.Skipf("socat is required for external Unix topology: %v", err)
}
if err := os.Remove(endpoint); err != nil && !os.IsNotExist(err) {
t.Fatalf("remove stale Unix socket: %v", err)
}
cmd := exec.Command("socat", "UNIX-LISTEN:"+endpoint+",fork", "TCP:127.0.0.1:"+upstreamPort)
if err := cmd.Start(); err != nil {
t.Fatalf("start Unix bridge: %v", err)
}
t.Cleanup(func() { _ = cmd.Process.Kill() })
deadline := time.Now().Add(3 * time.Second)
for {
if _, err := os.Stat(endpoint); err == nil {
return cmd
}
if time.Now().After(deadline) {
t.Fatalf("Unix bridge did not create %s", endpoint)
}
time.Sleep(20 * time.Millisecond)
}
}
// TestHistoryRemoteSupportedFrontDoorParity checks the two operations that
// are intentionally shared by direct and proxied providers.
func TestHistoryRemoteSupportedFrontDoorParity(t *testing.T) {
@ -165,3 +374,94 @@ func TestHistoryRemoteSupportedFrontDoorParity(t *testing.T) {
})
}
}
func TestHistoryRemoteSupportedDirectAndProxiedParity(t *testing.T) {
if os.Getenv("BEADS_TEST_PROXIED_SERVER") != "1" {
t.Skip("set BEADS_TEST_PROXIED_SERVER=1 to run direct/server parity")
}
bd := buildEmbeddedBD(t)
direct := newDirectHistoryProject(t, bd, "hp_direct")
proxied := newSharedProxiedProject(t, bd, "hp_proxy")
directIssue := createDirectHistoryIssue(t, bd, direct)
proxyIssue := bdProxiedCreate(t, bd, proxied.dir, "history parity")
directEvents := exerciseHistoryParity(t, bd, directIssue, func(args ...string) (string, string, error) {
return runDirectHistory(t, bd, direct, args...)
}, openDirectHistoryDB(t, direct))
proxyEvents := exerciseHistoryParity(t, bd, proxyIssue.ID, func(args ...string) (string, string, error) {
return bdProxiedRunBuffers(t, bd, proxied.dir, args...)
}, openProxiedDB(t, proxied))
if !reflect.DeepEqual(directEvents, proxyEvents) {
t.Fatalf("history event types differ: direct=%v proxied=%v", directEvents, proxyEvents)
}
}
func createDirectHistoryIssue(t *testing.T, bd string, p directHistoryProject) string {
t.Helper()
stdout, stderr, err := runDirectHistory(t, bd, p, "create", "--json", "history parity")
if err != nil {
t.Fatalf("direct create failed: %v\nstdout=%s\nstderr=%s", err, stdout, stderr)
}
start := strings.Index(stdout, "{")
if start < 0 {
t.Fatalf("direct create did not return JSON: %q", stdout)
}
var issue struct {
ID string `json:"id"`
}
if err := json.Unmarshal([]byte(stdout[start:]), &issue); err != nil || issue.ID == "" {
t.Fatalf("direct create JSON: %v\n%s", err, stdout)
}
return issue.ID
}
func exerciseHistoryParity(t *testing.T, bd, issueID string, run func(...string) (string, string, error), db *sql.DB) []string {
t.Helper()
if _, stderr, err := run("update", "--json", issueID, "--title", "history parity updated"); err != nil {
t.Fatalf("update %s failed: %v\nstderr=%s", issueID, err, stderr)
}
// Event timestamps have second precision. Give this fixture distinct times
// so the parity assertion tests newest-first history rather than an
// unspecified order between two writes in the same second.
if _, err := db.ExecContext(context.Background(),
"UPDATE events SET created_at = CASE event_type WHEN 'created' THEN '2026-01-01 00:00:00' WHEN 'updated' THEN '2026-01-01 00:00:01' ELSE created_at END WHERE issue_id = ?", issueID); err != nil {
t.Fatalf("set deterministic history timestamps: %v", err)
}
stdout, stderr, err := run("--json", "history", issueID, "--events")
if err != nil {
t.Fatalf("history --events %s failed: %v\nstdout=%s\nstderr=%s", issueID, err, stdout, stderr)
}
start := strings.Index(stdout, "[")
if start < 0 {
t.Fatalf("history --events did not return JSON array: %q", stdout)
}
var events []struct {
IssueID string `json:"issue_id"`
EventType string `json:"event_type"`
}
if err := json.Unmarshal([]byte(stdout[start:]), &events); err != nil {
t.Fatalf("history --events JSON: %v\n%s", err, stdout)
}
if len(events) == 0 {
t.Fatalf("history --events returned no events for %s", issueID)
}
types := make([]string, 0, len(events))
for _, event := range events {
if event.IssueID != issueID {
t.Fatalf("history event issue_id=%q, want %q", event.IssueID, issueID)
}
types = append(types, event.EventType)
}
if !reflect.DeepEqual(types, []string{"updated", "created"}) {
t.Fatalf("history event types = %v, want updated then created", types)
}
if _, err := db.ExecContext(context.Background(), "CALL DOLT_REMOTE('add', ?, ?)", "backup", "https://example.invalid/backup"); err != nil {
t.Fatalf("seed direct/proxy remote: %v", err)
}
stdout, stderr, err = run("--json", "dolt", "remote", "remove", "backup")
if err != nil || !strings.Contains(stdout+stderr, "backup") {
t.Fatalf("remote remove failed: %v\nstdout=%s\nstderr=%s", err, stdout, stderr)
}
return types
}

View file

@ -202,6 +202,13 @@ func runListCore(cmd *cobra.Command, _ []string) error {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
// An error that already carries an exit code came from a handler
// that has already rendered it (the typed --repo refusal writes
// its JSON to stdout). Re-wrapping would print a second line,
// "Error: exit code 1", after the real message.
if _, rendered := exitCodeFromError(err); rendered {
return err
}
return HandleError("%v", err)
}
return nil

View file

@ -22,7 +22,11 @@ import (
func runListProxiedServer(cmd *cobra.Command, ctx context.Context, out io.Writer, in listInput) error {
if in.repoOverrideSet {
return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapRepo))
// The one live (non-shadowed) --repo refusal: the pre-provider gate
// covers `create` only, so this is the site the contract is read from.
// Typed, so the proxyCommandCapabilities["list"] row is the single
// source of the message and --json still gets code/mutates on stdout.
return HandleProxyCapabilityError(AssertProxyCommandCapability("list", ProxyModeProxied, ProxyCapRepo))
}
switch {
case in.watchMode:

View file

@ -723,6 +723,17 @@ func prepareSelectedNoDBContext(beadsDir string) {
prepareSelectedCommandContext(beadsDir, true)
}
func commandJSONFlagChanged(cmd *cobra.Command) bool {
if cmd == nil {
return false
}
if cmd.Flags().Changed("json") {
return true
}
root := cmd.Root()
return root != nil && root.PersistentFlags().Changed("json")
}
// refreshBoundCommandConfig reapplies config-backed defaults after the command
// context has been rebound to a resolved target beads directory. This keeps
// explicit flags authoritative while letting rerouted/explicit-db commands use
@ -735,7 +746,7 @@ func refreshBoundCommandConfig(cmd *cobra.Command) {
if root == nil {
root = cmd
}
if !root.PersistentFlags().Changed("json") && !root.PersistentFlags().Changed("format") {
if !commandJSONFlagChanged(cmd) && !root.PersistentFlags().Changed("format") {
jsonOutput = config.GetBool("json")
}
if !root.PersistentFlags().Changed("readonly") {
@ -1078,7 +1089,7 @@ var rootCmd = &cobra.Command{
}
}
// If flag wasn't explicitly set, use viper value
if !cmd.Root().PersistentFlags().Changed("json") && !cmd.Root().PersistentFlags().Changed("format") {
if !commandJSONFlagChanged(cmd) && !cmd.Root().PersistentFlags().Changed("format") {
jsonOutput = config.GetBool("json")
} else {
flagOverrides["json"] = struct {
@ -1276,7 +1287,7 @@ var rootCmd = &cobra.Command{
if beadsDir == "" {
beadsDir = beads.FindBeadsDir()
}
if cmdName == "doctor" && usesProxiedServer() {
if commandRegistryPath(cmd) == "doctor" && usesProxiedServer() {
// Refuse only on a real refusal. The registry validator
// returns nil for doctor subcommands, and returning early on
// that would skip the legacy-store guard and autocommit-mode

View file

@ -173,7 +173,7 @@ func TestProxiedServerCompactDolt(t *testing.T) {
if err == nil {
t.Fatalf("bd admin compact --stats should be rejected in proxied mode\nstdout:\n%s", stdout)
}
if !strings.Contains(stdout+stderr, "only 'compact --dolt' is supported") {
if !strings.Contains(stdout+stderr, "only 'bd admin compact --dolt' is supported in proxied-server mode") {
t.Errorf("expected scoped rejection message, got:\n%s\n%s", stdout, stderr)
}
})

View file

@ -125,18 +125,60 @@ func resolveMaxRows(cmd *cobra.Command) (int, string, error) {
// closed here would break automation that has a global BEADS_MAX_ROWS set
// but accidentally got a typo.
func resolveMaxRowsEnvOnly() (int, string) {
raw, ok := os.LookupEnv(maxRowsEnvVar)
if !ok || raw == "" {
return 0, ""
}
n, err := strconv.Atoi(raw)
if err != nil || n < 0 {
n, source, raw, ok := parseMaxRowsEnv()
if !ok {
fmt.Fprintf(os.Stderr,
"Warning: %s=%q is not a non-negative integer; ignoring.\n",
maxRowsEnvVar, raw)
return 0, ""
}
return n, maxRowsEnvVar
return n, source
}
// parseMaxRowsEnv reads BEADS_MAX_ROWS without warning about a malformed
// value. Returns (cap, source, raw, ok); ok is false only for a value that is
// present but unusable, in which case the cap is disabled exactly as
// resolveMaxRowsEnvOnly disables it. An unset or empty variable is a valid
// "no cap" and reports ok.
func parseMaxRowsEnv() (int, string, string, bool) {
raw, ok := os.LookupEnv(maxRowsEnvVar)
if !ok || raw == "" {
return 0, "", raw, true
}
n, err := strconv.Atoi(raw)
if err != nil || n < 0 {
return 0, "", raw, false
}
return n, maxRowsEnvVar, raw, true
}
// resolveMaxRowsQuiet resolves the effective cap like resolveMaxRows but never
// emits the malformed-BEADS_MAX_ROWS advisory.
//
// It exists for the proxied capability front door, which resolves the cap in
// PersistentPreRunE to decide a refusal before the provider is constructed.
// Every command that reads the cap resolves it again in its own body, and the
// advisory is a side effect of resolving, so warning in the front door too
// would print one typo twice. The body's resolution stays the one that warns:
// the message keeps appearing exactly once, at the same point in the output it
// appeared at before the front door existed. A malformed value disables the
// cap, so the front door reaching the same "no cap" conclusion silently is the
// correct decision, not a suppressed one.
//
// An explicit --max-rows is still resolved through resolveMaxRows: that path
// never reads the environment, and rejecting a negative flag before the
// provider opens is the front door's job.
//
// No source string, unlike resolveMaxRows: the front door decides whether a
// cap is set, not how to attribute one in a message. The command body resolves
// the source for the message it prints.
func resolveMaxRowsQuiet(cmd *cobra.Command) (int, error) {
if cmd != nil && cmd.Flags().Changed(maxRowsFlagName) {
n, _, err := resolveMaxRows(cmd)
return n, err
}
n, _, _, _ := parseMaxRowsEnv()
return n, nil
}
// handleMaxRowsError checks whether err is a *issueops.ErrTooManyRows from

View file

@ -63,7 +63,13 @@ Examples:
func init() {
preflightCmd.Flags().Bool("check", false, "Run checks automatically")
preflightCmd.Flags().Bool("fix", false, "Auto-fix issues where possible (vendorHash, version sync)")
preflightCmd.Flags().Bool("json", false, "Output results as JSON")
// Bound to the package global like every other command's local --json.
// commandJSONFlagChanged suppresses the config-driven default whenever a
// local --json is set, so a flag that does not write the global would
// leave `bd preflight --json` with jsonOutput=false — inverting JSON mode
// for everything that reads the global, including the front-door error
// renderers.
preflightCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output results as JSON")
preflightCmd.Flags().Bool("skip-lint", false, "Skip lint check explicitly")
rootCmd.AddCommand(preflightCmd)
@ -79,7 +85,6 @@ func runPreflight(cmd *cobra.Command, args []string) error {
check, _ := cmd.Flags().GetBool("check")
fix, _ := cmd.Flags().GetBool("fix")
jsonOutput, _ := cmd.Flags().GetBool("json")
skipLint, _ := cmd.Flags().GetBool("skip-lint")
if fix {

View file

@ -6,6 +6,8 @@ import (
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
)
func TestCheckResult_Passed(t *testing.T) {
@ -401,3 +403,101 @@ func TestIsBeadsRepo(t *testing.T) {
t.Error("dir without go.mod should not be detected as the beads repo")
}
}
// TestPreflightJSONFlagBindsGlobal pins both halves of preflight's --json
// binding, which is one flag serving two masters. Setting it must write the
// package global, or every jsonOutput reader (including the front-door refusal
// renderers) stays in text mode while the user asked for JSON. Leaving it
// unset must report unchanged to commandJSONFlagChanged, which is what lets a
// config-file `json: true` reach preflight the way it reaches its siblings —
// a deliberate behavior change from the unbound shadow this replaced, and the
// reason the CHANGELOG calls it out.
//
// The last two subtests drive that config half rather than only asserting the
// negative direction. flag.Value.Set never sets Changed (only FlagSet.Set
// does), so the Changed==true branch of commandJSONFlagChanged needs its own
// case, and the behavior the CHANGELOG announces — configured `json: true`
// with no flag flipping jsonOutput — only happens inside
// refreshBoundCommandConfig, so it has to be driven through that function.
func TestPreflightJSONFlagBindsGlobal(t *testing.T) {
flag := preflightCmd.Flags().Lookup("json")
if flag == nil {
t.Fatal("preflight has no --json flag")
}
rootJSON := preflightCmd.Root().PersistentFlags().Lookup("json")
if rootJSON == nil {
t.Fatal("root has no persistent --json flag")
}
// refreshBoundCommandConfig consults config only when neither --json nor
// its hidden --format alias was given, so this test owns that flag's
// Changed bit too.
rootFormat := preflightCmd.Root().PersistentFlags().Lookup("format")
if rootFormat == nil {
t.Fatal("root has no persistent --format flag")
}
oldGlobal := jsonOutput
oldValue, oldChanged := flag.Value.String(), flag.Changed
oldRootChanged := rootJSON.Changed
oldFormatChanged := rootFormat.Changed
// refreshBoundCommandConfig reapplies every config-backed default, not
// just json; restore the rest so this test cannot leak into siblings.
oldReadonly, oldActor, oldAutoCommit := readonlyMode, actor, doltAutoCommit
t.Cleanup(func() {
_ = flag.Value.Set(oldValue)
flag.Changed = oldChanged
rootJSON.Changed = oldRootChanged
rootFormat.Changed = oldFormatChanged
jsonOutput = oldGlobal
readonlyMode, actor, doltAutoCommit = oldReadonly, oldActor, oldAutoCommit
config.ResetForTesting()
})
t.Run("flag writes the package global", func(t *testing.T) {
jsonOutput = false
if err := flag.Value.Set("true"); err != nil {
t.Fatal(err)
}
if !jsonOutput {
t.Fatal("preflight --json did not write jsonOutput; an unbound shadow leaves every reader of the global in text mode")
}
})
t.Run("neither flag set reports unchanged", func(t *testing.T) {
flag.Changed = false
rootJSON.Changed = false
if commandJSONFlagChanged(preflightCmd) {
t.Fatal("preflight reported an explicit --json with neither flag set; the config-file json default would never apply")
}
})
t.Run("explicit --json reports changed", func(t *testing.T) {
flag.Changed = false
rootJSON.Changed = false
if err := preflightCmd.Flags().Set("json", "true"); err != nil {
t.Fatal(err)
}
if !commandJSONFlagChanged(preflightCmd) {
t.Fatal("an explicitly set --json reported unchanged; the config default would override the flag the user typed")
}
})
t.Run("configured json default applies with no flag", func(t *testing.T) {
config.ResetForTesting()
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
config.Set("json", true)
flag.Changed = false
rootJSON.Changed = false
rootFormat.Changed = false
jsonOutput = false
refreshBoundCommandConfig(preflightCmd)
if !jsonOutput {
t.Fatal("config json:true with no --json flag left jsonOutput false; preflight would render text while the repo config asks for JSON")
}
})
}

View file

@ -126,9 +126,10 @@ func honored() proxyCapabilityRule {
func notApplicable() proxyCapabilityRule { return proxyCapabilityRule{Outcome: ProxyOutcomeNA} }
// ProxyCapabilityKey identifies a command's flag/argument on a topology.
// Argument is intentionally explicit (for example, "--watch"), allowing
// callers and tests to distinguish a command that lacks a flag (N/A) from one
// that refuses it.
// Command is the command's path below the root ("dep tree", "mol ready"),
// never its cobra leaf name — see commandRegistryPath. Argument is intentionally
// explicit (for example, "--watch"), allowing callers and tests to
// distinguish a command that lacks a flag (N/A) from one that refuses it.
type ProxyCapabilityKey struct {
Command string
Argument string
@ -169,6 +170,11 @@ var (
// `list --watch` is routed, so watching is possible over the provider;
// nothing else has been wired to it.
watchRefusal = refused("proxy.watch.unsupported", "watch mode not supported in proxied-server mode", ProxyReasonUnimplemented, trackLongTail)
// --repo routes to another workspace, bypassing the proxied root entirely,
// which is why it is design rather than a gap. `bd list` honors a repo
// override and refuses it at runtime, so its row specializes this rule
// instead of claiming the flag is absent.
repoRefusal = refused("proxy.repo.unsupported", "--repo is not supported with --proxied-server", ProxyReasonDesign, "")
)
// proxyCapabilityMatrix is the flag-keyed half of the policy; the path-keyed
@ -192,15 +198,24 @@ var proxyCapabilityMatrix = map[ProxyMode]map[ProxyCapability]proxyCapabilityRul
ProxyCapReadonly: refused("proxy.readonly.unsupported", "strict readonly is unavailable for dolt proxied-server backend; refusing to open a store that cannot guarantee mutation-free access", ProxyReasonDesign, "1.4 candidate: read-only SQL principal on the backend"),
ProxyCapMaxRows: maxRowsRefusal,
ProxyCapWatch: watchRefusal,
ProxyCapRepo: refused("proxy.repo.unsupported", "--repo is not supported with --proxied-server", ProxyReasonDesign, ""),
ProxyCapRepo: repoRefusal,
},
}
// proxyCommandCapabilities overrides the mode-wide default for one command.
// Keys are command paths (commandRegistryPath), so a row lands on the command it
// was written for and on nothing else. The "mol ready" row is a documentation
// pin rather than the guard: path keying is what stops `bd mol ready --gated`
// from inheriting the refusal `bd ready` carries on their shared leaf name
// "ready", and the row records that the command has no --max-rows flag to
// refuse. TestProxyCapabilityPolicyKeysResolveInRealCommandTree keeps the pin
// honest by failing if the path it names stops existing.
var proxyCommandCapabilities = map[string]map[ProxyMode]map[ProxyCapability]proxyCapabilityRule{
"show": {ProxyModeProxied: {ProxyCapWatch: watchRefusal}},
"list": {ProxyModeProxied: {ProxyCapWatch: honored(), ProxyCapMaxRows: honored(), ProxyCapRepo: notApplicable()}},
"list": {ProxyModeProxied: {ProxyCapWatch: honored(), ProxyCapMaxRows: honored(), ProxyCapRepo: repoRefusal}},
"dep tree": {ProxyModeProxied: {ProxyCapMaxRows: honored()}},
"ready": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}},
"mol ready": {ProxyModeProxied: {ProxyCapMaxRows: notApplicable()}},
"graph": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}},
"find-duplicates": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}},
}
@ -264,33 +279,53 @@ func AssertProxyCapability(mode ProxyMode, capability ProxyCapability) error {
return AssertProxyCommandCapability("", mode, capability)
}
// proxyCapabilityAllowed reports whether an outcome lets the invocation
// proceed. ProxyOutcomeNA means the command does not have the flag at all
// (see ProxyCapabilityKey), which is a fact about the command rather than a
// policy objection: there is nothing to refuse, so it asserts successfully.
func proxyCapabilityAllowed(outcome ProxyCapabilityOutcome) bool {
return outcome == ProxyOutcomeHonored || outcome == ProxyOutcomeDelegated || outcome == ProxyOutcomeNA
}
// proxyCapabilityRuleError renders a non-allowing rule as an error. A rule
// with neither a code nor a message would otherwise produce an error whose
// Error() is the empty string, which the CLI prints as a bare "Error: " with
// exit 1 — the least debuggable failure available — so it falls back to a
// generic message no matter how a future rule is written.
// It builds the typed error through proxyCapabilityErrorFor so a rule's Reason
// reaches the JSON refusal here exactly as it does from the registry half; a
// local struct literal would silently drop it.
func proxyCapabilityRuleError(rule proxyCapabilityRule, capability ProxyCapability, mode ProxyMode) error {
if rule.Code != "" {
if rule.Message == "" {
// rule is a copy, so this fills the fallback in for this render
// only and never edits the policy table.
rule.Message = fmt.Sprintf("%s is not supported in %s mode", capability, mode)
}
return proxyCapabilityErrorFor(rule)
}
if rule.Message != "" {
return fmt.Errorf("%s", rule.Message)
}
return fmt.Errorf("%s is not supported in %s mode", capability, mode)
}
// AssertProxyCommandCapability checks a command-specific capability rule.
// command is a command path (commandRegistryPath), not a cobra leaf name.
func AssertProxyCommandCapability(command string, mode ProxyMode, capability ProxyCapability) error {
if commands, ok := proxyCommandCapabilities[command]; ok {
if modes, ok := commands[mode]; ok {
if rule, ok := modes[capability]; ok {
// N/A means the command has no such flag, which is not a
// refusal. Without it, a future assert call site on an N/A row
// would return a non-nil error carrying an empty message.
if rule.Outcome == ProxyOutcomeHonored || rule.Outcome == ProxyOutcomeDelegated || rule.Outcome == ProxyOutcomeNA {
if proxyCapabilityAllowed(rule.Outcome) {
return nil
}
if rule.Code != "" {
return proxyCapabilityErrorFor(rule)
}
return fmt.Errorf("%s", rule.Message)
return proxyCapabilityRuleError(rule, capability, mode)
}
}
}
rule, ok := LookupProxyCapability(mode, capability)
if !ok || (rule.Outcome != ProxyOutcomeHonored && rule.Outcome != ProxyOutcomeDelegated) {
if rule.Code != "" {
return proxyCapabilityErrorFor(rule)
}
if rule.Message != "" {
return fmt.Errorf("%s", rule.Message)
}
return fmt.Errorf("%s is not supported in %s mode", capability, mode)
if !ok || !proxyCapabilityAllowed(rule.Outcome) {
return proxyCapabilityRuleError(rule, capability, mode)
}
return nil
}
@ -301,31 +336,38 @@ func validateProxyCapabilitiesBeforeProvider(cmd *cobra.Command) error {
if cmd == nil {
return nil
}
name := cmd.Name()
if name == "create" && cmd.Flags().Changed("repo") {
path := commandRegistryPath(cmd)
if path == "create" && cmd.Flags().Changed("repo") {
return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapRepo))
}
if name == "show" {
if path == "show" {
if watch, _ := cmd.Flags().GetBool("watch"); watch {
return HandleProxyCapabilityError(AssertProxyCommandCapability("show", ProxyModeProxied, ProxyCapWatch))
return HandleProxyCapabilityError(AssertProxyCommandCapability(path, ProxyModeProxied, ProxyCapWatch))
}
}
if name == "ready" {
maxRows, _, err := resolveMaxRows(cmd)
if path == "ready" {
// --claim is NOT exempt. The proxied ready role cannot enforce a row
// cap on either arm, and ready.go refuses a positive cap on both (see
// its comment above rejectMaxRowsUnderProxiedServer) — so exempting
// the claim here would not have let it through, only downgraded the
// same refusal to an untyped one raised after the provider opened.
// A malformed or negative value is still rejected here, before any
// provider work, which is what the claim path gained.
maxRows, err := resolveMaxRowsQuiet(cmd)
if err != nil {
return err
}
if maxRows > 0 {
return HandleProxyCapabilityError(AssertProxyCommandCapability(name, ProxyModeProxied, ProxyCapMaxRows))
return HandleProxyCapabilityError(AssertProxyCommandCapability(path, ProxyModeProxied, ProxyCapMaxRows))
}
}
if name == "graph" || name == "find-duplicates" {
maxRows, _, err := resolveMaxRows(cmd)
if path == "graph" || path == "find-duplicates" {
maxRows, err := resolveMaxRowsQuiet(cmd)
if err != nil {
return err
}
if maxRows > 0 {
return HandleProxyCapabilityError(AssertProxyCommandCapability(name, ProxyModeProxied, ProxyCapMaxRows))
return HandleProxyCapabilityError(AssertProxyCommandCapability(path, ProxyModeProxied, ProxyCapMaxRows))
}
}
return nil

View file

@ -2,9 +2,13 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"maps"
"os"
"slices"
"strings"
"testing"
@ -12,30 +16,288 @@ import (
)
func TestProxyCapabilityMatrix(t *testing.T) {
for _, cap := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows} {
err := AssertProxyCapability(ProxyModeProxied, cap)
for _, capability := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows} {
err := AssertProxyCapability(ProxyModeProxied, capability)
if err == nil {
t.Errorf("%s unexpectedly honored", cap)
t.Errorf("%s unexpectedly honored", capability)
}
var typed *ProxyCapabilityError
if !errors.As(err, &typed) || typed.Code == "" || typed.ExitCode != 1 || typed.Mutates {
t.Errorf("%s error = %#v, want stable non-mutating refusal", cap, err)
t.Errorf("%s error = %#v, want stable non-mutating refusal", capability, err)
}
}
for _, tc := range []struct {
cap ProxyCapability
want string
capability ProxyCapability
want string
}{
{ProxyCapWatch, "watch mode not supported in proxied-server mode"},
{ProxyCapRepo, "--repo is not supported with --proxied-server"},
} {
err := AssertProxyCapability(ProxyModeProxied, tc.cap)
err := AssertProxyCapability(ProxyModeProxied, tc.capability)
if err == nil || err.Error() != tc.want {
t.Errorf("%s error = %v, want %q", tc.cap, err, tc.want)
t.Errorf("%s error = %v, want %q", tc.capability, err, tc.want)
}
}
}
// realCommandPaths walks the actual bd command tree once and returns every
// command path below the root. Policy tables and front-door branches are only
// as good as their correspondence to this set: a key that matches nothing is
// dead policy, and a branch keyed on something that is not a path applies to
// whichever commands happen to share the string.
func realCommandPaths(t *testing.T) map[string]bool {
t.Helper()
paths := map[string]bool{}
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
if path := commandRegistryPath(c); path != "" {
paths[path] = true
}
for _, child := range c.Commands() {
walk(child)
}
}
walk(rootCmd)
if len(paths) == 0 {
t.Fatal("walked the real command tree and found no commands")
}
return paths
}
func realCommandAtPath(t *testing.T, path string) *cobra.Command {
t.Helper()
found, _, err := rootCmd.Find(strings.Split(path, " "))
if err != nil {
t.Fatalf("resolve %q in the real command tree: %v", path, err)
}
if got := commandRegistryPath(found); got != path {
t.Fatalf("resolve %q in the real command tree = %q", path, got)
}
return found
}
// TestProxyCapabilityPolicyKeysResolveInRealCommandTree is the drift guard for
// the flag-keyed policy table. Every key must name a command that exists, so a
// renamed or removed command turns into a test failure instead of a rule that
// silently stops applying.
func TestProxyCapabilityPolicyKeysResolveInRealCommandTree(t *testing.T) {
paths := realCommandPaths(t)
for _, table := range []struct {
name string
keys []string
}{
// The path-keyed half (proxyCapabilityRegistry) has its own drift guard
// in TestProxyCapabilityRegistryHasNoStaleRows, so only the flag-keyed
// table is checked here.
{"proxyCommandCapabilities", slices.Sorted(maps.Keys(proxyCommandCapabilities))},
} {
for _, key := range table.keys {
if !paths[key] {
t.Errorf("%s has a row for %q, which is not a real command path", table.name, key)
}
}
}
}
// TestProxyFrontDoorBranchesUseRealCommandPaths pins the command paths the
// three front-door branches key on by hand: the two validators, plus the
// skipsStoreInit route into validateProxyRegistryBeforeProvider in main.go.
// This is the assertion that would have failed on the leaf-name keying: a
// branch written for `bd ready` must name a path, because "ready" as a leaf
// name is also `bd mol ready --gated`.
func TestProxyFrontDoorBranchesUseRealCommandPaths(t *testing.T) {
paths := realCommandPaths(t)
for _, path := range []string{"create", "show", "ready", "graph", "find-duplicates", "admin compact", "mol ready", "doctor"} {
if !paths[path] {
t.Errorf("front door branches on %q, which is not a real command path", path)
}
}
}
// TestProxyCapabilityFrontDoorAllowsSupportedCommands is the allow-path
// complement of the refusal matrix, and it runs against the real command tree
// rather than a synthetic one. The refusal direction degrades to the older,
// opaque late failure when it misses; a spurious refusal breaks a working
// command outright, so the allow path is the side that needs the guard.
func TestProxyCapabilityFrontDoorAllowsSupportedCommands(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
for _, tc := range []struct {
path string
cappedEnv bool
wantRefuse bool
}{
// `bd mol ready --gated` is the regression: proxy-supported, accepts
// no --max-rows, and shares its leaf name with `bd ready`.
{path: "mol ready"},
{path: "mol ready", cappedEnv: true},
{path: "ready"},
{path: "list"},
{path: "list", cappedEnv: true},
{path: "dep tree"},
{path: "dep tree", cappedEnv: true},
{path: "compact"},
{path: "compact", cappedEnv: true},
// `bd ready` is the command the max-rows refusal was written for, so
// it must still refuse an active cap.
{path: "ready", cappedEnv: true, wantRefuse: true},
} {
name := tc.path
if tc.cappedEnv {
name += " with " + maxRowsEnvVar
}
t.Run(name, func(t *testing.T) {
if tc.cappedEnv {
t.Setenv(maxRowsEnvVar, "5")
} else {
t.Setenv(maxRowsEnvVar, "")
}
cmd := realCommandAtPath(t, tc.path)
var err error
stderr := captureStderr(t, func() {
err = validateProxyCapabilitiesBeforeProvider(cmd)
if err == nil {
// managed-local is the shape that owns its own dolt
// server, so a refusal here is a policy decision about the
// command rather than about the deployment.
err = validateProxyRegistryBeforeProvider(cmd, ProxyTopologyManagedLocal)
}
})
if tc.wantRefuse {
if err == nil {
t.Fatalf("bd %s was allowed; want a refusal", tc.path)
}
return
}
if err != nil {
t.Fatalf("bd %s refused before the provider: %v (stderr=%q)", tc.path, err, stderr)
}
if stderr != "" {
t.Fatalf("bd %s wrote %q to stderr on the allow path", tc.path, stderr)
}
})
}
}
// TestProxyCapabilityRulesAlwaysCarryAMessage covers the whole policy surface
// rather than the rows that exist today: a rule that refuses with no message
// renders as a bare "Error: " with exit 1, and an N/A rule describes a command
// that does not have the flag, which is nothing to refuse.
func TestProxyCapabilityRulesAlwaysCarryAMessage(t *testing.T) {
for _, command := range slices.Sorted(maps.Keys(proxyCommandCapabilities)) {
for mode, capabilities := range proxyCommandCapabilities[command] {
for capability, rule := range capabilities {
err := AssertProxyCommandCapability(command, mode, capability)
if proxyCapabilityAllowed(rule.Outcome) {
if err != nil {
t.Errorf("%s/%s/%s outcome=%s asserted %v, want nil", command, mode, capability, rule.Outcome, err)
}
continue
}
if err == nil {
t.Errorf("%s/%s/%s outcome=%s asserted nil, want a refusal", command, mode, capability, rule.Outcome)
continue
}
if err.Error() == "" {
t.Errorf("%s/%s/%s refused with an empty message", command, mode, capability)
}
}
}
}
// A rule with neither a code nor a message must still say something.
if got := proxyCapabilityRuleError(proxyCapabilityRule{Outcome: ProxyOutcomeRefused}, ProxyCapMaxRows, ProxyModeProxied); got == nil || got.Error() == "" {
t.Errorf("message-less refusal rendered as %v, want a non-empty error", got)
}
// The mirror hole on the same path: the allow branch above returns nil,
// and the front door wraps that return value, so a rule added as a bare
// `return HandleProxyCapabilityError(AssertProxy...(...))` must not turn
// an allowed capability into "Error: <nil>" with exit 1.
if got := HandleProxyCapabilityError(nil); got != nil {
t.Errorf("HandleProxyCapabilityError(nil) = %v, want nil", got)
}
}
// TestListRepoRowMatchesShippedBehavior pins the row against the runtime
// refusal it is supposed to describe. The table documents itself as the
// deterministic audit source of truth, so a row that disagrees with the
// command is worse than an absent one.
func TestListRepoRowMatchesShippedBehavior(t *testing.T) {
err := AssertProxyCommandCapability("list", ProxyModeProxied, ProxyCapRepo)
if err == nil {
t.Fatal("list --repo asserted nil; bd list --repo is refused under --proxied-server")
}
if got, want := err.Error(), "--repo is not supported with --proxied-server"; got != want {
t.Fatalf("list --repo refusal = %q, want %q", got, want)
}
}
// TestListRepoProxiedRefusalIsStrictJSON pins the refusal's SHAPE, where the
// test above pins only its text. `bd list --repo` is the one --repo refusal
// the pre-provider gate does not shadow (it covers `create` only), so this
// call site is where the contract is actually observed — and a message-only
// assertion is exactly what let the site go untyped while the row still
// promised a code. A wrapper parsing --json must get the stable code and the
// mutates flag on stdout, and the error must still carry exit 1.
func TestListRepoProxiedRefusalIsStrictJSON(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "list"}
root.AddCommand(cmd)
var gotErr error
out := captureStdout(t, func() error {
gotErr = runListProxiedServer(cmd, context.Background(), io.Discard, listInput{repoOverrideSet: true})
return nil
})
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("list --repo refusal exit = %v (typed=%v), want 1", code, ok)
}
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("list --repo refusal is not JSON on stdout: %q (%v)", out, err)
}
if got["code"] != "proxy.repo.unsupported" {
t.Fatalf("list --repo refusal code = %v, want proxy.repo.unsupported (out=%q)", got["code"], out)
}
if got["error"] != "--repo is not supported with --proxied-server" {
t.Fatalf("list --repo refusal error = %v", got["error"])
}
if got["mutates"] != false {
t.Fatalf("list --repo refusal mutates = %v, want false", got["mutates"])
}
}
// TestReadyClaimResolvesRowCapOnceBeforeProvider pins the malformed-value
// advisory to one line. The command body resolves the cap again for itself, so
// a front door that also warned would print one typo twice.
func TestReadyClaimResolvesRowCapOnceBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
t.Setenv(maxRowsEnvVar, "bogus")
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
var err error
stderr := captureStderr(t, func() { err = validateProxyCapabilitiesBeforeProvider(cmd) })
if err != nil {
t.Fatalf("malformed %s refused the claim: %v", maxRowsEnvVar, err)
}
if strings.Contains(stderr, "is not a non-negative integer") {
t.Fatalf("front door warned about %s; the command body is the one that warns (stderr=%q)", maxRowsEnvVar, stderr)
}
}
func TestProxyCapabilityRowsCoverTopologies(t *testing.T) {
for _, topology := range []ProxyTopology{ProxyTopologyManagedLocal, ProxyTopologyExternalTCP, ProxyTopologyExternalUnix} {
for _, arg := range []string{"--readonly", "--max-rows", "--watch", "--repo"} {
@ -220,15 +482,30 @@ func TestProxyMaintenanceRefusalLeavesFilesUntouched(t *testing.T) {
}
}
// newWatchShowCommand builds `bd show --watch`. The root matters: the front
// door keys on a command's path below its root, so a parentless command has no
// path and matches no rule — which is how a test tree can report success for a
// refusal that never fired.
func newWatchShowCommand(t *testing.T) *cobra.Command {
t.Helper()
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "show"}
cmd.Flags().Bool("watch", false, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("watch", "true"); err != nil {
t.Fatal(err)
}
if got := commandRegistryPath(cmd); got != "show" {
t.Fatalf("test command path = %q, want %q", got, "show")
}
return cmd
}
func TestProxyCapabilityRefusalFrontDoorTextBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = false
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := &cobra.Command{Use: "show"}
cmd.Flags().Bool("watch", false, "")
if err := cmd.Flags().Set("watch", "true"); err != nil {
t.Fatal(err)
}
cmd := newWatchShowCommand(t)
got := captureStderr(t, func() { _ = validateProxyCapabilitiesBeforeProvider(cmd) })
if !strings.Contains(got, "watch mode not supported in proxied-server mode") {
t.Fatalf("text refusal = %q", got)
@ -239,9 +516,7 @@ func TestProxyCapabilityRefusalFrontDoorJSONIncludesCode(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
cmd := &cobra.Command{Use: "show"}
cmd.Flags().Bool("watch", false, "")
_ = cmd.Flags().Set("watch", "true")
cmd := newWatchShowCommand(t)
out := captureStdout(t, func() error {
_ = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
@ -251,22 +526,6 @@ func TestProxyCapabilityRefusalFrontDoorJSONIncludesCode(t *testing.T) {
}
}
func TestProxyCapabilityRefusalDoesNotNeedProvider(t *testing.T) {
oldProvider := uowProvider
uowProvider = nil
t.Cleanup(func() { uowProvider = oldProvider })
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
out := captureStdout(t, func() error {
_ = runCreateProxiedServer(nil, t.Context(), createInput{repoOverrideSet: true})
return nil
})
if !strings.Contains(out, `"code": "proxy.repo.unsupported"`) {
t.Fatalf("refusal = %q", out)
}
}
func TestProxyCapabilityDirectEscapeHatch(t *testing.T) {
for _, cap := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows, ProxyCapWatch, ProxyCapRepo} {
if err := AssertProxyCapability(ProxyModeDirect, cap); err != nil {
@ -274,3 +533,105 @@ func TestProxyCapabilityDirectEscapeHatch(t *testing.T) {
}
}
}
func TestReadyClaimValidatesMaxRowsBeforeProvider(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
if err := cmd.Flags().Set("max-rows", "-1"); err != nil {
t.Fatal(err)
}
var gotErr error
out := captureStdout(t, func() error {
gotErr = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("ready claim invalid max-rows exit = %v, want 1", code)
}
if !strings.Contains(out, "--max-rows must be non-negative") {
t.Fatalf("ready claim invalid max-rows refusal = %q", out)
}
}
// TestReadyPositiveCapRefusedTypedWithAndWithoutClaim pins one refusal to one
// shape. --claim does not exempt a positive row cap: the proxied ready role
// cannot enforce one on either arm, and ready.go refuses both (see its comment
// above rejectMaxRowsUnderProxiedServer). Exempting the claim at the front door
// would not let it through — it would only downgrade the same refusal to an
// untyped one raised after the provider opened, so `bd ready --max-rows 5` and
// `bd ready --claim --max-rows 5` would answer --json in two different shapes,
// selected by a flag that has nothing to do with the cap.
func TestReadyPositiveCapRefusedTypedWithAndWithoutClaim(t *testing.T) {
const wantCode = "proxy.max_rows.unsupported"
const wantMessage = "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode"
assertTypedRefusal := func(t *testing.T, gotErr error, out string) {
t.Helper()
if code, ok := exitCodeFromError(gotErr); !ok || code != 1 {
t.Fatalf("refusal exit = %v (typed=%v), want 1", code, ok)
}
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("refusal is not JSON on stdout: %q (%v)", out, err)
}
if got["code"] != wantCode || got["error"] != wantMessage || got["mutates"] != false {
t.Fatalf("refusal = %q, want code=%q error=%q mutates=false", out, wantCode, wantMessage)
}
}
for _, tc := range []struct {
name string
claim bool
}{{name: "bulk"}, {name: "claim", claim: true}} {
t.Run(tc.name, func(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
root := &cobra.Command{Use: "bd"}
cmd := &cobra.Command{Use: "ready"}
cmd.Flags().Bool("claim", false, "")
cmd.Flags().Int("max-rows", 0, "")
root.AddCommand(cmd)
if err := cmd.Flags().Set("max-rows", "5"); err != nil {
t.Fatal(err)
}
if tc.claim {
if err := cmd.Flags().Set("claim", "true"); err != nil {
t.Fatal(err)
}
}
var gotErr error
out := captureStdout(t, func() error {
gotErr = validateProxyCapabilitiesBeforeProvider(cmd)
return nil
})
assertTypedRefusal(t, gotErr, out)
})
}
// The command body refuses the same cap behind the front door. It renders
// identically so the contract survives on whichever path reaches it first.
t.Run("backstop", func(t *testing.T) {
oldJSON := jsonOutput
jsonOutput = true
t.Cleanup(func() { jsonOutput = oldJSON })
var gotErr error
out := captureStdout(t, func() error {
gotErr = rejectResolvedMaxRowsUnderProxiedServer(5)
return nil
})
assertTypedRefusal(t, gotErr, out)
})
}

View file

@ -61,7 +61,9 @@ This is useful for agents executing molecules to see which steps can run next.`,
if usesProxiedServer() {
// The proxied ready role cannot enforce a row cap, including on
// --claim. Refuse any positive cap rather than silently dropping
// this safety limit; malformed values remain usage errors.
// this safety limit; malformed values remain usage errors. The
// pre-provider front door refuses the same cap first, so this is
// its backstop — both raise proxy.max_rows.unsupported.
if err := rejectMaxRowsUnderProxiedServer(cmd); err != nil {
return err
}

View file

@ -28,10 +28,12 @@ func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error {
return HandleError("--offset must be >= 0")
}
// No cap resolver: the RunE that routed here has already resolved
// --max-rows / BEADS_MAX_ROWS, either to reject a live one or to validate
// the value it then ignores for --claim. Resolving it again would repeat
// the malformed-value warning and stamp a cap this route cannot enforce.
// No cap resolver: --max-rows / BEADS_MAX_ROWS has already been resolved
// twice before this route runs — once at the proxied front door and once
// in the RunE that routed here — and any positive cap was refused by both,
// on --claim as much as on a bulk read. Resolving it a third time would
// repeat the malformed-value warning and stamp a cap this route cannot
// enforce.
in, err := gatherReadyInput(cmd, nil)
if err != nil {
return err

View file

@ -95,6 +95,9 @@ func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string
in := gatherShowProxiedInput(cmd, args)
if in.watchMode {
// Defense in depth, like create's --repo fallback: the pre-provider
// gate refuses `show --watch` first. Typed so all three refusals render
// identically if one ever becomes reachable.
return HandleProxyCapabilityError(AssertProxyCommandCapability("show", ProxyModeProxied, ProxyCapWatch))
}