* fix(mol): route bond operand resolution like show/update/close (closes #4714) bd mol bond resolved operands with utils.ResolvePartialID against the local store only, so a bead that lived in a routed store failed with "'<id>' not found (not an issue ID or formula name)" — even though bd show resolved the same ID. This broke `gt sling <bead> <rig>`, which cooks the default formula and bonds it to a rig-routed bead. - Resolve operands through resolveAndGetIssueForMutation, the same routing fallback bd show/update/close use (local, then prefix-routed rig via routes.jsonl, then contributor auto-routing). Write-intent so a prefix-routed target opens writable and the bond commits where the bead lives. - Run the bond mutation against the store that owns the resolved issue instead of the global local store; reject a bond whose two operands resolve to different stores rather than writing to the wrong database. - Route the --dry-run preview read-only so it previews routed operands too. - Add TestResolveMolBondOperandRouting covering local and routed resolution. Same routing-parity fix as #3608/#3609 for bd close. * fix(mol): fail fast on read-only routed stores, share same-rig bond handles Address the two structural issues from the #4720 review beyond the rebase itself (the rebase already preserves main's unconditional formula fallback from #3874 instead of reintroducing the looksLikeFormulaName gate): - Routed operands resolve but couldn't be bonded: contributor auto-routing deliberately opens stores read-only (they hydrate foreign projects that must never be mutated), yet the bond selected that store and dispatched mutations that only failed at the store layer. Operand resolution now mirrors resolveCloseTargets explicitly (local, then prefix-routed write-intent, then the shared auto-routed read-only handle) and records writability per operand; pickBondStore rejects a bond pinned to a read-only store with a clear message before any mutation is attempted. TestMolBondPrefixRoutedWriteThrough now verifies the actual dependency write commits in the routed database, not just resolution, and TestMolBondAutoRoutedReadOnlyFailsFast covers the fail-fast path. - Same routed database compared as two different stores: pickBondStore compared Go handle identity, but each route-open constructs a fresh store in server mode, so two operands in the same routed rig were wrongly rejected as cross-store. Both operands of a bond now share one routed handle (an already-opened routed store is tried before opening another), and sameBondStore falls back to StoreLocator identity (CLIDir pins the concrete database) for separately-opened handles onto the same database. TestSameBondStoreSeparateHandles covers the two-handle case directly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mol): validate routed bond homes before mutation Discover bond operands read-only, enforce dry-run parity and cross-store policy before writable reopen, unwrap decorated store identities, preserve actionable route failures, and verify the accepted home after reopen. Co-authored-by: Johan Snyman <johan.snyman@orange.com> Agent-Signature: codex-gpt-5.6-sol-high on behalf of matt wilkie * fix(mol): reconcile routed bond discovery with #5253 var validation The rebase onto current main carried two silent regressions the Aug 16 review named: the discovery-based resolution (which replaced resolveOrDescribe on the direct-store path) never validated --var values, so `bd mol bond --dry-run <formula> <x> --var bad=...` previewed success for a bond execution refuses — exactly the false preview #5253 fixed — and materializeMolBondOperand wrapped every cook error as "'%s' not found as issue or formula", re-introducing the ErrVarValidation double-wrap #5253 removed from resolveOrCookToSubgraph. discoverMolBondOperand now takes the provided vars and runs formula.ValidateProvidedVars on its formula fallback, so --dry-run and execution reject the bond identically, before any writable reopen. materializeMolBondOperand passes formula.ErrVarValidation through unwrapped, matching resolveOrCookToSubgraph and pour/wisp. Agent-Signature: claude-fable-5 on behalf of R0SEWT Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mol): review polish — fs.ErrNotExist, hook-isolated test repos, auto-route coverage Three non-blocking notes from the Aug 16 review: - routed.go: errors.Is(err, fs.ErrNotExist) instead of the legacy os.IsNotExist, so the not-found check keeps working if loadPrefixRoutes ever starts wrapping its open error. - mol_bond_routing_test.go: pin core.hooksPath to .git/hooks after each git init (the initGitRepoAt convention), so a developer or CI box with a global hooksPath override never runs foreign hooks inside test repos. - The widened openAutoRoutedStore behavior (maintainer/default auto-routes open writable for any validated write-intent resolver, not just mol bond) now has both the CHANGELOG sentence and a write-through test: TestMaintainerAutoRouteMutationWritesThrough drives resolveAndGetIssueForMutation — the bd update resolver — through a maintainer auto-route, commits a real update there, and re-reads it via a fresh routed read. Agent-Signature: claude-fable-5 on behalf of R0SEWT Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mol): carry main's #5761 formula validation into routed bond discovery Rebase adaptation for #4720 onto mainb303d494df. The PR moved the direct (non-proxied) `bd mol bond` path off resolveOrDescribe and resolveOrCookToSubgraph onto discoverMolBondOperand and materializeMolBondOperand. Main's #5761 meanwhile fixed the old pair so a --dry-run fails on exactly what the real bond fails on; the new pair did not have that fix: - discoverMolBondOperand loaded the formula with parser.LoadByName, which never runs Formula.Validate, so a --dry-run previewed a successful bond for a formula the cook rejects (e.g. a waits_for gate with no spawner). It also validated --var values against the unmerged formula, so a var whose enum is declared only in a parent went unchecked. Discovery now resolves the formula with parser.Resolve first, the way resolveAndCookFormulaWithVars does, and wraps both failures the way the cook does, so --dry-run and execution report the same message. - materializeMolBondOperand passed only formula.ErrVarValidation through unwrapped. A formula that fails validation was reported as "not found as issue or formula". formula.ErrValidation now passes through too, as in main's resolveOrCookToSubgraph. TestDiscoverMolBondOperandRejectsWhatMaterializeRejects and TestDiscoverMolBondOperandValidatesVarsAgainstTheMergedFormula assert the two phases against each other, like main's TestBondDryRun* pair does for the proxied route. Also: - The PR's routing tests now pass the `exact` argument that main's #5393 added to resolveViaPrefixRoutingWithAccess. They pass false, which keeps the partial-ID resolution the tests were written against. - The PR's three new cgo test files are added to the bd_test srcs. This is `make bazel-sync` output on the merged tree, and it touches nothing else. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> * test(mol): rebuild the RepoContext cache in the PR's role-routing tests Rebase adaptation for #4720 onto mainb303d494df. Main's #5243 moved auto-routing role detection onto beads.GetRepoContext(), which caches the repo context once per process; before it, role detection ran routing.DetectUserRole(".") on every call. The PR's auto-routing tests chdir into a fresh repo and set beads.role there, so after the rebase they read the context an earlier test built for its own, now-deleted repo. There beads.role is unset, and the remote-URL fallback finds no origin and answers maintainer: - TestMolBondAutoRoutedReadOnlyFailsFast fails whenever a role-routing test ran before it in the same binary (reproducible alone with -count=2): discovery looks for the contributor operand in the local store and reports it not found. - TestDiscoverMolBondOperandRouting/maintainer_routed_issue and TestMaintainerAutoRouteMutationWritesThrough still pass, but only because that fallback is also maintainer; they never read the beads.role they configure. Each test now calls resetRepoContextCachesForTest after its chdir, as #5243 did for main's own role-routing tests (TestResolveCloseTargets, which TestDiscoverMolBondOperandRouting mirrors, and the routing_read tests). Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> * fix(routing): open maintainer auto-routes writable for exact-match writes #5393 landed after this PR was written. It moved `bd comment` and `bd comments add` off resolveAndGetIssueForMutation onto a new resolveAndGetIssueForMutationExact. This PR widens the former's auto-route tier for write intent: a maintainer/default target opens writable, while a contributor target stays read-only and MutationForbidden. On the PR's original base that widening covered comment writes. After the rebase the exact resolver still opened every auto-route read-only, so comment writes lost it and the CHANGELOG's "any validated write-intent resolver" no longer held. The exact resolver is meant to keep the mutation resolver's routing fallbacks and only tighten matching (#5393: it "keeps the existing cross-rig prefix-routing and contributor auto-routing fallbacks intact"). Its auto tier now takes the same write-intent path. Matching stays exact, and the abbreviation-refusal precedence is unchanged. TestMaintainerAutoRouteExactMutationWritesThrough pins the change: the routed store must not be read-only, and a comment written through it must commit in the planning database. Without this change the read-only check fails. The write itself still succeeds, because a server-mode read-only open does not refuse it. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> * fix(routing): harden routed writes and surface routing failures Review fixes for #4720. bd close resolved its batch's shared auto-route through openRoutedReadStore, so the route opened read-only even though every other write-intent resolver opened it writable. The shared handle now opens through openAutoRoutedStore with write intent, so the close commits where the issue lives. A contributor auto-route now opens writable for write-intent callers, as maintainer and default routes do. The refusal the previous revision added (errContributorRouteMutationForbidden, contributorRouteRefusal, RoutedResult.MutationForbidden) is gone. A contributor's route target is their own planning repository, the one bd create writes to: docs/multi-agent/multi-repo-migration.md and examples/contributor-workflow/README.md have the contributor claim and close planning issues from the fork, and GH#2345, beads-0km and GH#3608 made bd show, update and close reach those issues. The read-only rule came from #4389's review fixes (e8ae7a291a), which kept "contributor auto-routing" read-only to preserve the bd-6dnrw.32/GH#3231 guarantee that "routed reads never mutate a foreign project's history". That guarantee is about reads, and the planning repository is not a foreign project. Base therefore split by backend: a server-mode bd update, close or comment of a planning issue committed, because a read-only server store accepts the write, while the embedded store refused it with "store is read-only". Refusing in every resolver would have broken the documented workflow on both backends. bd mol bond was the only command that checked MutationForbidden, so its check goes too, and a bond of planning issues commits in the planning repository like any other routed write. Reads through every route stay read-only. This reverses the previous revision's stance and is flagged here as a maintainer call. bd unclaim now resolves its issue through resolveAndGetIssueForMutation, as bd update --claim does, so a routed issue opens writable; with the read resolver an embedded routed target refused the release with "store is read-only". Like bd close, it commits a routed change itself (commitPendingIfEmbedded), since the post-run auto-commit covers only the local store. bd human respond and dismiss already opened their target writable but never committed it, so on an embedded workspace the close sat uncommitted in the routed repository's working set; they now commit it the same way. resolveAndGetIssueWithRoutingAccess's writablePrefixRoute parameter is renamed writable, since it now governs auto routes too. A routed commit that fails no longer looks like success, and a retry commits it. bd unclaim printed "Unclaimed" (or listed the issue in its --json output) even when the release's routed commit failed; it now reports the commit error and leaves the issue out. The failed commit leaves the release, or the close human respond and dismiss make, in the routed repository's working set. There a retry finds the issue unassigned or already closed and refuses before it reaches its commit, and nothing else commits a routed target. On that refusal unclaim, respond and dismiss now commit the pending write before reporting it, through commitRoutedWrite, which their success paths share. A routed write never creates the target's database. The routed open runs before the lookup it serves, so an embedded open of a repository that had not been bootstrapped yet created an empty database that outlived an id that missed; bd bootstrap then took it for the real one and skipped the clone from sync.remote. openRoutedTargetStore's writable branch now opens through newExistingDoltStoreFromConfig, which refuses an embedded workspace without a database (embeddeddolt.HasRepository) before the sanitize migration can rewrite anything there. A server-mode open already never creates one. resolveAndGetIssueForMutation already returned a routing failure (an unreadable routes.jsonl, a routed store that fails to open) as itself. The exact resolver and bd close still fell through to "no issue found matching", which misstates why the lookup missed. All of them now share isRoutingFailure. The exact resolver checks its abbreviation refusal first, so the auto tier still gets its chance at an exact match. A prefix route whose target has no usable metadata.json now names the route and the file and says why the file could not be used. An auto-routed store now opens the target's own dolt_database, as a prefix route already did. Otherwise BEADS_DOLT_SERVER_DATABASE, which names the launching workspace's database, would point a server-mode open at the wrong database on a shared server. openRoutedTargetStore holds that override for both route kinds. A write refuses a target whose metadata.json cannot be read or parsed or names no dolt_database (autoRouteTargetDatabase) instead of falling back to that variable. A target with no metadata.json at all opens, read or written, the only embedded database it holds (embeddeddolt.Databases), or the default database (configfile.DefaultDoltDatabase) when it holds none or several. Contributor setup leaves the planning repository without one until the first routed bd create writes it, and names its database the way any workspace without metadata.json does, BEADS_DOLT_SERVER_DATABASE first. The open would otherwise resolve that name again from the launcher's variable, so when the two differed a read that missed failed with "database not found" and a write that missed created a database beside the one setup created. A server-mode target holds no embedded database, so with the variable set such a route now opens the default database rather than the launcher's, which is what it opens without the variable. A read of a target whose metadata.json is unreadable or names no database keeps the lenient lookup it had. bd mol bond's routed home now gets the external-dependency policy and nothing else, as wireExternalDependencyPolicy asks of routed stores. The launching workspace's hooks and telemetry no longer wrap writes into another rig. runMolBond's tail is split into planMolBond, openMolBondHome, materializeMolBondOperands and bondMolBondOperands, which takes it from cyclomatic 26 down to 10 or less per function. getIssueWithRouting and the resolveViaAutoRouting wrapper had no callers left and are removed. Tests: - TestMaintainerAutoRouteMutationWritesThrough now checks that the routed store is writable. Without that check it passes even against a read-only open, because a server-mode read-only store accepts the write. - TestAutoRouteCloseTargetWriteIntent covers bd close's write intent for a maintainer route. - TestContributorAutoRouteWritesThrough replaces TestContributorAutoRouteRefusesWriteIntent: an update, a comment and a close through a contributor route each open the target writable and commit, a read through the same route stays read-only, and a missing id stays a plain not-found. - TestEmbeddedContributorRoutedWritesCommitInPlanning runs bd update --claim, unclaim, comment, close, human respond and human dismiss through the bd binary in a contributor checkout. Each advances the planning database's HEAD, and the issues end up closed there and absent from the fork's database. The embedded shard manifest gains the test. - TestMolBondContributorAutoRoutedWriteThrough replaces TestMolBondAutoRoutedReadOnlyFailsFast: bd mol bond's pipeline bonds two planning issues through a contributor route, and a fresh routed read sees the dependency; setupAutoRoute now seeds extra planning issues for it. TestDiscoverMolBondOperandRouting's contributor case now expects the writable reopen. - TestResolveCloseTargets keeps base's contributor cases (beads-0km); the previous revision had moved them to routing.maintainer. - TestRoutedWriteDoesNotCreateTargetDatabase (in-process) and TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase (the bd binary) check that a missed write through a prefix route and through a maintainer auto-route leaves an embedded target that has not been bootstrapped without an embeddeddolt directory. The embedded shard manifest gains the test. - TestRoutedMutationResolversReportRoutingFailures runs each write-intent resolver against an auto route whose store fails to open, an auto route whose target's metadata.json names no dolt_database while BEADS_DOLT_SERVER_DATABASE names the launcher's, and a prefix route whose target cannot load. - TestAutoRouteTargetDatabase covers a write and a read of a target whose metadata.json names a database, is missing, names none, or cannot be parsed; a missing one yields the target's only embedded database, or the default database when it holds none or several, either way. TestDatabases covers the listing, which applies HasRepository's .dolt marker probe to each database. - TestAutoRouteMissWithoutMetadataIgnoresEnv runs a missed read and a missed write through an auto-route to a target that has one database but no metadata.json: the default database while BEADS_DOLT_SERVER_DATABASE names the launcher's, and a database named after the launcher's with the variable set and unset at use. Each miss must report not found and leave the target holding only its database. - TestRoutedWriteRetryCommitsFailedCommit fails the routed commit of bd unclaim (text and --json), human respond and human dismiss with an invalid --dolt-auto-commit. The run must fail with nothing on stdout and leave the routed repository's HEAD as it was; a retry must report its refusal and commit the write there. - TestAutoRouteOpensTargetDatabaseDespiteEnv checks the target-database change. - The auto-routing tests clear BEADS_ROUTING_MODE and BD_ROUTING_MODE through neutralizeRoutingModeEnv. Viper ranks them above the routing.mode the tests write, so a host that exports either var never routes. bdEnv, which builds the bd binary's environment in the embedded tests, now drops BD_ROUTING_MODE as it drops BEADS_*; agent hosts export it, and TestEmbeddedContributorRoutedWritesCommitInPlanning failed on such a host. TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase no longer needs its own envWithout. - Reverting each fix turns its test red: the contributor read-only clamp (the contributor tests above), unclaim's resolver or commit and the respond and dismiss commits (the matching step of the embedded test), and each autoRouteTargetDatabase rule. So does dropping unclaim's, respond's or dismiss's retry commit, or unclaim's skip of a release whose commit failed (TestRoutedWriteRetryCommitsFailedCommit); either earlier no-metadata.json rule, the variable, which leaves the stray database the review reported, or a fixed default database, which fails the read of a target setup named after the variable (TestAutoRouteMissWithoutMetadataIgnoresEnv and TestAutoRouteTargetDatabase), and taking the first of several databases (TestAutoRouteTargetDatabase); and bdEnv's BD_ROUTING_MODE drop, on a host that exports BD_ROUTING_MODE=off (both embedded tests). The CHANGELOG entry now records that every auto-route opens writable for the commands that change an existing issue, the unclaim and human respond/dismiss commits, that a routed write never creates the target's database, and the target-database and routing-failure changes. docs/multi-agent/routing.md says that write commands follow every route, contributor, maintainer and default alike, never create the routed repository's database, and refuse a target whose metadata.json is unreadable or names no dolt_database. Both say that an auto-route opens a target with no metadata.json at the one embedded database it holds, or its default database when it holds none or several, while a prefix route always needs the target's dolt_database. That page documents behavior that is not in a release yet, which the docs release-pin decision (engdocs/decisions/2026-07-17-docs-release-pin.md §1) would leave undocumented. The review asked for docs that match the behavior, as feature PRs #6508, #5855, #5997 and #5092 also did, so it is flagged here as a maintainer call. Open, and not changed here. bd close has the same retry gap on base: a re-close of an issue that a failed routed commit left closed counts as already closed and never commits that store (mutatedStores). commitPendingIfEmbedded gates on the launcher's mode (isEmbeddedMode), not the routed store's, so a server-mode launcher that opens an embedded routed repository would leave the write uncommitted there. That gate is shared by every routed write command and is not exercised here. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> * ci(shards): list TestDatabases in the 40-shard embedded storage manifest The routed-write hardening added TestDatabases to internal/storage/embeddeddolt/detection_test.go without a slot in the Bazel-only 40-shard block of .github/scripts/embedded-storage-test-shards.txt, so gen_embedded_storage_shard_manifest.py 40 --weights=duration --check reported it missing and TestStorageEmbeddedShardManifestGeneratorNotStale (go test ./scripts) failed. Regenerated with the repository command (gen_embedded_storage_shard_manifest.py 40 --weights=duration --write); the incremental pack adds exactly one line, on shard 25. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> --------- Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: matt wilkie <maphew@gmail.com> Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
521 lines
17 KiB
Go
521 lines
17 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/workapi"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
var humanCmd = &cobra.Command{
|
|
Use: "human",
|
|
GroupID: "setup",
|
|
Short: "Show essential commands for human users",
|
|
Long: `Display a focused help menu showing only the most common commands.
|
|
|
|
bd has 70+ commands - many for AI agents, integrations, and advanced workflows.
|
|
This command shows the ~15 essential commands that human users need most often.
|
|
|
|
For the full command list, run: bd --help
|
|
|
|
SUBCOMMANDS:
|
|
human list List human-needed beads (issues with 'human' label; hides closed by default)
|
|
human respond <id> Respond to a human-needed bead (adds comment and closes)
|
|
human dismiss <id> Dismiss a human-needed bead permanently
|
|
human stats Show summary statistics for human-needed beads`,
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
evt := metrics.NewCommandEvent("human")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
fmt.Printf("\n%s\n", ui.RenderBold("bd - Essential Commands for Humans"))
|
|
fmt.Printf("For all 70+ commands: bd --help\n\n")
|
|
|
|
// Issues - Core workflow
|
|
fmt.Printf("%s\n", ui.RenderAccent("Working With Issues:"))
|
|
printCmd("create", "Create a new issue")
|
|
printCmd("list", "List issues (filter with --status, --priority, --label)")
|
|
printCmd("show <id>", "Show issue details")
|
|
printCmd("update <id>", "Update an issue (--status, --priority, --assignee)")
|
|
printCmd("close <id>", "Close one or more issues")
|
|
printCmd("reopen <id>", "Reopen a closed issue")
|
|
printCmd("note <id> <text>", "Add a note to an issue (or: comments add <id>)")
|
|
fmt.Println()
|
|
|
|
// Workflow
|
|
fmt.Printf("%s\n", ui.RenderAccent("Finding Work:"))
|
|
printCmd("ready", "Show issues ready to work on (no blockers)")
|
|
printCmd("search <query>", "Search issues by text")
|
|
printCmd("status", "Show project overview and counts")
|
|
printCmd("stats", "Show detailed statistics")
|
|
fmt.Println()
|
|
|
|
// Dependencies
|
|
fmt.Printf("%s\n", ui.RenderAccent("Dependencies:"))
|
|
printCmd("dep add <a> <b>", "Add dependency (a depends on b)")
|
|
printCmd("dep remove <a> <b>", "Remove a dependency")
|
|
printCmd("dep tree <id>", "Show dependency tree")
|
|
printCmd("graph", "Display visual dependency graph")
|
|
printCmd("blocked", "Show all blocked issues")
|
|
fmt.Println()
|
|
|
|
// Setup & Maintenance
|
|
fmt.Printf("%s\n", ui.RenderAccent("Setup & Maintenance:"))
|
|
printCmd("init", "Initialize bd in current directory")
|
|
printCmd("doctor", "Check installation health")
|
|
fmt.Println()
|
|
|
|
// Help
|
|
fmt.Printf("%s\n", ui.RenderAccent("Getting Help:"))
|
|
printCmd("quickstart", "Quick start guide with examples")
|
|
printCmd("help <cmd>", "Help for any command")
|
|
printCmd("--help", "Full command list (70+ commands)")
|
|
fmt.Println()
|
|
|
|
// Common examples
|
|
fmt.Printf("%s\n", ui.RenderAccent("Quick Examples:"))
|
|
fmt.Printf(" %s\n", ui.RenderMuted("# Create and track an issue"))
|
|
fmt.Printf(" bd create \"Fix login bug\" --priority 1\n")
|
|
fmt.Printf(" bd update bd-abc123 --claim\n")
|
|
fmt.Printf(" bd close bd-abc123\n\n")
|
|
|
|
fmt.Printf(" %s\n", ui.RenderMuted("# See what needs doing"))
|
|
fmt.Printf(" bd ready # What can I work on?\n")
|
|
fmt.Printf(" bd list --status open # All open issues\n")
|
|
fmt.Printf(" bd blocked # What's stuck?\n\n")
|
|
},
|
|
}
|
|
|
|
// human list command
|
|
var humanListCmd = &cobra.Command{
|
|
Use: "list",
|
|
Short: "List human-needed beads",
|
|
Long: `List issues labeled with 'human' tag.
|
|
|
|
These are issues that require human intervention or input. Every
|
|
human-labeled bead shows regardless of type (including gates and wisps).
|
|
By default closed, pinned, and other done/frozen beads are hidden; use
|
|
--status to select specific statuses, or --status=all to include every
|
|
status.
|
|
|
|
Examples:
|
|
bd human list
|
|
bd human list --status=closed
|
|
bd human list --status=all
|
|
bd human list --json`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("human-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
status, _ := cmd.Flags().GetString("status")
|
|
|
|
issues, err := humanIssues(rootCtx, status)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("listing human beads: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
// SearchIssues already hydrated .Labels on both backends (the
|
|
// filter never sets SkipLabels), so the issues marshal with their
|
|
// labels attached.
|
|
data, err := json.MarshalIndent(issues, "", " ")
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("encoding JSON: %v", err)
|
|
}
|
|
fmt.Println(string(data))
|
|
return nil
|
|
}
|
|
|
|
printHumanList(issues)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// humanIssues loads the human-labeled beads matching the status selector
|
|
// through whichever backend this invocation uses: the direct store, or a
|
|
// proxied-server unit of work. Both routes apply the same humanListFilter.
|
|
func humanIssues(ctx context.Context, status string) ([]*types.Issue, error) {
|
|
if usesProxiedServer() {
|
|
return proxiedHumanIssues(ctx, status)
|
|
}
|
|
|
|
if err := ensureStoreActive(); err != nil {
|
|
return nil, err
|
|
}
|
|
cfg, err := workapi.LoadStoreListConfig(ctx, store)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("loading status configuration: %w", err)
|
|
}
|
|
filter, err := humanListFilter(status, cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return store.SearchIssues(ctx, "", filter)
|
|
}
|
|
|
|
// humanListRequest builds the list request for "human list": every
|
|
// human-labeled bead regardless of type — a human label is an explicit
|
|
// request for a person's attention, and this command is the only place a
|
|
// person sees it, so gates, wisps, infra beads, and templates all show.
|
|
// Status filtering matches `bd list`: done/frozen statuses and pinned beads
|
|
// are hidden by default, an explicit --status selects specific statuses
|
|
// (validated against the built-in and custom status names), and "all" lifts
|
|
// the status defaults entirely.
|
|
func humanListRequest(status string) issueops.ListRequest {
|
|
unlimited := 0
|
|
req := issueops.ListRequest{
|
|
Labels: []string{"human"},
|
|
Limit: &unlimited, // human list has never paginated; 0 = unlimited
|
|
// No bead type is hidden from a human listing.
|
|
IncludeAllTypes: true,
|
|
}
|
|
req.Status = status // "" applies the defaults; "all" lifts them
|
|
return req
|
|
}
|
|
|
|
// humanListFilter resolves humanListRequest against loaded status/type config.
|
|
func humanListFilter(status string, cfg workapi.ListConfig) (types.IssueFilter, error) {
|
|
return workapi.BuildListFilter(humanListRequest(status), cfg)
|
|
}
|
|
|
|
// warnIfNotHumanLabeled warns on stderr when the bead lacks the 'human'
|
|
// label. The check is advisory — respond/dismiss act on whichever bead the
|
|
// user named. The issue must carry its labels; anything returned by
|
|
// GetIssue/resolveAndGetIssueForMutation does.
|
|
func warnIfNotHumanLabeled(issue *types.Issue) {
|
|
if !slices.Contains(issue.Labels, "human") {
|
|
fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issue.ID)
|
|
}
|
|
}
|
|
|
|
func printHumanList(issues []*types.Issue) {
|
|
if len(issues) == 0 {
|
|
fmt.Println("No human-needed beads found.")
|
|
return
|
|
}
|
|
|
|
fmt.Printf("\n%s (%d found)\n\n", ui.RenderBold("Human-needed beads"), len(issues))
|
|
for _, issue := range issues {
|
|
if issue.Status == types.StatusClosed {
|
|
// Closed items fade to muted gray, matching bd list/query. They
|
|
// only appear under an explicit --status, so the fade is what
|
|
// distinguishes them from the work still waiting on a person.
|
|
fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("%s %s", issue.ID, issue.Title)))
|
|
fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("Status: %s", issue.Status)))
|
|
fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("Priority: P%d", issue.Priority)))
|
|
fmt.Println()
|
|
continue
|
|
}
|
|
fmt.Printf(" %s %s\n", ui.RenderCommand(issue.ID), issue.Title)
|
|
if issue.Status != "open" {
|
|
fmt.Printf(" Status: %s\n", issue.Status)
|
|
}
|
|
fmt.Printf(" Priority: %s\n", ui.RenderPriorityForStatus(issue.Priority, string(issue.Status)))
|
|
fmt.Println()
|
|
}
|
|
}
|
|
|
|
// human respond command
|
|
var humanRespondCmd = &cobra.Command{
|
|
Use: "respond <issue-id> [response...]",
|
|
Short: "Respond to a human-needed bead",
|
|
Long: `Respond to a human-needed bead by adding a comment and closing it.
|
|
|
|
The response is added as a comment and the issue is closed with reason "Responded".
|
|
The response text can be given as positional arguments, --response, --file, or --stdin.
|
|
|
|
Examples:
|
|
bd human respond bd-123 "Use OAuth2 for authentication"
|
|
bd human respond bd-123 -r "Approved, proceed with implementation"
|
|
bd human respond bd-123 --file response.md
|
|
echo "Approved" | bd human respond bd-123 --stdin`,
|
|
Args: cobra.MinimumNArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("human respond")
|
|
|
|
evt := metrics.NewCommandEvent("human-respond")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
src := cmdTextSources(cmd, args[1:])
|
|
src.flagText, _ = cmd.Flags().GetString("response")
|
|
src.flagName = "--response"
|
|
src.flagSet = cmd.Flags().Changed("response")
|
|
response, err := requireTextFromSources("response text", "use positional args, --response, --file, or --stdin", src)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
ctx := rootCtx
|
|
issueID := args[0]
|
|
// Formatted once here so the direct and proxied backends store
|
|
// identically-shaped comments.
|
|
commentText := fmt.Sprintf("Response: %s", response)
|
|
|
|
if usesProxiedServer() {
|
|
return runHumanRespondProxiedServer(ctx, issueID, commentText)
|
|
}
|
|
|
|
// Direct mode
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleErrorRespectJSON("responding to human bead: %v", err)
|
|
}
|
|
|
|
// Resolve partial ID and get issue
|
|
result, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving issue ID %s: %v", issueID, err)
|
|
}
|
|
if result == nil || result.Issue == nil {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
return HandleErrorRespectJSON("issue not found: %s", issueID)
|
|
}
|
|
defer result.Close()
|
|
|
|
resolvedID := result.ResolvedID
|
|
issue := result.Issue
|
|
targetStore := result.Store
|
|
|
|
if issue.Status == "closed" {
|
|
// A response whose routed commit failed left its close in the
|
|
// target's working set, where this run finds the issue closed.
|
|
// Nothing else commits a routed target, so commit the close here.
|
|
if err := commitRoutedWrite(ctx, result, "human respond"); err != nil {
|
|
return HandleErrorRespectJSON("issue %s is already closed; committing its routed close failed: %v", resolvedID, err)
|
|
}
|
|
return HandleErrorRespectJSON("issue %s is already closed", resolvedID)
|
|
}
|
|
|
|
warnIfNotHumanLabeled(issue)
|
|
|
|
_, err = targetStore.AddIssueComment(ctx, resolvedID, currentActor(), commentText)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("adding comment: %v", err)
|
|
}
|
|
|
|
if err := targetStore.CloseIssue(ctx, resolvedID, "Responded", currentActor(), ""); err != nil {
|
|
return HandleErrorRespectJSON("closing bead: %v", err)
|
|
}
|
|
|
|
if err := commitRoutedWrite(ctx, result, "human respond"); err != nil {
|
|
return HandleErrorRespectJSON("committing response to %s: %v", resolvedID, err)
|
|
}
|
|
|
|
fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("✔"), resolvedID)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// human dismiss command
|
|
var humanDismissCmd = &cobra.Command{
|
|
Use: "dismiss <issue-id> [reason...]",
|
|
Short: "Dismiss a human-needed bead",
|
|
Long: `Dismiss a human-needed bead permanently without responding.
|
|
|
|
The issue is closed with a "Dismissed" reason and optional note.
|
|
The reason can be given as positional arguments or --reason.
|
|
|
|
Examples:
|
|
bd human dismiss bd-123
|
|
bd human dismiss bd-123 "No longer applicable"
|
|
bd human dismiss bd-123 --reason "No longer applicable"`,
|
|
Args: cobra.MinimumNArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("human dismiss")
|
|
|
|
evt := metrics.NewCommandEvent("human-dismiss")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
reasonFlag, _ := cmd.Flags().GetString("reason")
|
|
|
|
// A dismissal reason is optional, so this is textFromSources rather
|
|
// than requireTextFromSources: no source at all is fine, but naming
|
|
// two is still the same hard error every other text input gives.
|
|
reason, _, err := textFromSources(textSources{
|
|
flagText: reasonFlag,
|
|
flagName: "--reason",
|
|
flagSet: cmd.Flags().Changed("reason"),
|
|
positional: args[1:],
|
|
})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
reason = strings.TrimSpace(reason)
|
|
|
|
closeReason := dismissedCloseReason
|
|
if reason != "" {
|
|
closeReason = fmt.Sprintf("%s: %s", dismissedCloseReason, reason)
|
|
}
|
|
|
|
ctx := rootCtx
|
|
issueID := args[0]
|
|
|
|
if usesProxiedServer() {
|
|
return runHumanDismissProxiedServer(ctx, issueID, closeReason)
|
|
}
|
|
|
|
// Direct mode
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleErrorRespectJSON("dismissing human bead: %v", err)
|
|
}
|
|
|
|
// Resolve partial ID and get issue
|
|
result, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving issue ID %s: %v", issueID, err)
|
|
}
|
|
if result == nil || result.Issue == nil {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
return HandleErrorRespectJSON("issue not found: %s", issueID)
|
|
}
|
|
defer result.Close()
|
|
|
|
resolvedID := result.ResolvedID
|
|
issue := result.Issue
|
|
targetStore := result.Store
|
|
|
|
if issue.Status == "closed" {
|
|
// As in respond: commit a dismissal whose routed commit failed.
|
|
if err := commitRoutedWrite(ctx, result, "human dismiss"); err != nil {
|
|
return HandleErrorRespectJSON("issue %s is already closed; committing its routed close failed: %v", resolvedID, err)
|
|
}
|
|
return HandleErrorRespectJSON("issue %s is already closed", resolvedID)
|
|
}
|
|
|
|
warnIfNotHumanLabeled(issue)
|
|
|
|
if err := targetStore.CloseIssue(ctx, resolvedID, closeReason, currentActor(), ""); err != nil {
|
|
return HandleErrorRespectJSON("closing bead: %v", err)
|
|
}
|
|
|
|
if err := commitRoutedWrite(ctx, result, "human dismiss"); err != nil {
|
|
return HandleErrorRespectJSON("committing dismissal of %s: %v", resolvedID, err)
|
|
}
|
|
|
|
fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("✔"), resolvedID)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// human stats command
|
|
var humanStatsCmd = &cobra.Command{
|
|
Use: "stats",
|
|
Short: "Show summary statistics for human-needed beads",
|
|
Long: `Display summary statistics for human-needed beads.
|
|
|
|
Shows counts for total, pending (open), responded (closed without dismiss),
|
|
and dismissed beads.
|
|
|
|
Example:
|
|
bd human stats`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("human-stats")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
// The stats universe is `human list --status=all`: every human-labeled
|
|
// bead, every status, every type.
|
|
issues, err := humanIssues(rootCtx, "all")
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("getting human bead stats: %v", err)
|
|
}
|
|
|
|
printHumanStats(issues)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// dismissedCloseReason prefixes the close reason `human dismiss` writes;
|
|
// printHumanStats classifies dismissed beads by this same prefix so the
|
|
// writer and the classifier cannot drift apart.
|
|
const dismissedCloseReason = "Dismissed"
|
|
|
|
func printHumanStats(issues []*types.Issue) {
|
|
total := len(issues)
|
|
pending := 0
|
|
closed := 0
|
|
dismissed := 0
|
|
|
|
for _, issue := range issues {
|
|
switch issue.Status {
|
|
case "closed":
|
|
closed++
|
|
if strings.HasPrefix(issue.CloseReason, dismissedCloseReason) {
|
|
dismissed++
|
|
}
|
|
default:
|
|
// All non-closed statuses (open, in_progress, blocked, hooked, etc.) are pending
|
|
pending++
|
|
}
|
|
}
|
|
|
|
responded := closed - dismissed
|
|
|
|
fmt.Printf("\n%s\n", ui.RenderBold("Human Beads Stats"))
|
|
fmt.Println()
|
|
fmt.Printf(" Total: %d\n", total)
|
|
fmt.Printf(" Pending: %d\n", pending)
|
|
fmt.Printf(" Responded: %d\n", responded)
|
|
fmt.Printf(" Dismissed: %d\n", dismissed)
|
|
fmt.Println()
|
|
}
|
|
|
|
// printCmd prints a command with consistent formatting
|
|
func printCmd(cmd, description string) {
|
|
fmt.Printf(" %-20s %s\n", ui.RenderCommand(cmd), description)
|
|
}
|
|
|
|
func init() {
|
|
// Add subcommands to humanCmd
|
|
humanCmd.AddCommand(humanListCmd)
|
|
humanCmd.AddCommand(humanRespondCmd)
|
|
humanCmd.AddCommand(humanDismissCmd)
|
|
humanCmd.AddCommand(humanStatsCmd)
|
|
|
|
// Add flags for subcommands
|
|
humanListCmd.Flags().StringP("status", "s", "", "Filter by status (open, closed, etc.; comma-separated for multiple, 'all' for every status)")
|
|
humanRespondCmd.Flags().StringP("response", "r", "", "Response text")
|
|
registerTextSourceFlags(humanRespondCmd, "response text", "response")
|
|
humanDismissCmd.Flags().StringP("reason", "", "", "Reason for dismissal (optional)")
|
|
|
|
// Register with root command
|
|
rootCmd.AddCommand(humanCmd)
|
|
}
|