diff --git a/.claude/skills/beads-docs/SKILL.md b/.claude/skills/beads-docs/SKILL.md index a5454d2ea..52bab8362 100644 --- a/.claude/skills/beads-docs/SKILL.md +++ b/.claude/skills/beads-docs/SKILL.md @@ -201,8 +201,7 @@ document what the pinned release does, never main-only features. See ## 9. Verify before you call it done Run the gates in [references/verification.md](references/verification.md). -The short list: `bazel test //test/docsync:docsync_test --config=ci` -(nav↔file sync + link conventions), +The short list: `go test ./test/docsync` (nav↔file sync + link conventions), `./scripts/generate-cli-docs.sh --check` (generated docs fresh), `./scripts/check-doc-freshness.sh` (Last reviewed markers), and a live preview with `make docs-dev` (or `./mint.sh dev`) at `localhost:3000`. diff --git a/.claude/skills/beads-docs/references/simplification.md b/.claude/skills/beads-docs/references/simplification.md index 916834ca5..5152fd2b5 100644 --- a/.claude/skills/beads-docs/references/simplification.md +++ b/.claude/skills/beads-docs/references/simplification.md @@ -39,9 +39,8 @@ don't measure that work by the word delta. *not* simplifying — it buries the real change in the diff. 4. **Loss-check** (below). 5. **Fact-check** (below). -6. **Gates:** `bazel test //test/docsync:docsync_test --config=ci`, every - fence parses, no body H1, no HTML comments (MDX), preview with - `make docs-dev`. +6. **Gates:** `go test ./test/docsync`, every fence parses, no body H1, no + HTML comments (MDX), preview with `make docs-dev`. 7. **Preview, then commit on approval** — one page or section per batch, so the reviewer can steer before a cut compounds across the section. diff --git a/.claude/skills/beads-docs/references/verification.md b/.claude/skills/beads-docs/references/verification.md index 44aabca76..559bfb6f3 100644 --- a/.claude/skills/beads-docs/references/verification.md +++ b/.claude/skills/beads-docs/references/verification.md @@ -8,7 +8,7 @@ Run these before considering docs work complete. Ordered cheapest-first. # 1. Docs sync: docs.json nav <-> file consistency, link conventions # (root-relative extensionless in docs/, exact paths in engdocs/ and # curated root files), orphan detection (only CLI_REFERENCE.md is exempt). -bazel test //test/docsync:docsync_test --config=ci +go test ./test/docsync # 2. Generated CLI docs freshness: regenerates from the live command tree # and diffs docs/CLI_REFERENCE.md, docs/cli-reference/, and the CLI diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index 21e6f181d..fe342055e 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -11,7 +11,7 @@ # t.Parallel) add up, parallel ones share -test.parallel=4. # Regenerate with scripts/ci/gen_embedded_cmd_shard_manifest.py 100 # --weights=duration --write after adding, splitting or removing -# TestEmbedded* functions in cmd/bd/*_test.go. --write is +# TestEmbedded* functions in cmd/bd/*_embedded_test.go. --write is # incremental: it keeps every already-assigned test on its current shard # and only places newly-discovered names, onto whichever shard is # currently lightest, so two unrelated PRs that each add one test do not @@ -59,206 +59,108 @@ 100 17 TestEmbeddedReopen 100 18 TestEmbeddedLabelPropagateRename -100 18 TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead 100 19 TestEmbeddedLabelConcurrent -100 19 TestEmbeddedNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase 100 20 TestEmbeddedInitRoleRoutingRetainedFork -100 20 TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying 100 21 TestEmbeddedMaxRowsReady -100 21 TestEmbeddedMigratePersonal_movesIssues 100 22 TestEmbeddedCount -100 22 TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose 100 23 TestEmbeddedCountConcurrent -100 23 TestEmbeddedExportExcludeOwner_flag -100 24 TestEmbeddedEventsTailFollowReportsTruncationOnTheStream 100 24 TestEmbeddedUndeferConcurrent -100 24 TestEmbeddedWispGCProtectsActiveWisps -100 25 TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard 100 25 TestEmbeddedMaxRowsListBasic -100 25 TestEmbeddedRemovedBackendHealRejectionPerBackend -100 26 TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr 100 26 TestEmbeddedExternalMutationPolicy -100 26 TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace -100 27 TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy -100 27 TestEmbeddedNewDoltStoreFromConfig_DottedDBName 100 27 TestEmbeddedShipConcurrent -100 28 TestEmbeddedDoltLocalOnly_RemoteAdd_RefusesExitOne 100 28 TestEmbeddedHistoryConcurrent -100 28 TestEmbeddedImportChunkedRealStoreResumeConverges -100 29 TestEmbeddedDoltLocalOnly_RemoteAdd_ErrorOnStderr 100 29 TestEmbeddedEpicCloseEligibleReasonFlag -100 29 TestEmbeddedImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle 100 30 TestEmbeddedCloseGuardsAndEpics -100 30 TestEmbeddedDoltLocalOnly_Push_ExitsZeroWithMessage -100 30 TestEmbeddedImportChunkedCrossBucketBlocksEdgesResumeBackfills -100 31 TestEmbeddedDoltLocalOnly_ConfigRoundTrip -100 31 TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren 100 31 TestEmbeddedInitSelectedExcludeRoutingForkInvalidQuiet -100 32 TestEmbeddedDoctorUnsupportedJSON -100 32 TestEmbeddedIfRevisionAdvertisedOnFourVerbs 100 32 TestEmbeddedListSearchAndOutputFormats 100 33 TestEmbeddedBootstrapJSONLAndGitOrigin -100 33 TestEmbeddedDeleteJournalsTheRequestingActor -100 33 TestEmbeddedExportExcludeOwner_verbose -100 34 TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp -100 34 TestEmbeddedEventsTailReportsTruncationToTheCLI 100 34 TestEmbeddedUnclaimBatchAndRefusals -100 34 TestEmbeddedWispGCPurgeClosedDoesNotCascadeIntoLiveSteps -100 35 TestEmbeddedAutoPruneRespectsBdConfigSet -100 35 TestEmbeddedEventsReadNoticesADisabledJournal 100 35 TestEmbeddedGateCreateBeadRename -100 35 TestEmbeddedVersionedHistoryEnvIsProcessWideAndOnlyTurnsRecordingOn -100 36 TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone -100 36 TestEmbeddedDoltRemoteResetData_UnknownRemote 100 36 TestEmbeddedGateConcurrent -100 36 TestEmbeddedUnclaimIfAssigneeCLIDifferentSpelling -100 37 TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand -100 37 TestEmbeddedDoltRemoteResetData_CloudRemoteRefused 100 37 TestEmbeddedMaxRowsDepTreeAndDuplicates -100 37 TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields 100 38 TestEmbeddedGraphConcurrent -100 38 TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace -100 38 TestEmbeddedUnclaimIfAssigneeFlagValidation -100 39 TestEmbeddedIfRevisionRejectsLabelAndParentEdits 100 39 TestEmbeddedMaxRowsGraph -100 39 TestEmbeddedNewDoltStoreFromConfig_NoMetadata -100 40 TestEmbeddedIfRevisionOutranksReassignFenceCLI -100 40 TestEmbeddedNewDoltStoreFromConfig_HyphenatedDBName 100 40 TestEmbeddedUpdateLifecycleClaimParentCommit 100 41 TestEmbeddedDuplicateConcurrent -100 41 TestEmbeddedVersionedHistoryFollowsTheStoreItWritesInto 100 42 TestEmbeddedInitAForkAutoContributor -100 42 TestEmbeddedUpdateIfGuardsFlagValidation -100 43 TestEmbeddedIfRevisionMultiIDRejected 100 43 TestEmbeddedInitExplicitBeadsDirIsAuthoritative -100 44 TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus 100 44 TestEmbeddedStaleConcurrent 100 45 TestEmbeddedGraph -100 45 TestEmbeddedUpdateIfGuardsCLI 100 46 TestEmbeddedCloseAlreadyClosedClaimNextAndMolecule -100 46 TestEmbeddedIfRevisionMatchAndMismatch 100 47 TestEmbeddedListSearchAndOutputSearchAndSort -100 47 TestEmbeddedRevisionRemintMatrix 100 48 TestEmbeddedDeferConcurrent -100 48 TestEmbeddedReassignFenceCLI -100 49 TestEmbeddedBackupRestoreStrictReadonly 100 49 TestEmbeddedInitAPushConsentAndRemoteBootstrap -100 49 TestEmbeddedMigratePersonal_abortOnNoConfirm 100 50 TestEmbeddedDiffConcurrent -100 50 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr -100 50 TestEmbeddedImportChunkedWaitsForChildImportedLaterStaysBlocked -100 50 TestEmbeddedVersionOutputShape -100 51 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0 -100 51 TestEmbeddedHistoryAndShowAsOfReadDoltCommits -100 51 TestEmbeddedImportChunkedStaleRejectedRowKeepsDeferredDepsOut 100 51 TestEmbeddedInitGitBootstrapRoutingFreshQuiet -100 52 TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan -100 52 TestEmbeddedDoltLocalOnly_Push_LocalStoreCopy -100 52 TestEmbeddedImportChunkedNoReadyWindowAtAnyFreezePoint 100 52 TestEmbeddedSwarmConcurrent -100 53 TestEmbeddedDoltLocalOnly_Push_JSON_DisabledStatus -100 53 TestEmbeddedIfRevisionOrdinaryCAS -100 53 TestEmbeddedImportChunkedMixedRegularWispCrossBucketEdgesWired 100 53 TestEmbeddedInitSelectedExcludeRoutingStealthDecoyQuiet -100 54 TestEmbeddedDiscoveryPinsEnvFileReadonly -100 54 TestEmbeddedFormatJSONAliasMatchesJSON -100 54 TestEmbeddedGraphModeDependencyWorkspaceUnaffected -100 54 TestEmbeddedInitAgentArtifactsGolden 100 54 TestEmbeddedSearchConcurrent -100 54 TestEmbeddedShowAsOfFailureExitCodes -100 55 TestEmbeddedDoltLocalOnly_Pull_JSON_DisabledStatus -100 55 TestEmbeddedImportChunkedConcurrentUpdateKeepsDeferredDeps 100 55 TestEmbeddedUndefer -100 55 TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage 100 56 TestEmbeddedDepNoCycleCheck -100 56 TestEmbeddedDoltLocalOnly_Pull_ExitsZeroWithMessage -100 56 TestEmbeddedImportChunkedConcurrentUpdateKeepsBlockingDeps -100 56 TestEmbeddedVersionedHistorySwitchRoundTrip -100 57 TestEmbeddedDoltLocalOnly_DoltStatus_ShowsDisabled -100 57 TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed 100 57 TestEmbeddedQueryConcurrent -100 57 TestEmbeddedVersionedHistorySwitchRefusesUnversionableMetadata 100 58 TestEmbeddedDepAAddRejectionsAndBulk -100 58 TestEmbeddedDoctorUnsupportedProse -100 58 TestEmbeddedIfRevisionCascadeDelete -100 58 TestEmbeddedVersionedHistorySwitchRefusesAnUnrecordableGateTimeout 100 59 TestEmbeddedDeferAutoWake -100 59 TestEmbeddedDoctorSupportedChecks -100 59 TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace -100 59 TestEmbeddedVersionedHistorySetManyRefusesUnversionableMetadata 100 60 TestEmbeddedCommentsCLI -100 60 TestEmbeddedCorruptMetadataFailsLoudUntilRestored -100 60 TestEmbeddedExportExcludeOwner_config 100 60 TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase -100 60 TestEmbeddedWispGCPurgeClosedStillPurgesFullyClosedMolecules 100 61 TestEmbeddedBootstrapCloneFailureScrubsCredentials 100 61 TestEmbeddedContributorRoutedWritesCommitInPlanning -100 61 TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig 100 61 TestEmbeddedUpdateRoutedStoreCommitsTargetHead -100 61 TestEmbeddedVersionedHistoryConfigSetWritesTheStoreRow -100 62 TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands -100 62 TestEmbeddedDoltRemoteResetData_GitBacked 100 62 TestEmbeddedGateCheckSkipsTemplateGates 100 62 TestEmbeddedReadyBlockersAndLabels -100 62 TestEmbeddedUnclaimIfAssigneeCLI 100 63 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead 100 63 TestEmbeddedGateCheckLimitCountsOnlyLiveGates 100 63 TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed 100 63 TestEmbeddedListPageEdges -100 64 TestEmbeddedAutoExportExcludeOwner_config -100 64 TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally 100 64 TestEmbeddedGateWaiterCheckLifecycle 100 64 TestEmbeddedPromoteMovesAWispParent -100 64 TestEmbeddedSpawnMolecule_PreservesStepLabels 100 65 TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb -100 65 TestEmbeddedRemovedBackendHealRoundTrip 100 65 TestEmbeddedSupersede 100 66 TestEmbeddedCloseBasicIsolatedStores @@ -323,7 +225,6 @@ 100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose 100 71 TestEmbeddedInitRoleRoutingExplicitDefault 100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget -100 71 TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig 100 71 TestEmbeddedSearchRoutesAgree 100 72 TestEmbeddedContributorCreateMultiple @@ -434,10 +335,8 @@ 100 83 TestEmbeddedPurgeFiltered 100 83 TestEmbeddedReadyConcurrent -100 84 TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1 100 84 TestEmbeddedInitGitBootstrapRoutingDecoyInvalid 100 84 TestEmbeddedInitSelectedExcludeRoutingStealthInvalid -100 84 TestEmbeddedMigratePersonal_preservesComments 100 85 TestEmbeddedBootstrapExistingDryRunInit 100 85 TestEmbeddedChildrenBasicAndEmpty @@ -446,10 +345,8 @@ 100 85 TestEmbeddedIfRevisionReopenGuardDirect 100 85 TestEmbeddedInitArtifactRouting -100 86 TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally 100 86 TestEmbeddedExplicitHierarchicalParentEdges 100 86 TestEmbeddedInitHooksRouting -100 86 TestEmbeddedMigratePersonal_noopWhenEmpty 100 87 TestEmbeddedCreateRepoProxiedTargetError 100 87 TestEmbeddedGateInheritsDownParentChain diff --git a/.github/scripts/embedded-storage-test-shards.txt b/.github/scripts/embedded-storage-test-shards.txt index c3f45aacb..f06b0bcd3 100644 --- a/.github/scripts/embedded-storage-test-shards.txt +++ b/.github/scripts/embedded-storage-test-shards.txt @@ -178,6 +178,7 @@ 40 4 TestBlockedListerContract 40 4 TestCreateBatchFastPathsMatchPerRowSmallDepAdd_Embedded +40 4 TestEmbeddedFirstMintOnEmptyHistoryIsRevisionOne 40 4 TestEmbeddedIssueOperationsUpdateLabelPatchOrdering 40 4 TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay 40 4 TestEmbeddedReaderListFilterFamiliesNarrowToTheirRows @@ -186,7 +187,6 @@ 40 5 TestEmbeddedClaimerRefusesIncompleteRequestsAndAnAbsentIDWithoutTouchingState 40 5 TestEmbeddedIssueOperationsCloseAndReopenAWisp 40 5 TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder -40 5 TestRecordVersionKeepsSubSecondChangeAt 40 5 TestWithPeerAuth 40 6 TestCreateBatchFastPathsMatchPerRowApplyWaitsFor_Embedded @@ -196,7 +196,6 @@ 40 6 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection 40 6 TestPromoteStillWorksWithCollisionGuard 40 6 TestSearchWithMissingWispPlaneTables -40 6 TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart 40 7 TestConcurrencyMultiProcess 40 7 TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded @@ -205,20 +204,17 @@ 40 7 TestEmbeddedIssueOperationsUpdateMetadataReplaceClearsAndValidates 40 7 TestEmbeddedLenientOpenWarning_DataBehind 40 7 TestEmbeddedRelationsLeavesTheCallersRequestAlone -40 7 TestLoseVersionLeavesTheEpochTablesCommitted 40 7 TestMergeAndSettleWithStrategy_ResolvesDeclinedConflict 40 8 TestDeleterContract 40 8 TestEmbeddedDependencyEditorRoutesWispSourcedRemovalToTheWispPlane 40 8 TestEmbeddedMergeAndSettleDirtyWorkingSetSurvivesRefusedMerge -40 8 TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes 40 8 TestEmbeddedReaderGetBriefDepsProjectsTheDependencyRows 40 8 TestEmbeddedRelationsOrdersNeighborsFromBothPlanesTogether 40 8 TestEmbeddedReopenIssueCategorySemantics 40 8 TestGetIssueCommentsPageEmbedded 40 8 TestListWisps -40 9 TestBumpEpochCarryingNeitherCarriesNorServesARowFromAFutureEpoch 40 9 TestEmbeddedDependencyEditorRefusesCrossPlaneCycle 40 9 TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent 40 9 TestEmbeddedDependencyEditorSnapshotsTheRequest @@ -237,10 +233,8 @@ 40 10 TestGraphCounterContract 40 10 TestIgnoredCursorHealRespectsOperatorOverride 40 10 TestRunInTransactionPostCommitStageFailureIsIndeterminate -40 10 TestVersionedHistoryOffMatchesPreStackGolden_Embedded 40 10 TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPasswordAmbient -40 11 TestABumpUnderOneStoreIDMovesTheEpochSeenThroughEveryStoreID 40 11 TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges 40 11 TestEmbeddedClaimerRefusalMessagesCarryTheirFragments 40 11 TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches @@ -342,7 +336,6 @@ 40 19 TestRemoteVerbsPresentStoredPeerCredentials 40 19 TestRenameLabelMintsOneVersionPerTouchedBead -40 20 TestBumpEpochCarryingCarriesOnlyTheLineageHoldingTheNewestRow 40 20 TestCreateIssue 40 20 TestEmbeddedCheckedWrappersRouteTheirPreconditions 40 20 TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps @@ -354,7 +347,6 @@ 40 20 TestHeartbeatRejectsWispEmbedded 40 20 TestIgnoredCursorHealNeverResurrectsRolledBackVersions -40 21 TestBumpEpochCarryingCarriesTheLiveRowsOfEveryStoreInTheDatabase 40 21 TestCreateRejectsCrossTableIDCollision 40 21 TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards 40 21 TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants @@ -378,7 +370,6 @@ 40 22 TestLeaseLifecycleEmbedded 40 22 TestPolicyBlockingAnnotatorForeignOpensAreSublinear -40 23 TestAsOfReadContract 40 23 TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes 40 23 TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed 40 23 TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes @@ -441,7 +432,6 @@ 40 27 TestRemoteGitDataRefOnEngine 40 27 TestSweeperContract -40 28 TestBumpEpochCarryingDoesNotCarryALostLineage 40 28 TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy 40 28 TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed 40 28 TestEmbeddedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow @@ -479,7 +469,6 @@ 40 30 TestLegacyTrackedIgnoredCursorUnwedgesPull 40 30 TestUpdateMergeOps_DoltEngine_TwoIssues -40 31 TestBumpEpochCarryingWritesOneCarryRowPerLiveIDNamingTheLineageRoot 40 31 TestDualWriteContract 40 31 TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget 40 31 TestEmbeddedDependencyEditorMaintainsBlockedStateAcrossPlanes @@ -492,7 +481,6 @@ 40 31 TestReadyCounterContract 40 31 TestWithPeerAuth_KeyMismatchFailsClosed -40 32 TestCurrentAddressForNeverReseedsAnAbsentStoreEpochRow 40 32 TestEmbeddedClaimerGrantsALiveLeaseOnTheRowItWonAndLeavesARefusedOneAlone 40 32 TestEmbeddedDependencyEditorRefusesAMissingLocalTarget 40 32 TestEmbeddedDirtyTablesGate_BlocksReopenThenWorkingSetReconcileRecovers @@ -513,13 +501,11 @@ 40 33 TestEmbeddedRelationsResolvesTheAnchorIDExactly 40 33 TestEmbeddedSyncCommitsConfigBeforeMerge 40 33 TestEventsAutoPruneThrottleSkipsTheSecondPass -40 33 TestFirstMintLeavesTheEpochTablesCommitted 40 33 TestGetDependentRecordsEmbedded 40 33 TestPruneEventsBatchDeletesTheLowestSeqsOnly 40 33 TestTreeWalkerContract 40 34 TestAddLabel -40 34 TestBumpEpochCarryingLeavesTheEpochTablesCommitted 40 34 TestDecryptPassword_KeyMismatchNamesTheLocalKey 40 34 TestEmbeddedBlockedRecheckRecordsUnblockingWrites 40 34 TestEmbeddedDependencyEditorAttributesItsEventsToTheActor @@ -543,7 +529,6 @@ 40 35 TestReadyWorkWithMissingDeferredParentTables 40 35 TestReclaimExpiredLeaseSurvivesRestartEmbedded -40 36 TestBumpEpochCarryingFailsAndRollsBackWhenARowAlreadyExistsAtTheNewEpoch 40 36 TestCommenterContract 40 36 TestConcurrentOpenReturnsCached 40 36 TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory @@ -566,7 +551,6 @@ 40 37 TestEmbeddedMergeAndSettleReportsOperatorConflicts 40 37 TestEmbeddedReaderListBriefDropsTheFreeFormTextAndNothingElse 40 37 TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch -40 37 TestEpochWritesReportAnUnpublishedCommitAsIndeterminate 40 37 TestIgnoredCursorHealRespectsOverrideUnderBroaderPattern 40 38 TestCreateIssues @@ -588,6 +572,7 @@ 40 39 TestEmbeddedDependencyEditorMixedBatchRefusalRollsBackBothPlanes 40 39 TestEmbeddedIssueOperationsClaimLeavesBlockedStateAlone 40 39 TestEmbeddedMigrateRepairedDependenciesIDColumnCommitsAtomicallyWithVersion53_4690 +40 39 TestEmbeddedMigration0071ReplacesDescendingCompactionSnapshotsIndex 40 39 TestEmbeddedReaderListSkipCountsDropsTheCardinalitiesAndNothingElse 40 39 TestEmbeddedRelationsResolvesAWispAnchor 40 39 TestParticipationGenerationFence diff --git a/.github/scripts/embedded-test-shard.sh b/.github/scripts/embedded-test-shard.sh index 3b7bdc7e2..a89757e69 100755 --- a/.github/scripts/embedded-test-shard.sh +++ b/.github/scripts/embedded-test-shard.sh @@ -3,7 +3,7 @@ # # Usage: embedded-test-shard.sh # -# Discovers all TestEmbedded* top-level functions in cmd/bd/*_test.go. +# Discovers all TestEmbedded* top-level functions from cmd/bd/*_embedded_test.go. # Tests listed in embedded-cmd-test-shards.txt for the requested shard count use # that committed assignment; newly-added tests fall back to hash(name) % total. # Runs the matching subset using the pre-built test binary at @@ -33,12 +33,8 @@ fi SHARD_INDEX=$(( SHARD_NUMBER - 1 )) MANIFEST="${BEADS_TEST_SHARD_MANIFEST:-.github/scripts/embedded-cmd-test-shards.txt}" -# Discover all top-level TestEmbedded* functions across every cmd/bd test -# file, by name rather than by file glob (as proxied-test-shard.sh does): a -# test gated on BEADS_TEST_EMBEDDED_DOLT runs in this lane or in none, wherever -# it lives. scripts/embedded_lane_coverage_test.go fails on a gated test this -# selection misses. -ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_test.go \ +# Discover all top-level TestEmbedded* functions. +ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go \ | sed 's/func \(TestEmbedded[A-Za-z0-9_]*\).*/\1/' \ | sort -u) diff --git a/.github/scripts/proxied-cmd-test-shards.txt b/.github/scripts/proxied-cmd-test-shards.txt index fca167226..7c60e35ad 100644 --- a/.github/scripts/proxied-cmd-test-shards.txt +++ b/.github/scripts/proxied-cmd-test-shards.txt @@ -69,7 +69,6 @@ 34 6 TestProxiedServerServeReadsTheJournalItJustWrote 34 6 TestProxiedServerSwarm 34 6 TestProxiedServerUpdate2B -34 6 TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout 34 6 TestProxiedServerWispList 34 7 TestProxiedServerCloseConcurrent @@ -157,7 +156,6 @@ 34 17 TestProxiedServerPrime 34 17 TestProxiedServerSQLDatabaseFlag 34 17 TestProxiedServerServeModeGate -34 17 TestServerModeServeIgnoresGraphModeDependency 34 18 TestProxiedServerClose3 34 18 TestProxiedServerCount @@ -256,7 +254,6 @@ 34 30 TestProxiedServerStatus 34 30 TestProxiedServerTodo 34 30 TestProxiedServerUpdate2 -34 30 TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow 34 31 TestProxiedServerCloseBeadGate 34 31 TestProxiedServerComment diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index b319ab300..03a769e7f 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -1085,7 +1085,7 @@ jobs: outputs: result: ${{ steps.result.outputs.result }} env: - PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoStoreFactoriesRefuseGraphWorkspace)' + PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag)' # The only pre-merge run of these boundaries: where it executes # remotely --config=sole-run fails on a remote cache eviction instead # of re-running the whole invocation (whose retry could turn a failed diff --git a/AGENTS.md b/AGENTS.md index e908a5070..1a450309e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -126,29 +126,9 @@ make install # build and install bd to ~/.local/bin (canonical) certificate `--config=remote-exec`, agent hosts whose `~/.bazelrc` names the executor neither. Make yours the default with a `build --config=...` line in the gitignored `.bazelrc.local`, or pass `BAZEL_FLAGS=...` to make. -- Agents run tests only with `bazel test`, also while iterating on one - behavior: - - ```bash - bazel test //cmd/bd:bd_test --config=ci --test_filter='^TestName$' --test_output=all - ``` - - A target also passes when the test never ran (a filter that matches - nothing, a skip, a file the configuration does not compile), so count a run - only when its log shows `--- PASS: TestName` and no `--- SKIP` for the test - or a `TestName/...` subtest: Go prints `--- PASS` for a test whose every - subtest skipped. "Check That the Test Ran" in - [engdocs/TESTING.md](engdocs/TESTING.md) names the tests `--config=ci` does - not run (Dolt-backed, `-short`-gated, integration-tagged, `TestEmbedded*` - and embedded-Dolt, files `BUILD.bazel` does not list) and the way into - each. An unchanged target returns its cached result, which is the same - evidence. Finish with `make test`. -- Agents do not run `go test` (`./scripts/test.sh`, `make test-go`): CI does - not enforce it, it skips nogo, gofmt and the guards, and agent hosts may - refuse it. It stays a convenience for humans working offline. The exception - is regenerating golden files (`make corpus-regen`, `make githooks-regen`, - `BD_UPDATE_GOLDEN=1`), which Bazel cannot do: see "Regenerating Golden - Files" in [engdocs/TESTING.md](engdocs/TESTING.md). +- `go test` (`./scripts/test.sh`, `make test-go`) is an inner-loop + convenience only. CI does not enforce it, and it skips nogo, gofmt and the + guards; finish with `make test`. - **Do NOT** use `go build -o bd ./cmd/bd`, `go install ./cmd/bd`, or raw `go run ./cmd/bd ...`: they bypass the canonical build path, leave stale binaries, and raw `go run` misses the `gms_pure_go` tag. Use `make install`, diff --git a/BUILD.bazel b/BUILD.bazel index 0a1d10355..7b10becbc 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -74,13 +74,6 @@ exports_files( visibility = ["//scripts:__pkg__"], ) -# //scripts:shell_scripts_test: Oracle A's runner, whose EXIT-trap removal of -# its reference worktree oracle_a_script_test.go checks in a fixture repository. -exports_files( - ["tests/oracle-a/run-oracle-a.sh"], - visibility = ["//scripts:__pkg__"], -) - # The nested Go modules' go.mod files, which mark where the root module ends: # //scripts:go_test_sources_test's scan of every _test.go file skips their # trees, as `go test ./...` does. (go.mod is in no Go partition below: it is @@ -253,20 +246,6 @@ exports_files( visibility = ["//internal/httpclient/encode:__pkg__"], ) -# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- - -filegroup( - name = "go_srcs", - srcs = glob( - ["**/*.go"], - allow_empty = True, - exclude = ["bazel-*/**"], - ), - visibility = ["//:__subpackages__"], -) - -# --- end go_srcs --- - # --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- filegroup( @@ -365,7 +344,6 @@ filegroup( "//internal/httpclient/encode:repo_doc_files", "//internal/httpclient/wire:repo_doc_files", "//internal/idgen:repo_doc_files", - "//internal/initprocs:repo_doc_files", "//internal/jira:repo_doc_files", "//internal/linear:repo_doc_files", "//internal/lockfile:repo_doc_files", @@ -405,7 +383,6 @@ filegroup( "//internal/storage/externaldeps:repo_doc_files", "//internal/storage/fs:repo_doc_files", "//internal/storage/git:repo_doc_files", - "//internal/storage/historyoffequiv:repo_doc_files", "//internal/storage/issueops:repo_doc_files", "//internal/storage/journalscan:repo_doc_files", "//internal/storage/kvkeys:repo_doc_files", @@ -436,7 +413,6 @@ filegroup( "//internal/utils:repo_doc_files", "//internal/validation:repo_doc_files", "//internal/versioncheck:repo_doc_files", - "//internal/versionedhistory:repo_doc_files", "//internal/workapi:repo_doc_files", "//internal/workapi/storecounter:repo_doc_files", "//internal/workapi/storequerier:repo_doc_files", @@ -602,7 +578,6 @@ filegroup( "//internal/httpclient/encode:repo_go_srcs", "//internal/httpclient/wire:repo_go_srcs", "//internal/idgen:repo_go_srcs", - "//internal/initprocs:repo_go_srcs", "//internal/jira:repo_go_srcs", "//internal/linear:repo_go_srcs", "//internal/lockfile:repo_go_srcs", @@ -642,7 +617,6 @@ filegroup( "//internal/storage/externaldeps:repo_go_srcs", "//internal/storage/fs:repo_go_srcs", "//internal/storage/git:repo_go_srcs", - "//internal/storage/historyoffequiv:repo_go_srcs", "//internal/storage/issueops:repo_go_srcs", "//internal/storage/journalscan:repo_go_srcs", "//internal/storage/kvkeys:repo_go_srcs", @@ -673,7 +647,6 @@ filegroup( "//internal/utils:repo_go_srcs", "//internal/validation:repo_go_srcs", "//internal/versioncheck:repo_go_srcs", - "//internal/versionedhistory:repo_go_srcs", "//internal/workapi:repo_go_srcs", "//internal/workapi/storecounter:repo_go_srcs", "//internal/workapi/storequerier:repo_go_srcs", @@ -824,7 +797,6 @@ filegroup( "//internal/httpclient/encode:repo_go_test_srcs", "//internal/httpclient/wire:repo_go_test_srcs", "//internal/idgen:repo_go_test_srcs", - "//internal/initprocs:repo_go_test_srcs", "//internal/jira:repo_go_test_srcs", "//internal/linear:repo_go_test_srcs", "//internal/lockfile:repo_go_test_srcs", @@ -864,7 +836,6 @@ filegroup( "//internal/storage/externaldeps:repo_go_test_srcs", "//internal/storage/fs:repo_go_test_srcs", "//internal/storage/git:repo_go_test_srcs", - "//internal/storage/historyoffequiv:repo_go_test_srcs", "//internal/storage/issueops:repo_go_test_srcs", "//internal/storage/journalscan:repo_go_test_srcs", "//internal/storage/kvkeys:repo_go_test_srcs", @@ -895,7 +866,6 @@ filegroup( "//internal/utils:repo_go_test_srcs", "//internal/validation:repo_go_test_srcs", "//internal/versioncheck:repo_go_test_srcs", - "//internal/versionedhistory:repo_go_test_srcs", "//internal/workapi:repo_go_test_srcs", "//internal/workapi/storecounter:repo_go_test_srcs", "//internal/workapi/storequerier:repo_go_test_srcs", @@ -1055,7 +1025,6 @@ filegroup( "//internal/httpclient/encode:repo_other_files", "//internal/httpclient/wire:repo_other_files", "//internal/idgen:repo_other_files", - "//internal/initprocs:repo_other_files", "//internal/jira:repo_other_files", "//internal/linear:repo_other_files", "//internal/lockfile:repo_other_files", @@ -1095,7 +1064,6 @@ filegroup( "//internal/storage/externaldeps:repo_other_files", "//internal/storage/fs:repo_other_files", "//internal/storage/git:repo_other_files", - "//internal/storage/historyoffequiv:repo_other_files", "//internal/storage/issueops:repo_other_files", "//internal/storage/journalscan:repo_other_files", "//internal/storage/kvkeys:repo_other_files", @@ -1126,7 +1094,6 @@ filegroup( "//internal/utils:repo_other_files", "//internal/validation:repo_other_files", "//internal/versioncheck:repo_other_files", - "//internal/versionedhistory:repo_other_files", "//internal/workapi:repo_other_files", "//internal/workapi/storecounter:repo_other_files", "//internal/workapi/storequerier:repo_other_files", diff --git a/CHANGELOG.md b/CHANGELOG.md index 884a0d7f0..f74c873b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,41 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- `bd versions ` lists the versions recorded for a bead, and - `versioned-history.enabled` turns recording on. While it is on, every - accepted change to a bead created while it is on, or that enters the issues - plane while it is on (a wisp promoted or made persistent), stores a - snapshot of it as a row of `issue_versions` in the same transaction. It is - off by default and nothing is backfilled: a bead already on the issues - plane when it is turned on is legacy, and editing it records nothing. A - recorded write leaves `updated_at` where an unrecorded one would, so - `bd import`'s stale check sees the same timestamps either way. - `bd versions --json` answers `{"versions": [...], "recording": bool}`; the - command still lists what was recorded after recording is turned off, and - proxied-server and HTTP workspaces refuse it. The setting is a row of each - store's `config` table (`bd config set versioned-history.enabled true`), - and every store reads its own when it is opened: a write routed into - another workspace (a prefix-routed `bd update` or `bd close`, - `bd create --repo`) follows the target store's row, a proxied-server - provider reads it when it is constructed, and a long-lived `bd serve` - keeps the value it read until it restarts. - `BD_VERSIONED_HISTORY_ENABLED=1` (or a `config.yaml` value) turns - recording on for every store the process opens, and never turns it off. - The row replicates on `bd dolt push`/`pull`, and recording is single-writer - only: two clones recording at once can mint the same revision and fail the - pull, and a write from a writer that is not recording is folded into the - next recorded version under that version's actor, so keep recording on for - every writer of a store or off for all of them. Turning it on with - `bd config set` first checks every issue the store would version and - refuses, writing nothing, while any holds a number outside the I-JSON - exact-integer range (magnitude above 2^53-1, however it is spelled) in its - metadata or in a gate's timeout (held as nanoseconds, so about 104.25 - days), and prints the count, the ids, the field and the fix. There is no - override, and the check runs once; after that, a recorded write that would - hold such a number fails atomically. Migration 0071 adds a nullable - `removed_restriction` column to `issue_versions`. `bd version` now refuses - an argument and suggests `bd versions `, instead of printing bd's - build for a mistyped `bd version bd-123`. - `bd blocked --flags` prints the blocked flag for each id read from stdin (one per line; blank lines and repeats ignored), with `--json` as `[{"id","is_blocked"}]` in the order the ids were given, omitting an id that @@ -499,24 +464,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- Over an HTTP workspace, `bd ready --json` without `BD_JSON_ENVELOPE` no - longer sends `GET /v0/beads/ready:count` after a page the limit cut short: - the total only went into the stderr hint. It lists one row past the limit - instead, and the hint says more issues matched without saying how many - (the wording the proxied-server route already uses). A local store, and the - envelope's `pagination.total`, keep the total. -- `bd` initializes its packages with `GOMAXPROCS` capped at 4 and hands it - back before `main` runs anything, so the garbage collections package - initialization triggers do not stop the world across every CPU of a large - host. On a 192-CPU machine this takes about 17 ms off every bd process. An - explicit `GOMAXPROCS` is restored as set. -- Over an HTTP workspace, `bd ready` no longer fetches `GET /v0/beads/context` - before its listing in every process only to learn whether the server - enforces the external-dependency policy. The answer is kept for 5 minutes - per server URL and pinned project under the user cache directory - (`BEADS_HTTP_POLICY_CACHE_TTL`, a duration, a number of seconds, or `off`), - and a handshake the process already holds still wins. Claims and closes - always ask the server. - `bd serve` normalizes every RFC 3339 time bound on the issue listing and count (`created_*`, `updated_*`, `closed_*`, and the new `defer_*` and `due_*`) to UTC before it reaches storage. A bound carrying an offset @@ -588,6 +535,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 transport, so a write makes one handshake. `bd list` reads its vocabulary with one `listSettings`, and the hook decorator skips its post-write re-reads when no hook for the event is installed. +- **Embedded mode now runs Dolt 2.4.1 (`dolthub/driver` v2.4.1), and + migration 0071 keeps the databases it creates open to Dolt older than + 2.3.3.** Dolt 2.3.3 and later store a descending index column as + descending (dolthub/dolt#11746), where earlier releases silently stored it + ascending, and migration 0010 declares `compaction_snapshots`' + `idx_comp_snap_issue` with `created_at DESC`. Dolt older than 2.3.3 cannot + read a table holding such an index: writes to any table and + `information_schema` queries fail with `table has unknown fields`, on 2.1.8 + an `UPDATE` or `DELETE` on `issues` reports a `fk_comp_snap_issue` violation, + and a `bd` that links an older Dolt fails to open the workspace with + `schema skew check: probing schema_migrations existence: Error 1105: table + has unknown fields`, which `BD_IGNORE_SCHEMA_SKEW=1` does not get past. The + descending order never served a query, so migration 0071 replaces the + index with `idx_comp_snap_issue_asc` (`issue_id`, `compaction_level`, + `created_at`, all ascending) on every database, including one whose schema + a `dolt sql-server` 2.3.3 or newer created. At schema version 71, Dolt + 2.1.8 and 2.2.0 read, write, push and clone the database, and a v69 `bd` + on the Dolt 2.2.0 driver stops at its ordinary schema-version refusal + instead, which `BD_IGNORE_SCHEMA_SKEW=1` gets past (measured 2026-10-18). + One gap remains: `bd init` commits each migration separately, so on a + database created by Dolt 2.3.3 or later the commits from before 0071 still + hold the descending index. On older Dolt, reading `compaction_snapshots` at + one of them (`AS OF`, `dolt_history_compaction_snapshots`, + `dolt_diff_compaction_snapshots`) fails, and so does any `dolt diff` with + one as an endpoint. The recommended `dolt` CLI and `dolt sql-server` + version is now 2.4.1 or later, the release CI pins, measured free of the + `DOLT_RESET('--hard')` defect described in docs/architecture/dolt.md. + Releases before 2.4.0 also drop a join condition when an `ON` clause has an + `OR` over indexed columns (dolthub/dolt#11886, the cause of #7037). Managed + proxied-server mode now recommends dolt 2.4.1 or newer and warns below it; + it is still a warning, not a refusal. Dolt 2.3.3 and later also report a + stricter default `sql_mode` than 2.2.0, adding `NO_ZERO_IN_DATE`, + `NO_ZERO_DATE` and `ERROR_FOR_DIVISION_BY_ZERO`, in embedded mode and on + those servers. - **`created_by` defaults to the actor in the library, for every create shape and every backend.** `PreparePublicCreateRequest`, which `Lifecycle.Create`, `BatchCreator` items and batch-apply create items all @@ -781,175 +762,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- An HTTP workspace whose server cannot be reached now says which step - failed. A connect that is refused names the address and says nothing is - listening; one that times out (a filtered port, a down host) names the - address that never answered and how long it waited; a host name that does - not resolve is named as such. The error was the transport's - `Get "https://…/v0/beads/context": dial tcp …: i/o timeout`, which named the - request rather than the address. -- **`bd link` works over a connected HTTP workspace.** It wrote through the - store's raw `AddDependencyWithOptions`, which the HTTP client refuses, so - every `bd link` failed there with `operation "AddDependencyWithOptions" not - supported by the http backend`, whatever the type. It now writes through - the `DependencyEditor` role, the route `bd dep add` takes, on the direct - and HTTP routes alike (the proxied-server route is unchanged). Over HTTP - that is one `dependencies:add` request, so `bd link` keeps accepting any - non-empty type of at most 32 characters (`owned-by`, `ships-in`, ...). - An empty or over-long type is still refused before anything is written, - and an edge that already exists with another type still reports the typed - conflict. On a Dolt store the history commit is now the role's, like - `bd dep add`'s: `bd: dep add ` in place of - `dependency: add -> `. - -- **`bd query` reports an uppercase duration unit as an unparseable time, not - a negated internal error.** `created>30M` failed with - `not a compact duration: "-30M"`, naming a value nobody typed; it now fails - with `cannot parse time expression: "30M"`. A signed spelling - (`created>+30M`) stops at the parser, as `created>+30x` already did, so - quote one to match it as a literal (`label="+30M"`). Units remain lowercase - (`30min`, `6h`, `7d`, `2w`, `3m`, `1y`); help and docs already say so. -- **Strict `--readonly` no longer creates workspace gate files.** A - `bd --readonly` command took its shared workspace gates with - create-if-missing, so on a workspace no bd command had gated yet it left - `/.beads.gate.lock` and the physical-root gate file - (`.beads/embeddeddolt.gate.lock` or `.beads/dolt.gate.lock`) behind, although - strict readonly promises not to mutate the workspace. It now opens an - existing gate file read-only and holds it shared as before, so a maintenance - operation still sees it and a running one still makes it wait; when no gate - file exists it holds nothing. Every other command still creates the files. -- **Strict `--readonly` refuses `bd backup init`, `backup sync`, - `backup remove`, `backup restore` and `bd import`.** None of them checked - readonly mode. On a server-mode store they ran to completion under - `--readonly`: `backup init` and `backup remove` rewrote or emptied the - server's backup registry, `backup sync` wrote the backup destination, - `backup restore --force` replaced the store, and `import` wrote issues. On - an embedded store they failed with the storage layer's `store is read-only` - error instead, after `backup sync` had left `.beads/backup.lock` behind and - `backup restore` had left workspace-gate holder files. They now exit 1 with - the standard `Error: operation '' is not allowed in read-only mode`, - and a restore is refused before it takes the exclusive workspace gate. - `bd import --dry-run` is refused too, as `bd create --dry-run` already is - and as a migration freeze already refuses it. `bd backup status` still runs - under `--readonly`. -- **`bd init --server --external` no longer starts a Dolt server of its own.** - Init builds its store config by hand and turned auto-start on for every - server init, so an `--external` init that named no port launched a - repo-local `dolt sql-server`, although `--external` says the server is - managed outside bd. `--external` now turns auto-start off. When the - external server cannot be reached, init gives one message on every route - (host and port, socket, shared server, auto-start pinned off): it names the - endpoint it dialed, says that bd did not start a server, and no longer - advises `bd dolt start`. With no port named at all, it asks for one - (`--server-port` or `BEADS_DOLT_SERVER_PORT`) instead of offering a default. -- **A failed `bd init --server` can be retried.** A first attempt that could - not reach its server left an empty `.beads/dolt` and nothing on disk that - records the server choice, so the legacy-upgrade guard refused every retry - as a "legacy Dolt workspace" and no bd command could repair it. When init - itself selects server mode, the guard now admits exactly that root: empty, - with no `.local_version` witness. A pre-1.0 witness, or a `.beads/dolt` that - holds anything, is still refused, and commands other than `bd init` are - decided as before. -- **A graph-mode workspace is refused instead of opened as an Issue store.** - Graph-preview builds mark their workspaces with `"graph_mode": "link"` and - `graph_*` binding fields in `metadata.json`, beside an ordinary Dolt - backend. bd opened such a workspace as an Issue store and ran Issue schema - initialization against the graph database, and every `metadata.json` rewrite - (including the `config.json` to `metadata.json` migration) dropped the - marker and the binding. Now any `graph_mode` other than `dependency`, - including a value bd does not recognize, makes every command that runs in - the workspace or names it with `--db` or `BEADS_DB` (`bd init`, `bd doctor` - and `bd bootstrap` included), and `bd create --repo` aimed at it, refuse it - before touching anything. The refusal names the format and exits with code - 16, so installed beads git hooks refuse commits and pushes there too. - Commands that reach such a workspace only through a route from another - one, such as a routed `bd show`, fail without touching it, but not with - code 16. Store-less commands such as `bd version` and `bd help` still run. - A `metadata.json` rewrite keeps `graph_mode` and the `graph_*` fields - graph-preview builds write, and like those builds it omits a zero - `graph_schema_version` and a false `graph_ready`. -- **A graph workspace without `graph_mode` in its metadata is refused too.** - Graph-preview builds write a `.beads/graph-preview-format` marker before - `metadata.json`. bd ignored it. When an older bd had rewritten - `metadata.json` without `graph_mode`, bd opened the graph database by its - recorded name and ran Issue schema initialization against it; when - `metadata.json` was never written or was lost, bd fell back to the default - database name and created an Issue database inside the graph workspace, and - `bd init` initialized an Issue workspace there. A `.beads` holding that - marker, whatever it contains and whatever its metadata says (absent, - stripped, unparseable or an explicit `dependency`), is now refused wherever - a `graph_mode` workspace is: commands run in it or naming it with `--db` or - `BEADS_DB`, `bd create --repo` aimed at it, and `bd bootstrap` in a - workspace below it that would take its metadata exit with code 16 and a - hint to restore `metadata.json`, and routed and cross-repository opens fail - without opening its database. -- **The Go library's opens refuse a graph workspace too.** - `beads.OpenBestAvailable`, `OpenBestAvailableWith`, `OpenFromConfig` and - `OpenGated` opened a workspace whose `metadata.json` declares a - `graph_mode` other than `dependency`, or whose `.beads` holds the - `graph-preview-format` marker, as an Issue store and ran Issue schema - migrations into the graph database. They now - return `*beads.UnsupportedWorkspaceFormatError` (match it with `errors.As`) - before opening, creating or changing anything, the same refusal the CLI - exits 16 with. -- **`bd setup claude --remove` no longer leaves a blank-line hole.** Removing - the beads section from `CLAUDE.md` (or, with the other setup recipes, from - `AGENTS.md` or `GEMINI.md`) left the blank lines around it behind, three in - the `CLAUDE.md` `bd init` writes, and setup then re-added the section after - two more, so every remove and re-add grew the file. `--remove` now takes - those blank lines with the section, and setup appends a section after one - blank line, so removing and re-adding it toggles between the same two files. - A re-added section goes at the end of the file. -- **`bd config set` no longer truncates a `config.yaml` that has a line of - 64 KiB or more.** Setting an undotted key (such as `actor` or `no-db`) - rewrites the file line by line, and a line of 65,536 bytes or more ended - that read early without an error, so the command reported success and wrote - back only the lines before the long one, plus the key it set. Dotted keys - and `bd config unset` were not affected. Setting an undotted key in such a - file now fails with `bufio.Scanner: token too long`. `bd config set` leaves - the file as it was. `set-many` stops at that key, but it has already written - any `config.yaml` keys listed before it, such as a dotted `sync.remote`. -- **`bd show --as-of` exits 1 when it reads no issue.** A ref the Dolt AS OF - read does not take (an instant, a versioned-history address), a ref that - does not exist, or an issue that did not exist at the ref was reported on - stderr while the command exited 0 with nothing on stdout, even under - `--json`. It now ends the way plain `bd show` does: exit 1, with the JSON - error envelope on stdout under `--json`. A batch that reads at least one of - its ids still exits 0. Both the direct and the proxied-server routes - changed. -- **`bd list --format dot` prints the same graph the same way every time.** - Nodes are declared in id order and edges in source, target and type order. - They used to follow the listing order, which breaks a priority tie by - creation time to the second, so two equal-priority issues swapped places - depending on whether they were created in the same second, and the - proxied-server route did not pin the order of one issue's edges. `--sort` - and `--limit` still choose which issues are listed. -- **`bd init --quiet` no longer prints "Removed SessionStart hook" or "Removed - PreCompact hook"** when the project's `.claude/settings.json` (or the legacy - `.claude/settings.local.json`) still carries the bare `bd prime` hooks an - older bd registered. The hooks are still migrated to the SessionStart - `bd prime --hook-json` hook; the removal lines now go to the installer's own - output, which `--quiet` discards, instead of straight to stdout. -- **A new `AGENTS.md` from `bd init` lists `bd dolt push` in its Quick - Reference only when the workspace has a Dolt remote.** The managed Beads - section already left out its push lines when no Dolt remote is configured or - the workspace is `no-push`, but the Quick Reference above it still showed - `bd dolt push # Push beads data to remote`. It now follows the same rule. - `bd init` still leaves an existing `AGENTS.md` alone outside the managed - section, and writes an `--agents-template` as given. -- **`bd setup claude` no longer rewrites a CLAUDE.md whose beads section is - already current.** A rerun (and `bd init`, which runs it) wrote the same - bytes back as a new file, resetting its mode to 0644 and its mtime, and - reported "Updated existing beads section"; it now leaves the file alone and - reports the section current (the report `bd init` already gives a current - AGENTS.md). `bd setup factory`, `opencode`, `mux` and `gemini` share the - fix. A section whose END marker is missing or comes before BEGIN, which was - also reported as updated while nothing changed, is now reported as an error: - `bd setup factory`, `opencode` and `mux` exit 1 (`mux` before installing its - `.mux` hooks), while `claude` and `gemini` warn and carry on. When CLAUDE.md - is an `@AGENTS.md` stub and it is AGENTS.md that cannot be updated, `claude` - now names AGENTS.md in the warning and keeps the beads block left in the - stub, which it used to delete although AGENTS.md was never updated. - **Time-bound filters and the keyset cursor compare the same instant on every engine, whatever zone they are given in.** The storage filter builder binds every time bound (`created_*`, `updated_*`, `closed_*`, `started_*`, @@ -961,27 +773,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 driver sends a `time.Time` as its wall clock with no zone, so a library caller paging with a cursor in another zone was answered from the wrong position there (server Dolt was unaffected). -- **`bd setup claude --global` keeps its beads section in `~/.claude/CLAUDE.md`.** - It wrote the section into the current directory's `CLAUDE.md`: run from your - home directory it created `~/CLAUDE.md`, which by default stops Claude Code - reading `AGENTS.md` in the projects below it, and `--remove --global` - stripped the section a project's own install had put in its `CLAUDE.md` - while leaving that project's hooks in place. A global install and removal now - use only the user-level files beside `~/.claude/settings.json`. A new - `~/.claude/CLAUDE.md` holds just the section, rendered the same whichever - project you run from. Claude Code loads that file in every project, so its - section, task-tracking rules included, applies only in repositories that use - beads. With global or plugin hooks `--check` accepts it when the project's - instructions have none, or names `--global` when it is missing and the - project has no `CLAUDE.md` of its own. Run from `~/.claude`, - or from your home directory unless `~/CLAUDE.md` still holds a section an - earlier run left there, `--check` judges the user-level files, and from your - home directory it names `--global` when no hooks are installed. From your - home directory, whose `.claude/settings.json` is the global one, `--remove` - removes the user-level section with the hooks. If you ran `--global` before, - re-run `bd setup claude --global` to add the section to `~/.claude/CLAUDE.md`. - A section an earlier `--global` run left in a directory's `CLAUDE.md` stays - there; delete it by hand if you don't want it. - **`bd blocked --label`, `--label-any` and `--exclude-label` apply to a row blocked only by an unsatisfied `external:` dependency.** The external-dependency policy lists such a row itself, after the label query diff --git a/README.md b/README.md index f7909900f..5faca32f1 100644 --- a/README.md +++ b/README.md @@ -275,24 +275,10 @@ instead of 60s, because `bd serve` gives such a request its `--large-apply-ceiling` (5 minutes by default) and finishes it even after the client has given up. A server whose ceiling is raised past about 5m15s can still outlast the client. A dial or TLS timeout stays a plain connection -error, since the server never saw the request, and a connect that fails says -so: it names the address that refused the connection (nothing listening) or -never answered (a filtered port or a down host, after the dialer's 30s), or -the host name that did not resolve. `off` turns off only the +error, since the server never saw the request. `off` turns off only the header timer: a reset read is still retried, and a write's timeout is still reported as above. -Whether the server applies bd's external-dependency policy itself (the -`policy.external_dependencies` capability) is remembered for 5 minutes per -server URL and pinned project, in `beads/http-policy/` under the user cache -directory, so `bd ready` does not fetch the server's context before every -listing just to learn it. `BEADS_HTTP_POLICY_CACHE_TTL` sets that window (a -duration such as `1m`, a number of seconds, or `off`); a server restarted -with a different composition is seen once it passes. Claims and closes never -use the cached answer: they ask the server, since a stale one could skip the -client-side refusal of externally blocked work. A workspace connected without -a project pin is not cached. - `bd search`, `bd show --current` and `bd recompute-blocked` work over HTTP too, each in its own way. `bd search` asks the server's listing with its text (`q`, behind the `issues.list.search` capability) and refuses before dialing against a server that does not advertise it. `bd list diff --git a/RELEASING.md b/RELEASING.md index 50acb6497..e05b73072 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -145,8 +145,7 @@ Before starting a release: - [ ] All tests passing (`make test`, the Bazel test lane) - [ ] npm package tests passing (`cd npm-package && npm run test:all`) - [ ] **Upgrade smoke tests pass** (`make test-upgrade`) — see [Release Stability Gate](engdocs/RELEASE-STABILITY-GATE.md) -- [ ] **Regression tests pass** - (`bazel test //tests/regression:regression_test --config=doltserver-cmd`) +- [ ] **Regression tests pass** (`make test-regression`) - [ ] **Every release target cross-compiles** — see [Cross-compile before tagging](#cross-compile-before-tagging). PR CI builds them only with cgo off, and a target that fails at tag time diff --git a/backend/conformance/BUILD.bazel b/backend/conformance/BUILD.bazel index 2ba90b30b..545efa1aa 100644 --- a/backend/conformance/BUILD.bazel +++ b/backend/conformance/BUILD.bazel @@ -65,7 +65,6 @@ go_library( "transaction_parity.go", "tree_walker_contract.go", "version_reconciler_contract.go", - "versioned_read_contract.go", "workspaceconfig_contract.go", ], importpath = "github.com/steveyegge/beads/backend/conformance", diff --git a/backend/conformance/dualwrite_participation_generation_contract.go b/backend/conformance/dualwrite_participation_generation_contract.go index 7943e7e4a..e1e283380 100644 --- a/backend/conformance/dualwrite_participation_generation_contract.go +++ b/backend/conformance/dualwrite_participation_generation_contract.go @@ -267,65 +267,6 @@ func RunParticipationGenerationProceedsForPromotedRecord(t *testing.T, ctx conte } } -// RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord pins the -// switch's off half for a record the fence would let through: created with -// the flag on (so participation_generation is stamped), then updated after -// the flag is turned back off, it must mint nothing. ProceedsForPromotedRecord -// shows the fence passes such a record, so only the flag stands between this -// update and a mint. No other case can see a writer that ignores the flag on -// updates: every other flag-off record is legacy, and the fence stops those -// first. -func RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { - t.Helper() - if err := fixture.SetFlag(ctx, true); err != nil { - t.Fatalf("enabling versioned history: %v", err) - } - id := fixture.IssuePrefix + "-flag-off-skip" - if err := fixture.Mutate(ctx, id); err != nil { - t.Fatalf("mutating %s: %v", id, err) - } - if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { - t.Fatalf("reading participation_generation for %s: %v", id, err) - } else if gen == nil { - t.Fatalf("participation_generation for %s is NULL immediately after a create with the flag on — "+ - "this case cannot test the flag against a record the fence would have stopped anyway", id) - } - - if err := fixture.SetFlag(ctx, false); err != nil { - t.Fatalf("disabling versioned history: %v", err) - } - beforeRevision, err := fixture.CurrentRevision(ctx, id) - if err != nil { - t.Fatalf("reading current_revision for %s: %v", id, err) - } - beforeCount, err := fixture.VersionRowCount(ctx, id) - if err != nil { - t.Fatalf("counting version rows for %s: %v", id, err) - } - - if err := fixture.MutateExisting(ctx, id); err != nil { - t.Fatalf("mutating existing %s: %v", id, err) - } - - afterRevision, err := fixture.CurrentRevision(ctx, id) - if err != nil { - t.Fatalf("reading current_revision for %s: %v", id, err) - } - afterCount, err := fixture.VersionRowCount(ctx, id) - if err != nil { - t.Fatalf("counting version rows for %s: %v", id, err) - } - if afterCount != beforeCount { - t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation with the "+ - "flag off, want unchanged: turning versioned history off stops minting for every record, "+ - "including one that already participates", id, beforeCount, afterCount) - } - if afterRevision != beforeRevision { - t.Errorf("current_revision for %s went from %d to %d across the same update with the flag off, "+ - "want unchanged", id, beforeRevision, afterRevision) - } -} - // RunParticipationGenerationWispPromotionBeginsHistory pins that promoting a // wisp onto the issues plane is CREATE-shaped in design §16.2b's sense. (This // is wisp promotion, PromoteFromEphemeral: not R2.3's promotion of a legacy diff --git a/backend/conformance/retention_epoch_contract.go b/backend/conformance/retention_epoch_contract.go index b2c0d100e..472b7a896 100644 --- a/backend/conformance/retention_epoch_contract.go +++ b/backend/conformance/retention_epoch_contract.go @@ -769,21 +769,7 @@ type EpochFixture struct { // Version now resolves to under the new epoch. A nil hook means this // backend cannot report that, and the case that needs it skips with // that reason. - // - // It only reads: it mints nothing and changes no state. It returns the - // address it was given when nothing carried the Version to a new one, - // and an error for an address the store does not serve. CurrentAddressFor func(ctx context.Context, storeID string, oldAddress Address) (Address, error) - - // LoseVersion records that storeID no longer serves the Version named by - // address. That address, and every address the same Version was carried - // to or from by a token-scheme change, resolves GoneReorganization from - // then on, in every later epoch: an epoch voids what the store lost, - // never what it still serves (R20-n). It is idempotent, never revives - // anything, and returns an error for an address storeID never minted. A - // nil LoseVersion means this backend cannot record a loss, and the cases - // that need one skip with that reason. - LoseVersion func(ctx context.Context, storeID string, address Address) error } // RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange pins R20-m: a @@ -833,258 +819,94 @@ func RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t *testing.T, ct // RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed pins R20-n — "Rev7 // tightening... the clause most likely to be gotten wrong" in the -// architecture doc's own words: an epoch voids what the store lost, never -// what it still serves. +// architecture doc's own words. A prior-epoch Address goes +// GoneReorganization UNLESS the backend still serves that Version, in which +// case it must stay Live AND additionally report the Address it now +// resolves to under the new epoch. // -// Survival is RECORDED, never inferred (gastownhall/beads#6664, bee-ghosttrack -// review 5360880888, Major 1). An earlier form of this case made a Version -// survive by minting it again in every later epoch, and treated a Version -// nobody minted again as lost. That reads loss off the absence of a mint, so -// it could not express a Version the store lost after minting it, and it -// voided every survivor that nobody happened to mint again. Here a restore or -// a destructive reinit leaves every address row alone: an address the store -// still serves stays Live at its own address with no upkeep, and the only way -// an address goes Gone is LoseVersion saying so. -// -// Each phase is a named subtest, so a backend that cannot record a loss skips -// only the phases that need LoseVersion, and a failure names its phase. +// StillServes is an ORACLE here, not a control: this case cannot make a real +// backend keep serving one address and drop another, since Phase 0 wires no +// real backend. It asks StillServes what the fixture (once real) decided, +// and checks the rest of the contract's promise against that decision for +// both outcomes. func RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t *testing.T, ctx context.Context, fixture EpochFixture) { t.Helper() - epochSkipUnlessReady(t, fixture, false) - - // survivor-and-lost: of two Versions minted before a transition, the one - // the store loses goes Gone and the other stays Live at the address it - // already had, with no re-mint, for both triggers that leave addresses - // alone. - t.Run("survivor-and-lost", func(t *testing.T) { - if fixture.LoseVersion == nil { - t.Skip(epochLoseVersionSkip) - } - for _, trigger := range []EpochBumpTrigger{EpochBumpTriggerRestore, EpochBumpTriggerDestructiveReinit} { - t.Run(trigger.String(), func(t *testing.T) { - store := epochStore(fixture, "survivor-"+trigger.String()) - addrA := epochMintAddress(t, ctx, fixture, store, "record-a") - addrB := epochMintAddress(t, ctx, fixture, store, "record-b") - - newEpoch := epochBumpTo(t, ctx, fixture, store, trigger) - epochLoseAddress(t, ctx, fixture, store, addrB) - - epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, - "record-a was never lost, so the transition leaves it served at its own address with no re-mint (R20-n's exception)") - epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, - "record-b was lost, so the transition voids it (R20-n)") - - current := epochCurrentAddress(t, ctx, fixture, store, addrA) - epochRequireLive(t, ctx, fixture, store, current, newEpoch, - "the address CurrentAddressFor reports for a survivor must be served") - epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, - "asking CurrentAddressFor must not retire or move the survivor's address") - - if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil { - t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version has no current address", lostCurrent) - } - epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, - "CurrentAddressFor on a lost address must not bring it back") - }) - } - }) - - // gone-is-terminal: once an address is lost it stays lost. A later mint of - // the same id starts a new lineage under a new address, and neither that - // mint nor CurrentAddressFor revives the lost one (bee-ghosttrack's - // assertion for Major 1: a read-only lookup must not mint a replacement - // that makes a lost address look served). - t.Run("gone-is-terminal", func(t *testing.T) { - if fixture.LoseVersion == nil { - t.Skip(epochLoseVersionSkip) - } - store := epochStore(fixture, "terminal") - lost := epochMintAddress(t, ctx, fixture, store, "record-g") - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - epochLoseAddress(t, ctx, fixture, store, lost) - laterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - - fresh := epochMintAddress(t, ctx, fixture, store, "record-g") - if fresh == lost { - t.Fatalf("MintUnderEpoch(record-g) returned %s, the address already lost: a lost address is never handed out again", lost) - } - epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch, - "a fresh mint of the id is a new lineage and is served") - epochRequireGone(t, ctx, fixture, store, lost, laterEpoch, - "a later mint of the same id must not revive a lost address") - - if replacement, err := fixture.CurrentAddressFor(ctx, store, lost); err == nil { - t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: asking where a lost address resolves must not mint a replacement", replacement) - } - epochRequireGone(t, ctx, fixture, store, lost, laterEpoch, - "CurrentAddressFor on a lost address must not revive it") - - // Losing it a second time is a no-op that leaves the fresh lineage - // alone. - epochLoseAddress(t, ctx, fixture, store, lost) - epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch, - "losing the old address again must leave the fresh lineage served") - }) - - // survival-needs-no-upkeep: with nothing lost, an address stays Live across - // any number of counter-only transitions without being minted again, and a - // later mint of the same id neither retires it nor revives anything. This - // is the phase the earlier, mint-driven form failed: it answered Gone for - // every survivor nobody minted again. - t.Run("survival-needs-no-upkeep", func(t *testing.T) { - store := epochStore(fixture, "upkeep") - kept := epochMintAddress(t, ctx, fixture, store, "record-c") - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit) - finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - - epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, - "nothing was lost, so three counter-only transitions leave the address served without a re-mint") - - fresh := epochMintAddress(t, ctx, fixture, store, "record-c") - if fresh == kept { - t.Fatalf("MintUnderEpoch(record-c) returned %s again after three bumps, want a new address for the new epoch", kept) - } - epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, - "a later mint of the same id must not retire a served address") - epochRequireLive(t, ctx, fixture, store, fresh, finalEpoch, - "the fresh mint is served") - - current := epochCurrentAddress(t, ctx, fixture, store, kept) - epochRequireLive(t, ctx, fixture, store, current, finalEpoch, - "the current address of a survivor must be served") - epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, - "asking for the current address must not change the survivor") - }) -} - -// RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose pins R20-n's retained -// mapping for the one trigger that changes how addresses are encoded. A -// token-scheme-change bump gives every Version the store still serves a new -// address under the new epoch and keeps the old address resolving, so a holder -// of the old address is neither stranded nor pointed at something else. A -// Version the store already lost gets no new address and stays Gone. -func RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t *testing.T, ctx context.Context, fixture EpochFixture) { - t.Helper() - epochSkipUnlessReady(t, fixture, true) - store := epochStore(fixture, "scheme-change") - - addrA := epochMintAddress(t, ctx, fixture, store, "record-a") - addrB := epochMintAddress(t, ctx, fixture, store, "record-b") - // record-b is lost in the epoch it was minted in, which a store may do. - epochLoseAddress(t, ctx, fixture, store, addrB) - - newEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) - - epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, - "record-a is still served after the scheme change, through the retained mapping") - epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, - "record-b was lost before the scheme change, which must not carry it") - - carried := epochCurrentAddress(t, ctx, fixture, store, addrA) - if carried == addrA { - t.Errorf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one: a scheme change re-encodes every served address, which is what tells a carry from a no-op", addrA) + if fixture.MintUnderEpoch == nil { + t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)") } - epochRequireLive(t, ctx, fixture, store, carried, newEpoch, - "the carried address must be served under the new epoch") - epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, - "the old address must keep resolving after its carried address is looked up") - - if again := epochCurrentAddress(t, ctx, fixture, store, carried); again != carried { - t.Errorf("CurrentAddressFor(%s) = %s, want the carried address itself: from the newest address the mapping is already current", carried, again) + if fixture.BumpEpoch == nil { + t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)") } - if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil { - t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version is not carried", lostCurrent) + if fixture.StillServes == nil { + t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)") } -} + if fixture.Resolve == nil { + t.Skip("this backend does not yet report retention state (Resolve is nil)") + } + if fixture.CurrentAddressFor == nil { + t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)") + } + store := epochStore(fixture, "voids") -// RunACarriedAddressKeepsResolvingAcrossLaterBumps pins that a carried mapping -// is recorded once and then simply persists: later counter-only transitions do -// not change it, and a second token-scheme change extends it to the newest -// address without breaking any older one. Every address of the Version points -// directly at the newest address (one hop from any member), never along a -// chain. -func RunACarriedAddressKeepsResolvingAcrossLaterBumps(t *testing.T, ctx context.Context, fixture EpochFixture) { - t.Helper() - epochSkipUnlessReady(t, fixture, false) - store := epochStore(fixture, "carried-later") - - addrA := epochMintAddress(t, ctx, fixture, store, "record-a") - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) - addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA) - if addrA1 == addrA { - t.Fatalf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one", addrA) + addrA, err := fixture.MintUnderEpoch(ctx, store, "record-a") + if err != nil { + t.Fatalf("MintUnderEpoch(record-a): %v", err) + } + addrB, err := fixture.MintUnderEpoch(ctx, store, "record-b") + if err != nil { + t.Fatalf("MintUnderEpoch(record-b): %v", err) } - // Two counter-only transitions, with nothing minted in between. - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - counterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit) - epochRequireLive(t, ctx, fixture, store, addrA, counterEpoch, - "the original address must still resolve after counter-only transitions") - epochRequireLive(t, ctx, fixture, store, addrA1, counterEpoch, - "the carried address must still resolve after counter-only transitions") - if got := epochCurrentAddress(t, ctx, fixture, store, addrA); got != addrA1 { - t.Errorf("CurrentAddressFor(%s) = %s, want %s: a counter-only transition does not change the mapping", addrA, got, addrA1) + newEpoch, err := fixture.BumpEpoch(ctx, store, EpochBumpTriggerRestore) + if err != nil { + t.Fatalf("BumpEpoch: %v", err) } - // A second scheme change carries the Version again. - secondEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) - addrA2 := epochCurrentAddress(t, ctx, fixture, store, addrA) - if addrA2 == addrA || addrA2 == addrA1 { - t.Fatalf("CurrentAddressFor(%s) = %s after a second scheme change, want an address different from %s and %s", addrA, addrA2, addrA, addrA1) + servesA, err := fixture.StillServes(ctx, store, addrA) + if err != nil { + t.Fatalf("StillServes(%s): %v", addrA, err) } - for _, member := range []Address{addrA, addrA1, addrA2} { - epochRequireLive(t, ctx, fixture, store, member, secondEpoch, - "every address of a carried Version must resolve after a second scheme change") + servesB, err := fixture.StillServes(ctx, store, addrB) + if err != nil { + t.Fatalf("StillServes(%s): %v", addrB, err) } - if got := epochCurrentAddress(t, ctx, fixture, store, addrA1); got != addrA2 { - t.Errorf("CurrentAddressFor(%s) = %s, want %s: every address of the Version points straight at the newest one", addrA1, got, addrA2) + if servesA == servesB { + t.Skip("this scenario needs one still-served and one no-longer-served address to exercise both halves of R20-n; StillServes reported the same answer for both, so this fixture gives this case nothing to contrast") } - finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - epochRequireLive(t, ctx, fixture, store, addrA2, finalEpoch, - "the newest carried address must still resolve after a later restore") -} - -// RunALostAddressStaysGoneAcrossASchemeChange pins that loss is terminal even -// across a token-scheme change. Losing a Version loses every address of its -// lineage at once, and a later scheme change must not carry a lost lineage -// back into service. -func RunALostAddressStaysGoneAcrossASchemeChange(t *testing.T, ctx context.Context, fixture EpochFixture) { - t.Helper() - epochSkipUnlessReady(t, fixture, true) - store := epochStore(fixture, "lost-scheme-change") - - addrA := epochMintAddress(t, ctx, fixture, store, "record-a") - epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) - addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA) - lostEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) - - // One lineage, two addresses: losing either loses both. - epochLoseAddress(t, ctx, fixture, store, addrA) - epochRequireGone(t, ctx, fixture, store, addrA, lostEpoch, - "the original address of a lost Version must be Gone") - epochRequireGone(t, ctx, fixture, store, addrA1, lostEpoch, - "the carried address of a lost Version must be Gone too") - - schemeEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) - epochRequireGone(t, ctx, fixture, store, addrA, schemeEpoch, - "a later scheme change must not carry a lost lineage back into service") - epochRequireGone(t, ctx, fixture, store, addrA1, schemeEpoch, - "a later scheme change must not carry a lost lineage back into service") - for _, lostAddress := range []Address{addrA, addrA1} { - if current, err := fixture.CurrentAddressFor(ctx, store, lostAddress); err == nil { - t.Errorf("CurrentAddressFor(%s) = %s with no error, want an error: a lost lineage has no current address", lostAddress, current) - } + stillServed, noLongerServed := addrA, addrB + if servesB && !servesA { + stillServed, noLongerServed = addrB, addrA } - fresh := epochMintAddress(t, ctx, fixture, store, "record-a") - if fresh == addrA || fresh == addrA1 { - t.Fatalf("MintUnderEpoch(record-a) returned %s, an address of the lost lineage: a lost address is never handed out again", fresh) + voidedAnswer, err := fixture.Resolve(ctx, store, noLongerServed) + if err != nil { + t.Fatalf("Resolve(no-longer-served): %v", err) + } + if voidedAnswer.Restriction != RestrictionGoneReorganization { + t.Errorf("Resolve(a prior-epoch Address no longer served) = %s, want RestrictionGoneReorganization (R20-n)", voidedAnswer.Restriction) + } + if voidedAnswer.Epoch == nil { + t.Fatal("Resolve(a prior-epoch Address no longer served).Epoch = nil, want the current epoch populated (R20-n: the answer must name the current epoch, not just Restriction alone)") + } else if *voidedAnswer.Epoch != newEpoch { + t.Errorf("Resolve(a prior-epoch Address no longer served).Epoch = %d, want the current epoch %d", *voidedAnswer.Epoch, newEpoch) + } + + keptAnswer, err := fixture.Resolve(ctx, store, stillServed) + if err != nil { + t.Fatalf("Resolve(still-served): %v", err) + } + if keptAnswer.Restriction != RestrictionLive { + t.Errorf("Resolve(a prior-epoch Address the backend still serves) = %s, want RestrictionLive (R20-n's exception)", keptAnswer.Restriction) + } + + newAddr, err := fixture.CurrentAddressFor(ctx, store, stillServed) + if err != nil { + t.Fatalf("CurrentAddressFor(%s): %v", stillServed, err) + } + if newAddr == "" { + t.Error("CurrentAddressFor(a still-served prior-epoch Address) returned an empty Address, want a real one under the new epoch") } - epochRequireLive(t, ctx, fixture, store, fresh, schemeEpoch, - "a fresh mint of the id after the loss is a new lineage and is served") } // --- fixture helpers ------------------------------------------------------- @@ -1131,137 +953,6 @@ func epochStore(fixture EpochFixture, tag string) string { return fixture.IssuePrefix + "-epoch-store-" + tag } -// epochLoseVersionSkip is the skip reason of every phase that needs -// EpochFixture.LoseVersion. -const epochLoseVersionSkip = "this backend cannot record that the store lost a Version (LoseVersion is nil)" - -// epochSkipUnlessReady skips the case when the fixture lacks a capability the -// epoch cases need. The cases that record a loss also need LoseVersion. The -// all-nil wiring test runs every case against an empty fixture, so each case -// must call this before it touches any of them. -func epochSkipUnlessReady(t *testing.T, fixture EpochFixture, needsLoseVersion bool) { - t.Helper() - if fixture.MintUnderEpoch == nil { - t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)") - } - if fixture.BumpEpoch == nil { - t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)") - } - if fixture.StillServes == nil { - t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)") - } - if fixture.Resolve == nil { - t.Skip("this backend does not yet report retention state (Resolve is nil)") - } - if fixture.CurrentAddressFor == nil { - t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)") - } - if needsLoseVersion && fixture.LoseVersion == nil { - t.Skip(epochLoseVersionSkip) - } -} - -// epochMintAddress mints id on store, failing the case if minting fails. -func epochMintAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store, id string) Address { - t.Helper() - address, err := fixture.MintUnderEpoch(ctx, store, id) - if err != nil { - t.Fatalf("MintUnderEpoch(%s, %s): %v", store, id, err) - } - return address -} - -// epochBumpTo bumps store's epoch for trigger and returns the epoch it -// reports. Epochs are captured from the return value, never assumed: the -// counter is one per database, shared by every store the suite uses. -func epochBumpTo(t *testing.T, ctx context.Context, fixture EpochFixture, store string, trigger EpochBumpTrigger) int { - t.Helper() - epoch, err := fixture.BumpEpoch(ctx, store, trigger) - if err != nil { - t.Fatalf("BumpEpoch(%s, %s): %v", store, trigger, err) - } - return epoch -} - -// epochLoseAddress records that store lost the Version behind address. -func epochLoseAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) { - t.Helper() - if err := fixture.LoseVersion(ctx, store, address); err != nil { - t.Fatalf("LoseVersion(%s, %s): %v", store, address, err) - } -} - -// epochCurrentAddress asks where address now resolves, failing the case on an -// error or an empty answer. -func epochCurrentAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) Address { - t.Helper() - current, err := fixture.CurrentAddressFor(ctx, store, address) - if err != nil { - t.Fatalf("CurrentAddressFor(%s, %s): %v", store, address, err) - } - if current == "" { - t.Fatalf("CurrentAddressFor(%s, %s) returned an empty Address, want a real one", store, address) - } - return current -} - -// epochRequireLive asserts that address is served at epoch: StillServes is true -// and Resolve answers RestrictionLive naming that epoch. why says what the -// assertion is checking, for the failure message. -func epochRequireLive(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) { - t.Helper() - serves, err := fixture.StillServes(ctx, store, address) - if err != nil { - t.Fatalf("StillServes(%s): %v", address, err) - } - if !serves { - t.Errorf("StillServes(%s) = false, want true: %s", address, why) - } - answer, err := fixture.Resolve(ctx, store, address) - if err != nil { - t.Fatalf("Resolve(%s): %v", address, err) - } - if answer.Restriction != RestrictionLive { - t.Errorf("Resolve(%s) = %s, want RestrictionLive: %s", address, answer.Restriction, why) - } - epochRequireAnswerEpoch(t, answer, address, epoch, why) -} - -// epochRequireGone asserts that address is no longer served at epoch: -// StillServes is false and Resolve answers RestrictionGoneReorganization -// naming that epoch. -func epochRequireGone(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) { - t.Helper() - serves, err := fixture.StillServes(ctx, store, address) - if err != nil { - t.Fatalf("StillServes(%s): %v", address, err) - } - if serves { - t.Errorf("StillServes(%s) = true, want false: %s", address, why) - } - answer, err := fixture.Resolve(ctx, store, address) - if err != nil { - t.Fatalf("Resolve(%s): %v", address, err) - } - if answer.Restriction != RestrictionGoneReorganization { - t.Errorf("Resolve(%s) = %s, want RestrictionGoneReorganization: %s", address, answer.Restriction, why) - } - epochRequireAnswerEpoch(t, answer, address, epoch, why) -} - -// epochRequireAnswerEpoch asserts that a Live or Gone answer names the current -// epoch (R20-n: the answer carries the epoch, not just the Restriction). -func epochRequireAnswerEpoch(t *testing.T, answer RetentionAnswer, address Address, epoch int, why string) { - t.Helper() - if answer.Epoch == nil { - t.Errorf("Resolve(%s).Epoch = nil, want the current epoch %d: %s", address, epoch, why) - return - } - if *answer.Epoch != epoch { - t.Errorf("Resolve(%s).Epoch = %d, want the current epoch %d: %s", address, *answer.Epoch, epoch, why) - } -} - // sameRetentionAnswer compares two RetentionAnswer values by content rather // than identity, so a case can assert "this did not change" without // depending on the concrete Restriction the backend happened to pick. diff --git a/backend/conformance/versioned_history_wiring_test.go b/backend/conformance/versioned_history_wiring_test.go index b022b716e..08eed2b53 100644 --- a/backend/conformance/versioned_history_wiring_test.go +++ b/backend/conformance/versioned_history_wiring_test.go @@ -129,14 +129,5 @@ func TestVersionedHistoryPhase0RunsInFullSkipMode(t *testing.T) { t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) { RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture) }) - t.Run("TokenSchemeChangeCarriesLiveAddressesAndOnlyThose", func(t *testing.T) { - RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t, ctx, fixture) - }) - t.Run("ACarriedAddressKeepsResolvingAcrossLaterBumps", func(t *testing.T) { - RunACarriedAddressKeepsResolvingAcrossLaterBumps(t, ctx, fixture) - }) - t.Run("ALostAddressStaysGoneAcrossASchemeChange", func(t *testing.T) { - RunALostAddressStaysGoneAcrossASchemeChange(t, ctx, fixture) - }) }) } diff --git a/backend/conformance/versioned_read_contract.go b/backend/conformance/versioned_read_contract.go deleted file mode 100644 index 0e187117c..000000000 --- a/backend/conformance/versioned_read_contract.go +++ /dev/null @@ -1,356 +0,0 @@ -package conformance - -import ( - "context" - "testing" - "time" -) - -// This file holds the contract for R7.1 (gastownhall/beads#6136, design doc -// gastownhall/beads#5898 revision 9): the as-of read — the "versioned -// reads" half of Phase 3's title, authored here from scratch, since no -// fixture for it exists anywhere in this package to un-skip. -// -// R7.1, VERBATIM (design doc #5898 rev 9): "An as-of read is a named read -// whose selector is an instant. Given an instant T or a version address, a -// store returns one Bead's durable state as of that point — the latest -// version it holds that was accepted at or before T, with everything later -// excluded — under R7's record shape, marking the address it served, or -// refuses as gone or unknown with the reason (R8, R20). Like every history -// answer it is complete for the answering store's holdings and may change -// after a sync (TC3)." -// -// ADDRESS, RESTRICTION, AND CHANGEATTRIBUTION ARE DECLARED IN -// expected_revision_contract.go — see that file's package-level note on -// where this suite's shared vocabulary lives and why. This file reuses -// Restriction's five values as-is for the gone-or-unknown refusal outcome -// (R8): an as-of read never invents a sixth state, and never distinguishes -// "gone" from "unknown" any differently than R20 already does. -// -// EVERY HOOK ON THE FIXTURE BELOW IS INDEPENDENTLY NILABLE — see the -// package-level note in expected_revision_contract.go. Every case -// nil-checks every hook it uses and SKIPS BY NAME when one is missing. No -// backend implements as-of reads yet — the implementation is -// the child this suite is written ahead of. -// -// EXPLICIT NON-GOAL: MEMORY-PLANE CONSUMER POLICY IS NOT PART OF THIS -// PRIMITIVE. R7.1's own text is explicit that a closed-before-T boundary, -// sibling exclusion, and supersession exclusion "are Memory-plane policies -// a consumer layers on this primitive (#5877), not part of it." This suite -// does not implement or assert any of the three — a future reader who finds -// them absent should read that as this file honoring R7.1's own scope, not -// as an oversight. This is the read-side analog of the R16/R16.1 boundary -// risk already recorded in expected_revision_contract.go: do not conflate -// the primitive with policy layered on top of it. -// -// THIS SUITE ASSERTS LOCAL COMPLETENESS ONLY (TC3). Nothing below requires, -// or even checks, that two stores asked about the same lineage agree — R7.1 -// itself says an as-of answer "may change after a sync," so two stores at -// different sync points are expected to answer differently, and neither is -// wrong. RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings is the one -// case that touches more than one store, and what it asserts is exactly -// this: each store answers strictly from its own holdings, never a -// sibling's — not that the two agree. - -// AsOfSelector names the point R7.1 resolves against: either a wall-clock -// instant, or a specific version Address treated as the selector itself — -// "the read that names its own answer" (R7.1: "an instant T or a version -// address"). Exactly one of At/Version is populated in every case this file -// exercises; R7.1 does not speak to the shape where both or neither are -// set, so this suite does not either. -type AsOfSelector struct { - At *time.Time - Version *Address -} - -// AsOfReadRefusal is R8's typed outcome for an as-of read that cannot be -// answered. Restriction is always one of the four Gone*/Unknown values, -// never RestrictionLive — a live answer is a served AsOfReadResult, not a -// refusal. Reason explains why (R8). -type AsOfReadRefusal struct { - Restriction Restriction - Reason string -} - -// AsOfReadResult is the outcome of an as-of read (R7.1). Address/State and -// Refusal are mutually exclusive: read Address/State only when Refusal is -// nil. -type AsOfReadResult struct { - // Address is the version this read served, marking "the address it - // served" (R7.1). Populated only when Refusal is nil. - Address Address - // State is the served version's durable state under R7's record shape. - // Opaque to this suite: the fixture adapter translates a backend's real - // record shape into this map, and no case here asserts its field-level - // content — only that a served result carries an Address. - State map[string]any - // Refusal is populated instead of Address/State when the read cannot be - // answered (R8). Nil means the read was served. - Refusal *AsOfReadRefusal -} - -// AsOfRead resolves storeID's answer to an as-of read against id's lineage, -// at selector (R7.1). -type AsOfRead func(ctx context.Context, storeID, id string, selector AsOfSelector) (AsOfReadResult, error) - -// AsOfReadFixture supplies the capability under test for R7.1: a read whose -// selector is an instant or a version address, resolving to the latest -// version accepted at or before that point, or a typed refusal. -type AsOfReadFixture struct { - IssuePrefix string - - // Resolve performs the as-of read under test (R7.1). A nil hook means - // this backend does not implement as-of reads yet, and every case in - // this file skips with that reason. - Resolve AsOfRead - - // MintAt mints a fresh version for id under storeID, recorded as - // accepted at the given instant, and returns its Address. Cases use - // this to build a lineage with known accept-times to resolve an as-of - // read against. A nil hook means this backend has no way to mint a - // version at a controlled accept-time, and cases that need one skip - // with that reason. - MintAt func(ctx context.Context, storeID, id string, acceptedAt time.Time) (Address, error) - - // MakeUnanswerable arranges for id to be unanswerable at storeID for - // the given Restriction (one of RestrictionGoneRetention/GoneErasure/ - // GoneReorganization/Unknown) — independently of - // RetentionFixture/EpochFixture's own removal machinery, since R7.1's - // refusal is a sibling contract to R17/R20, not a dependent of them. A - // nil hook means this backend has no way to arrange this, and the case - // that needs it skips with that reason. - MakeUnanswerable func(ctx context.Context, storeID, id string, restriction Restriction) error -} - -// RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress pins R7.1's -// selector shape: an instant T and the version address that instant -// resolves to are two names for the same answer, and a store must accept -// either. -func RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { - t.Helper() - if fixture.Resolve == nil { - t.Skip("this backend does not implement as-of reads (Resolve is nil)") - } - if fixture.MintAt == nil { - t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") - } - store := asOfReadStore(fixture, "selector-kinds") - id := fixture.IssuePrefix + "-asof-selector" - t0 := time.Now().UTC().Add(-time.Hour) - asOfReadMint(t, ctx, fixture, store, id, t0) - t1 := t0.Add(time.Minute) - second := asOfReadMint(t, ctx, fixture, store, id, t1) - - byInstant, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1}) - if err != nil { - t.Fatalf("Resolve(selector=instant): %v", err) - } - if byInstant.Refusal != nil { - t.Fatalf("Resolve(selector=instant) = %+v, want a served result", byInstant) - } - - byVersion, err := fixture.Resolve(ctx, store, id, AsOfSelector{Version: &second}) - if err != nil { - t.Fatalf("Resolve(selector=version address): %v", err) - } - if byVersion.Refusal != nil { - t.Fatalf("Resolve(selector=version address) = %+v, want a served result", byVersion) - } - - if byInstant.Address != second { - t.Errorf("Resolve(selector=instant matching a version's own accept-time).Address = %s, want %s", byInstant.Address, second) - } - if byVersion.Address != second { - t.Errorf("Resolve(selector=version address).Address = %s, want the same address named %s", byVersion.Address, second) - } - if byInstant.Address != byVersion.Address { - t.Errorf("an instant selector (served %s) and a version-address selector naming the same version (served %s) resolved to different addresses; R7.1 accepts either as a name for the same answer", byInstant.Address, byVersion.Address) - } -} - -// RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater pins -// R7.1's ordering promise: resolving at T returns the latest version -// accepted at or before T, and a version accepted after T is excluded even -// when its own instant is close by. -func RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { - t.Helper() - if fixture.Resolve == nil { - t.Skip("this backend does not implement as-of reads (Resolve is nil)") - } - if fixture.MintAt == nil { - t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") - } - store := asOfReadStore(fixture, "ordering") - id := fixture.IssuePrefix + "-asof-ordering" - t0 := time.Now().UTC().Add(-time.Hour) - asOfReadMint(t, ctx, fixture, store, id, t0) - t1 := t0.Add(time.Minute) - middle := asOfReadMint(t, ctx, fixture, store, id, t1) - t2 := t0.Add(2 * time.Minute) - asOfReadMint(t, ctx, fixture, store, id, t2) - - atExactly, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1}) - if err != nil { - t.Fatalf("Resolve(T=middle's own instant): %v", err) - } - if atExactly.Refusal != nil || atExactly.Address != middle { - t.Errorf("Resolve(T=middle's own instant) = %+v, want the version accepted exactly at T (%s), not a later one", atExactly, middle) - } - - between := t1.Add(30 * time.Second) - betweenResult, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &between}) - if err != nil { - t.Fatalf("Resolve(T strictly between two versions): %v", err) - } - if betweenResult.Refusal != nil || betweenResult.Address != middle { - t.Errorf("Resolve(T strictly between two versions) = %+v, want the latest version at-or-before T (%s); the version accepted after T must be strictly excluded", betweenResult, middle) - } -} - -// RunAsOfReadReportsTheAddressItServed pins R7.1's "marking the address it -// served": a served result names the exact Address of the version it -// returned, not merely a truthy success. -func RunAsOfReadReportsTheAddressItServed(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { - t.Helper() - if fixture.Resolve == nil { - t.Skip("this backend does not implement as-of reads (Resolve is nil)") - } - if fixture.MintAt == nil { - t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") - } - store := asOfReadStore(fixture, "reports-address") - id := fixture.IssuePrefix + "-asof-reports-address" - at := time.Now().UTC() - address := asOfReadMint(t, ctx, fixture, store, id, at) - - result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at}) - if err != nil { - t.Fatalf("Resolve: %v", err) - } - if result.Refusal != nil { - t.Fatalf("Resolve = %+v, want a served result", result) - } - if result.Address == "" { - t.Fatal("Resolve returned an empty Address on a served result, want the address of the version it served (R7.1)") - } - if result.Address != address { - t.Errorf("Resolve(...).Address = %s, want the served version's own address %s", result.Address, address) - } -} - -// RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion pins R8: -// a read that cannot be answered refuses as a typed Gone or Unknown outcome -// with a reason, and never silently returns a neighboring version, the -// nearest surviving version, or current state as a substitute — R8's own -// text names all three as non-answers. -func RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { - t.Helper() - if fixture.Resolve == nil { - t.Skip("this backend does not implement as-of reads (Resolve is nil)") - } - if fixture.MintAt == nil { - t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") - } - if fixture.MakeUnanswerable == nil { - t.Skip("this backend has no way to make a lineage unanswerable (MakeUnanswerable is nil)") - } - - for _, restriction := range []Restriction{ - RestrictionGoneRetention, - RestrictionGoneErasure, - RestrictionGoneReorganization, - RestrictionUnknown, - } { - t.Run(restriction.String(), func(t *testing.T) { - store := asOfReadStore(fixture, "unanswerable-"+restriction.String()) - id := fixture.IssuePrefix + "-asof-unanswerable-" + restriction.String() - at := time.Now().UTC() - address := asOfReadMint(t, ctx, fixture, store, id, at) - - if err := fixture.MakeUnanswerable(ctx, store, id, restriction); err != nil { - t.Fatalf("MakeUnanswerable(%s, %s): %v", id, restriction, err) - } - - result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at}) - if err != nil { - t.Fatalf("Resolve after MakeUnanswerable(%s): %v", restriction, err) - } - if result.Refusal == nil { - t.Fatalf("Resolve after MakeUnanswerable(%s) = %+v, want a Refusal, not a served result (R8)", restriction, result) - } - if result.Refusal.Restriction != restriction { - t.Errorf("Refusal.Restriction = %s, want %s", result.Refusal.Restriction, restriction) - } - if result.Refusal.Reason == "" { - t.Error("Refusal.Reason is empty, want a reason (R8)") - } - if result.Address != "" { - t.Errorf("Resolve on a refusal returned Address = %s, want empty: R8 forbids silently substituting a neighboring version, the nearest surviving version, or current state (the pre-refusal address was %s)", result.Address, address) - } - }) - } -} - -// RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings pins R7.1's closing -// clause and TC3: an as-of answer "is complete for the answering store's -// holdings and may change after a sync." This case asserts NOTHING about -// agreement between two stores asked about the same lineage — proving that -// absence is the point, not a gap. It mints a lineage into exactly one of -// two stores and confirms each store answers strictly from its own -// holdings: the store that holds the lineage serves it, and the store that -// never received it answers Unknown (FR-06, reused from R20) rather than -// reaching across to a sibling store's knowledge, erroring, or answering -// Gone — which would claim knowledge of a lineage it never held. -func RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { - t.Helper() - if fixture.Resolve == nil { - t.Skip("this backend does not implement as-of reads (Resolve is nil)") - } - if fixture.MintAt == nil { - t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") - } - holds := asOfReadStore(fixture, "tc3-holds-the-lineage") - neverSynced := asOfReadStore(fixture, "tc3-never-synced") - id := fixture.IssuePrefix + "-asof-tc3" - at := time.Now().UTC() - address := asOfReadMint(t, ctx, fixture, holds, id, at) - - local, err := fixture.Resolve(ctx, holds, id, AsOfSelector{At: &at}) - if err != nil { - t.Fatalf("Resolve on the store that holds the lineage: %v", err) - } - if local.Refusal != nil || local.Address != address { - t.Fatalf("Resolve on the store that holds the lineage = %+v, want it served from that store's own holdings (%s)", local, address) - } - - remote, err := fixture.Resolve(ctx, neverSynced, id, AsOfSelector{At: &at}) - if err != nil { - t.Fatalf("Resolve on a store that never received this lineage: %v", err) - } - if remote.Refusal == nil { - t.Fatalf("Resolve on a store that never received this lineage = %+v, want a Refusal: an as-of answer is complete for the answering store's own holdings, not a sibling's (TC3)", remote) - } - if remote.Refusal.Restriction != RestrictionUnknown { - t.Errorf("Refusal.Restriction on the never-synced store = %s, want RestrictionUnknown: no lineage knowledge is Unknown, not Gone (FR-06)", remote.Refusal.Restriction) - } -} - -// --- fixture helpers ------------------------------------------------------- - -// asOfReadStore names a storeID namespaced by the fixture's IssuePrefix and -// tag, so cases that need more than one store (e.g. the TC3 local- -// completeness case) get independent ones. -func asOfReadStore(fixture AsOfReadFixture, tag string) string { - return fixture.IssuePrefix + "-asof-store-" + tag -} - -// asOfReadMint mints a version for id on store at the given instant via -// fixture.MintAt, fataling the case if minting fails. -func asOfReadMint(t *testing.T, ctx context.Context, fixture AsOfReadFixture, store, id string, at time.Time) Address { - t.Helper() - address, err := fixture.MintAt(ctx, store, id, at) - if err != nil { - t.Fatalf("MintAt(%s, %s, %s): %v", store, id, at, err) - } - return address -} diff --git a/backend/http/BUILD.bazel b/backend/http/BUILD.bazel index f6359f820..1e622733c 100644 --- a/backend/http/BUILD.bazel +++ b/backend/http/BUILD.bazel @@ -37,7 +37,6 @@ go_test( "e2e_export_test.go", "e2e_gates_test.go", "e2e_heartbeat_test.go", - "e2e_link_test.go", "e2e_list_filters_test.go", "e2e_list_page_edges_test.go", "e2e_mol_test.go", diff --git a/backend/http/e2e_link_test.go b/backend/http/e2e_link_test.go deleted file mode 100644 index ae5a75146..000000000 --- a/backend/http/e2e_link_test.go +++ /dev/null @@ -1,137 +0,0 @@ -//go:build cgo - -package bdhttp_test - -import ( - "encoding/json" - "strings" - "testing" -) - -// TestE2E_LinkOverHTTP runs `bd link` through the real `bd` binary against an -// in-process `bd serve`. -// -// bd link writes through the DependencyEditor role (one addDependencies -// request), so it is served over http for any type a workspace spells, well- -// known or not: the server takes any 1-32 character type. Its own checks — -// a non-empty type of at most 32 characters — refuse before anything is -// written, and an edge that already exists with another type reports the -// typed conflict. -func TestE2E_LinkOverHTTP(t *testing.T) { - skipUnlessEmbeddedDolt(t) - bin := buildBD(t) - addr := startE2EServer(t) - proxyAddr, counter := startCountingProxy(t, addr) - f := newHTTPFixture(t, bin, proxyAddr) - - t.Run("custom types are served", func(t *testing.T) { - for _, depType := range []string{"owned-by", "ships-in", "available-in", "excluded-from", "advances", "launches", "blocks"} { - from := f.create("link source " + depType) - to := f.create("link target " + depType) - - counter.reset() - r := f.mustRun(nil, "link", from, to, "--type", depType, "--json") - var out map[string]any - if err := json.Unmarshal([]byte(strings.TrimSpace(r.stdout)), &out); err != nil { - t.Fatalf("bd link --json: %v\n%s", err, r.stdout) - } - if out["status"] != "added" || out["issue_id"] != from || out["depends_on_id"] != to || out["type"] != depType { - t.Errorf("bd link --type %s --json = %v, want added %s -> %s", depType, out, from, to) - } - adds := 0 - for _, p := range counter.snapshot() { - if p == "POST /v0/beads/dependencies:add" { - adds++ - } - } - if adds != 1 { - t.Errorf("bd link --type %s sent %d addDependencies requests, want exactly one: %v", depType, adds, counter.snapshot()) - } - - list := f.mustRun(nil, "dep", "list", from, "--json").stdout - if !depListHas(t, list, to, depType) { - t.Errorf("bd dep list %s does not show the %s edge to %s: %s", from, depType, to, list) - } - } - }) - - t.Run("text output names both issues", func(t *testing.T) { - from := f.create("text link source") - to := f.create("text link target") - r := f.mustRun(nil, "link", from, to, "--type", "owned-by") - if !strings.Contains(r.stdout, "Linked:") || !strings.Contains(r.stdout, "text link source") || - !strings.Contains(r.stdout, "text link target") || !strings.Contains(r.stdout, "(owned-by)") { - t.Errorf("bd link output = %q, want the Linked line with both titles and the type", r.stdout) - } - }) - - t.Run("invalid types refuse before any write", func(t *testing.T) { - from := f.create("invalid link source") - to := f.create("invalid link target") - for _, depType := range []string{"", strings.Repeat("x", 33)} { - counter.reset() - r := f.run(nil, "link", from, to, "--type", depType) - if r.code == 0 { - t.Fatalf("bd link --type %q exited 0: %s", depType, r.stdout) - } - if !strings.Contains(r.stderr, "invalid dependency type") { - t.Errorf("bd link --type %q stderr = %s, want the invalid-type refusal", depType, r.stderr) - } - for _, p := range counter.snapshot() { - if !strings.HasPrefix(p, "GET ") { - t.Errorf("bd link --type %q wrote %s; the refusal must come before any write", depType, p) - } - } - } - if list := f.mustRun(nil, "dep", "list", from, "--json").stdout; depListHas(t, list, to, "") { - t.Errorf("a refused link left an edge %s -> %s: %s", from, to, list) - } - }) - - t.Run("an edge of another type is a typed conflict", func(t *testing.T) { - from := f.create("conflict source") - to := f.create("conflict target") - f.mustRun(nil, "link", from, to, "--type", "owned-by") - r := f.run(nil, "link", from, to, "--type", "ships-in") - if r.code == 0 { - t.Fatalf("bd link over an existing owned-by edge with ships-in exited 0: %s", r.stdout) - } - // The server answers the role's typed conflict as 409 - // dependency_exists, which the client surfaces verbatim. - if !strings.Contains(r.stderr, "dependency_exists") || !strings.Contains(r.stderr, "different type") { - t.Errorf("conflict stderr = %s, want the typed dependency_exists conflict", r.stderr) - } - list := f.mustRun(nil, "dep", "list", from, "--json").stdout - if !depListHas(t, list, to, "owned-by") || depListHas(t, list, to, "ships-in") { - t.Errorf("the conflicting link changed the edge: %s", list) - } - // Re-asserting the same edge is idempotent. - f.mustRun(nil, "link", from, to, "--type", "owned-by") - }) -} - -// depListHas reports whether `bd dep list --json` lists an edge to target of -// depType (any type when depType is empty). -func depListHas(t *testing.T, out, target, depType string) bool { - t.Helper() - trimmed := strings.TrimSpace(out) - if trimmed == "" || trimmed == "null" { - return false - } - var rows []map[string]any - if err := json.Unmarshal([]byte(trimmed), &rows); err != nil { - t.Fatalf("parse bd dep list --json: %v\n%s", err, out) - } - for _, row := range rows { - if row["id"] != target && row["depends_on_id"] != target { - continue - } - if depType == "" { - return true - } - if row["dependency_type"] == depType || row["type"] == depType { - return true - } - } - return false -} diff --git a/backend/http/e2e_request_budget_test.go b/backend/http/e2e_request_budget_test.go index a37eaae64..fc8380d0e 100644 --- a/backend/http/e2e_request_budget_test.go +++ b/backend/http/e2e_request_budget_test.go @@ -53,15 +53,8 @@ func TestE2E_PerCommandRequestBudget(t *testing.T) { args []string }{ {"ready", 2, []string{"ready", "--json"}}, - // The limit hides rows, and without BD_JSON_ENVELOPE nothing - // prints their count: one listing, no ready:count after it. - {"ready --limit 1", 2, []string{"ready", "--json", "--limit", "1"}}, {"list", 4, []string{"list", "--json"}}, {"show", 1, []string{"show", target, "--json"}}, - // The first ready learned the server's external-dependency - // policy from the handshake; a later process reads it from the - // policy cache instead of fetching the context again. - {"ready, policy cached", 1, []string{"ready", "--json"}}, {"create", 2, []string{"create", "budget created", "-t", "task", "--json"}}, {"update --append-notes", 3, []string{"update", target, "--append-notes", "more", "--json"}}, {"update --status", 3, []string{"update", target, "--status", "in_progress", "--json"}}, diff --git a/beads.go b/beads.go index 235415c84..3b7d03fde 100644 --- a/beads.go +++ b/beads.go @@ -99,18 +99,6 @@ func configuredBackendUnavailable(backend, beadsDir string, cfg *configfile.Conf } } -// UnsupportedWorkspaceFormatError is returned by OpenBestAvailable, -// OpenBestAvailableWith, OpenFromConfig and OpenGated when the workspace -// declares a data model this build cannot open: a metadata.json graph_mode -// other than "dependency", such as the "link" workspaces graph-preview builds -// of bd write, or the .beads/graph-preview-format marker those builds write -// beside it (FormatMarker), whatever the metadata says. Nothing was opened, -// created or modified. Match it with errors.As to read BeadsDir, GraphMode and -// FormatMarker; the bd CLI refuses the same workspaces with exit code 16. -// Aliased here because internal/configfile is unimportable outside this -// module. -type UnsupportedWorkspaceFormatError = configfile.UnsupportedWorkspaceFormatError - // Transaction provides atomic multi-operation support within a database transaction. // Use Storage.RunInTransaction() to obtain a Transaction instance. type Transaction = beads.Transaction @@ -381,9 +369,6 @@ func Open(ctx context.Context, dbPath string) (Storage, error) { // name configuration. // beadsDir is the path to the .beads directory. func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) { - if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true}) } @@ -418,11 +403,6 @@ func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) { // operation holds one exclusively; zero means fail fast. A busy gate is // reported as ErrGateBusy (match with errors.Is). func OpenGated(ctx context.Context, beadsDir string, wait time.Duration) (Storage, error) { - // Before the gates: taking them creates gate files in and beside a - // workspace this build must leave untouched. - if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } wsGate, err := workspacegate.ForWorkspace(beadsDir) if err != nil { return nil, err diff --git a/beads_cgo.go b/beads_cgo.go index 31b91c683..d36297ce3 100644 --- a/beads_cgo.go +++ b/beads_cgo.go @@ -46,11 +46,6 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { // typed refusal (the matching ErrXWithoutOpenWith sentinel), never a silent // open with the field ignored. func OpenBestAvailableWith(ctx context.Context, beadsDir string, opts OpenOptions) (Storage, error) { - // Before Load, which can migrate a legacy config.json, and before any - // backend is chosen, as the CLI store factories do. - if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { return nil, fmt.Errorf("loading storage metadata: %w", err) diff --git a/beads_nocgo.go b/beads_nocgo.go index 878a87d45..ba6853c4a 100644 --- a/beads_nocgo.go +++ b/beads_nocgo.go @@ -32,11 +32,6 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { // rationale; behavior here is identical except that embedded Dolt is // unavailable without CGO. func OpenBestAvailableWith(ctx context.Context, beadsDir string, opts OpenOptions) (Storage, error) { - // Before Load, which can migrate a legacy config.json, and before any - // backend is chosen, as the CLI store factories do. - if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { return nil, fmt.Errorf("loading storage metadata: %w", err) diff --git a/cmd/bd/AGENTS.md b/cmd/bd/AGENTS.md index fcaf8bef8..5ddbc95f5 100644 --- a/cmd/bd/AGENTS.md +++ b/cmd/bd/AGENTS.md @@ -38,10 +38,6 @@ Which tier a test belongs in, and which command runs it, is decided by 6. Regenerate the CLI reference with `scripts/generate-cli-docs.sh`; `scripts/check-cli-docs-drift.sh` fails a PR whose command-surface change leaves the generated docs stale. -7. Regenerate the command-surface goldens and review the testdata diff: - `BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'`. - `TestCommandTreeGolden` fails on any added, removed or reworded command or - flag until you do. Prefer a flag on an existing command over a new command, and route recovery/repair operations to `bd doctor --fix`; see the CLI design principles @@ -89,9 +85,6 @@ no linter enforces it). or serialize the call under `stdioMutex`. - `TestCorpusGolden` (`protocol/`) — no unreviewed change to the `--json` wire shapes. -- `TestCommandTreeGolden` and `TestCommandHelpGolden` — no unreviewed change - to the command tree (every command and flag, hidden ones included) or to - the pinned `--help` output in `testdata/command_tree/`. Fresh-workspace command fixtures call `isolateBeadsDirForTest(t)` before setup or dispatch and must not use `t.Parallel()`. diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 6178f6900..409654492 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -375,13 +375,9 @@ go_library( "version.go", "version_proxied_server.go", "version_tracking.go", - "versioned_history.go", - "versioned_history_switch.go", - "versions.go", "where.go", "wisp.go", "wisp_proxied_server.go", - "workspace_format_guard.go", "workspace_gate.go", "worktree.go", "worktree_cmd.go", @@ -422,7 +418,6 @@ go_library( "//internal/httpapi", "//internal/httpclient", "//internal/httpclient/wire", - "//internal/initprocs", "//internal/jira", "//internal/linear", "//internal/lockfile", @@ -468,7 +463,6 @@ go_library( "//internal/utils", "//internal/validation", "//internal/versioncheck", - "//internal/versionedhistory", "//internal/workapi", "//internal/workspacegate", "//internal/worktreeremove", @@ -549,7 +543,6 @@ go_test( "actor_test.go", "ado_roundtrip_test.go", "ado_test.go", - "agent_artifacts_embedded_test.go", "agent_hook_test.go", "assign_fence_embedded_test.go", "assign_fence_proxied_test.go", @@ -607,7 +600,6 @@ go_test( "cobra_flag_reset_test.go", "codex_hook_test.go", "command_telemetry_test.go", - "command_tree_golden_test.go", "comment_promote_embedded_test.go", "comment_proxied_integration_test.go", "comment_reserved_word_test.go", @@ -718,8 +710,6 @@ go_test( "dependency_hierarchy_embedded_test.go", "diff_embedded_test.go", "directory_flag_test.go", - "discovery_refusal_pins_embedded_test.go", - "discovery_refusal_pins_test.go", "doctor_backend_guard_test.go", "doctor_check_gate_test.go", "doctor_context_test.go", @@ -761,7 +751,6 @@ go_test( "dolt_remote_add_test.go", "dolt_remote_adopt_test.go", "dolt_remote_json_test.go", - "dolt_remote_origin_guard_embedded_test.go", "dolt_remote_origin_guard_test.go", "dolt_remote_remove_proxied_integration_test.go", "dolt_remote_reset_data_embedded_test.go", @@ -811,7 +800,6 @@ go_test( "find_duplicates_test.go", "flags_test.go", "flatten_embedded_test.go", - "format_json_alias_embedded_test.go", "formula_fixture_proxied_test.go", "formula_help_test.go", "formula_primitives_test.go", @@ -844,8 +832,6 @@ go_test( "graph_apply_thread_spawner_embedded_test.go", "graph_embedded_test.go", "graph_export_test.go", - "graph_mode_admission_e2e_test.go", - "graph_mode_dependency_embedded_test.go", "graph_proxied_integration_test.go", "graph_test.go", "graph_visual_test.go", @@ -875,7 +861,6 @@ go_test( "identity_preview_refusal_test.go", "if_revision_embedded_test.go", "if_revision_gc_matcher_embedded_test.go", - "if_revision_ordinary_cas_embedded_test.go", "if_revision_proxied_close_delete_test.go", "if_revision_proxied_integration_test.go", "if_revision_reassign_fence_embedded_test.go", @@ -898,13 +883,10 @@ go_test( "info_kv_exclusion_test.go", "info_proxied_integration_test.go", "info_test.go", - "init_agent_test.go", "init_cancel_e2e_test.go", "init_commit_test.go", "init_embedded_test.go", "init_explicit_beads_dir_embedded_test.go", - "init_external_autostart_test.go", - "init_external_message_test.go", "init_gateway_test.go", "init_git_bootstrap_routing_test.go", "init_guard_force_e2e_test.go", @@ -953,8 +935,6 @@ go_test( "legacy_upgrade_guard_e2e_test.go", "legacy_upgrade_guard_empty_root_test.go", "legacy_upgrade_guard_external_server_test.go", - "legacy_upgrade_guard_init_flag_e2e_test.go", - "legacy_upgrade_guard_init_flag_test.go", "legacy_upgrade_guard_test.go", "legacy_upgrade_guard_witness_test.go", "linear_roundtrip_test.go", @@ -1106,7 +1086,6 @@ go_test( "ready_embedded_test.go", "ready_explain_ids_test.go", "ready_input_test.go", - "ready_json_no_total_test.go", "ready_max_rows_proxied_test.go", "ready_max_rows_test.go", "ready_proxied_integration_test.go", @@ -1169,7 +1148,6 @@ go_test( "serve_delete_proxied_integration_test.go", "serve_dependencies_proxied_integration_test.go", "serve_edge_counts_proxied_integration_test.go", - "serve_graph_mode_env_test.go", "serve_inprocess_test.go", "serve_list_sort_proxied_integration_test.go", "serve_proxied_integration_test.go", @@ -1312,14 +1290,6 @@ go_test( "version_embedded_test.go", "version_test.go", "version_tracking_test.go", - "versioned_history_construction_test.go", - "versioned_history_e2e_test.go", - "versioned_history_serve_e2e_test.go", - "versioned_history_switch_scan_embedded_test.go", - "versioned_history_switch_scan_proxied_integration_test.go", - "versioned_history_switch_test.go", - "versions_switch_embedded_test.go", - "versions_test.go", "where_cgo_test.go", "where_embedded_test.go", "where_test.go", @@ -1329,7 +1299,6 @@ go_test( "wisp_gc_purge_closed_embedded_test.go", "wisp_proxied_integration_test.go", "wisp_test.go", - "workspace_format_guard_test.go", "workspace_gate_test.go", "workspace_identity_test.go", "worktree_cmd_test.go", @@ -1350,7 +1319,6 @@ go_test( ":go_srcs", ":preflight_go_fixture", "//:bd_test_files", - "//:go_srcs", "//cmd/bd/doctor:go_srcs", "//cmd/bd/doctor/fix:go_srcs", "//internal/storage/embeddeddolt/cmd:go_srcs", @@ -1386,7 +1354,6 @@ go_test( "//internal/httpclient", "//internal/httpclient/encode", "//internal/httpclient/wire", - "//internal/initprocs", "//internal/linear", "//internal/metrics", "//internal/migration", @@ -1418,7 +1385,6 @@ go_test( "//internal/storage/uow", "//internal/storage/versioncontrolops", "//internal/telemetry", - "//internal/templates/agents", "//internal/testutil", "//internal/testutil/bazeltest", "//internal/testutil/credentialcmd", @@ -1491,7 +1457,7 @@ go_test( ) # bd_embedded_test and bd_embedded_part2_test run the TestEmbedded* functions -# of cmd/bd's _test.go files between them: the manifest's 100-shard block +# of *_embedded_test.go between them: the manifest's 100-shard block # (duration-balanced; see scripts/ci/embedded_cmd_test_durations.json) is # more than Bazel's 50-shard cap per rule, so bd_embedded_test runs its # shards 1-50 and bd_embedded_part2_test its shards 51-100 diff --git a/cmd/bd/agent_artifacts_embedded_test.go b/cmd/bd/agent_artifacts_embedded_test.go deleted file mode 100644 index 3b7d1c8a4..000000000 --- a/cmd/bd/agent_artifacts_embedded_test.go +++ /dev/null @@ -1,310 +0,0 @@ -//go:build cgo - -package main - -import ( - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - - "github.com/steveyegge/beads/internal/templates/agents" -) - -// TestEmbeddedInitAgentArtifactsGolden pins the Claude agent artifacts a real -// `bd init` writes — .claude/settings.json with its hook events and commands, -// CLAUDE.md and AGENTS.md with their managed sections — and what -// `bd setup claude --check`, `--remove` and a reinstall then report and leave -// behind, through the bd binary. Each scenario is a transcript golden under -// testdata/agent_artifacts/, so a change to any artifact or outcome (a new -// hook event, a changed command, new template text and its hash) shows up as -// a reviewed golden diff. -// -// A managed section is shown by its BEGIN marker line (profile and hash) and a -// pointer to the internal/templates/agents golden that pins its bytes -// (TestManagedSectionGolden), after checking the file holds exactly that -// section; one that matches no rendered variant is shown in full. The -// in-process `bd setup claude` scenarios are pinned by -// TestClaudeSetupArtifactsGolden in cmd/bd/setup. -// -// The scenarios run a direct (embedded) bd init with no Dolt remote. Not -// pinned here: a proxied-server bd init, which installs no Codex section and -// decides HasRemote from its own remote URL; a bd init with a remote, which -// renders the managed section's with-remote variant; and the Cursor files. -// AGENTS.md is shown in full apart from its managed section, so a change to -// its wrapper text or its Codex section can pass the cmd/bd/setup and -// internal/templates/agents tests and fail only here. -// -// bd runs with HOME outside the project, so an artifact written to the home -// directory instead of the project shows up under $HOME. -// -// Regenerate with -// -// BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden -func TestEmbeddedInitAgentArtifactsGolden(t *testing.T) { - if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { - t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") - } - t.Parallel() - - bd := buildEmbeddedBD(t) - - scenarios := []struct { - name string - initArgs []string - steps [][]string - }{ - { - name: "init-default", - initArgs: []string{"--prefix", "aa"}, - steps: [][]string{ - {"setup", "claude", "--check"}, - {"setup", "claude"}, - {"setup", "claude", "--remove"}, - {"setup", "claude", "--check"}, - {"setup", "claude"}, - {"setup", "claude", "--check"}, - }, - }, - { - name: "init-agents-profile-full", - initArgs: []string{"--prefix", "ab", "--agents-profile", "full"}, - steps: [][]string{ - {"setup", "claude", "--check"}, - }, - }, - } - - for _, sc := range scenarios { - t.Run(sc.name, func(t *testing.T) { - t.Parallel() - // bdInit, with HOME in a directory of its own. - dir, home := t.TempDir(), t.TempDir() - initGitRepoAt(t, dir) - database, seeded := seededInitDatabase(sc.initArgs) - if seeded { - seedEmbeddedSchema(t, dir, database) - } - initArgs := append([]string{"init", "--quiet"}, sc.initArgs...) - if stdout, stderr, exitCode := runAgentArtifactCommand(t, bd, dir, home, initArgs...); exitCode != 0 { - t.Fatalf("bd %s: exit %d\nstdout:\n%s\nstderr:\n%s", strings.Join(initArgs, " "), exitCode, stdout, stderr) - } - if seeded { - requireSeededEmbeddedInit(t, filepath.Join(dir, ".beads"), database) - } - - var transcript strings.Builder - fmt.Fprintf(&transcript, "# bd init agent artifact transcript: %s\n", sc.name) - fmt.Fprintf(&transcript, "# Regenerate with BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden\n") - fmt.Fprintf(&transcript, "\n=== bd %s\n", strings.Join(initArgs, " ")) - previous := map[string]string{} - writeAgentArtifactChanges(t, &transcript, dir, home, previous) - - for _, args := range sc.steps { - stdout, stderr, exitCode := runAgentArtifactCommand(t, bd, dir, home, args...) - fmt.Fprintf(&transcript, "\n=== bd %s\n", strings.Join(args, " ")) - fmt.Fprintf(&transcript, "exit: %d\n", exitCode) - writeAgentArtifactBlock(&transcript, "stdout", normalizeAgentArtifactOutput(stdout, dir, home)) - writeAgentArtifactBlock(&transcript, "stderr", normalizeAgentArtifactOutput(stderr, dir, home)) - writeAgentArtifactChanges(t, &transcript, dir, home, previous) - } - - assertAgentArtifactGolden(t, filepath.Join("testdata", "agent_artifacts", sc.name+".golden"), transcript.String()) - }) - } -} - -// agentArtifactPaths are the Claude agent artifacts bd init and bd setup -// claude write in a project ($PROJECT), and those in the home directory -// ($HOME): the $HOME/.claude/ files a global install writes, and the -// $HOME/CLAUDE.md an older --global run from $HOME wrote. -var agentArtifactPaths = []string{ - "$PROJECT/.claude/settings.json", - "$PROJECT/.claude/settings.local.json", - "$PROJECT/AGENTS.md", - "$PROJECT/CLAUDE.md", - "$HOME/.claude/settings.json", - "$HOME/.claude/CLAUDE.md", - "$HOME/CLAUDE.md", -} - -// agentArtifactManagedSections maps each managed section bd renders to the -// internal/templates/agents golden file that pins its bytes. -var agentArtifactManagedSections = []struct { - golden string - profile agents.Profile - opts agents.RenderOpts -}{ - {golden: "managed-section-minimal.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{HasRemote: true}}, - {golden: "managed-section-minimal-no-remote.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{}}, - {golden: "managed-section-minimal-user.md", profile: agents.ProfileMinimal, opts: agents.UserLevelRenderOpts()}, - {golden: "managed-section-full.md", profile: agents.ProfileFull, opts: agents.RenderOpts{HasRemote: true}}, - {golden: "managed-section-full-no-remote.md", profile: agents.ProfileFull, opts: agents.RenderOpts{}}, - {golden: "managed-section-full-user.md", profile: agents.ProfileFull, opts: agents.UserLevelRenderOpts()}, -} - -// elideAgentArtifactManagedSection replaces the body of a managed section -// that is byte-identical to a rendered variant with a pointer to that -// variant's golden, keeping the BEGIN marker line (profile and hash) and the -// END marker. -func elideAgentArtifactManagedSection(content string) string { - const endMarker = "\n" - begin := strings.Index(content, "\nOlder guidance; its END marker was lost.\n", - }, - { - name: "END before BEGIN", - content: "# My Project\n\n\nStray text.\n\nOlder guidance.\n", - }, -} - -// A section with malformed markers cannot be replaced. installAgents used to -// write the file back unchanged and report "Updated existing beads section"; -// like bd init's updateAgentFile it now leaves the file alone and returns the -// error. -func TestInstallAgentsReportsMalformedMarkers(t *testing.T) { - stubDetectRenderOpts(t) - for _, tt := range malformedMarkerContents { - t.Run(tt.name, func(t *testing.T) { - env, stdout, stderr := newFactoryTestEnv(t) - seed := seedAgentsFileWithOldMtime(t, env.agentsPath, tt.content) - - integration := agentsIntegration{name: "TestAgent", setupCommand: "bd setup testagent", profile: agents.ProfileFull} - err := installAgents(env, integration) - if !errors.Is(err, agents.ErrMalformedMarkers) { - t.Fatalf("installAgents error = %v, want %v", err, agents.ErrMalformedMarkers) - } - - assertAgentsFileUntouched(t, env.agentsPath, tt.content, seed) - if strings.Contains(stdout.String(), "Updated existing beads section") { - t.Errorf("reported an update to a file it could not update:\n%s", stdout.String()) - } - if !strings.Contains(stderr.String(), "malformed beads section markers") { - t.Errorf("expected the malformed markers on stderr, got: %q", stderr.String()) - } - }) - } -} - -// bd setup claude treats a CLAUDE.md it cannot update as non-fatal: hooks are -// already installed, so it warns and returns nil, leaving the file alone. -// When CLAUDE.md is an @AGENTS.md stub, the file it cannot update is AGENTS.md, -// and the beads block still in the stub must stay: stripping it is safe only -// once AGENTS.md holds the current section. -func TestInstallClaudeWarnsOnMalformedMarkers(t *testing.T) { - stubDetectRenderOpts(t) - for _, tt := range malformedMarkerContents { - t.Run(tt.name, func(t *testing.T) { - env, stdout, stderr := newClaudeTestEnv(t) - claudePath := filepath.Join(env.projectDir, claudeInstructionsFile) - seed := seedAgentsFileWithOldMtime(t, claudePath, tt.content) - - if err := installClaude(env, false, false); err != nil { - t.Fatalf("installClaude returned error: %v", err) - } - - assertAgentsFileUntouched(t, claudePath, tt.content, seed) - if strings.Contains(stdout.String(), "Updated existing beads section") { - t.Errorf("reported an update to a file it could not update:\n%s", stdout.String()) - } - if !strings.Contains(stderr.String(), "Warning: failed to update "+claudeInstructionsFile) { - t.Errorf("expected a non-fatal warning on stderr, got: %q", stderr.String()) - } - }) - t.Run(tt.name+" in the redirected AGENTS.md", func(t *testing.T) { - env, stdout, stderr := newClaudeTestEnv(t) - claudePath := filepath.Join(env.projectDir, claudeInstructionsFile) - claudeContent := staleClaudeStubWithBlock() - claudeSeed := seedAgentsFileWithOldMtime(t, claudePath, claudeContent) - agentsPath := filepath.Join(env.projectDir, "AGENTS.md") - agentsSeed := seedAgentsFileWithOldMtime(t, agentsPath, tt.content) - - if err := installClaude(env, false, false); err != nil { - t.Fatalf("installClaude returned error: %v", err) - } - - assertAgentsFileUntouched(t, agentsPath, tt.content, agentsSeed) - // AGENTS.md was not updated, so the stub's block is the only - // well-formed beads section the project has. - assertAgentsFileUntouched(t, claudePath, claudeContent, claudeSeed) - if strings.Contains(stdout.String(), "Removed stale beads block") { - t.Errorf("reported stripping %s although AGENTS.md was not updated:\n%s", claudeInstructionsFile, stdout.String()) - } - if !strings.Contains(stderr.String(), "Warning: failed to update AGENTS.md") { - t.Errorf("expected the warning to name AGENTS.md, the file that failed, got: %q", stderr.String()) - } - }) - } -} - -// bd setup mux fails on an AGENTS.md it cannot update, before installing its -// .mux hooks. -func TestInstallMuxFailsOnMalformedMarkers(t *testing.T) { - stubDetectRenderOpts(t) - for _, tt := range malformedMarkerContents { - t.Run(tt.name, func(t *testing.T) { - env, _, _ := newFactoryTestEnv(t) - seed := seedAgentsFileWithOldMtime(t, env.agentsPath, tt.content) - - err := installMux(env, false, false) - if !errors.Is(err, agents.ErrMalformedMarkers) { - t.Fatalf("installMux error = %v, want %v", err, agents.ErrMalformedMarkers) - } - - assertAgentsFileUntouched(t, env.agentsPath, tt.content, seed) - if _, statErr := os.Stat(muxProjectDir(env.agentsPath)); !os.IsNotExist(statErr) { - t.Errorf("expected no .mux hooks directory, stat err = %v", statErr) - } - }) - } -} diff --git a/cmd/bd/setup/claude.go b/cmd/bd/setup/claude.go index 832d68a20..ed9e25266 100644 --- a/cmd/bd/setup/claude.go +++ b/cmd/bd/setup/claude.go @@ -27,14 +27,6 @@ var claudeAgentsIntegration = agentsIntegration{ profile: agents.ProfileMinimal, } -// claudeGlobalAgentsIntegration is claudeAgentsIntegration for the user-level -// instructions file, so its hints name the command that maintains that file. -var claudeGlobalAgentsIntegration = agentsIntegration{ - name: "Claude Code", - setupCommand: "bd setup claude --global", - profile: agents.ProfileMinimal, -} - type claudeEnv struct { stdout io.Writer stderr io.Writer @@ -79,13 +71,6 @@ func globalSettingsPath(home string) string { return filepath.Join(home, ".claude", "settings.json") } -// globalClaudeInstructionsPath is Claude Code's user-level instructions file, -// which it loads in every project. A global install keeps its managed beads -// section there, beside the ~/.claude/settings.json its hook goes in. -func globalClaudeInstructionsPath(home string) string { - return filepath.Join(home, ".claude", claudeInstructionsFile) -} - // marshalSettings renders a Claude settings map as two-space-indented JSON // with the trailing newline json.MarshalIndent omits, so the file stays // POSIX-clean and byte-stable across runs. @@ -146,80 +131,6 @@ func claudeAgentsEnvRedirect(env claudeEnv) (agentsEnv, bool) { }, false } -// claudeInstructionsEnv resolves the file an install or removal manages the -// beads section in, with the integration whose hints name its command. A -// global install uses the user-level ~/.claude/CLAUDE.md and leaves the -// current directory's files alone. It renders that file with fixed options: -// every project shares it, so it must not follow one project's config, and -// Claude Code loads it in projects that do not use beads too, so its section -// applies only in those that do. A project install uses the project's -// CLAUDE.md, or AGENTS.md when the bool reports the claudeAgentsEnvRedirect -// redirect. -func claudeInstructionsEnv(env claudeEnv, global bool) (agentsEnv, agentsIntegration, bool) { - if !global { - ae, redirected := claudeAgentsEnvRedirect(env) - return ae, claudeAgentsIntegration, redirected - } - return agentsEnv{ - agentsPath: globalClaudeInstructionsPath(env.homeDir), - stdout: env.stdout, - stderr: env.stderr, - sectionOnly: true, - renderOpts: agents.UserLevelRenderOpts, - }, claudeGlobalAgentsIntegration, false -} - -// claudeCheckAgentsEnv picks the instructions file --check reports on. Run -// from ~/.claude, the project's CLAUDE.md is the user-level file, so it is -// judged as one. Otherwise it is the project's file, unless the hooks are -// user-level (a global install's, or the plugin's) and the project's file has -// no beads section. Then it is the ~/.claude/CLAUDE.md a global install -// writes, which Claude Code loads alongside the project's own instructions, -// if that has a section, if the project's file does not exist, or if the -// project is the home directory: there a project install's hint would create -// the ~/CLAUDE.md a global install exists to avoid. A project install with -// project hooks is judged on the project's file alone; one whose hooks the -// plugin manages has no project hooks, so it is treated as user-level. -func claudeCheckAgentsEnv(env claudeEnv, userLevelHooks bool) (agentsEnv, agentsIntegration) { - globalEnv, globalIntegration, _ := claudeInstructionsEnv(env, true) - if sameDir(env.projectDir, filepath.Dir(globalEnv.agentsPath)) { - return globalEnv, globalIntegration - } - projectEnv := claudeAgentsEnv(env) - if !userLevelHooks || claudeFileHasBeadsSection(env, projectEnv.agentsPath) { - return projectEnv, claudeAgentsIntegration - } - if claudeFileHasBeadsSection(env, globalEnv.agentsPath) || claudeProjectIsHome(env) { - return globalEnv, globalIntegration - } - if _, err := env.readFile(projectEnv.agentsPath); err != nil { - return globalEnv, globalIntegration - } - return projectEnv, claudeAgentsIntegration -} - -// claudeProjectIsHome reports whether the current directory is the home -// directory, where the project's .claude/settings.json is the global one. -func claudeProjectIsHome(env claudeEnv) bool { - return sameDir(env.projectDir, env.homeDir) -} - -// sameDir reports whether a and b are the same directory, following -// symlinks; it compares cleaned paths when either cannot be stat'd. -func sameDir(a, b string) bool { - ai, errA := os.Stat(a) - bi, errB := os.Stat(b) - if errA == nil && errB == nil { - return os.SameFile(ai, bi) - } - return filepath.Clean(a) == filepath.Clean(b) -} - -func claudeFileHasBeadsSection(env claudeEnv, path string) bool { - data, err := env.readFile(path) - return err == nil && containsBeadsMarker(string(data)) -} - // stripStaleClaudeBlock removes a beads-managed block left behind in CLAUDE.md // by an older bd version, once the AGENTS.md redirect is active. Older bd // releases wrote the managed block directly into CLAUDE.md; a project that has @@ -378,11 +289,11 @@ func installClaude(env claudeEnv, global bool, stealth bool) error { if legacy == command { continue } - removeHookCommand(env.stdout, hooks, "SessionStart", legacy) - removeHookCommand(env.stdout, hooks, "PreCompact", legacy) + removeHookCommand(hooks, "SessionStart", legacy) + removeHookCommand(hooks, "PreCompact", legacy) } - removeHookCommand(env.stdout, hooks, "PreCompact", "bd prime --hook-json") - removeHookCommand(env.stdout, hooks, "PreCompact", "bd prime --stealth --hook-json") + removeHookCommand(hooks, "PreCompact", "bd prime --hook-json") + removeHookCommand(hooks, "PreCompact", "bd prime --stealth --hook-json") // GH#3192: Skip writing hooks if the beads plugin is already providing them, // so project-level hooks don't fire bd prime twice per session. @@ -415,8 +326,8 @@ func installClaude(env claudeEnv, global bool, stealth bool) error { if json.Unmarshal(legacyData, &legacySettings) == nil { if legacyHooks, ok := legacySettings["hooks"].(map[string]interface{}); ok { for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} { - removeHookCommand(env.stdout, legacyHooks, "SessionStart", v) - removeHookCommand(env.stdout, legacyHooks, "PreCompact", v) + removeHookCommand(legacyHooks, "SessionStart", v) + removeHookCommand(legacyHooks, "PreCompact", v) } if migrated, marshalErr := marshalSettings(legacySettings); marshalErr == nil { if writeErr := writeSettingsIfChanged(env, legacyPath, migrated); writeErr == nil { @@ -431,21 +342,19 @@ func installClaude(env claudeEnv, global bool, stealth bool) error { // Install minimal beads section in CLAUDE.md. // Hooks handle the heavy lifting via bd prime; CLAUDE.md just needs a pointer. - agentsEnv, integration, redirected := claudeInstructionsEnv(env, global) + agentsEnv, redirected := claudeAgentsEnvRedirect(env) agentsSkipped := false agentsEnv.skipped = &agentsSkipped - agentsErr := installAgents(agentsEnv, integration) - if agentsErr != nil { + if err := installAgents(agentsEnv, claudeAgentsIntegration); err != nil { // Non-fatal: hooks are already installed - _, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", agentsFileName(agentsEnv.agentsPath), agentsErr) + _, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", claudeInstructionsFile, err) } - // Only strip the stale CLAUDE.md block once AGENTS.md holds the current - // section (written now or already current). If installAgents skipped - // injection (e.g. AGENTS.md is a symlink) or failed (e.g. its markers are - // malformed), stripping here would delete-before-write and leave the - // project with no beads section anywhere. - if redirected && agentsErr == nil && !agentsSkipped { + // Only strip the stale CLAUDE.md block once the redirect has actually + // written the replacement to AGENTS.md. If installAgents skipped injection + // (e.g. AGENTS.md is a symlink), stripping here would delete-before-write + // and leave the project with no beads section anywhere. + if redirected && !agentsSkipped { if err := stripStaleClaudeBlock(env); err != nil { // Non-fatal: the redirect itself already succeeded above _, _ = fmt.Fprintf(env.stderr, "Warning: failed to clean stale beads block from %s: %v\n", claudeInstructionsFile, err) @@ -536,37 +445,24 @@ func checkClaude(env claudeEnv) error { globalSettings := globalSettingsPath(env.homeDir) legacySettings := legacyProjectSettingsPath(env.projectDir) - // From the home directory the project's settings are the global ones, - // so hooks there are user-level and reported as global. - atHome := claudeProjectIsHome(env) - userLevelHooks := false switch { - case !atHome && hasBeadsHooks(projectSettings): + case hasBeadsHooks(projectSettings): _, _ = fmt.Fprintf(env.stdout, "✓ Project hooks installed: %s\n", projectSettings) case hasBeadsHooks(globalSettings): _, _ = fmt.Fprintf(env.stdout, "✓ Global hooks installed: %s\n", globalSettings) - userLevelHooks = true case hasBeadsHooks(legacySettings): _, _ = fmt.Fprintf(env.stdout, "✓ Project hooks installed (legacy): %s\n", legacySettings) _, _ = fmt.Fprintf(env.stdout, " Consider running 'bd setup claude' to migrate to .claude/settings.json\n") case hasBeadsPlugin(env): // GH#3192: Plugin provides hooks via plugin.json — no project-level hooks needed _, _ = fmt.Fprintln(env.stdout, "✓ Hooks provided by beads plugin (plugin-managed)") - userLevelHooks = true default: _, _ = fmt.Fprintln(env.stdout, "✗ No hooks installed") - if atHome { - // A project install here would create the ~/CLAUDE.md a global - // install exists to avoid. - _, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude --global") - } else { - _, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude") - } + _, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude") return errClaudeHooksMissing } - agentsEnv, integration := claudeCheckAgentsEnv(env, userLevelHooks) - return checkAgents(agentsEnv, integration) + return checkAgents(claudeAgentsEnv(env), claudeAgentsIntegration) } func RemoveClaude(global bool) error { @@ -602,8 +498,8 @@ func removeClaude(env claudeEnv, global bool) error { _, _ = fmt.Fprintln(env.stdout, "No hooks found") } else { for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} { - removeHookCommand(env.stdout, hooks, "SessionStart", v) - removeHookCommand(env.stdout, hooks, "PreCompact", v) + removeHookCommand(hooks, "SessionStart", v) + removeHookCommand(hooks, "PreCompact", v) } data, err = marshalSettings(settings) @@ -627,8 +523,8 @@ func removeClaude(env claudeEnv, global bool) error { if json.Unmarshal(legacyData, &legacySettings) == nil { if legacyHooks, ok := legacySettings["hooks"].(map[string]interface{}); ok { for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} { - removeHookCommand(env.stdout, legacyHooks, "SessionStart", v) - removeHookCommand(env.stdout, legacyHooks, "PreCompact", v) + removeHookCommand(legacyHooks, "SessionStart", v) + removeHookCommand(legacyHooks, "PreCompact", v) } if migrated, marshalErr := marshalSettings(legacySettings); marshalErr == nil { _ = writeSettingsIfChanged(env, legacyPath, migrated) @@ -638,7 +534,7 @@ func removeClaude(env claudeEnv, global bool) error { } } - agentsEnv, integration, redirected := claudeInstructionsEnv(env, global) + agentsEnv, redirected := claudeAgentsEnvRedirect(env) if redirected { // When redirected, AGENTS.md carries the project-authoritative shared // beads section (created by `bd init` or another agent's setup), not a @@ -649,23 +545,12 @@ func removeClaude(env claudeEnv, global bool) error { _, _ = fmt.Fprintf(env.stderr, "Warning: failed to clean stale beads block from %s: %v\n", claudeInstructionsFile, err) } } else { - if err := removeAgents(agentsEnv, integration); err != nil { + if err := removeAgents(agentsEnv, claudeAgentsIntegration); err != nil { // Non-fatal _, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", claudeInstructionsFile, err) } } - // From the home directory a project removal has just removed the global - // hooks, since the settings files are the same; remove the user-level - // section a global install paired with them too. - if !global && claudeProjectIsHome(env) { - globalEnv, globalIntegration, _ := claudeInstructionsEnv(env, true) - if err := removeAgents(globalEnv, globalIntegration); err != nil { - // Non-fatal - _, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", globalEnv.agentsPath, err) - } - } - _, _ = fmt.Fprintln(env.stdout, "✓ Claude hooks removed") return nil } @@ -720,10 +605,8 @@ func addHookCommand(hooks map[string]interface{}, event, command string) bool { // removeHookCommand removes a specific command from an event's hook entries. // Only the matching command object is removed; sibling commands in the same // hook entry are preserved. A hook entry is dropped only when its command list -// becomes empty after filtering. Each removal is reported to w, the caller's -// stdout: bd init --quiet hands the installers a discarding writer, so a -// print to the process stdout here would escape it. -func removeHookCommand(w io.Writer, hooks map[string]interface{}, event, command string) { +// becomes empty after filtering. +func removeHookCommand(hooks map[string]interface{}, event, command string) { eventHooks, ok := hooks[event].([]interface{}) if !ok { return @@ -761,7 +644,7 @@ func removeHookCommand(w io.Writer, hooks map[string]interface{}, event, command } if removed { - _, _ = fmt.Fprintf(w, "✓ Removed %s hook\n", event) + fmt.Printf("✓ Removed %s hook\n", event) } // Drop the hook entry only when it has no commands left. diff --git a/cmd/bd/setup/claude_artifacts_golden_test.go b/cmd/bd/setup/claude_artifacts_golden_test.go deleted file mode 100644 index 710d49423..000000000 --- a/cmd/bd/setup/claude_artifacts_golden_test.go +++ /dev/null @@ -1,514 +0,0 @@ -package setup - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "sort" - "strings" - "testing" - - "github.com/steveyegge/beads/internal/templates/agents" -) - -// The tests in this file pin the agent artifacts `bd setup claude` writes, and -// what its --check and --remove report and leave behind: the hook events and -// commands in the Claude settings files, the CLAUDE.md / AGENTS.md files with -// their managed section, and the output of each step. Each scenario is a -// transcript golden under testdata/, so a change to any of them (a new hook -// event, a changed hook command, new template text, a different --check or -// --remove outcome) shows up as a reviewed golden diff. -// -// A managed section is shown by its BEGIN marker line (profile and hash) and a -// pointer to the internal/templates/agents golden that pins its bytes -// (TestManagedSectionGolden), after checking the file holds exactly that -// section. A template change therefore shows up once, as that golden's diff, -// and here as the new marker hash in every file it lands in. A section that -// matches no rendered variant is shown in full. The `bd init` side of the same -// artifacts is pinned by TestEmbeddedInitAgentArtifactsGolden in cmd/bd. -// -// Regenerate with -// -// BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden - -// claudeArtifactPaths are the files bd setup claude can create, change or -// delete, relative to the root holding the test's project and home dirs. -var claudeArtifactPaths = []string{ - "home/.claude/CLAUDE.md", - "home/.claude/settings.json", - "project/.claude/settings.json", - "project/.claude/settings.local.json", - "project/AGENTS.md", - "project/CLAUDE.md", -} - -// managedSectionGoldens maps each managed section bd renders to the -// internal/templates/agents golden file that pins its bytes. -var managedSectionGoldens = []struct { - golden string - profile agents.Profile - opts agents.RenderOpts -}{ - {golden: "managed-section-minimal.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{HasRemote: true}}, - {golden: "managed-section-minimal-no-remote.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{}}, - {golden: "managed-section-minimal-user.md", profile: agents.ProfileMinimal, opts: agents.UserLevelRenderOpts()}, - {golden: "managed-section-full.md", profile: agents.ProfileFull, opts: agents.RenderOpts{HasRemote: true}}, - {golden: "managed-section-full-no-remote.md", profile: agents.ProfileFull, opts: agents.RenderOpts{}}, - {golden: "managed-section-full-user.md", profile: agents.ProfileFull, opts: agents.UserLevelRenderOpts()}, -} - -// elideManagedSection replaces the body of a managed section that is -// byte-identical to a rendered variant with a pointer to that variant's -// golden, keeping the BEGIN marker line (profile and hash) and END marker. -func elideManagedSection(content string) string { - const endMarker = "\n" - begin := strings.Index(content, "\nOlder beads guidance.\n\n\n## Notes\n", - }, - steps: []claudeArtifactStep{ - claudeCheckStep(), - claudeInstallStep(false, false), - claudeCheckStep(), - }, - }, - { - // A legacy install in settings.local.json: install migrates - // its hook to settings.json. - name: "legacy-local-settings", - seed: map[string]string{ - "project/.claude/settings.local.json": legacyLocalSettings, - }, - steps: []claudeArtifactStep{ - claudeCheckStep(), - claudeInstallStep(false, false), - claudeCheckStep(), - claudeRemoveStep(false), - }, - }, - { - // CLAUDE.md imports AGENTS.md: the managed section goes to - // AGENTS.md, and --remove leaves that shared section in place. - name: "agents-import-stub", - seed: map[string]string{ - "project/AGENTS.md": "# Agent Instructions\n\nShared by every agent.\n", - "project/CLAUDE.md": "@AGENTS.md\n", - }, - steps: []claudeArtifactStep{ - claudeInstallStep(false, false), - claudeCheckStep(), - claudeRemoveStep(false), - claudeCheckStep(), - }, - }, - } - - for _, sc := range scenarios { - t.Run(sc.name, func(t *testing.T) { - env, _, _ := newClaudeTestEnv(t) - root := filepath.Dir(env.projectDir) - for rel, content := range sc.seed { - path := filepath.Join(root, filepath.FromSlash(rel)) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatalf("mkdir for seed %s: %v", rel, err) - } - if err := os.WriteFile(path, []byte(content), 0o644); err != nil { - t.Fatalf("seed %s: %v", rel, err) - } - } - - var transcript strings.Builder - fmt.Fprintf(&transcript, "# bd setup claude artifact transcript: %s\n", sc.name) - fmt.Fprintf(&transcript, "# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden\n") - previous := map[string]string{} - writeClaudeArtifactChanges(t, &transcript, "seed", root, previous) - for _, step := range sc.steps { - out, errOut, err := runClaudeArtifactStep(t, env, step.run) - fmt.Fprintf(&transcript, "\n=== %s\n", step.title) - fmt.Fprintf(&transcript, "result: %s\n", claudeStepResult(err)) - writeTranscriptBlock(&transcript, "stdout", normalizeArtifactOutput(out, root)) - writeTranscriptBlock(&transcript, "stderr", normalizeArtifactOutput(errOut, root)) - writeClaudeArtifactChanges(t, &transcript, "files", root, previous) - } - - assertArtifactGolden(t, filepath.Join("testdata", "claude-setup-"+sc.name+".golden"), transcript.String()) - }) - } -} - -// TestClaudePluginManifestHookEvents pins the hook events and commands the -// beads Claude Code plugin declares. With the plugin enabled bd setup claude -// writes no hooks of its own (GH#3192), so these are the hooks such a user -// runs. -func TestClaudePluginManifestHookEvents(t *testing.T) { - var manifest struct { - Hooks map[string][]struct { - Matcher string `json:"matcher"` - Hooks []struct { - Type string `json:"type"` - Command string `json:"command"` - } `json:"hooks"` - } `json:"hooks"` - } - readJSONFile(t, filepath.Join("..", "..", "..", "plugins", "beads", ".claude-plugin", "plugin.json"), &manifest) - - var got []string - for event, entries := range manifest.Hooks { - for _, entry := range entries { - for _, hook := range entry.Hooks { - got = append(got, fmt.Sprintf("%s matcher=%q %s: %s", event, entry.Matcher, hook.Type, hook.Command)) - } - } - } - sort.Strings(got) - want := []string{ - `PreCompact matcher="" command: bd prime`, - `SessionStart matcher="" command: bd prime`, - } - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Errorf("Claude plugin hooks changed:\ngot:\n %s\nwant:\n %s", strings.Join(got, "\n "), strings.Join(want, "\n ")) - } -} - -// runClaudeArtifactStep runs one step with env.stdout and the process stdout -// sent to the same file, so the transcript keeps the order a user sees: -// addHookCommand prints with fmt.Printf rather than to env.stdout. Swapping -// os.Stdout is why these tests must not run in parallel. -func runClaudeArtifactStep(t *testing.T, env claudeEnv, run func(claudeEnv) error) (stdout, stderr string, err error) { - t.Helper() - capture, createErr := os.CreateTemp(t.TempDir(), "stdout-*") - if createErr != nil { - t.Fatalf("create stdout capture: %v", createErr) - } - errBuf := &bytes.Buffer{} - env.stdout, env.stderr = capture, errBuf - - origStdout := os.Stdout - os.Stdout = capture - func() { - defer func() { os.Stdout = origStdout }() - err = run(env) - }() - - if closeErr := capture.Close(); closeErr != nil { - t.Fatalf("close stdout capture: %v", closeErr) - } - data, readErr := os.ReadFile(capture.Name()) - if readErr != nil { - t.Fatalf("read stdout capture: %v", readErr) - } - return string(data), errBuf.String(), err -} - -func claudeStepResult(err error) string { - if err == nil { - return "ok" - } - return "error: " + err.Error() -} - -// writeClaudeArtifactChanges appends every artifact file created, modified or -// deleted since previous (which it then updates), with its full contents. -func writeClaudeArtifactChanges(t *testing.T, b *strings.Builder, label, root string, previous map[string]string) { - t.Helper() - changed := false - for _, rel := range claudeArtifactPaths { - data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel))) - before, existed := previous[rel] - switch { - case os.IsNotExist(err): - if existed { - fmt.Fprintf(b, "--- %s: deleted $ROOT/%s\n", label, rel) - delete(previous, rel) - changed = true - } - case err != nil: - t.Fatalf("read %s: %v", rel, err) - case !existed || before != string(data): - verb := "created" - if existed { - verb = "modified" - } - shown := string(data) - if strings.HasSuffix(rel, ".md") { - shown = elideManagedSection(shown) - } - writeTranscriptBlock(b, fmt.Sprintf("%s: %s $ROOT/%s", label, verb, rel), shown) - previous[rel] = string(data) - changed = true - } - } - switch { - case changed: - case label == "seed": - fmt.Fprintf(b, "--- %s: none\n", label) - default: - fmt.Fprintf(b, "--- %s: unchanged\n", label) - } -} - -// writeTranscriptBlock appends a titled block, marking empty content and a -// missing trailing newline so neither is lost in the golden. -func writeTranscriptBlock(b *strings.Builder, title, content string) { - fmt.Fprintf(b, "--- %s\n", title) - switch { - case content == "": - b.WriteString("(empty)\n") - case !strings.HasSuffix(content, "\n"): - b.WriteString(content) - b.WriteString("\n(no newline at end of file)\n") - default: - b.WriteString(content) - } -} - -// normalizeArtifactOutput replaces the test's temporary root with $ROOT and -// uses forward slashes, so the transcript is the same on every host. -func normalizeArtifactOutput(s, root string) string { - s = strings.ReplaceAll(s, root, "$ROOT") - if filepath.Separator != '/' { - s = strings.ReplaceAll(s, string(filepath.Separator), "/") - } - return s -} - -// assertArtifactGolden compares got with the golden file at path, or rewrites -// the file when BD_UPDATE_GOLDEN=1. -func assertArtifactGolden(t *testing.T, path, got string) { - t.Helper() - if os.Getenv("BD_UPDATE_GOLDEN") == "1" { - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) - } - if err := os.WriteFile(path, []byte(got), 0o644); err != nil { - t.Fatalf("write golden %s: %v", path, err) - } - t.Logf("updated golden %s", path) - return - } - want, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read golden %s (regenerate with BD_UPDATE_GOLDEN=1): %v", path, err) - } - if got == string(want) { - return - } - wantLines, gotLines := strings.Split(string(want), "\n"), strings.Split(got, "\n") - line := func(lines []string, i int) string { - if i >= len(lines) { - return "(end of output)" - } - return fmt.Sprintf("%q", lines[i]) - } - i := 0 - for i < len(wantLines) && i < len(gotLines) && wantLines[i] == gotLines[i] { - i++ - } - t.Errorf("Claude agent artifacts drifted from %s (regenerate with BD_UPDATE_GOLDEN=1 if intended)\nfirst difference at line %d:\n want: %s\n got: %s\n--- got ---\n%s", path, i+1, line(wantLines, i), line(gotLines, i), got) -} diff --git a/cmd/bd/setup/claude_test.go b/cmd/bd/setup/claude_test.go index 78f99f6c9..4d1e178e1 100644 --- a/cmd/bd/setup/claude_test.go +++ b/cmd/bd/setup/claude_test.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "errors" - "io" "os" "path/filepath" "strings" @@ -66,12 +65,6 @@ func writeSettings(t *testing.T, path string, settings map[string]interface{}) { } } -// userLevelSection is the managed section a global install writes to -// ~/.claude/CLAUDE.md. -func userLevelSection() string { - return agents.RenderSectionWithOpts(agents.ProfileMinimal, agents.UserLevelRenderOpts()) -} - func TestAddHookCommand(t *testing.T) { tests := []struct { name string @@ -278,7 +271,7 @@ func TestRemoveHookCommand(t *testing.T) { }, }, } - removeHookCommand(io.Discard, hooks, "SessionStart", "bd prime") + removeHookCommand(hooks, "SessionStart", "bd prime") entries, ok := hooks["SessionStart"].([]interface{}) if !ok || len(entries) != 1 { @@ -296,7 +289,7 @@ func TestRemoveHookCommand(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - removeHookCommand(io.Discard, tt.existingHooks, tt.event, tt.command) + removeHookCommand(tt.existingHooks, tt.event, tt.command) eventHooks, ok := tt.existingHooks[tt.event].([]interface{}) if !ok && tt.wantRemaining > 0 { @@ -339,7 +332,7 @@ func TestRemoveHookCommandNoNull(t *testing.T) { }, } - removeHookCommand(io.Discard, hooks, "SessionStart", "bd prime") + removeHookCommand(hooks, "SessionStart", "bd prime") // Key should be deleted, not set to null or empty array if _, exists := hooks["SessionStart"]; exists { @@ -356,79 +349,6 @@ func TestRemoveHookCommandNoNull(t *testing.T) { } } -// bd init --quiet hands the Claude installer QuietProjectInstallOutput. When -// the project's settings still carry the bare `bd prime` hooks an older bd -// registered, the migration sweep's "Removed hook" lines must go to -// that output like the rest of the installer's progress: removeHookCommand -// printed them straight to the process stdout, so a quiet init still wrote -// them. -func TestClaudeLegacyHookRemovalReportsThroughGivenOutput(t *testing.T) { - legacyHook := func() []interface{} { - return []interface{}{map[string]interface{}{ - "matcher": "", - "hooks": []interface{}{map[string]interface{}{"type": "command", "command": "bd prime"}}, - }} - } - for _, tc := range []struct { - name string - path func(projectDir string) string - }{ - {name: "settings.json", path: projectSettingsPath}, - {name: "legacy settings.local.json", path: legacyProjectSettingsPath}, - } { - t.Run(tc.name, func(t *testing.T) { - env, _, _ := newClaudeTestEnv(t) - stubClaudeEnvProvider(t, env, nil) - writeSettings(t, tc.path(env.projectDir), map[string]interface{}{ - "hooks": map[string]interface{}{"SessionStart": legacyHook(), "PreCompact": legacyHook()}, - }) - - var out, errOut bytes.Buffer - processOut := captureProcessStdout(t, func() { - if err := InstallClaudeProjectTo(false, ProjectInstallOutput{Stdout: &out, Stderr: &errOut}); err != nil { - t.Fatalf("InstallClaudeProjectTo: %v", err) - } - }) - if processOut != "" { - t.Errorf("Claude installer wrote to the process stdout instead of the given one: %q", processOut) - } - for _, want := range []string{"✓ Removed SessionStart hook\n", "✓ Removed PreCompact hook\n"} { - if !strings.Contains(out.String(), want) { - t.Errorf("given stdout is missing %q:\n%s", want, out.String()) - } - } - if errOut.Len() != 0 { - t.Errorf("install wrote errors: %q", errOut.String()) - } - }) - } -} - -// captureProcessStdout runs fn with the process stdout sent to a temp file and -// returns what was written there. Swapping os.Stdout is why the tests in this -// package must not run in parallel. -func captureProcessStdout(t *testing.T, fn func()) string { - t.Helper() - capture, err := os.CreateTemp(t.TempDir(), "process-stdout-*") - if err != nil { - t.Fatalf("create stdout capture: %v", err) - } - orig := os.Stdout - os.Stdout = capture - func() { - defer func() { os.Stdout = orig }() - fn() - }() - if err := capture.Close(); err != nil { - t.Fatalf("close stdout capture: %v", err) - } - data, err := os.ReadFile(capture.Name()) - if err != nil { - t.Fatalf("read stdout capture: %v", err) - } - return string(data) -} - // TestInstallClaudeCleanupNullHooks verifies that install cleans up existing null values. // GH#955: null values left by previous buggy removal cause Claude Code to fail. func TestInstallClaudeCleanupNullHooks(t *testing.T) { @@ -799,110 +719,15 @@ func TestInstallClaudeGlobalStealth(t *testing.T) { if !strings.Contains(string(data), "bd prime --stealth") { t.Error("expected stealth command in settings") } - // The managed section goes to Claude Code's user-level instructions file, - // beside the global settings, holding only the section, worded for a file - // every project loads: none of the project scaffolding a new project - // CLAUDE.md gets. - instructions, err := os.ReadFile(globalClaudeInstructionsPath(env.homeDir)) - if err != nil { - t.Fatalf("expected user-level %s to be created: %v", claudeInstructionsFile, err) - } - if want := userLevelSection(); string(instructions) != want { - t.Errorf("user-level %s should hold only the managed section:\ngot:\n%s\nwant:\n%s", claudeInstructionsFile, instructions, want) - } - // A global install must not touch the current directory's files. - if _, err := os.Stat(filepath.Join(env.projectDir, claudeInstructionsFile)); !os.IsNotExist(err) { - t.Errorf("global install should not create the project's %s (stat err: %v)", claudeInstructionsFile, err) + instructionsPath := filepath.Join(env.projectDir, claudeInstructionsFile) + if _, err := os.Stat(instructionsPath); err != nil { + t.Fatalf("expected %s to be created: %v", claudeInstructionsFile, err) } if !strings.Contains(stdout.String(), "globally") { t.Error("expected global installation message") } } -// The user-level ~/.claude/CLAUDE.md is shared by every project, so a global -// install renders and checks it the same way whatever beads config the -// current directory has: otherwise --check from one project calls the section -// another project wrote stale, and following its hint flips it back. -func TestClaudeGlobalSectionIgnoresProjectConfig(t *testing.T) { - configs := []struct { - name string - opts agents.RenderOpts - }{ - {"remote", agents.RenderOpts{HasRemote: true}}, - {"no remote", agents.RenderOpts{HasRemote: false}}, - {"no push", agents.RenderOpts{HasRemote: true, NoPush: true}}, - } - wantHash := agents.CurrentHashWithOpts(agents.ProfileMinimal, agents.UserLevelRenderOpts()) - orig := detectRenderOptsImpl - t.Cleanup(func() { detectRenderOptsImpl = orig }) - for _, install := range configs { - for _, check := range configs { - t.Run(install.name+" install, "+check.name+" check", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - installOpts := install.opts - detectRenderOptsImpl = func() agents.RenderOpts { return installOpts } - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - data, err := os.ReadFile(globalInstructions) - if err != nil { - t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) - } - if !strings.Contains(string(data), "hash:"+wantHash) { - t.Errorf("expected hash %s regardless of project config, got:\n%s", wantHash, data) - } - checkOpts := check.opts - detectRenderOptsImpl = func() agents.RenderOpts { return checkOpts } - stdout.Reset() - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), globalInstructions+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - } - } -} - -// A section worded for a project, such as a project install run from -// ~/.claude leaves there, is stale in the user-level file: --check names the -// global install, which rewords the section in place and keeps the user's -// own text. -func TestInstallClaudeGlobalRewordsProjectSection(t *testing.T) { - stubDetectRenderOpts(t) - env, stdout, _ := newClaudeTestEnv(t) - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - if err := os.WriteFile(globalInstructions, []byte("# Mine\n\n"+agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - stdout.Reset() - if err := checkClaude(env); !errors.Is(err, errBeadsSectionStale) { - t.Fatalf("expected errBeadsSectionStale, got %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude --global (to update)") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - data, err := os.ReadFile(globalInstructions) - if err != nil { - t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) - } - if want := "# Mine\n\n" + userLevelSection(); string(data) != want { - t.Errorf("user-level %s after the global install:\ngot:\n%s\nwant:\n%s", claudeInstructionsFile, data, want) - } - stdout.Reset() - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } -} - func TestInstallClaudeErrors(t *testing.T) { t.Run("invalid json", func(t *testing.T) { env, _, stderr := newClaudeTestEnv(t) @@ -995,19 +820,6 @@ func TestCheckClaudeScenarios(t *testing.T) { } }) - // From the home directory a project install would create ~/CLAUDE.md, - // so the hint names the global install. - t.Run("missing hooks checked from home", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - env.projectDir = env.homeDir - if err := checkClaude(env); !errors.Is(err, errClaudeHooksMissing) { - t.Fatalf("expected errClaudeHooksMissing, got %v", err) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } - }) - t.Run("missing instructions", func(t *testing.T) { env, stdout, _ := newClaudeTestEnv(t) writeSettings(t, globalSettingsPath(env.homeDir), map[string]interface{}{ @@ -1028,298 +840,10 @@ func TestCheckClaudeScenarios(t *testing.T) { if !strings.Contains(stdout.String(), claudeInstructionsFile+" not found") { t.Fatalf("expected missing %s message, got: %s", claudeInstructionsFile, stdout.String()) } - // With global hooks and no instructions file in the project, the - // missing section is the user-level one the global install writes. - if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } }) - - // A project CLAUDE.md without a section is still reported as the - // project's: adding the section there is one way to finish the setup. - t.Run("project instructions without a section", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), map[string]interface{}{ - "hooks": map[string]interface{}{ - "SessionStart": []interface{}{ - map[string]interface{}{ - "matcher": "", - "hooks": []interface{}{ - map[string]interface{}{"type": "command", "command": "bd prime --hook-json"}, - }, - }, - }, - }, - }) - if err := os.WriteFile(filepath.Join(env.projectDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { - t.Fatalf("write project %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); !errors.Is(err, errBeadsSectionMissing) { - t.Fatalf("expected errBeadsSectionMissing, got %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude (to add beads section)") { - t.Errorf("expected the project setup hint, got:\n%s", stdout.String()) - } - }) - - primeHookSettings := map[string]interface{}{ - "hooks": map[string]interface{}{ - "SessionStart": []interface{}{ - map[string]interface{}{ - "matcher": "", - "hooks": []interface{}{ - map[string]interface{}{"type": "command", "command": "bd prime --hook-json"}, - }, - }, - }, - }, - } - - // A global install is checked from any directory: with no beads section - // in the project, the one in ~/.claude/CLAUDE.md is the one Claude loads. - t.Run("global install from another directory", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), globalInstructions+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - - // The common global case: the project has its own CLAUDE.md with no - // beads section, and the user-level file carries the section. - t.Run("global install beside project instructions without a section", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - if err := os.WriteFile(filepath.Join(env.projectDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { - t.Fatalf("write project %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), globalInstructions+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - - // From the home directory a ~/CLAUDE.md without a section is not the - // file to fix: the project hint would add the section there. - t.Run("home instructions without a section checked from home", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - env.projectDir = env.homeDir - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - if err := os.WriteFile(filepath.Join(env.homeDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { - t.Fatalf("write home %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { - t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } - }) - - t.Run("stale user-level section", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - stale := "\nOld.\n\n" - if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(stale), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); !errors.Is(err, errBeadsSectionStale) { - t.Fatalf("expected errBeadsSectionStale, got %v", err) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude --global (to update)") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } - }) - - // The plugin's hooks are user-level too, so --global can supply the section. - t.Run("plugin hooks with user-level section", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), settingsWithPlugin()) - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), globalInstructions+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - - // A project install is judged on the project's file alone: the - // user-level section does not stand in for a missing project one. - t.Run("project hooks ignore the user-level section", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, projectSettingsPath(env.projectDir), primeHookSettings) - if err := os.MkdirAll(filepath.Dir(globalClaudeInstructionsPath(env.homeDir)), 0o755); err != nil { - t.Fatalf("mkdir user-level dir: %v", err) - } - if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(userLevelSection()), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { - t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) - } - }) - - // With global hooks the project's own section still wins over the - // user-level one, as project hooks win over global ones. - t.Run("project section preferred", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - stale := "\nOld.\n\n" - if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(stale), 0o644); err != nil { - t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) - } - projectInstructions := filepath.Join(env.projectDir, claudeInstructionsFile) - if err := os.WriteFile(projectInstructions, []byte(agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { - t.Fatalf("write project %s: %v", claudeInstructionsFile, err) - } - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), projectInstructions+" (current)") { - t.Errorf("expected the project file reported, got:\n%s", stdout.String()) - } - }) - - // From the home directory the project's settings are the global ones and - // its CLAUDE.md is ~/CLAUDE.md, so a global install must still be judged - // on the user-level files. - t.Run("global install checked from home", func(t *testing.T) { - env, _, _ := newClaudeTestEnv(t) - env.projectDir = env.homeDir - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - stdout := &bytes.Buffer{} - env.stdout = stdout - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "Global hooks installed") { - t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) - } - if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - - // The project hint would create ~/CLAUDE.md from the home directory. - t.Run("missing section checked from home", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - env.projectDir = env.homeDir - writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) - if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { - t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "Global hooks installed") { - t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) - } - if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { - t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) - } - }) - - // From ~/.claude the project's CLAUDE.md is the user-level file: it is - // judged with the fixed global render options, not this directory's. - t.Run("global install checked from the user-level directory", func(t *testing.T) { - env, _, _ := newClaudeTestEnv(t) - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - orig := detectRenderOptsImpl - t.Cleanup(func() { detectRenderOptsImpl = orig }) - detectRenderOptsImpl = func() agents.RenderOpts { return agents.RenderOpts{HasRemote: false} } - env.projectDir = filepath.Dir(globalClaudeInstructionsPath(env.homeDir)) - stdout := &bytes.Buffer{} - env.stdout = stdout - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - - // The home directory and ~/.claude are recognized when reached through a - // symlink too (a symlinked /home, a linked checkout): sameDir compares - // the directories, not their path strings. - for _, link := range []struct { - name string - target func(home string) string - }{ - {"home", func(home string) string { return home }}, - {"the user-level directory", func(home string) string { return filepath.Dir(globalClaudeInstructionsPath(home)) }}, - } { - t.Run("global install checked from a symlink to "+link.name, func(t *testing.T) { - env, _, _ := newClaudeTestEnv(t) - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - linkDir := filepath.Join(t.TempDir(), "link") - if err := os.Symlink(link.target(env.homeDir), linkDir); err != nil { - t.Skipf("symlink: %v", err) - } - env.projectDir = linkDir - stdout := &bytes.Buffer{} - env.stdout = stdout - if err := checkClaude(env); err != nil { - t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) - } - if !strings.Contains(stdout.String(), "✓ Global hooks installed") { - t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) - } - if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { - t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) - } - }) - } } func TestRemoveClaudeScenarios(t *testing.T) { - // From the home directory a project removal removes the global hooks, - // whose settings file is the same, so it removes their user-level - // section too. - t.Run("remove from home", func(t *testing.T) { - env, stdout, _ := newClaudeTestEnv(t) - env.projectDir = env.homeDir - if err := installClaude(env, true, false); err != nil { - t.Fatalf("installClaude: %v", err) - } - if err := removeClaude(env, false); err != nil { - t.Fatalf("removeClaude: %v", err) - } - data, err := os.ReadFile(globalSettingsPath(env.homeDir)) - if err != nil { - t.Fatalf("read global settings: %v", err) - } - if strings.Contains(string(data), "bd prime") { - t.Error("expected bd prime hooks removed") - } - instructions, err := os.ReadFile(globalClaudeInstructionsPath(env.homeDir)) - if err != nil { - t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) - } - if containsBeadsMarker(string(instructions)) { - t.Errorf("expected the user-level section removed, got:\n%s\nstdout:\n%s", instructions, stdout.String()) - } - }) - t.Run("remove global hooks", func(t *testing.T) { env, stdout, _ := newClaudeTestEnv(t) path := globalSettingsPath(env.homeDir) @@ -1336,16 +860,9 @@ func TestRemoveClaudeScenarios(t *testing.T) { }, }, }) - section := agents.RenderSection(agents.ProfileMinimal) - globalInstructions := globalClaudeInstructionsPath(env.homeDir) - if err := os.WriteFile(globalInstructions, []byte("# Mine\n\n"+section), 0o644); err != nil { - t.Fatalf("seed user-level %s: %v", claudeInstructionsFile, err) - } - // The project's own section, as bd init leaves it, belongs to the - // project install: a global removal must leave it alone. - projectInstructions := filepath.Join(env.projectDir, claudeInstructionsFile) - if err := os.WriteFile(projectInstructions, []byte(section), 0o644); err != nil { - t.Fatalf("seed project %s: %v", claudeInstructionsFile, err) + instructionsPath := filepath.Join(env.projectDir, claudeInstructionsFile) + if err := os.WriteFile(instructionsPath, []byte(agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { + t.Fatalf("seed %s: %v", claudeInstructionsFile, err) } // global=true → remove from global settings if err := removeClaude(env, true); err != nil { @@ -1358,19 +875,12 @@ func TestRemoveClaudeScenarios(t *testing.T) { if strings.Contains(string(data), "bd prime") { t.Error("expected bd prime hooks removed") } - instructions, err := os.ReadFile(globalInstructions) + instructions, err := os.ReadFile(instructionsPath) if err != nil { - t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) + t.Fatalf("read %s: %v", claudeInstructionsFile, err) } - if strings.Contains(string(instructions), "BEGIN BEADS INTEGRATION") || !strings.HasPrefix(string(instructions), "# Mine\n") { - t.Errorf("expected only the beads section removed from user-level %s, got:\n%s", claudeInstructionsFile, instructions) - } - project, err := os.ReadFile(projectInstructions) - if err != nil { - t.Fatalf("read project %s: %v", claudeInstructionsFile, err) - } - if string(project) != section { - t.Errorf("global removal changed the project's %s:\n%s", claudeInstructionsFile, project) + if strings.Contains(string(instructions), "BEGIN BEADS INTEGRATION") { + t.Fatalf("expected beads section removed from %s", claudeInstructionsFile) } if !strings.Contains(stdout.String(), "hooks removed") { t.Error("expected success message") diff --git a/cmd/bd/setup/factory_test.go b/cmd/bd/setup/factory_test.go index 6c868750f..2af6c84b0 100644 --- a/cmd/bd/setup/factory_test.go +++ b/cmd/bd/setup/factory_test.go @@ -82,6 +82,7 @@ Beads content More content`, expected: `# My Project + More content`, }, { @@ -96,6 +97,7 @@ Beads content expected: `# My Project Content + `, }, { @@ -109,39 +111,9 @@ Content expected: "# My Project\n\nContent", }, { - name: "rejoin surrounding content with one blank line", + name: "preserve surrounding whitespace and unrelated content", content: "Header\n\n" + agents.EmbeddedBeadsSection() + "\n\nFooter\n", - expected: "Header\n\nFooter\n", - }, - { - name: "remove section at top", - content: agents.EmbeddedBeadsSection() + "\n# My Project\n", - expected: "# My Project\n", - }, - { - name: "remove section from a new agents file", - content: createNewAgentsFile(), - expected: strings.Replace(createNewAgentsFile(), agents.RenderSection(agents.ProfileFull)+"\n\n", "", 1), - }, - { - name: "CRLF line endings", - content: "Header\r\n\r\n\r\nBeads content\r\n\r\n\r\nFooter\r\n", - expected: "Header\r\n\r\nFooter\r\n", - }, - { - name: "no blank line added where the section had none", - content: "Header\n\nBeads content\n\nFooter\n", - expected: "Header\nFooter\n", - }, - { - name: "marker sharing a line with text is cut exactly", - content: "Intro \nBeads content\n\n\nFooter\n", - expected: "Intro \nFooter\n", - }, - { - name: "file holding only the section becomes empty", - content: agents.EmbeddedBeadsSection(), - expected: "", + expected: "Header\n\n\n\nFooter\n", }, } diff --git a/cmd/bd/setup/gemini.go b/cmd/bd/setup/gemini.go index aa5c47273..d4442cfb7 100644 --- a/cmd/bd/setup/gemini.go +++ b/cmd/bd/setup/gemini.go @@ -129,15 +129,15 @@ func installGemini(env geminiEnv, project bool, stealth bool) error { if legacy == command { continue // never remove the variant we're about to add } - removeHookCommand(env.stdout, hooks, "SessionStart", legacy) - removeHookCommand(env.stdout, hooks, "PreCompress", legacy) + removeHookCommand(hooks, "SessionStart", legacy) + removeHookCommand(hooks, "PreCompress", legacy) } // Also clear any --hook-json registration from PreCompress. Beads previously // registered bd prime on PreCompress before we discovered that Gemini's // PreCompress event is advisory-only and cannot inject additionalContext // into the model regardless of output format. Re-running setup migrates cleanly. - removeHookCommand(env.stdout, hooks, "PreCompress", "bd prime --hook-json") - removeHookCommand(env.stdout, hooks, "PreCompress", "bd prime --stealth --hook-json") + removeHookCommand(hooks, "PreCompress", "bd prime --hook-json") + removeHookCommand(hooks, "PreCompress", "bd prime --stealth --hook-json") if addHookCommand(hooks, "SessionStart", command) { _, _ = fmt.Fprintln(env.stdout, "✓ Registered SessionStart hook") @@ -246,8 +246,8 @@ func removeGemini(env geminiEnv, project bool) error { "bd prime --stealth --hook-json", } for _, cmd := range variants { - removeHookCommand(env.stdout, hooks, "SessionStart", cmd) - removeHookCommand(env.stdout, hooks, "PreCompress", cmd) + removeHookCommand(hooks, "SessionStart", cmd) + removeHookCommand(hooks, "PreCompress", cmd) } data, err = json.MarshalIndent(settings, "", " ") diff --git a/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden b/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden deleted file mode 100644 index 68c99593c..000000000 --- a/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden +++ /dev/null @@ -1,83 +0,0 @@ -# bd setup claude artifact transcript: agents-import-stub -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: created $ROOT/project/AGENTS.md -# Agent Instructions - -Shared by every agent. ---- seed: created $ROOT/project/CLAUDE.md -@AGENTS.md - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Added beads section to existing AGENTS.md - -✓ Claude Code integration installed - File: $ROOT/project/AGENTS.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: modified $ROOT/project/AGENTS.md -# Agent Instructions - -Shared by every agent. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/AGENTS.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -result: ok ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook - Leaving shared beads section in AGENTS.md untouched (project-authoritative, not Claude-specific) -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": {} -} - -=== bd setup claude --check -result: error: claude hooks not installed ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden b/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden deleted file mode 100644 index a799c799f..000000000 --- a/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden +++ /dev/null @@ -1,171 +0,0 @@ -# bd setup claude artifact transcript: existing-user-files -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: created $ROOT/project/.claude/settings.json -{ - "permissions": { - "allow": [ - "Bash(go test:*)" - ] - }, - "hooks": { - "SessionStart": [ - { - "matcher": "", - "hooks": [ - { - "type": "command", - "command": "echo session started" - } - ] - } - ], - "Stop": [ - { - "matcher": "", - "hooks": [ - { - "type": "command", - "command": "notify-send done" - } - ] - } - ] - } -} ---- seed: created $ROOT/project/CLAUDE.md -# My Project - -House rules live here. - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Added beads section to existing CLAUDE.md - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "echo session started", - "type": "command" - } - ], - "matcher": "" - }, - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ], - "Stop": [ - { - "hooks": [ - { - "command": "notify-send done", - "type": "command" - } - ], - "matcher": "" - } - ] - }, - "permissions": { - "allow": [ - "Bash(go test:*)" - ] - } -} ---- files: modified $ROOT/project/CLAUDE.md -# My Project - -House rules live here. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -result: ok ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "echo session started", - "type": "command" - } - ], - "matcher": "" - } - ], - "Stop": [ - { - "hooks": [ - { - "command": "notify-send done", - "type": "command" - } - ], - "matcher": "" - } - ] - }, - "permissions": { - "allow": [ - "Bash(go test:*)" - ] - } -} ---- files: modified $ROOT/project/CLAUDE.md -# My Project - -House rules live here. - -=== bd setup claude --check -result: error: claude hooks not installed ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden b/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden deleted file mode 100644 index e6f628d1a..000000000 --- a/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden +++ /dev/null @@ -1,108 +0,0 @@ -# bd setup claude artifact transcript: global-beside-project-install -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: created $ROOT/home/.claude/CLAUDE.md -# My preferences - -Answer tersely. ---- seed: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- seed: created $ROOT/project/CLAUDE.md -# My Project - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - -=== bd setup claude --global -result: ok ---- stdout -Installing Claude hooks globally... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Added beads section to existing CLAUDE.md - -✓ Claude Code integration installed - File: $ROOT/home/.claude/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/home/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: modified $ROOT/home/.claude/CLAUDE.md -# My preferences - -Answer tersely. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-user.md] - ---- files: created $ROOT/home/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove --global -result: ok ---- stdout -Removing Claude hooks globally... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/home/.claude/CLAUDE.md -# My preferences - -Answer tersely. ---- files: modified $ROOT/home/.claude/settings.json -{ - "hooks": {} -} - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-global.golden b/cmd/bd/setup/testdata/claude-setup-global.golden deleted file mode 100644 index 0cfbfea4f..000000000 --- a/cmd/bd/setup/testdata/claude-setup-global.golden +++ /dev/null @@ -1,77 +0,0 @@ -# bd setup claude artifact transcript: global -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: none - -=== bd setup claude --global -result: ok ---- stdout -Installing Claude hooks globally... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Created new CLAUDE.md with beads integration - -✓ Claude Code integration installed - File: $ROOT/home/.claude/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/home/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: created $ROOT/home/.claude/CLAUDE.md - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-user.md] - ---- files: created $ROOT/home/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} - -=== bd setup claude --check -result: ok ---- stdout -✓ Global hooks installed: $ROOT/home/.claude/settings.json -✓ Claude Code integration installed: $ROOT/home/.claude/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove --global -result: ok ---- stdout -Removing Claude hooks globally... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/home/.claude/CLAUDE.md -(empty) ---- files: modified $ROOT/home/.claude/settings.json -{ - "hooks": {} -} - -=== bd setup claude --check -result: error: claude hooks not installed ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden b/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden deleted file mode 100644 index 96d9a5530..000000000 --- a/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden +++ /dev/null @@ -1,155 +0,0 @@ -# bd setup claude artifact transcript: legacy-local-settings -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: created $ROOT/project/.claude/settings.local.json -{ - "hooks": { - "SessionStart": [ - { - "matcher": "", - "hooks": [ - { - "type": "command", - "command": "bd prime" - } - ] - } - ], - "PreCompact": [ - { - "matcher": "", - "hooks": [ - { - "type": "command", - "command": "bd prime" - } - ] - } - ] - } -} - -=== bd setup claude --check -result: error: agents file not found ---- stdout -✓ Project hooks installed (legacy): $ROOT/project/.claude/settings.local.json - Consider running 'bd setup claude' to migrate to .claude/settings.json -✗ CLAUDE.md not found - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -✓ Removed SessionStart hook -✓ Removed PreCompact hook -✓ Migrated hooks from $ROOT/project/.claude/settings.local.json -Installing Claude Code integration... -✓ Created new CLAUDE.md with beads integration - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: modified $ROOT/project/.claude/settings.local.json -{ - "hooks": {} -} ---- files: created $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -result: ok ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": {} -} ---- files: modified $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ diff --git a/cmd/bd/setup/testdata/claude-setup-project-stealth.golden b/cmd/bd/setup/testdata/claude-setup-project-stealth.golden deleted file mode 100644 index 6912f2bde..000000000 --- a/cmd/bd/setup/testdata/claude-setup-project-stealth.golden +++ /dev/null @@ -1,120 +0,0 @@ -# bd setup claude artifact transcript: project-stealth -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: none - -=== bd setup claude --stealth -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Created new CLAUDE.md with beads integration - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --stealth --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: created $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -result: ok ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": {} -} ---- files: modified $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -result: error: claude hooks not installed ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-project.golden b/cmd/bd/setup/testdata/claude-setup-project.golden deleted file mode 100644 index 6f9736e3f..000000000 --- a/cmd/bd/setup/testdata/claude-setup-project.golden +++ /dev/null @@ -1,140 +0,0 @@ -# bd setup claude artifact transcript: project -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: none - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Created new CLAUDE.md with beads integration - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: created $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Hook already registered: SessionStart -Installing Claude Code integration... -✓ CLAUDE.md already has the current beads section - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -result: ok ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $ROOT/project/.claude/settings.json -{ - "hooks": {} -} ---- files: modified $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -result: error: claude hooks not installed ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-stale-section.golden b/cmd/bd/setup/testdata/claude-setup-stale-section.golden deleted file mode 100644 index c6be8e135..000000000 --- a/cmd/bd/setup/testdata/claude-setup-stale-section.golden +++ /dev/null @@ -1,72 +0,0 @@ -# bd setup claude artifact transcript: stale-section -# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden ---- seed: created $ROOT/project/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- seed: created $ROOT/project/CLAUDE.md -# My Project - - -Older beads guidance. - - -## Notes - -=== bd setup claude --check -result: error: beads section is stale ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -⚠ Claude Code integration installed but stale: $ROOT/project/CLAUDE.md - Run: bd setup claude (to update) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude -result: ok ---- stdout -Installing Claude hooks for this project... -✓ Hook already registered: SessionStart -Installing Claude Code integration... -✓ Updated existing beads section in CLAUDE.md - -✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $ROOT/project/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: modified $ROOT/project/CLAUDE.md -# My Project - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - -## Notes - -=== bd setup claude --check -result: ok ---- stdout -✓ Project hooks installed: $ROOT/project/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/show_children.go b/cmd/bd/show_children.go index 5daea300b..010c11b01 100644 --- a/cmd/bd/show_children.go +++ b/cmd/bd/show_children.go @@ -87,7 +87,6 @@ func showIssueChildren(ctx context.Context, args []string, jsonOut bool, shortMo // This requires a versioned storage backend (e.g., Dolt). func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode bool) error { var allIssues []*types.Issue - foundCount := 0 for idx, id := range args { issue, err := store.AsOf(ctx, id, ref) if err != nil { @@ -98,7 +97,6 @@ func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode boo fmt.Fprintf(os.Stderr, "Issue %s did not exist at %s\n", id, ref) continue } - foundCount++ if shortMode { fmt.Println(formatShortIssue(issue)) @@ -124,24 +122,8 @@ func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode boo fmt.Println() } - if foundCount == 0 { - return showAsOfFoundNothing() - } if jsonOutput && len(allIssues) > 0 { return outputJSON(allIssues) } return nil } - -// showAsOfFoundNothing ends an --as-of read, on either route, in which no -// lookup succeeded. Each failed lookup has already said why on stderr, so this -// is plain show's ending for a batch that found nothing: the JSON error -// envelope on stdout under --json, a bare exit 1 otherwise. A batch that read -// at least one issue still exits 0, as plain show's does. -func showAsOfFoundNothing() error { - if jsonOutput { - return HandleErrorWithHintRespectJSON("no issues found matching the provided IDs", - "check the --as-of ref (a branch name, or a full 32-character commit hash from 'bd history ') and that each issue existed at it") - } - return SilentExit() -} diff --git a/cmd/bd/show_comments_tail_proxied_integration_test.go b/cmd/bd/show_comments_tail_proxied_integration_test.go index 6936f7229..c0a0bc909 100644 --- a/cmd/bd/show_comments_tail_proxied_integration_test.go +++ b/cmd/bd/show_comments_tail_proxied_integration_test.go @@ -11,8 +11,8 @@ import ( // Route tests for `bd show --comments-tail N` (#6618 follow-up, bd-6gl9h7): // the shared fixtures and the proxied routes live here; the direct routes -// are in show_comments_tail_embedded_test.go, whose TestEmbedded* names put -// them in the embedded cmd shard manifest. +// are in show_comments_tail_embedded_test.go, which the embedded cmd shard +// manifest discovers by its *_embedded_test.go name. // // show_comments_tail_test.go pins printComments and renderWatchComments by // calling them directly, so a regression that passed 0 at any of the three diff --git a/cmd/bd/show_embedded_test.go b/cmd/bd/show_embedded_test.go index 11576f3b9..b142aa2f8 100644 --- a/cmd/bd/show_embedded_test.go +++ b/cmd/bd/show_embedded_test.go @@ -29,14 +29,13 @@ func bdShowRaw(t *testing.T, bd, dir string, args ...string) string { return string(out) } -// bdShowDetails runs "bd show --json [extra...]" and parses the -// IssueDetails. Retries on flock contention. -func bdShowDetails(t *testing.T, bd, dir, id string, extra ...string) map[string]interface{} { +// bdShowDetails runs "bd show --json" and parses the IssueDetails. +// Retries on flock contention. +func bdShowDetails(t *testing.T, bd, dir, id string) map[string]interface{} { t.Helper() - args := append([]string{"show", id, "--json"}, extra...) - out, err := bdRunWithFlockRetry(t, bd, dir, args...) + out, err := bdRunWithFlockRetry(t, bd, dir, "show", id, "--json") if err != nil { - t.Fatalf("bd %s failed: %v\n%s", strings.Join(args, " "), err, out) + t.Fatalf("bd show %s --json failed: %v\n%s", id, err, out) } // JSON output may be wrapped in an array s := strings.TrimSpace(string(out)) @@ -283,34 +282,6 @@ func TestEmbeddedShowBasicsAndJSON(t *testing.T) { if _, ok := m["comments"]; ok { t.Errorf("comments slice should be absent by default") } - if omitted, _ := m["comments_omitted"].(bool); !omitted { - t.Errorf("comments_omitted: got %v, want true beside a nonzero comment_count and no rows", m["comments_omitted"]) - } - }) - - // GH#5565 / bd-u96si: direct/embedded twin of proxied - // show_wisp_comments_include_streams. --include-comments must stream the - // wisp's comments from wisp_comments, the count in the same payload must - // agree, and comments_omitted must stay omitted. - t.Run("show_json_wisp_comments_include_streams", func(t *testing.T) { - wisp := bdCreate(t, bd, dir, "Wisp stream", "--type", "task", "--ephemeral") - for i := 0; i < 2; i++ { - if out, err := bdRunWithFlockRetry(t, bd, dir, "comments", "add", wisp.ID, fmt.Sprintf("wisp stream %d", i)); err != nil { - t.Fatalf("bd comments add failed: %v\n%s", err, out) - } - } - - m := bdShowDetails(t, bd, dir, wisp.ID, "--include-comments") - comments, _ := m["comments"].([]interface{}) - if len(comments) != 2 { - t.Fatalf("comments: got %d rows, want 2 with --include-comments: %v", len(comments), m) - } - if got, _ := m["comment_count"].(float64); got != 2 { - t.Errorf("comment_count: got %v, want 2 beside the 2 streamed rows", m["comment_count"]) - } - if v, present := m["comments_omitted"]; present { - t.Errorf("comments_omitted should be absent under --include-comments, got %v", v) - } }) // ===== --short ===== @@ -513,109 +484,6 @@ func TestEmbeddedShowDetailAndCurrentHistoryAndCurrent(t *testing.T) { }) } -// TestEmbeddedShowAsOfFailureExitCodes pins `bd show --as-of` to plain show's -// failure contract on the direct route. Each lookup that fails is reported on -// stderr and the others still render; the command fails only when no issue -// could be read at the ref, with show's JSON error envelope on stdout under -// --json and a bare exit 1 otherwise. A ref the Dolt AS OF read does not take -// (a versioned-history address, an instant), a branch that does not exist, -// and an issue created after the ref each used to exit 0 with nothing on -// stdout, which a caller cannot tell from a successful read. -func TestEmbeddedShowAsOfFailureExitCodes(t *testing.T) { - if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { - t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") - } - t.Parallel() - - bd := buildEmbeddedBD(t) - dir, beadsDir, _ := bdInit(t, bd, "--prefix", "sx") - - issue := bdCreate(t, bd, dir, "AsOf original", "--type", "task") - store := openStore(t, beadsDir, "sx") - ref, err := store.GetCurrentCommit(t.Context()) - if err != nil { - t.Fatalf("GetCurrentCommit: %v", err) - } - store.Close() // release flock before subprocess - later := bdCreate(t, bd, dir, "Created after the ref", "--type", "task") - - show := func(t *testing.T, args ...string) (stdout, stderr string, exitCode int) { - t.Helper() - cmd := exec.Command(bd, append([]string{"show"}, args...)...) - cmd.Dir = dir - cmd.Env = bdEnv(dir) - out, errOut, err := runCommandBuffers(t, cmd) - if err != nil { - var ee *exec.ExitError - if !errors.As(err, &ee) { - t.Fatalf("bd show %s did not run: %v", strings.Join(args, " "), err) - } - exitCode = ee.ExitCode() - } - return out.String(), errOut.String(), exitCode - } - - for _, tc := range []struct { - name string - args []string - // why is what the per-id report on stderr has to name. - why string - }{ - {"versioned_history_address", []string{issue.ID, "--as-of", "asof:" + issue.ID + ":1"}, "invalid ref"}, - {"instant", []string{issue.ID, "--as-of", "2026-10-17T00:00:00Z"}, "invalid ref"}, - {"unknown_branch", []string{issue.ID, "--as-of", "no-such-branch"}, "no-such-branch"}, - {"issue_created_after_ref", []string{later.ID, "--as-of", ref}, later.ID}, - {"issue_created_after_ref_short", []string{later.ID, "--as-of", ref, "--short"}, later.ID}, - } { - t.Run(tc.name, func(t *testing.T) { - stdout, stderr, code := show(t, tc.args...) - if code != 1 || stdout != "" || !strings.Contains(stderr, tc.why) { - t.Errorf("bd show %s exited %d, want 1 with empty stdout and %q on stderr\nstdout:\n%s\nstderr:\n%s", - strings.Join(tc.args, " "), code, tc.why, stdout, stderr) - } - - args := append(append([]string{}, tc.args...), "--json") - stdout, stderr, code = show(t, args...) - var envelope struct { - Error string `json:"error"` - Hint string `json:"hint"` - } - if code != 1 || json.Unmarshal([]byte(stdout), &envelope) != nil || - envelope.Error != "no issues found matching the provided IDs" || envelope.Hint == "" { - t.Errorf("bd show %s exited %d, want 1 with show's JSON error envelope on stdout\nstdout:\n%s\nstderr:\n%s", - strings.Join(args, " "), code, stdout, stderr) - } - if !strings.Contains(stderr, tc.why) { - t.Errorf("bd show %s stderr does not name %q:\n%s", strings.Join(args, " "), tc.why, stderr) - } - }) - } - - // Plain show's partial failure: the issues that were read are the - // answer, the miss is reported on stderr, and the command succeeds. - t.Run("partial_failure_exits_zero", func(t *testing.T) { - stdout, stderr, code := show(t, issue.ID, later.ID, "--as-of", ref, "--json") - var shown []struct { - ID string `json:"id"` - Title string `json:"title"` - } - if code != 0 || json.Unmarshal([]byte(stdout), &shown) != nil || len(shown) != 1 || - shown[0].ID != issue.ID || shown[0].Title != "AsOf original" { - t.Errorf("bd show %s %s --as-of %s --json exited %d, want 0 with an array of %s alone\nstdout:\n%s\nstderr:\n%s", - issue.ID, later.ID, ref, code, issue.ID, stdout, stderr) - } - if !strings.Contains(stderr, later.ID) { - t.Errorf("--json stderr does not report %s:\n%s", later.ID, stderr) - } - - stdout, stderr, code = show(t, issue.ID, later.ID, "--as-of", ref) - if code != 0 || !strings.Contains(stdout, "AsOf original") || !strings.Contains(stderr, later.ID) { - t.Errorf("bd show %s %s --as-of %s exited %d, want 0 rendering %s and reporting %s on stderr\nstdout:\n%s\nstderr:\n%s", - issue.ID, later.ID, ref, code, issue.ID, later.ID, stdout, stderr) - } - }) -} - // TestEmbeddedShowConcurrent exercises show operations concurrently. func TestEmbeddedShowConcurrent(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { diff --git a/cmd/bd/show_proxied_integration_test.go b/cmd/bd/show_proxied_integration_test.go index 353d4e844..b518aac7d 100644 --- a/cmd/bd/show_proxied_integration_test.go +++ b/cmd/bd/show_proxied_integration_test.go @@ -799,47 +799,10 @@ func TestProxiedServerShow3(t *testing.T) { p := newSharedProxiedProject(t, bd, "saoi") issue := bdProxiedCreate(t, bd, p.dir, "AsOf invalid", "--type", "task") - stdout, stderr := bdProxiedShowFail(t, bd, p.dir, issue.ID, "--as-of", "'; DROP TABLE issues; --") + _, stderr, _ := bdProxiedRunBuffers(t, bd, p.dir, "show", issue.ID, "--as-of", "'; DROP TABLE issues; --") if !strings.Contains(stderr, "invalid ref") { t.Errorf("expected 'invalid ref' in stderr, got: %s", stderr) } - if stdout != "" { - t.Errorf("expected nothing on stdout when no issue was read, got: %s", stdout) - } - }) - - // The proxied twin of TestEmbeddedShowAsOfFailureExitCodes: when no issue - // can be read at the ref the command fails the way plain show does, and a - // batch that read at least one issue still succeeds. - t.Run("show_as_of_nothing_found_fails_like_show", func(t *testing.T) { - t.Parallel() - p := newSharedProxiedProject(t, bd, "saon") - issue := bdProxiedCreate(t, bd, p.dir, "AsOf kept", "--type", "task") - hash := proxiedCurrentCommit(t, p) - later := bdProxiedCreate(t, bd, p.dir, "AsOf created later", "--type", "task") - - stdout, stderr := bdProxiedShowFail(t, bd, p.dir, later.ID, "--as-of", hash) - if stdout != "" || !strings.Contains(stderr, later.ID) { - t.Errorf("want empty stdout and %s reported on stderr\nstdout:\n%s\nstderr:\n%s", later.ID, stdout, stderr) - } - - stdout, stderr = bdProxiedShowFail(t, bd, p.dir, later.ID, "--as-of", hash, "--json") - var envelope struct { - Error string `json:"error"` - Hint string `json:"hint"` - } - if err := json.Unmarshal([]byte(stdout), &envelope); err != nil || - envelope.Error != "no issues found matching the provided IDs" || envelope.Hint == "" { - t.Errorf("--json stdout is not show's error envelope (%v):\n%s", err, stdout) - } - if !strings.Contains(stderr, later.ID) { - t.Errorf("--json stderr does not report %s:\n%s", later.ID, stderr) - } - - arr := bdProxiedShowDetailsAll(t, bd, p.dir, issue.ID, later.ID, "--as-of", hash) - if len(arr) != 1 || arr[0]["id"] != issue.ID || arr[0]["title"] != "AsOf kept" { - t.Errorf("partial --as-of read: want only %s as of the ref, got %v", issue.ID, arr) - } }) t.Run("show_as_of_short_mode", func(t *testing.T) { diff --git a/cmd/bd/show_proxied_server.go b/cmd/bd/show_proxied_server.go index 45b3582d6..741bbbb63 100644 --- a/cmd/bd/show_proxied_server.go +++ b/cmd/bd/show_proxied_server.go @@ -126,7 +126,7 @@ func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string switch { case in.asOfRef != "": - return runShowProxiedAsOf(ctx, uw, in) + runShowProxiedAsOf(ctx, uw, in) case in.thread: return runShowProxiedThread(ctx, uw, in) case in.refs: @@ -218,9 +218,8 @@ func reportIssueLookupFailure(verb, id string, err error) { fmt.Fprintf(os.Stderr, "Error %s %s: %v\n", verb, id, err) } -func runShowProxiedAsOf(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) error { +func runShowProxiedAsOf(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) { var jsonIssues []*types.Issue - foundCount := 0 for idx, id := range in.ids { issue, err := uw.IssueUseCase().AsOf(ctx, id, in.asOfRef) if err != nil { @@ -231,7 +230,6 @@ func runShowProxiedAsOf(ctx context.Context, uw uow.UnitOfWork, in *showProxiedI fmt.Fprintf(os.Stderr, "Issue %s did not exist at %s\n", id, in.asOfRef) continue } - foundCount++ if in.shortMode { fmt.Println(formatShortIssue(issue)) @@ -252,13 +250,9 @@ func runShowProxiedAsOf(ctx context.Context, uw uow.UnitOfWork, in *showProxiedI } fmt.Println() } - if foundCount == 0 { - return showAsOfFoundNothing() - } if jsonOutput && len(jsonIssues) > 0 { - return outputJSON(jsonIssues) + _ = outputJSON(jsonIssues) } - return nil } func runShowProxiedRefs(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) { diff --git a/cmd/bd/show_test.go b/cmd/bd/show_test.go index c5687630e..0a4a46764 100644 --- a/cmd/bd/show_test.go +++ b/cmd/bd/show_test.go @@ -137,46 +137,6 @@ func TestShow_NotFoundJSON(t *testing.T) { } } -// TestShow_AsOfFoundNothingExitsNonZero holds --as-of to the contract the two -// tests above pin for plain show, on the server leg's direct route: when no -// issue can be read at the ref (a ref the Dolt AS OF read does not take, or an -// issue absent at it) the command exits non-zero, with show's JSON error -// envelope on stdout under --json. Both used to exit 0 with nothing on stdout. -func TestShow_AsOfFoundNothingExitsNonZero(t *testing.T) { - tmpDir := setupCLITestDB(t) - - out := runBDInProcess(t, tmpDir, "create", "AsOf server", "-p", "1", "--json") - jsonStart := strings.Index(out, "{") - if jsonStart < 0 { - t.Fatalf("no JSON found in create output: %s", out) - } - var issue map[string]interface{} - if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil { - t.Fatalf("failed to parse create output: %v, output: %s", err, out) - } - id := issue["id"].(string) - - stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "show", id, "--as-of", "asof:"+id+":1") - if err == nil || stdout != "" || !strings.Contains(stderr, "invalid ref") { - t.Errorf("bd show %s --as-of asof:%s:1 returned %v, want an error with empty stdout and 'invalid ref' on stderr\nstdout: %s\nstderr: %s", id, id, err, stdout, stderr) - } - - stdout, stderr, err = runBDInProcessAllowError(t, tmpDir, "show", "test-nonexistent", "--as-of", "main", "--json") - if err == nil { - t.Errorf("expected error for an issue absent at the ref with --json, but command succeeded\nstdout: %s\nstderr: %s", stdout, stderr) - } - var errResp map[string]interface{} - if jsonErr := json.Unmarshal([]byte(stdout), &errResp); jsonErr != nil { - t.Fatalf("expected show's JSON error envelope on stdout, got parse error: %v\nStdout: %s", jsonErr, stdout) - } - if errField, _ := errResp["error"].(string); errField != "no issues found matching the provided IDs" { - t.Errorf("expected plain show's 'error' text, got: %s", stdout) - } - if !strings.Contains(stderr, "test-nonexistent") { - t.Errorf("expected the failed lookup reported on stderr, got: %s", stderr) - } -} - // TestShow_NotFoundHintExplainsAmbiguity guards ga-m6inyb: a never-existed ID // and a deleted/purged ID currently print the identical "not found" text, so // a reader has no way to know the two are different situations (deleted diff --git a/cmd/bd/storage_chain.go b/cmd/bd/storage_chain.go index 85e554b53..0c420d5c2 100644 --- a/cmd/bd/storage_chain.go +++ b/cmd/bd/storage_chain.go @@ -23,13 +23,6 @@ import ( // storage spans measure pure DB time without hook-firing overhead. The policy // sits directly beneath hooks so serve's one hook-layer peel retains it. // -// Versioned-history activation is NOT applied here. It used to be, and this runs -// on the one store a command opens for its own workspace, so every store a -// routed write opens for another workspace missed it. It now happens in the -// factories that construct a store, on the raw store before anything can wrap it -// (see versioned_history.go) -- which is also why the decorators above, none of -// which forwards SetVersionedHistoryEnabled, cannot get in its way. -// // Extracted from main.go's PersistentPreRunE so the chain composition is // unit-testable — the bug this PR fixes was a missing WrapStorage call, // and the regression class deserves test coverage. diff --git a/cmd/bd/store_factory.go b/cmd/bd/store_factory.go index e41e88bd9..d9a720e69 100644 --- a/cmd/bd/store_factory.go +++ b/cmd/bd/store_factory.go @@ -56,7 +56,6 @@ func usesProxiedServer() bool { // registered backend decides for itself what read-only means, and refusing to // offer it the setting would be this factory guessing on its behalf. func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readOnly bool) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(beadsDir, s, err) }() backend, ok := backends.Lookup(name) if !ok { @@ -69,7 +68,6 @@ func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readO } func newDoltStore(ctx context.Context, cfg *dolt.Config) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(cfg.BeadsDir, s, err) }() if cfg.ProxiedServer { return nil, errProxiedStoreUnrouted() @@ -178,11 +176,7 @@ func newExistingDoltStoreFromConfig(ctx context.Context, beadsDir string) (stora // openDoltStoreFromConfig is the body of newDoltStoreFromConfig and // newExistingDoltStoreFromConfig; requireExisting selects the latter. func openDoltStoreFromConfig(ctx context.Context, beadsDir string, requireExisting bool) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(beadsDir, s, err) }() - if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { // A present-but-unloadable metadata.json must not degrade to the @@ -302,9 +296,6 @@ func newPreviewStoreFromConfig(ctx context.Context, beadsDir string) (storage.Do // OpenNonMutating hook on backends.Backend, which this function would call // instead, is the follow-up that closes the exception. func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, preview bool) (storage.DoltStorage, error) { - if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { // Same contract as newDoltStoreFromConfig: a present-but-unloadable diff --git a/cmd/bd/store_factory_nocgo.go b/cmd/bd/store_factory_nocgo.go index b5e882750..566953d21 100644 --- a/cmd/bd/store_factory_nocgo.go +++ b/cmd/bd/store_factory_nocgo.go @@ -34,7 +34,6 @@ func usesProxiedServer() bool { // exists here too so the root pre-run's registry arm has one activating // construction path in both builds. func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readOnly bool) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(beadsDir, s, err) }() backend, ok := backends.Lookup(name) if !ok { @@ -49,7 +48,6 @@ func newRegisteredBackendStore(ctx context.Context, name, beadsDir string, readO // newDoltStore applies events-journal activation for the same reason its CGO // twin does — see the note at the top of events_journal.go. func newDoltStore(ctx context.Context, cfg *dolt.Config) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(cfg.BeadsDir, s, err) }() if cfg.ProxiedServer { return nil, errProxiedStoreUnrouted() @@ -67,11 +65,7 @@ func acquireEmbeddedLock(_ string, _ bool) (util.Unlocker, error) { // newDoltStoreFromConfig creates a SQL-server-backed storage backend from config. func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.DoltStorage, err error) { - defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }() defer func() { s, err = activateEventsJournalStore(beadsDir, s, err) }() - if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { // Name the real cause: without this, a present-but-unloadable @@ -109,9 +103,6 @@ func newExistingDoltStoreFromConfig(ctx context.Context, beadsDir string) (stora // in the construction guard). The registry arm is the exception the cgo // twin, openNonMutatingStoreFromConfig, describes. func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { - if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil { - return nil, err - } cfg, err := configfile.Load(beadsDir) if err != nil { return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err) diff --git a/cmd/bd/store_factory_nocgo_test.go b/cmd/bd/store_factory_nocgo_test.go index 52dc49e89..b20a8cacc 100644 --- a/cmd/bd/store_factory_nocgo_test.go +++ b/cmd/bd/store_factory_nocgo_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/steveyegge/beads/internal/config" - "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" ) @@ -199,83 +198,3 @@ func TestNocgoFactoriesHonorSharedServer(t *testing.T) { }) } } - -// TestNocgoStoreFactoriesRefuseGraphWorkspace is the !cgo half of -// TestStoreFactoriesRefuseGraphWorkspace. The CGO_ENABLED=0 binaries -// .goreleaser.yml ships open routed, cross-repository and create --repo -// targets through their own copies of these factories, so each must refuse a -// graph workspace before its configfile.Load, which would otherwise migrate -// one marked only by a legacy config.json into metadata.json first, and one -// declared only by the graph-preview-format marker, whose metadata is lost or -// stripped. It runs in CI only because bazel.yml's PURE_CMD_BD_TESTS -// allowlists it by name. -func TestNocgoStoreFactoriesRefuseGraphWorkspace(t *testing.T) { - isolateSharedServerSignals(t) - pinLegacyUpgradeGuardEnv(t) - const graphMetadata = `{"backend":"dolt","graph_mode":"link"}` - // What a bd that predates graph_mode leaves of a graph workspace's - // metadata: the database name still selects the graph database. - const strippedMetadata = `{"backend":"dolt","dolt_mode":"server","dolt_database":"beads_graph_0123456789abcdef0123456789abcdef"}` - factories := map[string]func(context.Context, string) (storage.DoltStorage, error){ - "read-write": newDoltStoreFromConfig, - "routed": newExistingDoltStoreFromConfig, - "read-only": newReadOnlyStoreFromConfig, - "preview": newPreviewStoreFromConfig, - } - layouts := []struct { - name string - // filename is the metadata file; "" lays down no metadata. - filename string - metadata string - // marker adds the graph-preview-format sentinel. - marker bool - }{ - {name: "metadata.json", filename: "metadata.json", metadata: graphMetadata}, - {name: "config.json", filename: "config.json", metadata: graphMetadata}, - {name: "marker only", marker: true}, - {name: "marker, metadata stripped", filename: "metadata.json", metadata: strippedMetadata, marker: true}, - } - for _, layout := range layouts { - for name, open := range factories { - t.Run(layout.name+"/"+name, func(t *testing.T) { - beadsDir := t.TempDir() - want := map[string]bool{} - path := "" - if layout.filename != "" { - path = filepath.Join(beadsDir, layout.filename) - if err := os.WriteFile(path, []byte(layout.metadata), 0o600); err != nil { - t.Fatal(err) - } - want[layout.filename] = true - } - if layout.marker { - if err := os.WriteFile(filepath.Join(beadsDir, "graph-preview-format"), []byte("link-preview-v9\n"), 0o600); err != nil { - t.Fatal(err) - } - want["graph-preview-format"] = true - } - store, err := open(t.Context(), beadsDir) - if err == nil { - _ = store.Close() - } - if !isUnsupportedWorkspaceFormat(err) { - t.Fatalf("%s open = %v, want unsupported workspace format refusal", name, err) - } - if path != "" { - if got, readErr := os.ReadFile(path); readErr != nil || string(got) != layout.metadata { - t.Fatalf("%s open rewrote %s: %q, %v", name, layout.filename, got, readErr) - } - } - entries, readErr := os.ReadDir(beadsDir) - if readErr != nil || len(entries) != len(want) { - t.Fatalf("%s open left %d entries in the workspace, want %d (%v)", name, len(entries), len(want), readErr) - } - for _, entry := range entries { - if !want[entry.Name()] { - t.Fatalf("%s open created %s in the workspace", name, entry.Name()) - } - } - }) - } - } -} diff --git a/cmd/bd/store_factory_test.go b/cmd/bd/store_factory_test.go index 0de28bdb8..aec0dd965 100644 --- a/cmd/bd/store_factory_test.go +++ b/cmd/bd/store_factory_test.go @@ -18,10 +18,10 @@ import ( "github.com/steveyegge/beads/internal/storage/dolt" ) -// TestEmbeddedNewDoltStoreFromConfig_NoMetadata verifies that newDoltStoreFromConfig +// TestNewDoltStoreFromConfig_NoMetadata verifies that newDoltStoreFromConfig // succeeds when the beads directory has no metadata.json (fresh project). // Regression test for GH#2988: "no database selected" error. -func TestEmbeddedNewDoltStoreFromConfig_NoMetadata(t *testing.T) { +func TestNewDoltStoreFromConfig_NoMetadata(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") } @@ -307,11 +307,11 @@ func TestOpenNonMutatingStoreHonorsSharedServerConfig(t *testing.T) { // a correct implementation. const readOnlySharedServerPort = "19998" -// TestEmbeddedNewDoltStoreFromConfig_HyphenatedDBName verifies that +// TestNewDoltStoreFromConfig_HyphenatedDBName verifies that // newDoltStoreFromConfig auto-sanitizes hyphenated database names for embedded // mode and persists the fix to metadata.json. // Regression test for GH#3231: pre-#2142 projects break on embedded upgrade. -func TestEmbeddedNewDoltStoreFromConfig_HyphenatedDBName(t *testing.T) { +func TestNewDoltStoreFromConfig_HyphenatedDBName(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") } @@ -465,9 +465,9 @@ func TestMigrateHyphenatedDB_NoOldDir(t *testing.T) { } } -// TestEmbeddedNewDoltStoreFromConfig_DottedDBName verifies that dots are also +// TestNewDoltStoreFromConfig_DottedDBName verifies that dots are also // auto-sanitized, not just hyphens (GH#3231). -func TestEmbeddedNewDoltStoreFromConfig_DottedDBName(t *testing.T) { +func TestNewDoltStoreFromConfig_DottedDBName(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") } @@ -498,7 +498,7 @@ func TestEmbeddedNewDoltStoreFromConfig_DottedDBName(t *testing.T) { } } -// TestEmbeddedNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase covers Blocker 2 +// TestNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase covers Blocker 2 // of the 2026-07-23 maintainer review on gastownhall/beads#4930: cfg.ReadOnly // alone (an ordinary classified-read command) must route through // OpenForReadOnlyCommand, which creates the embedded data directory on first @@ -506,7 +506,7 @@ func TestEmbeddedNewDoltStoreFromConfig_DottedDBName(t *testing.T) { // --readonly signal) must route through the genuinely write-refusing // OpenReadOnly instead, which fails rather than create anything for a fresh // database. -func TestEmbeddedNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase(t *testing.T) { +func TestNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") } diff --git a/cmd/bd/store_reopen.go b/cmd/bd/store_reopen.go index 4a774a7fe..f65f69255 100644 --- a/cmd/bd/store_reopen.go +++ b/cmd/bd/store_reopen.go @@ -91,10 +91,7 @@ func resolveBeadsDirForDBPath(dbPath string) string { } for _, beadsDir := range candidates { - // Read-only: --db, BEADS_DB and create --repo resolve their target - // here before command admission classifies it, and configfile.Load - // would migrate a candidate's legacy config.json on the way. - cfg, err := configfile.LoadForDiscovery(beadsDir) + cfg, err := configfile.Load(beadsDir) if err != nil || cfg == nil { continue } diff --git a/cmd/bd/store_selection_failloud_test.go b/cmd/bd/store_selection_failloud_test.go index 86231c85e..5f441e4be 100644 --- a/cmd/bd/store_selection_failloud_test.go +++ b/cmd/bd/store_selection_failloud_test.go @@ -65,14 +65,12 @@ func TestLoadServerModeFromBeadsDirCorruptMetadataReturnsError(t *testing.T) { } // End-to-end contract for a corrupt metadata.json, exercised through the -// real binary on an embedded workspace. Since #4857 a metadata.json that -// exists but cannot be parsed fails safe wherever a workspace is selected, -// doctor and init included (TestDoctorRejectsCorruptMetadataBeforeSharedServerChecks -// pins doctor's shared-server half): bd version still runs and warns, every -// workspace command fails loud naming the file instead of answering -// false-empty from the embedded fallback, nothing rewrites the file, and -// restoring it brings the data back. -func TestEmbeddedCorruptMetadataFailsLoudUntilRestored(t *testing.T) { +// real binary: diagnostic and repair commands still run (warn-and-continue), +// data commands fail loud instead of answering false-empty from the embedded +// fallback, and bd init can rewrite the file — after which data commands work +// again. Guards the scoping of the fail-loud behavior: fatal only where a +// store is actually selected, never on the repair path itself. +func TestCorruptMetadataDiagnosticsRunAndDataFailsLoud(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") } @@ -80,15 +78,8 @@ func TestEmbeddedCorruptMetadataFailsLoudUntilRestored(t *testing.T) { bd := buildEmbeddedBD(t) dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cm") - bdCreate(t, bd, dir, "survives the corruption") - metadataPath := filepath.Join(beadsDir, "metadata.json") - original, err := os.ReadFile(metadataPath) - if err != nil { - t.Fatalf("read metadata.json: %v", err) - } - corrupt := []byte(`{"dolt_mode":"serv`) - if err := os.WriteFile(metadataPath, corrupt, 0o600); err != nil { + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"dolt_mode":"serv`), 0o600); err != nil { t.Fatalf("corrupt metadata.json: %v", err) } @@ -100,43 +91,27 @@ func TestEmbeddedCorruptMetadataFailsLoudUntilRestored(t *testing.T) { return string(out), err } - // bd version needs no workspace: it warns and runs. - if out, err := run("version"); err != nil || !strings.Contains(out, "metadata.json") { - t.Errorf("bd version with corrupt metadata.json: want success with a warning naming the file, got %v\n%s", err, out) - } - - // Every command that selects the workspace refuses before opening or - // modifying storage, naming the file. - for _, args := range [][]string{ - {"doctor"}, - {"list", "--json"}, - {"init", "--prefix", "cm", "--quiet", "--skip-hooks", "--skip-agents"}, - } { - out, err := run(args...) - if err == nil { - t.Errorf("bd %s with corrupt metadata.json: want a loud failure, got success:\n%s", strings.Join(args, " "), out) - continue - } - for _, want := range []string{"metadata.json", "parsing config", "no storage database was opened or modified"} { - if !strings.Contains(out, want) { - t.Errorf("bd %s with corrupt metadata.json: output missing %q:\n%s", strings.Join(args, " "), want, out) - } + // Diagnostic / repair-path commands must keep working. + for _, args := range [][]string{{"version"}, {"doctor"}} { + if out, err := run(args...); err != nil { + t.Errorf("bd %s with corrupt metadata.json: want success, got %v\n%s", strings.Join(args, " "), err, out) } } - if after, err := os.ReadFile(metadataPath); err != nil || string(after) != string(corrupt) { - t.Fatalf("a refused command rewrote metadata.json (err %v):\nbefore: %q\nafter: %q", err, corrupt, after) - } - // Restoring the file is the repair, and the data was never touched. - if err := os.WriteFile(metadataPath, original, 0o600); err != nil { - t.Fatalf("restore metadata.json: %v", err) - } + // Data commands must fail loud, naming the file — not answer false-empty. out, err := run("list", "--json") - if err != nil { - t.Fatalf("bd list after restoring metadata.json: %v\n%s", err, out) + if err == nil { + t.Fatalf("bd list with corrupt metadata.json: want loud failure, got success:\n%s", out) } - if !strings.Contains(out, "survives the corruption") { - t.Fatalf("bd list after restoring metadata.json lost the issue created before the corruption:\n%s", out) + if !strings.Contains(out, "metadata.json") { + t.Fatalf("bd list error should name metadata.json:\n%s", out) + } + + // bd init is the documented repair path: it must run, rewrite the file, + // and restore data commands. + runBDInit(t, bd, dir, "--prefix", "cm") + if out, err := run("list", "--json"); err != nil { + t.Fatalf("bd list after bd init repair: %v\n%s", err, out) } } diff --git a/cmd/bd/test_repo_beads_guard_test.go b/cmd/bd/test_repo_beads_guard_test.go index e3c38c88a..e5876e5b5 100644 --- a/cmd/bd/test_repo_beads_guard_test.go +++ b/cmd/bd/test_repo_beads_guard_test.go @@ -2,14 +2,11 @@ package main import ( "errors" - "flag" "fmt" "os" "os/exec" "path/filepath" - "runtime" "slices" - "strconv" "strings" "testing" @@ -18,7 +15,6 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/git" - "github.com/steveyegge/beads/internal/initprocs" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/migration" "github.com/steveyegge/beads/internal/testutil" @@ -82,13 +78,6 @@ const suiteRootPrefix = "beads-bd-tests-" // Guardrail: ensure the cmd/bd test suite does not touch the real repo .beads state. // Disable with BEADS_TEST_GUARD_DISABLE=1 (useful when running tests while actively using beads). func TestMain(m *testing.M) { - // main() is not run here, so hand back the Ps initprocs held during init, - // and the -test.parallel default testing derived from the capped count. - // An explicit -test.parallel is parsed later, by m.Run, and still wins. - initprocs.Done() - if f := flag.Lookup("test.parallel"); f != nil { - _ = f.Value.Set(strconv.Itoa(runtime.GOMAXPROCS(0))) - } if code, ok := credentialcmd.Dispatch(); ok { os.Exit(code) } diff --git a/cmd/bd/testdata/agent_artifacts/init-agents-profile-full.golden b/cmd/bd/testdata/agent_artifacts/init-agents-profile-full.golden deleted file mode 100644 index 790ec3900..000000000 --- a/cmd/bd/testdata/agent_artifacts/init-agents-profile-full.golden +++ /dev/null @@ -1,132 +0,0 @@ -# bd init agent artifact transcript: init-agents-profile-full -# Regenerate with BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden - -=== bd init --quiet --prefix ab --agents-profile full ---- files: created $PROJECT/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: created $PROJECT/AGENTS.md -# Agent Instructions - -This project uses **bd** (beads) for issue tracking. Run `bd prime` for full workflow context. - -> **Architecture in one line:** Issues live in a local Dolt database -> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a -> git-compatible protocol), stored under `refs/dolt/data` on your git -> remote — separate from `refs/heads/*` where your code lives. -> `.beads/issues.jsonl` is a passive export, not the wire protocol. -> -> See [sync-concepts](https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md) -> for the one-screen overview and anti-patterns (don't treat JSONL as the -> source of truth; don't `bd import` during normal operation; don't -> reach for third-party Dolt hosting before trying the default). - -## Quick Reference - -```bash -bd ready # Find available work -bd show # View issue details -bd update --claim # Claim work atomically -bd close # Complete work -``` - -## Non-Interactive Shell Commands - -**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts. - -Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input. - -**Use these forms instead:** -```bash -# Force overwrite without prompting -cp -f source dest # NOT: cp source dest -mv -f source dest # NOT: mv source dest -rm -f file # NOT: rm file - -# For recursive operations -rm -rf directory # NOT: rm -r directory -cp -rf source dest # NOT: cp -r source dest -``` - -**Other commands that may prompt:** -- `scp` - use `-o BatchMode=yes` for non-interactive -- `ssh` - use `-o BatchMode=yes` to fail instead of prompting -- `apt-get` - use `-y` flag -- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-full-no-remote.md] - - - -## Beads Issue Tracker - -Use Beads (`bd`) for durable task tracking in repositories that include it. Use the `beads` skill at `.agents/skills/beads/SKILL.md` (project install) or `~/.agents/skills/beads/SKILL.md` (global install) for Beads workflow guidance, then use the `bd` CLI for issue operations. - -### Quick Reference - -```bash -bd ready # Find available work -bd show # View issue details -bd update --claim # Claim work -bd close # Complete work -bd prime # Refresh Beads context -``` - -### Rules - -- Use `bd` for all task tracking; do not create markdown TODO lists. -- Run `bd prime` when Beads context is missing or stale. Codex 0.129.0+ can load Beads context automatically through native hooks; use `/hooks` to inspect or toggle them. -- Keep durable project facts in Beads via `bd remember` rather than in per-tool memory files, which fragment across accounts; per-operator preferences belong in your harness's own memory. - -**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. - ---- files: created $PROJECT/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md] - - - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -exit: 0 ---- stdout -✓ Project hooks installed: $PROJECT/.claude/settings.json -✓ Claude Code integration installed: $PROJECT/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/testdata/agent_artifacts/init-default.golden b/cmd/bd/testdata/agent_artifacts/init-default.golden deleted file mode 100644 index 154b699be..000000000 --- a/cmd/bd/testdata/agent_artifacts/init-default.golden +++ /dev/null @@ -1,268 +0,0 @@ -# bd init agent artifact transcript: init-default -# Regenerate with BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden - -=== bd init --quiet --prefix aa ---- files: created $PROJECT/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: created $PROJECT/AGENTS.md -# Agent Instructions - -This project uses **bd** (beads) for issue tracking. Run `bd prime` for full workflow context. - -> **Architecture in one line:** Issues live in a local Dolt database -> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a -> git-compatible protocol), stored under `refs/dolt/data` on your git -> remote — separate from `refs/heads/*` where your code lives. -> `.beads/issues.jsonl` is a passive export, not the wire protocol. -> -> See [sync-concepts](https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md) -> for the one-screen overview and anti-patterns (don't treat JSONL as the -> source of truth; don't `bd import` during normal operation; don't -> reach for third-party Dolt hosting before trying the default). - -## Quick Reference - -```bash -bd ready # Find available work -bd show # View issue details -bd update --claim # Claim work atomically -bd close # Complete work -``` - -## Non-Interactive Shell Commands - -**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts. - -Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input. - -**Use these forms instead:** -```bash -# Force overwrite without prompting -cp -f source dest # NOT: cp source dest -mv -f source dest # NOT: mv source dest -rm -f file # NOT: rm file - -# For recursive operations -rm -rf directory # NOT: rm -r directory -cp -rf source dest # NOT: cp -r source dest -``` - -**Other commands that may prompt:** -- `scp` - use `-o BatchMode=yes` for non-interactive -- `ssh` - use `-o BatchMode=yes` to fail instead of prompting -- `apt-get` - use `-y` flag -- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md] - - - -## Beads Issue Tracker - -Use Beads (`bd`) for durable task tracking in repositories that include it. Use the `beads` skill at `.agents/skills/beads/SKILL.md` (project install) or `~/.agents/skills/beads/SKILL.md` (global install) for Beads workflow guidance, then use the `bd` CLI for issue operations. - -### Quick Reference - -```bash -bd ready # Find available work -bd show # View issue details -bd update --claim # Claim work -bd close # Complete work -bd prime # Refresh Beads context -``` - -### Rules - -- Use `bd` for all task tracking; do not create markdown TODO lists. -- Run `bd prime` when Beads context is missing or stale. Codex 0.129.0+ can load Beads context automatically through native hooks; use `/hooks` to inspect or toggle them. -- Keep durable project facts in Beads via `bd remember` rather than in per-tool memory files, which fragment across accounts; per-operator preferences belong in your harness's own memory. - -**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. - ---- files: created $PROJECT/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md] - - - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -exit: 0 ---- stdout -✓ Project hooks installed: $PROJECT/.claude/settings.json -✓ Claude Code integration installed: $PROJECT/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude -exit: 0 ---- stdout -Installing Claude hooks for this project... -✓ Hook already registered: SessionStart -Installing Claude Code integration... -✓ CLAUDE.md already has the current beads section - -✓ Claude Code integration installed - File: $PROJECT/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $PROJECT/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude --remove -exit: 0 ---- stdout -Removing Claude hooks from project... -✓ Removed SessionStart hook -Removing Claude Code integration... -✓ Removed beads section from CLAUDE.md -✓ Claude hooks removed ---- stderr -(empty) ---- files: modified $PROJECT/.claude/settings.json -{ - "hooks": {} -} ---- files: modified $PROJECT/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - -=== bd setup claude --check -exit: 1 ---- stdout -✗ No hooks installed - Run: bd setup claude ---- stderr -(empty) ---- files: unchanged - -=== bd setup claude -exit: 0 ---- stdout -Installing Claude hooks for this project... -✓ Registered SessionStart hook -Installing Claude Code integration... -✓ Added beads section to existing CLAUDE.md - -✓ Claude Code integration installed - File: $PROJECT/CLAUDE.md -No additional configuration needed! - -✓ Claude Code integration installed - Settings: $PROJECT/.claude/settings.json - -Restart Claude Code for changes to take effect. ---- stderr -(empty) ---- files: modified $PROJECT/.claude/settings.json -{ - "hooks": { - "SessionStart": [ - { - "hooks": [ - { - "command": "bd prime --hook-json", - "type": "command" - } - ], - "matcher": "" - } - ] - } -} ---- files: modified $PROJECT/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## Build & Test - -_Add your build and test commands here_ - -```bash -# Example: -# npm install -# npm test -``` - -## Architecture Overview - -_Add a brief overview of your project architecture_ - -## Conventions & Patterns - -_Add your project-specific conventions here_ - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md] - - -=== bd setup claude --check -exit: 0 ---- stdout -✓ Project hooks installed: $PROJECT/.claude/settings.json -✓ Claude Code integration installed: $PROJECT/CLAUDE.md (current) ---- stderr -(empty) ---- files: unchanged diff --git a/cmd/bd/testdata/command_tree/help/bd.golden b/cmd/bd/testdata/command_tree/help/bd.golden deleted file mode 100644 index 619e70296..000000000 --- a/cmd/bd/testdata/command_tree/help/bd.golden +++ /dev/null @@ -1,163 +0,0 @@ -Issues chained together like beads. A lightweight issue tracker with first-class dependency support. - -Usage: - bd [flags] - bd [command] - -Working With Issues: - assign Assign an issue to someone - children List child beads of a parent - close Close one or more issues - comment Add a comment to an issue - comments View or manage comments on an issue - create Create a new issue (or batch from markdown/graph JSON) - create-form Create a new issue using an interactive form - delete Delete one or more issues and clean up references - edit Edit an issue field in $EDITOR - gate Manage async coordination gates - heartbeat Refresh the lease on an issue you hold in_progress - label Manage issue labels - link Link two issues with a dependency - list List issues - merge-slot Manage merge-slot gates for serialized conflict resolution - note Append a note to an issue - priority Set the priority of an issue - promote Promote a wisp to a permanent bead - provenance Append-only provenance event log - q Quick capture: create issue and output only ID - query Query issues using a simple query language - reclaim Revert stale-lease in_progress issues back to ready (dead-worker recovery) - reopen Reopen one or more closed issues - search Search issues by text query - set-state Set operational state (creates event + updates label) - show Show issue details - state Query the current value of a state dimension - tag Add a label to an issue - todo Manage TODO items (convenience wrapper for task issues) - unclaim Release a claimed issue - update Update one or more issues - -Views & Reports: - count Count issues matching filters - diff Show changes between two commits or branches - find-duplicates Find semantically similar issues using text analysis or AI - history Show version history for an issue - lint Check issues for missing template sections - stale Show stale issues (not updated recently) - status Show issue database overview and statistics - statuses List valid issue statuses - types List valid issue types - versions List the recorded versions of a bead - -Dependencies & Structure: - dep Manage dependencies - duplicate Mark an issue as a duplicate of another - duplicates Find and optionally merge duplicate issues - epic Epic management commands - graph Display issue dependency graph - supersede Mark an issue as superseded by a replacement issue - swarm Swarm management for structured epics - -Sync & Data: - backup Back up your beads database - branch List or create branches - conflicts Inspect and resolve live merge conflicts - export Export issues to JSONL format - federation Manage peer-to-peer federation with other workspaces - import Import issues from a JSONL file or stdin into the database - restore Restore the pre-compaction content of a compacted issue - sync Pull, check for conflicts, repair is_blocked, and push (the federation loop) - vc Version control operations - -Setup & Configuration: - bootstrap Non-destructive database setup for fresh clones and recovery - config Manage configuration settings - connect Attach this workspace to a remote bd serve over HTTP - context Show effective backend identity and repository context - dolt Configure Dolt database settings - forget Remove a persistent memory - hooks Manage git hooks for beads integration - human Show essential commands for human users - info Show database information - init Initialize bd in the current directory - kv Key-value store commands - memories List or search persistent memories - migrate-personal Move personal planning issues from the project database to your planning repo - onboard Display minimal snippet for agent instructions file - prime Output AI-optimized workflow context - quickstart Quick start guide for bd - recall Retrieve a specific memory - remember Store a persistent memory - setup Setup integration with AI editors - where Show active beads location - -Maintenance: - batch Run multiple write operations in a single database transaction - compact Squash old Dolt commits to reduce history size - doctor Check and fix beads installation health (start here) - events Read and manage the durable events journal - flatten Squash all Dolt history into a single commit - gc Garbage collect: decay old issues, compact Dolt commits, run Dolt GC - migrate Database migration commands - ping Check database connectivity - preflight Show PR readiness checklist - prune Delete old closed beads to reclaim space and shrink exports - purge Delete closed ephemeral beads to reclaim space - recompute-blocked Recompute is_blocked for all issues (repairs stale flags after a pull) - rename-prefix Rename the issue prefix for all issues in the database - rules Audit and compact Claude rules - sql Execute raw SQL against the beads database - upgrade Check and manage bd version upgrades - worktree Manage git worktrees for parallel development - -Integrations & Advanced: - admin Administrative commands for database maintenance - jira Jira integration commands - linear Linear integration commands - repo Manage multiple repository configuration - -Additional Commands: - ado Azure DevOps integration commands - audit Record and label agent interactions (append-only JSONL) - blocked Show blocked issues - completion Generate the autocompletion script for the specified shell - cook Compile a formula into a proto (ephemeral by default) - defer Defer one or more issues for later - formula Manage workflow formulas - github GitHub integration commands - gitlab GitLab integration commands - help Help about any command - init-safety Explain bd init flag semantics and the destroy-token format - mail Delegate to mail provider (e.g., gt mail) - metrics Show or change anonymous usage-metrics settings - mol Molecule commands (work templates) - notion Notion integration commands - orphans Identify orphaned issues (referenced in commits but still open) - ready Show ready work (open, no active blockers) - rename Rename an issue ID - schema Print the JSON Schema for bd's --json / export output - serve Serve the beads HTTP API over loopback - ship Publish a capability for cross-project dependencies - undefer Undefer one or more issues (restore to open) - version Print version information - -Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - -h, --help help for bd - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output - -V, --version Print version information - -Use "bd [command] --help" for more information about a command. diff --git a/cmd/bd/testdata/command_tree/help/bd_close.golden b/cmd/bd/testdata/command_tree/help/bd_close.golden deleted file mode 100644 index eefb0db30..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_close.golden +++ /dev/null @@ -1,57 +0,0 @@ -Close one or more issues. - -If no issue ID is provided, closes the last touched issue (from most recent -create, update, show, or close operation). This fallback only applies in -interactive sessions (stdin is a terminal); in scripts and agent sessions a -missing ID is an error, so a command built from an empty variable cannot -silently close an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow -the fallback anywhere, or =0 to disable it entirely. - -When closing multiple issues, provide one --reason for all IDs or repeat ---reason once per ID. Reasons map positionally: the first --reason applies -to the first ID, the second --reason to the second ID, regardless of where -the flags appear in the command line. - -Closing a molecule's last open step also closes the molecule's root, with -the reason "all steps complete", when the root is a poured molecule, a wisp, -or an epic labeled "template"; any other epic stays open as close-eligible -work. A root that would refuse its own close (an open blocker, a pin, another -assignee) stays open with a warning, and the step's close stands. Under ---json, the step's entry names the closed root (auto_closed_molecule) or the -refusal (molecule_auto_close_refusal). --continue claims the next ready step -in the molecule for you; add --no-auto to only show it. - -Usage: - bd close [id...] [flags] - -Aliases: - close, done - -Flags: - --claim-next Automatically claim the next highest priority available issue - --continue Auto-advance to next step in molecule - -f, --force Force close pinned issues or unsatisfied gates - -h, --help help for close - --if-revision bd show --json Apply the write only if the issue's current revision equals this value (the decimal int64 from bd show --json's "revision" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures). - --no-auto With --continue, show next step but don't claim it - -r, --reason string Reason for closing - --reason-file string Read close reason from file (use - for stdin) - --session string Claude Code session ID (or set CLAUDE_SESSION_ID env var) - --suggest-next Show newly unblocked issues after closing - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_config.golden b/cmd/bd/testdata/command_tree/help/bd_config.golden deleted file mode 100644 index a5bed0d60..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_config.golden +++ /dev/null @@ -1,122 +0,0 @@ -Manage configuration settings for external integrations and preferences. - -Configuration is stored per-project in the beads database and is version-control-friendly. - -Common namespaces: - - export.* Auto-export settings (stored in config.yaml) - - import.* JSONL import settings (stored in config.yaml) - - jira.* Jira integration settings - - linear.* Linear integration settings - - github.* GitHub integration settings - - gitlab.* GitLab integration settings - - ado.* Azure DevOps integration settings - - notion.* Notion integration settings - - custom.* Custom integration settings - - status.* Issue status configuration - - claim.* Claim arbitration settings (pool-aware claiming) - - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095) - - lint.* Additional per-type lint sections (stored in config.yaml) - -Auto-Export (config.yaml): - Optional JSONL export to .beads/issues.jsonl after write commands (throttled). - Useful for viewers (bv), interchange, and issue-level migration; not a backup. - It is not cross-machine sync; use bd dolt push/pull with a Dolt remote. - Disabled by default. Enable only for integrations that need fresh JSONL. - Auto-staging is separate and disabled by default. - - Keys: - export.auto Enable/disable auto-export (default: false) - export.path Output filename relative to .beads/ (default: issues.jsonl) - export.interval Minimum time between exports (default: 60s) - export.git-add Auto-stage the export file (default: false) - -Auto-Import (config.yaml): - Reads .beads/issues.jsonl by default when a JSONL import path is implied. - Use a relative filename/path so the import stays within the project .beads/ - directory and remains portable across machines. - - Keys: - import.path Input filename relative to .beads/ (default: issues.jsonl) - -Custom Status States: - You can define custom status states for multi-step pipelines using the - status.custom config key. Statuses should be comma-separated. - - Example: - bd config set status.custom "awaiting_review,awaiting_testing,awaiting_docs" - - This enables issues to use statuses like 'awaiting_review' in addition to - the built-in statuses (open, in_progress, blocked, deferred, closed). - -Claim Pools: - A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g. - "fable-crew") and let any actor take them with --claim. List the pool - aliases in the claim.pools config key, comma-separated: - - bd config set claim.pools "fable-crew,night-crew" - - Issues assigned to a real actor (or to an alias not in the list) keep - their anti-steal protection. Pool takes carry the normal lease; note - that if a taker's lease expires, bd reclaim returns the issue to the - unassigned pool, not to the pool alias it was dispatched to. - -Suppressing Doctor Warnings: - Suppress specific bd doctor warnings by check name slug: - bd config set doctor.suppress.pending-migrations true - bd config set doctor.suppress.git-hooks true - Check names are converted to slugs: "Git Hooks" → "git-hooks". - Only warnings are suppressed (errors and passing checks always show). - To unsuppress: bd config unset doctor.suppress. - -Examples: - bd config set export.auto true # Enable auto-export for viewer integrations - bd config set export.path "beads.jsonl" # Custom export filename - bd config set import.path "beads.jsonl" # Custom import filename - bd config set export.git-add true # Also stage the export file - bd config set jira.url "https://company.atlassian.net" - bd config set jira.project "PROJ" - bd config set status.custom "awaiting_review,awaiting_testing" - bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor - bd config set doctor.suppress.pending-migrations true - bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) - bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init - bd config set lint.sections.epic "Standards scorecard, Cost" # Extra sections bd lint requires for epics - bd config get export.auto - bd config list - bd config unset jira.url - -Usage: - bd config [command] - -Available Commands: - apply Reconcile system state to match configuration - drift Detect config-vs-reality inconsistencies - get Get a configuration value - list List all configuration - set Set a configuration value - set-many Set multiple configuration values in one operation - show Show all effective configuration with provenance - unset Delete a configuration value - validate Validate sync-related configuration - -Flags: - -h, --help help for config - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output - -Use "bd config [command] --help" for more information about a command. diff --git a/cmd/bd/testdata/command_tree/help/bd_create.golden b/cmd/bd/testdata/command_tree/help/bd_create.golden deleted file mode 100644 index adc90d852..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_create.golden +++ /dev/null @@ -1,72 +0,0 @@ -Create a new issue (or batch from markdown/graph JSON) - -Usage: - bd create [title] [flags] - -Aliases: - create, new - -Flags: - --acceptance string Acceptance criteria - --allow-empty-description Allow empty description input from stdin or file - --append-notes string Append to existing notes (with newline separator) - -a, --assignee string Assignee - --body-file string Read description from file (use - for stdin) - --context string Additional context for the issue - --defer string Defer until date (issue hidden from bd ready until then). Same formats as --due - --deps strings 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' - -d, --description string Issue description - --design string Design notes - --design-file string Read design from file (use - for stdin) - --dry-run Preview what would be created without actually creating - --due string Due date/time. Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15 - --ephemeral Create as ephemeral (short-lived, subject to TTL compaction) - -e, --estimate int Time estimate in minutes (e.g., 60 for 1 hour) - --event-actor string Entity URI who caused this event (requires --type=event) - --event-category string Event category (e.g., patrol.muted, agent.started) (requires --type=event) - --event-payload string Event-specific JSON data (requires --type=event) - --event-target string Entity URI or bead ID affected (requires --type=event) - --external-ref string External reference (e.g., 'gh-9', 'jira-ABC', Linear URL) - -f, --file string Create one issue per ## heading (### fields attach to that issue); for title plus description-from-file, use --body-file - --force Force creation even if prefix doesn't match database prefix - --graph string Create a graph of issues with dependencies from JSON plan file - -h, --help help for create - --id string Explicit issue ID (e.g., 'bd-42' for partitioning) - -l, --labels strings Labels (comma-separated) - --metadata string Set custom metadata (JSON object, or @file.json to read from file) - --mol-type string Molecule type: swarm (multi-agent), patrol (recurring ops), work (default) - --no-history Skip Dolt commit history without making GC-eligible (for permanent agent beads) - --no-inherit-labels Don't inherit labels from parent issue - --notes string Notes - --parent string Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9') - -p, --priority string Priority (0-4 or P0-P4, 0=highest) (default "2") - --repo string Target repository for issue (overrides auto-routing) - --silent Output only the issue ID (for scripting) - --skills string Required skills for this issue - --spec-id string Link to specification document - -s, --status string Initial status - --stdin Read description from stdin (alias for --body-file -) - --storage-class string Storage class: versioned, unversioned, or ephemeral (default: storage-class. config, else versioned) - --title string Issue title (alternative to positional argument) - -t, --type string Issue type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision (default "task") - --validate Validate description contains required sections for issue type - --waits-for string Spawner issue ID to wait for (creates waits-for dependency for fanout gate) - --waits-for-gate string Gate type: all-children (wait for all) or any-children (wait for first) (default "all-children") - --wisp-type string Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_list.golden b/cmd/bd/testdata/command_tree/help/bd_list.golden deleted file mode 100644 index d9c582c3a..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_list.golden +++ /dev/null @@ -1,89 +0,0 @@ -List issues - -Usage: - bd list [flags] - -Flags: - --all Show all issues including closed (overrides default filter) - -a, --assignee string Filter by assignee - --brief Omit the free-form text (description, design, acceptance criteria, notes, payload, waiters) from each row. Filters that read those fields, such as --desc-contains, still select on them. An omitted field is indistinguishable from an empty one in --json; fetch a whole issue with bd show. - --closed-after string Filter issues closed after date (YYYY-MM-DD or RFC3339) - --closed-before string Filter issues closed before date (YYYY-MM-DD or RFC3339) - --created-after string Filter issues created after date (YYYY-MM-DD or RFC3339) - --created-before string Filter issues created before date (YYYY-MM-DD or RFC3339) - --defer-after string Filter issues deferred after date (supports relative: +6h, tomorrow) - --defer-before string Filter issues deferred before date (supports relative: +6h, tomorrow) - --deferred Show only issues with defer_until set - --deps string[="scheduling"] Annotate tree with dependency edges and order siblings by them: 'scheduling' (bare --deps) or 'all' - --desc-contains string Filter by description substring (case-insensitive) - --due-after string Filter issues due after date (supports relative: +6h, tomorrow) - --due-before string Filter issues due before date (supports relative: +6h, tomorrow) - --empty-description Filter issues with empty or missing description - --exclude-label strings Exclude issues that have ANY of these labels - --exclude-type strings Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic) - --external-contains string Filter by external ref substring (case-insensitive) - --external-ref string Filter by exact external_ref value - --flat Disable tree format and use legacy flat list output - --format string Export the dependency graph of the listed issues: 'digraph' (edge list for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or a Go template rendered once per edge over .IssueID, .DependsOnID, .Type, .Issue, .Dependency. 'json' is the exception and does not export the graph: it is equivalent to --json, which also wins when both flags are given. 'digraph' and templates print nothing when no listed issue depends on another; 'dot' still prints the nodes - --has-metadata-key string Filter issues that have this metadata key set - -h, --help help for list - --id string Filter by specific issue IDs (comma-separated or repeated, e.g., bd-1,bd-5,bd-10) - --include-comments Populate each row's comments field with full comment bodies in JSON output (--json only; costs one query per row that has comments). Without it, a row with comments carries comments_omitted=true, so an absent comments field is never mistaken for having none. Text output is unaffected either way. - --include-ephemeral Include ephemeral wisp-plane rows in output (normally hidden) - --include-gates Include gate issues in output (normally hidden) - --include-infra Include infrastructure beads (agent/role/message) in output - --include-templates Include template molecules in output - -l, --label strings Filter by labels (AND: must have ALL). Can combine with --label-any - --label-any strings Filter by labels (OR: must have AT LEAST ONE). Can combine with --label - --label-pattern string Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy) - --label-regex string Filter by label regex pattern (e.g., 'tech-(debt|legacy)') - -n, --limit int Limit results (an explicit --limit always wins, 0 meaning unlimited; otherwise --all is unlimited; otherwise a configured list.limit applies; otherwise unlimited when piped, else 20 in agent mode at a terminal, else 50) (default 50) - --long Show detailed multi-line output for each issue - --max-rows int Hard upper bound on rows returned. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Honored on both the direct and the --proxied-server route. - --metadata-field stringArray Filter by metadata field (key=value, repeatable) - --mol-type string Filter by molecule type: swarm, patrol, or work - --no-assignee Filter issues with no assignee - --no-labels Filter issues with no labels - --no-pager Disable pager output - --no-parent Exclude child issues (show only top-level issues) - --no-pinned Exclude pinned issues - --notes-contains string Filter by notes substring (case-insensitive) - --offset int Skip the first N matching results (0-based). Only supported under --proxied-server. - --overdue Show only issues with due_at in the past (not closed) - --parent string Filter by parent issue ID (shows children of specified issue) - --pinned Show only pinned issues - --pretty Display issues in a tree format with status/priority symbols - -p, --priority string Priority (0-4 or P0-P4, 0=highest) - --priority-max string Filter by maximum priority (inclusive, 0-4 or P0-P4) - --priority-min string Filter by minimum priority (inclusive, 0-4 or P0-P4) - --ready Show only ready issues (no active blockers, same semantics as bd ready) - -r, --reverse Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first) - --skip-labels Skip label hydration. The labels field in output will be empty regardless of actual labels. Use only when the caller does not depend on label data. Cannot combine with --label, --label-any, --label-pattern, --label-regex, --exclude-label, or --no-labels. - --sort string Sort by field: priority, created, updated, closed, status, id, title, type, assignee - --spec string Filter by spec_id prefix - -s, --status string Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated or repeated for multiple: --status open,in_progress - --title string Filter by title text (case-insensitive substring match) - --title-contains string Filter by title substring (case-insensitive) - --tree Hierarchical tree format (default: true; use --flat to disable) (default true) - -t, --type string Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate, convoy). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision - --updated-after string Filter issues updated after date (YYYY-MM-DD or RFC3339) - --updated-before string Filter issues updated before date (YYYY-MM-DD or RFC3339) - -w, --watch Watch for changes and auto-update display (implies --pretty) - --wisp-type string Filter by wisp type: heartbeat, ping, patrol, gc_report, recovery, error, escalation - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_serve.golden b/cmd/bd/testdata/command_tree/help/bd_serve.golden deleted file mode 100644 index 848d00820..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_serve.golden +++ /dev/null @@ -1,119 +0,0 @@ -Serve the beads HTTP API — the same work surface the CLI answers, for -automation clients that would otherwise fork a bd subprocess per call. - -The wire contract is described by an OpenAPI document (/v0); GET -/v0/beads/context reports which operations this build actually implements. - -DEPLOYMENT - - Pass an explicit port. The default 127.0.0.1:0 takes an ephemeral one, which - is right for ad-hoc and test use — where the bound address printed on stdout - is read immediately — but carries no mutual exclusion: two serves against one - workspace then run side by side on different ports with no way to enumerate - them. On a fixed port the second one fails to bind, which is the intended - behavior. Concurrent serves are data-safe either way; claims are arbitrated - in the SQL server. - - Run it under a supervisor. bd shuts down gracefully on SIGHUP as well as - SIGINT and SIGTERM, so closing the terminal of a foreground bd serve stops it. - -PROBES - - GET /healthz is LIVENESS only: it answers from the process and never touches - the database, so it stays green while the database is unreachable. For - readiness use GET /v0/beads/ready?limit=1 — a real query, where 200 means - ready and 503 means live but not ready. - -AUTHENTICATION - - Optional, and off by default on loopback — where the trust model is the - loopback boundary itself, the same one the database behind it already relies - on. --auth-token-file turns it on: every operation except GET /healthz then - requires an "Authorization: Bearer " header, GET /v0/beads/context - included, because it reports the repo root, beads directory and database name. - - The file holds ONE TOKEN PER LINE and every line is accepted. That is the - rotation mechanism: write the new token alongside the old, roll the clients - over, then delete the old line. The file is re-read while the server runs, so - both the addition and the removal take effect within about a second and - neither needs a restart. Write it atomically (a temp file plus rename; a - Kubernetes secret mount already does this). - - There is deliberately no --auth-token flag. A credential passed as an - argument is readable by every local user in the process listing. - - --allow-non-loopback REQUIRES a token file. Beyond loopback, reaching the - address would otherwise be the whole authorization: any peer could read every - issue and claim work as any actor. --insecure-no-auth is the explicit, - auditable way to say you meant that anyway. - - The Host allowlist is what a service deployment usually trips over first. The - DNS-rebinding check answers only to loopback spellings and the bind address, - so a client dialing a service name gets 400 on every request; enumerate the - names it dials with --allowed-host (repeatable). Matching is exact — no - wildcards — and the startup log line prints the effective allowlist. - -WHAT THIS DOES NOT DO - - No TLS. Even with a token, the credential and every issue body travel in - plaintext, so a deployment beyond loopback has to supply confidentiality - itself — a service mesh, or a network boundary you already trust. - - Hooks do not fire. A hook is a user-controlled subprocess per mutation: in a - concurrent server that is an unbounded latency multiplier and an orphaned - child at shutdown, and its working-directory-derived hook lookup is - meaningless in a server process. A CLI claim runs on_update; an HTTP claim - does not. - - The per-command auto-commit machinery does not run. Durability is per request: - a successful claim commits inside its own transaction, exactly as a proxied - CLI claim does today. - - An actor on an HTTP request is caller-asserted provenance for the audit trail, - not authenticated identity — the same thing it has always been on the CLI, - where any local process can pass any --actor. - - It does not run under --readonly, and refuses to start rather than binding. - Every server it binds publishes the issue-claim operation, and the capability - set it advertises is a property of the build rather than of the flags on the - process that started it — so a read-only server would advertise a write it - could never land. - -DESTRUCTIVE OPERATIONS - - POST /v0/beads/issues:sweep deletes closed beads in bulk — the operation - behind bd purge and bd prune — and nothing it deletes comes back. It shares - the library surface those commands call, so it inherits their guards: pinned - beads are never swept, and a durable sweep with neither a cutoff nor an id - pattern is refused rather than clearing every closed bead in the workspace. - Combined with the trust model above, that means anyone who can reach this - address can erase closed work; bind it accordingly. - -Usage: - bd serve [flags] - -Flags: - --addr string Address to bind as IP:PORT; the host must be a numeric IP literal, and port 0 takes an ephemeral port (default "127.0.0.1:0") - --allow-non-loopback Permit a bind beyond loopback. Requires --auth-token-file, since reaching the address would otherwise be the whole authorization - --allowed-host stringArray Additional Host header value to answer to, e.g. a service DNS name. Repeatable; matched exactly, with no wildcards - --auth-token-file string Require an Authorization: Bearer token from this file, one token per line, all accepted. Re-read while running, so rewriting it rotates tokens without a restart (env BEADS_SERVE_TOKEN_FILE) - -h, --help help for serve - --insecure-no-auth Serve a non-loopback bind with NO authentication. Every peer that can reach the address gets full read and claim access - --large-apply-ceiling duration Whole-run budget for a POST issues:batchApply request over 100 items (a ceiling, not a target; requests at or under 100 items are unaffected). Must be positive. The orchestrator's stop grace must be at least this long plus 5s, or an external SIGKILL can cut off an in-flight large apply a graceful drain would otherwise have waited out; see engdocs/SERVE_RUNBOOK.md (default 5m0s) - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_show.golden b/cmd/bd/testdata/command_tree/help/bd_show.golden deleted file mode 100644 index 595a7dd74..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_show.golden +++ /dev/null @@ -1,41 +0,0 @@ -Show issue details - -Usage: - bd show [id...] [--id=...] [--current] [flags] - -Aliases: - show, view - -Flags: - --as-of string Show issue as it existed at a specific commit hash or branch (requires Dolt; commit hashes must be the full 32-character hash from 'bd history', not a prefix) - --brief-deps Reduce each dependency to its identity fields in JSON output (--json only; drops description, design, notes and acceptance criteria) - --children Show only the children of this issue - --comments-tail int Render only the last N comments in text output, preceded by one elision line naming how many older ones were hidden (text output only; 0, the default, renders every comment unchanged; N must be >= 0) - --current Show the currently active issue (in-progress, hooked, or last touched) - -h, --help help for show - --id stringArray Issue ID (use for IDs that look like flags, e.g., --id=gt--xyz) - --include-comments Stream full comment bodies in JSON output (--json only; may be slow on issues with many comments). Without it the comments field is absent entirely, not truncated: an issue with comments carries comment_count and comments_omitted=true, so check those before reading an absent comments field as none. - --include-dependents Stream full dependent issues in JSON output (--json only; may be slow on hub beads) - --local-time Show timestamps in local time instead of UTC (date-only fields are always local) - --long Show all available fields (extended metadata, agent identity, gate fields, etc.) - --refs Show issues that reference this issue (reverse lookup) - --short Show compact one-line output per issue - --thread Show full conversation thread (for messages) - -w, --watch Watch for changes and auto-refresh display - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_update.golden b/cmd/bd/testdata/command_tree/help/bd_update.golden deleted file mode 100644 index 37451cdc6..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_update.golden +++ /dev/null @@ -1,78 +0,0 @@ -Update one or more issues. - -If no issue ID is provided, updates the last touched issue (from most recent -create, update, show, or close operation). This fallback only applies in -interactive sessions (stdin is a terminal); in scripts and agent sessions a -missing ID is an error, so a command built from an empty variable cannot -silently mutate an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow -the fallback anywhere, or =0 to disable it entirely. - -Updates are applied per issue ID, not atomically across IDs: when some IDs -fail, the remaining issues are still updated, every failed ID is reported on -stderr, and the command exits nonzero. - -Exit codes: 1 for general failures; 13 when every failure is a stale ---if-assignee/--if-status guard (the precondition no longer held, nothing was -written — another actor won the race, so retrying the same guard is -pointless). - -Usage: - bd update [id...] [flags] - -Flags: - --acceptance string Acceptance criteria - -l, --add-label strings Add labels (repeatable); -l matches bd create -l - --allow-empty-description Allow empty description replacement when reading from stdin or file - --append-notes string Append to existing notes (with newline separator) - -a, --assignee string Assignee - --await-id string Set gate await_id (e.g., GitHub run ID for gh:run gates) - --body-file string Read description from file (use - for stdin) - --claim Atomically claim the issue (sets assignee to you, status to in_progress; idempotent if already claimed by you; issues assigned to a pool alias listed in the claim.pools config are claimable too) - --clear-notes Clear the notes field (--notes "" is refused: an empty value is usually a dead command substitution) - --defer string Defer until date (empty to clear). Issue hidden from bd ready until then, then auto-wakes to open - -d, --description string Issue description - --design string Design notes - --design-file string Read design from file (use - for stdin) - --due string Due date/time (empty to clear). Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15 - --ephemeral Mark issue as ephemeral (wisp) - not exported to JSONL - -e, --estimate int Time estimate in minutes (e.g., 60 for 1 hour) - --external-ref string External reference (e.g., 'gh-9', 'jira-ABC', Linear URL) - --force Override refusals: let -a/--assignee overwrite another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim), let -s/--status move the issue into closed (or a configured done status) despite open children or a live blocker (same as bd close --force), and let --notes overwrite existing non-empty notes (use --append-notes to preserve history instead) - -h, --help help for update - --history Clear no-history flag (re-enable Dolt commit history) - --if-assignee string Apply the update only if the current assignee equals this value (--if-assignee '' requires unassigned); a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim - --if-revision bd show --json Apply the write only if the issue's current revision equals this value (the decimal int64 from bd show --json's "revision" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures). Composes with --if-assignee/--if-status: all guards present must hold. - --if-status string Apply the update only if the current status equals this value; a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim - --metadata string Set custom metadata (JSON object, or @file.json to read from file) - --no-history Mark issue as no-history (skip Dolt commits, not GC-eligible) - --notes string Replace the notes field (requires --force over existing non-empty notes; --clear-notes clears; --append-notes appends instead) - --parent string New parent issue ID (reparents the issue, use empty string to remove parent) - --persistent Mark issue as persistent (promote wisp to regular issue) - -p, --priority string Priority (0-4 or P0-P4, 0=highest) - --remove-label strings Remove labels (repeatable) - --session string Claude Code session ID for status=closed (or set CLAUDE_SESSION_ID env var) - --set-labels strings Set labels, replacing all existing (repeatable) - --set-metadata stringArray Set metadata key=value (repeatable, e.g., --set-metadata team=platform) - --spec-id string Link to specification document - -s, --status string New status - --stdin Read description from stdin (alias for --body-file -) - --title string New title - -t, --type string New type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision - --unset-metadata stringArray Remove metadata key (repeatable, e.g., --unset-metadata team) - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_version.golden b/cmd/bd/testdata/command_tree/help/bd_version.golden deleted file mode 100644 index cb5978ad7..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_version.golden +++ /dev/null @@ -1,24 +0,0 @@ -Print version information - -Usage: - bd version [flags] - -Flags: - -h, --help help for version - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/help/bd_versions.golden b/cmd/bd/testdata/command_tree/help/bd_versions.golden deleted file mode 100644 index 54d21dac5..000000000 --- a/cmd/bd/testdata/command_tree/help/bd_versions.golden +++ /dev/null @@ -1,60 +0,0 @@ -List the versions recorded for a bead by versioned history. - -Recording is off by default. Turn it on with: - - bd config set versioned-history.enabled true - -That writes the setting into the store, so every client of that store agrees -about whether a write is recorded, and it is the setting this command reports. -BD_VERSIONED_HISTORY_ENABLED=1 (or a value in config.yaml) also turns recording -on for the writes a process makes, but it says nothing about the store, and -this command only reads, so it does not consult them. - -Either source turning it on is enough for a writer; neither can switch the -other off. The consequence worth knowing: once the store setting says on, -BD_VERSIONED_HISTORY_ENABLED=0 will not turn recording off for one run. Turn -it off where it was turned on: - - bd config set versioned-history.enabled false - -Only beads created while recording is on, or that enter the issues plane -while it is on (a wisp promoted or made persistent), are versioned. A bead -already on the issues plane when recording was turned on is legacy: editing -it records nothing (the write fence, design §16.2b), and nothing is -backfilled. - -Turning recording off does not hide what was already recorded — this command -still lists it, and says that recording is currently off. - -A caution while the feature is young: keep recording ON for every writer of a -shared store, or leave it off for all of them. A write from a client with -recording off advances nothing, and the next recorded write mints a version -that absorbs that unrecorded change under its own actor — the revisions stay -contiguous and the listing looks gapless when it is not. - -Examples: - bd versions bd-123 - bd versions bd-123 --json - -Usage: - bd versions [flags] - -Flags: - -h, --help help for versions - -Global Flags: - --actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER) - --cpu-profile Generate CPU profile for performance analysis - --database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only) - --db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database) - -C, --directory string Change to this directory before running the command (like git -C) - --dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit - --global Use the global shared-server database (beads_global) - --ignore-schema-skew Proceed despite forward schema drift (some queries may fail) - --json Output in JSON format - --mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE) - --no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0) - -q, --quiet Suppress non-essential output (errors only) - --readonly Read-only mode: block write operations (for worker sandboxes) - --sandbox Sandbox mode: disables Dolt auto-push - -v, --verbose Enable verbose/debug output diff --git a/cmd/bd/testdata/command_tree/tree.golden b/cmd/bd/testdata/command_tree/tree.golden deleted file mode 100644 index 79d89ce5e..000000000 --- a/cmd/bd/testdata/command_tree/tree.golden +++ /dev/null @@ -1,7461 +0,0 @@ -# bd command tree (cgo build), pinned by TestCommandTreeGolden. -# Regenerate after an intentional CLI change: -# BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$' - -bd - use: "bd" - short: "bd - Dependency-aware issue tracker" - hidden: false - runnable: true - long: - | Issues chained together like beads. A lightweight issue tracker with first-class dependency support. - persistent-flag --actor type=string default="" usage="Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)" - persistent-flag --cpu-profile type=bool default="false" usage="Generate CPU profile for performance analysis" - persistent-flag --database type=string default="" usage="Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)" - persistent-flag --db type=string default="" usage="Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)" - persistent-flag --directory -C type=string default="" usage="Change to this directory before running the command (like git -C)" - persistent-flag --dolt-auto-commit type=string default="" usage="Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit" - persistent-flag --format type=string default="" hidden usage="Output format (json). Alias for --json" - persistent-flag --global type=bool default="false" usage="Use the global shared-server database (beads_global)" - persistent-flag --ignore-schema-skew type=bool default="false" usage="Proceed despite forward schema drift (some queries may fail)" - persistent-flag --json type=bool default="false" usage="Output in JSON format" - persistent-flag --mem-profile type=string default="" usage="Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)" - persistent-flag --no-color type=bool default="false" usage="Disable color output (also: NO_COLOR=1 or CLICOLOR=0)" - persistent-flag --quiet -q type=bool default="false" usage="Suppress non-essential output (errors only)" - persistent-flag --readonly type=bool default="false" usage="Read-only mode: block write operations (for worker sandboxes)" - persistent-flag --sandbox type=bool default="false" usage="Sandbox mode: disables Dolt auto-push" - persistent-flag --verbose -v type=bool default="false" usage="Enable verbose/debug output" - flag --version -V type=bool default="false" usage="Print version information" - -bd admin - use: "admin" - short: "Administrative commands for database maintenance" - group: "advanced" - hidden: false - runnable: false - long: - | Administrative commands for beads database maintenance. - | - | These commands are for advanced users and should be used carefully: - | cleanup Delete closed issues (issue lifecycle) - | compact Compact old closed issues to save space (storage optimization) - | reset Remove all beads data and configuration (full reset) - | - | For routine maintenance, prefer 'bd doctor --fix' which handles common repairs - | automatically. Use these admin commands for targeted database operations. - -bd admin cleanup - use: "cleanup" - short: "Delete closed issues to reduce database size" - hidden: false - runnable: true - long: - | Delete closed issues to reduce database size. - | - | This command permanently removes closed issues from the database. - | - | NOTE: This command only manages issue lifecycle (closed -> deleted). For general - | health checks and automatic repairs, use 'bd doctor --fix' instead. - | - | By default, deletes ALL closed issues. Use --older-than to only delete - | issues closed before a certain date. - | - | EXAMPLES: - | bd admin cleanup --force # Delete all closed issues - | bd admin cleanup --older-than 30 --force # Only issues closed 30+ days ago - | bd admin cleanup --ephemeral --force # Only closed wisps (transient molecules) - | bd admin cleanup --dry-run # Preview what would be deleted - | - | SAFETY: - | - Requires --force flag to actually delete (unless --dry-run) - | - Supports --cascade to delete dependents - | - Shows preview of what will be deleted - | - Use --json for programmatic output - | - | SEE ALSO: - | bd doctor --fix Automatic health checks and repairs (recommended for routine maintenance) - | bd admin compact Compact old closed issues to save space - flag --cascade type=bool default="false" usage="Recursively delete all dependent issues" - flag --dry-run type=bool default="false" usage="Preview what would be deleted without making changes" - flag --ephemeral type=bool default="false" usage="Only delete closed wisps (transient molecules)" - flag --force -f type=bool default="false" usage="Actually delete (without this flag, shows error)" - flag --older-than type=int default="0" usage="Only delete issues closed more than N days ago (0 = all closed issues)" - -bd admin compact - use: "compact" - short: "Compact old closed issues to save space" - hidden: false - runnable: true - long: - | Compact old closed issues using semantic summarization. - | - | Compaction reduces database size by summarizing closed issues that are no longer - | actively referenced. This is permanent graceful decay - original content is discarded. - | - | Modes: - | - Analyze: Export candidates for agent review (no API key needed) - | - Apply: Accept agent-provided summary (no API key needed) - | - Auto: AI-powered compaction (requires ANTHROPIC_API_KEY, MINIMAX_API_KEY, or ai.api_key) - | - Dolt: Run Dolt garbage collection (for Dolt-backend repositories) - | - | Tiers: - | - Tier 1: Semantic compression (30 days closed, 70% reduction) - | - Tier 2: Ultra compression (90 days closed) - planned, not yet implemented - | - | Dolt Garbage Collection: - | With auto-commit per mutation, Dolt commit history grows over time. Use - | --dolt to run Dolt garbage collection and reclaim disk space. - | - | --dolt: Run Dolt GC on the active database to free disk space. - | This removes unreachable commits and compacts storage. - | - | Examples: - | # Dolt garbage collection - | bd compact --dolt # Run Dolt GC - | bd compact --dolt --dry-run # Preview without running GC - | - | # Agent-driven workflow (recommended) - | bd compact --analyze --json # Get candidates with full content - | bd compact --apply --id bd-42 --summary summary.txt - | bd compact --apply --id bd-42 --summary - < summary.txt - | - | # AI-powered workflow - | bd compact --auto --dry-run # Preview candidates - | bd compact --auto --all # Compact all eligible issues - | bd compact --auto --id bd-42 # Compact specific issue - | MINIMAX_API_KEY=... bd compact --auto --all - | - | # Statistics - | bd compact --stats # Show statistics - | - flag --actor type=string default="agent" usage="Actor name for audit trail" - flag --all type=bool default="false" usage="Process all candidates" - flag --analyze type=bool default="false" usage="Analyze mode: export candidates for agent review" - flag --apply type=bool default="false" usage="Apply mode: accept agent-provided summary" - flag --auto type=bool default="false" usage="Auto mode: AI-powered compaction" - flag --batch-size type=int default="10" usage="Issues per batch" - flag --dolt type=bool default="false" usage="Dolt mode: run Dolt garbage collection on the active database" - flag --dry-run type=bool default="false" usage="Preview without compacting" - flag --force type=bool default="false" usage="Force compact (bypass checks, requires --id)" - flag --id type=string default="" usage="Compact specific issue" - flag --limit type=int default="0" usage="Limit number of candidates (0 = no limit)" - flag --stats type=bool default="false" usage="Show compaction statistics" - flag --summary type=string default="" usage="Path to summary file (use '-' for stdin)" - flag --tier type=int default="1" usage="Compaction tier (only tier 1 is implemented)" - flag --workers type=int default="5" usage="Parallel workers" - -bd admin reset - use: "reset" - short: "Remove all beads data and configuration" - hidden: false - runnable: true - long: - | Reset beads to an uninitialized state, removing all local data. - | - | This command removes: - | - The .beads directory (database, JSONL, config) - | - Git hooks installed by bd - | - Sync branch worktrees - | - | By default, shows what would be deleted (dry-run mode). - | Use --force to actually perform the reset. - | - | Examples: - | bd reset # Show what would be deleted - | bd reset --force # Actually delete everything - flag --force type=bool default="false" usage="Actually perform the reset (required)" - -bd ado - use: "ado" - short: "Azure DevOps integration commands" - hidden: false - runnable: false - long: - | Commands for syncing issues between beads and Azure DevOps. - | - | Configuration can be set via 'bd config' or environment variables: - | ado.org / AZURE_DEVOPS_ORG - Organization name - | ado.project / AZURE_DEVOPS_PROJECT - Project name (single) - | ado.projects / AZURE_DEVOPS_PROJECTS - Project names (comma-separated) - | ado.pat / AZURE_DEVOPS_PAT - Personal access token - | ado.url / AZURE_DEVOPS_URL - Custom base URL (on-prem) - -bd ado projects - use: "projects" - short: "List accessible Azure DevOps projects" - hidden: false - runnable: true - long: - | List Azure DevOps projects that the configured token has access to. - -bd ado pull - use: "pull [refs...]" - short: "Pull specific items from Azure DevOps" - hidden: false - runnable: true - long: - | Pull one or more items from Azure DevOps. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd ado sync --pull-only --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - -bd ado push - use: "push [bead-ids...]" - short: "Push specific beads to Azure DevOps" - hidden: false - runnable: true - long: - | Push one or more beads issues to Azure DevOps. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd ado sync --push-only --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd ado status - use: "status" - short: "Show Azure DevOps sync status" - hidden: false - runnable: true - long: - | Display current Azure DevOps configuration and sync status. - -bd ado sync - use: "sync" - short: "Sync issues with Azure DevOps" - hidden: false - runnable: true - long: - | Synchronize issues between beads and Azure DevOps. - | - | By default, performs bidirectional sync: - | - Pulls new/updated work items from Azure DevOps to beads - | - Pushes local beads issues to Azure DevOps - | - | Use --pull-only or --push-only to limit direction. - | - | Filters (--area-path, --iteration-path, --types, --states) restrict - | which work items are synced. On pull, they limit the WIQL query. On push, - | --types and --states filter local beads before pushing to ADO. Use - | --no-create with push to skip creating new ADO work items (only update - | existing linked items). Filters can also be persisted via config: - | ado.filter.area_path, ado.filter.iteration_path, - | ado.filter.types, ado.filter.states - | CLI flags override config values when both are set. - flag --area-path type=string default="" usage="Filter to ADO area path (e.g., \"Project\\Team\")" - flag --bootstrap-match type=bool default="false" usage="Enable heuristic matching for first sync" - flag --dry-run type=bool default="false" usage="Show what would be synced without making changes" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --iteration-path type=string default="" usage="Filter to ADO iteration path (e.g., \"Project\\Sprint 1\")" - flag --no-create type=bool default="false" usage="Never create new items in either direction (pull or push)" - flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." - flag --prefer-ado type=bool default="false" usage="On conflict, use Azure DevOps version" - flag --prefer-local type=bool default="false" usage="On conflict, keep local beads version" - flag --prefer-newer type=bool default="false" usage="On conflict, use most recent version (default)" - flag --project type=stringSlice default="[]" usage="Project name(s) to sync (overrides configured project/projects)" - flag --pull-only type=bool default="false" usage="Only pull issues from Azure DevOps" - flag --push-only type=bool default="false" usage="Only push issues to Azure DevOps" - flag --reconcile type=bool default="false" usage="Force reconciliation scan for deleted items" - flag --states type=string default="" usage="Filter to ADO states, comma-separated (e.g., \"New,Active,Resolved\")" - flag --types type=string default="" usage="Filter to work item types, comma-separated (e.g., \"Bug,Task,User Story\")" - -bd assign - use: "assign " - short: "Assign an issue to someone" - group: "issues" - hidden: false - runnable: true - long: - | Assign an issue to someone. - | - | Shorthand for 'bd update --assignee '. - | - | Refuses to overwrite another actor's live in_progress claim without --force - | (bd-98s5c); issues assigned to a claim.pools alias are exempt, matching - | --claim. For a holder-aware transfer prefer - | 'bd update --if-assignee -a '. - | - | Examples: - | bd assign bd-123 alice - | bd assign bd-123 "" # unassign - flag --force type=bool default="false" usage="Allow overwriting another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim)" - flag --if-revision type=string default="" usage="Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)." - -bd audit - use: "audit" - short: "Record and label agent interactions (append-only JSONL)" - hidden: false - runnable: false - long: - | Record explicit agent/tool interaction audit entries in .beads/interactions.jsonl. - | - | This optional JSONL sidecar is disabled by default. Enable it with: - | - | bd config set audit.enabled true - | - | Issue history is always recorded in the database and is visible with - | bd history --events. The JSONL sidecar is for explicit interaction capture: - | - auditing ("why did the agent do that?") - | - dataset generation (SFT/RL fine-tuning) - | - | Entries are append-only. Labeling creates a new "label" entry that references a parent entry. - -bd audit label - use: "label " - short: "Append a label entry referencing an existing interaction" - hidden: false - runnable: true - flag --label type=string default="" usage="Label value (e.g. \"good\" or \"bad\")" - flag --reason type=string default="" usage="Reason for label" - -bd audit record - use: "record" - short: "Append an audit interaction entry" - hidden: false - runnable: true - flag --error type=string default="" usage="Error string (llm_call/tool_call)" - flag --exit-code type=int default="-1" usage="Exit code (tool_call)" - flag --issue-id type=string default="" usage="Related issue id (bd-...)" - flag --kind type=string default="" usage="Entry kind (e.g. llm_call, tool_call, label)" - flag --model type=string default="" usage="Model name (llm_call)" - flag --prompt type=string default="" usage="Prompt text (llm_call)" - flag --response type=string default="" usage="Response text (llm_call)" - flag --stdin type=bool default="false" usage="Read a JSON object from stdin (must match audit.Entry schema)" - flag --tool-name type=string default="" usage="Tool name (tool_call)" - -bd backup - use: "backup" - short: "Back up your beads database" - group: "sync" - hidden: false - runnable: false - long: - | Back up your beads database for off-machine recovery. - | - | This is a Dolt-native database backup. It preserves the database state, - | including tables, branches, commit history, and working-set data. This is - | different from 'bd export', which writes issue records to JSONL for migration - | and interoperability. - | - | Commands: - | bd backup init Set up a backup destination (filesystem or DoltHub) - | bd backup sync Push to configured backup destination - | bd backup restore [path] Restore from a backup directory - | bd backup remove Remove backup destination - | bd backup status Show backup status - | - | DoltHub is recommended for cloud backup: - | bd backup init https://doltremoteapi.dolthub.com// - | Set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD for authentication. - | - | Auto-backup default: - | When backup.enabled is unset, auto-backup turns ON in embedded mode if a - | git remote exists, and stays OFF in sql-server / shared-server mode. In - | server mode many bd clients share one Dolt server, and each would register - | a server-side backup remote under the same name pointing at its own local - | dir and full-sync the whole database — a self-amplifying storm. To back up - | a shared server, run 'bd backup' explicitly (or set backup.enabled=true and - | coordinate destinations). 'bd config get backup.enabled' shows the effective - | value and its source. - | - | A proxied-server workspace is server mode too: auto-backup is OFF by - | default and backup.enabled=true opts in. Both the opt-in and the five - | backup verbs above are honored only on a managed-local proxied server — - | one bd started itself; on a Dolt server bd does not own they are refused. - -bd backup init - use: "init " - aliases: ["add"] - short: "Set up a Dolt backup destination" - hidden: false - runnable: true - long: - | Configure a filesystem path or URL as a backup destination. - | - | The path can be a local directory (external drive, NAS, Dropbox folder) or a - | DoltHub remote URL. If the destination was previously configured, it is - | updated to the new path. - | - | Filesystem examples: - | bd backup add /mnt/usb/beads-backup - | bd backup add ~/Dropbox/beads-backup - | - | DoltHub (recommended for cloud backup): - | bd backup add https://doltremoteapi.dolthub.com/myuser/beads-backup - | - | After adding, run 'bd backup sync' to push your data. - -bd backup remove - use: "remove" - aliases: ["rm"] - short: "Remove the configured backup destination" - hidden: false - runnable: true - long: - | Remove the configured backup destination. - | - | This unregisters the backup remote from Dolt and removes the local - | backup configuration. The backup data at the destination is not deleted. - -bd backup restore - use: "restore [path]" - short: "Restore database from a Dolt backup" - hidden: false - runnable: true - long: - | Restore the beads database from a Dolt-native backup. - | - | By default, reads from .beads/backup/ (or the configured backup directory). - | Optionally specify a path to a directory containing a Dolt backup. - | - | This restores a full database backup created by 'bd backup sync' or an - | equivalent Dolt backup. JSONL files produced by 'bd export' are issue exports, - | not restore targets for this command. - | - | Use --force to overwrite an existing database with the backup contents. - | - | The database must already be initialized (run 'bd init' first if needed). - | To initialize and restore in one step, use: bd init && bd backup restore - flag --force type=bool default="false" usage="Overwrite existing database with backup contents" - -bd backup status - use: "status" - short: "Show last backup status" - hidden: false - runnable: true - -bd backup sync - use: "sync" - short: "Push database to configured Dolt backup" - hidden: false - runnable: true - long: - | Sync the current beads database to the configured Dolt backup destination. - | - | This pushes the entire database state (all branches, full history) to the - | backup location configured with 'bd backup init'. - | - | The backup is atomic — if the sync fails, the previous backup state is preserved. - | - | Run 'bd backup init ' first to configure a destination. - -bd batch - use: "batch" - short: "Run multiple write operations in a single database transaction" - group: "maint" - hidden: false - runnable: true - long: - | Run multiple write operations in a single database transaction. - | - | Commands are read from stdin (one per line) or from a file via -f/--file. - | All operations execute inside a single dolt transaction: on any error the - | whole batch is rolled back, otherwise it is committed with one DOLT_COMMIT. - | - | This is intended for shell scripts that currently invoke 'bd' many times in - | a loop, which causes severe write amplification on a dolt sql-server backed - | by btrfs+compression. Batching collapses N invocations into one transaction - | and one dolt commit. - | - | Grammar (one command per line): - | close [reason...] - | update = [= ...] - | create - | dep add [type] - | dep remove - | #comment (blank lines and '# ...' comments are ignored) - | - | Supported 'update' keys: status, priority, title, assignee, force - | Supported dependency types: see 'bd dep add --help' (default: blocks) - | - | 'force' is not a field. An update whose status moves the issue into closed - | (or a configured done status) is refused when it still has open children or - | a live blocker, the same as 'bd close'; 'force=true' overrides that refusal. - | Because the batch is one transaction, an unforced refusal rolls back EVERY - | operation in the batch, not just the offending line. Note the asymmetry with - | 'close ', which does not apply that policy at all. - | - | Tokens are whitespace-separated. Double-quoted strings ("like this") may - | contain spaces; use \" to embed a quote and \\ for a backslash. - | - | Examples: - | # From a pipe - | bd list --status stale -q | awk '{print "close",$1," stale"}' | bd batch - | - | # From a file - | bd batch -f operations.txt - | - | # Inline - | printf 'close bd-1 done\nupdate bd-2 status=in_progress\n' | bd batch - | - | On success, exits 0 and prints a summary (or JSON with --json). On any error, - | rolls back the entire transaction and exits non-zero with the failing line. - | - | NOTE: This is a narrow subset. Commands like 'show', 'list', 'ready', 'sync', - | complex create flows, or any flag not listed above are NOT accepted. Use - | normal 'bd' subcommands for interactive/read operations. - flag --dry-run type=bool default="false" usage="Parse input and echo commands without executing" - flag --file -f type=string default="" usage="Read commands from file instead of stdin" - flag --message -m type=string default="" usage="DOLT_COMMIT message (default: 'bd: batch N ops by ')" - -bd blocked - use: "blocked" - short: "Show blocked issues" - hidden: false - runnable: true - flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" - flag --flags type=bool default="false" usage="Print the blocked flag for each id read from stdin (one per line) instead of the listing; with --json, [{\"id\",\"is_blocked\"}]" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" - flag --parent type=string default="" usage="Filter to descendants of this bead/epic" - flag --raw type=bool default="false" usage="With --flags: the stored blocked column itself, without the external-dependency policy (an unsatisfied external: blocker does not set it)" - -bd bootstrap - use: "bootstrap" - short: "Non-destructive database setup for fresh clones and recovery" - group: "setup" - hidden: false - runnable: true - long: - | Bootstrap sets up the beads database without destroying existing data. - | Unlike 'bd init --force', bootstrap will never delete existing issues. - | - | Bootstrap auto-detects the right action: - | • If sync.remote is configured: clones from the remote - | • If git origin has Dolt data (refs/dolt/data): clones from git and wires origin for future push/pull - | • If .beads/backup/*.jsonl exists: restores from backup - | • If .beads/issues.jsonl exists: imports from git-tracked JSONL - | • If no database exists: creates a fresh one — unless the workspace was already - | initialized (metadata.json has a project_id) and its server-mode database is - | missing, in which case bootstrap refuses rather than strand the existing data - | • If database already exists: validates and reports status - | - | If sync.remote points at a git repository, bootstrap verifies refs/dolt/data - | before cloning. Bootstrap exits non-zero when it cannot set up a database. - | - | This is the recommended command for: - | • Setting up beads on a fresh clone - | • Recovering after moving to a new machine - | • Repairing a broken database configuration - | - | Non-interactive mode (--non-interactive, --yes/-y, or BD_NON_INTERACTIVE=1): - | Skips the confirmation prompt before executing the bootstrap plan. - | Also auto-detected when stdin is not a terminal or CI=true is set. - | - | Examples: - | bd bootstrap # Auto-detect and set up - | bd bootstrap --dry-run # Show what would be done - | bd bootstrap --json # Output plan as JSON - | bd bootstrap --yes # Skip confirmation prompt - | - flag --dry-run type=bool default="false" usage="Show what would be done without doing it" - flag --non-interactive type=bool default="false" usage="Alias for --yes" - flag --yes -y type=bool default="false" usage="Skip confirmation prompts (for CI/automation)" - -bd branch - use: "branch [name]" - short: "List or create branches" - group: "sync" - hidden: false - runnable: true - long: - | List all branches or create a new branch. - | - | This command requires the Dolt storage backend. Without arguments, - | it lists all branches. With an argument, it creates a new branch. - | - | Examples: - | bd branch # List all branches - | bd branch feature-xyz # Create a new branch named feature-xyz - -bd children - use: "children " - short: "List child beads of a parent" - group: "issues" - hidden: false - runnable: true - long: - | List all beads that are children of the specified parent bead. - | - | This is a convenience alias for 'bd list --parent --status all'. - | Unlike plain 'bd list', children includes closed issues by default, - | since the primary use case is inspecting all work under a parent. - | - | Examples: - | bd children hq-abc123 # List all children of hq-abc123 - | bd children hq-abc123 --json # List children in JSON format - | bd children hq-abc123 --pretty # Show children in tree format - flag --pretty type=bool default="false" usage="Show children in tree format" - -bd close - use: "close [id...]" - aliases: ["done"] - short: "Close one or more issues" - group: "issues" - hidden: false - runnable: true - long: - | Close one or more issues. - | - | If no issue ID is provided, closes the last touched issue (from most recent - | create, update, show, or close operation). This fallback only applies in - | interactive sessions (stdin is a terminal); in scripts and agent sessions a - | missing ID is an error, so a command built from an empty variable cannot - | silently close an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow - | the fallback anywhere, or =0 to disable it entirely. - | - | When closing multiple issues, provide one --reason for all IDs or repeat - | --reason once per ID. Reasons map positionally: the first --reason applies - | to the first ID, the second --reason to the second ID, regardless of where - | the flags appear in the command line. - | - | Closing a molecule's last open step also closes the molecule's root, with - | the reason "all steps complete", when the root is a poured molecule, a wisp, - | or an epic labeled "template"; any other epic stays open as close-eligible - | work. A root that would refuse its own close (an open blocker, a pin, another - | assignee) stays open with a warning, and the step's close stands. Under - | --json, the step's entry names the closed root (auto_closed_molecule) or the - | refusal (molecule_auto_close_refusal). --continue claims the next ready step - | in the molecule for you; add --no-auto to only show it. - flag --claim-next type=bool default="false" usage="Automatically claim the next highest priority available issue" - flag --comment type=string default="" hidden usage="Alias for --reason" - flag --continue type=bool default="false" usage="Auto-advance to next step in molecule" - flag --force -f type=bool default="false" usage="Force close pinned issues or unsatisfied gates" - flag --if-revision type=string default="" usage="Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)." - flag --message -m type=string default="" hidden usage="Alias for --reason (git commit convention)" - flag --no-auto type=bool default="false" usage="With --continue, show next step but don't claim it" - flag --reason -r type=string default="" usage="Reason for closing" - flag --reason-file type=string default="" usage="Read close reason from file (use - for stdin)" - flag --resolution type=string default="" hidden usage="Alias for --reason (Jira CLI convention)" - flag --session type=string default="" usage="Claude Code session ID (or set CLAUDE_SESSION_ID env var)" - flag --suggest-next type=bool default="false" usage="Show newly unblocked issues after closing" - -bd codex-hook - use: "codex-hook " - short: "Run an internal Codex lifecycle hook" - hidden: true - runnable: true - -bd comment - use: "comment [text...]" - short: "Add a comment to an issue" - group: "issues" - hidden: false - runnable: true - long: - | Add a comment to an issue. - | - | Shorthand for 'bd comments add "text"'. - | - | Examples: - | bd comment bd-123 "Working on this now" - | bd comment bd-123 Working on this now - | echo "comment from pipe" | bd comment bd-123 --stdin - | bd comment bd-123 --file notes.txt - | - | Note: "comment" (singular) only adds a comment — it has no "list" subcommand. - | To list comments on an issue, use the plural form: bd comments - flag --file type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read comment text from file" - flag --stdin type=bool default="false" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read comment text from stdin" - -bd comments - use: "comments [issue-id]" - short: "View or manage comments on an issue" - group: "issues" - hidden: false - runnable: true - long: - | View or manage comments on an issue. - | - | Examples: - | # List all comments on an issue (issue id is required — there is no "comments list") - | bd comments bd-123 - | - | # List comments in JSON format - | bd comments bd-123 --json - | - | # Add a comment - | bd comments add bd-123 "This is a comment" - | - | # Add a comment from a file - | bd comments add bd-123 -f notes.txt - flag --local-time type=bool default="false" usage="Show timestamps in local time instead of UTC" - -bd comments add - use: "add [issue-id] [text...]" - short: "Add a comment to an issue" - hidden: false - runnable: true - long: - | Add a comment to an issue. - | - | Examples: - | # Add a comment - | bd comments add bd-123 "Working on this now" - | - | # Add a comment from a file - | bd comments add bd-123 -f notes.txt - flag --author -a type=string default="" usage="Add author to comment" - flag --file -f type=string default="" usage="Read comment text from file" - -bd comments list - use: "list" - short: "Invalid — use bd comments to list comments" - hidden: false - runnable: true - -bd compact - use: "compact" - short: "Squash old Dolt commits to reduce history size" - group: "maint" - hidden: false - runnable: true - long: - | Squash Dolt commits older than N days into a single commit. - | - | Recent commits (within the retention window) are preserved via cherry-pick. - | This reduces Dolt storage overhead from auto-commit history while keeping - | recent change tracking intact. - | - | For semantic issue compaction (summarizing closed issues), use 'bd admin compact'. - | For full history squash, use 'bd flatten'. - | - | How it works: - | 1. Identifies commits older than --days threshold - | 2. Creates a squashed base commit from all old history - | 3. Cherry-picks recent commits on top - | 4. Swaps main branch to the compacted version - | 5. Prunes remote-tracking refs (they would keep the old history alive; - | the next push or fetch re-creates them at the new tip) - | 6. Runs a full Dolt GC (all storage generations) to reclaim the old history - | - | The GC pass is a full collection: Dolt storage is generational, and a default - | GC never revisits data an earlier GC moved to the old generation. On any store - | that has been GC'd before (bd gc, or a previous flatten or compact), only a - | full collection reclaims the squashed history. A full GC can take minutes on - | multi-gigabyte stores. - | - | Examples: - | bd compact --dry-run # Preview: show commit breakdown - | bd compact --force # Squash commits older than 30 days - | bd compact --days 7 --force # Keep only last 7 days of history - | bd compact --days 90 --force # Conservative: squash 90+ day old commits - flag --days type=int default="30" usage="Keep commits newer than N days" - flag --dry-run type=bool default="false" usage="Preview without making changes" - flag --force -f type=bool default="false" usage="Confirm commit squash" - -bd completion - use: "completion" - short: "Generate the autocompletion script for the specified shell" - hidden: false - runnable: false - long: - | Generate the autocompletion script for bd for the specified shell. - | See each sub-command's help for details on how to use the generated script. - | - -bd completion bash - use: "bash" - short: "Generate the autocompletion script for bash" - hidden: false - runnable: true - long: - | Generate the autocompletion script for the bash shell. - | - | This script depends on the 'bash-completion' package. - | If it is not installed already, you can install it via your OS's package manager. - | - | To load completions in your current shell session: - | - | source <(bd completion bash) - | - | To load completions for every new session, execute once: - | - | #### Linux: - | - | bd completion bash > /etc/bash_completion.d/bd - | - | #### macOS: - | - | bd completion bash > $(brew --prefix)/etc/bash_completion.d/bd - | - | You will need to start a new shell for this setup to take effect. - | - flag --no-descriptions type=bool default="false" usage="disable completion descriptions" - -bd completion fish - use: "fish" - short: "Generate the autocompletion script for fish" - hidden: false - runnable: true - long: - | Generate the autocompletion script for the fish shell. - | - | To load completions in your current shell session: - | - | bd completion fish | source - | - | To load completions for every new session, execute once: - | - | bd completion fish > ~/.config/fish/completions/bd.fish - | - | You will need to start a new shell for this setup to take effect. - | - flag --no-descriptions type=bool default="false" usage="disable completion descriptions" - -bd completion powershell - use: "powershell" - short: "Generate the autocompletion script for powershell" - hidden: false - runnable: true - long: - | Generate the autocompletion script for powershell. - | - | To load completions in your current shell session: - | - | bd completion powershell | Out-String | Invoke-Expression - | - | To load completions for every new session, add the output of the above command - | to your powershell profile. - | - flag --no-descriptions type=bool default="false" usage="disable completion descriptions" - -bd completion zsh - use: "zsh" - short: "Generate the autocompletion script for zsh" - hidden: false - runnable: true - long: - | Generate the autocompletion script for the zsh shell. - | - | If shell completion is not already enabled in your environment you will need - | to enable it. You can execute the following once: - | - | echo "autoload -U compinit; compinit" >> ~/.zshrc - | - | To load completions in your current shell session: - | - | source <(bd completion zsh) - | - | To load completions for every new session, execute once: - | - | #### Linux: - | - | bd completion zsh > "${fpath[1]}/_bd" - | - | #### macOS: - | - | bd completion zsh > $(brew --prefix)/share/zsh/site-functions/_bd - | - | You will need to start a new shell for this setup to take effect. - | - flag --no-descriptions type=bool default="false" usage="disable completion descriptions" - -bd config - use: "config" - short: "Manage configuration settings" - group: "setup" - hidden: false - runnable: false - long: - | Manage configuration settings for external integrations and preferences. - | - | Configuration is stored per-project in the beads database and is version-control-friendly. - | - | Common namespaces: - | - export.* Auto-export settings (stored in config.yaml) - | - import.* JSONL import settings (stored in config.yaml) - | - jira.* Jira integration settings - | - linear.* Linear integration settings - | - github.* GitHub integration settings - | - gitlab.* GitLab integration settings - | - ado.* Azure DevOps integration settings - | - notion.* Notion integration settings - | - custom.* Custom integration settings - | - status.* Issue status configuration - | - claim.* Claim arbitration settings (pool-aware claiming) - | - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095) - | - lint.* Additional per-type lint sections (stored in config.yaml) - | - | Auto-Export (config.yaml): - | Optional JSONL export to .beads/issues.jsonl after write commands (throttled). - | Useful for viewers (bv), interchange, and issue-level migration; not a backup. - | It is not cross-machine sync; use bd dolt push/pull with a Dolt remote. - | Disabled by default. Enable only for integrations that need fresh JSONL. - | Auto-staging is separate and disabled by default. - | - | Keys: - | export.auto Enable/disable auto-export (default: false) - | export.path Output filename relative to .beads/ (default: issues.jsonl) - | export.interval Minimum time between exports (default: 60s) - | export.git-add Auto-stage the export file (default: false) - | - | Auto-Import (config.yaml): - | Reads .beads/issues.jsonl by default when a JSONL import path is implied. - | Use a relative filename/path so the import stays within the project .beads/ - | directory and remains portable across machines. - | - | Keys: - | import.path Input filename relative to .beads/ (default: issues.jsonl) - | - | Custom Status States: - | You can define custom status states for multi-step pipelines using the - | status.custom config key. Statuses should be comma-separated. - | - | Example: - | bd config set status.custom "awaiting_review,awaiting_testing,awaiting_docs" - | - | This enables issues to use statuses like 'awaiting_review' in addition to - | the built-in statuses (open, in_progress, blocked, deferred, closed). - | - | Claim Pools: - | A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g. - | "fable-crew") and let any actor take them with --claim. List the pool - | aliases in the claim.pools config key, comma-separated: - | - | bd config set claim.pools "fable-crew,night-crew" - | - | Issues assigned to a real actor (or to an alias not in the list) keep - | their anti-steal protection. Pool takes carry the normal lease; note - | that if a taker's lease expires, bd reclaim returns the issue to the - | unassigned pool, not to the pool alias it was dispatched to. - | - | Suppressing Doctor Warnings: - | Suppress specific bd doctor warnings by check name slug: - | bd config set doctor.suppress.pending-migrations true - | bd config set doctor.suppress.git-hooks true - | Check names are converted to slugs: "Git Hooks" → "git-hooks". - | Only warnings are suppressed (errors and passing checks always show). - | To unsuppress: bd config unset doctor.suppress. - | - | Examples: - | bd config set export.auto true # Enable auto-export for viewer integrations - | bd config set export.path "beads.jsonl" # Custom export filename - | bd config set import.path "beads.jsonl" # Custom import filename - | bd config set export.git-add true # Also stage the export file - | bd config set jira.url "https://company.atlassian.net" - | bd config set jira.project "PROJ" - | bd config set status.custom "awaiting_review,awaiting_testing" - | bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor - | bd config set doctor.suppress.pending-migrations true - | bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) - | bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init - | bd config set lint.sections.epic "Standards scorecard, Cost" # Extra sections bd lint requires for epics - | bd config get export.auto - | bd config list - | bd config unset jira.url - -bd config apply - use: "apply" - short: "Reconcile system state to match configuration" - hidden: false - runnable: true - long: - | Reconcile actual system state to match declared configuration. - | - | Runs drift detection and then fixes any mismatches it finds: - | - | - hooks Reinstall git hooks if missing or outdated - | - remote Add/update Dolt origin remote to match federation.remote - | - server Start Dolt server if dolt.shared-server is enabled - | - | This command is idempotent — safe to run multiple times. Use --dry-run - | to preview what would change without making modifications. - | - | Examples: - | bd config apply - | bd config apply --dry-run - | bd config apply --json - flag --dry-run type=bool default="false" usage="Show what would change without making modifications" - -bd config drift - use: "drift" - short: "Detect config-vs-reality inconsistencies" - hidden: false - runnable: true - long: - | Detect drift between declared configuration and actual system state. - | - | This is a read-only diagnostic that answers "is my environment consistent - | with my config?" — no mutations are performed. - | - | Checks: - | - hooks Git hooks installed and up-to-date - | - remote Dolt remote matches federation.remote config - | - server Server state matches dolt.shared-server config - | - | Exit codes: - | 0 No drift detected (all checks ok/info/skipped) - | 1 Drift detected (at least one check has status "drift") - | - | Examples: - | bd config drift - | bd config drift --json - -bd config get - use: "get " - short: "Get a configuration value" - hidden: false - runnable: true - -bd config list - use: "list" - short: "List all configuration" - hidden: false - runnable: true - -bd config set - use: "set " - short: "Set a configuration value" - hidden: false - runnable: true - flag --force-git-tracked type=bool default="false" usage="Allow writing secret keys to git-tracked config files (use with caution)" - -bd config set-many - use: "set-many ..." - short: "Set multiple configuration values in one operation" - hidden: false - runnable: true - long: - | Set multiple configuration values at once with a single auto-commit and auto-push. - | - | Each argument must be in key=value format. All values are validated before - | any writes occur. This is faster and less noisy than separate 'bd config set' - | calls, especially in CI. - | - | Examples: - | bd config set-many ado.state_map.open=New ado.state_map.closed=Closed - | bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ - flag --force-git-tracked type=bool default="false" usage="Allow writing secret keys to git-tracked config files (use with caution)" - -bd config show - use: "show" - short: "Show all effective configuration with provenance" - hidden: false - runnable: true - long: - | Display a unified view of all effective configuration across all sources - | with annotations showing where each value comes from. - | - | Sources (by precedence for Viper-managed keys): - | - env Environment variable (BD_* or BEADS_*) - | - config.yaml Project config file (.beads/config.yaml) - | - default Built-in default value - | - | Additional sources: - | - metadata Connection settings from .beads/metadata.json - | - database Integration config stored in the Dolt database - | - git Git config (e.g., beads.role) - | - | Examples: - | bd config show - | bd config show --json - | bd config show --source config.yaml - flag --source type=string default="" usage="Filter by source (e.g., config.yaml, env, default, metadata, database, git)" - -bd config unset - use: "unset " - short: "Delete a configuration value" - hidden: false - runnable: true - -bd config validate - use: "validate" - short: "Validate sync-related configuration" - hidden: false - runnable: true - long: - | Validate sync-related configuration settings. - | - | Checks: - | - federation.sovereignty is valid (T1, T2, T3, T4, or empty) - | - federation.remote is set for Dolt sync - | - Remote URL format is valid (dolthub://, gs://, s3://, az://, file://) - | - routing.mode is valid (auto, maintainer, contributor, explicit) - | - | Examples: - | bd config validate - | bd config validate --json - -bd conflicts - use: "conflicts" - short: "Inspect and resolve live merge conflicts" - group: "sync" - hidden: false - runnable: false - long: - | Inspect and resolve the merge conflicts sitting in the working set. - | - | Conflicts appear when a pull or merge brought in changes that collide with - | local ones and could not be settled automatically. These commands present them - | per issue and per field, and resolve them without the raw dolt CLI. - | - | Examples: - | bd conflicts list # which tables and issues are conflicted - | bd conflicts show # every conflicted row, field by field - | bd conflicts show bd-1234 # one issue - | bd conflicts resolve bd-1234 --ours # keep our side of one issue - | bd conflicts resolve --all --theirs # take their side of everything - -bd conflicts list - use: "list" - short: "List tables and issues with live merge conflicts" - hidden: false - runnable: true - -bd conflicts resolve - use: "resolve [...]" - short: "Resolve merge conflicts with --ours or --theirs" - hidden: false - runnable: true - long: - | Resolve live merge conflicts, then conclude the merge with a commit. - | - | Named issue IDs are resolved row by row, leaving every other conflicted row - | alone. --all resolves whole tables at once (dolt's own table-level - | resolution). The merge is committed only once NO conflicts remain, so a - | partial resolution leaves the merge open for the next pass. - | - | Row-by-row resolution requires the row to exist on both sides: when one side - | deleted it, resolve that table wholesale or edit the row directly. - | - | Examples: - | bd conflicts resolve bd-1234 --ours # keep our side of one issue - | bd conflicts resolve bd-1234 bd-5678 --theirs # take their side of two - | bd conflicts resolve --all --ours # every conflicted table - | bd conflicts resolve --all --table config --theirs - | bd conflicts resolve --conclude # commit an already-resolved merge - flag --all type=bool default="false" usage="Resolve whole tables instead of named issues" - flag --conclude type=bool default="false" usage="Commit a merge whose conflicts are already resolved" - flag --no-commit type=bool default="false" usage="Resolve without committing the merge" - flag --ours type=bool default="false" usage="Keep our side" - flag --strategy type=string default="" usage="Resolution strategy: ours|theirs" - flag --table type=string default="" usage="Table to resolve (default: issues)" - flag --theirs type=bool default="false" usage="Take their side" - -bd conflicts show - use: "show []" - short: "Show conflicted rows field by field (base/ours/theirs)" - hidden: false - runnable: true - long: - | Show each conflicted row with its fields side by side. - | - | Only fields where our side and their side disagree are shown; --all-fields - | shows every column. Without an issue ID, every conflicted row of every - | conflicted table is shown. - flag --all-fields type=bool default="false" usage="Show every column, not just the fields that diverged" - flag --table type=string default="" usage="Restrict to one conflicted table (default: all)" - -bd connect - use: "connect [url]" - short: "Attach this workspace to a remote bd serve over HTTP" - group: "setup" - hidden: false - runnable: true - annotations: {bd:skip_store="1"} - long: - | Attach this workspace to a remote bd serve over HTTP. - | - | bd connect verifies the server first (a handshake: api_version, wire - | revision, and — when --expect-project-id is given — workspace identity) and - | writes nothing until that succeeds. On success it writes the per-user - | activation sidecar (.beads/http_target.json, never git-tracked) and sets this - | workspace's metadata.json to backend "http". - | - | A credential, if the server requires one, is never read from a flag or - | recorded on disk by this command. It comes from the same ladder every http - | request does: the BEADS_HTTP_TOKEN environment variable, then - | BEADS_HTTP_TOKEN_COMMAND (a helper that prints a token), then the credentials - | file's [host:port] section, then no credential at all — which the tip OSS - | server's loopback-trust posture answers legitimately, not as a failure. Both - | variables name the server they are for, host[:port]=value (for example - | BEADS_HTTP_TOKEN=bd.example.com=); a bare value is refused, since it - | would be sent to whatever server the workspace's http_target.json names. - | - | --allow-plaintext IS recorded on disk, in the sidecar alongside the server - | url: once granted here, a credential may cross this one server in the clear - | on every later command too, not only this one, without re-passing the flag - | or setting BEADS_HTTP_ALLOW_INSECURE=1 yourself. A later connect to a - | DIFFERENT url starts that grant over; it is never carried forward to a - | server it was not given for. - | - | Examples: - | bd connect http://127.0.0.1:8080 # loopback, no TLS needed - | bd connect https://bd.example.com --expect-project-id p1 # pin workspace identity - | bd connect https://bd.example.com --ca-file ./ca.pem # trust only this CA - | bd connect --clear # forget the server, restoring the previous backend - | - flag --allow-plaintext type=bool default="false" usage="allow a plain http connection to a non-loopback host; remembered in the sidecar for every later command against this server" - flag --ca-file type=string default="" usage="trust ONLY this PEM file for this server (resolved and recorded as an absolute path)" - flag --clear type=bool default="false" usage="remove this workspace's http activation sidecar and restore its previous backend selection in metadata.json" - flag --expect-project-id type=string default="" usage="pin the workspace identity the server must present at every handshake" - flag --force type=bool default="false" usage="allow switching a workspace that already selects a different backend" - -bd context - use: "context" - short: "Show effective backend identity and repository context" - group: "setup" - hidden: false - runnable: true - long: - | Show the effective backend identity information including repository paths, - | backend configuration, and sync settings. - | - | This command reads directly from config files and does not require the - | database to be open, making it useful for diagnostics in degraded states. - | - | Examples: - | bd context # Show context information - | bd context --json # Output in JSON format - | - -bd cook - use: "cook " - short: "Compile a formula into a proto (ephemeral by default)" - hidden: false - runnable: true - long: - | Cook transforms a .formula.json file into a proto. - | - | By default, cook outputs the resolved formula as JSON to stdout for - | ephemeral use. The output can be inspected, piped, or saved to a file. - | - | Two cooking modes are available: - | - | COMPILE-TIME (default, --mode=compile): - | Produces a proto with {{variable}} placeholders intact. - | Use for: modeling, estimation, contractor handoff, planning. - | Variables are NOT substituted - the output shows the template structure. - | - | RUNTIME (--mode=runtime or when --var flags provided): - | Produces a fully-resolved proto with variables substituted. - | Use for: final validation before pour, seeing exact output. - | Requires all variables to have values (via --var or defaults). - | - | Formulas are high-level workflow templates that support: - | - Variable definitions with defaults and validation - | - Step definitions that become issue hierarchies - | - Composition rules for bonding formulas together - | - Inheritance via extends - | - | The --persist flag enables the legacy behavior of writing the proto - | to the database. This is useful when you want to reuse the same - | proto multiple times without re-cooking. - | - | For most workflows, prefer ephemeral protos: pour and wisp commands - | accept formula names directly and cook inline. - | - | Examples: - | bd cook mol-feature.formula.json # Compile-time: keep {{vars}} - | bd cook mol-feature --var name=auth # Runtime: substitute vars - | bd cook mol-feature --mode=runtime --var name=auth # Explicit runtime mode - | bd cook mol-feature --dry-run # Preview steps - | bd cook mol-release.formula.json --persist # Write to database - | bd cook mol-release.formula.json --persist --force # Replace existing - | - | Output (default): - | JSON representation of the resolved formula with all steps. - | - | Output (--persist): - | Creates a proto bead in the database with: - | - ID matching the formula name (e.g., mol-feature) - | - The "template" label for proto identification - | - Child issues for each step - | - Dependencies matching depends_on relationships - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --force type=bool default="false" usage="Replace existing proto if it exists (requires --persist)" - flag --mode type=string default="" usage="Cooking mode: compile (keep placeholders) or runtime (substitute vars)" - flag --persist type=bool default="false" usage="Persist proto to database (legacy behavior)" - flag --prefix type=string default="" usage="Prefix to prepend to proto ID (e.g., 'gt-' creates 'gt-mol-feature')" - flag --search-path type=stringSlice default="[]" usage="Additional paths to search for formula inheritance" - flag --var type=stringArray default="[]" usage="Variable substitution (key=value), enables runtime mode" - -bd count - use: "count" - short: "Count issues matching filters" - group: "views" - hidden: false - runnable: true - long: - | Count issues matching the specified filters. - | - | By default, returns the total count of issues matching the filters. - | Use --by-* flags to group counts by different attributes. - | - | Examples: - | bd count # Count all issues - | bd count --status open # Count open issues - | bd count --by-status # Group count by status - | bd count --by-priority # Group count by priority - | bd count --by-type # Group count by issue type - | bd count --by-assignee # Group count by assignee - | bd count --by-label # Group count by label - | bd count --assignee alice --by-status # Count alice's issues by status - | bd count --include-infra # Count issues + wisps tier (matches 'bd list --include-infra --all' cardinality) - | bd count --type task --include-ephemeral # Count tasks in the durable AND wisps tiers - | - flag --assignee -a type=string default="" usage="Filter by assignee" - flag --by-assignee type=bool default="false" usage="Group count by assignee" - flag --by-label type=bool default="false" usage="Group count by label" - flag --by-priority type=bool default="false" usage="Group count by priority" - flag --by-status type=bool default="false" usage="Group count by status" - flag --by-type type=bool default="false" usage="Group count by issue type" - flag --closed-after type=string default="" usage="Filter issues closed after date (YYYY-MM-DD or RFC3339)" - flag --closed-before type=string default="" usage="Filter issues closed before date (YYYY-MM-DD or RFC3339)" - flag --created-after type=string default="" usage="Filter issues created after date (YYYY-MM-DD or RFC3339)" - flag --created-before type=string default="" usage="Filter issues created before date (YYYY-MM-DD or RFC3339)" - flag --desc-contains type=string default="" usage="Filter by description substring" - flag --empty-description type=bool default="false" usage="Filter issues with empty description" - flag --exclude-status type=stringSlice default="[]" usage="Exclude statuses from the count (comma-separated or repeatable)" - flag --exclude-type type=stringSlice default="[]" usage="Exclude issue types from the count (comma-separated or repeatable)" - flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" - flag --id type=string default="" usage="Filter by specific issue IDs (comma-separated)" - flag --include-ephemeral type=bool default="false" usage="Include ephemeral wisp-plane rows in the count (normally hidden), without lifting type exclusions" - flag --include-infra type=bool default="false" usage="Include infrastructure beads and the wisps tier (matches 'bd list --include-infra --all' cardinality)" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL)" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE)" - flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" - flag --no-assignee type=bool default="false" usage="Filter issues with no assignee" - flag --no-labels type=bool default="false" usage="Filter issues with no labels" - flag --no-parent type=bool default="false" usage="Count only top-level issues (exclude child issues)" - flag --notes-contains type=string default="" usage="Filter by notes substring" - flag --parent type=string default="" usage="Filter by parent issue ID (count children of specified issue)" - flag --priority -p type=int default="0" usage="Filter by priority (0-4: 0=critical, 1=high, 2=medium, 3=low, 4=backlog)" - flag --priority-max type=int default="0" usage="Filter by maximum priority (inclusive)" - flag --priority-min type=int default="0" usage="Filter by minimum priority (inclusive)" - flag --status -s type=string default="" usage="Filter by stored status (open, in_progress, blocked, deferred, closed). Note: dependency-blocked issues use 'bd blocked'" - flag --title type=string default="" usage="Filter by title text (case-insensitive substring match)" - flag --title-contains type=string default="" usage="Filter by title substring" - flag --type -t type=string default="" usage="Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate)" - flag --updated-after type=string default="" usage="Filter issues updated after date (YYYY-MM-DD or RFC3339)" - flag --updated-before type=string default="" usage="Filter issues updated before date (YYYY-MM-DD or RFC3339)" - -bd create - use: "create [title]" - aliases: ["new"] - short: "Create a new issue (or batch from markdown/graph JSON)" - group: "issues" - hidden: false - runnable: true - flag --acceptance type=string default="" usage="Acceptance criteria" - flag --allow-empty-description type=bool default="false" usage="Allow empty description input from stdin or file" - flag --append-notes type=string default="" usage="Append to existing notes (with newline separator)" - flag --assignee -a type=string default="" usage="Assignee" - flag --body type=string default="" hidden annotations={cobra_annotation_mutually_exclusive=["stdin body"]} usage="Alias for --description (GitHub CLI convention)" - flag --body-file type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin body-file"]} usage="Read description from file (use - for stdin)" - flag --context type=string default="" usage="Additional context for the issue" - flag --defer type=string default="" usage="Defer until date (issue hidden from bd ready until then). Same formats as --due" - flag --deps type=stringSlice default="[]" usage="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'" - flag --description -d type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin description"]} usage="Issue description" - flag --description-file type=string default="" hidden annotations={cobra_annotation_mutually_exclusive=["stdin description-file"]} usage="Alias for --body-file" - flag --design type=string default="" annotations={cobra_annotation_mutually_exclusive=["design design-file"]} usage="Design notes" - flag --design-file type=string default="" annotations={cobra_annotation_mutually_exclusive=["design design-file"]} usage="Read design from file (use - for stdin)" - flag --dry-run type=bool default="false" usage="Preview what would be created without actually creating" - flag --due type=string default="" usage="Due date/time. Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15" - flag --ephemeral type=bool default="false" usage="Create as ephemeral (short-lived, subject to TTL compaction)" - flag --estimate -e type=int default="0" usage="Time estimate in minutes (e.g., 60 for 1 hour)" - flag --event-actor type=string default="" usage="Entity URI who caused this event (requires --type=event)" - flag --event-category type=string default="" usage="Event category (e.g., patrol.muted, agent.started) (requires --type=event)" - flag --event-payload type=string default="" usage="Event-specific JSON data (requires --type=event)" - flag --event-target type=string default="" usage="Entity URI or bead ID affected (requires --type=event)" - flag --external-ref type=string default="" usage="External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)" - flag --file -f type=string default="" usage="Create one issue per ## heading (### fields attach to that issue); for title plus description-from-file, use --body-file" - flag --force type=bool default="false" usage="Force creation even if prefix doesn't match database prefix" - flag --graph type=string default="" usage="Create a graph of issues with dependencies from JSON plan file" - flag --id type=string default="" usage="Explicit issue ID (e.g., 'bd-42' for partitioning)" - flag --label type=stringSlice default="[]" hidden usage="Alias for --labels" - flag --labels -l type=stringSlice default="[]" usage="Labels (comma-separated)" - flag --message -m type=string default="" hidden annotations={cobra_annotation_mutually_exclusive=["stdin message"]} usage="Alias for --description (git commit convention)" - flag --metadata type=string default="" usage="Set custom metadata (JSON object, or @file.json to read from file)" - flag --mol-type type=string default="" usage="Molecule type: swarm (multi-agent), patrol (recurring ops), work (default)" - flag --no-history type=bool default="false" usage="Skip Dolt commit history without making GC-eligible (for permanent agent beads)" - flag --no-inherit-labels type=bool default="false" usage="Don't inherit labels from parent issue" - flag --notes type=string default="" usage="Notes" - flag --parent type=string default="" usage="Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')" - flag --priority -p type=string default="2" usage="Priority (0-4 or P0-P4, 0=highest)" - flag --repo type=string default="" usage="Target repository for issue (overrides auto-routing)" - flag --silent type=bool default="false" usage="Output only the issue ID (for scripting)" - flag --skills type=string default="" usage="Required skills for this issue" - flag --spec-id type=string default="" usage="Link to specification document" - flag --status -s type=string default="" usage="Initial status" - flag --stdin type=bool default="false" annotations={cobra_annotation_mutually_exclusive=["stdin body-file" "stdin description-file" "stdin description" "stdin body" "stdin message"]} usage="Read description from stdin (alias for --body-file -)" - flag --storage-class type=string default="" usage="Storage class: versioned, unversioned, or ephemeral (default: storage-class. config, else versioned)" - flag --title type=string default="" usage="Issue title (alternative to positional argument)" - flag --type -t type=string default="task" usage="Issue type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision" - flag --validate type=bool default="false" usage="Validate description contains required sections for issue type" - flag --waits-for type=string default="" usage="Spawner issue ID to wait for (creates waits-for dependency for fanout gate)" - flag --waits-for-gate type=string default="all-children" usage="Gate type: all-children (wait for all) or any-children (wait for first)" - flag --wisp-type type=string default="" usage="Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation" - -bd create-form - use: "create-form" - short: "Create a new issue using an interactive form" - group: "issues" - hidden: false - runnable: true - long: - | Create a new issue using an interactive terminal form. - | - | This command provides a user-friendly form interface for creating issues, - | with fields for title, description, type, priority, labels, and more. - | - | Use --parent to create a sub-issue under an existing parent issue. - | The child will get an auto-generated hierarchical ID (e.g., parent-id.1). - | - | The form uses keyboard navigation: - | - Tab/Shift+Tab: Move between fields - | - Enter: Submit the form (on the last field or submit button) - | - Ctrl+C: Cancel and exit - | - Arrow keys: Navigate within select fields - flag --parent type=string default="" usage="Parent issue ID for creating a hierarchical child (e.g., 'bd-a3f8e9')" - -bd cursor-hook - use: "cursor-hook " - short: "Run an internal Cursor agent lifecycle hook" - hidden: true - runnable: true - -bd db-proxy-child - use: "db-proxy-child" - short: "Internal: run as the database proxy child process" - hidden: true - runnable: true - long: - | db-proxy-child runs the long-lived per-rootDir TCP proxy that fronts a - | DatabaseServer. It is spawned by the parent bd process via fork+exec and is - | not intended to be invoked directly by users. - flag --backend type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="backend kind: external | local-server | local-shared-server" - flag --config type=string default="" usage="path to backend server config (e.g. dolt sql-server YAML)" - flag --database type=string default="" usage="database to select when running shutdown maintenance (local-server backend)" - flag --dolt-bin type=string default="" usage="path to the dolt executable" - flag --external-host type=string default="" usage="external backend: hostname or IP of the dolt sql-server" - flag --external-keep-alive type=duration default="0s" usage="external backend: TCP keepalive period (default 30s)" - flag --external-port type=int default="0" usage="external backend: TCP port of the dolt sql-server" - flag --external-socket-path type=string default="" usage="external backend: absolute path to a unix domain socket (overrides host/port)" - flag --idle-timeout type=duration default="0s" usage="idle timeout before shutdown (0 or negative = never shut down)" - flag --logpath type=string default="" usage="path the backend server should write its stdout/stderr to" - flag --port type=int default="0" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="port to listen on" - flag --root type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="root directory holding proxy.lock, proxy.pid, proxy.log" - flag --stop-epoch type=string default="" usage="stop epoch the parent observed at spawn; the proxy aborts before publishing if it advances" - -bd defer - use: "defer [id...]" - short: "Defer one or more issues for later" - hidden: false - runnable: true - long: - | Defer issues to put them on ice for later. - | - | Deferred issues are deliberately set aside - not blocked by anything specific, - | just postponed for future consideration. Unlike blocked issues, there's no - | dependency keeping them from being worked. Unlike closed issues, they will - | be revisited. - | - | Deferred issues don't show in 'bd ready' but remain visible in 'bd list'. - | - | A defer WITH a date is a snooze: once --until passes, the next ready-front - | read returns the issue to open automatically (same shape as 'bd undefer'). - | A defer WITHOUT a date is the indefinite icebox: it stays deferred until - | someone runs 'bd undefer'. - | - | Examples: - | bd defer bd-abc # Icebox indefinitely (until bd undefer) - | bd defer bd-abc --until=tomorrow # Snooze: auto-wakes once the date passes - | bd defer bd-abc --reason="waiting on API access" - | bd defer bd-abc bd-def # Defer multiple issues - flag --reason type=string default="" usage="Record why this issue is being deferred (appended to notes)" - flag --until type=string default="" usage="Defer until specific time (e.g., +1h, tomorrow, next monday)" - -bd delete - use: "delete [issue-id...]" - short: "Delete one or more issues and clean up references" - group: "issues" - hidden: false - runnable: true - long: - | Delete one or more issues and clean up all references to them. - | This command will: - | 1. Remove all dependency links (any type, both directions) involving the issues - | 2. Update text references to "[deleted:ID]" in directly connected issues - | 3. Permanently delete the issues from the database - | - | This is a destructive operation that cannot be undone. Use with caution. - | - | BATCH DELETION: - | Delete multiple issues at once: - | bd delete bd-1 bd-2 bd-3 --force - | - | Delete from file (one ID per line): - | bd delete --from-file deletions.txt --force - | - | Preview before deleting: - | bd delete --from-file deletions.txt --dry-run - | - | DEPENDENCY HANDLING (the same on a local database and against a team server): - | Default: Fails if any issue has dependents not in deletion set - | bd delete bd-1 bd-2 - | - | Cascade: Recursively delete all dependents - | bd delete bd-1 --cascade --force - | - | Force: Delete and orphan dependents - | bd delete bd-1 --force - flag --cascade type=bool default="false" usage="Recursively delete all dependent issues" - flag --dry-run type=bool default="false" usage="Preview what would be deleted without making changes" - flag --force -f type=bool default="false" usage="Actually delete (without this flag, shows preview)" - flag --from-file type=string default="" usage="Read issue IDs from file (one per line)" - flag --if-revision type=string default="" usage="Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)." - -bd dep - use: "dep [issue-id]" - short: "Manage dependencies" - group: "deps" - hidden: false - runnable: true - long: - | Manage dependencies between issues. - | - | When called with an issue ID and --blocks flag, creates a blocking dependency: - | bd dep --blocks - | - | This is equivalent to: - | bd dep add - | - | Examples: - | bd dep bd-xyz --blocks bd-abc # bd-xyz blocks bd-abc - | bd dep add bd-abc bd-xyz # Same as above (bd-abc depends on bd-xyz) - flag --blocks -b type=string default="" usage="Issue ID that this issue blocks (shorthand for: bd dep add )" - flag --no-cycle-check type=bool default="false" usage="Skip the post-add cycle warning (the per-edge cycle check still runs)" - -bd dep add - use: "add [issue-id] [depends-on-id]" - short: "Add a dependency" - hidden: false - runnable: true - long: - | Add a dependency between two issues. - | - | The depends-on-id can be provided as: - | - A positional argument: bd dep add issue-123 issue-456 - | - A flag: bd dep add issue-123 --blocked-by issue-456 - | - A flag: bd dep add issue-123 --depends-on issue-456 - | - | The --blocked-by and --depends-on flags are aliases and both mean "issue-123 - | depends on (is blocked by) the specified issue." - | - | The depends-on-id can be: - | - A local issue ID (e.g., bd-xyz) - | - An external reference: external:: - | - | For bulk wiring, pass newline-delimited JSON with --file. Each line must be an - | object with "from" and "to" fields, and may include "type". The aliases - | "issue_id" and "depends_on_id" are also accepted. Use --file - to read stdin. - | - | External references are stored as-is and resolved at query time using - | the external_projects config. They block the issue until the capability - | is "shipped" in the target project. - | - | With no -t/--type the edge is created as type=blocks, which excludes the - | dependent from bd ready. When stderr is an interactive terminal, an advisory - | note says so once per command; it is silent for scripted and agent callers - | (non-TTY stderr) and can be turned off with --quiet or BD_NO_DEP_TYPE_WARNING=1. - | - | Examples: - | bd dep add bd-42 bd-41 # Positional args - | bd dep add bd-42 --blocked-by bd-41 # Flag syntax (same effect) - | bd dep add bd-42 --depends-on bd-41 # Alias (same effect) - | bd dep add gt-xyz external:beads:mol-run-assignee # Cross-project dependency - | bd dep add bd-42 bd-41 --no-cycle-check # Skip the post-add cycle warning - | bd dep add --file deps.jsonl # Bulk JSONL: {"from":"bd-42","to":"bd-41"} - flag --blocked-by type=string default="" usage="Issue ID that blocks the first issue (alternative to positional arg)" - flag --depends-on type=string default="" usage="Issue ID that the first issue depends on (alias for --blocked-by)" - flag --file type=string default="" usage="Read dependency edges from JSONL file, or '-' for stdin" - flag --no-cycle-check type=bool default="false" usage="On bulk --file adds, skip per-edge cycle checks and the post-add cycle warning (one final whole-graph check still runs before commit); on a single-edge add, skip only the post-add cycle warning" - flag --type -t type=string default="blocks" usage="Dependency type (blocks|tracks|related|parent-child|discovered-from|until|caused-by|validates|relates-to|supersedes); 'blocked-by' and 'depends-on' are accepted as aliases for 'blocks'" - -bd dep cycles - use: "cycles" - short: "Detect dependency cycles" - hidden: false - runnable: true - flag --include-tracks type=bool default="false" usage="Also walk 'tracks' edges: reports every cycle the default walk finds plus cycles that close through a tracks edge, never a loop made only of tracks edges (diagnostic for molecule-root deadlocks hidden by tracks-only propagation)" - flag --limit type=int default="50" usage="Maximum cycles to print (0 = no limit); the reported total is always the whole count, and --json is never truncated" - -bd dep list - use: "list [issue-id...]" - short: "List dependencies or dependents of one or more issues" - hidden: false - runnable: true - long: - | List dependencies or dependents of one or more issues with optional type filtering. - | - | By default shows dependencies (what issues depend on). Use --direction to control: - | - down: Show dependencies (what this issue depends on) - default - | - up: Show dependents (what depends on this issue) - | - | Multiple IDs can be provided for batch dep listing. With --json, the output - | is a flat array of dependency records across all requested issues. - | - | Use --type to filter by dependency type (e.g., tracks, blocks, parent-child). - | - | Examples: - | bd dep list gt-abc # Show what gt-abc depends on - | bd dep list gt-abc gt-def # Batch: deps for both issues - | bd dep list gt-abc --direction=up # Show what depends on gt-abc - | bd dep list gt-abc --direction=up -t tracks # Show what tracks gt-abc (convoy tracking) - flag --direction type=string default="down" usage="Direction: 'down' (dependencies), 'up' (dependents)" - flag --type -t type=string default="" usage="Filter by dependency type (e.g., tracks, blocks, parent-child)" - -bd dep relate - use: "relate " - short: "Create a bidirectional relates_to link between issues" - hidden: false - runnable: true - long: - | Create a loose 'see also' relationship between two issues. - | - | The relates_to link is bidirectional - both issues will reference each other. - | This enables knowledge graph connections without blocking or hierarchy. - | - | Examples: - | bd relate bd-abc bd-xyz # Link two related issues - | bd relate bd-123 bd-456 # Create see-also connection - -bd dep remove - use: "remove [issue-id] [depends-on-id]" - aliases: ["rm"] - short: "Remove a dependency" - hidden: false - runnable: true - -bd dep tree - use: "tree [issue-id]" - short: "Show dependency tree" - hidden: false - runnable: true - long: - | Show dependency tree rooted at the given issue. - | - | By default, shows dependencies (what blocks this issue). Use --direction to control: - | - down: Show dependencies (what blocks this issue) - default - | - up: Show dependents (what this issue blocks) - | - both: Show full graph in both directions - | - | Examples: - | bd dep tree gt-0iqq # Show what blocks gt-0iqq - | bd dep tree gt-0iqq --direction=up # Show what gt-0iqq blocks - | bd dep tree gt-0iqq --status=open # Only show open issues - | bd dep tree gt-0iqq --depth=3 # Limit to 3 levels deep - | - | A node reached by two paths is shown ONCE, under the first path that got - | there, and a cycle simply ends the descent. --show-all-paths is a deprecated - | no-op; use 'bd dep cycles' to find circular dependencies. - | - | --max-rows / BEADS_MAX_ROWS caveat: the tree walk has no query filter to - | thread the cap through, so the full tree is always built first and the - | node count is checked afterward (post-hoc), not during the walk. The cap is - | honored on the --proxied-server route too, which it was not before. - flag --direction type=string default="" usage="Tree direction: 'down' (dependencies), 'up' (dependents), or 'both'" - flag --format type=string default="" usage="Output format: 'mermaid' for Mermaid.js flowchart" - flag --max-depth -d type=int default="50" usage="Maximum tree depth to display (safety limit)" - flag --max-rows type=int default="0" usage="Hard upper bound on rows returned. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Honored on both the direct and the --proxied-server route." - flag --reverse type=bool default="false" usage="Show dependent tree (deprecated: use --direction=up)" - flag --show-all-paths type=bool default="false" usage="Deprecated no-op: accepted and ignored. A node reached by two paths is shown once, under the first." - flag --status type=string default="" usage="Filter to only show issues with this status (open, in_progress, blocked, deferred, closed)" - -bd dep unrelate - use: "unrelate " - short: "Remove a relates_to link between issues" - hidden: false - runnable: true - long: - | Remove a relates_to relationship between two issues. - | - | Removes the link in both directions. - | - | Example: - | bd unrelate bd-abc bd-xyz - -bd diff - use: "diff " - short: "Show changes between two commits or branches" - group: "views" - hidden: false - runnable: true - long: - | Show the differences in issues between two commits or branches. - | - | The refs can be: - | - Commit hashes (e.g., abc123def) - | - Branch names (e.g., main, feature-branch) - | - Special refs like HEAD, HEAD~1 - | - | Examples: - | bd diff main feature-branch # Compare main to feature branch - | bd diff HEAD~5 HEAD # Show changes in last 5 commits - | bd diff abc123 def456 # Compare two specific commits - -bd doctor - use: "doctor [path]" - short: "Check and fix beads installation health (start here)" - group: "maint" - hidden: false - runnable: true - annotations: {bd:skip_store="1"} - long: - | Sanity check the beads installation for the current directory or specified path. - | - | This command checks: - | - If .beads/ directory exists - | - Database version and migration status - | - Schema compatibility (all required tables and columns present) - | - Whether using hash-based vs sequential IDs - | - If CLI version is current (checks GitHub releases) - | - If Claude plugin is current (when running in Claude Code) - | - File permissions - | - Circular dependencies - | - Git hooks (pre-commit, post-merge, pre-push) - | - .beads/.gitignore up to date - | - Metadata.json version tracking (LastBdVersion field) - | - | Storage Availability: - | Full diagnostics, --perf, --deep, --server, --migration, and - | --check=validate currently require Dolt server mode. Embedded Dolt - | supports --check=artifacts, --check=conventions, and - | --check=pollution. --check-health has a limited hook-health fallback. - | Unsupported combinations return a notice without changing storage. - | - | Performance Mode (--perf): - | Run performance diagnostics on your database: - | - Times key operations (bd ready, bd list, bd show, etc.) - | - Collects system info (OS, arch, database stats) - | - Generates CPU profile for analysis - | - Outputs shareable report for bug reports - | - | Export Mode (--output): - | Save diagnostics to a JSON file for historical analysis and bug reporting. - | Includes timestamp and platform info for tracking intermittent issues. - | - | Specific Check Mode (--check): - | Run a specific check in detail. Available checks: - | - artifacts: Detect and optionally clean beads classic artifacts - | (stale JSONL, SQLite files, cruft .beads dirs). Use with --clean. - | - conventions: Check for convention drift (lint warnings, stale - | issues, orphaned issues). Advisory only - warns, never blocks. - | - pollution: Detect and optionally clean test issues from database - | - validate: Run focused data-integrity checks (duplicates, orphaned - | deps, test pollution, git conflicts). Use with --fix to auto-repair. - | - | Deep Validation Mode (--deep): - | Validate full graph integrity. May be slow on large databases. - | Additional checks: - | - Parent consistency: All parent-child deps point to existing issues - | - Dependency integrity: All deps reference valid issues - | - Epic completeness: Find epics ready to close (all children closed as - | completed work; duplicate/wontfix/superseded closes do not count) - | - Agent bead integrity: Agent beads have valid state values - | - Mail thread integrity: Thread IDs reference existing issues - | - Molecule integrity: Molecules have valid parent-child structures - | - | Server Mode (--server): - | Run health checks for Dolt server mode connections (bd-dolt.2.3): - | - Server reachable: Can connect to configured host:port? - | - Dolt version: Is it a Dolt server (not vanilla MySQL)? - | - Database exists: Does the 'beads' database exist? - | - Schema compatible: Can query beads tables? - | - Connection pool: Pool health metrics - | - | Legacy Dolt Migration Validation Mode (--migration): - | Retained for older SQLite-to-Dolt migration workflows and available only in - | Dolt server mode. It is not the migration path for removed backends - | (PostgreSQL, MySQL, SQLite); those fail closed with export/import guidance. - | Combine - | with --json for machine-parseable diagnostic output. - | - | Agent Mode (--agent): - | Output diagnostics designed for AI agent consumption. Instead of terse - | pass/fail messages, each issue includes: - | - Observed state: what the system actually looks like - | - Expected state: what it should look like - | - Explanation: full prose context about the issue and why it matters - | - Commands: exact remediation commands to run - | - Source files: where in the codebase to investigate further - | - Severity: blocking (prevents operation), degraded (partial function), - | or advisory (informational only) - | ZFC-compliant: Go observes and reports, the agent decides and acts. - | Combine with --json for structured agent-facing output. - | - | Suppressing Warnings: - | Suppress specific warnings by setting doctor.suppress. config: - | bd config set doctor.suppress.pending-migrations true - | bd config set doctor.suppress.git-hooks true - | Check names are converted to slugs: "Git Hooks" → "git-hooks". - | Only warnings are suppressed; errors and passing checks always show. - | To unsuppress: bd config unset doctor.suppress. - | - | Examples: - | bd doctor # Check current directory - | bd doctor /path/to/repo # Check specific repository - | bd doctor --json # Machine-readable output - | bd doctor --agent # Agent-facing diagnostic output - | bd doctor --agent --json # Structured agent diagnostics (JSON) - | bd doctor --fix # Automatically fix issues (with confirmation) - | bd doctor --fix --yes # Automatically fix issues (no confirmation) - | bd doctor --fix -i # Confirm each fix individually - | bd doctor --fix --fix-child-parent # Also fix child→parent deps (opt-in) - | bd doctor --fix --force # Force repair even when database can't be opened - | bd doctor --fix --source=jsonl # Rebuild database from a JSONL export - | bd doctor --dry-run # Preview what --fix would do without making changes - | bd doctor --perf # Performance diagnostics - | bd doctor --output diagnostics.json # Export diagnostics to file - | bd doctor --check=artifacts # Show classic artifacts (JSONL, SQLite, cruft dirs) - | bd doctor --check=artifacts --clean # Delete safe-to-delete artifacts (with confirmation) - | bd doctor --check=conventions # Convention drift check (lint, stale, orphans) - | bd doctor --check=pollution # Show potential test issues - | bd doctor --check=pollution --clean # Delete test issues (with confirmation) - | bd doctor --check=validate # Data-integrity checks only - | bd doctor --check=validate --fix # Auto-fix data-integrity issues - | bd doctor --deep # Full graph integrity validation - | bd doctor --server # Dolt server mode health checks - | bd doctor --migration=pre # Legacy Dolt-server migration diagnostic - | bd doctor --migration=post # Legacy Dolt-server completion diagnostic - | bd doctor --migration=pre --json # Machine-parseable legacy diagnostic - flag --agent type=bool default="false" usage="Agent-facing diagnostic mode: rich context for AI agents (ZFC-compliant)" - flag --check type=string default="" usage="Run specific check in detail (e.g., 'pollution')" - flag --check-health type=bool default="false" usage="Quick health check for git hooks (silent on success)" - flag --clean type=bool default="false" usage="For pollution check: delete detected test issues" - flag --deep type=bool default="false" usage="Validate full graph integrity" - flag --dry-run type=bool default="false" usage="Preview fixes without making changes" - flag --fix type=bool default="false" usage="Automatically fix issues where possible" - flag --fix-child-parent type=bool default="false" usage="Remove child→parent dependencies (opt-in)" - flag --interactive -i type=bool default="false" usage="Confirm each fix individually" - flag --migration type=string default="" usage="Run legacy Dolt-server migration diagnostics: 'pre' or 'post'" - flag --orchestrator type=bool default="false" usage="Running in orchestrator multi-workspace mode (routes.jsonl is expected, higher duplicate tolerance)" - flag --orchestrator-duplicates-threshold type=int default="1000" usage="Duplicate tolerance threshold for orchestrator mode (wisps are ephemeral)" - flag --output -o type=string default="" usage="Export diagnostics to JSON file" - flag --perf type=bool default="false" usage="Run performance diagnostics and generate CPU profile" - flag --server type=bool default="false" usage="Run Dolt server mode health checks (connectivity, version, schema)" - flag --verbose -v type=bool default="false" usage="Show all checks (default shows only warnings/errors)" - flag --yes -y type=bool default="false" usage="Skip confirmation prompt (for non-interactive use)" - -bd dolt - use: "dolt" - short: "Configure Dolt database settings" - group: "setup" - hidden: false - runnable: false - long: - | Configure and manage Dolt database settings and server lifecycle. - | - | Beads runs Dolt embedded (in-process) by default: there is no sql-server and - | nothing is auto-started. A database only uses a dolt sql-server when it is - | configured for one: shared-server mode, an explicit server mode, or a - | non-localhost dolt_server_host. The server-only commands below fail with - | "not supported in embedded mode (no Dolt server)" on an embedded database. - | - | Server lifecycle (server mode only): - | bd dolt start Start the Dolt server for this project - | bd dolt stop Stop the Dolt server for this project - | - | Diagnostics (both modes): - | bd dolt status Show Dolt engine status (embedded: in-process, data dir) - | bd dolt show Show current Dolt configuration with connection test - | - | Configuration (server mode only): - | bd dolt set Set a configuration value - | bd dolt test Test server connection - | - | Version control: - | bd dolt commit Commit pending changes - | bd dolt push Push commits to Dolt remote - | bd dolt pull Pull commits from Dolt remote - | - | Remote management: - | bd dolt remote add Add a Dolt remote - | bd dolt remote list List configured remotes - | bd dolt remote remove Remove a Dolt remote - | - | Configuration keys for 'bd dolt set': - | database Database name (default: issue prefix or "beads") - | host Server host (default: 127.0.0.1) - | port Server port (auto-detected; override with bd dolt set port ) - | user MySQL user (default: root) - | data-dir Custom dolt data directory (absolute path; default: .beads/dolt) - | - | Remote server authentication (password + TLS) is NOT stored via 'bd dolt set' - | (keeps secrets out of metadata.json). Configure them with: - | - | BEADS_DOLT_PASSWORD Server password (highest priority) - | BEADS_DOLT_SERVER_TLS Enable TLS (set to "1" or "true") - | BEADS_DOLT_SERVER_USER MySQL user override (else use 'bd dolt set user') - | BEADS_CREDENTIALS_FILE Optional path to credentials file - | - | Default credentials file: ~/.config/beads/credentials (Linux/macOS) - | %APPDATA%\beads\credentials (Windows) - | Format (INI, section = host:port of the resolved connection): - | [127.0.0.1:3307] - | password = secret - | - | Password resolution: BEADS_DOLT_PASSWORD → credentials [host:port] → empty. - | Full reference: docs/architecture/dolt.md (Environment Variables / Credentials). - | - | Flags for 'bd dolt set': - | --update-config Also write to config.yaml for team-wide defaults - | - | Examples: - | bd dolt set database myproject - | bd dolt set host 192.168.1.100 --update-config - | bd dolt set data-dir /home/user/.beads-dolt/myproject - | export BEADS_DOLT_PASSWORD=... BEADS_DOLT_SERVER_TLS=1 - | bd dolt test - -bd dolt clean-databases - use: "clean-databases" - short: "Drop stale test databases from the Dolt server" - hidden: false - runnable: true - long: - | Identify and drop leftover test and agent databases that accumulate - | on the shared Dolt server from interrupted test runs and terminated agents. - | - | Stale database prefixes: testdb_*, beads_test*, beads_pt*, beads_vr*, doctest_*, doctortest_*, benchdb_* - | - | These waste server memory and can degrade performance under concurrent load. - | Use --dry-run to see what would be dropped without actually dropping. - | - | DROP DATABASE only marks a database as dropped; Dolt keeps its directory - | under .dolt_dropped_databases/ so it can be restored with - | CALL DOLT_UNDROP(name) until an explicit purge — disk is not reclaimed - | until then. Pass --purge-dropped to run CALL DOLT_PURGE_DROPPED_DATABASES() - | after cleanup. - | - | --purge-dropped is SERVER-GLOBAL and IRREVERSIBLE. Dolt has no way to scope - | the purge to only the databases this run dropped: it permanently deletes - | every dropped-but-not-yet-purged database on the server, including ones - | dropped by something else entirely (e.g. an operator's accidental - | DROP DATABASE on an unrelated database that was still recoverable via - | DOLT_UNDROP). It also purges pre-existing residue from earlier - | clean-databases runs even if this run finds no stale databases to drop. - | Only pass it when nothing else on the server may be relying on DOLT_UNDROP - | recovery. - flag --dry-run type=bool default="false" usage="Show what would be dropped without dropping" - flag --purge-dropped type=bool default="false" usage="After dropping, also run CALL DOLT_PURGE_DROPPED_DATABASES() — server-global and irreversible, see --help" - -bd dolt commit - use: "commit" - short: "Create a Dolt commit from pending changes" - hidden: false - runnable: true - long: - | Create a Dolt commit from any uncommitted changes in the working set. - | - | This is the primary commit point for batch mode. When auto-commit is set to - | "batch", changes accumulate in the working set across multiple bd commands and - | are committed together here with a descriptive summary message. - | - | Also useful before push operations that require a clean working set, or when - | auto-commit was off or changes were made externally. - | - | For more options (--stdin, custom messages), see: bd vc commit - flag --message -m type=string default="" usage="Commit message (default: auto-generated)" - -bd dolt killall - use: "killall" - short: "Kill all orphan Dolt server processes" - hidden: false - runnable: true - long: - | Find and kill orphan dolt sql-server processes not tracked by the - | canonical PID file for the current repo's Dolt data directory. - | - | Under an orchestrator, the canonical server lives at $GT_ROOT/.beads/. Any other - | dolt sql-server processes using that shared data directory are considered - | orphans and will be killed. - | - | In standalone mode, only dolt sql-server processes using the current - | project's Dolt data directory are eligible for cleanup. Other projects' - | servers are preserved. - -bd dolt pull - use: "pull" - short: "Pull commits from Dolt remote" - hidden: false - runnable: true - long: - | Pull commits from the configured Dolt remote into the local database. - | - | Requires a Dolt remote to be configured in the database directory. - | For Hosted Dolt, set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD environment - | variables for authentication. - | - | Use --remote to pull from a specific named remote instead of the default. - | The remote must already exist (see 'bd dolt remote add'). - | - | Use --strategy ours|theirs to resolve conflicts the auto-resolver declines - | (e.g. both sides edited the same issue since the last sync) instead of - | aborting the pull for manual resolution. Embedded storage only (#4992); on - | server-mode/sql-server storage use 'bd conflicts resolve' after a pull that - | reports conflicts. - flag --remote type=string default="" usage="Pull from a specific named remote instead of the default" - flag --strategy type=string default="" usage="Conflict resolution strategy for conflicts the auto-resolver declines: 'ours' or 'theirs' (embedded storage only, #4992)" - -bd dolt push - use: "push" - short: "Push commits to Dolt remote" - hidden: false - runnable: true - long: - | Push local Dolt commits to the configured remote. - | - | Requires a Dolt remote to be configured in the database directory. With no - | remote configured, bd can adopt one derived from git origin — only with - | consent: interactively, or via --yes; --no-adopt or BD_NO_REMOTE_ADOPT=1 - | disables adoption entirely. - | For Hosted Dolt, set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD environment - | variables for authentication. - | - | Use --force to overwrite remote changes (e.g., when the remote has - | uncommitted changes in its working set). - | - | Use --remote to push to a specific named remote instead of the default. - | The remote must already exist (see 'bd dolt remote add'). - flag --force type=bool default="false" usage="Force push (overwrite remote changes)" - flag --no-adopt type=bool default="false" usage="Never derive a Dolt remote from git origin (also BD_NO_REMOTE_ADOPT=1)" - flag --remote type=string default="" usage="Push to a specific named remote instead of the default" - flag --yes -y type=bool default="false" usage="Consent to adopting a Dolt remote derived from git origin when none is configured" - -bd dolt remote - use: "remote" - short: "Manage Dolt remotes" - hidden: false - runnable: false - long: - | Manage Dolt remotes for push/pull replication. - | - | Subcommands: - | add Add a new remote - | list List all configured remotes - | remove Remove a remote - | reset-data Replace a remote's data plane after a history squash - -bd dolt remote add - use: "add " - short: "Add a Dolt remote" - hidden: false - runnable: true - flag --allow-git-origin type=bool default="false" usage="Allow adding a Dolt remote whose URL matches the git origin (proceed with a warning instead of aborting)" - -bd dolt remote list - use: "list" - short: "List configured Dolt remotes" - hidden: false - runnable: true - -bd dolt remote remove - use: "remove " - short: "Remove a Dolt remote" - hidden: false - runnable: true - -bd dolt remote reset-data - use: "reset-data " - short: "Replace a remote's data plane in place after a history squash" - hidden: false - runnable: true - long: - | Replace a Dolt remote's stored data with a fresh copy of local HEAD. - | - | After a history squash (see the History Bloat recovery runbook), a plain - | 'bd dolt push --force' re-points the remote's refs but deletes nothing: - | Dolt remotes accumulate chunks monotonically, so the remote keeps the full - | pre-squash store. This command rebuilds the remote's data plane so it holds - | only live chunks: - | - | - Git-backed remotes (issue data riding a git remote under refs/dolt/data): - | deletes the Dolt data refs on the git remote, then force-pushes to - | rebuild a fresh store. Code branches are untouched. - | - Native file remotes (file:// paths): clears the store directory, then - | force-pushes to rebuild it. - | - Cloud/hosted remotes (aws://, gs://, dolthub://, ...): bd cannot clear - | the stored data safely — replace the remote with a fresh URL or prefix: - | bd dolt remote remove - | bd dolt remote add - | bd dolt push --force - | - | This rewrites the remote's data plane. Every other clone must re-clone from - | the reset remote (that is already true after the squash itself). Refuses to - | run with uncommitted working-set changes: the rebuilt remote holds exactly - | HEAD, and anything uncommitted would not be part of it. - | - | Examples: - | bd dolt remote reset-data origin # prompts for confirmation - | bd dolt remote reset-data origin --yes # no prompt (scripts, agents) - flag --yes -y type=bool default="false" usage="Skip the confirmation prompt (required in non-interactive use)" - -bd dolt set - use: "set " - short: "Set a Dolt configuration value" - hidden: false - runnable: true - long: - | Set a Dolt configuration value in metadata.json. - | - | Keys: - | database Database name (default: issue prefix or "beads") - | host Server host (default: 127.0.0.1) - | port Server port (auto-detected; override with bd dolt set port ) - | user MySQL user (default: root) - | data-dir Custom dolt data directory (absolute path; default: .beads/dolt) - | - | There is no 'password' or 'tls' key here on purpose — secrets and TLS must - | not land in metadata.json. Use environment variables or the credentials file: - | - | BEADS_DOLT_PASSWORD Server password (highest priority) - | BEADS_DOLT_SERVER_TLS Enable TLS ("1" or "true") - | BEADS_CREDENTIALS_FILE Optional override path for credentials - | - | Default credentials file: ~/.config/beads/credentials - | Format: - | [host:port] - | password = secret - | - | See: bd dolt --help and docs/architecture/dolt.md - | - | Use --update-config to also write to config.yaml for team-wide defaults. - | - | Examples: - | bd dolt set database myproject - | bd dolt set host 192.168.1.100 - | bd dolt set port 3307 --update-config - | bd dolt set data-dir /home/user/.beads-dolt/myproject - | export BEADS_DOLT_PASSWORD=... BEADS_DOLT_SERVER_TLS=1 - flag --update-config type=bool default="false" usage="Also write to config.yaml for team-wide defaults" - -bd dolt show - use: "show" - short: "Show current Dolt configuration with connection status" - hidden: false - runnable: true - -bd dolt start - use: "start" - short: "Start the Dolt SQL server for this project" - hidden: false - runnable: true - long: - | Start a dolt sql-server for the current beads project. - | - | The server runs in the background on a per-project port derived from the - | project path. PID and logs are stored in .beads/. - | - | The server auto-starts transparently when needed, so manual start is rarely - | required. Use this command for explicit control or diagnostics. - | - | Not available in proxied-server mode: there the proxy owns its dolt backend's - | lifecycle and starts it on demand, so a server started here would be a second, - | unsupervised one over the same data directory. Use 'bd dolt status' to see what - | is running and 'bd dolt stop' to shut it down. - -bd dolt status - use: "status" - short: "Show Dolt engine status" - hidden: false - runnable: true - long: - | Show the status of the Dolt engine for the current project. - | - | In embedded mode, reports that the Dolt engine runs in-process and shows - | the on-disk data directory. For beads-managed (local) servers, displays - | PID, port, and data directory from the local PID file. For externally- - | managed servers — a shared server (dolt.shared-server: true), a remote - | dolt_server_host, or a local server managed outside bd (dolt.auto-start: - | false, e.g. an orchestrator-shared sql-server) — pings the configured - | endpoint via SQL and reports reachability, server version, and database. - | - | In proxied-server mode, reports the proxy (the endpoint every bd command - | connects through) and the dolt backend behind it separately, read from the - | proxy's own process records. Reporting starts nothing: a quiesced workspace - | is shown as not running, and the next bd command launches it. - -bd dolt stop - use: "stop" - short: "Stop the Dolt SQL server for this project" - hidden: false - runnable: true - long: - | Stop the dolt sql-server managed by beads for the current project. - | - | This sends a graceful shutdown signal. The server will restart automatically - | on the next bd command unless auto-start is disabled. - | - | For a managed proxied server, --force can recover unverifiable or legacy - | process records (both the proxy and its backend) only after each live process - | executable is matched to bd or dolt and its command line ties it to this - | workspace. In that recovery path, force still refuses to signal a process - | whose executable identity cannot be matched to bd or dolt, or whose workspace - | scope cannot be established. - flag --force type=bool default="false" usage="Force stop (proxied recovery still requires a bd/dolt executable match)" - -bd dolt test - use: "test" - short: "Test connection to Dolt server" - hidden: false - runnable: true - long: - | Test the connection to the configured Dolt server. - | - | This verifies that: - | 1. The server is reachable at the configured host:port - | 2. The connection can be established - | - | Use this before switching to server mode to ensure the server is running. - -bd duplicate - use: "duplicate --of " - short: "Mark an issue as a duplicate of another" - group: "deps" - hidden: false - runnable: true - long: - | Mark an issue as a duplicate of a canonical issue. - | - | The duplicate issue is automatically closed with a reference to the canonical. - | This is essential for large issue databases with many similar reports. - | - | Examples: - | bd duplicate bd-abc --of bd-xyz # Mark bd-abc as duplicate of bd-xyz - flag --of type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Canonical issue ID (required)" - -bd duplicates - use: "duplicates" - short: "Find and optionally merge duplicate issues" - group: "deps" - hidden: false - runnable: true - long: - | Find issues with identical content (title, description, design, acceptance criteria). - | Groups issues by content hash and reports duplicates with suggested merge targets. - | The merge target is chosen by: - | 1. Reference count (most referenced issue wins) - | 2. Lexicographically smallest ID if reference counts are equal - | Only groups issues with matching status (open with open, closed with closed). - | Example: - | bd duplicates # Show all duplicate groups - | bd duplicates --auto-merge # Automatically merge all duplicates - | bd duplicates --dry-run # Show what would be merged - flag --auto-merge type=bool default="false" usage="Automatically merge all duplicates" - flag --dry-run type=bool default="false" usage="Show what would be merged without making changes" - -bd edit - use: "edit [id]" - short: "Edit an issue field in $EDITOR" - group: "issues" - hidden: false - runnable: true - long: - | Edit an issue field using your configured $EDITOR. - | - | By default, edits the description. Use flags to edit other fields. - | - | Examples: - | bd edit bd-42 # Edit description - | bd edit bd-42 --title # Edit title - | bd edit bd-42 --design # Edit design notes - | bd edit bd-42 --notes # Edit notes - | bd edit bd-42 --acceptance # Edit acceptance criteria - flag --acceptance type=bool default="false" usage="Edit the acceptance criteria" - flag --description type=bool default="false" usage="Edit the description (default)" - flag --design type=bool default="false" usage="Edit the design notes" - flag --notes type=bool default="false" usage="Edit the notes" - flag --title type=bool default="false" usage="Edit the title" - -bd epic - use: "epic" - short: "Epic management commands" - group: "deps" - hidden: false - runnable: false - -bd epic close-eligible - use: "close-eligible" - short: "Close epics where all children are complete" - hidden: false - runnable: true - flag --dry-run type=bool default="false" usage="Preview what would be closed without making changes" - flag --reason -r type=string default="All children completed" usage="Close reason applied to every epic closed" - -bd epic status - use: "status" - short: "Show epic completion status" - hidden: false - runnable: true - flag --eligible-only type=bool default="false" usage="Show only epics eligible for closure" - -bd events - use: "events" - short: "Read and manage the durable events journal" - group: "maint" - hidden: false - runnable: false - long: - | Read and manage the durable events journal (bd_events_journal). - | - | The journal records every committed issue mutation as an ordered, replayable - | row. Enable it with 'bd config set events-journal true' (or - | BD_EVENTS_JOURNAL=1). Records are emitted only while it is enabled. - | - | Retention is automatic: an enabled journal is bounded to the retention floors - | (events-journal-retain-days / -rows, 7 days / 100k rows by default) without - | anyone running a command. Disable both floors for an unbounded ledger, or - | events-journal-auto-prune for manual control; 'bd events prune' remains for an - | earlier, on-demand cut below the floors. - | - | Coverage and scope: - | - Every mutation through bd's normal write paths (create, update, close, - | reopen, delete, claim, dependency add/remove, label add/remove, comment) is - | journaled in the same transaction as the change. Raw DML run through - | 'bd sql' bypasses those paths and is NOT journaled — a known non-coverage. - | - The journal is per-branch working-set state (dolt_ignored): it records the - | mutations committed on the writer's active branch. Rows arrive by direct - | write, not by merge, so a consumer must read the journal on the same branch - | the writer commits to; a branch checkout or merge does not carry journal - | rows across branches. - | - For the same reason the journal is per REPLICA. 'bd dolt pull' and the - | changes a merge settles into this clone are not journaled: those rows - | arrived as data, not as local mutations, and nothing on this clone wrote - | them through the mutation seam. A consumer that mirrors a synced workspace - | must re-baseline (a fresh export or a full re-read) after a sync, because - | the journal describes only what THIS clone mutated. - | Each replica also has its OWN seq space, counted from its own first - | mutation. A checkpoint taken against one replica is meaningless against - | another — the same seq names a different record, and a seq above the other - | replica's head reads as "caught up" and stalls forever. Track a checkpoint - | per replica, and re-baseline rather than carry one across. - | - A few writes that happen while a store is being OPENED are unjournaled by - | design: schema migrations and the version reconciliation that runs before - | the workspace's configuration has been applied to the store. They touch - | schema and clone-local metadata, never a bead, so a replaying consumer has - | nothing to apply them to. - | - Dependency records are not symmetric, in two ways. - | Count: a dep_add is emitted for every accepted add, INCLUDING an idempotent - | same-type re-add that only refreshes the edge's metadata. The audit 'events' - | table deduplicates that case and writes nothing; the journal does not. Treat - | dep_add as an upsert of the edge, not as proof the edge is new. A dep_remove - | naming an edge that is already gone emits nothing at all. - | Payload: dep.metadata differs in provenance between the two ops. On dep_add - | it is the value being written, as the caller supplied it; on dep_remove it is - | the raw stored column read back just before the delete. The two can differ - | byte for byte while meaning the same thing, so compare parsed values. - | - | Structural dependency edits — the ones bd wires up itself rather than a 'bd dep' - | verb — write no audit event but DO journal, by design: a replaying consumer - | needs the edge either way. - -bd events export - use: "export" - short: "Print the entire journal from the beginning (JSON lines)" - hidden: false - runnable: true - long: - | Print every events journal record from seq 1, in order, as JSON lines. - | - | Equivalent to 'bd events tail --since 0'. Like tail, it FAILS rather than - | present a pruned journal's surviving suffix as a complete history. - flag --limit type=int default="0" usage="maximum number of records to return (0 = no limit)" - -bd events prune - use: "prune" - short: "Delete journal records below a sequence number (retention)" - hidden: false - runnable: true - long: - | Delete events journal records with seq less than --before. - | - | Retention is already enforced automatically: after a mutating command commits, - | and on a timer in 'bd serve', bd deletes everything the floors below do not - | protect. This command is for an EARLIER, on-demand cut BELOW the floors — after - | a consumer has durably processed a span you do not want to wait out. It cannot - | cut deeper than the floors: shrinking the retained window itself means lowering - | them. The journal is clone-local operational state, so pruning never affects - | issue data. - | - | Two retention floors compose onto --before and can only reduce what a prune - | removes. They bound the automatic prune and this one identically: - | events-journal-retain-days keep every row younger than N days (default 7) - | events-journal-retain-rows always keep the newest N rows (default 100000) - | - | Set BOTH floors to 0 for an unbounded ledger: automatic pruning then does - | nothing, and this command becomes the only thing that deletes a record. To keep - | the floors but own deletion yourself, set events-journal-auto-prune false. - | - | Note the floors are time-based and count-based — they are NOT a consumer - | watermark. They protect only the recent window; a consumer that has fallen - | further behind than both floors allow will be pruned past and lose records. - | Consumers are responsible for tracking their own watermark (the highest seq they - | have durably processed) and for sizing the floors to the longest outage they - | intend to survive. Pruned history cannot be recovered from the workspace — the - | journal is the only local copy. Pruning frees rows, not disk: pair it with - | 'dolt gc' to reclaim the space, since the table is working-set (dolt_ignored) - | state that ordinary Dolt commits never garbage-collect. - flag --before type=int64 default="0" usage="delete records with seq less than this value" - -bd events tail - use: "tail" - short: "Print journal records after a sequence number (JSON lines)" - hidden: false - runnable: true - long: - | Print events journal records with seq greater than --since, in order. - | - | Each line is a JSON record: - | {"seq":N,"ts":"...","op":"create|update|close|delete|dep_add|dep_remove|comment", - | "issue_id":"...","actor":"...","issue":{...|null},"dep":{"kind":..,"target":..,"metadata":..},"comment":{...}} - | - | Record contract (stable for external consumers): - | seq int64 counter-assigned inside the mutation's transaction; gapless, - | strictly increasing in commit order, never reused or reset - | ts string UTC insert time, stamped inside the committing transaction - | op string one of the seven ops above - | issue_id string the mutated issue's id - | actor string the acting identity that performed the mutation, as resolved - | for the audit-events table (on a comment row: the comment's - | author). A delete — and the dep_remove rows a cascading - | delete produces — carries the identity that REQUESTED it. - | Empty (omitted) only when the path genuinely has no actor: - | derived maintenance, system cleanup with no request behind - | it, and rows older than the column. Never user attribution - | when empty. - | issue object full issue state AFTER the mutation; null on delete - | dep object {"kind","target","metadata"} for dep_add / dep_remove; omitted otherwise - | comment object {"id","author","text","created_at","source"} for comment; omitted otherwise - | - | Poll with the highest seq seen to consume new mutations incrementally, or pass - | --follow to keep printing new records as they are committed (Ctrl-C to stop). - | - | Retention boundary: if --since is below the oldest retained record — the prefix - | you asked for was pruned — the read FAILS instead of silently skipping ahead or - | returning an empty success. With --json the failure carries - | {"code":"events_journal_truncated","since":N,"floor":F,"head":H}: floor is the - | oldest seq still retained, head the highest ever assigned. Resume from floor-1 - | to continue with a known gap, or rebuild from a full export. - flag --follow type=bool default="false" usage="keep printing new records as they are committed (Ctrl-C to stop)" - flag --limit type=int default="0" usage="maximum number of records to return (0 = no limit)" - flag --since type=int64 default="0" usage="return records with seq greater than this value" - -bd export - use: "export" - short: "Export issues to JSONL format" - group: "sync" - hidden: false - runnable: true - long: - | Export all issues to JSONL (newline-delimited JSON) format. - | - | Each line is a complete JSON object representing one issue, including its - | labels, dependencies, and comments. - | - | This command is for issue export, migration, and interoperability. It exports - | records from the issues table; it is not a full database backup and does not - | capture Dolt branches, commit history, working-set state, or non-issue tables. - | For supported full backup/restore flows, use 'bd backup init', 'bd backup sync', - | and 'bd backup restore'. - | - | By default, exports only regular issues (excluding infrastructure beads - | like agents, roles, and messages). Use --all to include everything. - | - | Memories (from 'bd remember') are excluded by default because they may - | contain sensitive agent context. Use --include-memories or --all to - | include them. - | - | EXAMPLES: - | bd export # Export issues to stdout - | bd export -o issues.jsonl # Export issues to file - | bd export --include-memories # Export issues + memories - | bd export --all -o full.jsonl # Include infra + templates + gates + memories - | bd export --scrub -o clean.jsonl # Exclude test/pollution records - flag --all type=bool default="false" usage="Include all records (infra, templates, gates, memories)" - flag --exclude-owner type=stringArray default="[]" usage="Exclude issues created by this identity (repeatable; also reads export.exclude_owners config)" - flag --include-infra type=bool default="false" usage="Include infrastructure beads (agents, roles, messages)" - flag --include-memories type=bool default="false" usage="Include persistent memories (from 'bd remember') in the export" - flag --no-memories type=bool default="false" hidden usage="Exclude persistent memories (deprecated: now the default)" - flag --output -o type=string default="" usage="Output file path (default: stdout)" - flag --scrub type=bool default="false" usage="Exclude test/pollution records" - flag --verbose type=bool default="false" usage="Print filtered issue count when owners are excluded" - -bd federation - use: "federation" - short: "Manage peer-to-peer federation with other workspaces" - group: "sync" - hidden: false - runnable: false - long: - | Manage peer-to-peer federation between Dolt-backed beads databases. - | - | Federation enables synchronized issue tracking across multiple workspaces, - | each maintaining their own Dolt database while sharing updates via remotes. - | - | Requires the Dolt storage backend. - -bd federation add-peer - use: "add-peer " - short: "Add a federation peer with optional SQL credentials" - hidden: false - runnable: true - long: - | Add a new federation peer remote with optional SQL user authentication. - | - | The URL can be: - | - dolthub://org/repo DoltHub hosted repository - | - host:port/database Direct dolt sql-server connection - | - file:///path/to/repo Local file path (for testing) - | - | Credentials are encrypted and stored locally. They are used automatically - | when syncing with the peer. If --user is provided without --password, - | you will be prompted for the password interactively. - | - | Examples: - | bd federation add-peer town-beta dolthub://acme/town-beta-beads - | bd federation add-peer town-gamma 192.168.1.100:3306/beads --user sync-bot - | bd federation add-peer partner https://partner.example.com/beads --user admin --password secret - flag --password -p type=string default="" usage="SQL password (prompted if --user set without --password)" - flag --sovereignty type=string default="" usage="Sovereignty tier (T1, T2, T3, T4)" - flag --user -u type=string default="" usage="SQL username for authentication" - -bd federation list-peers - use: "list-peers" - short: "List configured federation peers" - hidden: false - runnable: true - -bd federation remove-peer - use: "remove-peer " - short: "Remove a federation peer" - hidden: false - runnable: true - -bd federation status - use: "status [--peer name]" - short: "Show federation sync status" - hidden: false - runnable: true - long: - | Show synchronization status with peer towns. - | - | Displays: - | - Configured peers and their URLs - | - Commits ahead/behind each peer - | - Whether there are unresolved conflicts - | - | Examples: - | bd federation status # Status for all peers - | bd federation status --peer town-beta # Status for specific peer - flag --peer type=string default="" usage="Specific peer to check" - -bd federation sync - use: "sync [--peer name]" - short: "Synchronize with a peer town" - hidden: false - runnable: true - long: - | Pull from and push to peer towns. - | - | Without --peer, syncs with all configured peers. - | With --peer, syncs only with the specified peer. - | - | Handles merge conflicts using the configured strategy: - | --strategy ours Keep local changes on conflict - | --strategy theirs Accept remote changes on conflict - | - | If no strategy is specified and conflicts occur, the sync will pause - | and report which tables have conflicts for manual resolution. - | - | Examples: - | bd federation sync # Sync with all peers - | bd federation sync --peer town-beta # Sync with specific peer - | bd federation sync --strategy theirs # Auto-resolve using remote values - flag --peer type=string default="" usage="Specific peer to sync with" - flag --strategy type=string default="" usage="Conflict resolution strategy (ours|theirs)" - -bd find-duplicates - use: "find-duplicates" - aliases: ["find-dups"] - short: "Find semantically similar issues using text analysis or AI" - group: "views" - hidden: false - runnable: true - long: - | Find issues that are semantically similar but not exact duplicates. - | - | Unlike 'bd duplicates' which finds exact content matches, find-duplicates - | uses text similarity or AI to find issues that discuss the same topic - | with different wording. - | - | Approaches: - | mechanical Token-based text similarity (default, no API key needed) - | ai LLM-based semantic comparison (requires ANTHROPIC_API_KEY, MINIMAX_API_KEY, or ai.api_key) - | - | The mechanical approach tokenizes titles and descriptions, then computes - | Jaccard similarity between all issue pairs. It's fast and free but may - | miss semantically similar issues with very different wording. - | - | The AI approach sends candidate pairs to an Anthropic-compatible model for semantic comparison. - | It first uses mechanical pre-filtering to reduce the number of API calls, - | then asks the LLM to judge whether the remaining pairs are true duplicates. - | - | Examples: - | bd find-duplicates # Mechanical similarity (default) - | bd find-duplicates --threshold 0.4 # Lower threshold = more results - | bd find-duplicates --method ai # Use AI for semantic comparison - | bd find-duplicates --status open # Only check open issues - | bd find-duplicates --limit 20 # Show top 20 pairs - | bd find-duplicates --json # JSON output - flag --limit -n type=int default="50" usage="Maximum number of pairs to show" - flag --max-rows type=int default="0" usage="Hard upper bound on rows fetched from storage. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Not supported under --proxied-server: an explicit --max-rows or BEADS_MAX_ROWS cap errors out rather than silently going unenforced." - flag --method type=string default="mechanical" usage="Detection method: mechanical, ai" - flag --model type=string default="" usage="AI model to use (only with --method ai; default from config ai.model)" - flag --status -s type=string default="" usage="Filter by status (default: non-closed)" - flag --threshold type=float64 default="0.5" usage="Similarity threshold (0.0-1.0, lower = more results)" - -bd flatten - use: "flatten" - short: "Squash all Dolt history into a single commit" - group: "maint" - hidden: false - runnable: true - long: - | Nuclear option: squash ALL Dolt commit history into a single commit. - | - | This uses the Tim Sehn recipe: - | 1. Create a new branch from the current state - | 2. Soft-reset to the initial commit (preserving all data) - | 3. Commit everything as a single snapshot - | 4. Swap main branch to the new flattened branch - | 5. Prune remote-tracking refs (they would keep the old history alive; - | the next push or fetch re-creates them at the new tip) - | 6. Run a full Dolt GC (all storage generations) to reclaim the old history - | - | The GC pass is a full collection: Dolt storage is generational, and a default - | GC never revisits data an earlier GC moved to the old generation. On any store - | that has been GC'd before (bd gc, or a previous flatten or compact), only a - | full collection reclaims the squashed history. A full GC can take minutes on - | multi-gigabyte stores. - | - | This is irreversible — all commit history is lost. The resulting database - | has exactly one commit containing all current data. - | - | Use this when: - | - Your active database has grown very large - | - You don't need commit-level history (time travel) - | - You want to start fresh with minimal storage - | - | Examples: - | bd flatten --dry-run # Preview: show commit count and disk usage - | bd flatten --force # Actually squash all history - | bd flatten --force --json # JSON output - flag --dry-run type=bool default="false" usage="Preview without making changes" - flag --force -f type=bool default="false" usage="Confirm irreversible history squash" - -bd forget - use: "forget " - short: "Remove a persistent memory" - group: "setup" - hidden: false - runnable: true - long: - | Remove a memory by its key. - | - | Use 'bd memories' to see available keys. - | - | Examples: - | bd forget dolt-phantoms - | bd forget auth-jwt - -bd formula - use: "formula" - short: "Manage workflow formulas" - hidden: false - runnable: false - long: - | Manage workflow formulas - the source layer for molecule templates. - | - | Formulas are TOML/JSON files that define workflows with composition rules. - | Define formulas, cook them into protos, then pour or wisp them into work. - | - | Search paths (in order): - | 1. /formulas/ (active project) - | 2. /.beads/formulas/ (repo-local formulas) - | 3. ~/.beads/formulas/ (user) - | 4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set) - | - | Commands: - | list List available formulas from all search paths - | show Show formula details, steps, and composition rules - | schema Show the formula schema index (alias: primitives) - | - | Discovering primitives: - | bd formula schema # list every declared formula struct - | bd formula schema loop # show LoopSpec fields, types, and tags - | bd formula primitives gate # alias; same handler as 'schema' - | examples/formulas/primitives/ # curated, smoke-tested wired fixtures - | docs/workflows/formulas.md # narrative reference - -bd formula convert - use: "convert [--all]" - short: "Convert formula from JSON to TOML" - hidden: false - runnable: true - long: - | Convert formula files from JSON to TOML format. - | - | TOML format provides better ergonomics: - | - Multi-line strings without \n escaping - | - Human-readable diffs - | - Comments allowed - | - | The convert command reads a .formula.json file and outputs .formula.toml. - | The original JSON file is preserved (use --delete to remove it). - | - | Examples: - | bd formula convert shiny # Convert shiny.formula.json to .toml - | bd formula convert ./my.formula.json # Convert specific file - | bd formula convert --all # Convert all JSON formulas - | bd formula convert shiny --delete # Convert and remove JSON file - | bd formula convert shiny --stdout # Print TOML to stdout - flag --all type=bool default="false" usage="Convert all JSON formulas" - flag --delete type=bool default="false" usage="Delete JSON file after conversion" - flag --stdout type=bool default="false" usage="Print TOML to stdout instead of file" - -bd formula list - use: "list" - short: "List available formulas" - hidden: false - runnable: true - long: - | List all formulas from search paths. - | - | Search paths (in order of priority): - | 1. /formulas/ (active project - highest priority) - | 2. /.beads/formulas/ (repo-local formulas) - | 3. ~/.beads/formulas/ (user) - | 4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set) - | - | Formulas in earlier paths shadow those with the same name in later paths. - | - | To list the declared formula schema structs an agent can write inside a .formula.toml, - | use 'bd formula schema' (alias: 'bd formula primitives'). - | - | Examples: - | bd formula list - | bd formula list --json - | bd formula list --type workflow - | bd formula list --type convoy - flag --type type=string default="" usage="Filter by type (workflow, expansion, aspect, convoy)" - -bd formula schema - use: "schema [primitive]" - aliases: ["primitives"] - short: "Show the formula schema index (every exported struct in types.go)" - hidden: false - runnable: true - long: - | Show the formula schema index: every exported struct declared - | in a .formula.toml/.formula.json, with field names, types, and tags. - | - | The index is generated from internal/formula/types.go via go:generate; the - | struct definitions are the source of truth, so this list cannot drift. It is - | structural reference, not proof that every declared runtime behavior is wired. - | - | Examples: - | bd formula schema # list every declared schema struct - | bd formula schema loop # show LoopSpec fields - | bd formula primitives gate # alias; shows Gate fields - | bd formula schema --json # machine-readable index - | - | Curated smoke-tested fixtures for wired primitives live in - | examples/formulas/primitives/ (with a smoke harness that proves they work). - -bd formula show - use: "show " - short: "Show formula details" - hidden: false - runnable: true - long: - | Show detailed information about a formula. - | - | Displays: - | - Formula metadata (name, type, description) - | - Variables with defaults and constraints - | - Steps with dependencies - | - Composition rules (extends, aspects, expansions) - | - Bond points for external composition - | - | To inspect the structure of an individual primitive (e.g. LoopSpec, Gate) - | rather than a user-authored formula, use 'bd formula schema '. - | - | Examples: - | bd formula show shiny - | bd formula show rule-of-five - | bd formula show security-audit --json - -bd gate - use: "gate" - short: "Manage async coordination gates" - group: "issues" - hidden: false - runnable: false - long: - | Gates are async wait conditions that block workflow steps. - | - | Gates are created automatically when a formula step has a gate field. - | They must be closed (manually or via watchers) for the blocked step to proceed. - | - | Gate types: - | human - Requires manual bd close (Phase 1) - | timer - Expires after timeout (Phase 2) - | gh:run - Waits for GitHub workflow (Phase 3) - | gh:pr - Waits for PR merge (Phase 3) - | bead - Waits for another bead to close (Phase 4) - | - | For bead gates, await_id may be a bead ID in this rig's database (e.g., - | "bd-abc123") or the historical cross-rig form :. Cross-rig - | targets resolve through the bead ID's prefix route in routes.jsonl. - | - | Examples: - | bd gate list # Show all open gates - | bd gate list --all # Show all gates including closed - | bd gate check # Evaluate all open gates - | bd gate check --type=bead # Evaluate only bead gates - | bd gate resolve # Close a gate manually - -bd gate add-waiter - use: "add-waiter " - short: "Add a waiter to a gate" - hidden: false - runnable: true - long: - | Register an agent as a waiter on a gate bead. - | - | When the gate closes, the waiter will receive a wake notification via 'bd gate wake'. - | The waiter is typically the worker's address (e.g., "my-project/workers/agent-1"). - | - | This is used by 'bd done --phase-complete' to register for gate wake notifications. - -bd gate check - use: "check" - short: "Evaluate gates and close resolved ones" - hidden: false - runnable: true - long: - | Evaluate gate conditions and automatically close resolved gates. - | - | By default, checks all open gates. Use --type to filter by gate type. - | - | Gate types: - | gh - Check all GitHub gates (gh:run and gh:pr) - | gh:run - Check GitHub Actions workflow runs - | gh:pr - Check pull request merge status - | timer - Check timer gates (auto-expire based on timeout) - | bead - Check bead gates - | all - Check all gate types - | - | GitHub gates use the 'gh' CLI to query status: - | - gh:run checks 'gh run view --json status,conclusion' - | - gh:pr checks 'gh pr view --json state,title' - | - | A gate is resolved when: - | - gh:run: status=completed AND conclusion=success - | - gh:pr: state=MERGED - | - timer: current time > created_at + timeout - | - bead: target bead status=closed, or a bead an earlier check saw in - | this rig no longer exists - | - | A gate is escalated when: - | - gh:run: status=completed AND conclusion in (failure, canceled) - | - gh:pr: state=CLOSED - | - | Examples: - | bd gate check # Check all gates - | bd gate check --type=gh # Check only GitHub gates - | bd gate check --type=gh:run # Check only workflow run gates - | bd gate check --type=timer # Check only timer gates - | bd gate check --type=bead # Check only bead gates - | bd gate check --dry-run # Show what would happen without changes - | bd gate check --escalate # Escalate expired/failed gates - flag --dry-run type=bool default="false" usage="Show what would happen without making changes" - flag --escalate -e type=bool default="false" usage="Escalate failed/expired gates" - flag --limit -l type=int default="100" usage="Limit results (default 100)" - flag --type -t type=string default="" usage="Gate type to check (gh, gh:run, gh:pr, timer, bead, all)" - -bd gate create - use: "create" - short: "Create a gate that blocks an issue" - hidden: false - runnable: true - long: - | Create an ad-hoc gate issue that blocks another issue until resolved. - | - | The blocked issue will not appear in 'bd ready' until the gate is resolved - | via 'bd gate resolve'. - | - | Gate types: - | human - Requires manual 'bd gate resolve' (default) - | timer - Auto-resolves after --timeout duration - | gh:run - Waits for GitHub Actions workflow - | gh:pr - Waits for PR merge - | - | gh:run and gh:pr gates are checked in the current Git repository unless - | --repo names another, or the blocked issue carries a metadata.repo value. - | - | Examples: - | bd gate create --blocks bd-abc - | bd gate create --type=human --blocks bd-abc --reason="Need design review" - | bd gate create --type=timer --blocks bd-abc --timeout=2h - | bd gate create --type=gh:pr --blocks bd-abc --await-id=42 - | bd gate create --type=gh:pr --blocks bd-abc --await-id=42 --repo=owner/other-repo - | bd gate create --blocks bd-abc --title="Gate: awaiting owner sign-off" - flag --await-id type=string default="" usage="Condition identifier (run ID, PR number, etc.)" - flag --blocks type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Issue ID to block (required)" - flag --reason -r type=string default="" usage="Reason for the gate" - flag --repo type=string default="" usage="GitHub repository the gh:run/gh:pr condition is checked in (OWNER/REPO or HOST/OWNER/REPO); default: the blocked issue's metadata.repo, else the current repository" - flag --timeout type=string default="" usage="Timeout duration (e.g., 2h, 30m)" - flag --title type=string default="" usage="Custom gate title (default: \"Gate: \")" - flag --type -t type=string default="human" usage="Gate type (human, timer, gh:run, gh:pr)" - -bd gate discover - use: "discover" - short: "Discover await_id for gh:run gates" - hidden: false - runnable: true - long: - | Discovers GitHub workflow run IDs for gates awaiting CI/CD completion. - | - | This command finds open gates with await_type="gh:run" that don't have an await_id, - | queries recent GitHub workflow runs, and matches them using heuristics: - | - Branch name matching - | - Commit SHA matching - | - Time proximity (runs within 5 minutes of gate creation) - | - | Once matched, the gate's await_id is updated with the GitHub run ID, enabling - | subsequent polling to check the run's status. - | - | A gate whose metadata.repo targets another repository is only matched - | against runs queried from that repository, never against the current - | repository's runs of a same-named workflow. - | - | Examples: - | bd gate discover # Auto-discover run IDs for all matching gates - | bd gate discover --dry-run # Preview what would be matched (no updates) - | bd gate discover --branch main --limit 10 # Only match runs on 'main' branch - flag --branch -b type=string default="" usage="Filter runs by branch (default: current branch)" - flag --dry-run -n type=bool default="false" usage="Preview mode: show matches without updating" - flag --limit -l type=int default="10" usage="Max runs to query from GitHub" - flag --max-age -a type=duration default="30m0s" usage="Max age for gate/run matching" - -bd gate list - use: "list [issue-id]" - short: "List gate issues" - hidden: false - runnable: true - long: - | List gate issues. - | - | With no argument, lists all gate issues in the current beads database. - | With an [issue-id] argument, lists ONLY the gates that block that issue - | (its own dependency gates) — not every gate in the database. - | - | By default, shows only open gates. Use --all to include closed gates. - flag --all -a type=bool default="false" usage="Show all gates including closed" - flag --limit -n type=int default="50" usage="Limit results (default 50)" - -bd gate resolve - use: "resolve " - short: "Manually resolve (close) a gate" - hidden: false - runnable: true - long: - | Close a gate issue to unblock the step waiting on it. - | - | This is equivalent to 'bd close ' but with a more explicit name. - | Use --reason to provide context for why the gate was resolved. - flag --reason -r type=string default="" usage="Reason for resolving the gate" - -bd gate show - use: "show " - short: "Show a gate issue" - hidden: false - runnable: true - long: - | Display details of a gate issue including its waiters. - | - | This is similar to 'bd show' but validates that the issue is a gate. - -bd gc - use: "gc" - short: "Garbage collect: decay old issues, compact Dolt commits, run Dolt GC" - group: "maint" - hidden: false - runnable: true - long: - | Full lifecycle garbage collection for standalone Beads databases. - | - | Runs three phases in sequence: - | 1. DECAY — Delete closed issues older than N days (default 90) - | 2. COMPACT — Squash old Dolt commits into fewer commits (bd compact) - | 3. GC — Run Dolt garbage collection to reclaim disk space - | - | Each phase can be skipped individually. Use --dry-run to preview all phases - | without making changes. - | - | Phase 3 runs Dolt's default, generational GC: it only examines data written - | since the last GC. Data that survived an earlier GC lives in the old generation - | and is never revisited, so on a long-lived store the space freed by decay may - | not be reclaimed. Use --full to collect all generations (slower on large - | stores). - | - | Examples: - | bd gc # Full GC with defaults (90 day decay) - | bd gc --dry-run # Preview what would happen - | bd gc --older-than 30 # Decay issues closed 30+ days ago - | bd gc --skip-decay # Skip issue deletion, just compact+GC - | bd gc --skip-dolt # Skip Dolt GC, just decay+compact - | bd gc --full # Collect all storage generations - | bd gc --force # Skip confirmation prompt - flag --dry-run type=bool default="false" usage="Preview without making changes" - flag --force -f type=bool default="false" usage="Skip confirmation prompts" - flag --full type=bool default="false" usage="Run a full Dolt GC (all generations; slower, reclaims space default passes cannot)" - flag --older-than type=int default="90" usage="Delete closed issues older than N days" - flag --skip-decay type=bool default="false" usage="Skip issue deletion phase" - flag --skip-dolt type=bool default="false" usage="Skip Dolt garbage collection phase" - -bd github - use: "github" - short: "GitHub integration commands" - hidden: false - runnable: false - long: - | Commands for syncing issues between beads and GitHub. - | - | Configuration can be set via 'bd config' or environment variables: - | github.token / GITHUB_TOKEN - Personal access token - | github.owner / GITHUB_OWNER - Repository owner - | github.repo / GITHUB_REPO - Repository name - | github.repository / GITHUB_REPOSITORY - Combined "owner/repo" format - | github.url / GITHUB_API_URL - Custom API URL (GitHub Enterprise) - -bd github pull - use: "pull [refs...]" - short: "Pull specific items from GitHub" - hidden: false - runnable: true - long: - | Pull one or more items from GitHub. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd github sync --pull-only --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - -bd github push - use: "push [bead-ids...]" - short: "Push specific beads to GitHub" - hidden: false - runnable: true - long: - | Push one or more beads issues to GitHub. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd github sync --push-only --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd github repos - use: "repos" - short: "List accessible GitHub repositories" - hidden: false - runnable: true - long: - | List GitHub repositories that the configured token has access to. - -bd github status - use: "status" - short: "Show GitHub sync status" - hidden: false - runnable: true - long: - | Display current GitHub configuration and sync status. - -bd github sync - use: "sync" - short: "Sync issues with GitHub" - hidden: false - runnable: true - long: - | Synchronize issues between beads and GitHub. - | - | By default, performs bidirectional sync: - | - Pulls new/updated issues from GitHub to beads - | - Pushes local beads issues to GitHub - | - | Use --pull-only or --push-only to limit direction. - flag --dry-run type=bool default="false" usage="Show what would be synced without making changes" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." - flag --prefer-github type=bool default="false" usage="On conflict, use GitHub version" - flag --prefer-local type=bool default="false" usage="On conflict, keep local beads version" - flag --prefer-newer type=bool default="false" usage="On conflict, use most recent version (default)" - flag --pull-only type=bool default="false" usage="Only pull issues from GitHub" - flag --push-only type=bool default="false" usage="Only push issues to GitHub" - -bd gitlab - use: "gitlab" - short: "GitLab integration commands" - hidden: false - runnable: false - long: - | Commands for syncing issues between beads and GitLab. - | - | Configuration can be set via 'bd config' or environment variables: - | gitlab.url / GITLAB_URL - GitLab instance URL - | gitlab.token / GITLAB_TOKEN - Personal access token - | gitlab.project_id / GITLAB_PROJECT_ID - Project ID or path - | gitlab.group_id / GITLAB_GROUP_ID - Group ID for group-level sync - | gitlab.default_project_id / GITLAB_DEFAULT_PROJECT_ID - Project for creating issues in group mode - -bd gitlab projects - use: "projects" - short: "List accessible GitLab projects" - hidden: false - runnable: true - long: - | List GitLab projects that the configured token has access to. - -bd gitlab pull - use: "pull [refs...]" - short: "Pull specific items from GitLab" - hidden: false - runnable: true - long: - | Pull one or more items from GitLab. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd gitlab sync --pull-only --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - -bd gitlab push - use: "push [bead-ids...]" - short: "Push specific beads to GitLab" - hidden: false - runnable: true - long: - | Push one or more beads issues to GitLab. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd gitlab sync --push-only --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd gitlab status - use: "status" - short: "Show GitLab sync status" - hidden: false - runnable: true - long: - | Display current GitLab configuration and sync status. - -bd gitlab sync - use: "sync" - short: "Sync issues with GitLab" - hidden: false - runnable: true - long: - | Synchronize issues between beads and GitLab. - | - | By default, performs bidirectional sync: - | - Pulls new/updated issues from GitLab to beads - | - Pushes local beads issues to GitLab - | - | Use --pull-only or --push-only to limit direction. - flag --assignee type=string default="" usage="Filter by assignee username" - flag --dry-run type=bool default="false" usage="Show what would be synced without making changes" - flag --exclude-type type=string default="" usage="Exclude these issue types from sync (comma-separated)" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --label type=string default="" usage="Filter by labels (comma-separated, AND logic)" - flag --milestone type=string default="" usage="Filter by milestone title" - flag --no-ephemeral type=bool default="true" usage="Exclude ephemeral/wisp issues from push (default: true)" - flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." - flag --prefer-gitlab type=bool default="false" usage="On conflict, use GitLab version" - flag --prefer-local type=bool default="false" usage="On conflict, keep local beads version" - flag --prefer-newer type=bool default="false" usage="On conflict, use most recent version (default)" - flag --project type=string default="" usage="Filter to issues from this project ID (group mode)" - flag --pull-only type=bool default="false" usage="Only pull issues from GitLab" - flag --push-only type=bool default="false" usage="Only push issues to GitLab" - flag --type type=string default="" usage="Only sync these issue types (comma-separated, e.g. 'epic,feature,task')" - -bd graph - use: "graph [issue-id]" - short: "Display issue dependency graph" - group: "deps" - hidden: false - runnable: true - long: - | Display a visualization of an issue's dependency graph. - | - | For epics, shows all children and their dependencies. - | For regular issues, shows the issue and its direct dependencies. - | - | With --all, shows all open issues grouped by connected component. - | With --open, filters to only open/actionable issues (compact layer format). - | - | Display formats: - | (default) DAG with columns and box-drawing edges (terminal-native) - | --box ASCII boxes showing layers, more detailed - | --compact Tree format, one line per issue, more scannable - | --dot Graphviz DOT format (pipe to dot -Tsvg > graph.svg) - | --html Self-contained interactive HTML with D3.js visualization - | --open Open issues only, compact layers (LLM-friendly) - | - | The graph shows execution order: - | - Layer 0 / leftmost = no dependencies (can start immediately) - | - Higher layers depend on lower layers - | - Nodes in the same layer can run in parallel - | - | Status icons: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred - | - | Examples: - | bd graph issue-id # Terminal DAG visualization (default) - | bd graph --box issue-id # ASCII boxes with layer grouping - | bd graph --dot issue-id | dot -Tsvg > graph.svg # SVG via Graphviz - | bd graph --dot issue-id | dot -Tpng > graph.png # PNG via Graphviz - | bd graph --html issue-id > graph.html # Interactive browser view - | bd graph --all --html > all.html # All issues, interactive - | bd graph --open issue-id # Open issues only, layered by blocking order - | bd graph --all --open # All open issues, compact layers - | - | --max-rows / BEADS_MAX_ROWS caveat: the cap is checked differently per mode. - | Single-issue graphs (no --all) check the connected-component node count - | after the BFS traversal completes — the whole subgraph is always walked - | first, then rejected if it's over cap. --all checks each status - | (open/in_progress/blocked) independently, so up to 3x the cap can be loaded - | in total before any individual status trips it. - flag --all type=bool default="false" usage="Show graph for all open issues" - flag --box type=bool default="false" usage="ASCII boxes showing layers" - flag --compact type=bool default="false" usage="Tree format, one line per issue, more scannable" - flag --dot type=bool default="false" usage="Output Graphviz DOT format (pipe to: dot -Tsvg > graph.svg)" - flag --html type=bool default="false" usage="Output self-contained interactive HTML (redirect to file)" - flag --max-rows type=int default="0" usage="Hard upper bound on rows fetched from storage. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Not supported under --proxied-server: an explicit --max-rows or BEADS_MAX_ROWS cap errors out rather than silently going unenforced." - flag --open type=bool default="false" usage="Show only open issues (filters out closed/deferred), forces compact layer format" - -bd graph check - use: "check" - short: "Check dependency graph integrity" - hidden: false - runnable: true - long: - | Check the dependency graph for cycles, orphans, and other integrity issues. - | - | Returns exit code 0 if the graph is clean, 1 if issues are found. - -bd heartbeat - use: "heartbeat " - aliases: ["hb"] - short: "Refresh the lease on an issue you hold in_progress" - group: "issues" - hidden: false - runnable: true - long: - | Refresh the lease on an issue you currently hold in_progress. - | - | A claim carries a lease that expires after a TTL. A worker keeps its claim alive - | by heartbeating faster than the TTL; once it stops (because it died), the lease - | goes stale and 'bd reclaim' reverts the issue to ready so another worker can pick - | it up. Heartbeat pushes lease_expires_at forward and stamps heartbeat_at = now. - | - | Only the current owner may heartbeat. If the lease has already been reclaimed or - | the issue closed, heartbeat fails so the worker learns to stop. - | - | Leases live in an ephemeral, node-local table: a heartbeat that refreshes your - | lease writes no Dolt commit and no history, so any cadence comfortably below - | the TTL is fine. Only a re-arm (the first heartbeat of a claim that has no - | lease, such as one set by a plain update) is recorded as a change to the issue - | and committed, once. Leases are only enforceable on the node that granted them; - | cross-machine claim visibility rides the issue's status and assignee, which do - | commit. - | - | Examples: - | bd heartbeat bd-123 - | bd hb bd-123 - -bd help - use: "help [command]" - short: "Help about any command" - hidden: false - runnable: true - long: - | Help provides help for any command in the application. - | Simply type bd help [path to command] for full details. - flag --all type=bool default="false" usage="Show help for all commands in a single document" - flag --doc type=string default="" usage="Generate markdown docs for a single command" - flag --docs-root type=string default="" usage="Generate repository CLI docs under this root" - flag --list type=bool default="false" usage="List all available commands" - -bd history - use: "history " - short: "Show version history for an issue" - group: "views" - hidden: false - runnable: true - long: - | Show the complete version history of an issue, including all commits - | where the issue was modified. - | - | Examples: - | bd history bd-123 # Show all history for issue bd-123 - | bd history bd-123 --limit 5 # Show last 5 changes - | bd history bd-123 --events # Show database audit events - flag --events type=bool default="false" usage="Show database audit events instead of commit snapshots" - flag --limit type=int default="0" usage="Limit number of history entries (0 = all)" - -bd hooks - use: "hooks" - short: "Manage git hooks for beads integration" - group: "setup" - hidden: false - runnable: false - long: - | Install, uninstall, or list git hooks for beads integration. - | - | The hooks provide: - | - pre-commit: Run chained hooks before commit - | - post-merge: Run chained hooks after pull/merge - | - pre-push: Run chained hooks before push - | - post-checkout: Run chained hooks after branch checkout - | - prepare-commit-msg: Add agent identity trailers for forensics - -bd hooks install - use: "install" - short: "Install bd git hooks" - hidden: false - runnable: true - long: - | Install git hooks for beads integration. - | - | By default, hooks are installed to .git/hooks/ in the current repository. - | Use --beads to install to .beads/hooks/ (recommended for Dolt backend). - | Use --shared to install to a versioned directory (.beads-hooks/) that can be - | committed to git and shared with team members. - | - | Hooks use section markers to coexist with existing hooks — any user content - | outside the markers is preserved across installs and upgrades. - | - | Installed hooks: - | - pre-commit: Run chained hooks before commit - | - post-merge: Run chained hooks after pull/merge - | - pre-push: Run chained hooks before push - | - post-checkout: Run chained hooks after branch checkout - | - prepare-commit-msg: Add agent identity trailers (for orchestrator agents) - flag --beads type=bool default="false" usage="Install hooks to .beads/hooks/ (recommended for Dolt backend)" - flag --chain type=bool default="false" usage="No-op, kept for compatibility (existing hook content always runs alongside the bd section)" - flag --force type=bool default="false" usage="No-op, kept for compatibility (section markers always preserve non-bd content)" - flag --shared type=bool default="false" usage="Install hooks to .beads-hooks/ (versioned) instead of .git/hooks/" - -bd hooks list - use: "list" - short: "List installed git hooks status" - hidden: false - runnable: true - long: - | Show the status of bd git hooks (installed, outdated, missing). - -bd hooks run - use: "run [args...]" - short: "Execute a git hook (called by thin shims)" - hidden: false - runnable: true - long: - | Execute the logic for a git hook. This command is typically called by - | thin shim scripts installed in .git/hooks/. - | - | Supported hooks: - | - pre-commit: Run chained hooks before commit - | - post-merge: Run chained hooks after pull/merge - | - pre-push: Run chained hooks before push - | - post-checkout: Run chained hooks after branch checkout - | - prepare-commit-msg: Add agent identity trailers for forensics - | - | The thin shim keeps delegated hook logic in sync with the installed bd - | version. Upgrading bd updates that delegated behavior. To adopt changes to the - | shim's generated shell policy, refresh it with 'bd hooks install'. - -bd hooks uninstall - use: "uninstall" - short: "Uninstall bd git hooks" - hidden: false - runnable: true - long: - | Remove bd git hooks from .git/hooks/ directory. - -bd human - use: "human" - short: "Show essential commands for human users" - group: "setup" - hidden: false - runnable: true - 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 Respond to a human-needed bead (adds comment and closes) - | human dismiss Dismiss a human-needed bead permanently - | human stats Show summary statistics for human-needed beads - -bd human dismiss - use: "dismiss [reason...]" - short: "Dismiss a human-needed bead" - hidden: false - runnable: true - 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" - flag --reason type=string default="" usage="Reason for dismissal (optional)" - -bd human list - use: "list" - short: "List human-needed beads" - hidden: false - runnable: true - 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 - flag --status -s type=string default="" usage="Filter by status (open, closed, etc.; comma-separated for multiple, 'all' for every status)" - -bd human respond - use: "respond [response...]" - short: "Respond to a human-needed bead" - hidden: false - runnable: true - 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 - flag --file type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin file response"]} usage="Read response text from file" - flag --response -r type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin file response"]} usage="Response text" - flag --stdin type=bool default="false" annotations={cobra_annotation_mutually_exclusive=["stdin file response"]} usage="Read response text from stdin" - -bd human stats - use: "stats" - short: "Show summary statistics for human-needed beads" - hidden: false - runnable: true - 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 - -bd import - use: "import [file|-]" - short: "Import issues from a JSONL file or stdin into the database" - group: "sync" - hidden: false - runnable: true - long: - | Import issues from a JSONL file (newline-delimited JSON) into the database. - | - | If no file is specified, imports from the configured import.path under .beads/ - | (default: issues.jsonl). Use "-" to read from stdin; redirecting stdin without - | "-" or a file argument is an error, so a typo'd 'bd import < file' cannot - | silently import the default file instead. This is the incremental counterpart to - | 'bd export': new issues are created and existing issues are updated (upsert - | semantics). - | - | Memory records (lines with "_type":"memory") are automatically detected and - | imported as persistent memories (equivalent to 'bd remember'). This makes - | 'bd export | bd import' a full round-trip for both issues and memories. - | - | Each JSONL line should map to an issue. The importer accepts every field - | 'bd export' emits — see 'bd export' output for the canonical schema. Only - | "title" is required; everything else is optional. - | - | Common fields: - | title Required. Short summary. - | description Long-form body. - | design, notes, Additional content sections. - | acceptance_criteria - | issue_type bug | feature | task | epic | chore | ... - | priority 0-4 (0 = critical). 0 is preserved (no omitempty). - | status open | in_progress | blocked | closed | ... - | (rows with status "tombstone" are skipped) - | assignee, owner, Ownership metadata. - | created_by - | labels Array of strings. - | dependencies Array of {issue_id, depends_on_id, type, ...}. - | comments Array of comment objects. - | external_ref, Cross-system identifiers (e.g. "gh-9"). - | source_system - | due_at, defer_until RFC3339 timestamps for scheduling. - | metadata Arbitrary JSON object preserved verbatim. - | - | Timestamps (created_at, updated_at, started_at, closed_at) are preserved - | when present in the JSONL and otherwise filled in by the importer. The - | legacy "wisp" boolean is accepted as an alias for "ephemeral". - | - | By default a row only rewrites an existing local issue when its - | updated_at is strictly newer. Older rows are skipped (reported as - | stale_skipped_ids) and rows with the same updated_at keep every local - | column — updated_at has second granularity, so a timestamp tie can be - | two distinct same-second updates, and the local row wins the tie - | (reported as tie_kept_local_ids; the row's labels/comments/dependencies - | still merge). The guard is also enforced inside the upsert itself, so a - | local update that lands while the import is running is preserved rather - | than overwritten. Existing issues that the import did rewrite are listed - | with a field-level summary (updated_issues), so local state changed by - | an import is visible. To deliberately restore an older snapshot, pass - | --allow-stale, which imports every row even when it overwrites newer - | local state. - | - | The staleness guard is import's ONLY overwrite guard: the per-field - | fences that bd update enforces (notes overwrite, live-claim reassign, - | close policy) do not apply to imported rows. Import replaces rows - | wholesale by design — a restore must not fail field-by-field — so - | --allow-stale is the single deliberate-overwrite opt-in, and - | updated_issues is where to look for what an import rewrote. - | - | Large imports are written in bounded transactions (a few hundred issues - | each, with a short pause between commits) with progress on stderr, so - | concurrent bd commands keep working while the import runs instead of - | stalling on one batch-wide write lock. Rows land in dependency order - | with their blocking edges in the same transaction, so a half-finished - | import never shows a blocked issue as ready. If an import fails partway, - | the already-committed chunks are durable and the command exits nonzero; - | re-running the same import is safe and converges (rows upsert, - | labels/comments/dependencies deduplicate). - | - | EXAMPLES: - | bd import # Import from configured import.path - | bd import backup.jsonl # Import from a specific file - | bd import -i backup.jsonl # Legacy alias for a specific file - | bd import - # Read JSONL from stdin - | cat issues.jsonl | bd import - # Pipe JSONL from another tool - | bd import --dry-run # Show what would be imported - | bd import --dedup # Skip issues with duplicate titles - | bd import --allow-stale old.jsonl # Restore an older snapshot (overwrites newer local rows) - | bd import --json # Structured output with created and skipped IDs - flag --allow-stale type=bool default="false" usage="Import rows even when older than the local issue (required to restore an older snapshot)" - flag --dedup type=bool default="false" usage="Skip lines whose title matches an existing open issue" - flag --dry-run type=bool default="false" usage="Show what would be imported without importing" - flag --input -i type=string default="" usage="Read JSONL from a specific file" - -bd info - use: "info" - short: "Show database information" - group: "setup" - hidden: false - runnable: true - long: - | Display information about the current database. - | - | This command helps debug issues where bd is using an unexpected database. It shows: - | - The absolute path to the database file - | - Database statistics (issue count) - | - Schema information (with --schema flag) - | - What's new in recent versions (with --whats-new flag) - | - | Examples: - | bd info - | bd info --json - | bd info --schema --json - | bd info --whats-new - | bd info --whats-new --json - | bd info --thanks - flag --schema type=bool default="false" usage="Include schema information in output" - flag --thanks type=bool default="false" usage="Show thank you page for contributors" - flag --whats-new type=bool default="false" usage="Show agent-relevant changes from recent versions" - -bd init - use: "init" - short: "Initialize bd in the current directory" - group: "setup" - hidden: false - runnable: true - long: - | Initialize bd in the current directory by creating a .beads/ directory - | and its storage (a Dolt database by default). Optionally specify a custom issue prefix. - | - | Dolt is the default and only supported storage backend, with full version - | control (history, branching, sync). - | - | Use --database to specify an existing server database name, overriding the - | default prefix-based naming. This is useful when an external tool (e.g. an orchestrator) - | has already created the database. - | - | With --stealth: configures per-repository git settings for invisible beads usage: - | • .git/info/exclude to prevent beads files from being committed - | Perfect for personal use without affecting repo collaborators. - | To set up a specific AI tool, run: bd setup --stealth - | - | By default, beads uses an embedded Dolt engine (no external server needed). - | Pass --server to use an external dolt sql-server instead. In server mode, - | set connection details with --server-host, --server-port, and --server-user. - | Password should be set via BEADS_DOLT_PASSWORD environment variable. - | - | Auto-export is optional. When enabled, bd exports issues to - | .beads/issues.jsonl after write commands (throttled to once per 60s). This is - | for viewers (bv), interchange, and issue-level migration; not backup. - | Cross-machine sync and backups use Dolt remotes/backups, not JSONL import/export. - | To enable: bd config set export.auto true - | - | Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): - | Skips all interactive prompts, using sensible defaults: - | • Role defaults to "maintainer" (override with --role) - | • Fork exclude auto-configured when fork detected - | • Auto-export left at default (disabled) - | • --contributor and --team flags are rejected (wizards require interaction) - | Also auto-detected when stdin is not a terminal or CI=true is set. - flag --agents-file type=string default="" usage="Custom filename for agent instructions (default: AGENTS.md)" - flag --agents-profile type=string default="" usage="AGENTS.md profile: 'minimal' (default, pointer to bd prime) or 'full' (complete command reference)" - flag --agents-template type=string default="" usage="Path to custom AGENTS.md template (overrides embedded default)" - flag --backend type=string default="" usage="Storage backend: dolt (default). Removed backends (postgres, mysql, sqlite) print migration guidance." - flag --contributor type=bool default="false" usage="Run OSS contributor setup wizard" - flag --debug type=bool default="false" usage="Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers." - flag --destroy-token type=string default="" usage="Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-')" - flag --discard-remote type=bool default="false" usage="Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'." - flag --external type=bool default="false" usage="Server is externally managed (skip server startup); use with --shared-server or --server" - flag --force type=bool default="false" usage="Deprecated alias for --reinit-local. Bypasses only the LOCAL data-safety guard; does NOT authorize remote divergence or recreating a missing server-mode database (see 'bd help init-safety')." - flag --from-jsonl type=bool default="false" usage="Import issues from configured import.path; refuses remote history unless --discard-remote authorizes replacement" - flag --init-if-missing type=bool default="false" usage="If the workspace is already initialized, skip init and exit 0 instead of failing (idempotent init for scaffolds)" - flag --mysql-database type=string default="" hidden usage="Legacy MySQL database (removed backend compatibility only)" - flag --mysql-url type=string default="" hidden usage="Legacy MySQL connection URL (removed backend compatibility only)" - flag --non-interactive type=bool default="false" usage="Skip all interactive prompts (auto-detected in CI or non-TTY environments)" - flag --pg-schema type=string default="" hidden usage="Legacy PostgreSQL schema (removed backend compatibility only)" - flag --pg-url type=string default="" hidden usage="Legacy PostgreSQL connection URL (removed backend compatibility only)" - flag --prefix -p type=string default="" usage="Issue prefix (default: current directory name)" - flag --proxied-server type=bool default="false" usage="[EXPERIMENTAL] Use a per-workspace proxied dolt sql-server (proxy + child dolt) rooted at .beads/dolt" - flag --proxied-server-config-path type=string default="" usage="[EXPERIMENTAL] Absolute path to an existing dolt sql-server YAML config (proxied-server mode only). When set, bd uses this file instead of auto-generating one. Relative paths are rejected. Managed mode requires listener.host to be a numeric loopback IP (hostnames including localhost, non-loopback addresses, listener.socket, remotesapi, and cluster config are rejected); the same policy applies to BEADS_PROXIED_SERVER_CONFIG." - flag --proxied-server-external-host type=string default="" usage="[EXPERIMENTAL] Hostname or IP of an externally-managed dolt sql-server the proxy should front (proxied-server mode only). Mutually exclusive with --proxied-server-external-socket-path." - flag --proxied-server-external-keep-alive type=duration default="0s" usage="[EXPERIMENTAL] TCP keepalive period for the proxy→external connection. Zero uses the package default (30s)." - flag --proxied-server-external-port type=int default="0" usage="[EXPERIMENTAL] TCP port of the externally-managed dolt sql-server (proxied-server mode only). Required when --proxied-server-external-host is set." - flag --proxied-server-external-socket-path type=string default="" usage="[EXPERIMENTAL] Absolute unix socket path of the externally-managed dolt sql-server (proxied-server mode only). Mutually exclusive with --proxied-server-external-host. Relative paths are rejected." - flag --proxied-server-external-tls type=bool default="false" usage="[EXPERIMENTAL] Require TLS when connecting to the externally-managed dolt sql-server (proxied-server mode only)." - flag --proxied-server-external-tls-ca-cert-path type=string default="" usage="[EXPERIMENTAL] Absolute path to a CA certificate (PEM) used to verify the externally-managed dolt sql-server. Empty uses the system trust store. Relative paths are rejected." - flag --proxied-server-external-tls-cert-path type=string default="" usage="[EXPERIMENTAL] Absolute path to a client TLS certificate (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-key-path. Relative paths are rejected." - flag --proxied-server-external-tls-key-path type=string default="" usage="[EXPERIMENTAL] Absolute path to the client TLS private key (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-cert-path. Relative paths are rejected." - flag --proxied-server-external-tls-server-name type=string default="" usage="[EXPERIMENTAL] Server name to verify in the external dolt sql-server's TLS certificate. Defaults to the external host. Required with a unix socket unless --proxied-server-external-tls-skip-verify is set." - flag --proxied-server-external-tls-skip-verify type=bool default="false" usage="[EXPERIMENTAL] Skip TLS certificate verification for the external dolt sql-server. Insecure; testing only." - flag --proxied-server-external-user type=string default="" usage="[EXPERIMENTAL] MySQL user for the externally-managed dolt sql-server (proxied-server mode only). Defaults to \"root\" when empty. Password is read at runtime from $BEADS_PROXIED_SERVER_EXTERNAL_PASSWORD and is never persisted to disk." - flag --proxied-server-idle-timeout type=duration default="0s" usage="[EXPERIMENTAL] Idle duration after which the proxy shuts down its loopback listener and backend (proxied-server mode only). Omit for the built-in default (30s); 0 keeps the proxy and backend alive indefinitely; a positive value sets the window." - flag --proxied-server-log-path type=string default="" usage="[EXPERIMENTAL] Absolute path to the proxied dolt sql-server log file (proxied-server mode only). Default: /dolt/server.log. Relative paths are rejected." - flag --proxied-server-port type=int default="0" usage="[EXPERIMENTAL] Fixed TCP port for the proxy's loopback listener (proxied-server mode only). Default 0 = an OS-assigned free port. Startup fails if the port is already in use." - flag --proxied-server-root-path type=string default="" usage="[EXPERIMENTAL] Absolute directory holding the proxied dolt sql-server's lockfiles, pidfiles, and child .dolt repository (proxied-server mode only). Default: /dolt. May not exist yet — bd will create it. Relative paths are rejected." - flag --quiet -q type=bool default="false" usage="Suppress output (quiet mode)" - flag --recreate-missing type=bool default="false" usage="Explicitly authorize creating a fresh, empty database when this project's configured server-mode database is missing or unreachable. Opt-in per invocation only; never implied by --force, config, or env (see 'bd help init-safety')." - flag --reinit-local type=bool default="false" usage="Re-initialize local .beads/ over existing local data. Does NOT authorize remote divergence (see --discard-remote) or recreating a missing server-mode database (see --recreate-missing)." - flag --remote type=string default="" usage="Dolt remote URL to clone from and persist as sync.remote" - flag --role type=string default="" usage="Set beads role without prompting: \"maintainer\" or \"contributor\"" - flag --server type=bool default="false" usage="Use external dolt sql-server instead of embedded engine" - flag --server-host type=string default="" usage="Dolt server host (default: 127.0.0.1)" - flag --server-port type=int default="0" usage="Dolt server port (default: 3307)" - flag --server-socket type=string default="" usage="Unix domain socket path (overrides host/port; pass '' to ignore an ambient BEADS_DOLT_SERVER_SOCKET and use TCP)" - flag --server-tls type=bool default="false" usage="Require TLS for the init-time Dolt server connection (overrides BEADS_DOLT_SERVER_TLS for this run; not persisted - set the env var or credentials file for later commands)" - flag --server-user type=string default="" usage="Dolt server MySQL user (default: root)" - flag --setup-exclude type=bool default="false" usage="Configure .git/info/exclude to keep beads files local (for forks)" - flag --shared-server type=bool default="false" usage="Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)" - flag --skip-agents type=bool default="false" usage="Skip AGENTS.md and Claude/Codex/Cursor setup generation" - flag --skip-hooks type=bool default="false" usage="Skip git hooks installation" - flag --sqlite-path type=string default="" hidden usage="Legacy SQLite database file (removed backend compatibility only)" - flag --stealth type=bool default="false" usage="Enable stealth mode: keep beads files out of git via .git/info/exclude (sets no-git-ops)" - flag --team type=bool default="false" usage="Run team workflow setup wizard" - flag --team-server type=bool default="false" usage="[EXPERIMENTAL] The shared database's schema is managed by beads-team-server (bts): bd never creates the database or runs schema migrations, only verifies the schema version (proxied-server mode only). Not related to --team." - -bd init-safety - use: "init-safety" - short: "Explain bd init flag semantics and the destroy-token format" - hidden: false - runnable: true - long: - | bd init flag safety contract. - | - | Every bd init invocation resolves project_id from exactly one explicitly - | named source (local reinit, remote adoption, or a fresh mint). When the - | source is ambiguous, bd init refuses. - | - | FLAG SURFACE - | - | bd init Mint a new identity. Bootstraps from - | origin if it has refs/dolt/data. - | - | bd init --reinit-local Re-initialize local .beads/ over existing - | local data. Does NOT authorize discarding - | remote history. If origin has Dolt data - | this will refuse — pair with - | --discard-remote to override. Nor does it - | authorize recreating a missing server-mode - | database; that takes --recreate-missing. - | - | bd init --reinit-local \ Discard the remote's Dolt history and - | --discard-remote replace it with the local reinit. First - | bd dolt push after this will be a - | history-replacing force-push. - | - | bd init --force Deprecated alias for --reinit-local, with - | the same limits. Kept working for ≥2 - | releases. - | - | bd init --recreate-missing Authorize creating a fresh, empty database - | when this project's configured server-mode - | database is missing or unreachable. Opt-in - | per invocation only: never implied by - | --force/--reinit-local, config, or env. - | Without it, bd init REFUSES rather than - | silently recreating a lost database as - | empty (be-5up5). First rule out a stopped - | server or a wrong port or data dir, and - | restore if you can; the playbook is - | init-missing-server-db in - | docs/recovery/init-safety.md. Only when - | nothing is recoverable: - | - | bd init --recreate-missing --prefix - | - | bd init --from-jsonl Import from configured import.path. If - | origin has Dolt data, this refuses unless - | --discard-remote authorizes replacing that - | remote history. - | - | ADOPTING A REMOTE - | - | If you want to use the remote's existing history, use: - | - | bd bootstrap - | - | bd init will automatically suggest this when a remote is detected. - | - | DESTROY-TOKEN (non-interactive only) - | - | When running with no TTY (CI, agents, piped input), a destructive - | re-init requires an explicit --destroy-token value. That covers both - | --discard-remote and --reinit-local over existing issues. The token - | format is: - | - | DESTROY- - | - | For example, if your issue prefix is "bd", the token is "DESTROY-bd": - | - | bd init --reinit-local --discard-remote --destroy-token=DESTROY-bd - | - | In interactive (TTY) mode you confirm via a typed prompt instead. The - | token is not echoed by bd's runtime error messages — this is a - | deliberate guard against pattern-matched one-liners (see - | engdocs/adr/0002-init-safety-invariants.md). - | - | EXIT CODES - | - | 10 refused: remote has Dolt history and you selected local history - | without --discard-remote - | 11 refused: existing local data and you declined the destroy confirm - | (interactive mode only) - | 12 refused: destructive re-init (--discard-remote, or --reinit-local - | over existing issues) without a valid --destroy-token - | (non-interactive mode); also returned when the interactive - | --discard-remote typed-token confirmation is declined - | 15 refused: run directly in your home directory, which is not itself - | a git repository, with no BEADS_DIR named by the caller - | - | RECOVERY - | - | If you hit a refusal, see docs/recovery/init-safety.md for step-by-step recovery - | playbooks for each exit code. - | - | RE-CLONE GOTCHAS - | - | Setting a damaged or superseded database directory aside by hand, or - | relying on a fresh clone right away? Two gotchas from live recovery: - | - | Crash-loop: a set-aside store left INSIDE data_dir makes the sql-server - | treat it as a database and crash-loop with "root hash doesn't exist: - | ". Move it OUTSIDE data_dir instead. - | - | Missing tables: a fresh clone lacks clone-local tables (leases, wisps, - | events, ...) until you run "bd migrate schema" (no --force). You'll see - | "table not found: leases" until then; "Schema already at v" after - | running it is expected, not an error. - | - | See docs/recovery/init-safety.md#re-clone-gotchas for full detail. - | - -bd jira - use: "jira" - short: "Jira integration commands" - group: "advanced" - hidden: false - runnable: false - long: - | Synchronize issues between beads and Jira. - | - | Configuration: - | bd config set jira.url "https://company.atlassian.net" - | bd config set jira.project "PROJ" - | bd config set jira.projects "PROJ1,PROJ2" # Multiple projects - | bd config set jira.api_token "YOUR_TOKEN" - | bd config set jira.username "your_email@company.com" # For Jira Cloud - | bd config set jira.push_prefix "hippo" # Only push hippo-* issues to Jira - | bd config set jira.push_prefix "proj1,proj2" # Multiple prefixes (comma-separated) - | - | Environment variables (alternative to config): - | JIRA_API_TOKEN - Jira API token - | JIRA_USERNAME - Jira username/email - | JIRA_PROJECTS - Comma-separated project keys - | - | Examples: - | bd jira sync --pull # Import issues from Jira - | bd jira sync --push # Export issues to Jira - | bd jira sync # Bidirectional sync (pull then push) - | bd jira sync --dry-run # Preview sync without changes - | bd jira status # Show sync status - -bd jira pull - use: "pull [refs...]" - short: "Pull specific items from Jira" - hidden: false - runnable: true - long: - | Pull one or more items from Jira. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd jira sync --pull --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - -bd jira push - use: "push [bead-ids...]" - short: "Push specific beads to Jira" - hidden: false - runnable: true - long: - | Push one or more beads issues to Jira. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd jira sync --push --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd jira status - use: "status" - short: "Show Jira sync status" - hidden: false - runnable: true - long: - | Show the current Jira sync status, including: - | - Last sync timestamp - | - Configuration status - | - Number of issues with Jira links - | - Issues pending push (no external_ref) - -bd jira sync - use: "sync" - short: "Synchronize issues with Jira" - hidden: false - runnable: true - long: - | Synchronize issues between beads and Jira. - | - | Modes: - | --pull Import issues from Jira into beads - | --push Export issues from beads to Jira - | (no flags) Bidirectional sync: pull then push, with conflict resolution - | - | Conflict Resolution: - | By default, newer timestamp wins. Override with: - | --prefer-local Always prefer local beads version - | --prefer-jira Always prefer Jira version - | - | Examples: - | bd jira sync --pull # Import from Jira - | bd jira sync --push --create-only # Push new issues only - | bd jira sync --dry-run # Preview without changes - | bd jira sync --prefer-local # Bidirectional, local wins - flag --create-only type=bool default="false" usage="Only create new issues, don't update existing" - flag --dry-run type=bool default="false" usage="Preview sync without making changes" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." - flag --prefer-jira type=bool default="false" usage="Prefer Jira version on conflicts" - flag --prefer-local type=bool default="false" usage="Prefer local version on conflicts" - flag --project type=stringSlice default="[]" usage="Project key(s) to sync (overrides configured project/projects)" - flag --pull type=bool default="false" usage="Pull issues from Jira" - flag --push type=bool default="false" usage="Push issues to Jira" - flag --state type=string default="all" usage="Issue state to sync: open, closed, all" - -bd kv - use: "kv" - short: "Key-value store commands" - group: "setup" - hidden: false - runnable: false - long: - | Commands for working with the beads key-value store. - | - | The key-value store is useful for storing flags, environment variables, - | or other user-defined data that persists across sessions. - | - | Examples: - | bd kv set mykey myvalue # Set a value - | bd kv get mykey # Get a value - | bd kv clear mykey # Delete a key - | bd kv list # List all key-value pairs - -bd kv clear - use: "clear " - short: "Delete a key-value pair" - hidden: false - runnable: true - long: - | Delete a key from the beads key-value store. - | - | Examples: - | bd kv clear feature_flag - | bd kv clear api_endpoint - -bd kv get - use: "get " - short: "Get a value by key" - hidden: false - runnable: true - long: - | Get a value from the beads key-value store. - | - | Examples: - | bd kv get feature_flag - | bd kv get api_endpoint - -bd kv list - use: "list" - short: "List all key-value pairs" - hidden: false - runnable: true - long: - | List all key-value pairs in the beads key-value store. - | - | With --prefix, list only the keys starting with that prefix. The filter is - | pushed into SQL on stores that support it, so a scoped read of a large kv - | store does not serialize the whole table. - | - | Examples: - | bd kv list - | bd kv list --json - | bd kv list --prefix mail.dog. --json - flag --prefix type=string default="" usage="list only keys starting with this prefix (filtered in SQL where supported)" - -bd kv set - use: "set " - short: "Set a key-value pair" - hidden: false - runnable: true - long: - | Set a key-value pair in the beads key-value store. - | - | This is useful for storing flags, environment variables, or other - | user-defined data that persists across sessions. - | - | Examples: - | bd kv set feature_flag true - | bd kv set api_endpoint https://api.example.com - | bd kv set max_retries 3 - -bd label - use: "label" - short: "Manage issue labels" - group: "issues" - hidden: false - runnable: false - -bd label add - use: "add [issue-id...] [label[,label...]]" - short: "Add one or more labels to one or more issues" - hidden: false - runnable: true - long: - | Add labels to issues. Issue IDs come first; the final argument is the label. Pass multiple labels comma-separated: bd label add bd-123 label1,label2 - -bd label list - use: "list [issue-id]" - short: "List labels for an issue" - hidden: false - runnable: true - -bd label list-all - use: "list-all" - short: "List all unique labels in the database" - hidden: false - runnable: true - -bd label propagate - use: "propagate [parent-id] [label]" - short: "Propagate a label from a parent issue to all its children" - hidden: false - runnable: true - long: - | Push a label from a parent down to all direct children that don't already have it. Useful for applying branch: labels across an epic's subtasks. - -bd label remove - use: "remove [issue-id...] [label[,label...]]" - short: "Remove one or more labels from one or more issues" - hidden: false - runnable: true - long: - | Remove labels from issues. Issue IDs come first; the final argument is the label. Pass multiple labels comma-separated: bd label remove bd-123 label1,label2 - | - | With --prefix, no label argument is needed: every label on the given issue(s) starting with the prefix is removed, e.g. bd label remove bd-123 --prefix pool:refused: - flag --prefix type=string default="" usage="Remove every label matching this prefix instead of an exact label (e.g., 'pool:refused:' removes all pool:refused:* labels). No label positional argument is needed when set. CAUTION: a short prefix removes every match on an issue in a single edit, including labels you may not have meant to touch (e.g. --prefix t removes both 'tier:opus' and 'test-needed') — check `bd label list ` first if unsure. State-dimension labels (e.g. 'launch:', 'scalegate:') should move via `bd set-state` instead, which this flag bypasses without its event-bead audit trail." - -bd label rename - use: "rename " - short: "Rename a label across every issue and wisp that carries it" - hidden: false - runnable: true - long: - | Rename a label everywhere it appears. An issue that already carries the new label keeps it and drops the old one instead of erroring - a merge, reported honestly (the write path measures merged from what the insert actually affected, never from a snapshot check, so its count is correct under concurrent writes). Pass --dry-run to preview the blast radius (a count and the first issues) without writing anything; the preview's merged count is a plain snapshot intersection of two separate reads, so treat it as an estimate, not the number the rename itself will report. - flag --dry-run type=bool default="false" usage="Preview the blast radius without renaming anything (merged count is a snapshot intersection, not authoritative - see --help)" - -bd linear - use: "linear" - short: "Linear integration commands" - group: "advanced" - hidden: false - runnable: false - long: - | Synchronize issues between beads and Linear. - | - | Configuration: - | bd config set linear.api_key "YOUR_API_KEY" - | bd config set linear.team_id "TEAM_ID" - | bd config set linear.team_ids "TEAM_ID1,TEAM_ID2" # Multiple teams (comma-separated) - | bd config set linear.project_id "PROJECT_ID" # Optional: sync only this project - | - | Environment variables (alternative to config): - | LINEAR_API_KEY - Linear API key (for individual developers) - | LINEAR_TEAM_ID - Linear team ID (UUID, singular) - | LINEAR_TEAM_IDS - Linear team IDs (comma-separated UUIDs) - | - | OAuth (for CI workers / automated sync): - | LINEAR_OAUTH_CLIENT_ID - OAuth app client ID - | LINEAR_OAUTH_CLIENT_SECRET - OAuth app client secret - | - | When both OAuth env vars are set, OAuth client_credentials flow is used - | instead of the API key. This allows CI workers to authenticate as an - | application (actor=application) rather than impersonating a user. - | Precedence: OAuth > LINEAR_API_KEY > config file. - | - | Data Mapping (optional, sensible defaults provided): - | Priority mapping (Linear 0-4 to Beads 0-4): - | bd config set linear.priority_map.0 4 # No priority -> Backlog - | bd config set linear.priority_map.1 0 # Urgent -> Critical - | bd config set linear.priority_map.2 1 # High -> High - | bd config set linear.priority_map.3 2 # Medium -> Medium - | bd config set linear.priority_map.4 3 # Low -> Low - | - | State mapping (Linear state type to Beads status): - | bd config set linear.state_map.backlog open - | bd config set linear.state_map.unstarted open - | bd config set linear.state_map.started in_progress - | bd config set linear.state_map.completed closed - | bd config set linear.state_map.canceled closed - | bd config set linear.state_map.my_custom_state in_progress # Custom state names - | - | Label to issue type mapping: - | bd config set linear.label_type_map.bug bug - | bd config set linear.label_type_map.feature feature - | bd config set linear.label_type_map.epic epic - | - | Relation type mapping (Linear relations to Beads dependencies): - | bd config set linear.relation_map.blocks blocks - | bd config set linear.relation_map.blockedBy blocks - | bd config set linear.relation_map.duplicate duplicates - | bd config set linear.relation_map.related related - | - | ID generation (optional, hash IDs to match bd/Jira hash mode): - | bd config set linear.id_mode "hash" # hash (default) - | bd config set linear.hash_length "6" # hash length 3-8 (default: 6) - | - | Examples: - | bd linear sync --pull # Import issues from Linear - | bd linear sync --push # Export issues to Linear - | bd linear sync # Bidirectional sync (pull then push) - | bd linear sync --dry-run # Preview sync without changes - | bd create "Fix login" --external-ref https://linear.app/team/issue/TEAM-123 - | # Link a local issue to an existing Linear issue - | bd linear status # Show sync status - -bd linear pull - use: "pull [refs...]" - short: "Pull specific items from Linear" - hidden: false - runnable: true - long: - | Pull one or more items from Linear. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd linear sync --pull --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - flag --relations type=bool default="false" usage="Import Linear relations as bd dependencies when pulling" - -bd linear push - use: "push [bead-ids...]" - short: "Push specific beads to Linear" - hidden: false - runnable: true - long: - | Push one or more beads issues to Linear. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd linear sync --push --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd linear status - use: "status" - short: "Show Linear sync status" - hidden: false - runnable: true - long: - | Show the current Linear sync status, including: - | - Last sync timestamp - | - Configuration status - | - Number of issues with Linear links - | - Issues pending push (no external_ref) - -bd linear sync - use: "sync" - short: "Synchronize issues with Linear" - hidden: false - runnable: true - long: - | Synchronize issues between beads and Linear. - | - | Modes: - | --pull Import issues from Linear into beads - | --push Export issues from beads to Linear - | --pull-if-stale Pull only if data is stale (skip if fresh) - | (no flags) Bidirectional sync: pull then push, with conflict resolution - | - | Staleness (--pull-if-stale): - | --threshold 20m How old data must be before pulling (default 20m) - | A 5-minute debounce prevents agent loops: if a pull completed within 5 minutes, - | data is always treated as fresh regardless of the threshold. - | - | Team Selection: - | --team ID1,ID2 Override configured team IDs for this sync - | Multiple teams can be configured via linear.team_ids (comma-separated). - | Falls back to linear.team_id for backward compatibility. - | Push requires explicit --team when multiple teams are configured. - | - | Pull Options: - | --milestones Reconstruct Linear project milestones as local epic parents - | - | Type Filtering (--push only): - | --type task,feature Only sync issues of these types - | --exclude-type wisp Exclude issues of these types - | --include-ephemeral Include ephemeral issues (wisps, etc.); default is to exclude - | --parent TICKET Only push this ticket and its descendants - | --relations Import Linear relations as bd dependencies on pull - | - | Persistent push-direction ID filters (workflow artifacts, sandbox beads, etc.): - | bd config set linear.exclude_id_prefix "hw-mol-" - | bd config set linear.exclude_id_patterns "-wisp-,sandbox-,scratch-" - | - | exclude_id_prefix is a single case-sensitive prefix on the bead ID. - | exclude_id_patterns is a comma-separated list of case-sensitive substrings - | (matched anywhere in the ID). Both are combined as a union: a bead - | matching either rule is skipped from push (no create, no update). Beads - | with an existing external_ref that NOW match are silently skipped on - | future syncs; the Linear-side issue persists — archive/delete it manually - | if desired. - | - | Conflict Resolution: - | By default, newer timestamp wins. Override with: - | --prefer-local Always prefer local beads version - | --prefer-linear Always prefer Linear version - | - | Examples: - | bd linear sync --pull # Import from Linear - | bd linear sync --pull-if-stale # Pull only if data is stale - | bd linear sync --pull-if-stale --threshold 5m # Pull if older than 5 minutes - | bd linear sync --pull --relations # Import Linear blocking relations as bd deps - | bd linear sync --push --create-only # Push new issues only - | bd linear sync --push --type=task,feature # Push only tasks and features - | bd linear sync --push --exclude-type=wisp # Push all except wisps - | bd linear sync --push --parent=bd-abc123 # Push one ticket tree - | bd linear sync --dry-run # Preview without changes - | bd linear sync --prefer-local # Bidirectional, local wins - flag --create-only type=bool default="false" usage="Only create new issues, don't update existing" - flag --dry-run type=bool default="false" usage="Preview sync without making changes" - flag --exclude-type type=stringSlice default="[]" usage="Exclude issues of these types (can be repeated)" - flag --include-ephemeral type=bool default="false" usage="Include ephemeral issues (wisps, etc.) when pushing to Linear" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --milestones type=bool default="false" usage="Reconstruct Linear project milestones as local epic parents when pulling" - flag --no-wait type=bool default="false" usage="Fail immediately if another sync is running instead of waiting" - flag --parent type=string default="" usage="Limit push to this beads ticket and its descendants" - flag --prefer-linear type=bool default="false" usage="Prefer Linear version on conflicts" - flag --prefer-local type=bool default="false" usage="Prefer local version on conflicts" - flag --pull type=bool default="false" usage="Pull issues from Linear" - flag --pull-if-stale type=bool default="false" usage="Pull only if Linear data is stale (skip if fresh)" - flag --push type=bool default="false" usage="Push issues to Linear" - flag --relations type=bool default="false" usage="Import Linear relations as bd dependencies when pulling" - flag --state type=string default="all" usage="Issue state to sync: open, closed, all" - flag --team type=stringSlice default="[]" usage="Team ID(s) to sync (overrides configured team_id/team_ids)" - flag --threshold type=duration default="20m0s" usage="Staleness threshold for --pull-if-stale (default 20m)" - flag --type type=stringSlice default="[]" usage="Only sync issues of these types (can be repeated)" - flag --update-refs type=bool default="true" usage="Update external_ref after creating Linear issues" - -bd linear teams - use: "teams" - short: "List available Linear teams" - hidden: false - runnable: true - long: - | List all teams accessible with your Linear API key. - | - | Use this to find the team ID (UUID) needed for configuration. - | - | Example: - | bd linear teams - | bd config set linear.team_id "12345678-1234-1234-1234-123456789abc" - -bd link - use: "link " - short: "Link two issues with a dependency" - group: "issues" - hidden: false - runnable: true - long: - | Link two issues with a dependency. - | - | Shorthand for 'bd dep add '. By default creates a "blocks" - | dependency (id2 blocks id1). Use --type to specify a different relationship. - | - | Examples: - | bd link bd-123 bd-456 # bd-456 blocks bd-123 - | bd link bd-123 bd-456 --type related # bd-123 related to bd-456 - | bd link bd-123 bd-456 --type parent-child - flag --type -t type=string default="blocks" usage="Dependency type (blocks|tracks|related|parent-child|discovered-from)" - -bd lint - use: "lint [issue-id...]" - short: "Check issues for missing template sections" - group: "views" - hidden: false - runnable: true - long: - | Check issues for missing recommended sections based on issue type. - | - | By default, lints all open issues. Specify issue IDs to lint specific issues. - | - | Section requirements by type: - | bug: Steps to Reproduce, Acceptance Criteria - | task: Acceptance Criteria - | feature: Acceptance Criteria - | epic: Success Criteria (or Acceptance Criteria) - | chore: (none) - | - | Additional per-type sections can be required via config; they are ADDITIVE - | to the built-ins above (built-in requirements are never relaxed): - | - | bd config set lint.sections.epic "Standards scorecard, Cost" - | - | Examples: - | bd lint # Lint all open issues - | bd lint bd-abc # Lint specific issue - | bd lint bd-abc bd-def # Lint multiple issues - | bd lint --type bug # Lint only bugs - | bd lint --status all # Lint all issues (including closed) - | - flag --status -s type=string default="" usage="Filter by status (default: open, use 'all' for all)" - flag --type -t type=string default="" usage="Filter by issue type (bug, task, feature, epic, decision, spike, story, chore, milestone)" - -bd list - use: "list" - short: "List issues" - group: "issues" - hidden: false - runnable: true - flag --all type=bool default="false" usage="Show all issues including closed (overrides default filter)" - flag --assignee -a type=string default="" usage="Filter by assignee" - flag --brief type=bool default="false" usage="Omit the free-form text (description, design, acceptance criteria, notes, payload, waiters) from each row. Filters that read those fields, such as --desc-contains, still select on them. An omitted field is indistinguishable from an empty one in --json; fetch a whole issue with bd show." - flag --closed-after type=string default="" usage="Filter issues closed after date (YYYY-MM-DD or RFC3339)" - flag --closed-before type=string default="" usage="Filter issues closed before date (YYYY-MM-DD or RFC3339)" - flag --created-after type=string default="" usage="Filter issues created after date (YYYY-MM-DD or RFC3339)" - flag --created-before type=string default="" usage="Filter issues created before date (YYYY-MM-DD or RFC3339)" - flag --defer-after type=string default="" usage="Filter issues deferred after date (supports relative: +6h, tomorrow)" - flag --defer-before type=string default="" usage="Filter issues deferred before date (supports relative: +6h, tomorrow)" - flag --deferred type=bool default="false" usage="Show only issues with defer_until set" - flag --deps type=string default="" no-opt-default="scheduling" usage="Annotate tree with dependency edges and order siblings by them: 'scheduling' (bare --deps) or 'all'" - flag --desc-contains type=string default="" usage="Filter by description substring (case-insensitive)" - flag --due-after type=string default="" usage="Filter issues due after date (supports relative: +6h, tomorrow)" - flag --due-before type=string default="" usage="Filter issues due before date (supports relative: +6h, tomorrow)" - flag --empty-description type=bool default="false" usage="Filter issues with empty or missing description" - flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" - flag --exclude-type type=stringSlice default="[]" usage="Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)" - flag --external-contains type=string default="" usage="Filter by external ref substring (case-insensitive)" - flag --external-ref type=string default="" usage="Filter by exact external_ref value" - flag --filter-parent type=string default="" hidden usage="Alias for --parent" - flag --flat type=bool default="false" usage="Disable tree format and use legacy flat list output" - flag --format type=string default="" usage="Export the dependency graph of the listed issues: 'digraph' (edge list for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or a Go template rendered once per edge over .IssueID, .DependsOnID, .Type, .Issue, .Dependency. 'json' is the exception and does not export the graph: it is equivalent to --json, which also wins when both flags are given. 'digraph' and templates print nothing when no listed issue depends on another; 'dot' still prints the nodes" - flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" - flag --id type=string default="" usage="Filter by specific issue IDs (comma-separated or repeated, e.g., bd-1,bd-5,bd-10)" - flag --include-comments type=bool default="false" usage="Populate each row's comments field with full comment bodies in JSON output (--json only; costs one query per row that has comments). Without it, a row with comments carries comments_omitted=true, so an absent comments field is never mistaken for having none. Text output is unaffected either way." - flag --include-ephemeral type=bool default="false" usage="Include ephemeral wisp-plane rows in output (normally hidden)" - flag --include-gates type=bool default="false" usage="Include gate issues in output (normally hidden)" - flag --include-infra type=bool default="false" usage="Include infrastructure beads (agent/role/message) in output" - flag --include-templates type=bool default="false" usage="Include template molecules in output" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" - flag --label-pattern type=string default="" usage="Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)" - flag --label-regex type=string default="" usage="Filter by label regex pattern (e.g., 'tech-(debt|legacy)')" - flag --limit -n type=int default="50" usage="Limit results (an explicit --limit always wins, 0 meaning unlimited; otherwise --all is unlimited; otherwise a configured list.limit applies; otherwise unlimited when piped, else 20 in agent mode at a terminal, else 50)" - flag --long type=bool default="false" usage="Show detailed multi-line output for each issue" - flag --max-rows type=int default="0" usage="Hard upper bound on rows returned. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Honored on both the direct and the --proxied-server route." - flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" - flag --mol-type type=string default="" usage="Filter by molecule type: swarm, patrol, or work" - flag --no-assignee type=bool default="false" usage="Filter issues with no assignee" - flag --no-labels type=bool default="false" usage="Filter issues with no labels" - flag --no-pager type=bool default="false" usage="Disable pager output" - flag --no-parent type=bool default="false" usage="Exclude child issues (show only top-level issues)" - flag --no-pinned type=bool default="false" usage="Exclude pinned issues" - flag --notes-contains type=string default="" usage="Filter by notes substring (case-insensitive)" - flag --offset type=int default="0" usage="Skip the first N matching results (0-based). Only supported under --proxied-server." - flag --overdue type=bool default="false" usage="Show only issues with due_at in the past (not closed)" - flag --parent type=string default="" usage="Filter by parent issue ID (shows children of specified issue)" - flag --pinned type=bool default="false" usage="Show only pinned issues" - flag --pretty type=bool default="false" usage="Display issues in a tree format with status/priority symbols" - flag --priority -p type=string default="" usage="Priority (0-4 or P0-P4, 0=highest)" - flag --priority-max type=string default="" usage="Filter by maximum priority (inclusive, 0-4 or P0-P4)" - flag --priority-min type=string default="" usage="Filter by minimum priority (inclusive, 0-4 or P0-P4)" - flag --ready type=bool default="false" usage="Show only ready issues (no active blockers, same semantics as bd ready)" - flag --reverse -r type=bool default="false" usage="Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)" - flag --skip-labels type=bool default="false" usage="Skip label hydration. The labels field in output will be empty regardless of actual labels. Use only when the caller does not depend on label data. Cannot combine with --label, --label-any, --label-pattern, --label-regex, --exclude-label, or --no-labels." - flag --sort type=string default="" usage="Sort by field: priority, created, updated, closed, status, id, title, type, assignee" - flag --spec type=string default="" usage="Filter by spec_id prefix" - flag --state type=string default="" hidden usage="Alias for --status" - flag --status -s type=string default="" usage="Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated or repeated for multiple: --status open,in_progress" - flag --title type=string default="" usage="Filter by title text (case-insensitive substring match)" - flag --title-contains type=string default="" usage="Filter by title substring (case-insensitive)" - flag --tree type=bool default="true" usage="Hierarchical tree format (default: true; use --flat to disable)" - flag --type -t type=string default="" usage="Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate, convoy). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision" - flag --updated-after type=string default="" usage="Filter issues updated after date (YYYY-MM-DD or RFC3339)" - flag --updated-before type=string default="" usage="Filter issues updated before date (YYYY-MM-DD or RFC3339)" - flag --watch -w type=bool default="false" usage="Watch for changes and auto-update display (implies --pretty)" - flag --wisp-type type=string default="" usage="Filter by wisp type: heartbeat, ping, patrol, gc_report, recovery, error, escalation" - -bd mail - use: "mail [subcommand] [args...]" - short: "Delegate to mail provider (e.g., gt mail)" - hidden: false - runnable: true - disable-flag-parsing: true - long: - | Delegates mail operations to an external mail provider. - | - | Agents often type 'bd mail' when working with beads, but mail functionality - | is typically provided by the orchestrator. This command bridges that gap - | by delegating to the configured mail provider. - | - | Configuration (checked in order): - | 1. BEADS_MAIL_DELEGATE or BD_MAIL_DELEGATE environment variable - | 2. 'mail.delegate' config setting (bd config set mail.delegate "gt mail") - | - | Examples: - | # Configure delegation (one-time setup) - | export BEADS_MAIL_DELEGATE="gt mail" - | # or - | bd config set mail.delegate "gt mail" - | - | # Then use bd mail as if it were gt mail - | bd mail inbox # Lists inbox - | bd mail send mayor/ -s "Hi" # Sends mail - | bd mail read msg-123 # Reads a message - -bd memories - use: "memories [search]" - short: "List or search persistent memories" - group: "setup" - hidden: false - runnable: true - long: - | List all memories, or search by keyword. - | - | Examples: - | bd memories # list all memories - | bd memories dolt # search for memories about dolt - | bd memories "race flag" # search for a phrase - -bd merge-slot - use: "merge-slot" - short: "Manage merge-slot gates for serialized conflict resolution" - group: "issues" - hidden: false - runnable: false - long: - | Merge-slot gates serialize conflict resolution in the merge queue. - | - | A merge slot is an exclusive access primitive: only one agent can hold it at a time. - | This prevents "monkey knife fights" where multiple polecats race to resolve conflicts - | and create cascading conflicts. - | - | Each rig has one merge slot bead: -merge-slot (labeled gt:slot). - | The slot uses: - | - status=open: slot is available - | - status=in_progress: slot is held - | - metadata.holder: who currently holds the slot - | - metadata.waiters: priority-ordered queue of waiters - | - | Examples: - | bd merge-slot create # Create merge slot for current rig - | bd merge-slot check # Check if slot is available - | bd merge-slot acquire # Try to acquire the slot - | bd merge-slot release # Release the slot - -bd merge-slot acquire - use: "acquire" - short: "Acquire the merge slot" - hidden: false - runnable: true - long: - | Attempt to acquire the merge slot for exclusive access. - | - | If the slot is available (status=open), it will be acquired: - | - status set to in_progress - | - holder set to the requester - | - | If the slot is held (status=in_progress), the command fails unless - | --wait is passed, which adds the requester to the waiters queue. - | - | Use --holder to specify who is acquiring (default: BEADS_ACTOR env var). - flag --holder type=string default="" usage="Who is acquiring the slot (default: BEADS_ACTOR)" - flag --wait type=bool default="false" usage="Add to waiters list if slot is held" - -bd merge-slot check - use: "check" - short: "Check merge slot availability" - hidden: false - runnable: true - long: - | Check if the merge slot is available or held. - | - | Returns: - | - available: slot can be acquired - | - held by : slot is currently held - | - not found: no merge slot exists for this rig - -bd merge-slot create - use: "create" - short: "Create a merge slot bead for the current rig" - hidden: false - runnable: true - long: - | Create a merge slot bead for serialized conflict resolution. - | - | The slot ID is automatically generated based on the beads prefix (e.g., gt-merge-slot). - | The slot is created with status=open (available). - -bd merge-slot release - use: "release" - short: "Release the merge slot" - hidden: false - runnable: true - long: - | Release the merge slot after conflict resolution is complete. - | - | Sets status back to open and clears the holder field. - | If there are waiters, the highest-priority waiter should then acquire. - flag --holder type=string default="" usage="Who is releasing the slot (for verification)" - -bd metrics - use: "metrics" - short: "Show or change anonymous usage-metrics settings" - hidden: false - runnable: true - long: - | Show whether anonymous usage metrics are on, see exactly what is sent, and - | turn them on or off. - | - | bd shares anonymous usage metrics to learn how people actually use it — just - | which commands get run, plus the bd version and OS platform. That's how we decide - | what to polish next. We never collect your issues, paths, remotes, identity, or - | any user-supplied text. - | - | bd metrics show the current status and what is collected - | bd metrics on turn metrics on - | bd metrics off turn metrics off - | bd metrics example show real examples of the events bd sends - -bd metrics example - use: "example" - short: "Show real examples of the anonymous metrics bd sends" - hidden: false - runnable: true - -bd metrics off - use: "off" - short: "Turn anonymous usage metrics off" - hidden: false - runnable: true - -bd metrics on - use: "on" - short: "Turn anonymous usage metrics on" - hidden: false - runnable: true - -bd migrate - use: "migrate" - short: "Database migration commands" - group: "maint" - hidden: false - runnable: true - long: - | Database migration and data transformation commands. - | - | Without subcommand, checks and updates database metadata to current version. - | - | Subcommands: - | hooks Plan git hook migration to marker-managed format - | issues Move issues between repositories - | schema Apply pending schema migrations (idempotent) - | sync Set up sync.branch workflow for multi-clone setups - | from-server-to-proxied-server [EXPERIMENTAL] Switch server mode to proxied-server mode - | from-proxied-server-to-server [EXPERIMENTAL] Switch proxied-server mode to server mode - | from-shared-server-to-proxied-server [EXPERIMENTAL] Switch shared-server mode to proxied-server mode - | from-proxied-server-to-shared-server [EXPERIMENTAL] Switch proxied-server mode to shared-server mode - | - | On a remote-backed database with pending schema migrations bd refuses to - | migrate in place (#4259): migrating two clones independently forks the schema - | so bd dolt pull can no longer merge — the break is silent and unrecoverable. - | Use --force to confirm you are the single designated migrator, after which you - | should publish the migrated schema with 'bd dolt push'. The env-var equivalent - | BD_ALLOW_REMOTE_MIGRATE=1 remains supported for scripted/CI use. - | - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - flag --force type=bool default="false" usage="Bypass the remote-migrate gate as the single designated migrator (equivalent to BD_ALLOW_REMOTE_MIGRATE=1)" - flag --inspect type=bool default="false" usage="Show migration plan and database state for AI agent analysis" - flag --update-repo-id type=bool default="false" usage="Update repository ID (use after changing git remote)" - flag --yes type=bool default="false" usage="Auto-confirm prompts" - -bd migrate from-proxied-server-to-server - use: "from-proxied-server-to-server" - short: "[EXPERIMENTAL] Switch a proxied-server repo to server mode" - hidden: false - runnable: true - long: - | Switch a repo from proxied-server mode to server mode (bd init --server). - | - | Both modes root their dolt sql-server at the same .beads/dolt directory, so this - | only rewrites .beads/metadata.json (dolt_mode) and removes the proxied-server - | sidecar — no Dolt data is copied or moved. Stop the running proxy first with - | 'bd dolt stop'. - | - | Note: dolt_mode lives in the committed metadata.json, so this change propagates - | to clones on the next push. - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - -bd migrate from-proxied-server-to-shared-server - use: "from-proxied-server-to-shared-server" - short: "[EXPERIMENTAL] Switch a proxied-server repo back to shared-server mode" - hidden: false - runnable: true - long: - | Switch a repo from proxied-server mode back to shared-server mode. - | - | Only applies to a proxied-server repo rooted at the shared dolt directory - | (~/.beads/shared-server/dolt) — the reverse of from-shared-server-to-proxied-server. - | This rewrites .beads/metadata.json (dolt_mode), re-enables dolt.shared-server, and - | removes the proxied-server sidecar; no Dolt data is copied or moved. Stop the - | running proxy first with 'bd dolt stop'. - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - -bd migrate from-server-to-proxied-server - use: "from-server-to-proxied-server" - short: "[EXPERIMENTAL] Switch a server-mode repo to proxied-server mode" - hidden: false - runnable: true - long: - | Switch a repo from server mode (bd init --server) to proxied-server mode. - | - | Both modes root their dolt sql-server at the same .beads/dolt directory, so this - | only rewrites .beads/metadata.json (dolt_mode) and writes the proxied-server - | sidecar — no Dolt data is copied or moved. Stop the running server first with - | 'bd dolt stop'. - | - | Note: dolt_mode lives in the committed metadata.json, so this change propagates - | to clones on the next push. - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - flag --idle-timeout type=duration default="0s" usage="Proxy idle timeout; omit for the 30s default, 0 for indefinite uptime" - -bd migrate from-shared-server-to-proxied-server - use: "from-shared-server-to-proxied-server" - short: "[EXPERIMENTAL] Switch a shared-server repo to proxied-server mode" - hidden: false - runnable: true - long: - | Switch a repo from shared-server mode to proxied-server mode. - | - | The proxied server is rooted at the shared dolt directory - | (~/.beads/shared-server/dolt), so no Dolt data is copied or moved; this rewrites - | .beads/metadata.json (dolt_mode), turns off dolt.shared-server for this repo, and - | writes the proxied-server sidecar. Stop the running shared server first with - | 'bd dolt stop' — note that stops it for every project sharing it. - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - flag --idle-timeout type=duration default="0s" usage="Proxy idle timeout; omit for the 30s default, 0 for indefinite uptime" - -bd migrate hooks - use: "hooks [path]" - short: "Plan or apply git hook migration to marker-managed format" - hidden: false - runnable: true - long: - | Analyze git hook files and sidecar artifacts for migration to marker-managed format. - | - | Modes: - | --dry-run Preview migration operations without changing files - | --apply Apply migration operations - | - | Examples: - | bd migrate hooks --dry-run - | bd migrate hooks --apply - | bd migrate hooks --apply --yes - | bd migrate hooks --dry-run --json - flag --apply type=bool default="false" usage="Apply planned hook migration changes" - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - flag --yes type=bool default="false" usage="Skip confirmation prompt for --apply" - -bd migrate issues - use: "issues" - short: "Move issues between repositories" - hidden: false - runnable: true - long: - | Move issues from one source repository to another with filtering and dependency preservation. - | - | This command updates the source_repo field for selected issues, allowing you to: - | - Move contributor planning issues to upstream repository - | - Reorganize issues across multi-phase repositories - | - Consolidate issues from multiple repos - | - | Examples: - | # Preview migration from planning repo to current repo - | bd migrate-issues --from ~/.beads-planning --to . --dry-run - | - | # Move all open P1 bugs - | bd migrate-issues --from ~/repo1 --to ~/repo2 --priority 1 --type bug --status open - | - | # Move specific issues with their dependencies - | bd migrate-issues --from . --to ~/archive --id bd-abc --id bd-xyz --include closure - | - | # Move issues with label filter - | bd migrate-issues --from . --to ~/feature-work --label frontend --label urgent - flag --dry-run type=bool default="false" usage="Show plan without making changes" - flag --from type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Source repository (required)" - flag --id type=stringSlice default="[]" usage="Specific issue IDs to migrate (can specify multiple)" - flag --ids-file type=string default="" usage="File containing issue IDs (one per line)" - flag --include type=string default="none" usage="Include dependencies: none/upstream/downstream/closure" - flag --label type=stringSlice default="[]" usage="Filter by labels (can specify multiple)" - flag --priority type=int default="-1" usage="Filter by priority (0-4)" - flag --status type=string default="" usage="Filter by status (open/closed/all)" - flag --strict type=bool default="false" usage="Fail on orphaned dependencies or missing repos" - flag --to type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Destination repository (required)" - flag --type type=string default="" usage="Filter by issue type (bug/feature/task/epic/chore/decision)" - flag --within-from-only type=bool default="true" usage="Only include dependencies from source repo" - flag --yes type=bool default="false" usage="Skip confirmation prompt" - -bd migrate legacy-sqlite - use: "legacy-sqlite --source-db PATH --output PATH|-" - short: "Read an authenticated legacy SQLite database as JSONL" - hidden: false - runnable: true - annotations: {bd:skip_store="1"} - flag --output type=string default="" usage="JSONL output path, or - for stdout" - flag --source-db type=string default="" usage="Legacy SQLite database (read-only)" - -bd migrate schema - use: "schema" - short: "Apply pending schema migrations (idempotent)" - hidden: false - runnable: true - long: - | Apply pending schema migrations idempotently. - | - | bd does not apply pending schema migrations to an existing database without - | the operator's consent, and running this command is that consent - | (BD_ALLOW_MIGRATE=1 is the scripted form). On a remote-backed database the - | remote-migrate gate still applies: --force confirms you are the single - | designated migrator. Migrating is one-way: bd releases built for an older - | schema refuse the migrated database. - | - | On an up-to-date database this is a no-op, so it is safe to run in CI, - | release gates, and recovery scenarios. - | - | Example: - | bd migrate schema - | bd migrate schema --json - flag --force type=bool default="false" usage="Bypass the remote-migrate gate as the single designated migrator (equivalent to BD_ALLOW_REMOTE_MIGRATE=1)" - -bd migrate sync - use: "sync " - short: "Set up sync.branch workflow for multi-clone setups" - hidden: false - runnable: true - long: - | Configure separate branch workflow for multi-clone setups. - | - | This sets the sync.branch config value so that issue data is committed - | to a dedicated branch, keeping your main branch clean. - | - | Example: - | bd migrate sync beads-sync - flag --dry-run type=bool default="false" usage="Show what would be done without making changes" - -bd migrate-issues - use: "migrate-issues" - short: "Move issues between repositories" - hidden: true - deprecated: "use 'bd migrate issues' instead (will be removed in v1.0.0)" - runnable: true - long: - | Move issues from one source repository to another with filtering and dependency preservation. - | - | This command updates the source_repo field for selected issues, allowing you to: - | - Move contributor planning issues to upstream repository - | - Reorganize issues across multi-phase repositories - | - Consolidate issues from multiple repos - | - | Examples: - | # Preview migration from planning repo to current repo - | bd migrate-issues --from ~/.beads-planning --to . --dry-run - | - | # Move all open P1 bugs - | bd migrate-issues --from ~/repo1 --to ~/repo2 --priority 1 --type bug --status open - | - | # Move specific issues with their dependencies - | bd migrate-issues --from . --to ~/archive --id bd-abc --id bd-xyz --include closure - | - | # Move issues with label filter - | bd migrate-issues --from . --to ~/feature-work --label frontend --label urgent - flag --dry-run type=bool default="false" usage="Show plan without making changes" - flag --from type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Source repository (required)" - flag --id type=stringSlice default="[]" usage="Specific issue IDs to migrate (can specify multiple)" - flag --ids-file type=string default="" usage="File containing issue IDs (one per line)" - flag --include type=string default="none" usage="Include dependencies: none/upstream/downstream/closure" - flag --label type=stringSlice default="[]" usage="Filter by labels (can specify multiple)" - flag --priority type=int default="-1" usage="Filter by priority (0-4)" - flag --status type=string default="" usage="Filter by status (open/closed/all)" - flag --strict type=bool default="false" usage="Fail on orphaned dependencies or missing repos" - flag --to type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Destination repository (required)" - flag --type type=string default="" usage="Filter by issue type (bug/feature/task/epic/chore/decision)" - flag --within-from-only type=bool default="true" usage="Only include dependencies from source repo" - flag --yes type=bool default="false" usage="Skip confirmation prompt" - -bd migrate-personal - use: "migrate-personal" - short: "Move personal planning issues from the project database to your planning repo" - group: "setup" - hidden: false - runnable: true - long: - | Identify issues you created in the project database and move them to your - | personal planning repository (~/.beads-planning by default). - | - | This is a one-time migration for contributors who created personal planning - | issues before contributor routing was configured. - | - | The command: - | 1. Finds all issues in the project database created by your git identity - | 2. Shows you the list and asks for confirmation - | 3. Moves them to the planning repo configured in routing.contributor - | - | EXAMPLES: - | bd migrate-personal # Interactive: show list and prompt - | bd migrate-personal -y # Non-interactive: skip confirmation - flag --yes -y type=bool default="false" usage="Skip confirmation prompt" - -bd mol - use: "mol" - aliases: ["protomolecule"] - short: "Molecule commands (work templates)" - hidden: false - runnable: false - long: - | Manage molecules - work templates for agent workflows. - | - | Protos are template epics with the "template" label. They define a DAG of work - | that can be spawned to create real issues (molecules). - | - | The molecule metaphor: - | - A proto is an uninstantiated template (reusable work pattern) - | - Spawning creates a molecule (real issues) from the proto - | - Variables ({{key}}) are substituted during spawning - | - Bonding combines protos or molecules into compounds - | - Distilling extracts a proto from an ad-hoc epic - | - | Commands: - | show Show proto/molecule structure and variables - | pour Instantiate proto as persistent mol (liquid phase) - | wisp Instantiate proto as ephemeral wisp (vapor phase) - | bond Polymorphic combine: proto+proto, proto+mol, mol+mol - | squash Condense molecule to digest - | burn Discard wisp - | distill Extract proto from ad-hoc epic - | - | Use "bd formula list" to list available formulas. - -bd mol bond - use: "bond " - aliases: ["fart"] - short: "Bond two protos or molecules together" - hidden: false - runnable: true - long: - | Bond two protos or molecules to create a compound. - | - | The bond command is polymorphic - it handles different operand types: - | - | formula + formula → cook both, compound proto - | formula + proto → cook formula, compound proto - | formula + mol → cook formula, spawn and attach - | proto + proto → compound proto (reusable template) - | proto + mol → spawn proto, attach to molecule - | mol + proto → spawn proto, attach to molecule - | mol + mol → join into compound molecule - | - | Formula names (e.g., mol-polecat-arm) are cooked inline as ephemeral protos. - | This avoids needing pre-cooked proto beads in the database. - | - | Bond types: - | sequential (default) - B runs after A completes - | parallel - B runs alongside A - | conditional - B runs only if A fails - | - | With --ref, the spawned proto arm is nested inside the molecule operand - | rather than ordered against it - whichever side of the bond that is - so a - | sequential --ref arm carries no ordering: it is ready as soon as it is - | spawned. Ordering a nested arm against its own container is unsatisfiable - | in both directions (the arm waits for the molecule to close; the molecule - | cannot close while it holds an open arm). --ref is refused with --type - | conditional, which has no safe degradation - omit --ref to bond a - | conditional arm as a sibling. - | - | Phase control: - | By default, spawned protos follow the target's phase: - | - Attaching to mol (Ephemeral=false) → spawns as persistent (Ephemeral=false) - | - Attaching to ephemeral issue (Ephemeral=true) → spawns as ephemeral (Ephemeral=true) - | - | Override with: - | --pour Force spawn as liquid (persistent, Ephemeral=false) - | --ephemeral Force spawn as vapor (ephemeral, Ephemeral=true, excluded from Dolt sync via dolt_ignore) - | - | Dynamic bonding (Christmas Ornament pattern): - | Use --ref to specify a custom child reference with variable substitution. - | This creates IDs like "parent.child-ref" instead of random hashes. - | - | Example: - | bd mol bond mol-worker-arm bd-patrol --ref arm-{{worker_name}} --var worker_name=ace - | # Creates: bd-patrol.arm-ace (and children like bd-patrol.arm-ace.capture) - | - | Use cases: - | - Found important bug during patrol? Use --pour to persist it - | - Need ephemeral diagnostic on persistent feature? Use --ephemeral - | - Spawning per-worker arms on a patrol? Use --ref for readable IDs - | - | Examples: - | bd mol bond mol-feature mol-deploy # Compound proto - | bd mol bond mol-feature mol-deploy --type parallel # Run in parallel - | bd mol bond mol-feature bd-abc123 # Attach proto to molecule - | bd mol bond bd-abc123 bd-def456 # Join two molecules - | bd mol bond mol-critical-bug wisp-patrol --pour # Persist found bug - | bd mol bond mol-temp-check bd-feature --ephemeral # Ephemeral diagnostic - | bd mol bond mol-arm bd-patrol --ref arm-{{name}} --var name=ace # Dynamic child ID - flag --as type=string default="" usage="Custom title for compound proto (proto+proto only)" - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --ephemeral type=bool default="false" usage="Force spawn as vapor (ephemeral, Ephemeral=true)" - flag --pour type=bool default="false" usage="Force spawn as liquid (persistent, Ephemeral=false)" - flag --ref type=string default="" usage="Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})" - flag --type type=string default="sequential" usage="Bond type: sequential, parallel, or conditional" - flag --var type=stringArray default="[]" usage="Variable substitution for spawned protos (key=value)" - -bd mol burn - use: "burn [molecule-id...]" - short: "Delete a molecule without creating a digest" - hidden: false - runnable: true - long: - | Burn a molecule, deleting it without creating a digest. - | - | Unlike squash (which creates a permanent digest before deletion), burn - | completely removes the molecule with no trace. Use this for: - | - Abandoned patrol cycles - | - Crashed or failed workflows - | - Test/debug molecules you don't want to preserve - | - | The burn operation differs based on molecule phase: - | - Wisp (ephemeral): Direct delete - | - Mol (persistent): Cascade delete (syncs to remotes) - | - | CAUTION: This is a destructive operation. The molecule's data will be - | permanently lost. If you want to preserve a summary, use 'bd mol squash'. - | - | Example: - | bd mol burn bd-abc123 # Delete molecule with no trace - | bd mol burn bd-abc123 --dry-run # Preview what would be deleted - | bd mol burn bd-abc123 --force # Skip confirmation - | bd mol burn bd-a1 bd-b2 bd-c3 # Batch delete multiple wisps - flag --dry-run type=bool default="false" usage="Preview what would be deleted" - flag --force type=bool default="false" usage="Skip confirmation prompt" - flag --yes -y type=bool default="false" hidden usage="Alias for --force (skip confirmation)" - -bd mol current - use: "current [molecule-id]" - short: "Show current position in molecule workflow" - hidden: false - runnable: true - long: - | Show where you are in a molecule workflow. - | - | If molecule-id is given, show status for that molecule. - | If not given, infer from in_progress issues assigned to current agent. - | - | The output shows all steps with status indicators: - | [done] - Step is complete (closed) - | [current] - Step is in_progress (you are here) - | [ready] - Step is ready to start (unblocked) - | [blocked] - Step is blocked by dependencies - | [pending] - Step is waiting - | - | For large molecules (>100 steps), a summary is shown instead. - | Use --limit or --range to view specific steps: - | bd mol current --limit 50 # Show first 50 steps - | bd mol current --range 100-150 # Show steps 100-150 - flag --for type=string default="" usage="Show molecules for a specific agent/assignee" - flag --limit type=int default="0" usage="Maximum number of steps to display (0 = auto, use 'all' threshold)" - flag --range type=string default="" usage="Display specific step range (e.g., '1-50', '100-150')" - -bd mol distill - use: "distill [formula-name]" - short: "Extract a formula from an existing epic" - hidden: false - runnable: true - long: - | Distill a molecule by extracting a reusable formula from an existing epic. - | - | This is the reverse of pour: instead of formula → molecule, it's molecule → formula. - | - | The distill command: - | 1. Loads the existing epic and all its children - | 2. Converts the structure to a .formula.json file - | 3. Replaces concrete values with {{variable}} placeholders (via --var flags) - | - | Use cases: - | - Team develops good workflow organically, wants to reuse it - | - Capture tribal knowledge as executable templates - | - Create starting point for similar future work - | - | Variable syntax (both work - we detect which side is the concrete value): - | --var branch=feature-auth Spawn-style: variable=value (recommended) - | --var feature-auth=branch Substitution-style: value=variable - | - | Output locations (first writable wins): - | 1. /formulas/ (project-level, default) - | 2. /.beads/formulas/ (repo-local formulas) - | 3. ~/.beads/formulas/ (user-level, if project not writable) - | - | Examples: - | bd mol distill bd-o5xe my-workflow - | bd mol distill bd-abc release-workflow --var feature_name=auth-refactor - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --output type=string default="" usage="Output directory for formula file" - flag --var type=stringArray default="[]" usage="Replace value with {{variable}} placeholder (variable=value)" - -bd mol last-activity - use: "last-activity " - short: "Show last activity timestamp for a molecule" - hidden: false - runnable: true - long: - | Show the most recent activity timestamp for a molecule. - | - | Returns the timestamp of the most recent change to any step in the molecule, - | making it easy to detect stale or stuck molecules. - | - | Activity sources: - | step_closed - A step was closed - | step_updated - A step was updated (claimed, edited, etc.) - | molecule_updated - The molecule root itself was updated - | - | Examples: - | bd mol last-activity hq-wisp-0laki - | bd mol last-activity hq-wisp-0laki --json - -bd mol pour - use: "pour " - short: "Instantiate a proto as a persistent mol (solid -> liquid)" - hidden: false - runnable: true - long: - | Pour a proto into a persistent mol - like pouring molten metal into a mold. - | - | This is the chemistry-inspired command for creating PERSISTENT work from templates. - | The resulting mol is stored as persistent beads in the issue database and - | syncs like any other bead (bd dolt push / pull). - | - | Phase transition: Proto (solid) -> pour -> Mol (liquid) - | - | WHEN TO USE POUR vs WISP: - | pour (liquid): Persistent work that needs audit trail - | - Feature implementations spanning multiple sessions - | - Work you may need to reference later - | - Anything worth preserving in git history - | - | wisp (vapor): Ephemeral work that auto-cleans up - | - Release workflows (one-time execution) - | - Operational loops and recurring cycles - | - Health checks and diagnostics - | - Any operational workflow without audit value - | - | TIP: Formulas can specify phase:"vapor" to recommend wisp usage. - | If you pour a vapor-phase formula, you'll get a warning. - | - | Examples: - | bd mol pour mol-feature --var name=auth # Persistent feature work - | bd mol pour mol-review --var pr=123 # Persistent code review - flag --assignee type=string default="" usage="Assign the root issue to this agent/user" - flag --attach type=stringSlice default="[]" usage="Proto to attach after spawning (repeatable)" - flag --attach-type type=string default="sequential" usage="Bond type for attachments: sequential, parallel, or conditional" - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" - -bd mol progress - use: "progress [molecule-id]" - short: "Show molecule progress summary" - hidden: false - runnable: true - long: - | Show efficient progress summary for a molecule. - | - | This command uses indexed queries to count progress without loading all steps, - | making it suitable for very large molecules (millions of steps). - | - | If no molecule-id is given, shows progress for any molecule you're working on. - | - | Output includes: - | - Progress: completed / total (percentage) - | - Current step: the in-progress step (if any) - | - Rate: steps/hour based on closure times - | - ETA: estimated time to completion - | - | Example: - | bd mol progress bd-hanoi-xyz - -bd mol ready - use: "ready --gated" - short: "Find molecules ready for gate-resume dispatch" - hidden: false - runnable: true - long: - | Find molecules where a gate has closed and the workflow is ready to resume. - | - | This command discovers molecules waiting at a gate step where: - | 1. The molecule has a gate bead that blocks a step - | 2. The gate bead is now closed (condition satisfied) - | 3. The blocked step is now ready to proceed - | 4. No agent currently has this molecule hooked - | - | This enables discovery-based resume without explicit waiter tracking. - | The patrol system uses this to find and dispatch gate-ready molecules. - | - | Examples: - | bd mol ready --gated # Find all gate-ready molecules - | bd mol ready --gated --json # JSON output for automation - flag --gated type=bool default="false" usage="Find molecules ready for gate-resume dispatch (always on for this subcommand)" - -bd mol seed - use: "seed " - short: "Verify formula accessibility" - hidden: false - runnable: true - long: - | Verify that a formula is accessible and can be cooked. - | - | The seed command checks formula search paths to ensure a formula exists - | and can be loaded. This is useful for verifying system health before - | attempting to spawn work from a formula. - | - | Formula search paths (checked in order): - | 1. /formulas/ (active project) - | 2. /.beads/formulas/ (repo-local formulas) - | 3. ~/.beads/formulas/ (user level) - | 4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set) - | - | Examples: - | bd mol seed mol-feature # Verify specific formula - | bd mol seed mol-review --var name=test # Verify with variable substitution - flag --var type=stringArray default="[]" usage="Variable substitution for condition filtering (key=value)" - -bd mol show - use: "show " - short: "Show molecule details" - hidden: false - runnable: true - long: - | Show molecule structure and details. - | - | A molecule's steps are the issues linked to its root by parent-child - | dependencies (bd create --parent, bd mol pour); an id that merely looks - | hierarchical, like bd-xyz.4, does not make an issue a step. - | - | The --parallel flag highlights parallelizable steps: - | - Steps with no blocking dependencies can run in parallel - | - Shows which steps are ready to start now - | - Identifies parallel groups (steps that can run concurrently) - | - | Example: - | bd mol show bd-patrol --parallel - flag --parallel -p type=bool default="false" usage="Show parallel step analysis" - -bd mol squash - use: "squash " - short: "Compress molecule execution into a digest" - hidden: false - runnable: true - long: - | Squash a molecule's ephemeral children into a single digest issue. - | - | This command collects all ephemeral child issues of a molecule (Ephemeral=true), - | generates a summary digest, and promotes the wisps to persistent by - | clearing their Wisp flag (or optionally deletes them). - | - | The squash operation: - | 1. Loads the molecule and all its children - | 2. Filters to only wisps (ephemeral issues with Ephemeral=true) - | 3. Generates a digest (summary of work done) - | 4. Creates a permanent digest issue (Ephemeral=false) - | 5. Clears Wisp flag on children (promotes to persistent) - | OR keeps them with --keep-children (default: delete) - | - | AGENT INTEGRATION: - | Use --summary to provide an AI-generated summary. This keeps bd as a pure - | tool - the calling agent (orchestrator worker, Claude Code, etc.) is responsible - | for generating intelligent summaries. Without --summary, a basic concatenation - | of child issue content is used. - | - | This is part of the wisp workflow: spawn creates wisps, - | execution happens, squash compresses the trace into an outcome (digest). - | - | Example: - | bd mol squash bd-abc123 # Squash and promote children - | bd mol squash bd-abc123 --dry-run # Preview what would be squashed - | bd mol squash bd-abc123 --keep-children # Keep wisps after digest - | bd mol squash bd-abc123 --summary "Agent-generated summary of work done" - flag --dry-run type=bool default="false" usage="Preview what would be squashed" - flag --keep-children type=bool default="false" usage="Don't delete ephemeral children after squash" - flag --summary type=string default="" usage="Agent-provided summary (bypasses auto-generation)" - -bd mol stale - use: "stale" - short: "Detect molecules with all children closed but root still open" - hidden: false - runnable: true - long: - | Detect molecules (epics with children) whose children are all closed - | with completing reasons, but the root is still open. - | - | A molecule is considered stale if: - | 1. Every child is closed with a completing reason (not duplicate/wontfix/superseded) - | 2. Root issue is still open - | 3. Not assigned to anyone (optional, use --unassigned) - | 4. Is blocking other work (optional, use --blocking) - | - | Review whether epic scope is actually finished before closing — child - | closure alone does not prove the epic's stated work is done (GH#5026). - | - | Examples: - | bd mol stale # List all stale molecules - | bd mol stale --json # Machine-readable output - | bd mol stale --blocking # Only show those blocking other work - | bd mol stale --unassigned # Only show unassigned molecules - | bd mol stale --all # Include molecules with 0 children - flag --all type=bool default="false" usage="Include molecules with 0 children" - flag --blocking type=bool default="false" usage="Only show molecules blocking other work" - flag --unassigned type=bool default="false" usage="Only show unassigned molecules" - -bd mol wisp - use: "wisp [proto-id]" - short: "Create or manage wisps (ephemeral molecules)" - hidden: false - runnable: true - long: - | Create or manage wisps - EPHEMERAL molecules for operational workflows. - | - | When called with a proto-id argument, creates a wisp from that proto. - | When called with a subcommand (list, gc), manages existing wisps. - | - | Wisps are issues with Ephemeral=true in the main database. They're stored - | locally but NOT synced via git. - | - | WHEN TO USE WISP vs POUR: - | wisp (vapor): Ephemeral work that auto-cleans up - | - Release workflows (one-time execution) - | - Operational loops and recurring cycles - | - Health checks and diagnostics - | - Any operational workflow without audit value - | - | pour (liquid): Persistent work that needs audit trail - | - Feature implementations spanning multiple sessions - | - Work you may need to reference later - | - Anything worth preserving in git history - | - | TIP: Formulas can specify phase:"vapor" to recommend wisp usage. - | If you use pour on a vapor-phase formula, you'll get a warning. - | - | The wisp lifecycle: - | 1. Create: bd mol wisp or bd create --ephemeral - | 2. Execute: Normal bd operations work on wisp issues - | 3. Squash: bd mol squash (clears Ephemeral flag, promotes to persistent) - | 4. Or burn: bd mol burn (deletes without creating digest) - | - | Examples: - | bd mol wisp beads-release --var version=1.0 # Release workflow - | bd mol wisp mol-my-workflow # Ephemeral operational cycle - | bd mol wisp list # List all wisps - | bd mol wisp gc # Garbage collect old wisps - | - | Subcommands: - | list List all wisps in current context - | gc Garbage collect orphaned wisps - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --root-only type=bool default="false" usage="Create only the root issue (no child step issues)" - flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" - -bd mol wisp create - use: "create " - short: "Instantiate a proto as a wisp (solid -> vapor)" - hidden: false - runnable: true - long: - | Create a wisp from a proto - sublimation from solid to vapor. - | - | This is the chemistry-inspired command for creating ephemeral work from templates. - | The resulting wisp is stored in the main database with Ephemeral=true and NOT synced via git. - | - | Phase transition: Proto (solid) -> Wisp (vapor) - | - | Use wisp for: - | - Operational loops and recurring cycles - | - Health checks and monitoring - | - One-shot orchestration runs - | - Routine operations with no audit value - | - | The wisp will: - | - Be stored in main database with Ephemeral=true flag - | - NOT be synced via git - | - Either evaporate (burn) or condense to digest (squash) - | - | Examples: - | bd mol wisp create mol-patrol # Ephemeral patrol cycle - | bd mol wisp create mol-health-check # One-time health check - | bd mol wisp create mol-diagnostics --var target=db # Diagnostic run - flag --dry-run type=bool default="false" usage="Preview what would be created" - flag --root-only type=bool default="false" usage="Create only the root issue (no child step issues)" - flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" - -bd mol wisp gc - use: "gc" - short: "Garbage collect old/abandoned wisps" - hidden: false - runnable: true - long: - | Garbage collect old or abandoned wisps from the database. - | - | A wisp is considered abandoned if: - | - It hasn't been updated in --age duration and is not closed - | - AND it is not live work: blocked steps (waiting on a dependency), pinned - | beads, and any step whose status category is wip (in_progress, blocked, - | hooked) or frozen (deferred, pinned) are never reclaimed by age, no matter - | how long they have been waiting (GH#4394). Custom statuses count by their - | configured category, so only plain open (active) and closed (done) steps - | are age-reclaimable. If the blocked set or the custom-status list cannot be - | read, the GC aborts rather than risk reclaiming live steps. - | - | Wisps that depend on an abandoned wisp are deleted with it, closed ones - | included even without --all, but only if they too haven't been updated in - | --age duration and are not live work. A dependent that is too young is - | spared and loses its edge to the deleted wisp: an open one is collected once - | it ages out, a closed one only by --all, --closed or 'bd purge'. - | - | Abandoned wisps are deleted without creating a digest. Use 'bd mol squash' - | if you want to preserve a summary before garbage collection. - | - | Use --closed to purge ALL closed wisps (regardless of age). This is the - | fastest way to reclaim space from accumulated wisp bloat. Safe by default: - | requires --force to actually delete. - | - | Note: This uses time-based cleanup, appropriate for ephemeral wisps. - | For graph-pressure staleness detection (blocking other work), see 'bd mol stale'. - | - | Examples: - | bd mol wisp gc # Clean abandoned wisps (default: 1h threshold) - | bd mol wisp gc --dry-run # Preview what would be cleaned - | bd mol wisp gc --age 24h # Custom age threshold - | bd mol wisp gc --all # Also clean closed wisps older than threshold - | bd mol wisp gc --closed # Preview closed wisp deletion - | bd mol wisp gc --closed --force # Delete all closed wisps - | bd mol wisp gc --closed --dry-run # Explicit dry-run (same as no --force) - | bd mol wisp gc --exclude-type agent,rig # Protect agent and rig wisps from GC - | bd mol wisp gc --closed --force --exclude-type mol # Delete closed wisps except mol type - flag --age type=string default="1h" usage="Age threshold for abandoned wisp detection" - flag --all type=bool default="false" usage="Also clean closed wisps older than threshold" - flag --closed type=bool default="false" usage="Delete all closed wisps (ignores --age threshold)" - flag --dry-run type=bool default="false" usage="Preview what would be cleaned" - flag --exclude-type type=stringSlice default="[]" usage="Exclude wisps of these types from GC (comma-separated, e.g., agent,rig)" - flag --force -f type=bool default="false" usage="Actually delete (default: preview only)" - -bd mol wisp list - use: "list" - short: "List all wisps in current context" - hidden: false - runnable: true - long: - | List all wisps (ephemeral molecules) in the current context. - | - | Wisps are issues with Ephemeral=true in the main database. They are stored - | locally but not synced via git. - | - | The list shows: - | - ID: Issue ID of the wisp - | - Title: Wisp title - | - Status: Current status (open, in_progress, closed) - | - Started: When the wisp was created - | - Updated: Last modification time - | - | Old wisp detection: - | - Old wisps haven't been updated in 24+ hours - | - Use 'bd mol wisp gc' to clean up old/abandoned wisps - | - | Examples: - | bd mol wisp list # List all wisps - | bd mol wisp list --json # JSON output for programmatic use - | bd mol wisp list --all # Include closed wisps - flag --all type=bool default="false" usage="Include closed wisps" - flag --type type=string default="" usage="Filter by issue type (e.g., agent, task, patrol)" - -bd note - use: "note [text...]" - short: "Append a note to an issue" - group: "issues" - hidden: false - runnable: true - long: - | Append a note to an issue's notes field. - | - | Shorthand for 'bd update --append-notes "text"'. - | - | Examples: - | bd note gt-abc "Fixed the flaky test" - | bd note gt-abc Fixed the flaky test - | echo "note from pipe" | bd note gt-abc --stdin - | bd note gt-abc --file notes.txt - | - | Note: "note" has NO subcommands — it only appends. - | To read notes on an issue, use: bd show - flag --file type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read note text from file" - flag --stdin type=bool default="false" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read note text from stdin" - -bd notion - use: "notion" - short: "Notion integration commands" - hidden: false - runnable: false - long: - | Commands for syncing issues between beads and Notion. - -bd notion connect - use: "connect" - short: "Connect bd to an existing Notion database or data source" - hidden: false - runnable: true - flag --url type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Existing Notion database or data source URL" - -bd notion init - use: "init" - short: "Create a dedicated Beads database in Notion" - hidden: false - runnable: true - flag --parent type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Parent page ID" - flag --title type=string default="Beads Issues" usage="Database title" - -bd notion pull - use: "pull [refs...]" - short: "Pull specific items from Notion" - hidden: false - runnable: true - long: - | Pull one or more items from Notion. - | - | Accepts bead IDs or external references as positional arguments. - | Equivalent to: bd notion sync --pull --issues - flag --dry-run type=bool default="false" usage="Preview pull without making changes" - -bd notion push - use: "push [bead-ids...]" - short: "Push specific beads to Notion" - hidden: false - runnable: true - long: - | Push one or more beads issues to Notion. - | - | Accepts bead IDs as positional arguments. - | Equivalent to: bd notion sync --push --issues - flag --dry-run type=bool default="false" usage="Preview push without making changes" - -bd notion status - use: "status" - short: "Show Notion sync status" - hidden: false - runnable: true - -bd notion sync - use: "sync" - short: "Sync issues with Notion" - hidden: false - runnable: true - long: - | Synchronize issues between beads and Notion. - | - | By default this performs bidirectional sync. Use --pull or --push to limit direction. - flag --create-only type=bool default="false" usage="Only create missing remote pages, do not update existing ones" - flag --dry-run type=bool default="false" usage="Preview changes without making mutations" - flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." - flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." - flag --prefer-local type=bool default="false" usage="On conflict, keep the local beads version" - flag --prefer-notion type=bool default="false" usage="On conflict, use the Notion version" - flag --pull type=bool default="false" usage="Only pull issues from Notion" - flag --push type=bool default="false" usage="Only push issues to Notion" - flag --state type=string default="all" usage="Issue state to sync: open, closed, or all" - -bd onboard - use: "onboard" - short: "Display minimal snippet for agent instructions file" - group: "setup" - hidden: false - runnable: true - long: - | Display a minimal snippet to add to your agent instructions file for bd integration. - | - | By default, the agent instructions file is AGENTS.md. Use 'bd init --agents-file' - | to configure a different filename (e.g. BEADS.md). - | - | This outputs a small (~10 line) snippet that points to 'bd prime' for full - | workflow context. This is the same minimal profile that 'bd init' generates - | by default. This approach: - | - | • Keeps your agent file lean (doesn't bloat with instructions) - | • bd prime provides dynamic, always-current workflow details - | • Hooks auto-inject bd prime at session start - | - | For agents or environments that do not auto-inject hook output, use - | 'bd init --agents-profile=full' to embed the complete command reference. - -bd orphans - use: "orphans" - short: "Identify orphaned issues (referenced in commits but still open)" - hidden: false - runnable: true - long: - | Identify orphaned issues - issues that are referenced in commit messages but remain open or in_progress in the database. - | - | This helps identify work that has been implemented but not formally closed. - | - | Examples: - | bd orphans # Show orphaned issues - | bd orphans --json # Machine-readable output - | bd orphans --details # Show full commit information - | bd orphans --fix # Close orphaned issues with confirmation - | bd orphans --label theme:personal # Only orphans with this label - | bd orphans --label-any theme:personal,theme:ventures # Orphans with either label - flag --details type=bool default="false" usage="Show full commit information" - flag --fix -f type=bool default="false" usage="Close orphaned issues with confirmation" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" - -bd ping - use: "ping" - short: "Check database connectivity" - group: "maint" - hidden: false - runnable: true - long: - | Lightweight health check that confirms bd can reach its database. - | - | Steps: - | 1. Resolve the .beads workspace - | 2. Open the store (embedded or server) - | 3. Run a trivial query (one issue row; a remote backend reads its - | authenticated server context instead) - | 4. Report timing - | - | Exit 0 on success, exit 1 on failure. - | - | Examples: - | bd ping # Quick connectivity check - | bd ping --json # Structured output for automation - -bd preflight - use: "preflight" - short: "Show PR readiness checklist" - group: "maint" - hidden: false - runnable: true - long: - | Display a checklist of common pre-PR checks for contributors. - | - | This command helps catch common issues before pushing to CI: - | - Tests not run locally - | - Lint errors - | - Unformatted Go files - | - .beads/issues.jsonl pollution - | - Stale nix vendorHash - | - Version mismatches - | - | Examples: - | bd preflight # Show checklist - | bd preflight --check # Run checks automatically - | bd preflight --check --json # JSON output for programmatic use - | bd preflight --check --skip-lint # Explicitly skip lint check - | - flag --check type=bool default="false" usage="Run checks automatically" - flag --fix type=bool default="false" usage="Auto-fix issues where possible (vendorHash)" - flag --skip-lint type=bool default="false" usage="Skip lint check explicitly" - -bd prime - use: "prime" - short: "Output AI-optimized workflow context" - group: "setup" - hidden: false - runnable: true - long: - | Output essential Beads workflow context in AI-optimized markdown format. - | - | Automatically detects if MCP server is active and adapts output: - | - MCP mode: Brief workflow reminders (~50 tokens) - | - CLI mode: Full command reference (~1-2k tokens) - | - | Designed for Claude Code, Gemini CLI, and Codex SessionStart hooks to prevent - | agents from forgetting bd workflow after context compaction. - | - | Config options: - | - no-git-ops: When true, outputs stealth mode (no git commands in session close protocol). - | Set via: bd config set no-git-ops true - | Useful when you want to control when commits happen manually. - | - agent.profile: Explicit policy profile for git/commit authority wording - | (conservative | minimal | team-maintainer; default conservative). - | Set via: bd config set agent.profile team-maintainer - | Or per-session: BD_AGENT_PROFILE=team-maintainer (env var takes precedence). - | See docs/getting-started/ide-setup.md#policy-profiles for what each profile means. - | - prime.disabled: When true, bd prime prints nothing, as it does outside a - | workspace (an empty envelope under --hook-json), whatever its other flags. - | For sessions whose host briefs the agent itself but that inherit a - | project's bd prime hook, such as an orchestrator's agent sessions. - | Set per-session: BD_PRIME_DISABLED=true. Or: bd config set prime.disabled true - | - | Workflow customization: - | - Place a PRIME.md file to override the default workflow text. Checked in this - | order, once bd resolves a workspace (outside one, prime emits no content): - | (1) .beads/PRIME.md relative to the current directory (the -C target - | when -C is set); - | (2) PRIME.md in the .beads directory bd resolves for this workspace - | (honors $BEADS_DIR, which -C overrides; a redirected .beads is - | followed); - | (3) the global PRIME.md in bd's user config dir: - | ~/.config/beads/ on Linux ($XDG_CONFIG_HOME/beads/ if set), - | ~/Library/Application Support/beads/ on macOS, - | %AppData%\beads\ on Windows. - | - Persistent memories (from bd remember) are still appended so memory - | injection keeps working under a custom template. - | - Use --export to dump the default content for customization. - | - Use --memories-only for hook contexts that should inject only persistent memories; this returns only the memories section even when a custom PRIME.md is present. - | - Use --no-memories to omit the persistent memories section (useful when the memories section is large and would dominate a context budget). --memories-only takes precedence if both are set. - | - | Memory injection caps: - | Large memory sets can exceed what a session-start hook host will ingest, - | and hosts truncate silently. Cap what prime injects with --max-memories N - | and/or --max-memory-chars N (or the prime.max-memories / - | prime.max-memory-chars config keys; an explicit flag wins, and an explicit - | 0 forces unlimited). Caps apply at whole-memory boundaries, at least one - | memory is always emitted, and a banner ahead of the entries reports how - | many were elided and how to browse the rest with bd memories. - | --max-memory-chars caps the total bytes of the injected memory entries; - | the section header and elision banner are excluded from the budget. - flag --export type=bool default="false" usage="Output default content (ignores PRIME.md override)" - flag --full type=bool default="false" usage="Force full CLI output (ignore MCP detection)" - flag --hook-json type=bool default="false" usage="Wrap output in the SessionStart hook JSON envelope (Claude Code, Gemini CLI, Codex)" - flag --max-memories type=int default="0" usage="Cap injected persistent memories to N entries (0 = unlimited; falls back to the prime.max-memories config key)" - flag --max-memory-chars type=int default="0" usage="Cap the total bytes of injected memory entries, at whole-memory boundaries; section header and banner are not counted (0 = unlimited; falls back to the prime.max-memory-chars config key)" - flag --mcp type=bool default="false" usage="Force MCP mode (minimal output)" - flag --memories-only type=bool default="false" usage="Output only persistent memories for compact hook contexts" - flag --no-memories type=bool default="false" usage="Omit the persistent memories section (ignored when --memories-only is set, which wins)" - flag --stealth type=bool default="false" usage="Stealth mode (no git operations, flush only)" - -bd priority - use: "priority " - short: "Set the priority of an issue" - group: "issues" - hidden: false - runnable: true - long: - | Set the priority of an issue. - | - | Shorthand for 'bd update --priority '. - | - | Priority levels: - | 0 - Critical (security, data loss, broken builds) - | 1 - High (major features, important bugs) - | 2 - Medium (default) - | 3 - Low (polish, optimization) - | 4 - Backlog (future ideas) - | - | Examples: - | bd priority bd-123 0 # Critical - | bd priority bd-123 2 # Medium - -bd promote - use: "promote " - short: "Promote a wisp to a permanent bead" - group: "issues" - hidden: false - runnable: true - long: - | Promote a wisp (ephemeral issue) to a permanent bead. - | - | This copies the issue from the wisps table (dolt_ignored) to the permanent - | issues table (Dolt-versioned), preserving labels, dependencies, events, and - | comments. The original ID is preserved so all links keep working. - | - | A comment is added recording the promotion and optional reason. - | - | Examples: - | bd promote bd-wisp-abc123 - | bd promote bd-wisp-abc123 --reason "Worth tracking long-term" - flag --reason -r type=string default="" usage="Reason for promotion" - -bd provenance - use: "provenance" - short: "Append-only provenance event log" - group: "issues" - hidden: false - runnable: false - long: - | Record and read provenance events: typed bindings from an issue to an - | opaque external artifact (a git SHA, PR, work-id, transcript, or branch). - | - | The log is append-only — there is no update or delete. bd never interprets the - | actor or ref; only kind and ref-kind are structurally validated. Recording is - | idempotent on a deterministic id, so a producer firing twice is harmless. - -bd provenance by-ref - use: "by-ref " - short: "List provenance events bound to a ref" - hidden: false - runnable: true - -bd provenance log - use: "log " - short: "List provenance events for an issue" - hidden: false - runnable: true - flag --kind type=string default="" usage="filter by kind (optional)" - -bd provenance record - use: "record --issue --kind --source " - short: "Record a provenance event (idempotent)" - hidden: false - runnable: true - long: - | Record a provenance event. The event is appended idempotently: a - | deterministic id is computed from source:issue:kind:(ref or --at), so re-running - | the same record is a no-op. - | - | An event recorded without --ref requires --at so the id is caller-owned. - flag --actor type=string default="" usage="opaque actor identifier (optional)" - flag --at type=string default="" usage="event-time as RFC3339 (required for ref-less kinds)" - flag --issue type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="issue id (required)" - flag --kind type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="event kind: cut|claim|suspend|resume|handoff|commit|land|used (required)" - flag --payload type=string default="" usage="opaque payload, e.g. JSON (optional)" - flag --ref type=string default="" usage="opaque external reference, e.g. a SHA or PR url (optional)" - flag --ref-kind type=string default="" usage="ref kind: git-sha|pr|work-id|transcript|branch (optional)" - flag --source type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="producer of the event, e.g. git-hook, orchestrator (required)" - -bd prune - use: "prune" - short: "Delete old closed beads to reclaim space and shrink exports" - group: "maint" - hidden: false - runnable: true - long: - | Permanently delete closed non-ephemeral beads and their associated data. - | - | Use this to trim closed regular beads (tasks, features, bugs, chores, etc.) - | that are no longer useful. The common case is a long-lived repo where - | closed work has piled up and is bloating auto-export or slowing queries. - | - | Requires --older-than or --pattern. The flag is a safety gate — without - | it, a muscle-memory `--force` could wipe every closed bead in the repo. - | Use `--pattern '*'` if you really do want to sweep everything closed. - | - | Deletes: issues, dependencies, labels, events, and comments for matching beads. - | Skips: pinned beads (protected), open/in-progress beads, and ephemeral beads. - | - | Also skips closed beads whose ID appears in the description, notes, or - | comments of any open / in-progress bead. This protects ADR / decision / - | verification trails that downstream beads still cite. Use - | --ignore-references to override (e.g., when bulk-decommissioning a - | retired label across the rig). - | - | To delete closed ephemeral beads (wisps, transient molecules) use - | `bd purge` instead. - | - | For full Dolt storage reclaim after deleting many rows, follow with `bd flatten` - | so history can be collapsed and old chunks can be garbage-collected. - | - | EXAMPLES: - | bd prune --older-than 30d # Preview closed beads >30d old - | bd prune --older-than 30d --force # Delete them - | bd prune --older-than 90d --dry-run # Detailed preview with stats - | bd prune --pattern "*" --force # Delete all closed regular beads - | bd prune --pattern "gm-temp-*" --force # Scope to a pattern - flag --dry-run type=bool default="false" usage="Preview what would be pruned with stats" - flag --force -f type=bool default="false" usage="Actually prune (without this, shows preview)" - flag --ignore-references type=bool default="false" usage="Delete closed beads even when referenced by open beads (use with care; see --help for details)" - flag --older-than type=string default="" usage="Only prune beads closed more than N ago (e.g., 30d, 2w, 60, 36h)" - flag --pattern type=string default="" usage="Only prune beads matching ID glob pattern (e.g., 'gm-old-*')" - -bd purge - use: "purge" - short: "Delete closed ephemeral beads to reclaim space" - group: "maint" - hidden: false - runnable: true - long: - | Permanently delete closed ephemeral beads and their associated data. - | - | Closed ephemeral beads (wisps, transient molecules) accumulate rapidly and - | have no value once closed. This command removes them to reclaim storage. - | - | Deletes: issues, dependencies, labels, events, and comments for matching beads. - | Skips: pinned beads, and closed beads a live bead still depends on through a - | parent-child, tracks or blocks edge (a closed molecule root whose step is open, - | a closed bead a live convoy tracks). Live means any status that is not done. - | - | --wisps-plane selects by storage plane instead: every closed row stored in the - | wisps table, including --no-history beads, which the default ephemeral - | selection leaves to `bd prune`. It reaches durable-tier rows, so it requires - | --older-than or --pattern, like `bd prune`. - | - | --limit N caps one run at N beads, oldest-closed first, so a large backlog can - | be drained in bounded transactions; --json then reports "remaining" and - | "has_more". Loop while has_more is true. - | - | --older-than takes days (7, 7d), weeks (2w) or a duration with hour precision - | (36h, 168h, 90m). - | - | To delete closed non-ephemeral beads (regular tasks, features, bugs, etc.) - | use `bd prune` instead. - | - | For full Dolt storage reclaim after deleting many rows, follow with `bd flatten` - | so history can be collapsed and old chunks can be garbage-collected. - | - | EXAMPLES: - | bd purge # Preview what would be purged - | bd purge --force # Delete all closed ephemeral beads - | bd purge --older-than 7d --force # Only purge items closed 7+ days ago - | bd purge --pattern "*-wisp-*" # Only purge matching ID pattern - | bd purge --older-than 36h --force # Hour precision: closed 36+ hours ago - | bd purge --wisps-plane --older-than 168h --force - | # Every closed wisps-table row, incl. no-history - | bd purge --dry-run # Detailed preview with stats - flag --dry-run type=bool default="false" usage="Preview what would be purged with stats" - flag --force -f type=bool default="false" usage="Actually purge (without this, shows preview)" - flag --limit type=int default="0" usage="Purge at most N beads this run, oldest-closed first (0 = no limit); --json reports remaining/has_more" - flag --older-than type=string default="" usage="Only purge beads closed more than N ago (e.g., 7d, 2w, 30, 36h)" - flag --pattern type=string default="" usage="Only purge beads matching ID glob pattern (e.g., *-wisp-*)" - flag --wisps-plane type=bool default="false" usage="Select every closed row in the wisps table, including --no-history beads (requires --older-than or --pattern)" - -bd q - use: "q [title]" - short: "Quick capture: create issue and output only ID" - group: "issues" - hidden: false - runnable: true - long: - | Quick capture creates an issue and outputs only the issue ID. - | Designed for scripting and AI agent integration. - | - | Example: - | bd q "Fix login bug" # Outputs: bd-a1b2 - | ISSUE=$(bd q "New feature") # Capture ID in variable - | bd q "Task" | xargs bd show # Pipe to other commands - | bd q "Subtask" --parent=bd-a1b2 # Hierarchical child (outputs: bd-a1b2.1) - flag --labels -l type=stringSlice default="[]" usage="Labels" - flag --parent type=string default="" usage="Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')" - flag --priority -p type=string default="2" usage="Priority (0-4 or P0-P4)" - flag --type -t type=string default="task" usage="Issue type" - -bd query - use: "query [expression]" - short: "Query issues using a simple query language" - group: "issues" - hidden: false - runnable: true - long: - | Query issues using a simple query language that supports compound filters, - | boolean operators, and date-relative expressions. - | - | The query language enables complex filtering that would otherwise require - | multiple flags or piping through jq. - | - | Syntax: - | field=value Equality comparison - | field!=value Inequality comparison - | field>value Greater than - | field>=value Greater than or equal - | field1" - | bd query "status=open AND priority<=2 AND updated>7d" - | bd query "(status=open OR status=blocked) AND priority<2" - | bd query "type=bug AND label=urgent" - | bd query "NOT status=closed" - | bd query "assignee=none AND type=task" - | bd query "created>30d AND status!=closed" - | bd query "label=frontend OR label=backend" - | bd query "title=authentication AND priority=0" - flag --all -a type=bool default="false" usage="Include closed issues (default: exclude closed)" - flag --limit -n type=int default="50" usage="Limit results (default: 50, 0 = unlimited)" - flag --long type=bool default="false" usage="Show detailed multi-line output for each issue" - flag --offset type=int default="0" usage="Skip the first N matching results (0-based). Only supported under --proxied-server." - flag --parse-only type=bool default="false" usage="Only parse the query and show the AST (for debugging)" - flag --reverse -r type=bool default="false" usage="Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)" - flag --sort type=string default="" usage="Sort by field: priority, created, updated, closed, status, id, title, type, assignee" - -bd quickstart - use: "quickstart" - short: "Quick start guide for bd" - group: "setup" - hidden: false - runnable: true - long: - | Display a quick start guide showing common bd workflows and patterns. - -bd ready - use: "ready" - short: "Show ready work (open, no active blockers)" - hidden: false - runnable: true - long: - | Show ready work (open issues with no active blockers). - | - | Excludes in_progress, blocked, deferred, and hooked issues. This uses the - | GetReadyWork API which applies blocker-aware semantics to find truly claimable work. - | - | Note: 'bd list --ready' uses the same blocker-aware ready-work semantics. - | - | Use --mol to filter to a specific molecule's steps: - | bd ready --mol bd-patrol # Show ready steps within molecule - | - | Use --gated to find molecules ready for gate-resume dispatch: - | bd ready --gated # Find molecules where a gate closed - | - | Use --claim to atomically claim the first ready issue matching the filters: - | bd ready --claim --json - | - | This is useful for agents executing molecules to see which steps can run next. - flag --assignee -a type=string default="" usage="Filter by assignee" - flag --brief type=bool default="false" usage="Omit the free-form text (description, design, acceptance criteria, notes, payload, waiters) from each row. Filters that read those fields still select on them. An omitted field is indistinguishable from an empty one; fetch a whole issue with bd show. Requires --json, and cannot be combined with --claim, --gated, --mol or --explain." - flag --claim type=bool default="false" usage="Atomically claim the first ready issue matching the filters" - flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" - flag --exclude-type type=stringSlice default="[]" usage="Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)" - flag --explain type=bool default="false" usage="Show dependency-aware reasoning for why issues are ready or blocked" - flag --flat type=bool default="false" usage="Alias for --plain, spelled the way bd list spells it" - flag --gated type=bool default="false" usage="Find molecules ready for gate-resume dispatch" - flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" - flag --include-deferred type=bool default="false" usage="Include issues with future defer_until timestamps" - flag --include-ephemeral type=bool default="false" usage="Include ephemeral issues (wisps) in results" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" - flag --label-pattern type=string default="" usage="Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)" - flag --label-regex type=string default="" usage="Filter by label regex pattern (e.g., 'tech-(debt|legacy)')" - flag --limit -n type=int default="100" usage="Maximum issues to show (use 0 for unlimited)" - flag --max-rows type=int default="0" usage="Hard upper bound on rows fetched from storage. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Not supported under --proxied-server: an explicit --max-rows or BEADS_MAX_ROWS cap errors out rather than silently going unenforced." - flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" - flag --mol type=string default="" usage="Filter to steps within a specific molecule" - flag --mol-type type=string default="" usage="Filter by molecule type: swarm, patrol, or work" - flag --offset type=int default="0" usage="Skip the first N matching results (0-based). Only supported under --proxied-server." - flag --parent type=string default="" usage="Filter to descendants of this bead/epic" - flag --plain type=bool default="false" usage="Display issues as a plain numbered list" - flag --pretty type=bool default="true" usage="Display issues in a tree format with status/priority symbols" - flag --priority -p type=int default="0" usage="Filter by priority" - flag --sort -s type=string default="priority" usage="Sort policy: priority (default), hybrid, oldest" - flag --type -t type=string default="" usage="Filter by issue type (task, bug, feature, epic, decision, merge-request). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision" - flag --unassigned -u type=bool default="false" usage="Show only unassigned issues" - -bd recall - use: "recall " - short: "Retrieve a specific memory" - group: "setup" - hidden: false - runnable: true - long: - | Retrieve the full content of a memory by its key. - | - | Examples: - | bd recall dolt-phantoms - | bd recall auth-jwt - -bd reclaim - use: "reclaim" - short: "Revert stale-lease in_progress issues back to ready (dead-worker recovery)" - group: "issues" - hidden: false - runnable: true - long: - | Revert in_progress issues whose lease has gone stale back to ready. - | - | When a worker claims an issue it takes a lease that expires after a TTL, kept - | alive by 'bd heartbeat'. A worker that dies stops heartbeating, so its lease - | expires and its issue would otherwise stay in_progress forever. reclaim is the - | reaper: it finds in_progress issues whose lease expired more than --older-than - | ago, clears the assignee, and sets them back to open so another worker can - | claim them. The previous owner's stale lease is recorded as a recovery event. - | - | --older-than is a grace window past lease expiry: only leases that expired at - | least this long ago are reclaimed, so a worker briefly paused (GC, clock skew) - | is not robbed of live work. Run it from a supervisor on a timer with a window - | of roughly 2× the claim TTL. - | - | By default reclaim covers every stale lease THIS replica granted. The scope - | filters below narrow it further, using the same label surface claiming is - | scoped by (--label / --label-any / --exclude-label), plus --assignee and --id. - | Filters AND-combine and never widen the set: a reclaimed lease must still be - | stale. - | - | Replicas and leases (federated deployments) - | ------------------------------------------- - | A lease is only meaningful on the replica that granted it. Every other - | replica's view of the holder's liveness is stale by up to one sync interval, - | so a reaper elsewhere can revert a unit that is very much alive over there. - | reclaim therefore records the granting replica on each lease and SKIPS a lease - | another replica granted, summarizing what it declined on stderr (one line per - | run; 'bd -v' expands it to the first 20 leases individually). Reap it where it - | was granted; use --any-replica only when that replica is permanently gone (or - | when this node was renamed and its own old leases now look foreign — an - | ordinary heartbeat keeps a lease alive but does not re-home it to the node - | heartbeating it). Prefer the narrow form '--any-replica --id ': bare - | --any-replica reverts EVERY foreign stale lease, live peers included. - | - | Two invariants the guard cannot enforce for you: - | - | grace window > sync interval, and lease TTL > sync interval. - | - | A TTL or grace shorter than the cadence at which replicas exchange state is - | meaningless across the bridge — the remote view is a full interval old by - | construction. Raise the TTL/grace above the sync interval, never the reverse. - | The guard is opt-in: set BEADS_NODE_ID, or run 'bd config set node_id ' - | (which writes the per-machine ~/.config/bd/config.yaml — never commit a node_id - | to the git-tracked .beads/config.yaml, or every clone reads the same name and - | the guard goes armed-but-inert). One id per STORE, not per host: machines that - | are clients of the same dolt sql-server are ONE replica and must share one value - | or leave it unset. There is no hostname fallback — the hostname names the client - | process's machine, not the store — so an unnamed deployment keeps the old, - | unguarded behavior instead of stranding its own work. - | - | Examples: - | bd reclaim # default grace window (2× the lease TTL) - | bd reclaim --older-than 10m # reclaim leases expired >10m ago - | bd reclaim --older-than 0s # reclaim every currently-expired lease - | bd reclaim --label lane-a # only this machine's claim partition - | bd reclaim --label-any lane-a,lane-b --exclude-label pinned - | bd reclaim --assignee zelda --assignee epona # only these workers' leases - | bd reclaim --id wy-abc --id wy-def # exactly these issues - | bd reclaim --any-replica # also reap leases granted by a departed replica - flag --any-replica type=bool default="false" usage="Also reclaim leases granted by ANOTHER replica (unsafe unless that replica is gone; see 'Replicas and leases')" - flag --assignee -a type=stringSlice default="[]" usage="Only reclaim leases held by these assignees (repeatable)" - flag --exclude-label type=stringSlice default="[]" usage="Never reclaim issues carrying ANY of these labels" - flag --id type=stringSlice default="[]" usage="Only reclaim these issue IDs (repeatable)" - flag --label -l type=stringSlice default="[]" usage="Only reclaim issues with ALL these labels (AND). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Only reclaim issues with AT LEAST ONE of these labels (OR). Can combine with --label" - flag --older-than type=duration default="10m0s" usage="Only reclaim leases that expired at least this long ago (grace window)" - -bd recompute-blocked - use: "recompute-blocked" - short: "Recompute is_blocked for all issues (repairs stale flags after a pull)" - group: "maint" - hidden: false - runnable: true - long: - | Recompute the denormalized is_blocked flag for every issue and wisp. - | - | is_blocked is derived from the dependency graph and maintained automatically by - | local writes and by a post-pull recompute scoped to what the merge changed. If - | that scoped recompute is skipped — a recompute that failed after its merge - | committed, or a conflicted pull resolved by hand — the flag can go stale, and a - | later pull that merges nothing will not refresh it (bd-6dnrw.37). 'bd ready' - | trusts the flag, so stale values silently hide ready work or surface blocked - | work. - | - | This command runs the full recompute unconditionally and commits the result. - | It is idempotent: on a consistent database it changes nothing. Works in every - | storage mode — embedded, server, and proxied-server (unlike 'bd doctor', which - | is server-mode only). - | - | On a workspace connected to a bd serve backend ('bd connect') it is a no-op - | that exits 0: the server maintains is_blocked on every write, and the column - | lives in the server's database, so the repair is run there, by the server's - | operator. --json then reports {"rows_corrected": 0, "maintained_by": "server"}. - | - | Examples: - | bd recompute-blocked # Repair stale is_blocked flags - | bd recompute-blocked --json # Machine-parseable {"rows_corrected": N} - -bd remember - use: "remember \"\"" - short: "Store a persistent memory" - group: "setup" - hidden: false - runnable: true - long: - | Store a memory that persists across sessions and account rotations. - | - | Memories are injected at prime time (bd prime) so you have them - | in every session without manual loading. - | - | The positional arg is the memory CONTENT (the key is auto-generated from it - | unless --key is given). As a convenience, if the arg is a bare key naming an - | existing memory, it is RECALLED instead of stored (same as 'bd recall'); - | a bare key naming nothing is refused. Use --key to store slug-like content. - | - | Corpus budget (opt-in, off by default): set the memories.budget-chars config - | key to a byte ceiling for the whole memory corpus (sum of len(key)+len(content)). - | A write that would cross it is refused, and --force overrides; a write that - | lands at or above 80% of the budget warns. With the key unset nothing changes. - | bd prime's --max-memory-chars also counts bytes, but of each memory as - | injected, formatting included, so a budget equal to that cap does not - | guarantee prime injects every memory; set the budget below it for that. - | - | Examples: - | bd remember "always run tests with -race flag" - | bd remember "Dolt phantom DBs hide in three places" --key dolt-phantoms - | bd remember "auth module uses JWT not sessions" --key auth-jwt - | bd remember dolt-phantoms # bare existing key: reads it (= bd recall) - flag --force type=bool default="false" usage="Store even when the write would cross the memories.budget-chars corpus budget (no effect when the budget is unset)" - flag --key type=string default="" usage="Explicit key for the memory (auto-generated from content if not set). If a memory with this key already exists, it will be updated in place" - -bd rename - use: "rename " - short: "Rename an issue ID" - hidden: false - runnable: true - long: - | Rename an issue from one ID to another. - | - | This updates: - | - The issue's primary ID - | - All references in other issues (descriptions, titles, notes, etc.) - | - Dependencies pointing to/from this issue - | - Labels, comments, and events - | - | Examples: - | bd rename bd-w382l bd-dolt # Rename to memorable ID - | bd rename gt-abc123 gt-auth # Use descriptive ID - | - | Note: The new ID must use a valid prefix for this database. - -bd rename-prefix - use: "rename-prefix " - short: "Rename the issue prefix for all issues in the database" - group: "maint" - hidden: false - runnable: true - long: - | Rename the issue prefix for all issues in the database. - | This will update all issue IDs and all text references across all fields. - | - | USE CASES: - | - Shortening long prefixes (e.g., 'knowledge-work-' → 'kw-') - | - Rebranding project naming conventions - | - Consolidating multiple prefixes after database corruption - | - Migrating to team naming standards - | - | Prefix validation rules: - | - Allowed characters: lowercase letters, numbers, hyphens - | - Must start with a letter - | - Must end with a hyphen (e.g., 'kw-', 'work-') - | - Cannot be empty or just a hyphen - | - | Multiple prefix detection and repair: - | If issues have multiple prefixes (corrupted database), use --repair to consolidate them. - | The --repair flag will rename all issues with incorrect prefixes to the new prefix, - | preserving issues that already have the correct prefix. - | - | EXAMPLES: - | bd rename-prefix kw- # Rename from 'knowledge-work-' to 'kw-' - | bd rename-prefix mtg- --repair # Consolidate multiple prefixes into 'mtg-' - | bd rename-prefix team- --dry-run # Preview changes without applying - | - | NOTE: This is a rare operation. Most users never need this command. - flag --dry-run type=bool default="false" usage="Preview changes without applying them" - flag --repair type=bool default="false" usage="Repair database with multiple prefixes by consolidating them" - -bd reopen - use: "reopen [id...]" - short: "Reopen one or more closed issues" - group: "issues" - hidden: false - runnable: true - long: - | Reopen closed issues by setting status to 'open' and clearing the closed_at timestamp. - | This is more explicit than 'bd update --status open' and emits a Reopened event. - | - | Exit codes: 1 for general failures; 13 when the failure is a stale - | --if-revision guard (the precondition no longer held, nothing was written — - | another actor won the race, so retrying the same guard is pointless). - flag --if-revision type=string default="" usage="Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)." - flag --reason -r type=string default="" usage="Reason for reopening" - -bd repo - use: "repo" - short: "Manage multiple repository configuration" - group: "advanced" - hidden: false - runnable: false - long: - | Configure and manage multiple repository support for multi-repo hydration. - | - | Multi-repo support allows hydrating issues from multiple beads repositories - | into a single database for unified cross-repo issue tracking. - | - | Configuration is stored in .beads/config.yaml under the 'repos' section: - | - | repos: - | primary: "." - | additional: - | - ~/beads-planning - | - ~/work-repo - | - | Examples: - | bd repo add ~/beads-planning # Add planning repo - | bd repo add ../other-repo # Add relative path repo - | bd repo list # Show all configured repos - | bd repo remove ~/beads-planning # Remove by path - | bd repo sync # Sync from all configured repos - -bd repo add - use: "add " - short: "Add an additional repository to sync" - hidden: false - runnable: true - long: - | Add a repository path to the repos.additional list in config.yaml. - | - | The path should point to a directory containing a .beads folder. - | Paths can be absolute or relative (they are stored as-is). - | - | This modifies .beads/config.yaml, which is version-controlled and - | shared across all clones of this repository. - -bd repo list - use: "list" - short: "List all configured repositories" - hidden: false - runnable: true - long: - | List all repositories configured in .beads/config.yaml. - | - | Shows the primary repository (always ".") and any additional - | repositories configured for hydration. - -bd repo remove - use: "remove " - short: "Remove a repository from sync configuration" - hidden: false - runnable: true - long: - | Remove a repository path from the repos.additional list in config.yaml. - | - | The path must exactly match what was added (e.g., if you added "~/foo", - | you must remove "~/foo", not "/home/user/foo"). - | - | This command also removes any previously-hydrated issues from the database - | that came from the removed repository. - -bd repo sync - use: "sync" - short: "Manually trigger multi-repo sync" - hidden: false - runnable: true - long: - | Synchronize issues from all configured additional repositories. - | - | Reads issues.jsonl from each additional repository and imports them into - | the primary database with their original prefixes and source_repo set. - | Uses mtime caching to skip repos whose JSONL hasn't changed. - | - | Also triggers Dolt push/pull if a remote is configured. - flag --verbose type=bool default="false" usage="Show detailed sync progress" - -bd restore - use: "restore " - short: "Restore the pre-compaction content of a compacted issue" - group: "sync" - hidden: false - runnable: true - long: - | Restore the pre-compaction content of a compacted issue. - | - | When an issue is compacted, its description/design/notes/acceptance criteria - | are summarized and the originals are archived to a compaction snapshot. This - | command recovers that original content. - | - | By default it is read-only: it displays the archived content without modifying - | the database. Pass --apply to write the original content back into the issue - | and step its compaction level back down. - | - | If no archived snapshot exists (e.g. the issue was compacted by an older bd - | before snapshot archiving), restore falls back to a best-effort reconstruction - | from Dolt version history, which can only be displayed, not applied. - flag --apply type=bool default="false" usage="Write the restored content back into the issue (default: display only)" - -bd rules - use: "rules" - short: "Audit and compact Claude rules" - group: "maint" - hidden: false - runnable: false - -bd rules audit - use: "audit" - short: "Scan rules for contradictions and merge opportunities" - hidden: false - runnable: true - flag --path type=string default=".claude/rules/" usage="Path to rules directory" - flag --threshold type=float64 default="0.6" usage="Jaccard similarity threshold" - -bd rules compact - use: "compact" - short: "Merge related rules into composites" - hidden: false - runnable: true - flag --auto type=bool default="false" usage="Apply audit suggestions" - flag --dry-run type=bool default="false" usage="Preview without applying" - flag --group type=stringSlice default="[]" usage="Rule names to merge" - flag --path type=string default=".claude/rules/" usage="Path to rules directory" - -bd schema - use: "schema" - short: "Print the JSON Schema for bd's --json / export output" - hidden: false - runnable: true - annotations: {bd:skip_store="1"} - long: - | Print the JSON Schema for bd's canonical output record types. - | - | The schema is reflected from the same Go structs bd serializes, so it stays in - | lockstep with the actual --json / export output. Use it to generate typed - | consumer models (datamodel-code-generator, quicktype, ...) rather than - | hand-maintaining them. - | - | bd schema | jq '.types.issue' # the issue record schema - | bd schema | jq '.types.dependency' # the dependency record schema - -bd search - use: "search [query]" - short: "Search issues by text query" - group: "issues" - hidden: false - runnable: true - long: - | Search issues across title and ID (all statuses, including closed). - | - | ID-like queries (e.g., "bd-123", "hq-319") use fast exact/prefix matching. - | Text queries search titles. Use --desc-contains for description search. - | Use --status open (etc.) to narrow; closed issues are included by default - | so "was this already filed/fixed?" cannot silently answer no. Matches - | beyond --limit are dropped status-blind, so when hunting live work in a - | large DB, narrow with --status open or raise --limit. - | - | Examples: - | bd search "authentication bug" - | bd search "login" --status open - | bd search "database" --label backend --limit 10 - | bd search --query "performance" --assignee alice - | bd search "bd-5q" # Search by partial ID (fast prefix match) - | bd search "security" --priority-min 0 --priority-max 2 - | bd search "bug" --created-after 2025-01-01 - | bd search "refactor" --status open # Only open issues - | bd search "bug" --sort priority - | bd search "task" --sort created --reverse - | bd search "api" --desc-contains "endpoint" - | bd search "cleanup" --no-assignee --no-labels - flag --assignee -a type=string default="" usage="Filter by assignee" - flag --closed-after type=string default="" usage="Filter issues closed after date (YYYY-MM-DD or RFC3339)" - flag --closed-before type=string default="" usage="Filter issues closed before date (YYYY-MM-DD or RFC3339)" - flag --created-after type=string default="" usage="Filter issues created after date (YYYY-MM-DD or RFC3339)" - flag --created-before type=string default="" usage="Filter issues created before date (YYYY-MM-DD or RFC3339)" - flag --desc-contains type=string default="" usage="Filter by description substring (case-insensitive)" - flag --empty-description type=bool default="false" usage="Filter issues with empty or missing description" - flag --external-contains type=string default="" usage="Filter by external ref substring (case-insensitive)" - flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL)" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE)" - flag --limit -n type=int default="50" usage="Limit results (default: 50)" - flag --long type=bool default="false" usage="Show detailed multi-line output for each issue" - flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" - flag --no-assignee type=bool default="false" usage="Filter issues with no assignee" - flag --no-labels type=bool default="false" usage="Filter issues with no labels" - flag --notes-contains type=string default="" usage="Filter by notes substring (case-insensitive)" - flag --priority-max type=string default="" usage="Filter by maximum priority (inclusive, 0-4 or P0-P4)" - flag --priority-min type=string default="" usage="Filter by minimum priority (inclusive, 0-4 or P0-P4)" - flag --query type=string default="" usage="Search query (alternative to positional argument)" - flag --reverse -r type=bool default="false" usage="Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)" - flag --sort type=string default="" usage="Sort by field: priority, created, updated, closed, status, id, title, type, assignee" - flag --status -s type=string default="" usage="Filter by stored status (comma-separated for OR; open, in_progress, blocked, deferred, closed, all). Default searches all statuses including closed. Note: dependency-blocked issues use 'bd blocked'" - flag --type -t type=string default="" usage="Filter by type (bug, feature, task, epic, chore, decision, message, molecule, gate, spike, story, milestone); custom types require types.custom config, and an unknown type is an error. Aliases: feat/enhancement→feature, mol→molecule, dec/adr→decision, mr→merge-request" - flag --updated-after type=string default="" usage="Filter issues updated after date (YYYY-MM-DD or RFC3339)" - flag --updated-before type=string default="" usage="Filter issues updated before date (YYYY-MM-DD or RFC3339)" - -bd send-metrics - use: "send-metrics" - short: "Internal: flush queued telemetry events (spawned by bd)" - hidden: true - runnable: true - -bd serve - use: "serve" - short: "Serve the beads HTTP API over loopback" - hidden: false - runnable: true - long: - | Serve the beads HTTP API — the same work surface the CLI answers, for - | automation clients that would otherwise fork a bd subprocess per call. - | - | The wire contract is described by an OpenAPI document (/v0); GET - | /v0/beads/context reports which operations this build actually implements. - | - | DEPLOYMENT - | - | Pass an explicit port. The default 127.0.0.1:0 takes an ephemeral one, which - | is right for ad-hoc and test use — where the bound address printed on stdout - | is read immediately — but carries no mutual exclusion: two serves against one - | workspace then run side by side on different ports with no way to enumerate - | them. On a fixed port the second one fails to bind, which is the intended - | behavior. Concurrent serves are data-safe either way; claims are arbitrated - | in the SQL server. - | - | Run it under a supervisor. bd shuts down gracefully on SIGHUP as well as - | SIGINT and SIGTERM, so closing the terminal of a foreground bd serve stops it. - | - | PROBES - | - | GET /healthz is LIVENESS only: it answers from the process and never touches - | the database, so it stays green while the database is unreachable. For - | readiness use GET /v0/beads/ready?limit=1 — a real query, where 200 means - | ready and 503 means live but not ready. - | - | AUTHENTICATION - | - | Optional, and off by default on loopback — where the trust model is the - | loopback boundary itself, the same one the database behind it already relies - | on. --auth-token-file turns it on: every operation except GET /healthz then - | requires an "Authorization: Bearer " header, GET /v0/beads/context - | included, because it reports the repo root, beads directory and database name. - | - | The file holds ONE TOKEN PER LINE and every line is accepted. That is the - | rotation mechanism: write the new token alongside the old, roll the clients - | over, then delete the old line. The file is re-read while the server runs, so - | both the addition and the removal take effect within about a second and - | neither needs a restart. Write it atomically (a temp file plus rename; a - | Kubernetes secret mount already does this). - | - | There is deliberately no --auth-token flag. A credential passed as an - | argument is readable by every local user in the process listing. - | - | --allow-non-loopback REQUIRES a token file. Beyond loopback, reaching the - | address would otherwise be the whole authorization: any peer could read every - | issue and claim work as any actor. --insecure-no-auth is the explicit, - | auditable way to say you meant that anyway. - | - | The Host allowlist is what a service deployment usually trips over first. The - | DNS-rebinding check answers only to loopback spellings and the bind address, - | so a client dialing a service name gets 400 on every request; enumerate the - | names it dials with --allowed-host (repeatable). Matching is exact — no - | wildcards — and the startup log line prints the effective allowlist. - | - | WHAT THIS DOES NOT DO - | - | No TLS. Even with a token, the credential and every issue body travel in - | plaintext, so a deployment beyond loopback has to supply confidentiality - | itself — a service mesh, or a network boundary you already trust. - | - | Hooks do not fire. A hook is a user-controlled subprocess per mutation: in a - | concurrent server that is an unbounded latency multiplier and an orphaned - | child at shutdown, and its working-directory-derived hook lookup is - | meaningless in a server process. A CLI claim runs on_update; an HTTP claim - | does not. - | - | The per-command auto-commit machinery does not run. Durability is per request: - | a successful claim commits inside its own transaction, exactly as a proxied - | CLI claim does today. - | - | An actor on an HTTP request is caller-asserted provenance for the audit trail, - | not authenticated identity — the same thing it has always been on the CLI, - | where any local process can pass any --actor. - | - | It does not run under --readonly, and refuses to start rather than binding. - | Every server it binds publishes the issue-claim operation, and the capability - | set it advertises is a property of the build rather than of the flags on the - | process that started it — so a read-only server would advertise a write it - | could never land. - | - | DESTRUCTIVE OPERATIONS - | - | POST /v0/beads/issues:sweep deletes closed beads in bulk — the operation - | behind bd purge and bd prune — and nothing it deletes comes back. It shares - | the library surface those commands call, so it inherits their guards: pinned - | beads are never swept, and a durable sweep with neither a cutoff nor an id - | pattern is refused rather than clearing every closed bead in the workspace. - | Combined with the trust model above, that means anyone who can reach this - | address can erase closed work; bind it accordingly. - flag --addr type=string default="127.0.0.1:0" usage="Address to bind as IP:PORT; the host must be a numeric IP literal, and port 0 takes an ephemeral port" - flag --allow-non-loopback type=bool default="false" usage="Permit a bind beyond loopback. Requires --auth-token-file, since reaching the address would otherwise be the whole authorization" - flag --allowed-host type=stringArray default="[]" usage="Additional Host header value to answer to, e.g. a service DNS name. Repeatable; matched exactly, with no wildcards" - flag --auth-token-file type=string default="" usage="Require an Authorization: Bearer token from this file, one token per line, all accepted. Re-read while running, so rewriting it rotates tokens without a restart (env BEADS_SERVE_TOKEN_FILE)" - flag --insecure-no-auth type=bool default="false" usage="Serve a non-loopback bind with NO authentication. Every peer that can reach the address gets full read and claim access" - flag --large-apply-ceiling type=duration default="5m0s" usage="Whole-run budget for a POST issues:batchApply request over 100 items (a ceiling, not a target; requests at or under 100 items are unaffected). Must be positive. The orchestrator's stop grace must be at least this long plus 5s, or an external SIGKILL can cut off an in-flight large apply a graceful drain would otherwise have waited out; see engdocs/SERVE_RUNBOOK.md" - -bd set-state - use: "set-state =" - short: "Set operational state (creates event + updates label)" - group: "issues" - hidden: false - runnable: true - long: - | Atomically set operational state on an issue. - | - | This command: - | 1. Creates an event bead recording the state change (source of truth) - | 2. Removes any existing label for the dimension - | 3. Adds the new dimension:value label (fast lookup cache) - | - | State labels follow the convention :, for example: - | patrol:active, patrol:muted - | mode:normal, mode:degraded - | health:healthy, health:failing - | - | Examples: - | bd set-state agent-abc patrol=muted --reason "Investigating stuck worker" - | bd set-state agent-abc mode=degraded --reason "High error rate detected" - | bd set-state agent-abc health=healthy - | - | The --reason flag provides context for the event bead (recommended). - flag --reason type=string default="" usage="Reason for the state change (recorded in event)" - -bd setup - use: "setup [recipe]" - short: "Setup integration with AI editors" - group: "setup" - hidden: false - runnable: true - long: - | Setup integration files for AI editors and coding assistants. - | - | Recipes define where beads workflow instructions are written. Built-in recipes - | include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, kiro, windsurf, cody, and kilocode. - | - | Examples: - | bd setup cursor # Install Cursor IDE integration (rules + agent hooks) - | bd setup cursor --global # Install global Cursor hooks (~/.cursor/hooks.json) - | bd setup kiro # Install Kiro steering guidance - | bd setup codex # Install Codex skill + AGENTS.md guidance + native hooks - | bd setup codex --global # Install global Codex skill + guidance + native hooks - | bd setup copilot # Install Copilot CLI plugin + repository instructions - | bd setup mux --project # Install Mux workspace layer (.mux/AGENTS.md) - | bd setup mux --global # Install Mux global layer (~/.mux/AGENTS.md) - | bd setup mux --project --global # Install both Mux layers - | bd setup --list # Show all available recipes - | bd setup --print # Print the template to stdout - | bd setup -o rules.md # Write template to custom path - | bd setup --add myeditor .myeditor/rules.md # Add custom recipe - | - | Use 'bd setup --check' to verify installation status. - | Use 'bd setup --remove' to uninstall. - flag --add type=string default="" usage="Add a custom recipe with given name" - flag --check type=bool default="false" usage="Check if integration is installed" - flag --global type=bool default="false" usage="Install globally (claude/codex/cursor/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, ~/.cursor/hooks.json, or ~/.mux/AGENTS.md)" - flag --list type=bool default="false" usage="List all available recipes" - flag --output -o type=string default="" usage="Write template to custom path" - flag --print type=bool default="false" usage="Print the template to stdout" - flag --project type=bool default="false" usage="Install for this project only (gemini/mux)" - flag --remove type=bool default="false" usage="Remove the integration" - flag --stealth type=bool default="false" usage="Use stealth mode (claude/gemini)" - -bd ship - use: "ship " - short: "Publish a capability for cross-project dependencies" - hidden: false - runnable: true - long: - | Ship a capability to satisfy cross-project dependencies. - | - | This command: - | 1. Finds issue with export: label - | 2. Validates issue is closed (or --force to override) - | 3. Adds provides: label - | - | External projects can depend on this capability using: - | bd dep add external:: - | - | The capability is resolved when the external project has a closed issue - | with the provides: label. - | - | Examples: - | bd ship mol-run-assignee # Ship the mol-run-assignee capability - | bd ship mol-run-assignee --force # Ship even if issue is not closed - | bd ship mol-run-assignee --dry-run # Preview without making changes - flag --dry-run type=bool default="false" usage="Preview without making changes" - flag --force type=bool default="false" usage="Ship even if issue is not closed" - -bd show - use: "show [id...] [--id=...] [--current]" - aliases: ["view"] - short: "Show issue details" - group: "issues" - hidden: false - runnable: true - flag --as-of type=string default="" usage="Show issue as it existed at a specific commit hash or branch (requires Dolt; commit hashes must be the full 32-character hash from 'bd history', not a prefix)" - flag --brief-deps type=bool default="false" usage="Reduce each dependency to its identity fields in JSON output (--json only; drops description, design, notes and acceptance criteria)" - flag --children type=bool default="false" usage="Show only the children of this issue" - flag --comments-tail type=int default="0" usage="Render only the last N comments in text output, preceded by one elision line naming how many older ones were hidden (text output only; 0, the default, renders every comment unchanged; N must be >= 0)" - flag --current type=bool default="false" usage="Show the currently active issue (in-progress, hooked, or last touched)" - flag --id type=stringArray default="[]" usage="Issue ID (use for IDs that look like flags, e.g., --id=gt--xyz)" - flag --include-comments type=bool default="false" usage="Stream full comment bodies in JSON output (--json only; may be slow on issues with many comments). Without it the comments field is absent entirely, not truncated: an issue with comments carries comment_count and comments_omitted=true, so check those before reading an absent comments field as none." - flag --include-dependents type=bool default="false" usage="Stream full dependent issues in JSON output (--json only; may be slow on hub beads)" - flag --local-time type=bool default="false" usage="Show timestamps in local time instead of UTC (date-only fields are always local)" - flag --long type=bool default="false" usage="Show all available fields (extended metadata, agent identity, gate fields, etc.)" - flag --refs type=bool default="false" usage="Show issues that reference this issue (reverse lookup)" - flag --short type=bool default="false" usage="Show compact one-line output per issue" - flag --thread type=bool default="false" usage="Show full conversation thread (for messages)" - flag --watch -w type=bool default="false" usage="Watch for changes and auto-refresh display" - -bd sql - use: "sql " - short: "Execute raw SQL against the beads database" - group: "maint" - hidden: false - runnable: true - long: - | Execute a raw SQL query against the underlying database (Dolt). - | - | Useful for debugging, maintenance, and working around bugs in higher-level commands. - | - | Examples: - | bd sql 'SELECT COUNT(*) FROM issues' - | bd sql 'SELECT id, title FROM issues WHERE status = "open" LIMIT 5' - | bd sql 'DELETE FROM dirty_issues WHERE issue_id = "bd-abc123"' - | bd sql --csv 'SELECT id, title, status FROM issues' - | - | The query is passed directly to the database. Reads (SELECT, WITH ... SELECT, - | SHOW, EXPLAIN) return results as a table (or JSON/CSV with --json/--csv). Writes - | (INSERT, UPDATE, DELETE, DDL) report the number of rows affected. Statements - | that may both write and return rows, such as CALL, are committed and print any - | rows they return (or "OK"). - | - | In proxied-server mode, multiple statements separated by ';' run as a single - | committed batch and report "OK", and --database runs the query against a - | different server database (equivalent to a session USE) without changing the - | project's configured database. - | - | WARNING: Direct database access bypasses the storage layer. Use with caution. - flag --csv type=bool default="false" usage="Output results in CSV format" - -bd stale - use: "stale" - short: "Show stale issues (not updated recently)" - group: "views" - hidden: false - runnable: true - long: - | Show issues that haven't been updated recently and may need attention. - | This helps identify: - | - In-progress issues with no recent activity (may be abandoned) - | - Open issues that have been forgotten - | - Issues that might be outdated or no longer relevant - flag --days -d type=int default="30" usage="Issues not updated in this many days" - flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" - flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" - flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" - flag --limit -n type=int default="50" usage="Maximum issues to show" - flag --status -s type=string default="" usage="Filter by status (open|in_progress|blocked|deferred)" - -bd state - use: "state " - short: "Query the current value of a state dimension" - group: "issues" - hidden: false - runnable: true - long: - | Query the current value of a state dimension from an issue's labels. - | - | State labels follow the convention :, for example: - | patrol:active - | mode:degraded - | health:healthy - | - | This command extracts the value for a given dimension. - | - | Examples: - | bd state witness-abc patrol # Output: active - | bd state witness-abc mode # Output: normal - | bd state witness-abc health # Output: healthy - -bd state list - use: "list " - short: "List all state dimensions on an issue" - hidden: false - runnable: true - long: - | List all state labels (dimension:value format) on an issue. - | - | This filters labels to only show those following the state convention. - | - | Example: - | bd state list witness-abc - | # Output: - | # patrol: active - | # mode: normal - | # health: healthy - -bd status - use: "status" - aliases: ["stats"] - short: "Show issue database overview and statistics" - group: "views" - hidden: false - runnable: true - long: - | Show a quick snapshot of the issue database state and statistics. - | - | This command provides a summary of issue counts by state (open, in_progress, - | blocked, closed), ready work, extended statistics (pinned issues, - | average lead time), and recent activity over the last 24 hours from git history. - | - | Similar to how 'git status' shows working tree state, 'bd status' gives you - | a quick overview of your issue database without needing multiple queries. - | - | Use cases: - | - Quick project health check - | - Onboarding for new contributors - | - Integration with shell prompts or CI/CD - | - Daily standup reference - | - Fast CI status checks that don't need blocked-count accuracy - | - | Examples: - | bd status # Show summary with activity - | bd status --no-activity # Skip git activity (faster) - | bd status --no-blocked # Skip slow blocked-count scan (faster) - | bd stats --no-blocked --json # JSON output without blocked count - | bd status --json # JSON format output - | bd status --assigned # Show issues assigned to current user - | bd stats # Alias for bd status - flag --all type=bool default="false" usage="Show all issues (default behavior)" - flag --assigned type=bool default="false" usage="Show issues assigned to current user" - flag --no-activity type=bool default="false" usage="Skip git activity summary (faster)" - flag --no-blocked type=bool default="false" usage="Skip blocked-count computation (faster on large rigs; not supported in proxied-server mode)" - -bd statuses - use: "statuses" - short: "List valid issue statuses" - group: "views" - hidden: false - runnable: true - long: - | List all valid issue statuses and their categories. - | - | Built-in statuses (open, in_progress, blocked, etc.) are always valid. - | Additional statuses can be configured via status.custom: - | - | bd config set status.custom "in_review:active,qa_testing:wip,on_hold:frozen" - | - | Categories control behavior: - | active — appears in 'bd ready' and default 'bd list' - | wip — excluded from 'bd ready', visible in default 'bd list' - | done — excluded from 'bd ready' and default 'bd list' - | frozen — excluded from 'bd ready' and default 'bd list' - | - | Statuses without a category (legacy format) are valid but excluded from 'bd ready'. - | - | Examples: - | bd statuses # List all statuses with icons and categories - | bd statuses --json # Output as JSON - | - -bd supersede - use: "supersede --with " - short: "Mark an issue as superseded by a replacement issue" - group: "deps" - hidden: false - runnable: true - long: - | Mark an issue as superseded by a different (replacement) issue. - | - | The superseded issue is automatically closed with a reference to the replacement. - | Useful for design docs, specs, and evolving artifacts. - | - | Examples: - | bd supersede bd-old --with bd-new # Mark bd-old as superseded by bd-new - flag --with type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Replacement issue ID (required)" - -bd swarm - use: "swarm" - short: "Swarm management for structured epics" - group: "deps" - hidden: false - runnable: false - long: - | Swarm management commands for coordinating parallel work on epics. - | - | A swarm is a structured body of work defined by an epic and its children, - | with dependencies forming a DAG (directed acyclic graph) of work. - -bd swarm create - use: "create [epic-id]" - short: "Create a swarm molecule from an epic" - hidden: false - runnable: true - long: - | Create a swarm molecule to orchestrate parallel work on an epic. - | - | The swarm molecule: - | - Links to the epic it orchestrates - | - Has mol_type=swarm for discovery - | - Specifies a coordinator (optional) - | - Can be picked up by any coordinator agent - | - | If given a single issue (not an epic), it will be auto-wrapped: - | - Creates an epic with that issue as its only child - | - Then creates the swarm molecule for that epic - | - | Examples: - | bd swarm create bd-epic-123 # Create swarm for epic - | bd swarm create bd-epic-123 --coordinator=observer/ # With specific coordinator - | bd swarm create bd-task-456 # Auto-wrap single issue - flag --coordinator type=string default="" usage="Coordinator address (e.g., my-project/witness)" - flag --force type=bool default="false" usage="Create new swarm even if one already exists" - -bd swarm list - use: "list" - short: "List all swarm molecules" - hidden: false - runnable: true - long: - | List all swarm molecules with their status. - | - | Shows each swarm molecule with: - | - Progress (completed/total issues) - | - Active workers - | - Epic ID and title - | - | Examples: - | bd swarm list # List all swarms - | bd swarm list --json # Machine-readable output - -bd swarm status - use: "status [epic-or-swarm-id]" - short: "Show current swarm status" - hidden: false - runnable: true - long: - | Show the current status of a swarm, computed from beads. - | - | Accepts either: - | - An epic ID (shows status for that epic's children) - | - A swarm molecule ID (follows the link to find the epic) - | - | Displays issues grouped by state: - | - Completed: Closed issues - | - Active: Issues currently in_progress (with assignee) - | - Ready: Open issues with all dependencies satisfied - | - Blocked: Open issues waiting on dependencies - | - | The status is COMPUTED from beads, not stored separately. - | If beads changes, status changes. - | - | Examples: - | bd swarm status gt-epic-123 # Show swarm status by epic - | bd swarm status gt-swarm-456 # Show status via swarm molecule - | bd swarm status gt-epic-123 --json # Machine-readable output - -bd swarm validate - use: "validate [epic-id]" - short: "Validate epic structure for swarming" - hidden: false - runnable: true - long: - | Validate an epic's structure to ensure it's ready for swarm execution. - | - | Checks for: - | - Correct dependency direction (requirement-based, not temporal) - | - Orphaned issues (roots with no dependents) - | - Missing dependencies (leaves that should depend on something) - | - Cycles (impossible to resolve) - | - Disconnected subgraphs - | - | Reports: - | - Ready fronts (waves of parallel work) - | - Estimated worker-sessions - | - Maximum parallelism - | - Warnings for potential issues - | - | Examples: - | bd swarm validate gt-epic-123 # Validate epic structure - | bd swarm validate gt-epic-123 --verbose # Include detailed issue graph - flag --verbose type=bool default="false" usage="Include detailed issue graph in output" - -bd sync - use: "sync" - short: "Pull, check for conflicts, repair is_blocked, and push (the federation loop)" - group: "sync" - hidden: false - runnable: true - long: - | Run one full synchronization cycle against the Dolt remote. - | - | This is the loop every multi-machine beads deployment otherwise hand-rolls in - | shell: - | - | 1. pull from the remote - | 2. check for merge conflicts POSITIVELY, from the merge's own conflict rows - | and from Dolt's conflict tables — never inferred from the pull's exit - | status, which is not a trustworthy conflict signal in either direction - | 3. recompute the denormalized is_blocked flag, so dependency edges merged in - | from another replica do not leave 'bd ready' stale - | 4. push, retrying a bounded number of times when another replica wins the - | push race - | - | The repair in step 3 refuses to run while another writer has uncommitted changes - | to issues/dependencies. That is transient and not this sync's doing, so it is - | retried on the same budget as a push race rather than failing the run. A working - | set that is NOT transient exits 4 instead, because no amount of retrying will - | ever publish and only an operator can clear it. Two kinds of evidence say so: - | constraint violations on the dirty tables are detected positively and escalate - | on the very attempt that finds them; an abandoned uncommitted edit has no such - | positive signal, so it is only inferred once the same pending graph edits have - | blocked every attempt of several consecutive runs. - | - | Conflicts sync cannot resolve safely are NEVER auto-resolved: it halts before - | recomputing or pushing and exits 2, and repeated runs keep halting the same way - | until an operator resolves the divergence. (The pull underneath does auto-settle - | the conflict classes it can settle convergently — machine-local metadata, - | audit-only dependency rows, and last-write-wins on issue cells. Anything beyond - | those halts here.) Whether the halted merge was aborted or left live in the - | working set depends on the pull route, so the halt message reports which. - | - | Exit codes (a sync timer can branch on these without parsing output): - | - | 0 synced, or nothing to do - | 1 error (transport, auth, storage) - | 2 merge conflict — halted, nothing pushed, resolve it by hand - | 3 retries exhausted (push race, or a concurrent writer's dirty working set) - | — transient, nothing pushed, retry on the next tick - | 4 the dirty working set is stuck, not busy: identical pending graph edits - | blocked every attempt of several consecutive runs — nothing pushed, and no - | later tick will publish until an operator clears it - | - | On the default-remote path, a rig with no Dolt remote yet but a git origin - | configured adopts that origin as its Dolt remote first, exactly as 'bd dolt push' - | does — so 'bd sync' works as a first-time federation bring-up step instead of - | reporting 'no remote' and doing nothing. Passing --remote never adopts anything. - | - | This is not 'bd federation sync', which syncs with named peer towns and takes a - | --strategy ours|theirs to resolve whatever conflicts it meets. 'bd sync' targets - | the configured remote and has no such switch: what it cannot settle, it halts on. - | - | Examples: - | bd sync # sync with the default remote - | bd sync --remote mini # sync with a specific remote - | bd sync --attempts 5 # allow more push-race retries - | bd sync --json # machine-parseable outcome - flag --attempts type=int default="3" usage="Maximum pull/push attempts before reporting a transient retry exhaustion (exit 3)" - flag --no-adopt type=bool default="false" usage="Never derive a Dolt remote from git origin (also BD_NO_REMOTE_ADOPT=1)" - flag --remote type=string default="" usage="Sync with a specific named remote instead of the default" - flag --yes -y type=bool default="false" usage="Consent to adopting a Dolt remote derived from git origin when none is configured" - -bd tag - use: "tag