* fix(routing): bind role detection to the -C target repo (re-port of #4242) Role detection previously called routing.DetectUserRole(".") directly, which resolves against the caller's CWD rather than the repo selected via `bd -C <target>` (BEADS_DIR-driven). This meant auto-routing and role-based behavior could silently apply the wrong repo's role when invoked with -C. Introduce activeRepoPathForRouting(), which prefers beads.GetRepoContext().RepoRoot (the BEADS_DIR-bound target) and falls back to the parent of beads.FindBeadsDir(), then to ".". Route role detection in cmd/bd/create.go and cmd/bd/routing_read.go through the new detectUserRoleForActiveRepo() helper instead of calling routing.DetectUserRole(".") directly. Faithful re-port of gastownhall/beads#4242 (osamu2001) onto current main: determineAutoRoutedRepoPath's signature changed to (string, routing.RoutingRule) since the PR was opened (89a4d6ed8/ #4866), so the one-line call-site change re-applies inside the new function body, and the new routing_read_test.go coverage destructures both return values. All other ported content (routing_role.go, context_binding_test.go, the create.go call site) is unchanged from the original PR. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * test(routing): fix the sole CI failure in the re-ported #4242 test TestActiveRepoPathForRoutingFallsBackToBeadsDirParent created its fake project under this repo's tree, so beads.GetRepoContext() resolved a real repo root from the caller's CWD and the FindBeadsDir fallback the test claimed to cover was never exercised — an unreachable assertion that CI reproduced as the PR's only failing test. Rewrite it to target a directory that is genuinely outside any git repo: targetDir now comes from t.TempDir() (its .beads/config.yaml still written via writeTestConfigYAML), and the caller CWD is also moved to a fresh t.TempDir() via t.Chdir() so GetRepoContext() can't resolve through the CWD either. Both resolve under os.TempDir(), which internal/beads/context.go's isPathInSafeBoundary explicitly admits, so this stays safe under the existing boundary check. This makes safeTempDirForContextTest (the manual git-repo-relative temp dir helper the original test used to dodge the same problem) dead code; delete it. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): a .beads/redirect must not move role detection to the storage root Cross-vendor review of e8600e732 caught a regression the re-port would have introduced for redirect users: with a .beads/redirect pointing at storage outside any git repo, RepoContext.RepoRoot is the redirect target's parent, so beads.role would be read from the storage location instead of the workspace repo — silently bypassing contributor routing. The two external-BeadsDir shapes now get their opposite answers explicitly: an explicit BEADS_DIR selection (what bd -C plumbs) binds role detection to the selected project (the GH#4242 fix), while a followed redirect keeps it on the CWD workspace repo (pre-existing semantics — a redirect relocates storage, not the project). Mutation-tested: with the guard removed, the new test fails by resolving to the storage root. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): read BEADS_DIR selection provenance at startup, not the live env var The self-review on this PR found a startup-path gap: rootCmd's PersistentPreRunE calls prepareSelectedCommandContext for every command, which sets BEADS_DIR to the resolved target — redirects included. By the time role detection ran, activeRepoPathForRouting's os.Getenv("BEADS_DIR") check was therefore always true, classifying a plain .beads/redirect as explicit selection and binding beads.role to the storage root instead of the workspace repo. Capture whether BEADS_DIR was present in the environment at process start, and treat selection as explicit only for that case or a -C flag. The new TestActiveRepoPathForRoutingSurvivesStartupRebindAcrossRedirect goes through the real startup rebind with a real redirect and fails on the previous logic; the two tests that simulate a caller-exported BEADS_DIR now pin their provenance explicitly. Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): .env-provided BEADS_DIR is user selection, mark its provenance Cross-vendor review of the previous commit caught a regression it would have introduced: loadBeadsSelectionEnvFile intentionally lets a project's .beads/.env route commands via BEADS_DIR, and that selection happens after the process-start snapshot. Flip the provenance flag when the selector loader sets BEADS_DIR, so .env routing keeps binding role detection to the selected project. TestActiveRepoPathForRoutingHonorsEnvFileSelection pins it end to end through loadSelectionEnvironment. Agent-Signature: claude-fable-5-high on behalf of maphew * test(routing): make the BeadsDir-parent fallback test order-robust on macOS The macOS CI leg failed on /private/var vs /var: the test asserted a raw string path while resolution can hand back the canonicalized spelling of the same directory depending on which branch wins under test ordering. Compare through EvalSymlinks like the sibling redirect tests, and pin selection provenance in the two tests that had not declared theirs. Agent-Signature: claude-fable-5-high on behalf of maphew * ci: retrigger - dolt-install/download infra outage (curl 56/503) killed 4 jobs Agent-Signature: claude-fable-5-high on behalf of maphew * build(bazel): enumerate cmd/bd/routing_role.go in bd_lib srcs The PR adds cmd/bd/routing_role.go, whose detectUserRoleForActiveRepo is called from create.go and routing_read.go. cmd/bd/BUILD.bazel lists go_library srcs explicitly, so the unenumerated new file broke the Bazel library compile: cmd/bd/create.go:303:21: undefined: detectUserRoleForActiveRepo cmd/bd/routing_read.go:52:19: undefined: detectUserRoleForActiveRepo Generated by `bazel run //:gazelle` (one srcs row, idempotent; no deps row owed because the library already carries internal/beads and internal/routing). Base parity at89348699b0was 336/336 non-test .go files enumerated in cmd/bd, so the gap was PR-introduced, not pre-existing. * fix(routing): bind role to the selected workspace across a .beads/redirect Maintainer review fixup for the adopted PR (review iterations 1 to 3). Iteration 1 addressed the one gating major plus both minors and both nits from its review synthesis. Iteration 2 addressed the major, the minor and the nit that the next synthesis raised against that fixup, and iteration 3 addresses the minor and the nit raised against iteration 2; see "Review iteration 2" and "Review iteration 3" below. The major: routing_role.go ordered its guard `explicitBeadsSelection() || !rc.IsRedirected`, but every beads-dir resolver follows a .beads/redirect before that guard can run (ExplicitBeadsDir via FollowRedirect, FindBeadsDir, and -C's own resolution). So an explicit selection of a REDIRECTED workspace arrived already rewritten to the storage root, short-circuited the redirect doctrine the PR had just written, and bound beads.role to wherever the DATA lives — the same misroute GH#4242 reported, one resolution step further in. Worse, it was silent: `git config --get beads.role` succeeds outside a repo by reading GLOBAL config, and routing.DetectUserRole returns on that first success, so its own "beads.role not configured" notice never fired and a contributor workspace could be routed with the user's global role with no diagnostic on any stream. The remedy has to be anchored per shape, because the two selection shapes carry the pre-redirect directory in different places: - `bd -C <dir>`: applyChangeDirSelection has already rewritten BEADS_DIR to the resolved target, so only the -C argument still names the chosen project. CWD-anchored GetRedirectInfo() cannot see this case at all — under -C the CWD is some unrelated directory — so this arm asks GetRedirectInfoFrom(dir), which is documented for exactly this case (GH#5509) and deliberately does not consult BEADS_DIR. - exported BEADS_DIR: here the CWD *is* the selected workspace, so the CWD-anchored probe is the correct one. The selection is vacuous when it merely names that workspace's own redirect, under both spellings of it: BEADS_DIR=<workspace>/.beads and BEADS_DIR=<storage>/.beads both arrive as the storage dir (the bd-wayc3 tooling shape), so both fall through to rc.CWDRepoRoot. An explicit selection of a genuinely different, non-redirected project still wins — that is the GH#4242 fix itself, and a control test pins it. Also in this commit: - A role path that is not a git repository now warns instead of quietly inheriting global beads.role (new beads.RepoRootFor answers both "what is the repo root for this dir" and "is this a repo at all"). - A .env-provided BEADS_DIR records selection provenance on the broad loader too, not only via loadBeadsSelectionEnvFile. That loader early-returns whenever BEADS_DB or BD_DB is already exported, and loadBeadsEnvFile then imports the same .env line, so one .env line meant target-role or CWD-role depending on the caller's unrelated BEADS_DB export. Internal rebinds are unaffected: the marking is conditional on BEADS_DIR having been unset, which is what separates user selection from prepareSelectedCommandContext's per-command rebind. - The four-way role-path choice is logged via debug.Logf, since the downstream "failed to detect user role" warning fires on none of those branches. - The PR's new routing test neutralizes BEADS_ROUTING_MODE / BD_ROUTING_MODE, which viper binds onto the routing.mode key and which reds the test on any host that exports them. - routing_role.go now cross-references RepoContext.Role(), the second, known-divergent role oracle in internal/beads. No behavior change there. Tests: the explicit x redirect cell was the one combination the PR's new tests left empty. Both probe shapes land as tests, plus the `bd -C <redirected-ws>` shape, a non-redirected -C control, the non-repo warning, and both provenance polarities. Each new pin was verified to FAIL against the pre-fix code. Review iteration 2: - Major: the non-repo warning above ran inside detectUserRoleForActiveRepo, which create.go and determineAutoRoutedRepoPath called before resolving the routing config. Routing is off by default and only auto mode reads the role, so in any non-git beads project every bd create/list/ready printed a 4-line warning about a role nothing used. The leak also broke six TestParity* characterization tests at the iteration-1 head: CreateHumanOutput, CreateOnOccupiedIDRefuses, CreateParentNotFoundExits1, CreateMissingDepTargetIsFatal, CreateJSONErrorShape and ReopenErrorExits1Silently. Detection now runs only when the fully resolved config can use its answer: new RoutingConfig.UsesUserRole (auto mode, no explicit override, a role-specific repo configured) gates the new detectUserRoleForRouting, which both call sites invoke after building the config, so the legacy contributor.auto_route=true fallback to auto counts where a raw routing.mode check would miss it. Side effect: routing's own GH#2950 "beads.role not configured" notice is also skipped when routing cannot use the role, as docs/multi-agent/routing.md already promises when it calls `routing.mode explicit` "disabling role detection entirely". - Minor: for an exported BEADS_DIR, selectedWorkspaceRepoRoot called the selection vacuous when the CWD-anchored GetRedirectInfo reported a redirect to it. With no redirect in the CWD repo, GetRedirectInfo falls back to the raw BEADS_DIR, so a FOREIGN redirected workspace vouched for its own redirect and the CWD repo's role was bound. The check now also requires the redirect to sit in the CWD repo's own .beads (RedirectInfo.LocalDir). A foreign redirected selection falls through to its storage root, which is the answer a live command already reaches after the pre-RunE rebind, so unit and command behavior agree. Binding the foreign workspace itself would need the raw startup BEADS_DIR, which nothing keeps; the routing_role.go comment records that limit. - Nit: the non-repo warning prints at most once per process. An ID lookup falls back to auto-routing once per missing ID, and each fallback re-ran detection. - Test isolation: the PR makes role detection read the process-wide beads.GetRepoContext() cache, a sync.Once. Three existing tests chdir between temp repos without resetting it and so read beads.role from an earlier test's deleted repo: TestResolveCloseTargets/ contributor_mixed_local_and_routed, TestDetermineAutoRoutedRepoPath_ContributorToPlanning and TestOpenRoutedReadStore_ContributorRouting fail in a broad cmd/bd run at86b8abff3fand 8dbfc6c721 and pass at base89348699b0. The failure is order-dependent, and the tests skip without a Dolt test server. Each now rebuilds the cache after its chdir, as does the MaintainerToPlanning sibling, which has the same exposure. Iteration-2 tests: a property test pins UsesUserRole to DetermineTargetRepoWithRule (true exactly when the answer varies by role, across unset/auto/explicit modes and every override and repo combination). A table test covers routing unset, explicit mode, auto without a role repo, auto, and legacy auto_route. Two more cover the foreign redirected BEADS_DIR cell and repeated detection (the once-guard). Each pin was mutation-checked: dropping the gate, gating on the raw mode, or dropping the LocalDir guard, the once-guard, the role-repo clause or the override clause turns a test red. Validated (iteration 1): gofmt, go build ./..., go vet ./cmd/bd/ ./internal/beads/, focused go test over cmd/bd role/routing/envfile/context tests and ./internal/beads/ ./internal/routing/, gazelle (0 srcs rows owed), and bazel build //cmd/bd:bd_lib //internal/beads:beads. Validated (iteration 2): gofmt, git diff --check, go build ./..., go vet ./cmd/bd/ ./internal/routing/ ./internal/beads/ with and without cgo, golangci-lint v2.10.1 --new-from-rev=HEAD on cmd/bd and internal/routing (0 issues), go test ./internal/routing/ ./internal/beads/, and a broad cmd/bd routing/role/redirect/context/Parity run. The only reds on this host, TestInitRedirect/RedirectCreatesDBInTarget, TestBareParentWorktreeCoreCommandsWithoutRedirect and TestServeIssueRolesComeFromBeneathTheHookDecorator, fail the same way at base89348699b0. No files were added and the only new import is stdlib, so no BUILD.bazel change is owed. Review iteration 3: - Minor: the iteration-2 guard counted a redirect as the CWD workspace's own only when it sat in the CWD git root's .beads (Dir(LocalDir) == rc.CWDRepoRoot), which equates the workspace with the git root. From a workspace nested below its repo root (<repo>/sub/.beads/redirect), or from a git worktree that inherits its main checkout's redirect, exporting that workspace's own .beads therefore moved role detection from the CWD repo to the storage root: the env-dependent inconsistency the iteration-1 vacuous rule exists to remove. Dropping the guard would not have fixed it. When the repo root's .beads holds no redirect, GetRedirectInfo checks BEADS_DIR itself, and prepareSelectedCommandContext has rebound BEADS_DIR to the storage .beads before RunE. After that rebind GetRedirectInfo finds no redirect in either shape, so the iteration-1 rule bound the storage root there too. New beads.GetDiscoveredRedirectInfo is GetRedirectInfo without the BEADS_DIR override: the redirect discovery finds from the CWD (the repo root's .beads, then the worktree-local redirect, the main checkout's .beads for a worktree, and the walk-up from the CWD), via findDiscoveredLocalBeadsDir, the BEADS_DIR-free half of findLocalBeadsDir. The exported-BEADS_DIR arm now calls a selection vacuous exactly when that discovered redirect exists and targets the selected storage. A foreign redirected selection still falls through to its storage root, because discovery from the CWD finds no redirect or one with a different target. - Nit: the foreign-selection test's comment now says only the exported arm pins the guard. The rebound storage .beads holds no redirect, so the rebind arm only checks that both states of the variable agree. Iteration-3 tests: nested-workspace and worktree-without-own-.beads cells, each with BEADS_DIR unset, as exported, and as rebound before RunE. Against the unchanged 07c7373dfb code the four set-BEADS_DIR cells fail and both unset controls pass. A new test pins the target comparison: from a redirected workspace, an exported BEADS_DIR naming a different, non-redirected project still binds that project. TestGetDiscoveredRedirectInfo pins the new API against GetRedirectInfo in both directions (a nested redirect that BEADS_DIR masks, and a BEADS_DIR redirect the CWD does not hold). Five mutants each turn a test red: probing with GetRedirectInfo again (the iteration-1 rule, which fails both rebind cells and the foreign test), dropping the target comparison, dropping the worktree-fallback tier, letting discovery honor BEADS_DIR, and restoring the git-root guard. Validated (iteration 3): gofmt, git diff --check, go build ./..., go vet ./cmd/bd/ ./internal/beads/ ./internal/routing/, golangci-lint v2.10.1 --new-from-rev=HEAD on cmd/bd and internal/beads (0 issues), go test ./internal/beads/ ./internal/routing/, and a focused cmd/bd run over the role, routing, redirect, envfile and context-binding tests against the Dolt test server (47 passed, 0 failed, 0 skipped). No files were added, so no BUILD.bazel change is owed. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1102 lines
43 KiB
Go
1102 lines
43 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/debug"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/remotecache"
|
|
"github.com/steveyegge/beads/internal/routing"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/dolt"
|
|
"github.com/steveyegge/beads/internal/timeparsing"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"github.com/steveyegge/beads/internal/validation"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// validateCreateArgs runs as cobra's Args validation, which executes before
|
|
// PersistentPreRunE opens the store or runs migrations. It reuses
|
|
// resolveTitle — the same shared validator gatherCreateInput calls for the
|
|
// proxied-server create path — so a whitespace-only title (GH#4771) is
|
|
// rejected identically for both backends, and before any invocation that is
|
|
// guaranteed to fail wastes a store open/migration.
|
|
func validateCreateArgs(cmd *cobra.Command, args []string) error {
|
|
markdownFile, _ := cmd.Flags().GetString("file")
|
|
graphFile, _ := cmd.Flags().GetString("graph")
|
|
titleFlag, _ := cmd.Flags().GetString("title")
|
|
|
|
_, err := resolveTitle(args, titleFlag, markdownFile, graphFile)
|
|
return err
|
|
}
|
|
|
|
var createCmd = &cobra.Command{
|
|
Use: "create [title]",
|
|
GroupID: "issues",
|
|
Aliases: []string{"new"},
|
|
Short: "Create a new issue (or batch from markdown/graph JSON)",
|
|
Args: cobra.MatchAll(cobra.MaximumNArgs(1), validateCreateArgs),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("create") // also covers the migration freeze check (dc-6jaq)
|
|
|
|
evt := metrics.NewCommandEvent("create")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
in, err := gatherCreateInput(cmd, args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return runCreateProxiedServer(cmd, rootCtx, in)
|
|
}
|
|
file, _ := cmd.Flags().GetString("file")
|
|
graphFile, _ := cmd.Flags().GetString("graph")
|
|
|
|
if file != "" {
|
|
// gatherCreateInput repeats the --file argument checks and applies
|
|
// the plan-wide flags this route used to accept and ignore
|
|
// (--ephemeral, --no-history, --mol-type, --validate). It is the
|
|
// same input the proxied route reads, which is what lets both build
|
|
// one issueops.CreateBatchRequest.
|
|
in, err := gatherCreateInput(cmd, args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return createIssuesFromMarkdown(rootCtx, in)
|
|
}
|
|
|
|
if graphFile != "" {
|
|
if len(args) > 0 {
|
|
return HandleError("cannot specify both title and --graph flag")
|
|
}
|
|
graphDryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
graphOpts := graphApplyOptionsFromFlags(cmd)
|
|
if err := graphOpts.Validate(); err != nil {
|
|
return HandleError("invalid graph options: %v", err)
|
|
}
|
|
if err := rejectSingleIssueFlagsForGraph(cmd); err != nil {
|
|
return err
|
|
}
|
|
return createIssuesFromGraph(graphFile, graphDryRun, graphOpts)
|
|
}
|
|
|
|
titleFlag, _ := cmd.Flags().GetString("title")
|
|
title, err := resolveTitle(args, titleFlag, "", "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Get silent flag
|
|
silent, _ := cmd.Flags().GetBool("silent")
|
|
|
|
// Warn if creating a test issue in a database with existing issues.
|
|
// A brand-new repo with zero issues is not a "production database" (#2898).
|
|
// store is nil here for `create --repo=<remote URL>` from a directory with
|
|
// no local .beads/: PersistentPreRunE skips local store init entirely for
|
|
// that path, so this check is best-effort only.
|
|
if store != nil && isTestIssue(title) && !silent && !debug.IsQuiet() {
|
|
if stats, err := store.GetStatistics(context.Background()); err == nil && stats != nil && stats.TotalIssues >= 5 {
|
|
fmt.Fprintf(os.Stderr, "%s Creating test issue in production database\n", ui.RenderWarn("⚠"))
|
|
fmt.Fprintf(os.Stderr, " Title: %q appears to be test data\n", title)
|
|
fmt.Fprintf(os.Stderr, " Recommendation: Use isolated test database with --db\n")
|
|
fmt.Fprintf(os.Stderr, " bd --db /tmp/test-beads create %q\n", title)
|
|
}
|
|
}
|
|
|
|
description, descriptionChanged, err := getDescriptionFlag(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := validateDescriptionUpdate(cmd, description, descriptionChanged); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
skills, _ := cmd.Flags().GetString("skills")
|
|
if skills != "" {
|
|
if description != "" {
|
|
description += "\n\n"
|
|
}
|
|
description += "## Required Skills\n" + skills
|
|
}
|
|
|
|
ctxStr, _ := cmd.Flags().GetString("context")
|
|
if ctxStr != "" {
|
|
if description != "" {
|
|
description += "\n\n"
|
|
}
|
|
description += "## Context\n" + ctxStr
|
|
}
|
|
|
|
if description == "" && !isTestIssue(title) {
|
|
if config.GetBool("create.require-description") {
|
|
return HandleError("description is required (set create.require-description: false in config.yaml to disable)")
|
|
}
|
|
}
|
|
|
|
design, _, err := getDesignFlag(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
acceptance, _ := cmd.Flags().GetString("acceptance")
|
|
notes, _ := cmd.Flags().GetString("notes")
|
|
specID, _ := cmd.Flags().GetString("spec-id")
|
|
|
|
priorityStr, _ := cmd.Flags().GetString("priority")
|
|
priority, err := validation.ValidatePriority(priorityStr)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
issueType, _ := cmd.Flags().GetString("type")
|
|
assignee, _ := cmd.Flags().GetString("assignee")
|
|
statusFlag, _ := cmd.Flags().GetString("status")
|
|
if statusFlag != "" {
|
|
if !types.Status(statusFlag).IsValidWithCustom(loadEmbeddedCustomStatuses()) {
|
|
return HandleErrorRespectJSON("invalid status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", statusFlag)
|
|
}
|
|
}
|
|
|
|
labels, _ := cmd.Flags().GetStringSlice("labels")
|
|
labelAlias, _ := cmd.Flags().GetStringSlice("label")
|
|
if len(labelAlias) > 0 {
|
|
labels = append(labels, labelAlias...)
|
|
}
|
|
labels = utils.NormalizeLabels(labels)
|
|
warnLabelsContainingWhitespace(labels)
|
|
|
|
explicitID, _ := cmd.Flags().GetString("id")
|
|
parentID, _ := cmd.Flags().GetString("parent")
|
|
externalRef, _ := cmd.Flags().GetString("external-ref")
|
|
deps, _ := cmd.Flags().GetStringSlice("deps")
|
|
waitsFor, _ := cmd.Flags().GetString("waits-for")
|
|
waitsForGate, _ := cmd.Flags().GetString("waits-for-gate")
|
|
forceCreate, _ := cmd.Flags().GetBool("force")
|
|
repoOverride, _ := cmd.Flags().GetString("repo")
|
|
wisp, _ := cmd.Flags().GetBool("ephemeral")
|
|
noHistory, _ := cmd.Flags().GetBool("no-history")
|
|
if wisp && noHistory {
|
|
return HandleError("--ephemeral and --no-history are mutually exclusive")
|
|
}
|
|
storageClassFlag, _ := cmd.Flags().GetString("storage-class")
|
|
storageClass, wisp, err := resolveCreateStorageClass(storageClassFlag, types.IssueType(issueType), wisp, noHistory)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
molTypeStr, _ := cmd.Flags().GetString("mol-type")
|
|
var molType types.MolType
|
|
if molTypeStr != "" {
|
|
molType = types.MolType(molTypeStr)
|
|
if !molType.IsValid() {
|
|
return HandleError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr)
|
|
}
|
|
}
|
|
|
|
wispTypeStr, _ := cmd.Flags().GetString("wisp-type")
|
|
var wispType types.WispType
|
|
if wispTypeStr != "" {
|
|
wispType = types.WispType(wispTypeStr)
|
|
if !wispType.IsValid() {
|
|
return HandleError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr)
|
|
}
|
|
}
|
|
|
|
eventCategory, _ := cmd.Flags().GetString("event-category")
|
|
eventActor, _ := cmd.Flags().GetString("event-actor")
|
|
eventTarget, _ := cmd.Flags().GetString("event-target")
|
|
eventPayload, _ := cmd.Flags().GetString("event-payload")
|
|
|
|
if (eventCategory != "" || eventActor != "" || eventTarget != "" || eventPayload != "") && issueType != "event" {
|
|
return HandleError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event")
|
|
}
|
|
|
|
var dueAt *time.Time
|
|
dueStr, _ := cmd.Flags().GetString("due")
|
|
if dueStr != "" {
|
|
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
|
|
if err != nil {
|
|
return HandleError("invalid --due format %q. %s", dueStr, deferUntilFormatHint)
|
|
}
|
|
dueAt = &t
|
|
}
|
|
|
|
var deferUntil *time.Time
|
|
deferStr, _ := cmd.Flags().GetString("defer")
|
|
if deferStr != "" {
|
|
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
|
|
if err != nil {
|
|
return HandleError("invalid --defer format %q. %s", deferStr, deferUntilFormatHint)
|
|
}
|
|
// Warn if defer date is in the past (user probably meant future)
|
|
if t.Before(time.Now()) && !silent && !debug.IsQuiet() {
|
|
fmt.Fprintf(os.Stderr, "%s Defer date %q is in the past. Issue will appear in bd ready immediately.\n",
|
|
ui.RenderWarn("!"), t.Local().Format("2006-01-02 15:04"))
|
|
fmt.Fprintf(os.Stderr, " Did you mean a future date? Use --defer=+1h or --defer=tomorrow\n")
|
|
}
|
|
deferUntil = &t
|
|
}
|
|
|
|
var metadata json.RawMessage
|
|
if cmd.Flags().Changed("metadata") {
|
|
metadataValue, _ := cmd.Flags().GetString("metadata")
|
|
parsed, err := readMetadataFlag(metadataValue)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
metadata = parsed
|
|
}
|
|
|
|
validateTemplate, _ := cmd.Flags().GetBool("validate")
|
|
validationMode := config.GetString("validation.on-create")
|
|
if validateTemplate || validationMode == "error" || validationMode == "warn" {
|
|
lintIssue := &types.Issue{
|
|
IssueType: types.IssueType(issueType).Normalize(),
|
|
Description: description,
|
|
AcceptanceCriteria: acceptance,
|
|
}
|
|
if err := validation.LintIssue(lintIssue); err != nil {
|
|
if validateTemplate || validationMode == "error" {
|
|
return HandleError("%v", err)
|
|
}
|
|
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
|
|
}
|
|
}
|
|
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
|
|
var estimatedMinutes *int
|
|
if cmd.Flags().Changed("estimate") {
|
|
est, _ := cmd.Flags().GetInt("estimate")
|
|
if est < 0 {
|
|
return HandleError("estimate must be a non-negative number of minutes")
|
|
}
|
|
estimatedMinutes = &est
|
|
}
|
|
|
|
// Use global jsonOutput set by PersistentPreRun
|
|
|
|
// Determine target repository using routing logic
|
|
repoPath := "." // default to current directory
|
|
if cmd.Flags().Changed("repo") {
|
|
// Explicit --repo flag overrides auto-routing
|
|
repoPath = repoOverride
|
|
} else {
|
|
// Build routing config with backward compatibility for legacy contributor.* keys.
|
|
// Prefer config.yaml values, but fall back to DB config values set by bd init --contributor.
|
|
routingMode := getRoutingConfigValue(rootCtx, store, "routing.mode")
|
|
contributorRepo := getRoutingConfigValue(rootCtx, store, "routing.contributor")
|
|
|
|
// NFR-001: Backward compatibility - fall back to legacy contributor.* keys
|
|
if routingMode == "" {
|
|
if getRoutingConfigValue(rootCtx, store, "contributor.auto_route") == "true" {
|
|
routingMode = "auto"
|
|
}
|
|
}
|
|
if contributorRepo == "" {
|
|
contributorRepo = getRoutingConfigValue(rootCtx, store, "contributor.planning_repo")
|
|
}
|
|
|
|
routingConfig := &routing.RoutingConfig{
|
|
Mode: routingMode,
|
|
DefaultRepo: getRoutingConfigValue(rootCtx, store, "routing.default"),
|
|
MaintainerRepo: getRoutingConfigValue(rootCtx, store, "routing.maintainer"),
|
|
ContributorRepo: contributorRepo,
|
|
ExplicitOverride: repoOverride,
|
|
}
|
|
|
|
// Auto-routing based on user role, detected only once the resolved
|
|
// config shows routing will read it.
|
|
userRole := detectUserRoleForRouting(routingConfig)
|
|
repoPath = routing.DetermineTargetRepo(routingConfig, userRole, ".")
|
|
}
|
|
|
|
renderDryRun := func() error {
|
|
previewIssue := buildCreateIssue(createIssueParams{
|
|
ID: explicitID,
|
|
Title: title,
|
|
Description: description,
|
|
Design: design,
|
|
AcceptanceCriteria: acceptance,
|
|
Notes: notes,
|
|
SpecID: specID,
|
|
Priority: priority,
|
|
IssueType: types.IssueType(issueType).Normalize(),
|
|
Assignee: assignee,
|
|
ExternalRef: externalRef,
|
|
EstimatedMinutes: estimatedMinutes,
|
|
Ephemeral: wisp,
|
|
NoHistory: noHistory,
|
|
StorageClass: storageClass,
|
|
CreatedBy: getActorWithGit(),
|
|
Owner: getOwner(),
|
|
Labels: labels,
|
|
MolType: molType,
|
|
WispType: wispType,
|
|
InitialStatus: statusFlag,
|
|
DueAt: dueAt,
|
|
DeferUntil: deferUntil,
|
|
Metadata: metadata,
|
|
EventKind: eventCategory,
|
|
Actor: eventActor,
|
|
Target: eventTarget,
|
|
Payload: eventPayload,
|
|
})
|
|
|
|
if jsonOutput {
|
|
return outputJSON(previewIssue)
|
|
}
|
|
renderCreateDryRunPreview(previewIssue, labels, deps)
|
|
return nil
|
|
}
|
|
|
|
if dryRun && parentID == "" {
|
|
return renderDryRun()
|
|
}
|
|
|
|
var targetStore storage.DoltStorage
|
|
var remoteCache *remotecache.Cache
|
|
if !dryRun && repoPath != "." {
|
|
if remotecache.IsRemoteURL(repoPath) {
|
|
var err error
|
|
remoteCache, err = remotecache.DefaultCache()
|
|
if err != nil {
|
|
return HandleError("failed to initialize remote cache: %v", err)
|
|
}
|
|
if _, err := remoteCache.Ensure(rootCtx, repoPath); err != nil {
|
|
return HandleError("failed to sync remote %s: %v", repoPath, err)
|
|
}
|
|
targetStore, err = remoteCache.OpenStore(rootCtx, repoPath, newDoltStoreFromConfig)
|
|
if err != nil {
|
|
return HandleError("failed to open remote store: %v", err)
|
|
}
|
|
} else {
|
|
targetBeadsDir := routing.ExpandPath(repoPath)
|
|
debug.Logf("DEBUG: Routing to target repo: %s\n", targetBeadsDir)
|
|
|
|
// Auto-routed paths (routing.mode: auto, routing.default)
|
|
// come from config, not caller input, so they're always
|
|
// allowed to auto-vivify as before; only an explicit --repo
|
|
// flag value can be ambiguous.
|
|
allowCreate := !isAmbiguousRepoTarget(cmd.Flags().Changed("repo"), repoOverride)
|
|
if err := ensureBeadsDirForPath(rootCtx, targetBeadsDir, store, allowCreate); err != nil {
|
|
return HandleError("failed to initialize target repo: %v", err)
|
|
}
|
|
|
|
targetBeadsDirPath := filepath.Join(targetBeadsDir, ".beads")
|
|
var err error
|
|
targetStore, err = newDoltStoreFromConfig(rootCtx, targetBeadsDirPath)
|
|
if err != nil {
|
|
return handleCreateTargetStoreError(err, targetBeadsDirPath, "failed to open target store: %v")
|
|
}
|
|
}
|
|
|
|
// Close the original store before replacing it (it won't be used anymore)
|
|
// Note: We don't defer-close targetStore here because PersistentPostRun
|
|
// will close whatever store is assigned to the global `store` variable.
|
|
// This fixes the "database is closed" error during auto-flush (GH#routing-close-bug).
|
|
if store != nil {
|
|
_ = store.Close() // Best effort cleanup on error path
|
|
}
|
|
|
|
// Replace store for remainder of create operation.
|
|
// Must use setStore to sync cmdCtx.Store — a bare `store = targetStore`
|
|
// leaves cmdCtx.Store pointing at the closed original, which causes
|
|
// "store is closed" in PostRun tip auto-commit (GH#tip-closed-bug).
|
|
setStore(targetStore)
|
|
}
|
|
|
|
if explicitID != "" && parentID != "" {
|
|
return HandleError("cannot specify both --id and --parent flags")
|
|
}
|
|
|
|
parentLookupStore := store
|
|
if dryRun && repoPath != "." {
|
|
var err error
|
|
parentLookupStore, err = openDryRunTargetStore(rootCtx, repoPath)
|
|
if err != nil {
|
|
targetPath := repoPath
|
|
if !remotecache.IsRemoteURL(repoPath) {
|
|
targetPath = filepath.Join(routing.ExpandPath(repoPath), ".beads")
|
|
}
|
|
return handleCreateTargetStoreError(err, targetPath, "%v")
|
|
}
|
|
defer func() { _ = parentLookupStore.Close() }()
|
|
}
|
|
|
|
var inheritedLabels []string
|
|
if parentID != "" {
|
|
ctx := rootCtx
|
|
_, err := parentLookupStore.GetIssue(ctx, parentID)
|
|
if err != nil {
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
return HandleError("parent issue %s not found", parentID)
|
|
}
|
|
return HandleError("failed to check parent issue: %v", err)
|
|
}
|
|
|
|
noInheritLabels, _ := cmd.Flags().GetBool("no-inherit-labels")
|
|
if !noInheritLabels {
|
|
inheritedLabels, _ = parentLookupStore.GetLabels(ctx, parentID)
|
|
}
|
|
}
|
|
|
|
labels = mergeCreateLabels(labels, inheritedLabels)
|
|
|
|
if dryRun {
|
|
return renderDryRun()
|
|
}
|
|
|
|
// Parse every requested dependency edge BEFORE reserving a child ID
|
|
// or creating anything so a malformed spec aborts with no burned
|
|
// child ID and no orphan issue behind it.
|
|
depSpecs, err := parseDepSpecs(deps)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
waitsForSpec, err := buildWaitsFor(waitsFor, waitsForGate, cmd.Flags().Changed("waits-for-gate"))
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
createCtx := rootCtx
|
|
if parentID != "" {
|
|
childID, err := store.GetNextChildID(rootCtx, parentID)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
explicitID = childID
|
|
createCtx = storage.WithReservedChildCounter(createCtx, parentID, childID)
|
|
}
|
|
|
|
if explicitID != "" {
|
|
_, err := validation.ValidateIDFormat(explicitID)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
// Validate prefix matches database prefix (YAML config takes
|
|
// precedence over DB, except under --global — see
|
|
// loadEmbeddedIDPrefixes).
|
|
dbPrefix, allowedPrefixes := loadEmbeddedIDPrefixes()
|
|
|
|
if err := validation.ValidateIDPrefixAllowed(explicitID, dbPrefix, allowedPrefixes, forceCreate); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
|
|
issue := buildCreateIssue(createIssueParams{
|
|
ID: explicitID,
|
|
Title: title,
|
|
Description: description,
|
|
Design: design,
|
|
AcceptanceCriteria: acceptance,
|
|
Notes: notes,
|
|
SpecID: specID,
|
|
Priority: priority,
|
|
IssueType: types.IssueType(issueType).Normalize(),
|
|
Assignee: assignee,
|
|
ExternalRef: externalRef,
|
|
EstimatedMinutes: estimatedMinutes,
|
|
Ephemeral: wisp,
|
|
NoHistory: noHistory,
|
|
StorageClass: storageClass,
|
|
CreatedBy: getActorWithGit(),
|
|
Owner: getOwner(),
|
|
Labels: labels,
|
|
MolType: molType,
|
|
WispType: wispType,
|
|
EventKind: eventCategory,
|
|
Actor: eventActor,
|
|
Target: eventTarget,
|
|
Payload: eventPayload,
|
|
InitialStatus: statusFlag,
|
|
DueAt: dueAt,
|
|
DeferUntil: deferUntil,
|
|
Metadata: metadata,
|
|
})
|
|
|
|
ctx := createCtx
|
|
|
|
// Resolve partial --deps targets the way `bd dep add` does, so a bare
|
|
// slug becomes a qualified id rather than a dangling edge, and an
|
|
// unknown target fails closed here instead of reaching the write.
|
|
resolvedDepSpecs, resolveErr := resolveDepSpecTargets(ctx, store, depSpecs)
|
|
if resolveErr != nil {
|
|
return HandleErrorRespectJSON("%v", resolveErr)
|
|
}
|
|
depSpecs = resolvedDepSpecs
|
|
|
|
// If a discovered-from dependency is present, inherit source_repo
|
|
// from the referenced parent issue. Reuse the already-parsed specs
|
|
// (not the raw --deps strings) so this can't drift from parseDepSpec's
|
|
// normalization rules.
|
|
if dfParent := discoveredFromParentSpec(depSpecs); dfParent != "" {
|
|
parentIssue, err := store.GetIssue(ctx, dfParent)
|
|
if err == nil && parentIssue.SourceRepo != "" {
|
|
issue.SourceRepo = parentIssue.SourceRepo
|
|
}
|
|
// If error getting parent or parent has no source_repo, continue with default
|
|
}
|
|
|
|
ops, err := writeOps(store)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
opsCtx, err := issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// Label inheritance stays CLI-side (mergeCreateLabels above) because the
|
|
// dry-run preview needs it too; asking the facade to inherit as well
|
|
// would append the parent's labels a second time.
|
|
result, err := ops.Create(opsCtx, issueops.CreateRequest{
|
|
Actor: actor,
|
|
Issue: issue,
|
|
ParentID: parentID,
|
|
Dependencies: createDependencyRequests(depSpecs),
|
|
WaitsFor: waitsForRequest(waitsForSpec),
|
|
ForceIDPrefix: forceCreate,
|
|
IDPrefix: createIDPrefixOverride(),
|
|
})
|
|
if err != nil {
|
|
// RULING R1: an occupied --id is a refusal, not a silent full-row
|
|
// upsert reported as success.
|
|
if errors.Is(err, storage.ErrAlreadyExists) && explicitID != "" {
|
|
return HandleErrorRespectJSON("%s already exists; use bd update, or bd import for upsert semantics", explicitID)
|
|
}
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// Every post-write read comes from the facade's result snapshot, never
|
|
// from the local struct: the facade clones its request, so the local
|
|
// struct still has no ID for an auto-minted create and no persisted
|
|
// timestamps. Dependencies and comments are dropped because `bd create`
|
|
// has never printed them.
|
|
created := result.Issue
|
|
created.Dependencies = nil
|
|
created.Comments = nil
|
|
|
|
edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec}
|
|
if edges.empty() {
|
|
// Bare create: preserve the embedded-mode follow-up Dolt commit.
|
|
// The deps path commits inside its transaction instead.
|
|
shouldCommit, err := shouldCommitCreatePostWrites(created, false)
|
|
if err != nil {
|
|
return HandleError("dolt auto-commit failed: %v", err)
|
|
}
|
|
if shouldCommit {
|
|
commitMsg := fmt.Sprintf("bd: create %s", created.ID)
|
|
if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
|
|
WarnError("failed to commit: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if repoPath != "." && targetStore != nil {
|
|
if err := commitPendingIfEmbedded(ctx, targetStore, actor, doltAutoCommitParams{
|
|
Command: "create",
|
|
IssueIDs: []string{created.ID},
|
|
}); err != nil {
|
|
debug.Logf("warning: failed to commit routed repo: %v", err)
|
|
}
|
|
}
|
|
|
|
if remoteCache != nil {
|
|
if pushErr := remoteCache.Push(rootCtx, repoPath); pushErr != nil {
|
|
return HandleError("failed to push to %s: %v\nThe issue was created locally but not synced to the remote.", repoPath, pushErr)
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(created); err != nil {
|
|
return err
|
|
}
|
|
} else if silent {
|
|
fmt.Println(created.ID)
|
|
} else {
|
|
debug.PrintNormal("%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(created.ID, created.Title))
|
|
debug.PrintNormal(" Priority: P%d\n", created.Priority)
|
|
debug.PrintNormal(" Status: %s\n", created.Status)
|
|
|
|
maybeShowTip(store)
|
|
}
|
|
|
|
SetLastTouchedID(created.ID)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
type createIssueParams struct {
|
|
ID string
|
|
Title string
|
|
Description string
|
|
Design string
|
|
AcceptanceCriteria string
|
|
Notes string
|
|
SpecID string
|
|
Priority int
|
|
IssueType types.IssueType
|
|
Assignee string
|
|
ExternalRef string
|
|
EstimatedMinutes *int
|
|
Ephemeral bool
|
|
NoHistory bool
|
|
StorageClass types.StorageClass
|
|
CreatedBy string
|
|
Owner string
|
|
Labels []string
|
|
MolType types.MolType
|
|
WispType types.WispType
|
|
EventKind string
|
|
Actor string
|
|
Target string
|
|
Payload string
|
|
InitialStatus string
|
|
DueAt *time.Time
|
|
DeferUntil *time.Time
|
|
Metadata json.RawMessage
|
|
}
|
|
|
|
// resolveStorageClass resolves the requested storage class at create time
|
|
// (Protocol v0.1 C1.3): the explicit --storage-class flag wins; otherwise the
|
|
// per-type config default storage-class.<type> applies; otherwise unset.
|
|
// The parsed class is returned verbatim, including versioned. The caller must
|
|
// normalize versioned to the unset marker (the marker is omitted when
|
|
// versioned, C2.4) only AFTER plane-conflict validation, so an explicit durable
|
|
// request paired with a wisp-plane flag is rejected rather than silently erased
|
|
// into an effective-ephemeral row. Values are validated wherever they came
|
|
// from: a bad flag is a usage error, a bad config value is a config bug and
|
|
// fails just as loudly.
|
|
func resolveStorageClass(explicit string, issueType types.IssueType) (types.StorageClass, error) {
|
|
raw := explicit
|
|
if raw == "" {
|
|
raw = config.GetString("storage-class." + string(issueType))
|
|
if raw == "" {
|
|
return "", nil
|
|
}
|
|
}
|
|
class, err := types.ParseStorageClass(raw)
|
|
if err != nil {
|
|
if explicit == "" {
|
|
return "", fmt.Errorf("config storage-class.%s: %w", issueType, err)
|
|
}
|
|
return "", err
|
|
}
|
|
return class, nil
|
|
}
|
|
|
|
// reconcileStorageClassPlane applies flag-over-config precedence between a
|
|
// resolved storage class and the effective wisp plane (Protocol v0.1 §C1.3).
|
|
// A wisp-plane record is ephemeral by construction, so a durable class
|
|
// (versioned/unversioned) cannot ride on it. explicit reports whether the class
|
|
// came from an explicit flag/field rather than a per-type config default:
|
|
// - explicit durable class + wisp plane -> conflict=true; the caller rejects
|
|
// it so the durable intent is preserved rather than silently collapsed into
|
|
// an effective-ephemeral record;
|
|
// - config-derived durable class + wisp plane -> cleared, yielding to the
|
|
// explicit --ephemeral/--no-history plane.
|
|
//
|
|
// versioned normalizes to the unset marker (C2.4) only after the check, so the
|
|
// durable request survives long enough to be honored, rejected, or yielded. On
|
|
// conflict the class is returned verbatim so the caller can name it in the error.
|
|
func reconcileStorageClassPlane(class types.StorageClass, explicit, wispPlane bool) (types.StorageClass, bool) {
|
|
if class != "" && wispPlane {
|
|
if explicit {
|
|
return class, true
|
|
}
|
|
class = "" // config default yields to the explicit wisp-plane flag
|
|
}
|
|
return class.Normalize(), false
|
|
}
|
|
|
|
// resolveCreateStorageClass is the ONE create-time storage-class decision every
|
|
// `bd create` CLI door makes: parse the flag (or fall back to the per-type
|
|
// storage-class.<type> config default), route the ephemeral spelling to the wisp
|
|
// plane, and reject a durable class that contradicts the plane. Every door goes
|
|
// through it so the direct, proxied, and --file routes cannot answer differently;
|
|
// graphApplyNodeStorageClass is the per-node mirror, which additionally honors a
|
|
// node's own pointer overrides.
|
|
//
|
|
// flagValue is the raw --storage-class spelling ("" when unset). wisp/noHistory
|
|
// are the plane flags as the caller read them; the returned wisp is the plane
|
|
// AFTER the ephemeral spelling has been folded in (Protocol v0.1 C1.4). The
|
|
// returned class is already normalized (C2.4), so it can go straight onto the
|
|
// issue.
|
|
func resolveCreateStorageClass(flagValue string, issueType types.IssueType, wisp, noHistory bool) (types.StorageClass, bool, error) {
|
|
class, err := resolveStorageClass(flagValue, issueType.Normalize())
|
|
if err != nil {
|
|
return "", wisp, err
|
|
}
|
|
// --storage-class ephemeral is the spelled-out spelling of --ephemeral
|
|
// (Protocol v0.1 C1.4: the wisp plane is today's ephemeral-class
|
|
// implementation). It routes to the wisp path exactly like the flag; the
|
|
// --ephemeral/--no-history mutual exclusion still applies.
|
|
if class == types.StorageClassEphemeral {
|
|
if noHistory {
|
|
return "", wisp, errors.New("--storage-class ephemeral and --no-history are mutually exclusive")
|
|
}
|
|
wisp = true
|
|
class = "" // wisp-plane rows derive ephemeral class (C1.2); no marker cell needed
|
|
}
|
|
// Reconcile the requested durable class with the effective wisp plane
|
|
// (flag > config, Protocol v0.1 §C1.3): an explicit --storage-class
|
|
// contradicts --ephemeral/--no-history and is rejected, so the durable
|
|
// intent is preserved rather than silently collapsed into an
|
|
// effective-ephemeral record; a per-type config default yields to the
|
|
// explicit flag. versioned normalizes to the unset marker only after the
|
|
// check (C2.4).
|
|
class, conflict := reconcileStorageClassPlane(class, flagValue != "", wisp || noHistory)
|
|
if conflict {
|
|
return "", wisp, fmt.Errorf("--storage-class %s conflicts with --ephemeral/--no-history: wisp-plane records are storage class ephemeral", class)
|
|
}
|
|
return class, wisp, nil
|
|
}
|
|
|
|
func buildCreateIssue(params createIssueParams) *types.Issue {
|
|
var externalRefPtr *string
|
|
if params.ExternalRef != "" {
|
|
externalRefPtr = ¶ms.ExternalRef
|
|
}
|
|
|
|
status := types.StatusOpen
|
|
if params.InitialStatus != "" {
|
|
status = types.Status(params.InitialStatus)
|
|
} else if params.DeferUntil != nil && params.DeferUntil.After(time.Now()) {
|
|
status = types.StatusDeferred
|
|
}
|
|
|
|
return &types.Issue{
|
|
ID: params.ID,
|
|
Title: params.Title,
|
|
Description: params.Description,
|
|
Design: params.Design,
|
|
AcceptanceCriteria: params.AcceptanceCriteria,
|
|
Notes: params.Notes,
|
|
SpecID: params.SpecID,
|
|
Status: status,
|
|
Priority: params.Priority,
|
|
IssueType: params.IssueType,
|
|
Assignee: params.Assignee,
|
|
ExternalRef: externalRefPtr,
|
|
EstimatedMinutes: params.EstimatedMinutes,
|
|
Ephemeral: params.Ephemeral,
|
|
NoHistory: params.NoHistory,
|
|
StorageClass: params.StorageClass,
|
|
CreatedBy: params.CreatedBy,
|
|
Owner: params.Owner,
|
|
Labels: append([]string(nil), params.Labels...),
|
|
MolType: params.MolType,
|
|
WispType: params.WispType,
|
|
EventKind: params.EventKind,
|
|
Actor: params.Actor,
|
|
Target: params.Target,
|
|
Payload: params.Payload,
|
|
DueAt: params.DueAt,
|
|
DeferUntil: params.DeferUntil,
|
|
Metadata: params.Metadata,
|
|
}
|
|
}
|
|
|
|
func mergeCreateLabels(labels, inheritedLabels []string) []string {
|
|
merged := make([]string, 0, len(labels)+len(inheritedLabels))
|
|
seen := make(map[string]struct{}, len(labels)+len(inheritedLabels))
|
|
for _, label := range labels {
|
|
if _, ok := seen[label]; ok {
|
|
continue
|
|
}
|
|
seen[label] = struct{}{}
|
|
merged = append(merged, label)
|
|
}
|
|
for _, label := range inheritedLabels {
|
|
if _, ok := seen[label]; ok {
|
|
continue
|
|
}
|
|
seen[label] = struct{}{}
|
|
merged = append(merged, label)
|
|
}
|
|
if len(merged) == 0 {
|
|
return nil
|
|
}
|
|
return merged
|
|
}
|
|
|
|
// createIDPrefixOverride is the prefix an explicit --id must match, when the
|
|
// WORKSPACE knows better than the database does.
|
|
//
|
|
// config.yaml's `issue-prefix` wins over the database's, except under --global
|
|
// where the shared database is authoritative (GH#4957, selectCreateIDPrefix).
|
|
// Only a front door can read config.yaml — a shared server's database knows
|
|
// only its own prefix — so both routes resolve it here and hand it to the role
|
|
// as CreateRequest.IDPrefix. Empty means "the substrate's prefix is right",
|
|
// which is the ordinary case.
|
|
func createIDPrefixOverride() string {
|
|
if globalFlag {
|
|
return ""
|
|
}
|
|
return overlayYAMLPrefix("")
|
|
}
|
|
|
|
func selectCreateIDPrefix(global bool, yamlPrefix, storePrefix string) string {
|
|
if global {
|
|
return storePrefix
|
|
}
|
|
if yamlPrefix != "" {
|
|
return yamlPrefix
|
|
}
|
|
return storePrefix
|
|
}
|
|
|
|
func renderCreateDryRunPreview(issue *types.Issue, labels, deps []string) {
|
|
idDisplay := issue.ID
|
|
if idDisplay == "" {
|
|
idDisplay = "(will be generated)"
|
|
}
|
|
fmt.Printf("%s [DRY RUN] Would create issue:\n", ui.RenderWarn("⚠"))
|
|
fmt.Printf(" ID: %s\n", idDisplay)
|
|
fmt.Printf(" Title: %s\n", issue.Title)
|
|
fmt.Printf(" Type: %s\n", issue.IssueType)
|
|
fmt.Printf(" Priority: P%d\n", issue.Priority)
|
|
fmt.Printf(" Status: %s\n", issue.Status)
|
|
if issue.Assignee != "" {
|
|
fmt.Printf(" Assignee: %s\n", issue.Assignee)
|
|
}
|
|
if issue.Description != "" {
|
|
fmt.Printf(" Description: %s\n", issue.Description)
|
|
}
|
|
if len(labels) > 0 {
|
|
fmt.Printf(" Labels: %s\n", strings.Join(labels, ", "))
|
|
}
|
|
if len(deps) > 0 {
|
|
fmt.Printf(" Dependencies: %s\n", strings.Join(deps, ", "))
|
|
}
|
|
if issue.EventKind != "" {
|
|
fmt.Printf(" Event category: %s\n", issue.EventKind)
|
|
}
|
|
}
|
|
|
|
func shouldCommitCreatePostWrites(_ *types.Issue, _ bool) (bool, error) {
|
|
return embeddedWritesCommitNow()
|
|
}
|
|
|
|
func createDepsAcceptedTypeList() string {
|
|
names := []string{"blocked-by", "depends-on"}
|
|
for _, depType := range types.WellKnownDependencyTypes() {
|
|
names = append(names, string(depType))
|
|
}
|
|
sort.Strings(names)
|
|
return strings.Join(names, ", ")
|
|
}
|
|
|
|
func init() {
|
|
createCmd.Flags().StringP("file", "f", "", "Create one issue per ## heading (### fields attach to that issue); for title plus description-from-file, use --body-file")
|
|
createCmd.Flags().String("graph", "", "Create a graph of issues with dependencies from JSON plan file")
|
|
createCmd.Flags().String("title", "", "Issue title (alternative to positional argument)")
|
|
createCmd.Flags().Bool("silent", false, "Output only the issue ID (for scripting)")
|
|
createCmd.Flags().Bool("dry-run", false, "Preview what would be created without actually creating")
|
|
registerPriorityFlag(createCmd, "2")
|
|
createCmd.Flags().StringP("type", "t", "task", "Issue type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision")
|
|
createCmd.Flags().StringP("status", "s", "", "Initial status")
|
|
registerCommonIssueFlags(createCmd)
|
|
createCmd.Flags().String("spec-id", "", "Link to specification document")
|
|
createCmd.Flags().StringSliceP("labels", "l", []string{}, "Labels (comma-separated)")
|
|
createCmd.Flags().String("skills", "", "Required skills for this issue")
|
|
createCmd.Flags().String("context", "", "Additional context for the issue")
|
|
createCmd.Flags().StringSlice("label", []string{}, "Alias for --labels")
|
|
_ = createCmd.Flags().MarkHidden("label") // Only fails if flag missing (caught in tests)
|
|
createCmd.Flags().String("id", "", "Explicit issue ID (e.g., 'bd-42' for partitioning)")
|
|
createCmd.Flags().String("parent", "", "Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')")
|
|
createCmd.Flags().Bool("no-inherit-labels", false, "Don't inherit labels from parent issue")
|
|
createCmd.Flags().StringSlice("deps", []string{}, "Dependencies as 'type:id' or bare 'id'. Bare 'id', 'depends-on:id', and 'blocked-by:id' all make THIS issue depend on id; 'blocks:id' reverses direction (id depends on this issue). E.g. 'blocked-by:bd-20,discovered-from:bd-15'")
|
|
createCmd.Flags().String("waits-for", "", "Spawner issue ID to wait for (creates waits-for dependency for fanout gate)")
|
|
createCmd.Flags().String("waits-for-gate", "all-children", "Gate type: all-children (wait for all) or any-children (wait for first)")
|
|
createCmd.Flags().Bool("force", false, "Force creation even if prefix doesn't match database prefix")
|
|
createCmd.Flags().String("repo", "", "Target repository for issue (overrides auto-routing)")
|
|
createCmd.Flags().IntP("estimate", "e", 0, "Time estimate in minutes (e.g., 60 for 1 hour)")
|
|
createCmd.Flags().Bool("ephemeral", false, "Create as ephemeral (short-lived, subject to TTL compaction)")
|
|
createCmd.Flags().Bool("no-history", false, "Skip Dolt commit history without making GC-eligible (for permanent agent beads)")
|
|
createCmd.Flags().String("storage-class", "", "Storage class: versioned, unversioned, or ephemeral (default: storage-class.<type> config, else versioned)")
|
|
createCmd.Flags().String("mol-type", "", "Molecule type: swarm (multi-agent), patrol (recurring ops), work (default)")
|
|
createCmd.Flags().String("wisp-type", "", "Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation")
|
|
createCmd.Flags().Bool("validate", false, "Validate description contains required sections for issue type")
|
|
createCmd.Flags().Bool("allow-empty-description", false, "Allow empty description input from stdin or file")
|
|
// Event-specific flags (only valid when --type=event)
|
|
createCmd.Flags().String("event-category", "", "Event category (e.g., patrol.muted, agent.started) (requires --type=event)")
|
|
createCmd.Flags().String("event-actor", "", "Entity URI who caused this event (requires --type=event)")
|
|
createCmd.Flags().String("event-target", "", "Entity URI or bead ID affected (requires --type=event)")
|
|
createCmd.Flags().String("event-payload", "", "Event-specific JSON data (requires --type=event)")
|
|
// Time-based scheduling flags (GH#820)
|
|
// Examples:
|
|
// --due=+6h Due in 6 hours
|
|
// --due=tomorrow Due tomorrow
|
|
// --due="next monday" Due next Monday
|
|
// --due=2025-01-15 Due on specific date
|
|
// --defer=+1h Hidden from bd ready for 1 hour
|
|
// --defer=tomorrow Hidden until tomorrow
|
|
createCmd.Flags().String("due", "", "Due date/time. Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15")
|
|
createCmd.Flags().String("defer", "", "Defer until date (issue hidden from bd ready until then). Same formats as --due")
|
|
createCmd.Flags().String("metadata", "", "Set custom metadata (JSON object, or @file.json to read from file)")
|
|
// Note: --json flag is defined as a persistent flag in main.go, not here
|
|
rootCmd.AddCommand(createCmd)
|
|
}
|
|
|
|
// handleCreateTargetStoreError preserves the existing text path for ordinary
|
|
// store failures while rendering capability refusals as typed JSON when asked.
|
|
func handleCreateTargetStoreError(err error, targetPath, fallbackFormat string) error {
|
|
var capErr *ProxyCapabilityError
|
|
if !errors.As(err, &capErr) {
|
|
return HandleError(fallbackFormat, err)
|
|
}
|
|
|
|
withContext := *capErr
|
|
withContext.Message = fmt.Sprintf("failed to open create target %q: %s", targetPath, capErr.Message)
|
|
if capErr.Code == "proxy.store.unrouted" {
|
|
withContext.Message = fmt.Sprintf("create target %q is a proxied-server workspace; bd cannot open it as a direct store", targetPath)
|
|
}
|
|
return HandleProxyCapabilityError(&withContext)
|
|
}
|
|
|
|
// formatTimeForRPC converts a *time.Time to RFC3339 string for RPC calls.
|
|
// Returns empty string if t is nil, to distinguish "not set" from "set to zero".
|
|
func formatTimeForRPC(t *time.Time) string {
|
|
if t == nil {
|
|
return ""
|
|
}
|
|
return t.Format(time.RFC3339)
|
|
}
|
|
|
|
// openDryRunTargetStore opens the store a `create --dry-run --repo <other>`
|
|
// resolves --parent against. It is read-only on BOTH paths and must stay that
|
|
// way: newDoltStoreFromConfig runs schema initialization on whatever it opens
|
|
// and can rename a legacy hyphenated database and rewrite the target's
|
|
// metadata.json on the way (GH#3231), so using it here would have a dry-run
|
|
// mutate a repository the user only named as a lookup target — the same
|
|
// migrate-at-open trap this preview policy exists to close, one repo over.
|
|
// newPreviewStoreFromConfig is the non-mutating factory for a foreign
|
|
// project (bd-6dnrw.32), relaxed for previews exactly as the root pre-run
|
|
// relaxes the command's own store.
|
|
func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltStorage, error) {
|
|
if remotecache.IsRemoteURL(repoPath) {
|
|
cache, err := remotecache.DefaultCache()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to initialize remote cache: %w", err)
|
|
}
|
|
// The dry-run parent lookup only reads from this cached remote store.
|
|
// Do not add writes here; dry-runs must not mutate cached remotes.
|
|
store, err := cache.OpenStore(ctx, repoPath, newPreviewStoreFromConfig)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("dry-run parent lookup requires an existing cached remote store for %s: %w", repoPath, err)
|
|
}
|
|
return store, nil
|
|
}
|
|
|
|
targetPath := routing.ExpandPath(repoPath)
|
|
beadsDir := filepath.Join(targetPath, ".beads")
|
|
metadataPath := filepath.Join(beadsDir, "metadata.json")
|
|
if _, err := os.Stat(metadataPath); err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("target repo %s is not initialized; refusing to initialize it during dry-run", targetPath)
|
|
}
|
|
return nil, fmt.Errorf("failed to inspect target repo %s: %w", targetPath, err)
|
|
}
|
|
|
|
store, err := newPreviewStoreFromConfig(ctx, beadsDir)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open target store for dry-run: %w", err)
|
|
}
|
|
return store, nil
|
|
}
|
|
|
|
// isAmbiguousRepoTarget reports whether an explicit --repo value is a
|
|
// bare/relative filesystem path (not absolute, not "~/"-prefixed). Such a
|
|
// value silently resolves against the current working directory (see
|
|
// routing.ExpandPath) rather than failing, so a misresolved value (e.g. a
|
|
// typo) previously wrote a bead into a brand-new, disconnected database
|
|
// instead of erroring (bd-8d3f).
|
|
func isAmbiguousRepoTarget(repoFlagChanged bool, repoOverride string) bool {
|
|
return repoFlagChanged && !filepath.IsAbs(repoOverride) && !strings.HasPrefix(repoOverride, "~/")
|
|
}
|
|
|
|
// ensureBeadsDirForPath ensures a beads directory exists at the target path.
|
|
// If the .beads directory doesn't exist, it creates it and initializes with
|
|
// the same prefix as the source store (T010, T012: prefix inheritance).
|
|
//
|
|
// When allowCreate is false, a target with no existing workspace is refused
|
|
// instead of fabricated — see isAmbiguousRepoTarget.
|
|
func ensureBeadsDirForPath(ctx context.Context, targetPath string, sourceStore storage.DoltStorage, allowCreate bool) error {
|
|
beadsDir := filepath.Join(targetPath, ".beads")
|
|
metadataPath := filepath.Join(beadsDir, "metadata.json")
|
|
|
|
// Check if beads directory already exists with a Dolt database.
|
|
// metadata.json is the canonical marker for an initialized beads dir.
|
|
if _, err := os.Stat(metadataPath); err == nil {
|
|
return nil
|
|
}
|
|
|
|
if !allowCreate {
|
|
return fmt.Errorf("no beads workspace found at %s and --repo's value is a relative/bare path, so it won't be auto-created here (this is likely not the target you intended). Pass an absolute or \"~/\"-prefixed --repo path to an existing workspace instead", targetPath)
|
|
}
|
|
|
|
// Create .beads directory
|
|
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
|
return fmt.Errorf("cannot create .beads directory: %w", err)
|
|
}
|
|
|
|
// Initialize database via NewFromConfigWithOptions to respect Dolt config.
|
|
// Set the prefix if source store has one (T012: prefix inheritance).
|
|
if sourceStore != nil {
|
|
sourcePrefix, err := sourceStore.GetConfig(ctx, "issue_prefix")
|
|
if err == nil && sourcePrefix != "" {
|
|
// Sanitize prefix for SQL database name (same as bd init).
|
|
dbName := strings.ReplaceAll(sourcePrefix, "-", "_")
|
|
|
|
// Open target store temporarily to set prefix.
|
|
// Use newDoltStore with explicit config since the target .beads
|
|
// directory was just created and has no metadata.json yet.
|
|
tempStore, err := newDoltStore(ctx, &dolt.Config{
|
|
BeadsDir: beadsDir,
|
|
Database: dbName,
|
|
CreateIfMissing: true,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to initialize target database: %w", err)
|
|
}
|
|
if err := tempStore.SetConfig(ctx, "issue_prefix", sourcePrefix); err != nil {
|
|
_ = tempStore.Close() // Best effort cleanup on error path
|
|
return fmt.Errorf("failed to set prefix in target store: %w", err)
|
|
}
|
|
if err := tempStore.Close(); err != nil {
|
|
return fmt.Errorf("failed to close target store: %w", err)
|
|
}
|
|
|
|
// Write metadata.json so newDoltStoreFromConfig can find the
|
|
// correct database name on subsequent opens (GH#2988).
|
|
cfg := configfile.DefaultConfig()
|
|
cfg.Backend = configfile.BackendDolt
|
|
cfg.DoltDatabase = dbName
|
|
cfg.DoltMode = configfile.DoltModeEmbedded
|
|
cfg.ProjectID = configfile.GenerateProjectID()
|
|
if err := cfg.Save(beadsDir); err != nil {
|
|
return fmt.Errorf("failed to write metadata.json: %w", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|