From 7ccb961f778367fc19ca686c2e9a28d5e161bce1 Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Tue, 22 Sep 2026 15:12:46 -0700 Subject: [PATCH] refactor(proxy): one capability registry with a reason on every refusal (proxied-parity S2) (#6582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(proxy): one capability registry, with a reason on every refusal Proxied-server policy lived in three path tables (a maintenance refusal map, a history classification map, a transform row list), each with its own lookup and its own front-door validator, plus a flag matrix. Nothing forced a new command to appear in any of them, so an unclassified command sailed past the gate and died in the store factory with `proxy server store should be uow provider`. That — not the table count — was the root problem. One table now (cmd/bd/capability_registry.go), and a test that fails when a runnable command is missing from it. Adding a command is no longer a place where policy can be forgotten: it is a build failure until someone decides whether the proxied front door lets it through. Every refusal carries a Reason: `design` where refusing is correct and expected to stay (shared history, multi-repo routing, destructive admin, storage-format surgery, strict --readonly), `unimplemented` where it is a gap with a named owner. The reason renders in the refusal JSON, additive to the frozen {code, error, mutates} contract, and is omitted on refusals that report a runtime state rather than a policy so a consumer keying on its presence is never told "" by mistake. The registry also inventories the 57 untyped refusals commands raise from their own RunE. Those rows are not enforced — converting them changes observable output and belongs to the slice that owns each family — but a source scan now keeps the inventory honest in both directions. The store-factory backstop is typed as `proxy.store.unrouted`, the unreachable duplicate readonly refusal in main.go is gone (the proxied branch above it already returns for the only config that reaches it), and with it `backendSupportsStrictReadonly`, which had no other caller. No outcome changes. Every code, message and exit status is identical, which #6576's five-topology matrix proves: 90/90 cells unchanged (HONORED 47, REFUSED_TYPED 24 = 4 design + 20 unimplemented, ERROR 12, WRONG_ANSWER 4, DEGRADED 3), all five topologies exercised, no skips. Co-Authored-By: Claude Fable 5 * refactor(proxy): `migrate hooks` is an unimplemented refusal, not a design one The registry filed `migrate hooks` under "storage-format and workspace surgery against a store other clients may be holding open". That rationale does not describe it: migrate_hooks.go plans and applies GIT HOOK FILE migration through doctor.PlanHookMigration, on the local filesystem, and opens no store at all. Left as it was, proxied-local — the default topology since 1.3.0 — loses the command permanently, because `design` tells every later slice the refusal is semantic and settled. It is not settled, but it is also not free to lift, and the difference is structural rather than semantic. `migrate hooks` appears on none of main.go's store-init skip lists, so permitting it makes the root pre-run open the proxied provider before RunE runs. Measured with the row flipped to permitted, not reasoned about: on a managed-local workspace `bd migrate hooks --dry-run` started the proxy AND its dolt child — both pidfiles present — to print a hook plan for five missing hooks, and on a workspace with an unreadable sidecar it exited 1 with "failed to open uow provider: corrupt proxied-server sidecar ..." where it had cleanly refused before. Trading a typed refusal for a provider-open error is not a lift. So: Reason=unimplemented with a Tracking item that names the actual work — put the command on the store-init skip list first, then permit it — which is S7's, not this slice's. No outcome changes; the row still refuses with the same code, message and exit status. The registry header now says that permitting a path costs a provider open, since that is the fact this row turns on and the one the completeness test cannot see. Also leaves S7 an explicit instruction on the rows next door. `migrate issues`, `migrate-personal` and `admin cleanup`/`admin reset` claim `design` on a topology-blind rationale — "a store other clients may be holding open", "destructive against a possibly-shared store" — that describes external and team-server workspaces and does not describe managed-local, which is 1:1 and bd-owned. They are not reclassified here: the table cannot yet express "refused, except on managed-local", and narrowing them is semantic work nobody has done. The comments now say that is why, so the next reader does not mistake conservatism for a considered verdict. Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Claude Fable 5 --- CHANGELOG.md | 13 + cmd/bd/capability_registry.go | 569 ++++++++++++++++++ ...go => capability_registry_history_test.go} | 12 +- cmd/bd/capability_registry_test.go | 399 ++++++++++++ ... => capability_registry_transform_test.go} | 27 +- cmd/bd/errors.go | 8 + cmd/bd/history_capability.go | 28 - cmd/bd/main.go | 21 +- cmd/bd/migrate_dolt_mode.go | 5 + cmd/bd/proxy_capability.go | 183 +++--- cmd/bd/proxy_capability_test.go | 14 +- cmd/bd/readonly_policy_test.go | 20 - cmd/bd/serve.go | 2 +- cmd/bd/store_factory.go | 21 +- cmd/bd/store_factory_nocgo.go | 21 +- cmd/bd/transform_capability.go | 90 --- 16 files changed, 1104 insertions(+), 329 deletions(-) create mode 100644 cmd/bd/capability_registry.go rename cmd/bd/{history_capability_test.go => capability_registry_history_test.go} (92%) create mode 100644 cmd/bd/capability_registry_test.go rename cmd/bd/{transform_capability_test.go => capability_registry_transform_test.go} (88%) delete mode 100644 cmd/bd/history_capability.go delete mode 100644 cmd/bd/transform_capability.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 088d49534..62433ec4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,6 +112,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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 + (`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 + should be uow provider`. + - **`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 diff --git a/cmd/bd/capability_registry.go b/cmd/bd/capability_registry.go new file mode 100644 index 000000000..276650bbe --- /dev/null +++ b/cmd/bd/capability_registry.go @@ -0,0 +1,569 @@ +package main + +import ( + "sort" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// The proxied-server capability registry: one table for every command path. +// +// Before this file the policy lived in three separate tables — a maintenance +// refusal map, a history classification map, and a transform row list — each +// with its own lookup and its own front-door validator. Nothing forced a new +// command to appear in any of them, so an unclassified command sailed past the +// gate and died deep in the store factory with an untyped error. The fix is not +// a fourth table: it is one table plus a test that fails when a command is +// missing from it (TestProxyCapabilityRegistryCoversCommandTree). +// +// WHAT A ROW MEANS. Outcome describes what the PRE-PROVIDER GATE does with the +// path on a proxied-server workspace, nothing more: +// +// ProxyOutcomeRefused the gate refuses with a typed ProxyCapabilityError +// before any workspace side effect +// ProxyOutcomeRefusedInRunE the gate lets the path through and the command +// refuses inside its own RunE with an untyped +// string; recorded here so the untyped surface is +// inventoried rather than invisible. Not enforced. +// ProxyOutcomeHonored the gate lets the path through. It does NOT +// promise a proxied route exists: a permitted +// command with no route still fails at the store +// factory with proxy.store.unrouted. +// +// Permitting a path also COSTS something, and the cost is invisible from this +// table: unless the command is on one of main.go's store-init skip lists, the +// root pre-run opens the proxied provider before RunE runs — which starts the +// proxy and its dolt child, creates the database and migrates the schema. For a +// command that genuinely uses the store that is the point. For a store-free one +// it is pure side effect, and on a workspace whose topology cannot be resolved +// it turns a clean typed refusal into a provider-open error. So "this command +// touches no store" is an argument for permitting it only once the command is +// also off the store-init path; see the `migrate hooks` row. Nothing here +// asserts that, and TestProxyCapabilityRegistryCoversCommandTree cannot see it. +// +// REASON is the load-bearing field. "design" means refusing is correct and is +// expected to stay that way — the semantics are undefined or unsafe against a +// backend that may be shared. "unimplemented" means the refusal is a capability +// gap with a named slice that closes it, and Tracking says which. Every later +// slice measures itself by turning "unimplemented" rows into honored ones; the +// count of remaining "unimplemented" rows is the completion signal for the whole +// proxied-parity effort. Assign the field row by row, from the command's actual +// semantics — a bulk assignment would destroy the only information it carries. +// +// The reason also renders in the refusal JSON, additive to the frozen +// {code, error, mutates} contract (see buildJSONCapabilityError). Codes are +// frozen; messages are informative-only. + +// ProxyRefusalReason distinguishes a deliberate policy refusal from a +// not-yet-built one. +type ProxyRefusalReason string + +const ( + // ProxyReasonDesign: the command is refused on purpose and is expected to + // stay refused. Lifting it would need a semantic decision, not plumbing. + ProxyReasonDesign ProxyRefusalReason = "design" + // ProxyReasonUnimplemented: the command could work over the proxied + // provider; nobody has routed it yet. Tracking names the work item. + ProxyReasonUnimplemented ProxyRefusalReason = "unimplemented" +) + +// Tracking values name the plan-of-record work item for an unimplemented +// refusal. These are the slices of the proxied-parity plan; a row gets a GitHub +// issue or bead ID instead once one is filed for it. +const ( + trackBackup = "proxied-parity S3 (backup/restore family)" + trackVersionCtl = "proxied-parity S4 (dolt commit/push/pull/remote)" + trackSync = "proxied-parity S5 (bd sync)" + trackDegradation = "proxied-parity S6 (doctor, config show, degradations)" + trackLongTail = "proxied-parity S7 (long-tail policy pass)" +) + +// capabilityRow is one command-path policy row. ArgSet is the sorted set of +// execution-altering flags that were set (for example "--auto-merge --dry-run"), +// empty for the bare path; a row keyed on an ArgSet wins over the bare row, which +// is how `duplicates --auto-merge --dry-run` stays honored while +// `duplicates --auto-merge` is refused. +type capabilityRow struct { + Path string + ArgSet string + Rule proxyCapabilityRule + History HistoryCapabilityClass + Note string +} + +// display renders the row's key the way its refusal message names it. +func (r capabilityRow) display() string { + if r.ArgSet == "" { + return r.Path + } + return r.Path + " " + r.ArgSet +} + +func (r capabilityRow) withHistory(class HistoryCapabilityClass) capabilityRow { + r.History = class + return r +} + +// asParentGroup marks a row whose path is a command GROUP. Cobra answers a +// non-runnable parent with its help text before PersistentPreRunE, so the gate +// never sees it; the row is kept because it is the parent every child row +// inherits its code from, and because a parent that later gains a Run must not +// silently become permitted. +func (r capabilityRow) asParentGroup() capabilityRow { + r.Note = "parent group: cobra shows help instead of reaching the gate" + return r +} + +func (r capabilityRow) withMessage(message string) capabilityRow { + r.Rule.Message = message + return r +} + +// refusedPath builds a typed front-door refusal for a bare command path. +func refusedPath(path, code string, reason ProxyRefusalReason, tracking string) capabilityRow { + return refusedArgs(path, "", code, reason, tracking) +} + +// refusedArgs builds a typed front-door refusal keyed on a flag set. +func refusedArgs(path, argSet, code string, reason ProxyRefusalReason, tracking string) capabilityRow { + row := capabilityRow{Path: path, ArgSet: argSet} + row.Rule = proxyCapabilityRule{ + Outcome: ProxyOutcomeRefused, + Code: code, + Message: row.display() + " is not supported in proxied-server mode", + ExitCode: 1, + Reason: reason, + Tracking: tracking, + } + return row +} + +// refusedInRunE records a command that the gate permits and that then refuses +// itself with an untyped string from RunE. The row carries no message: the +// string lives in the command, and duplicating it here would rot. The scan in +// TestProxyCapabilityRegistryCoversInlineRefusals keeps the two in step. +// +// The reason is always "unimplemented" and the owner is always the long-tail +// slice, because an untyped string inside RunE is not a considered policy +// statement: a refusal decided on purpose belongs in the gate, typed, where a +// consumer can read it. Anything here is a family nobody has routed yet. +func refusedInRunE(path, site string) capabilityRow { + return capabilityRow{ + Path: path, + Rule: proxyCapabilityRule{ + Outcome: ProxyOutcomeRefusedInRunE, ExitCode: 1, + Reason: ProxyReasonUnimplemented, Tracking: trackLongTail, + }, + Note: "untyped refusal in " + site, + } +} + +// permitted records that the gate lets a path through. See the header: this is +// a statement about the gate, not a promise that a proxied route exists. +func permitted(path string) capabilityRow { + return capabilityRow{Path: path, Rule: proxyCapabilityRule{Outcome: ProxyOutcomeHonored}} +} + +// proxyCapabilityRegistry is the whole path-keyed policy. Rows for permitted +// paths are appended from proxyPermittedPaths by init. +var proxyCapabilityRegistry = []capabilityRow{ + // --- doctor ------------------------------------------------------------- + // Diagnosis needs no version-control surface; the checks simply have no + // proxied dual yet. S6 splits them into client-local and store-backed. + refusedPath("doctor", "proxy.doctor.unsupported", ProxyReasonUnimplemented, trackDegradation), + + // --- backup / restore --------------------------------------------------- + // CALL DOLT_BACKUP(...) is pure SQL over a connection proxied mode already + // owns, so this family is plumbing, not policy. Locality policy (file:// + // URLs naming the server's filesystem on external topologies) is decided + // per topology when S3 lands. + refusedPath("backup", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup). + asParentGroup(), + refusedPath("backup init", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup), + refusedPath("backup sync", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup), + refusedPath("backup remove", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup), + refusedPath("backup status", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup), + refusedPath("backup restore", "proxy.backup.unsupported", ProxyReasonUnimplemented, trackBackup), + + // --- version control over a shared history ------------------------------ + // Refused by design: these mutate or traverse a history that several + // clients share through one connection, and the per-client semantics + // (whose working set? whose branch head?) are undefined. `diff` is the one + // plausible 1.4 candidate, via the dolt_diff system tables. + refusedPath("branch", "proxy.branch.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly), + refusedPath("diff", "proxy.diff.unsupported", ProxyReasonDesign, "1.4 candidate: dolt_diff system tables"), + refusedPath("flatten", "proxy.flatten.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly), + refusedPath("conflicts", "proxy.conflicts.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly). + asParentGroup(), + refusedPath("conflicts list", "proxy.conflicts.unsupported", ProxyReasonDesign, ""), + refusedPath("conflicts show", "proxy.conflicts.unsupported", ProxyReasonDesign, ""), + refusedPath("conflicts resolve", "proxy.conflicts.unsupported", ProxyReasonDesign, ""), + refusedPath("vc", "proxy.vc.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly). + asParentGroup(), + refusedPath("vc merge", "proxy.vc.unsupported", ProxyReasonDesign, ""), + refusedPath("vc commit", "proxy.vc.unsupported", ProxyReasonDesign, ""), + refusedPath("vc status", "proxy.vc.unsupported", ProxyReasonDesign, ""), + refusedPath("federation", "proxy.federation.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly). + asParentGroup(), + refusedPath("federation sync", "proxy.federation.unsupported", ProxyReasonDesign, ""), + refusedPath("federation status", "proxy.federation.unsupported", ProxyReasonDesign, ""), + refusedPath("federation add-peer", "proxy.federation.unsupported", ProxyReasonDesign, ""), + refusedPath("federation remove-peer", "proxy.federation.unsupported", ProxyReasonDesign, ""), + refusedPath("federation list-peers", "proxy.federation.unsupported", ProxyReasonDesign, ""), + + // --- multi-repo routing ------------------------------------------------- + // Routing to another workspace bypasses the proxied root entirely, which is + // the same reason --repo is N/A mode-wide. + refusedPath("repo", "proxy.repo.unsupported", ProxyReasonDesign, ""). + withHistory(HistoryDirectOnly). + asParentGroup(), + refusedPath("repo add", "proxy.repo.unsupported", ProxyReasonDesign, ""), + refusedPath("repo remove", "proxy.repo.unsupported", ProxyReasonDesign, ""), + refusedPath("repo list", "proxy.repo.unsupported", ProxyReasonDesign, ""), + refusedPath("repo sync", "proxy.repo.unsupported", ProxyReasonDesign, ""), + + // --- dolt version-control verbs ----------------------------------------- + // CALL DOLT_PUSH/DOLT_PULL/DOLT_COMMIT are SQL procedures and the generic + // repository that wraps them is already written; these need a use case and + // a route, not proxy work. `dolt remote remove` is already routed, which is + // the precedent. + refusedPath("dolt commit", "proxy.dolt_commit.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("dolt push", "proxy.dolt_push.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("dolt pull", "proxy.dolt_pull.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("dolt remote", "proxy.dolt_remote.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly). + asParentGroup(), + refusedPath("dolt remote add", "proxy.dolt_remote.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("dolt remote list", "proxy.dolt_remote.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("dolt remote reset-data", "proxy.dolt_remote.unsupported", ProxyReasonUnimplemented, trackVersionCtl). + withHistory(HistoryDirectOnly), + refusedPath("sync", "proxy.sync.unsupported", ProxyReasonUnimplemented, trackSync). + withHistory(HistoryDirectOnly), + + // --- migration and workspace surgery ------------------------------------ + // Storage-format and workspace surgery against a store other clients may be + // holding open. `migrate schema` is the exception and is already routed: + // the provider open runs it under the migration gate. + // + // S7 MUST RE-EXAMINE THE ROWS BELOW PER TOPOLOGY. "A store other clients may + // be holding open" describes external and team-server workspaces; it does + // not describe managed-local, which is 1:1 and bd-owned — bd spawned the + // dolt child itself. A row cannot yet say "refused, except on managed-local" + // (S3's backup locality policy is the slice that adds per-topology rules), + // so the blanket refusal is the only thing this table can express today. + // These rows keep it because nobody has done the semantic work to narrow + // them, not because the work has been done and come out this way. + refusedPath("migrate", "proxy.migrate.unsupported", ProxyReasonDesign, ""), + refusedPath("migrate sync", "proxy.migrate.unsupported", ProxyReasonDesign, ""), + // `migrate hooks` is the one row in this block the surgery rationale never + // described: it plans and applies GIT HOOK FILE migration (migrate_hooks.go + // -> doctor.PlanHookMigration) on the local filesystem and opens no store at + // all. It is refused for a structural reason instead — the command is wired + // into the store-opening path it does not need. It is on none of main.go's + // store-init skip lists, so permitting it makes the root pre-run open the + // proxied provider before RunE ever runs. Measured, not assumed: with this + // row flipped to permitted, `bd migrate hooks --dry-run` on a managed-local + // workspace started the proxy AND its dolt child (both pidfiles present) to + // print a hook plan, and on a workspace with an unreadable sidecar it exited + // 1 with "failed to open uow provider: corrupt proxied-server sidecar ..." + // where it had cleanly refused before. Trading a typed refusal for a + // connection error is not a lift. The honest fix is to take the command off + // the store path first, which is S7's job, not this slice's. + refusedPath("migrate hooks", "proxy.migrate.unsupported", ProxyReasonUnimplemented, + trackLongTail+" (specifically: put `migrate hooks` on main.go's store-init skip list, then permit it)"), + refusedPath("migrate issues", "proxy.migrate.unsupported", ProxyReasonDesign, ""), + refusedPath("migrate-issues", "proxy.migrate.unsupported", ProxyReasonDesign, ""), + refusedPath("migrate-personal", "proxy.migrate.unsupported", ProxyReasonDesign, ""), + + // --- destructive admin -------------------------------------------------- + // Same topology-blind rationale as the migrate block above, and the same + // instruction to S7: "destructive against a possibly-shared store" is a + // claim about external and team-server shapes. On managed-local the store is + // this workspace's alone, and `bd admin reset` there is no more shared than + // it is in embedded mode, where it is honored. Re-examine per topology. + refusedPath("admin cleanup", "proxy.admin.unsupported", ProxyReasonDesign, ""), + refusedPath("admin reset", "proxy.admin.unsupported", ProxyReasonDesign, ""), + // --- issue compaction --------------------------------------------------- + // `bd admin compact` without --dolt is the description-rewriting pass; only + // 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. + refusedPath("admin compact", "proxy.compact.unsupported", ProxyReasonUnimplemented, trackLongTail). + withMessage("only '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 + // snapshot was archived) touches version control. + refusedPath("restore", "proxy.restore.unsupported", ProxyReasonUnimplemented, trackLongTail), + + // --- gates, formulas, swarm, merge slots -------------------------------- + // Ordinary CRUD over a store with no version-control surface. They stay + // refused because nothing downstream has asked for them, which is this + // codebase's standing rule for lifting a refusal — not because the proxied + // topology makes them wrong. + refusedPath("gate discover", "proxy.gate.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("cook", "proxy.formula.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("ship", "proxy.formula.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("swarm create", "proxy.swarm.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("swarm list", "proxy.swarm.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("merge-slot create", "proxy.merge_slot.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("merge-slot check", "proxy.merge_slot.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("merge-slot acquire", "proxy.merge_slot.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("merge-slot release", "proxy.merge_slot.unsupported", ProxyReasonUnimplemented, trackLongTail), + + // --- transforms --------------------------------------------------------- + // ID rewrites walk every reference in the store. They need a routed + // multi-statement transaction, which the UOW can express; nobody has + // written it. The arg-set rows are what let the read-only preview of a + // duplicate merge stay honored while the merge itself is refused. + refusedPath("rename", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("rename-prefix", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("rename-prefix", "--dry-run", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("rename-prefix", "--repair", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("rename-prefix", "--dry-run --repair", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("duplicate", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("duplicate", "--of", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedPath("supersede", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("supersede", "--with", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + refusedArgs("duplicates", "--auto-merge", "proxy.transform.unsupported", ProxyReasonUnimplemented, trackLongTail), + // The dry run reports what the merge WOULD do without writing anything, so + // it rides the read path plain `duplicates` already uses. + {Path: "duplicates", ArgSet: "--auto-merge --dry-run", Rule: proxyCapabilityRule{Outcome: ProxyOutcomeHonored}}, + + // --- routed history ----------------------------------------------------- + // The two paths that already have a proxied route, recorded so the class is + // asserted rather than remembered. + permitted("history").withHistory(HistoryProxySupported), + permitted("dolt remote remove").withHistory(HistoryProxySupported), + + // --- untyped refusals inside RunE --------------------------------------- + // The gate permits these paths and the command refuses itself with a bare + // string, so a JSON consumer gets no code and no mutates flag. They are + // listed to inventory that surface, not to enforce it: converting them to + // typed refusals changes observable output and belongs to the slice that + // owns each family. Tracker verbs are ordinary store reads plus a network + // call; nothing about the proxied topology makes them wrong. + refusedInRunE("ado status", "ado.go"), + refusedInRunE("ado projects", "ado.go"), + refusedInRunE("ado sync", "ado.go"), + refusedInRunE("github status", "github.go"), + refusedInRunE("github repos", "github.go"), + refusedInRunE("github sync", "github.go"), + refusedInRunE("gitlab status", "gitlab.go"), + refusedInRunE("gitlab projects", "gitlab.go"), + refusedInRunE("gitlab sync", "gitlab.go"), + refusedInRunE("notion status", "notion.go"), + refusedInRunE("notion init", "notion.go"), + refusedInRunE("notion connect", "notion.go"), + refusedInRunE("notion sync", "notion.go"), + refusedInRunE("create-form", "create_form.go"), +} + +// proxyPermittedPaths lists every command path the proxied front door lets +// through. It exists so that a command added without a policy decision fails +// TestProxyCapabilityRegistryCoversCommandTree instead of shipping — the whole +// point of the registry. Being listed here says the GATE permits the path; a +// permitted command with no proxied route still fails at the store factory with +// proxy.store.unrouted. +var proxyPermittedPaths = []string{ + // issue CRUD and queries + "assign", "batch", "blocked", "children", "close", "comment", "count", "create", + "defer", "delete", "duplicates", "edit", "export", "find-duplicates", "forget", + "gc", "graph", "graph check", "heartbeat", "import", "info", "lint", "link", + "list", "note", "orphans", "priority", "promote", "prune", "purge", "q", "query", + "ready", "recompute-blocked", "reclaim", "reopen", "search", "set-state", "show", + "stale", "status", "statuses", "tag", "types", "unclaim", "undefer", "update", + + // comments, dependencies, labels, key-value + "comments", "comments add", "comments list", + "dep", "dep add", "dep cycles", "dep list", "dep relate", "dep remove", "dep tree", "dep unrelate", + "kv clear", "kv get", "kv list", "kv set", + "label add", "label list", "label list-all", "label propagate", "label remove", + + // molecules, epics, todos, state + "epic close-eligible", "epic status", + "mol bond", "mol burn", "mol current", "mol distill", "mol last-activity", "mol pour", + "mol progress", "mol ready", "mol seed", "mol show", "mol squash", "mol stale", + "mol wisp", "mol wisp create", "mol wisp gc", "mol wisp list", + "state", "state list", "todo", "todo add", "todo done", "todo list", + + // gates, rules, provenance, audit, upgrade review + "audit label", "audit record", + "gate add-waiter", "gate check", "gate create", "gate list", "gate resolve", "gate show", + "provenance by-ref", "provenance log", "provenance record", + "rules audit", "rules compact", + "upgrade ack", "upgrade review", "upgrade status", + + // workspace lifecycle and configuration + "bootstrap", "config apply", "config drift", "config get", "config list", "config set", + "config set-many", "config show", "config unset", "config validate", "context", + "init", "init-safety", "onboard", "preflight", "quickstart", "schema", "setup", "where", + "version", "worktree create", "worktree info", "worktree list", "worktree remove", + + // storage, history and migration paths that are already routed or store-free + "compact", "events export", "events prune", "events tail", + "dolt clean-databases", "dolt killall", "dolt set", "dolt show", "dolt status", + "dolt start", "dolt stop", "dolt test", + "migrate from-proxied-server-to-server", "migrate from-proxied-server-to-shared-server", + "migrate from-server-to-proxied-server", "migrate from-shared-server-to-proxied-server", + "migrate legacy-sqlite", "migrate schema", + + // formulas (parser-only), agent memory, swarm reads + "formula convert", "formula list", "formula schema", "formula show", + "mail", "memories", "ping", "prime", "recall", "remember", + "swarm status", "swarm validate", + + // human-in-the-loop queue + "human", "human dismiss", "human list", "human respond", "human stats", + + // trackers: the verbs with no proxied refusal of any kind + "ado pull", "ado push", "github pull", "github push", "gitlab pull", "gitlab push", + "jira pull", "jira push", "jira status", "jira sync", + "linear pull", "linear push", "linear status", "linear sync", "linear teams", + "notion pull", "notion push", + + // hooks, metrics, serving and internal entry points + "hooks install", "hooks list", "hooks run", "hooks uninstall", + "metrics", "metrics example", "metrics off", "metrics on", + "serve", "sql", + "codex-hook", "cursor-hook", "db-proxy-child", "send-metrics", +} + +func init() { + for _, path := range proxyPermittedPaths { + proxyCapabilityRegistry = append(proxyCapabilityRegistry, permitted(path)) + } + proxyCapabilityIndex = make(map[string]capabilityRow, len(proxyCapabilityRegistry)) + for _, row := range proxyCapabilityRegistry { + proxyCapabilityIndex[capabilityKey(row.Path, row.ArgSet)] = row + } +} + +// proxyCapabilityIndex is proxyCapabilityRegistry keyed for lookup. Duplicate +// keys are rejected by TestProxyCapabilityRegistryHasNoDuplicateRows rather +// than by a panic here: a typo must fail the build, not every bd invocation. +var proxyCapabilityIndex map[string]capabilityRow + +func capabilityKey(path, argSet string) string { return path + "\x00" + argSet } + +// LookupCapabilityRow returns the row for an exact path/arg-set key. +func LookupCapabilityRow(path, argSet string) (capabilityRow, bool) { + row, ok := proxyCapabilityIndex[capabilityKey(path, argSet)] + return row, ok +} + +// capabilityRowFor resolves a command to its row, preferring the row keyed on +// the flags the invocation actually set over the bare path. +// +// The fallback to the bare row is what lets one table serve both halves of the +// old policy: a path row refuses whatever flags were passed unless a more +// specific row says otherwise, so `backup sync --dry-run` is still refused by +// the `backup sync` row. The predecessor of the arg-set half matched exactly or +// not at all, which meant an unlisted flag combination on a refused path +// slipped through; no such combination exists among the commands that carry +// these flags, so nothing changes today, and the fallback is why none can +// appear later. +func capabilityRowFor(cmd *cobra.Command) (capabilityRow, bool) { + path := commandRegistryPath(cmd) + if argSet := commandPolicyArgSet(cmd); argSet != "" { + if row, ok := LookupCapabilityRow(path, argSet); ok { + return row, true + } + } + return LookupCapabilityRow(path, "") +} + +// commandRegistryPath is the registry key for a command: its full path with the +// root name removed, for example "dolt remote add". +func commandRegistryPath(cmd *cobra.Command) string { + return strings.TrimSpace(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name())) +} + +// proxyPolicyArgFlags are the flags that take part in a capability key. Only +// flags that alter a command's execution belong here: output, tracing and other +// inherited root flags must never bypass a refusal by changing the key. +var proxyPolicyArgFlags = map[string]bool{ + "auto-merge": true, "dry-run": true, "repair": true, "of": true, "with": true, +} + +// commandPolicyArgSet renders the set flags that take part in the key, sorted so +// the key does not depend on the order the user typed them. +func commandPolicyArgSet(cmd *cobra.Command) string { + var args []string + cmd.Flags().Visit(func(f *pflag.Flag) { + if proxyPolicyArgFlags[f.Name] { + args = append(args, "--"+f.Name) + } + }) + sort.Strings(args) + return strings.Join(args, " ") +} + +// validateProxyRegistryBeforeProvider is the path-keyed half of the proxied +// front door: it rejects direct-only commands before migrations, auto-start or +// provider construction, so a refusal leaves the workspace untouched. The +// flag-keyed half is validateProxyCapabilitiesBeforeProvider. +func validateProxyRegistryBeforeProvider(cmd *cobra.Command) error { + if cmd == nil { + return nil + } + // `compact` is the one rule that a flag VALUE decides rather than a flag's + // presence, so it cannot be expressed as an arg-set row. `bd compact` and + // `bd rules compact` have no --dolt flag at all and are never refused here; + // `bd admin compact --dolt` has a proxied route and falls through to it. + if cmd.Name() == "compact" { + if cmd.Flags().Lookup("dolt") == nil { + return nil + } + if dolt, _ := cmd.Flags().GetBool("dolt"); dolt { + return nil + } + } + row, ok := capabilityRowFor(cmd) + if !ok || row.Rule.Outcome != ProxyOutcomeRefused { + return nil + } + return HandleProxyCapabilityError(proxyCapabilityErrorFor(row.Rule)) +} + +func proxyCapabilityErrorFor(rule proxyCapabilityRule) *ProxyCapabilityError { + return &ProxyCapabilityError{ + Code: rule.Code, + Message: rule.Message, + ExitCode: rule.ExitCode, + Mutates: rule.Mutates, + Reason: rule.Reason, + } +} + +// HistoryCapabilityClass classifies history/version-control commands on the +// proxied topology without coupling them to a particular backend engine. +type HistoryCapabilityClass string + +const ( + HistoryProxySupported HistoryCapabilityClass = "proxy-supported" + HistoryDirectOnly HistoryCapabilityClass = "direct-only" +) + +// LookupHistoryCapability classifies an exact command path. Paths with no +// history classification are intentionally absent so callers cannot +// accidentally advertise support. +func LookupHistoryCapability(commandPath string) (HistoryCapabilityClass, bool) { + row, ok := LookupCapabilityRow(commandPath, "") + if !ok || row.History == "" { + return "", false + } + return row.History, true +} diff --git a/cmd/bd/history_capability_test.go b/cmd/bd/capability_registry_history_test.go similarity index 92% rename from cmd/bd/history_capability_test.go rename to cmd/bd/capability_registry_history_test.go index cc277190d..c0319a73b 100644 --- a/cmd/bd/history_capability_test.go +++ b/cmd/bd/capability_registry_history_test.go @@ -31,7 +31,7 @@ func TestSyncRefusesBeforeProvider(t *testing.T) { root := &cobra.Command{Use: "bd"} cmd := &cobra.Command{Use: "sync"} root.AddCommand(cmd) - err := validateProxyMaintenanceBeforeProvider(cmd) + err := validateProxyRegistryBeforeProvider(cmd) if err == nil { t.Fatalf("sync refusal = %#v", err) } @@ -71,7 +71,7 @@ func TestHistoryDirectOnlyRefusalContract(t *testing.T) { } uowProvider = nil jsonOutput = true - out := captureStdout(t, func() error { _ = validateProxyMaintenanceBeforeProvider(cmd); return nil }) + out := captureStdout(t, func() error { _ = validateProxyRegistryBeforeProvider(cmd); return nil }) var got map[string]any want := expected[path] if err := json.Unmarshal([]byte(out), &got); err != nil || got["code"] != want.code || got["error"] != want.message || got["mutates"] != false { @@ -104,7 +104,7 @@ func TestHistoryNestedFrontDoorsRefuseAndSupportedPathsPass(t *testing.T) { cmd.AddCommand(child) cmd = child } - err := validateProxyMaintenanceBeforeProvider(cmd) + err := validateProxyRegistryBeforeProvider(cmd) if path == "dolt remote remove" { if err != nil { t.Fatalf("supported %s refused: %v", path, err) @@ -118,9 +118,9 @@ func TestHistoryNestedFrontDoorsRefuseAndSupportedPathsPass(t *testing.T) { t.Fatalf("%s exit=%v, want 1", path, err) } var got map[string]any - // validateProxyMaintenanceBeforeProvider renders the typed refusal to + // validateProxyRegistryBeforeProvider renders the typed refusal to // stdout in JSON mode; the command must retain its nested path. - out := captureStdout(t, func() error { _ = validateProxyMaintenanceBeforeProvider(cmd); return nil }) + out := captureStdout(t, func() error { _ = validateProxyRegistryBeforeProvider(cmd); return nil }) if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("%s refusal JSON: %v (%q)", path, err, out) } @@ -132,7 +132,7 @@ func TestHistoryNestedFrontDoorsRefuseAndSupportedPathsPass(t *testing.T) { root := &cobra.Command{Use: "bd"} history := &cobra.Command{Use: "history"} root.AddCommand(history) - if err := validateProxyMaintenanceBeforeProvider(history); err != nil { + if err := validateProxyRegistryBeforeProvider(history); err != nil { t.Fatalf("history --events supported path refused: %v", err) } } diff --git a/cmd/bd/capability_registry_test.go b/cmd/bd/capability_registry_test.go new file mode 100644 index 000000000..f6f7f47c1 --- /dev/null +++ b/cmd/bd/capability_registry_test.go @@ -0,0 +1,399 @@ +package main + +import ( + "errors" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// cobraBuiltinCommands are added to the tree by cobra itself, not by bd, and +// only once something calls Execute — which another test in this package does +// (completions_test.go runs __complete). Without this set the completeness test +// below would pass or fail depending on test ORDER, which is the worst possible +// property for a policy gate. +var cobraBuiltinCommands = map[string]bool{ + "help": true, "completion": true, "__complete": true, "__completeNoDesc": true, +} + +// walkCommandPaths returns every command path in the tree, with the runnable +// ones flagged. Runnable is the property that matters: cobra returns ErrHelp +// for a non-runnable parent before PersistentPreRunE, so a group command never +// reaches the capability gate at all. +func walkCommandPaths(root *cobra.Command) map[string]bool { + paths := map[string]bool{} + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if cobraBuiltinCommands[c.Name()] { + return + } + if path := commandRegistryPath(c); path != "" { + paths[path] = c.Runnable() + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + return paths +} + +// TestProxyCapabilityRegistryCoversCommandTree is the reason this registry +// exists. Every command that can actually run must state what the proxied front +// door does with it. A new command with no row fails here, at build time, rather +// than shipping and dying in the store factory with an untyped error — which is +// how every scattered refusal in this codebase got there. +// +// Adding a row is not a formality: choose the outcome deliberately. +// - the command works over the proxied provider, or never opens a store at +// all => add its path to proxyPermittedPaths +// - the command must not run on a shared/proxied store => add a refusedPath +// row with Reason=design and say why in a comment +// - the command could work but nobody has routed it => add a refusedPath row +// with Reason=unimplemented and a Tracking item +func TestProxyCapabilityRegistryCoversCommandTree(t *testing.T) { + var missing []string + for path, runnable := range walkCommandPaths(rootCmd) { + if !runnable { + continue + } + if _, ok := LookupCapabilityRow(path, ""); !ok { + missing = append(missing, path) + } + } + sort.Strings(missing) + if len(missing) > 0 { + t.Fatalf("%d command(s) have no proxied-server capability row:\n %s\n\n"+ + "Add each to cmd/bd/capability_registry.go: proxyPermittedPaths if the proxied "+ + "front door should let it through, or a refusedPath row with a Reason if it should not.", + len(missing), strings.Join(missing, "\n ")) + } +} + +// TestProxyCapabilityRegistryHasNoStaleRows is the other direction: a row whose +// command no longer exists is policy for nothing, and would hide the renamed +// command's own missing row behind a green test. +func TestProxyCapabilityRegistryHasNoStaleRows(t *testing.T) { + tree := walkCommandPaths(rootCmd) + var stale []string + for _, row := range proxyCapabilityRegistry { + if _, ok := tree[row.Path]; !ok { + stale = append(stale, row.display()) + } + } + sort.Strings(stale) + if len(stale) > 0 { + t.Fatalf("registry rows for commands that do not exist:\n %s", strings.Join(stale, "\n ")) + } +} + +func TestProxyCapabilityRegistryHasNoDuplicateRows(t *testing.T) { + seen := map[string]bool{} + for _, row := range proxyCapabilityRegistry { + key := capabilityKey(row.Path, row.ArgSet) + if seen[key] { + t.Errorf("duplicate registry row for %q: one of them is dead and the lookup silently picks the last", row.display()) + } + seen[key] = true + } +} + +// TestProxyCapabilityRegistryRowInvariants pins the contract every row must +// satisfy. The Reason rules are the load-bearing ones: a refusal with no reason +// is exactly the tribal knowledge this registry replaces, and an unimplemented +// refusal with no tracking item is a gap nobody owns. +func TestProxyCapabilityRegistryRowInvariants(t *testing.T) { + for _, row := range proxyCapabilityRegistry { + switch row.Rule.Outcome { + case ProxyOutcomeRefused: + if row.Rule.Code == "" || row.Rule.Message == "" || row.Rule.ExitCode != 1 { + t.Errorf("%s: refusal must carry a code, a message and exit 1, got %#v", row.display(), row.Rule) + } + if row.Rule.Mutates { + t.Errorf("%s: a refusal never mutates", row.display()) + } + if !strings.HasPrefix(row.Rule.Code, "proxy.") { + t.Errorf("%s: code %q must be in the stable proxy.* namespace", row.display(), row.Rule.Code) + } + case ProxyOutcomeRefusedInRunE: + if row.Rule.Code != "" { + t.Errorf("%s: an untyped RunE refusal has no code; if it has one it belongs in the gate", row.display()) + } + case ProxyOutcomeHonored: + if row.Rule.Reason != "" { + t.Errorf("%s: Reason explains a refusal; an honored row must not carry one", row.display()) + } + default: + t.Errorf("%s: unexpected outcome %q", row.display(), row.Rule.Outcome) + } + + refusal := row.Rule.Outcome == ProxyOutcomeRefused || row.Rule.Outcome == ProxyOutcomeRefusedInRunE + if refusal { + switch row.Rule.Reason { + case ProxyReasonDesign, ProxyReasonUnimplemented: + default: + t.Errorf("%s: refusal must declare Reason design or unimplemented, got %q", row.display(), row.Rule.Reason) + } + if row.Rule.Reason == ProxyReasonUnimplemented && row.Rule.Tracking == "" { + t.Errorf("%s: an unimplemented refusal needs a Tracking item naming who closes it", row.display()) + } + } + if row.History == HistoryDirectOnly && row.Rule.Outcome != ProxyOutcomeRefused { + t.Errorf("%s: classified direct-only but the gate does not refuse it", row.display()) + } + if row.History == HistoryProxySupported && row.Rule.Outcome != ProxyOutcomeHonored { + t.Errorf("%s: classified proxy-supported but the gate refuses it", row.display()) + } + } +} + +// inlineProxiedRefusal matches the untyped refusals commands raise from their +// own RunE, e.g. HandleErrorRespectJSON("gitlab sync is not supported in +// proxied-server mode"). +var inlineProxiedRefusal = regexp.MustCompile(`HandleErrorRespectJSON\("([^"]*proxied-server mode)"\)`) + +// inlineProxiedMessages classifies the messages that do not name their command +// path in the standard " is not supported ..." shape. A path maps the +// message to its registry row; an empty string records a message that mentions +// 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", + // 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": "", +} + +// TestProxyCapabilityRegistryCoversInlineRefusals scans the package for +// refusals raised inside RunE and requires each one to resolve to a registry +// row. Those strings are the untyped half of the refusal surface — no code, no +// mutates flag, nothing a JSON consumer can classify — and before the registry +// they were discoverable only by grep. +// +// The scan runs in both directions on purpose: a new inline refusal must be +// registered, and a ProxyOutcomeRefusedInRunE row whose string has been deleted +// must be flipped to its new outcome by the slice that deleted it. +func TestProxyCapabilityRegistryCoversInlineRefusals(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatalf("read package dir: %v", err) + } + + found := map[string]string{} // registry path -> file it was found in + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + src, err := os.ReadFile(filepath.Clean(name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + for _, match := range inlineProxiedRefusal.FindAllStringSubmatch(string(src), -1) { + message := match[1] + path, ok := inlineRefusalPath(message) + if !ok { + t.Errorf("%s: %q mentions proxied-server mode but does not name a command path; "+ + "add it to inlineProxiedMessages so it can be checked against the registry "+ + "(map it to \"\" if it is not a capability refusal)", name, message) + continue + } + if path == "" { + continue // documented non-refusal + } + found[path] = name + } + } + + for path, file := range found { + argSet := "" + if base, args, split := strings.Cut(path, " --"); split { + argSet = "--" + args + path = base + } + row, ok := LookupCapabilityRow(path, argSet) + if !ok { + t.Errorf("%s refuses %q inside RunE with no registry row; the front door and the command disagree about what bd supports", + file, strings.TrimSpace(path+" "+argSet)) + continue + } + if row.Rule.Outcome == ProxyOutcomeHonored { + t.Errorf("%s refuses %q inside RunE, but the registry says the front door honors it", file, row.display()) + } + } + + for _, row := range proxyCapabilityRegistry { + if row.Rule.Outcome != ProxyOutcomeRefusedInRunE { + continue + } + if _, ok := found[row.Path]; !ok { + t.Errorf("%s is recorded as an untyped RunE refusal but no such refusal exists in the package any more (%s); "+ + "flip the row to its new outcome", row.display(), row.Note) + } + } +} + +func inlineRefusalPath(message string) (string, bool) { + if path, ok := inlineProxiedMessages[message]; ok { + return path, true + } + path, ok := strings.CutSuffix(message, " is not supported in proxied-server mode") + if !ok { + return "", false + } + // conflicts.go says "bd conflicts ..."; the registry keys on the path. + return strings.TrimPrefix(path, "bd "), true +} + +// TestProxyCapabilityRegistryReasonsAreAssignedIndividually guards the one way +// this registry could become useless while staying green: reasons assigned in +// bulk. Every later slice reads these to decide what is left to do, so both +// values have to be genuinely represented, and the design refusals — the claim +// a reviewer will challenge — are listed here by name. +func TestProxyCapabilityRegistryReasonsAreAssignedIndividually(t *testing.T) { + wantDesign := map[string]bool{ + "branch": true, "diff": true, "flatten": true, + "conflicts": true, "conflicts list": true, "conflicts show": true, "conflicts resolve": true, + "vc": true, "vc merge": true, "vc commit": true, "vc status": true, + "federation": true, "federation sync": true, "federation status": true, + "federation add-peer": true, "federation remove-peer": true, "federation list-peers": true, + "repo": true, "repo add": true, "repo remove": true, "repo list": true, "repo sync": true, + // `migrate hooks` is deliberately NOT here: it migrates git hook files + // and opens no store, so the surgery rationale the rest of this block + // rests on does not describe it. Its refusal is structural — the + // command is on none of main.go's store-init skip lists — which makes + // it unimplemented with a tracking item, not design. + "migrate": true, "migrate sync": true, "migrate issues": true, + "migrate-issues": true, "migrate-personal": true, + "admin cleanup": true, "admin reset": true, + } + + gotDesign := map[string]bool{} + unimplemented := 0 + for _, row := range proxyCapabilityRegistry { + switch row.Rule.Reason { + case ProxyReasonDesign: + gotDesign[row.display()] = true + case ProxyReasonUnimplemented: + unimplemented++ + } + } + + for path := range wantDesign { + if !gotDesign[path] { + t.Errorf("%q is no longer refused by design; if that is intended, update this test and say why in the PR", path) + } + } + for path := range gotDesign { + if !wantDesign[path] { + t.Errorf("%q claims Reason=design and is not in the reviewed list; a design refusal is a semantic claim that needs review", path) + } + } + if unimplemented == 0 { + t.Error("no unimplemented refusals left — either the work is done or the reasons were bulk-assigned") + } +} + +// TestProxyCapabilityArgSetFallsBackToBarePath pins the lookup rule that lets +// one table carry both the path policy and the flag policy: a flag combination +// with no row of its own inherits the bare path's verdict rather than escaping +// it. Written against the real command tree so it exercises the flags these +// commands actually declare. +func TestProxyCapabilityArgSetFallsBackToBarePath(t *testing.T) { + for _, tc := range []struct { + path string + flags []string + want ProxyCapabilityOutcome + wantMsg string + }{ + // Covered by an explicit row: the message names the flags. + {"rename-prefix", []string{"dry-run"}, ProxyOutcomeRefused, "rename-prefix --dry-run is not supported in proxied-server mode"}, + // No row for this combination: it inherits the refused bare row rather + // than slipping past the gate. + {"rename-prefix", []string{"dry-run", "auto-merge"}, ProxyOutcomeRefused, "rename-prefix is not supported in proxied-server mode"}, + // Inheriting an honored bare row is equally load-bearing: this is the + // read-only preview and it must keep working. + {"duplicates", []string{"dry-run"}, ProxyOutcomeHonored, ""}, + } { + t.Run(tc.path+" "+strings.Join(tc.flags, " "), func(t *testing.T) { + root := &cobra.Command{Use: "bd"} + cmd := &cobra.Command{Use: tc.path} + root.AddCommand(cmd) + for _, flag := range tc.flags { + cmd.Flags().Bool(flag, false, "") + if err := cmd.Flags().Set(flag, "true"); err != nil { + t.Fatal(err) + } + } + row, ok := capabilityRowFor(cmd) + if !ok { + t.Fatalf("no row resolved for %q with %v", tc.path, tc.flags) + } + if row.Rule.Outcome != tc.want || row.Rule.Message != tc.wantMsg { + t.Fatalf("row = outcome %q message %q, want %q / %q", + row.Rule.Outcome, row.Rule.Message, tc.want, tc.wantMsg) + } + }) + } +} + +// TestProxyRefusalJSONCarriesReason pins the additive half of the JSON +// contract. {code, error, mutates} is frozen and parsed downstream; reason is +// new, and it must appear without disturbing the three fields that were already +// there. +func TestProxyRefusalJSONCarriesReason(t *testing.T) { + t.Setenv("BD_JSON_ENVELOPE", "") + oldJSON := jsonOutput + jsonOutput = true + t.Cleanup(func() { jsonOutput = oldJSON }) + + for _, tc := range []struct { + path, code string + reason ProxyRefusalReason + }{ + {"branch", "proxy.branch.unsupported", ProxyReasonDesign}, + {"sync", "proxy.sync.unsupported", ProxyReasonUnimplemented}, + } { + t.Run(tc.path, func(t *testing.T) { + root := &cobra.Command{Use: "bd"} + cmd := &cobra.Command{Use: tc.path} + root.AddCommand(cmd) + out := captureStdout(t, func() error { + _ = validateProxyRegistryBeforeProvider(cmd) + return nil + }) + for _, want := range []string{ + `"code": "` + tc.code + `"`, + `"error": "` + tc.path + ` is not supported in proxied-server mode"`, + `"mutates": false`, + `"reason": "` + string(tc.reason) + `"`, + } { + if !strings.Contains(out, want) { + t.Fatalf("refusal JSON missing %s:\n%s", want, out) + } + } + }) + } +} + +// TestProxiedStoreUnroutedIsTyped covers the backstop: a permitted command with +// no proxied route used to die with a bare string that no consumer could tell +// from a real store failure. +func TestProxiedStoreUnroutedIsTyped(t *testing.T) { + var typed *ProxyCapabilityError + err := errProxiedStoreUnrouted() + if !errors.As(err, &typed) { + t.Fatalf("store backstop error = %#v, want *ProxyCapabilityError", err) + } + if typed.Code != "proxy.store.unrouted" || typed.ExitCode != 1 || typed.Mutates { + t.Fatalf("store backstop = %#v", typed) + } + if typed.Reason != ProxyReasonUnimplemented { + t.Fatalf("store backstop reason = %q, want unimplemented", typed.Reason) + } +} diff --git a/cmd/bd/transform_capability_test.go b/cmd/bd/capability_registry_transform_test.go similarity index 88% rename from cmd/bd/transform_capability_test.go rename to cmd/bd/capability_registry_transform_test.go index 913b4d39f..86ed302b4 100644 --- a/cmd/bd/transform_capability_test.go +++ b/cmd/bd/capability_registry_transform_test.go @@ -58,24 +58,25 @@ func TestProxyTransformCapabilityRows(t *testing.T) { } } } - row, ok := lookupTransformCapability(cmd) + row, ok := capabilityRowFor(cmd) if !ok { t.Fatalf("lookup(%q, %q) missing row", tc.path, tc.argument) } - if row.Path != tc.path || row.Argument != tc.argument || row.Outcome != tc.outcome { + if row.Path != tc.path || row.ArgSet != tc.argument || row.Rule.Outcome != tc.outcome { t.Fatalf("row = %#v, want path=%q argument=%q outcome=%q", row, tc.path, tc.argument, tc.outcome) } if tc.outcome == ProxyOutcomeRefused { - if row.Code != tc.code || row.Message != tc.message || row.ExitCode != tc.exit || row.Mutates != tc.mutates { - t.Fatalf("refusal fields = code=%q message=%q exit=%d mutates=%t", row.Code, row.Message, row.ExitCode, row.Mutates) + if row.Rule.Code != tc.code || row.Rule.Message != tc.message || row.Rule.ExitCode != tc.exit || row.Rule.Mutates != tc.mutates { + t.Fatalf("refusal fields = code=%q message=%q exit=%d mutates=%t", + row.Rule.Code, row.Rule.Message, row.Rule.ExitCode, row.Rule.Mutates) } - typed := transformCapabilityError(row) + var typed error = proxyCapabilityErrorFor(row.Rule) var got *ProxyCapabilityError if !errors.As(typed, &got) || got.Code != tc.code || got.ExitCode != 1 || got.Mutates { t.Fatalf("typed refusal = %#v", typed) } } - if err := validateProxyTransformBeforeProvider(cmd); tc.outcome == ProxyOutcomeHonored && err != nil { + if err := validateProxyRegistryBeforeProvider(cmd); tc.outcome == ProxyOutcomeHonored && err != nil { t.Fatalf("honored transform refused: %v", err) } }) @@ -85,11 +86,11 @@ func TestProxyTransformCapabilityRows(t *testing.T) { func TestProxyDuplicatesAutoMergeDryRunMatrix(t *testing.T) { cmd := transformTestCommand("duplicates", "auto-merge", "dry-run") _ = cmd.Flags().Set("auto-merge", "true") - if err := validateProxyTransformBeforeProvider(cmd); err == nil { + if err := validateProxyRegistryBeforeProvider(cmd); err == nil { t.Fatalf("non-dry auto-merge error = %v", err) } _ = cmd.Flags().Set("dry-run", "true") - if err := validateProxyTransformBeforeProvider(cmd); err != nil { + if err := validateProxyRegistryBeforeProvider(cmd); err != nil { t.Fatalf("dry-run auto-merge refused: %v", err) } } @@ -103,7 +104,7 @@ func TestProxyTransformRefusalRendering(t *testing.T) { jsonOutput = false var textErr string stderr := captureStderr(t, func() { - err := validateProxyTransformBeforeProvider(cmd) + err := validateProxyRegistryBeforeProvider(cmd) if code, ok := exitCodeFromError(err); !ok || code != 1 { t.Fatalf("exit = %v, want 1", err) } @@ -115,7 +116,7 @@ func TestProxyTransformRefusalRendering(t *testing.T) { jsonOutput = true stdout := captureStdout(t, func() error { - _ = validateProxyTransformBeforeProvider(cmd) + _ = validateProxyRegistryBeforeProvider(cmd) return nil }) var envelope map[string]any @@ -140,8 +141,8 @@ func TestProxyTransformMatcherIgnoresInheritedOutputFlags(t *testing.T) { if err := root.PersistentFlags().Set("json", "true"); err != nil { t.Fatal(err) } - row, ok := lookupTransformCapability(cmd) - if !ok || row.Argument != "--auto-merge" || row.Outcome != ProxyOutcomeRefused { + row, ok := capabilityRowFor(cmd) + if !ok || row.ArgSet != "--auto-merge" || row.Rule.Outcome != ProxyOutcomeRefused { t.Fatalf("row with inherited --json = %#v, ok=%v", row, ok) } } @@ -163,7 +164,7 @@ func TestProxyTransformRefusalHasNoProviderOrFileMutation(t *testing.T) { t.Cleanup(func() { uowProvider = oldProvider }) cmd := transformTestCommand("supersede") - err := validateProxyTransformBeforeProvider(cmd) + err := validateProxyRegistryBeforeProvider(cmd) if err == nil { t.Fatal("expected transform refusal") } diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go index 80ff1b5b3..bf753777b 100644 --- a/cmd/bd/errors.go +++ b/cmd/bd/errors.go @@ -76,8 +76,16 @@ func buildJSONError(message, hint string) interface{} { return inner } +// buildJSONCapabilityError renders a typed refusal. {code, error, mutates} is a +// frozen contract that downstream consumers parse; `reason` is additive and +// appears only on refusals that came from the capability registry, which is why +// it is omitted rather than emitted empty — a consumer that keys on its presence +// must not be told "" by a runtime state error that has no policy reason. func buildJSONCapabilityError(e *ProxyCapabilityError) interface{} { inner := map[string]interface{}{"error": e.Message, "code": e.Code, "mutates": e.Mutates} + if e.Reason != "" { + inner["reason"] = string(e.Reason) + } if jsonEnvelopeEnabled() { return map[string]interface{}{"schema_version": JSONSchemaVersion, "data": inner} } diff --git a/cmd/bd/history_capability.go b/cmd/bd/history_capability.go deleted file mode 100644 index c3e5fd3f7..000000000 --- a/cmd/bd/history_capability.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -// HistoryCapabilityClass classifies history/version-control commands on the -// proxied topology without coupling them to a particular backend engine. -type HistoryCapabilityClass string - -const ( - HistoryProxySupported HistoryCapabilityClass = "proxy-supported" - HistoryProxyAPI HistoryCapabilityClass = "proxy-api" - HistoryDirectOnly HistoryCapabilityClass = "direct-only" -) - -var historyCapabilityMatrix = map[string]HistoryCapabilityClass{ - "history": HistoryProxySupported, - "branch": HistoryDirectOnly, "conflicts": HistoryDirectOnly, "repo": HistoryDirectOnly, - "federation": HistoryDirectOnly, "vc": HistoryDirectOnly, "flatten": HistoryDirectOnly, - "dolt push": HistoryDirectOnly, "dolt pull": HistoryDirectOnly, "dolt commit": HistoryDirectOnly, - "dolt remote": HistoryDirectOnly, "dolt remote add": HistoryDirectOnly, "dolt remote list": HistoryDirectOnly, - "dolt remote reset-data": HistoryDirectOnly, "dolt remote remove": HistoryProxySupported, - "sync": HistoryDirectOnly, -} - -// LookupHistoryCapability classifies an exact command path. Unknown paths are -// intentionally absent so callers cannot accidentally advertise support. -func LookupHistoryCapability(commandPath string) (HistoryCapabilityClass, bool) { - c, ok := historyCapabilityMatrix[commandPath] - return c, ok -} diff --git a/cmd/bd/main.go b/cmd/bd/main.go index e68d7b02d..eadf17e25 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -229,13 +229,6 @@ func effectiveRootStorePolicy(cmdName string, strictReadonly bool) rootStorePoli } } -// backendSupportsStrictReadonly reports whether the live backend path can open -// without provisioning or lifecycle changes. Unsupported SQL backends are -// rejected earlier by validateConfiguredBackend; proxied Dolt remains writable-only. -func backendSupportsStrictReadonly(cfg *configfile.Config) bool { - return cfg == nil || !cfg.IsDoltProxiedServerMode() -} - // runsPostCommandMaintenance reports whether PersistentPostRunE should run the // post-command maintenance net — Dolt auto-commit, the tip-metadata commit, // auto-backup, auto-export and auto-push. @@ -1281,11 +1274,11 @@ var rootCmd = &cobra.Command{ } } if cmdName == "doctor" && usesProxiedServer() { - // Refuse only on a real refusal. validateProxyMaintenance... + // 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 // resolution every other skipsStoreInit command still runs. - if err := validateProxyMaintenanceBeforeProvider(cmd); err != nil { + if err := validateProxyRegistryBeforeProvider(cmd); err != nil { return err } } @@ -1492,14 +1485,13 @@ var rootCmd = &cobra.Command{ } // Reject proxy capability combinations before any workspace side effect // (version tracking, migration, auto-start, or provider construction). + // Two validators, one for each half of the policy: flag-keyed rules and + // the path-keyed capability registry. if cfg != nil && cfg.IsDoltProxiedServerMode() { if err := validateProxyCapabilitiesBeforeProvider(cmd); err != nil { return err } - if err := validateProxyMaintenanceBeforeProvider(cmd); err != nil { - return err - } - if err := validateProxyTransformBeforeProvider(cmd); err != nil { + if err := validateProxyRegistryBeforeProvider(cmd); err != nil { return err } } @@ -1510,9 +1502,6 @@ var rootCmd = &cobra.Command{ if readonlyMode && cfg != nil && cfg.IsDoltProxiedServerMode() { return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapReadonly)) } - if readonlyMode && !backendSupportsStrictReadonly(cfg) { - return HandleError("strict readonly is unavailable for dolt proxied-server backend; refusing to open a store that cannot guarantee mutation-free access") - } // Set actor for audit trail actor = getActorWithGit() diff --git a/cmd/bd/migrate_dolt_mode.go b/cmd/bd/migrate_dolt_mode.go index 387624e93..684212738 100644 --- a/cmd/bd/migrate_dolt_mode.go +++ b/cmd/bd/migrate_dolt_mode.go @@ -199,12 +199,17 @@ func migrateFault(phase migratePhase) error { return nil } +// externalMigrationRefusal is a policy refusal rather than a registry row: it +// depends on the workspace's endpoint, not on which command was typed. The +// reason is design because someone else owns that endpoint and its schema — +// no amount of plumbing on this side makes migrating it bd's business. func externalMigrationRefusal(message string) error { return HandleProxyCapabilityError(&ProxyCapabilityError{ Code: "proxy.migrate.external_endpoint", Message: message, ExitCode: 1, Mutates: false, + Reason: ProxyReasonDesign, }) } diff --git a/cmd/bd/proxy_capability.go b/cmd/bd/proxy_capability.go index 8c188183e..774323944 100644 --- a/cmd/bd/proxy_capability.go +++ b/cmd/bd/proxy_capability.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "strings" "github.com/spf13/cobra" ) @@ -47,17 +46,24 @@ const ( ProxyOutcomeRefused ProxyCapabilityOutcome = "refused" ProxyOutcomeDelegated ProxyCapabilityOutcome = "delegated" ProxyOutcomeNA ProxyCapabilityOutcome = "N/A" + // ProxyOutcomeRefusedInRunE records a path the gate permits and that the + // command then refuses itself, untyped, from RunE. It is inventory, not + // policy: nothing enforces it. See capability_registry.go. + ProxyOutcomeRefusedInRunE ProxyCapabilityOutcome = "refused-in-run" ) // proxyCapabilityRule is the stable contract for one command/argument/topology // capability. Mutates is false for all refusals; ExitCode is used by the CLI -// when rendering a typed refusal. +// when rendering a typed refusal. Reason and Tracking say why a refusal exists +// and who closes it — see the header of capability_registry.go. type proxyCapabilityRule struct { Outcome ProxyCapabilityOutcome Code string Message string ExitCode int Mutates bool + Reason ProxyRefusalReason + Tracking string } // ProxyCapabilityError is a machine-identifiable front-door refusal. @@ -66,12 +72,39 @@ type ProxyCapabilityError struct { Message string ExitCode int Mutates bool + Reason ProxyRefusalReason } func (e *ProxyCapabilityError) Error() string { return e.Message } -func refused(code, message string) proxyCapabilityRule { - return proxyCapabilityRule{Outcome: ProxyOutcomeRefused, Code: code, Message: message, ExitCode: 1} +// errProxiedStoreUnrouted is the backstop for a command that the front door +// permitted and that then asked for a classic store on a proxied-server +// workspace. The proxied topology has no such store — the provider owns the +// connection — so the factory refuses rather than opening the proxied root a +// second time behind the proxy's back, which is the one failure mode every +// slice of this work must not regress. +// +// Reaching this is a routing gap in the command, not a policy decision: the +// registry says the gate permits the path, and permitting a path is not a +// promise that a proxied route exists for it. The owner is therefore whichever +// slice routes the command that landed here, which is why the reason is +// "unimplemented" and no single tracking item fits. It is typed so that a +// caller can classify it; before the registry there was no way to tell this +// apart from a genuine store failure. +func errProxiedStoreUnrouted() error { + return &ProxyCapabilityError{ + Code: "proxy.store.unrouted", + Message: "this command has no proxied-server route; bd will not open a proxied-server workspace as a direct store", + ExitCode: 1, + Reason: ProxyReasonUnimplemented, + } +} + +func refused(code, message string, reason ProxyRefusalReason, tracking string) proxyCapabilityRule { + return proxyCapabilityRule{ + Outcome: ProxyOutcomeRefused, Code: code, Message: message, ExitCode: 1, + Reason: reason, Tracking: tracking, + } } func honored() proxyCapabilityRule { @@ -97,104 +130,6 @@ type ProxyCapabilityRow struct { Rule proxyCapabilityRule } -var proxyMaintenanceRefusals = map[string]proxyCapabilityRule{ - "doctor": refused("proxy.doctor.unsupported", "doctor is not supported in proxied-server mode"), - "backup": refused("proxy.backup.unsupported", "backup is not supported in proxied-server mode"), - "restore": refused("proxy.restore.unsupported", "restore is not supported in proxied-server mode"), - "diff": refused("proxy.diff.unsupported", "diff is not supported in proxied-server mode"), - "flatten": refused("proxy.flatten.unsupported", "flatten is not supported in proxied-server mode"), - "migrate": refused("proxy.migrate.unsupported", "migrate is not supported in proxied-server mode"), - "migrate-personal": refused("proxy.migrate.unsupported", "migrate-personal is not supported in proxied-server mode"), - "branch": refused("proxy.branch.unsupported", "branch is not supported in proxied-server mode"), - "conflicts": refused("proxy.conflicts.unsupported", "conflicts is not supported in proxied-server mode"), - "vc": refused("proxy.vc.unsupported", "vc is not supported in proxied-server mode"), - "federation": refused("proxy.federation.unsupported", "federation is not supported in proxied-server mode"), - "repo": refused("proxy.repo.unsupported", "repo is not supported in proxied-server mode"), - // Wording matches the long-standing compact.go refusal this pre-provider - // gate now short-circuits, so the user-facing message does not change. - "compact": refused("proxy.compact.unsupported", "only 'compact --dolt' is supported in proxied-server mode"), - "backup init": refused("proxy.backup.unsupported", "backup init is not supported in proxied-server mode"), - "backup sync": refused("proxy.backup.unsupported", "backup sync is not supported in proxied-server mode"), - "backup remove": refused("proxy.backup.unsupported", "backup remove is not supported in proxied-server mode"), - "backup status": refused("proxy.backup.unsupported", "backup status is not supported in proxied-server mode"), - "backup restore": refused("proxy.backup.unsupported", "backup restore is not supported in proxied-server mode"), - "migrate sync": refused("proxy.migrate.unsupported", "migrate sync is not supported in proxied-server mode"), - "migrate-issues": refused("proxy.migrate.unsupported", "migrate-issues is not supported in proxied-server mode"), - "gate discover": refused("proxy.gate.unsupported", "gate discover is not supported in proxied-server mode"), - "admin cleanup": refused("proxy.admin.unsupported", "admin cleanup is not supported in proxied-server mode"), - "admin reset": refused("proxy.admin.unsupported", "admin reset is not supported in proxied-server mode"), - "dolt push": refused("proxy.dolt_push.unsupported", "dolt push is not supported in proxied-server mode"), - "dolt pull": refused("proxy.dolt_pull.unsupported", "dolt pull is not supported in proxied-server mode"), - "dolt commit": refused("proxy.dolt_commit.unsupported", "dolt commit is not supported in proxied-server mode"), - "dolt remote": refused("proxy.dolt_remote.unsupported", "dolt remote is not supported in proxied-server mode"), - "dolt remote add": refused("proxy.dolt_remote.unsupported", "dolt remote add is not supported in proxied-server mode"), - "dolt remote list": refused("proxy.dolt_remote.unsupported", "dolt remote list is not supported in proxied-server mode"), - "cook": refused("proxy.formula.unsupported", "cook is not supported in proxied-server mode"), - "ship": refused("proxy.formula.unsupported", "ship is not supported in proxied-server mode"), - "swarm create": refused("proxy.swarm.unsupported", "swarm create is not supported in proxied-server mode"), - "swarm list": refused("proxy.swarm.unsupported", "swarm list is not supported in proxied-server mode"), - "merge-slot create": refused("proxy.merge_slot.unsupported", "merge-slot create is not supported in proxied-server mode"), - "merge-slot check": refused("proxy.merge_slot.unsupported", "merge-slot check is not supported in proxied-server mode"), - "merge-slot acquire": refused("proxy.merge_slot.unsupported", "merge-slot acquire is not supported in proxied-server mode"), - "merge-slot release": refused("proxy.merge_slot.unsupported", "merge-slot release is not supported in proxied-server mode"), - "dolt remote reset-data": refused("proxy.dolt_remote.unsupported", "dolt remote reset-data is not supported in proxied-server mode"), - "sync": refused("proxy.sync.unsupported", "sync is not supported in proxied-server mode"), -} - -func init() { - for parent, children := range map[string][]string{ - "vc": {"merge", "commit", "status"}, - "federation": {"sync", "status", "add-peer", "remove-peer", "list-peers"}, - "repo": {"add", "remove", "list", "sync"}, - "conflicts": {"list", "show", "resolve"}, - "migrate": {"hooks", "issues"}, - } { - rule := proxyMaintenanceRefusals[parent] - for _, child := range children { - path := parent + " " + child - proxyMaintenanceRefusals[path] = refused(rule.Code, path+" is not supported in proxied-server mode") - } - } -} - -// validateProxyMaintenanceBeforeProvider rejects known direct-only commands -// before migrations, auto-start, or provider construction. -func validateProxyMaintenanceBeforeProvider(cmd *cobra.Command) error { - if cmd == nil { - return nil - } - name := cmd.Name() - path := strings.TrimSpace(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name())) - if name == "compact" { - if cmd.Flags().Lookup("dolt") == nil { - return nil // root `bd compact` is the Dolt history command - } - dolt, _ := cmd.Flags().GetBool("dolt") - if dolt { - return nil - } - rule := proxyMaintenanceRefusals["compact"] - return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode}) - } - if rule, ok := proxyMaintenanceRefusals[path]; ok { - return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode}) - } - if class, ok := LookupHistoryCapability(path); ok && class == HistoryDirectOnly { - rule := refused("proxy.history.unsupported", path+" is not supported in proxied-server mode") - if specific, found := proxyMaintenanceRefusals[path]; found { - rule = specific - } - return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates}) - } - if strings.Contains(path, " ") { - return nil - } - if rule, ok := proxyMaintenanceRefusals[name]; ok { - return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode}) - } - return nil -} - // LookupProxyCapabilityFor returns the command/argument-specific rule. An // absent command row falls back to the topology-wide default. func LookupProxyCapabilityFor(command, argument string, mode ProxyMode) (proxyCapabilityRule, bool) { @@ -212,26 +147,50 @@ func LookupProxyCapabilityFor(command, argument string, mode ProxyMode) (proxyCa return LookupProxyCapability(mode, capability) } +// Shared by the mode-wide rule and its per-command overrides, so a command that +// refuses one of these refuses it with the same words and the same reason. +var ( + // The cap is refused rather than silently dropped, which is right; the fix + // is threading it through the UOW reader the way `list` already does, so + // the refusal itself is the gap. + maxRowsRefusal = refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode", ProxyReasonUnimplemented, trackLongTail) + // `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) +) + +// proxyCapabilityMatrix is the flag-keyed half of the policy; the path-keyed +// half is the registry in capability_registry.go. Reasons follow the same rule +// there and here. +// +// Strict --readonly is the one capability that needs real backend work rather +// than routing: it is a GUARANTEE, the proxied provider carries no read-only +// posture, and the only honest implementation is a read-only SQL principal on +// the backend — which on external topologies is the operator's configuration, +// not bd's. A best-effort version would betray exactly the workflows that ask +// for it, so it is refused by design until that principal exists. --repo is +// design for a simpler reason: it routes to another workspace, bypassing the +// proxied root entirely. var proxyCapabilityMatrix = map[ProxyMode]map[ProxyCapability]proxyCapabilityRule{ ProxyModeDirect: { ProxyCapReadonly: honored(), ProxyCapMaxRows: honored(), ProxyCapWatch: honored(), ProxyCapRepo: honored(), }, ProxyModeProxied: { - 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"), - ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode"), - ProxyCapWatch: refused("proxy.watch.unsupported", "watch mode not supported in proxied-server mode"), - ProxyCapRepo: refused("proxy.repo.unsupported", "--repo is not supported with --proxied-server"), + 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, ""), }, } var proxyCommandCapabilities = map[string]map[ProxyMode]map[ProxyCapability]proxyCapabilityRule{ - "show": {ProxyModeProxied: {ProxyCapWatch: refused("proxy.watch.unsupported", "watch mode not supported in proxied-server mode")}}, + "show": {ProxyModeProxied: {ProxyCapWatch: watchRefusal}}, "list": {ProxyModeProxied: {ProxyCapWatch: honored(), ProxyCapMaxRows: honored(), ProxyCapRepo: notApplicable()}}, "dep tree": {ProxyModeProxied: {ProxyCapMaxRows: honored()}}, - "ready": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}}, - "graph": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}}, - "find-duplicates": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}}, + "ready": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}}, + "graph": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}}, + "find-duplicates": {ProxyModeProxied: {ProxyCapMaxRows: maxRowsRefusal}}, } // proxyCapabilityRows materializes the policy for every supported proxied @@ -305,7 +264,7 @@ func AssertProxyCommandCapability(command string, mode ProxyMode, capability Pro return nil } if rule.Code != "" { - return &ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates} + return proxyCapabilityErrorFor(rule) } return fmt.Errorf("%s", rule.Message) } @@ -314,7 +273,7 @@ func AssertProxyCommandCapability(command string, mode ProxyMode, capability Pro rule, ok := LookupProxyCapability(mode, capability) if !ok || (rule.Outcome != ProxyOutcomeHonored && rule.Outcome != ProxyOutcomeDelegated) { if rule.Code != "" { - return &ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates} + return proxyCapabilityErrorFor(rule) } if rule.Message != "" { return fmt.Errorf("%s", rule.Message) diff --git a/cmd/bd/proxy_capability_test.go b/cmd/bd/proxy_capability_test.go index 80308e292..272d0a453 100644 --- a/cmd/bd/proxy_capability_test.go +++ b/cmd/bd/proxy_capability_test.go @@ -81,7 +81,7 @@ func TestProxyMaintenanceNestedPathsRefuseBeforeProvider(t *testing.T) { root.AddCommand(parent) parent.AddCommand(child) out := captureStdout(t, func() error { - _ = validateProxyMaintenanceBeforeProvider(child) + _ = validateProxyRegistryBeforeProvider(child) return nil }) if !strings.Contains(out, `"code":`) { @@ -101,7 +101,7 @@ func TestProxyFormulaSwarmMergeSlotRefusals(t *testing.T) { cmd.AddCommand(child) cmd = child } - err := validateProxyMaintenanceBeforeProvider(cmd) + err := validateProxyRegistryBeforeProvider(cmd) if err == nil { t.Fatalf("%s unexpectedly allowed", path) } @@ -139,7 +139,7 @@ func TestProxyWorkflowRefusalContractAndNoMutation(t *testing.T) { if !ok || row.Code != tc.code || row.Message != tc.message || row.ExitCode != 1 || row.Mutates { t.Fatalf("row = %#v, ok=%v", row, ok) } - var typed *ProxyCapabilityError = &ProxyCapabilityError{Code: row.Code, Message: row.Message, ExitCode: row.ExitCode, Mutates: row.Mutates} + typed := proxyCapabilityErrorFor(row) if typed.Code != tc.code || typed.Message != tc.message || typed.ExitCode != 1 || typed.Mutates { t.Fatalf("typed refusal = %#v", typed) } @@ -162,7 +162,7 @@ func TestProxyWorkflowRefusalContractAndNoMutation(t *testing.T) { oldDidWrite := commandDidWrite.Load() commandDidWrite.Store(false) t.Cleanup(func() { commandDidWrite.Store(oldDidWrite) }) - out := captureStdout(t, func() error { _ = validateProxyMaintenanceBeforeProvider(cmd); return nil }) + out := captureStdout(t, func() error { _ = validateProxyRegistryBeforeProvider(cmd); return nil }) var got map[string]any if err := json.Unmarshal([]byte(out), &got); err != nil || got["code"] != tc.code || got["error"] != tc.message { t.Fatalf("JSON refusal = %q (%v)", out, err) @@ -181,8 +181,8 @@ func TestProxyWorkflowRefusalContractAndNoMutation(t *testing.T) { } func lookupProxyMaintenanceRuleForTest(path string) (proxyCapabilityRule, bool) { - rule, ok := proxyMaintenanceRefusals[path] - return rule, ok + row, ok := LookupCapabilityRow(path, "") + return row.Rule, ok } func TestProxyMaintenanceRefusalLeavesFilesUntouched(t *testing.T) { @@ -199,7 +199,7 @@ func TestProxyMaintenanceRefusalLeavesFilesUntouched(t *testing.T) { oldProvider := uowProvider uowProvider = nil t.Cleanup(func() { uowProvider = oldProvider }) - err := validateProxyMaintenanceBeforeProvider(hooks) + err := validateProxyRegistryBeforeProvider(hooks) if err == nil { t.Fatal("expected typed maintenance refusal") } diff --git a/cmd/bd/readonly_policy_test.go b/cmd/bd/readonly_policy_test.go index cd5d78f91..afa6329c2 100644 --- a/cmd/bd/readonly_policy_test.go +++ b/cmd/bd/readonly_policy_test.go @@ -68,26 +68,6 @@ func TestEffectiveRootStorePolicy(t *testing.T) { } } -func TestStrictReadonlyBackendSupport(t *testing.T) { - tests := []struct { - name string - cfg *configfile.Config - want bool - }{ - {name: "fresh embedded default", cfg: nil, want: true}, - {name: "dolt server", cfg: &configfile.Config{Backend: configfile.BackendDolt, DoltMode: configfile.DoltModeServer}, want: true}, - {name: "proxied server", cfg: &configfile.Config{Backend: configfile.BackendDolt, DoltMode: configfile.DoltModeProxiedServer}, want: false}, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := backendSupportsStrictReadonly(tc.cfg); got != tc.want { - t.Fatalf("backendSupportsStrictReadonly() = %v, want %v", got, tc.want) - } - }) - } -} - type strictReadonlyPostRunStore struct { storage.DoltStorage metadataWrites int diff --git a/cmd/bd/serve.go b/cmd/bd/serve.go index ab5bcc88c..713a7ec5e 100644 --- a/cmd/bd/serve.go +++ b/cmd/bd/serve.go @@ -608,7 +608,7 @@ func serveDatabaseSource(beadsDir string) (serveDatabase, error) { // the server, which no client can discover before connecting. bd already // answers this question the same way one layer down, where a backend that // cannot guarantee mutation-free access is turned away rather than opened -// anyway (backendSupportsStrictReadonly, cmd/bd/main.go). +// anyway (the proxy.readonly.unsupported refusal in cmd/bd/main.go). // // The value is read from the global rather than a flag lookup because // `readonly` is also a config key, and PersistentPreRunE has already folded diff --git a/cmd/bd/store_factory.go b/cmd/bd/store_factory.go index 00f1afb32..0bf5fe521 100644 --- a/cmd/bd/store_factory.go +++ b/cmd/bd/store_factory.go @@ -70,9 +70,7 @@ func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readO func newDoltStore(ctx context.Context, cfg *dolt.Config) (s storage.DoltStorage, err error) { defer func() { s, err = activateEventsJournalStore(cfg.BeadsDir, s, err) }() if cfg.ProxiedServer { - // TODO: this should not be a store - // it should be a uow provider - return nil, fmt.Errorf("proxy server store should be uow provider") + return nil, errProxiedStoreUnrouted() } if cfg.ServerMode { return dolt.New(ctx, cfg) @@ -172,13 +170,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol return backend.Open(ctx, beadsDir) } if cfg != nil && cfg.IsDoltProxiedServerMode() { - // TODO: this needs to be uow provider - return nil, fmt.Errorf("proxy server store should be uow provider") - // return newProxiedServerStore(ctx, &dolt.Config{ - // BeadsDir: beadsDir, - // Database: cfg.GetDoltDatabase(), - // ProxiedServer: true, - // }) + return nil, errProxiedStoreUnrouted() } if cfg != nil && cfg.IsDoltServerMode() { return dolt.NewFromConfig(ctx, beadsDir) @@ -280,14 +272,7 @@ func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, previe return backend.OpenReadOnly(ctx, beadsDir) } if cfg != nil && cfg.IsDoltProxiedServerMode() { - // TODO: this needs to be uow provider - return nil, fmt.Errorf("proxy server store needs to be uow provider") - // return newProxiedServerStore(ctx, &dolt.Config{ - // BeadsDir: beadsDir, - // Database: cfg.GetDoltDatabase(), - // ProxiedServer: true, - // ReadOnly: true, - // }) + return nil, errProxiedStoreUnrouted() } if cfg != nil && cfg.IsDoltServerMode() { return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{ReadOnly: true}) diff --git a/cmd/bd/store_factory_nocgo.go b/cmd/bd/store_factory_nocgo.go index 3266e1aa9..152ceb294 100644 --- a/cmd/bd/store_factory_nocgo.go +++ b/cmd/bd/store_factory_nocgo.go @@ -50,9 +50,7 @@ func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readO func newDoltStore(ctx context.Context, cfg *dolt.Config) (s storage.DoltStorage, err error) { defer func() { s, err = activateEventsJournalStore(cfg.BeadsDir, s, err) }() if cfg.ProxiedServer { - // TODO: this should not be a store - // it should be a uow provider - return nil, fmt.Errorf("proxy server store should be uow provider") + return nil, errProxiedStoreUnrouted() } if !cfg.ServerMode { return nil, fmt.Errorf("%s", nocgoEmbeddedErrMsg) @@ -83,13 +81,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol return backend.Open(ctx, beadsDir) } if cfg != nil && cfg.IsDoltProxiedServerMode() { - // TODO: this needs to be uow provider - return nil, fmt.Errorf("proxy server store should be uow provider") - // return newProxiedServerStore(ctx, &dolt.Config{ - // BeadsDir: beadsDir, - // Database: cfg.GetDoltDatabase(), - // ProxiedServer: true, - // }) + return nil, errProxiedStoreUnrouted() } if cfg != nil && cfg.IsDoltServerMode() { return dolt.NewFromConfig(ctx, beadsDir) @@ -114,14 +106,7 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D return backend.OpenReadOnly(ctx, beadsDir) } if cfg != nil && cfg.IsDoltProxiedServerMode() { - // TODO: this needs to be uow provider - return nil, fmt.Errorf("proxy server store needs to be uow provider") - // return newProxiedServerStore(ctx, &dolt.Config{ - // BeadsDir: beadsDir, - // Database: cfg.GetDoltDatabase(), - // ProxiedServer: true, - // ReadOnly: true, - // }) + return nil, errProxiedStoreUnrouted() } if cfg != nil && cfg.IsDoltServerMode() { return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{ReadOnly: true}) diff --git a/cmd/bd/transform_capability.go b/cmd/bd/transform_capability.go deleted file mode 100644 index 2265a1b78..000000000 --- a/cmd/bd/transform_capability.go +++ /dev/null @@ -1,90 +0,0 @@ -package main - -import ( - "sort" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -type TransformCapability struct { - Path string - Argument string - Outcome ProxyCapabilityOutcome - Code string - Message string - ExitCode int - Mutates bool -} - -var transformCapabilityRows = []TransformCapability{ - transformRefused("rename"), - transformRefused("rename-prefix"), - transformRefusedWithArgs("rename-prefix", "--dry-run"), - transformRefusedWithArgs("rename-prefix", "--repair"), - transformRefusedWithArgs("rename-prefix", "--dry-run --repair"), - transformRefused("duplicate"), - transformRefusedWithArgs("duplicate", "--of"), - transformRefused("supersede"), - transformRefusedWithArgs("supersede", "--with"), - {Path: "duplicates", Outcome: ProxyOutcomeHonored}, - transformRefusedWithArgs("duplicates", "--auto-merge"), - {Path: "duplicates", Argument: "--auto-merge --dry-run", Outcome: ProxyOutcomeHonored}, -} - -func transformRefused(path string) TransformCapability { - return transformRefusedWithArgs(path, "") -} - -func transformRefusedWithArgs(path, argument string) TransformCapability { - displayPath := path - if argument != "" { - displayPath += " " + argument - } - return TransformCapability{ - Path: path, Argument: argument, Outcome: ProxyOutcomeRefused, - Code: "proxy.transform.unsupported", Message: displayPath + " is not supported in proxied-server mode", ExitCode: 1, - } -} - -func transformCapabilityError(row TransformCapability) *ProxyCapabilityError { - return &ProxyCapabilityError{Code: row.Code, Message: row.Message, ExitCode: row.ExitCode, Mutates: row.Mutates} -} - -func lookupTransformCapability(cmd *cobra.Command) (TransformCapability, bool) { - path := cmd.CommandPath() - path = strings.TrimSpace(strings.TrimPrefix(path, cmd.Root().Name())) - var args []string - cmd.Flags().Visit(func(f *pflag.Flag) { - if transformPolicyFlags[f.Name] { - args = append(args, "--"+f.Name) - } - }) - sort.Strings(args) - arg := strings.Join(args, " ") - for _, row := range transformCapabilityRows { - if row.Path == path && row.Argument == arg { - return row, true - } - } - return TransformCapability{}, false -} - -// Only flags that alter a transform's execution belong in the capability key. -// Output, tracing, and other inherited root flags must not bypass a refusal. -var transformPolicyFlags = map[string]bool{ - "auto-merge": true, "dry-run": true, "repair": true, "of": true, "with": true, -} - -func validateProxyTransformBeforeProvider(cmd *cobra.Command) error { - if cmd == nil { - return nil - } - if row, ok := lookupTransformCapability(cmd); ok { - if row.Outcome == ProxyOutcomeRefused { - return HandleProxyCapabilityError(transformCapabilityError(row)) - } - } - return nil -}