Compare commits
41 commits
deps/dolt-
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3c47390e7 |
||
|
|
bc1cd64c78 |
||
|
|
d0d9aa2145 |
||
|
|
1fcd715e75 |
||
|
|
4df395698b |
||
|
|
c86a87bb20 |
||
|
|
8988340994 |
||
|
|
2563f021ed |
||
|
|
d097b6c8a4 |
||
|
|
d28f56cd46 |
||
|
|
18b5c3cc39 |
||
|
|
4f9174e6ba |
||
|
|
1de9b59324 |
||
|
|
2829d22192 |
||
|
|
21dac62a4c |
||
|
|
4c473b4580 |
||
|
|
994f5b82dd |
||
|
|
4c48829c07 |
||
|
|
d855ac6c88 |
||
|
|
395e7beec0 |
||
|
|
c67a36e5e7 |
||
|
|
9893f9020d |
||
|
|
6db46664da |
||
|
|
8f960b1b6e |
||
|
|
ee441fdc73 |
||
|
|
5e2158ea08 |
||
|
|
fb912f2438 |
||
|
|
e3efb3107a |
||
|
|
9e2f25c322 |
||
|
|
786ed8a4b0 |
||
|
|
36f81bab1c |
||
|
|
eb5ab48950 |
||
|
|
3a5ade3a76 |
||
|
|
e24940e0c1 |
||
|
|
8fac20a7f1 |
||
|
|
05fffb1e11 |
||
|
|
f142cc2ffd |
||
|
|
f6f122894f |
||
|
|
3488dc4536 |
||
|
|
5c9c02ab77 |
||
|
|
9c6f6e15cd |
357 changed files with 41398 additions and 2067 deletions
|
|
@ -201,7 +201,8 @@ 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: `go test ./test/docsync` (nav↔file sync + link conventions),
|
||||
The short list: `bazel test //test/docsync:docsync_test --config=ci`
|
||||
(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`.
|
||||
|
|
|
|||
|
|
@ -39,8 +39,9 @@ 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:** `go test ./test/docsync`, every fence parses, no body H1, no
|
||||
HTML comments (MDX), preview with `make docs-dev`.
|
||||
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`.
|
||||
7. **Preview, then commit on approval** — one page or section per batch, so
|
||||
the reviewer can steer before a cut compounds across the section.
|
||||
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
go test ./test/docsync
|
||||
bazel test //test/docsync:docsync_test --config=ci
|
||||
|
||||
# 2. Generated CLI docs freshness: regenerates from the live command tree
|
||||
# and diffs docs/CLI_REFERENCE.md, docs/cli-reference/, and the CLI
|
||||
|
|
|
|||
105
.github/scripts/embedded-cmd-test-shards.txt
vendored
105
.github/scripts/embedded-cmd-test-shards.txt
vendored
|
|
@ -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/*_embedded_test.go. --write is
|
||||
# TestEmbedded* functions in cmd/bd/*_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,108 +59,206 @@
|
|||
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
|
||||
|
|
@ -225,6 +323,7 @@
|
|||
100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose
|
||||
100 71 TestEmbeddedInitRoleRoutingExplicitDefault
|
||||
100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget
|
||||
100 71 TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig
|
||||
100 71 TestEmbeddedSearchRoutesAgree
|
||||
|
||||
100 72 TestEmbeddedContributorCreateMultiple
|
||||
|
|
@ -335,8 +434,10 @@
|
|||
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
|
||||
|
|
@ -345,8 +446,10 @@
|
|||
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
|
||||
|
|
|
|||
19
.github/scripts/embedded-storage-test-shards.txt
vendored
19
.github/scripts/embedded-storage-test-shards.txt
vendored
|
|
@ -178,7 +178,6 @@
|
|||
|
||||
40 4 TestBlockedListerContract
|
||||
40 4 TestCreateBatchFastPathsMatchPerRowSmallDepAdd_Embedded
|
||||
40 4 TestEmbeddedFirstMintOnEmptyHistoryIsRevisionOne
|
||||
40 4 TestEmbeddedIssueOperationsUpdateLabelPatchOrdering
|
||||
40 4 TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay
|
||||
40 4 TestEmbeddedReaderListFilterFamiliesNarrowToTheirRows
|
||||
|
|
@ -187,6 +186,7 @@
|
|||
40 5 TestEmbeddedClaimerRefusesIncompleteRequestsAndAnAbsentIDWithoutTouchingState
|
||||
40 5 TestEmbeddedIssueOperationsCloseAndReopenAWisp
|
||||
40 5 TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder
|
||||
40 5 TestRecordVersionKeepsSubSecondChangeAt
|
||||
40 5 TestWithPeerAuth
|
||||
|
||||
40 6 TestCreateBatchFastPathsMatchPerRowApplyWaitsFor_Embedded
|
||||
|
|
@ -196,6 +196,7 @@
|
|||
40 6 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection
|
||||
40 6 TestPromoteStillWorksWithCollisionGuard
|
||||
40 6 TestSearchWithMissingWispPlaneTables
|
||||
40 6 TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart
|
||||
|
||||
40 7 TestConcurrencyMultiProcess
|
||||
40 7 TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded
|
||||
|
|
@ -204,17 +205,20 @@
|
|||
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
|
||||
|
|
@ -233,8 +237,10 @@
|
|||
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
|
||||
|
|
@ -336,6 +342,7 @@
|
|||
40 19 TestRemoteVerbsPresentStoredPeerCredentials
|
||||
40 19 TestRenameLabelMintsOneVersionPerTouchedBead
|
||||
|
||||
40 20 TestBumpEpochCarryingCarriesOnlyTheLineageHoldingTheNewestRow
|
||||
40 20 TestCreateIssue
|
||||
40 20 TestEmbeddedCheckedWrappersRouteTheirPreconditions
|
||||
40 20 TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps
|
||||
|
|
@ -347,6 +354,7 @@
|
|||
40 20 TestHeartbeatRejectsWispEmbedded
|
||||
40 20 TestIgnoredCursorHealNeverResurrectsRolledBackVersions
|
||||
|
||||
40 21 TestBumpEpochCarryingCarriesTheLiveRowsOfEveryStoreInTheDatabase
|
||||
40 21 TestCreateRejectsCrossTableIDCollision
|
||||
40 21 TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards
|
||||
40 21 TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants
|
||||
|
|
@ -370,6 +378,7 @@
|
|||
40 22 TestLeaseLifecycleEmbedded
|
||||
40 22 TestPolicyBlockingAnnotatorForeignOpensAreSublinear
|
||||
|
||||
40 23 TestAsOfReadContract
|
||||
40 23 TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes
|
||||
40 23 TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed
|
||||
40 23 TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes
|
||||
|
|
@ -432,6 +441,7 @@
|
|||
40 27 TestRemoteGitDataRefOnEngine
|
||||
40 27 TestSweeperContract
|
||||
|
||||
40 28 TestBumpEpochCarryingDoesNotCarryALostLineage
|
||||
40 28 TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy
|
||||
40 28 TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed
|
||||
40 28 TestEmbeddedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow
|
||||
|
|
@ -469,6 +479,7 @@
|
|||
40 30 TestLegacyTrackedIgnoredCursorUnwedgesPull
|
||||
40 30 TestUpdateMergeOps_DoltEngine_TwoIssues
|
||||
|
||||
40 31 TestBumpEpochCarryingWritesOneCarryRowPerLiveIDNamingTheLineageRoot
|
||||
40 31 TestDualWriteContract
|
||||
40 31 TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget
|
||||
40 31 TestEmbeddedDependencyEditorMaintainsBlockedStateAcrossPlanes
|
||||
|
|
@ -481,6 +492,7 @@
|
|||
40 31 TestReadyCounterContract
|
||||
40 31 TestWithPeerAuth_KeyMismatchFailsClosed
|
||||
|
||||
40 32 TestCurrentAddressForNeverReseedsAnAbsentStoreEpochRow
|
||||
40 32 TestEmbeddedClaimerGrantsALiveLeaseOnTheRowItWonAndLeavesARefusedOneAlone
|
||||
40 32 TestEmbeddedDependencyEditorRefusesAMissingLocalTarget
|
||||
40 32 TestEmbeddedDirtyTablesGate_BlocksReopenThenWorkingSetReconcileRecovers
|
||||
|
|
@ -501,11 +513,13 @@
|
|||
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
|
||||
|
|
@ -529,6 +543,7 @@
|
|||
40 35 TestReadyWorkWithMissingDeferredParentTables
|
||||
40 35 TestReclaimExpiredLeaseSurvivesRestartEmbedded
|
||||
|
||||
40 36 TestBumpEpochCarryingFailsAndRollsBackWhenARowAlreadyExistsAtTheNewEpoch
|
||||
40 36 TestCommenterContract
|
||||
40 36 TestConcurrentOpenReturnsCached
|
||||
40 36 TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory
|
||||
|
|
@ -551,6 +566,7 @@
|
|||
40 37 TestEmbeddedMergeAndSettleReportsOperatorConflicts
|
||||
40 37 TestEmbeddedReaderListBriefDropsTheFreeFormTextAndNothingElse
|
||||
40 37 TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch
|
||||
40 37 TestEpochWritesReportAnUnpublishedCommitAsIndeterminate
|
||||
40 37 TestIgnoredCursorHealRespectsOverrideUnderBroaderPattern
|
||||
|
||||
40 38 TestCreateIssues
|
||||
|
|
@ -572,7 +588,6 @@
|
|||
40 39 TestEmbeddedDependencyEditorMixedBatchRefusalRollsBackBothPlanes
|
||||
40 39 TestEmbeddedIssueOperationsClaimLeavesBlockedStateAlone
|
||||
40 39 TestEmbeddedMigrateRepairedDependenciesIDColumnCommitsAtomicallyWithVersion53_4690
|
||||
40 39 TestEmbeddedMigration0071ReplacesDescendingCompactionSnapshotsIndex
|
||||
40 39 TestEmbeddedReaderListSkipCountsDropsTheCardinalitiesAndNothingElse
|
||||
40 39 TestEmbeddedRelationsResolvesAWispAnchor
|
||||
40 39 TestParticipationGenerationFence
|
||||
|
|
|
|||
10
.github/scripts/embedded-test-shard.sh
vendored
10
.github/scripts/embedded-test-shard.sh
vendored
|
|
@ -3,7 +3,7 @@
|
|||
#
|
||||
# Usage: embedded-test-shard.sh <shard_number> <total_shards>
|
||||
#
|
||||
# Discovers all TestEmbedded* top-level functions from cmd/bd/*_embedded_test.go.
|
||||
# Discovers all TestEmbedded* top-level functions in cmd/bd/*_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,8 +33,12 @@ fi
|
|||
SHARD_INDEX=$(( SHARD_NUMBER - 1 ))
|
||||
MANIFEST="${BEADS_TEST_SHARD_MANIFEST:-.github/scripts/embedded-cmd-test-shards.txt}"
|
||||
|
||||
# Discover all top-level TestEmbedded* functions.
|
||||
ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go \
|
||||
# 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 \
|
||||
| sed 's/func \(TestEmbedded[A-Za-z0-9_]*\).*/\1/' \
|
||||
| sort -u)
|
||||
|
||||
|
|
|
|||
3
.github/scripts/proxied-cmd-test-shards.txt
vendored
3
.github/scripts/proxied-cmd-test-shards.txt
vendored
|
|
@ -69,6 +69,7 @@
|
|||
34 6 TestProxiedServerServeReadsTheJournalItJustWrote
|
||||
34 6 TestProxiedServerSwarm
|
||||
34 6 TestProxiedServerUpdate2B
|
||||
34 6 TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout
|
||||
34 6 TestProxiedServerWispList
|
||||
|
||||
34 7 TestProxiedServerCloseConcurrent
|
||||
|
|
@ -156,6 +157,7 @@
|
|||
34 17 TestProxiedServerPrime
|
||||
34 17 TestProxiedServerSQLDatabaseFlag
|
||||
34 17 TestProxiedServerServeModeGate
|
||||
34 17 TestServerModeServeIgnoresGraphModeDependency
|
||||
|
||||
34 18 TestProxiedServerClose3
|
||||
34 18 TestProxiedServerCount
|
||||
|
|
@ -254,6 +256,7 @@
|
|||
34 30 TestProxiedServerStatus
|
||||
34 30 TestProxiedServerTodo
|
||||
34 30 TestProxiedServerUpdate2
|
||||
34 30 TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow
|
||||
|
||||
34 31 TestProxiedServerCloseBeadGate
|
||||
34 31 TestProxiedServerComment
|
||||
|
|
|
|||
2
.github/workflows/bazel.yml
vendored
2
.github/workflows/bazel.yml
vendored
|
|
@ -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)'
|
||||
PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoStoreFactoriesRefuseGraphWorkspace)'
|
||||
# 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
|
||||
|
|
|
|||
26
AGENTS.md
26
AGENTS.md
|
|
@ -126,9 +126,29 @@ 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.
|
||||
- `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`.
|
||||
- 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).
|
||||
- **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`,
|
||||
|
|
|
|||
33
BUILD.bazel
33
BUILD.bazel
|
|
@ -74,6 +74,13 @@ 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
|
||||
|
|
@ -246,6 +253,20 @@ 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(
|
||||
|
|
@ -344,6 +365,7 @@ 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",
|
||||
|
|
@ -383,6 +405,7 @@ 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",
|
||||
|
|
@ -413,6 +436,7 @@ 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",
|
||||
|
|
@ -578,6 +602,7 @@ 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",
|
||||
|
|
@ -617,6 +642,7 @@ 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",
|
||||
|
|
@ -647,6 +673,7 @@ 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",
|
||||
|
|
@ -797,6 +824,7 @@ 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",
|
||||
|
|
@ -836,6 +864,7 @@ 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",
|
||||
|
|
@ -866,6 +895,7 @@ 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",
|
||||
|
|
@ -1025,6 +1055,7 @@ 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",
|
||||
|
|
@ -1064,6 +1095,7 @@ 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",
|
||||
|
|
@ -1094,6 +1126,7 @@ 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",
|
||||
|
|
|
|||
277
CHANGELOG.md
277
CHANGELOG.md
|
|
@ -9,6 +9,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Added
|
||||
|
||||
- `bd versions <id>` 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 <arg>`, 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
|
||||
|
|
@ -464,6 +499,24 @@ 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
|
||||
|
|
@ -535,40 +588,6 @@ 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
|
||||
|
|
@ -762,6 +781,175 @@ 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 <from> <to>` in place of
|
||||
`dependency: add <type> <from> -> <to>`.
|
||||
|
||||
- **`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
|
||||
`<project>/.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 '<op>' 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_*`,
|
||||
|
|
@ -773,6 +961,27 @@ 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
|
||||
|
|
|
|||
16
README.md
16
README.md
|
|
@ -275,10 +275,24 @@ 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. `off` turns off only the
|
||||
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
|
||||
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
|
||||
|
|
|
|||
|
|
@ -145,7 +145,8 @@ 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** (`make test-regression`)
|
||||
- [ ] **Regression tests pass**
|
||||
(`bazel test //tests/regression:regression_test --config=doltserver-cmd`)
|
||||
- [ ] **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
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ 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",
|
||||
|
|
|
|||
|
|
@ -267,6 +267,65 @@ 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
|
||||
|
|
|
|||
|
|
@ -769,7 +769,21 @@ 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
|
||||
|
|
@ -819,94 +833,258 @@ 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. 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.
|
||||
// architecture doc's own words: an epoch voids what the store lost, never
|
||||
// what it still serves.
|
||||
//
|
||||
// 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.
|
||||
// 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.
|
||||
func RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t *testing.T, ctx context.Context, fixture EpochFixture) {
|
||||
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)")
|
||||
}
|
||||
store := epochStore(fixture, "voids")
|
||||
epochSkipUnlessReady(t, fixture, false)
|
||||
|
||||
addrA, err := fixture.MintUnderEpoch(ctx, store, "record-a")
|
||||
if err != nil {
|
||||
t.Fatalf("MintUnderEpoch(record-a): %v", err)
|
||||
// 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)
|
||||
}
|
||||
addrB, err := fixture.MintUnderEpoch(ctx, store, "record-b")
|
||||
if err != nil {
|
||||
t.Fatalf("MintUnderEpoch(record-b): %v", err)
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
newEpoch, err := fixture.BumpEpoch(ctx, store, EpochBumpTriggerRestore)
|
||||
if err != nil {
|
||||
t.Fatalf("BumpEpoch: %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)
|
||||
}
|
||||
|
||||
servesA, err := fixture.StillServes(ctx, store, addrA)
|
||||
if err != nil {
|
||||
t.Fatalf("StillServes(%s): %v", addrA, 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)
|
||||
}
|
||||
servesB, err := fixture.StillServes(ctx, store, addrB)
|
||||
if err != nil {
|
||||
t.Fatalf("StillServes(%s): %v", addrB, 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")
|
||||
}
|
||||
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")
|
||||
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)
|
||||
}
|
||||
|
||||
stillServed, noLongerServed := addrA, addrB
|
||||
if servesB && !servesA {
|
||||
stillServed, noLongerServed = addrB, addrA
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
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)
|
||||
}
|
||||
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 -------------------------------------------------------
|
||||
|
|
@ -953,6 +1131,137 @@ 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.
|
||||
|
|
|
|||
|
|
@ -129,5 +129,14 @@ 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
|
|||
356
backend/conformance/versioned_read_contract.go
Normal file
356
backend/conformance/versioned_read_contract.go
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -37,6 +37,7 @@ 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",
|
||||
|
|
|
|||
137
backend/http/e2e_link_test.go
Normal file
137
backend/http/e2e_link_test.go
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
//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
|
||||
}
|
||||
|
|
@ -53,8 +53,15 @@ 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"}},
|
||||
|
|
|
|||
20
beads.go
20
beads.go
|
|
@ -99,6 +99,18 @@ 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
|
||||
|
|
@ -369,6 +381,9 @@ 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})
|
||||
}
|
||||
|
||||
|
|
@ -403,6 +418,11 @@ 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
|
||||
|
|
|
|||
|
|
@ -46,6 +46,11 @@ 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)
|
||||
|
|
|
|||
|
|
@ -32,6 +32,11 @@ 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)
|
||||
|
|
|
|||
|
|
@ -38,6 +38,10 @@ 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
|
||||
|
|
@ -85,6 +89,9 @@ 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()`.
|
||||
|
|
|
|||
|
|
@ -375,9 +375,13 @@ 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",
|
||||
|
|
@ -418,6 +422,7 @@ go_library(
|
|||
"//internal/httpapi",
|
||||
"//internal/httpclient",
|
||||
"//internal/httpclient/wire",
|
||||
"//internal/initprocs",
|
||||
"//internal/jira",
|
||||
"//internal/linear",
|
||||
"//internal/lockfile",
|
||||
|
|
@ -463,6 +468,7 @@ go_library(
|
|||
"//internal/utils",
|
||||
"//internal/validation",
|
||||
"//internal/versioncheck",
|
||||
"//internal/versionedhistory",
|
||||
"//internal/workapi",
|
||||
"//internal/workspacegate",
|
||||
"//internal/worktreeremove",
|
||||
|
|
@ -543,6 +549,7 @@ 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",
|
||||
|
|
@ -600,6 +607,7 @@ 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",
|
||||
|
|
@ -710,6 +718,8 @@ 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",
|
||||
|
|
@ -751,6 +761,7 @@ 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",
|
||||
|
|
@ -800,6 +811,7 @@ 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",
|
||||
|
|
@ -832,6 +844,8 @@ 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",
|
||||
|
|
@ -861,6 +875,7 @@ 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",
|
||||
|
|
@ -883,10 +898,13 @@ 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",
|
||||
|
|
@ -935,6 +953,8 @@ 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",
|
||||
|
|
@ -1086,6 +1106,7 @@ 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",
|
||||
|
|
@ -1148,6 +1169,7 @@ 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",
|
||||
|
|
@ -1290,6 +1312,14 @@ 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",
|
||||
|
|
@ -1299,6 +1329,7 @@ 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",
|
||||
|
|
@ -1319,6 +1350,7 @@ 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",
|
||||
|
|
@ -1354,6 +1386,7 @@ go_test(
|
|||
"//internal/httpclient",
|
||||
"//internal/httpclient/encode",
|
||||
"//internal/httpclient/wire",
|
||||
"//internal/initprocs",
|
||||
"//internal/linear",
|
||||
"//internal/metrics",
|
||||
"//internal/migration",
|
||||
|
|
@ -1385,6 +1418,7 @@ go_test(
|
|||
"//internal/storage/uow",
|
||||
"//internal/storage/versioncontrolops",
|
||||
"//internal/telemetry",
|
||||
"//internal/templates/agents",
|
||||
"//internal/testutil",
|
||||
"//internal/testutil/bazeltest",
|
||||
"//internal/testutil/credentialcmd",
|
||||
|
|
@ -1457,7 +1491,7 @@ go_test(
|
|||
)
|
||||
|
||||
# bd_embedded_test and bd_embedded_part2_test run the TestEmbedded* functions
|
||||
# of *_embedded_test.go between them: the manifest's 100-shard block
|
||||
# of cmd/bd's _test.go files 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
|
||||
|
|
|
|||
310
cmd/bd/agent_artifacts_embedded_test.go
Normal file
310
cmd/bd/agent_artifacts_embedded_test.go
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
//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 = "<!-- END BEADS INTEGRATION -->\n"
|
||||
begin := strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
|
||||
if begin < 0 {
|
||||
return content
|
||||
}
|
||||
rel := strings.Index(content[begin:], endMarker)
|
||||
if rel < 0 {
|
||||
return content
|
||||
}
|
||||
end := begin + rel + len(endMarker)
|
||||
section := content[begin:end]
|
||||
for _, v := range agentArtifactManagedSections {
|
||||
if section == agents.RenderSectionWithOpts(v.profile, v.opts) {
|
||||
marker, _, _ := strings.Cut(section, "\n")
|
||||
return content[:begin] + marker + "\n[managed section body: byte-identical to internal/templates/agents/testdata/" + v.golden + "]\n" + endMarker + content[end:]
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
// runAgentArtifactCommand runs bd in dir with HOME at home and returns its
|
||||
// stdout, stderr and exit code.
|
||||
func runAgentArtifactCommand(t *testing.T, bd, dir, home string, args ...string) (stdout, stderr string, exitCode int) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = agentArtifactEnv(dir, home)
|
||||
outBuf, errBuf, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
t.Fatalf("bd %s: %v", strings.Join(args, " "), err)
|
||||
}
|
||||
exitCode = exitErr.ExitCode()
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), exitCode
|
||||
}
|
||||
|
||||
// agentArtifactEnv is bdEnv(dir) with HOME at home and without the caller's
|
||||
// BD_OTEL_* and OTEL_* variables: bd warns on stderr about a legacy BD_OTEL_*
|
||||
// one whether or not telemetry is on, and the transcript pins stderr byte for
|
||||
// byte. (clearTelemetryEnv cannot be used: it calls t.Setenv, and these tests
|
||||
// run in parallel.)
|
||||
func agentArtifactEnv(dir, home string) []string {
|
||||
var env []string
|
||||
for _, e := range bdEnv(dir) {
|
||||
if strings.HasPrefix(e, "BD_OTEL_") || strings.HasPrefix(e, "OTEL_") || strings.HasPrefix(e, "HOME=") {
|
||||
continue
|
||||
}
|
||||
env = append(env, e)
|
||||
}
|
||||
return append(env, "HOME="+home)
|
||||
}
|
||||
|
||||
// writeAgentArtifactChanges appends every artifact created, modified or
|
||||
// deleted since previous (which it then updates), with its contents.
|
||||
func writeAgentArtifactChanges(t *testing.T, b *strings.Builder, dir, home string, previous map[string]string) {
|
||||
t.Helper()
|
||||
roots := strings.NewReplacer("$PROJECT", dir, "$HOME", home)
|
||||
changed := false
|
||||
for _, path := range agentArtifactPaths {
|
||||
data, err := os.ReadFile(filepath.FromSlash(roots.Replace(path)))
|
||||
before, existed := previous[path]
|
||||
switch {
|
||||
case os.IsNotExist(err):
|
||||
if existed {
|
||||
fmt.Fprintf(b, "--- files: deleted %s\n", path)
|
||||
delete(previous, path)
|
||||
changed = true
|
||||
}
|
||||
case err != nil:
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
case !existed || before != string(data):
|
||||
verb := "created"
|
||||
if existed {
|
||||
verb = "modified"
|
||||
}
|
||||
shown := string(data)
|
||||
if strings.HasSuffix(path, ".md") {
|
||||
shown = elideAgentArtifactManagedSection(shown)
|
||||
}
|
||||
writeAgentArtifactBlock(b, fmt.Sprintf("files: %s %s", verb, path), shown)
|
||||
previous[path] = string(data)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
b.WriteString("--- files: unchanged\n")
|
||||
}
|
||||
}
|
||||
|
||||
// writeAgentArtifactBlock appends a titled block, marking empty content and a
|
||||
// missing trailing newline so neither is lost in the golden.
|
||||
func writeAgentArtifactBlock(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)
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeAgentArtifactOutput replaces the project and home directories (as
|
||||
// given and with symlinks resolved, since bd reports the paths it sees) with
|
||||
// $PROJECT and $HOME and uses forward slashes, so the transcript is the same
|
||||
// on every host.
|
||||
func normalizeAgentArtifactOutput(s, dir, home string) string {
|
||||
for _, root := range []struct{ path, label string }{{dir, "$PROJECT"}, {home, "$HOME"}} {
|
||||
if resolved, err := filepath.EvalSymlinks(root.path); err == nil && resolved != root.path {
|
||||
s = strings.ReplaceAll(s, resolved, root.label)
|
||||
}
|
||||
s = strings.ReplaceAll(s, root.path, root.label)
|
||||
}
|
||||
if filepath.Separator != '/' {
|
||||
s = strings.ReplaceAll(s, string(filepath.Separator), "/")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// assertAgentArtifactGolden compares got with the golden file at path, or
|
||||
// rewrites the file when BD_UPDATE_GOLDEN=1.
|
||||
func assertAgentArtifactGolden(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("bd init 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)
|
||||
}
|
||||
|
|
@ -43,7 +43,7 @@ func bdRunOK(t *testing.T, bd, dir string, args ...string) string {
|
|||
return string(out)
|
||||
}
|
||||
|
||||
// TestReassignFenceCLI drives the bd-98s5c live-claim reassign fence
|
||||
// TestEmbeddedReassignFenceCLI drives the bd-98s5c live-claim reassign fence
|
||||
// end-to-end: plain `bd update -a` and `bd assign` were the last unfenced
|
||||
// cross-actor takeover path (--claim, unclaim, and close all refuse without
|
||||
// --force). The fence must refuse ONLY the silent steamroll — a different
|
||||
|
|
@ -51,7 +51,7 @@ func bdRunOK(t *testing.T, bd, dir string, args ...string) string {
|
|||
// leave routine dispatch untouched: open-bead reassigns, self-edits,
|
||||
// idempotent re-asserts, pool-alias takes, and holder-aware --if-assignee
|
||||
// transfers all proceed without --force.
|
||||
func TestReassignFenceCLI(t *testing.T) {
|
||||
func TestEmbeddedReassignFenceCLI(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,10 +12,23 @@ import (
|
|||
// the rejection inspects it (read-only) so a workspace that already holds a Dolt
|
||||
// database is told to fix the stale "backend" value rather than to export and
|
||||
// reinitialize. Pass "" only where there is genuinely no workspace directory.
|
||||
//
|
||||
// It also refuses metadata that declares a workspace format this build cannot
|
||||
// open (checkWorkspaceFormat). Command admission refuses those first, and the
|
||||
// store factories check before their migrating configfile.Load
|
||||
// (checkDiscoveredWorkspaceFormat), so here it backs up any other caller that
|
||||
// validates metadata it loaded itself. It returns early for a nil cfg, so that
|
||||
// backstop covers the graph format marker only when metadata was loaded; a
|
||||
// caller that may have none must check beadsDir with
|
||||
// checkDiscoveredWorkspaceFormat or command admission first, as every caller
|
||||
// does today.
|
||||
func validateConfiguredBackend(cfg *configfile.Config, beadsDir string) error {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
if err := checkWorkspaceFormat(cfg, beadsDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if backends.Registered(cfg.Backend) {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -80,14 +93,16 @@ func openStoreError(backendName string, err error) error {
|
|||
return fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
// backendNameForErrorFraming best-effort loads metadata.json to learn which
|
||||
// backendNameForErrorFraming best-effort reads metadata.json to learn which
|
||||
// backend a failed open was for, so a caller that does not already have cfg
|
||||
// in scope (for example direct mode's single-shot store-open) can still give
|
||||
// openStoreError the name it needs. A failure to even read the config
|
||||
// degrades to "" — openStoreError's default, Dolt-shaped framing — rather
|
||||
// than compounding one error with another.
|
||||
// than compounding one error with another. It reads with LoadForDiscovery:
|
||||
// the open it frames may have just refused the workspace, and
|
||||
// configfile.Load would migrate a legacy config.json into metadata.json.
|
||||
func backendNameForErrorFraming(beadsDir string) string {
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
cfg, err := configfile.LoadForDiscovery(beadsDir)
|
||||
if err != nil || cfg == nil {
|
||||
return ""
|
||||
}
|
||||
|
|
@ -95,6 +110,12 @@ func backendNameForErrorFraming(beadsDir string) string {
|
|||
}
|
||||
|
||||
func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) {
|
||||
// Refuse a workspace format this build cannot open before configfile.Load,
|
||||
// which would otherwise migrate a legacy config.json into metadata.json
|
||||
// before requireDoltBackend's own format check could refuse it.
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading config: %w", err)
|
||||
|
|
|
|||
|
|
@ -53,6 +53,8 @@ After adding, run 'bd backup sync' to push your data.`,
|
|||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("backup init")
|
||||
|
||||
evt := metrics.NewCommandEvent("backup-init")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
|
|
@ -134,6 +136,8 @@ Run 'bd backup init <path>' first to configure a destination.`,
|
|||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("backup sync")
|
||||
|
||||
evt := metrics.NewCommandEvent("backup-sync")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
|
|
@ -439,6 +443,8 @@ backup configuration. The backup data at the destination is not deleted.`,
|
|||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("backup remove")
|
||||
|
||||
evt := metrics.NewCommandEvent("backup-remove")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
|
|
|
|||
|
|
@ -217,3 +217,78 @@ func TestEmbeddedBackupConcurrent(t *testing.T) {
|
|||
t.Error("backup destination should exist after concurrent syncs")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedBackupRestoreStrictReadonly pins the refusal of a strict
|
||||
// --readonly restore. A restore replaces the store, so CheckReadonly must stop
|
||||
// it with the standard message before the command takes the exclusive workspace
|
||||
// gate. Embedded mode used to be stopped only by the storage layer
|
||||
// ("embeddeddolt: store is read-only"), after the gate had already left its
|
||||
// holder files in the workspace. The control proves the fixture really does
|
||||
// restore when --readonly is not asked for, so "the store is unchanged" below
|
||||
// cannot be vacuous.
|
||||
func TestEmbeddedBackupRestoreStrictReadonly(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt backup tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
// newWorkspace returns a workspace whose live store holds one issue its
|
||||
// backup does not (three against two), so a restore that really ran shows up
|
||||
// as a changed issue count. Each case gets its own: a restore that runs
|
||||
// replaces the store and would hide a leak from the next.
|
||||
newWorkspace := func(t *testing.T, prefix string) (dir, backupDir string) {
|
||||
t.Helper()
|
||||
dir, _, _ = bdInit(t, bd, "--prefix", prefix)
|
||||
bdCreateSilent(t, bd, dir, "issue in the backup A")
|
||||
bdCreateSilent(t, bd, dir, "issue in the backup B")
|
||||
|
||||
backupDir = filepath.Join(t.TempDir(), "dolt-backup")
|
||||
if err := os.MkdirAll(backupDir, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bdBackup(t, bd, dir, "init", "file://"+backupDir)
|
||||
bdBackup(t, bd, dir, "sync")
|
||||
|
||||
bdCreateSilent(t, bd, dir, "issue created after the backup")
|
||||
return dir, backupDir
|
||||
}
|
||||
|
||||
t.Run("control_restore_without_readonly", func(t *testing.T) {
|
||||
dir, backupDir := newWorkspace(t, "rrctl")
|
||||
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "backup", "restore", "--force", backupDir)
|
||||
if code != 0 {
|
||||
t.Fatalf("restore without --readonly exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, "Restore complete") {
|
||||
t.Errorf("stdout is missing %q:\n%s", "Restore complete", stdout)
|
||||
}
|
||||
if got := len(bdListJSON(t, bd, dir)); got != 2 {
|
||||
t.Errorf("issue count after a real restore = %d, want 2: the backup holds two issues and the live store held three", got)
|
||||
}
|
||||
})
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
prefix string
|
||||
flags []string
|
||||
}{
|
||||
{"readonly", "rrro", []string{"--readonly"}},
|
||||
{"readonly_sandbox", "rrrosb", []string{"--readonly", "--sandbox"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir, backupDir := newWorkspace(t, tc.prefix)
|
||||
before := snapshotWorkspace(t, dir)
|
||||
|
||||
args := append(append([]string{}, tc.flags...), "backup", "restore", "--force", backupDir)
|
||||
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, args...)
|
||||
|
||||
assertStrictReadonlyRestoreRefused(t, stdout, stderr, code)
|
||||
assertWorkspaceUnchanged(t, dir, before)
|
||||
if got := len(bdListJSON(t, bd, dir)); got != 3 {
|
||||
t.Errorf("issue count after the refused restore = %d, want 3: the restore replaced the store", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ To initialize and restore in one step, use: bd init && bd backup restore`,
|
|||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("backup restore")
|
||||
|
||||
evt := metrics.NewCommandEvent("backup-restore")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
|
|
|
|||
|
|
@ -4,14 +4,22 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestBackupRestoreMissingDir(t *testing.T) {
|
||||
|
|
@ -84,3 +92,257 @@ func TestSyncProjectIDFromDB_NoWorkspaceUsesActiveWorkspaceError(t *testing.T) {
|
|||
t.Fatalf("syncProjectIDFromDB should not create local .beads, stat err = %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// strictReadonlyRestoreRefusal is the line CheckReadonly prints when a write
|
||||
// command is run under strict --readonly.
|
||||
const strictReadonlyRestoreRefusal = "Error: operation 'backup restore' is not allowed in read-only mode\n"
|
||||
|
||||
// assertStrictReadonlyRestoreRefused checks one refused `bd --readonly backup
|
||||
// restore` run: the standard CheckReadonly refusal (text and exit code), nothing
|
||||
// on stdout, and none of the storage-layer message that embedded mode gives when
|
||||
// the command gets past CheckReadonly and opens the store.
|
||||
func assertStrictReadonlyRestoreRefused(t *testing.T, stdout, stderr string, code int) {
|
||||
t.Helper()
|
||||
if code != 1 {
|
||||
t.Errorf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, strictReadonlyRestoreRefusal) {
|
||||
t.Errorf("stderr is missing the standard refusal %q:\n%s", strictReadonlyRestoreRefusal, stderr)
|
||||
}
|
||||
if strings.Contains(stderr, "embeddeddolt: store is read-only") {
|
||||
t.Errorf("stderr carries the storage-layer refusal, so the command opened the store before being refused:\n%s", stderr)
|
||||
}
|
||||
if strings.TrimSpace(stdout) != "" {
|
||||
t.Errorf("stdout should be empty when the restore is refused, got:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// workspaceSnapshot is what a refused command must leave alone: the entries of
|
||||
// the project directory (the workspace gate file and its holder sidecar sit
|
||||
// beside .beads, not in it) and everything below .beads, content included.
|
||||
type workspaceSnapshot struct {
|
||||
projectEntries []string
|
||||
beads readonlyTreeSnapshot
|
||||
}
|
||||
|
||||
func snapshotWorkspace(t *testing.T, dir string) workspaceSnapshot {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
return workspaceSnapshot{
|
||||
projectEntries: names,
|
||||
beads: snapshotReadonlyTree(t, filepath.Join(dir, ".beads")),
|
||||
}
|
||||
}
|
||||
|
||||
// assertWorkspaceUnchanged fails, naming each path, when the workspace under dir
|
||||
// no longer matches a snapshot taken before a refused command.
|
||||
func assertWorkspaceUnchanged(t *testing.T, dir string, before workspaceSnapshot) {
|
||||
t.Helper()
|
||||
after := snapshotWorkspace(t, dir)
|
||||
var diffs []string
|
||||
for _, name := range before.projectEntries {
|
||||
if !slices.Contains(after.projectEntries, name) {
|
||||
diffs = append(diffs, "removed: "+name)
|
||||
}
|
||||
}
|
||||
for _, name := range after.projectEntries {
|
||||
if !slices.Contains(before.projectEntries, name) {
|
||||
diffs = append(diffs, "created: "+name)
|
||||
}
|
||||
}
|
||||
for path, want := range before.beads.Entries {
|
||||
switch got, ok := after.beads.Entries[path]; {
|
||||
case !ok:
|
||||
diffs = append(diffs, "removed: .beads/"+path)
|
||||
case got != want:
|
||||
diffs = append(diffs, "changed: .beads/"+path)
|
||||
}
|
||||
}
|
||||
for path := range after.beads.Entries {
|
||||
if _, ok := before.beads.Entries[path]; !ok {
|
||||
diffs = append(diffs, "created: .beads/"+path)
|
||||
}
|
||||
}
|
||||
if len(diffs) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Strings(diffs)
|
||||
const show = 20
|
||||
if len(diffs) > show {
|
||||
diffs = append(diffs[:show], fmt.Sprintf("... and %d more", len(diffs)-show))
|
||||
}
|
||||
t.Errorf("the refused restore changed the workspace:\n%s", strings.Join(diffs, "\n"))
|
||||
}
|
||||
|
||||
// TestBackupRestoreStrictReadonlyServerMode is the server-mode counterpart of
|
||||
// TestEmbeddedBackupRestoreStrictReadonly. Server mode is where the missing
|
||||
// refusal mattered: no storage layer stops a server connection, so a
|
||||
// `bd --readonly backup restore --force` ran to the end and replaced the store.
|
||||
// It drives the built bd as a subprocess because CheckReadonly exits the
|
||||
// process. Both the fixture's backup and the restore run inside the Dolt
|
||||
// server, against the same path on the server's own filesystem, so a local
|
||||
// and a containerized test server both serve.
|
||||
func TestBackupRestoreStrictReadonlyServerMode(t *testing.T) {
|
||||
if testDoltServerPort == 0 {
|
||||
t.Skip("Dolt test server not available")
|
||||
}
|
||||
if testutil.DoltContainerCrashed() {
|
||||
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
|
||||
}
|
||||
|
||||
bd := buildBDForInitTests(t)
|
||||
|
||||
// newWorkspace builds a server-mode workspace on the test server whose live
|
||||
// store holds one issue its backup does not (three against two), so a restore
|
||||
// that really ran shows up as a changed issue count. Each case gets its own: a
|
||||
// restore that runs replaces the store and would hide a leak from the next.
|
||||
newWorkspace := func(t *testing.T) (dir string, env []string, backupDir string) {
|
||||
t.Helper()
|
||||
dir = t.TempDir()
|
||||
beadsDir := filepath.Join(dir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
database := uniqueTestDBName(t)
|
||||
if err := (&configfile.Config{
|
||||
Backend: configfile.BackendDolt,
|
||||
DoltMode: configfile.DoltModeServer,
|
||||
DoltServerHost: "127.0.0.1",
|
||||
DoltServerPort: testDoltServerPort,
|
||||
DoltDatabase: database,
|
||||
}).Save(beadsDir); err != nil {
|
||||
t.Fatalf("save workspace metadata: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
seedStore, err := dolt.New(ctx, &dolt.Config{
|
||||
Path: filepath.Join(beadsDir, "dolt"),
|
||||
BeadsDir: beadsDir,
|
||||
ServerHost: "127.0.0.1",
|
||||
ServerPort: testDoltServerPort,
|
||||
Database: database,
|
||||
CreateIfMissing: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create the server-mode database: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
|
||||
defer func() { _ = seedStore.Close() }()
|
||||
|
||||
if err := seedStore.SetConfig(ctx, "issue_prefix", "rr"); err != nil {
|
||||
t.Fatalf("set issue_prefix: %v", err)
|
||||
}
|
||||
seed := func(id, title string) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
issue := &types.Issue{
|
||||
ID: id,
|
||||
Title: title,
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := seedStore.CreateIssue(ctx, issue, "test-user"); err != nil {
|
||||
t.Fatalf("create issue %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
commit := func(message string) {
|
||||
t.Helper()
|
||||
if err := seedStore.Commit(ctx, message); err != nil && !strings.Contains(err.Error(), "nothing to commit") {
|
||||
t.Fatalf("commit %q: %v", message, err)
|
||||
}
|
||||
}
|
||||
|
||||
seed("rr-1", "issue in the backup A")
|
||||
seed("rr-2", "issue in the backup B")
|
||||
commit("issues the backup holds")
|
||||
|
||||
backupDir = filepath.Join(t.TempDir(), "dolt-backup")
|
||||
if err := os.MkdirAll(backupDir, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := seedStore.BackupDatabase(ctx, backupDir); err != nil {
|
||||
t.Fatalf("back up the database (the Dolt server must be able to write %s): %v", backupDir, err)
|
||||
}
|
||||
|
||||
seed("rr-3", "issue created after the backup")
|
||||
commit("issue the backup lacks")
|
||||
|
||||
env = []string{
|
||||
"BEADS_TEST_MODE=1",
|
||||
// The subprocess connects to a testdb_* database on the test server;
|
||||
// this is the opt-in the test-database firewall asks for.
|
||||
"BEADS_TEST_SERVER=1",
|
||||
"BEADS_DIR=" + beadsDir,
|
||||
"XDG_CONFIG_HOME=" + t.TempDir(),
|
||||
// Keep the subprocess's circuit-breaker state in the suite's own
|
||||
// directory rather than the host's temp dir.
|
||||
"BEADS_TEST_CIRCUIT_DIR=" + os.Getenv("BEADS_TEST_CIRCUIT_DIR"),
|
||||
}
|
||||
return dir, env, backupDir
|
||||
}
|
||||
|
||||
issueCount := func(t *testing.T, dir string, env []string) int {
|
||||
t.Helper()
|
||||
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "list", "--json")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd list --json exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
start := strings.Index(stdout, "[")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON array in bd list --json output:\n%s", stdout)
|
||||
}
|
||||
var issues []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(stdout[start:]), &issues); err != nil {
|
||||
t.Fatalf("parse bd list --json output: %v\n%s", err, stdout)
|
||||
}
|
||||
return len(issues)
|
||||
}
|
||||
|
||||
// The control proves the fixture really does restore when --readonly is not
|
||||
// asked for, so "the store is unchanged" below cannot be vacuous.
|
||||
t.Run("control_restore_without_readonly", func(t *testing.T) {
|
||||
dir, env, backupDir := newWorkspace(t)
|
||||
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "backup", "restore", "--force", backupDir)
|
||||
if code != 0 {
|
||||
t.Fatalf("restore without --readonly exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, "Restore complete") {
|
||||
t.Errorf("stdout is missing %q:\n%s", "Restore complete", stdout)
|
||||
}
|
||||
if got := issueCount(t, dir, env); got != 2 {
|
||||
t.Errorf("issue count after a real restore = %d, want 2: the backup holds two issues and the live store held three", got)
|
||||
}
|
||||
})
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
flags []string
|
||||
}{
|
||||
{"readonly", []string{"--readonly"}},
|
||||
{"readonly_sandbox", []string{"--readonly", "--sandbox"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir, env, backupDir := newWorkspace(t)
|
||||
before := snapshotWorkspace(t, dir)
|
||||
|
||||
args := append(append([]string{}, tc.flags...), "backup", "restore", "--force", backupDir)
|
||||
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, args...)
|
||||
|
||||
assertStrictReadonlyRestoreRefused(t, stdout, stderr, code)
|
||||
assertWorkspaceUnchanged(t, dir, before)
|
||||
if got := issueCount(t, dir, env); got != 3 {
|
||||
t.Errorf("issue count after the refused restore = %d, want 3: the restore replaced the store", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -207,6 +207,12 @@ Examples:
|
|||
}
|
||||
|
||||
if beadsDir == "" {
|
||||
// Discovery passes over a .beads marked only by a legacy
|
||||
// config.json. One in a format this build cannot open is refused
|
||||
// as that, not reported as no workspace.
|
||||
if err := checkUndiscoveredWorkspaceFormat(); err != nil {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
if jsonOutput {
|
||||
if err := outputJSON(noWorkspaceBootstrapPayload()); err != nil {
|
||||
return err
|
||||
|
|
@ -219,7 +225,7 @@ Examples:
|
|||
}
|
||||
|
||||
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
||||
return HandleError("%v", err)
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
|
||||
// Load config from .beads/metadata.json. When the beadsDir was
|
||||
|
|
@ -234,7 +240,9 @@ Examples:
|
|||
}
|
||||
if cfg == nil {
|
||||
cfg, err = findParentConfig(beadsDir)
|
||||
if err != nil {
|
||||
if isUnsupportedWorkspaceFormat(err) {
|
||||
return handleWorkspaceGuardError(err)
|
||||
} else if err != nil {
|
||||
return HandleError("failed to load ancestor storage metadata: %v; no storage database was opened or modified; fix or restore metadata.json and retry", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1586,6 +1594,9 @@ func isNonInteractiveBootstrap(flagValue bool) bool {
|
|||
// parent workspace does. Returns nil if no parent config is found. A malformed
|
||||
// or unreadable ancestor metadata file is authoritative and returned as an error;
|
||||
// bootstrap must not skip it and select a more distant workspace or defaults.
|
||||
// An ancestor holding the graph format marker without metadata it can read is
|
||||
// a graph workspace, refused like one whose metadata declares graph_mode,
|
||||
// rather than skipped or reported as a metadata load failure.
|
||||
func findParentConfig(beadsDir string) (*configfile.Config, error) {
|
||||
// Start from the parent of beadsDir's enclosing directory.
|
||||
// beadsDir is typically "<project>/.beads", so we start from <project>'s parent.
|
||||
|
|
@ -1603,6 +1614,9 @@ func findParentConfig(beadsDir string) (*configfile.Config, error) {
|
|||
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
|
||||
candidate := filepath.Join(dir, ".beads")
|
||||
cfg, err := configfile.LoadForDiscovery(candidate)
|
||||
if (err != nil || cfg == nil) && hasGraphFormatMarker(candidate) {
|
||||
return nil, &configfile.UnsupportedWorkspaceFormatError{BeadsDir: candidate, FormatMarker: true}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", configfile.ConfigPath(candidate), err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,6 +79,9 @@ const (
|
|||
trackSync = "proxied-parity S5 (bd sync)"
|
||||
trackDegradation = "proxied-parity S6 (doctor, config show, degradations)"
|
||||
trackLongTail = "proxied-parity S7 (long-tail policy pass)"
|
||||
// Versioned history (gastownhall/beads#6132) is not a proxied-parity slice:
|
||||
// its reads need a storage.VersionLister over the proxied uow provider.
|
||||
trackVersionedHistory = "versioned history: VersionLister over the proxied uow provider (gastownhall/beads#6132)"
|
||||
)
|
||||
|
||||
// capabilityRow is one command-path policy row. ArgSet is the sorted set of
|
||||
|
|
@ -451,6 +454,16 @@ var proxyCapabilityRegistry = []capabilityRow{
|
|||
// at the front door would leave those modes with no way to flush.
|
||||
permitted("dolt commit").withHistory(HistoryProxySupported),
|
||||
|
||||
// --- versioned history ----------------------------------------------------
|
||||
// `bd versions` is a pure read (issueops.ListVersionsInTx in one read
|
||||
// transaction), so nothing about it is unsafe on a shared backend. It is
|
||||
// refused only because no proxied route exists yet: it reaches the backend
|
||||
// through the optional storage.VersionLister, which the dolt and embedded
|
||||
// stores implement and the uow provider does not. Permitting it would open
|
||||
// the proxied provider in the root pre-run and then fail untyped at
|
||||
// errVersionsUnsupported, so it is refused here, before any side effect.
|
||||
refusedPath("versions", "proxy.versions.unsupported", ProxyReasonUnimplemented, trackVersionedHistory),
|
||||
|
||||
// --- untyped refusals inside RunE ---------------------------------------
|
||||
// The gate permits these paths and the command refuses itself with a bare
|
||||
// string, so a JSON consumer gets no code and no mutates flag. They are
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestIfRevisionCloseReplaysMoleculeAutoClose pins mc-zndi7.75 item 1 on the
|
||||
// TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose pins mc-zndi7.75 item 1 on the
|
||||
// embedded/direct --if-revision close route: runCloseDirectIfRevision bypasses
|
||||
// `bd close`'s batch architecture entirely (A8, beads#4682 — BatchCloseItem
|
||||
// carries no per-item ExpectedVersion), so it must re-drive molecule auto-close
|
||||
|
|
@ -22,7 +22,7 @@ import (
|
|||
// state a crash between the final step's close and its root auto-close would
|
||||
// leave), then re-close the final step — this time guarded — and require the
|
||||
// stranded-open root to heal.
|
||||
func TestIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose(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")
|
||||
}
|
||||
|
|
@ -60,12 +60,12 @@ func TestIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestIfRevisionCloseWarnsOnForcedOpenChildren pins mc-zndi7.75 item 3: the
|
||||
// TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren pins mc-zndi7.75 item 3: the
|
||||
// "warning: closing X with N open child issue(s) still active" line
|
||||
// (close.go:194-196) must still print on the guarded direct close route when
|
||||
// --force waives the engine's open-children refusal, exactly as it does on
|
||||
// the unguarded batch path.
|
||||
func TestIfRevisionCloseWarnsOnForcedOpenChildren(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import (
|
|||
)
|
||||
|
||||
// TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose is
|
||||
// TestIfRevisionCloseReplaysMoleculeAutoClose's proxied-server twin, pinning
|
||||
// TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose's proxied-server twin, pinning
|
||||
// mc-zndi7.75 item 1 on the route `bd serve` actually runs:
|
||||
// runCloseProxiedIfRevision bypasses the batch entirely (A8, beads#4682), so
|
||||
// it must re-drive molecule auto-close itself via its own post-close unit of
|
||||
|
|
@ -53,7 +53,7 @@ func TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestProxiedServerIfRevisionCloseWarnsOnForcedOpenChildren is
|
||||
// TestIfRevisionCloseWarnsOnForcedOpenChildren's proxied-server twin, pinning
|
||||
// TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren's proxied-server twin, pinning
|
||||
// mc-zndi7.75 item 3 on the proxied route.
|
||||
func TestProxiedServerIfRevisionCloseWarnsOnForcedOpenChildren(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
|
|
|
|||
444
cmd/bd/command_tree_golden_test.go
Normal file
444
cmd/bd/command_tree_golden_test.go
Normal file
|
|
@ -0,0 +1,444 @@
|
|||
//go:build cgo
|
||||
|
||||
// cgo only: the goldens pin the cgo build, which every lane that runs this
|
||||
// package's full suite compiles. The !cgo build replaces the federation
|
||||
// subtree with a one-command stub (federation_nocgo.go), so its tree differs
|
||||
// by design.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// The committed command-surface goldens. Regenerate after an intentional CLI
|
||||
// change, then review the diff like code:
|
||||
//
|
||||
// BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'
|
||||
//
|
||||
// CGO_ENABLED=1 because this file builds only with cgo: with cgo off the
|
||||
// command matches no test, exits 0 and leaves the goldens as they were.
|
||||
const (
|
||||
commandTreeGoldenPath = "testdata/command_tree/tree.golden"
|
||||
commandHelpGoldenDir = "testdata/command_tree/help"
|
||||
commandGoldenRegen = "BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'"
|
||||
)
|
||||
|
||||
// commandHelpGoldenArgs is the representative set of commands whose exact
|
||||
// --help output is pinned, each as the argv after "bd". The tree golden
|
||||
// covers every command's metadata; these cover the rendering (usage line,
|
||||
// flag table layout, inherited global flags, root command groups).
|
||||
var commandHelpGoldenArgs = [][]string{
|
||||
{},
|
||||
{"create"},
|
||||
{"show"},
|
||||
{"list"},
|
||||
{"update"},
|
||||
{"close"},
|
||||
{"version"},
|
||||
{"versions"},
|
||||
{"config"},
|
||||
{"serve"},
|
||||
}
|
||||
|
||||
// TestCommandTreeGolden pins the whole bd command tree: for every command and
|
||||
// subcommand, hidden ones included, its Use, Aliases, Short, Long, Example,
|
||||
// group, hidden/deprecated state, runnability and annotations, and every
|
||||
// local and persistent flag it defines (name, shorthand, type, default,
|
||||
// usage, hidden, deprecation, annotations). Any added, removed or reworded
|
||||
// command or flag fails this test until the golden is regenerated, so the
|
||||
// change shows up as a reviewed testdata diff. It reads the in-memory tree
|
||||
// only: no store or subprocess.
|
||||
//
|
||||
// docs/cli-docs.pin pins the generated CLI reference (and check-doc-flags)
|
||||
// to a release, so drift on main is not caught there; this golden is the
|
||||
// live guard for the command surface.
|
||||
func TestCommandTreeGolden(t *testing.T) {
|
||||
pkgDir := enterOrdinaryWorkspaceForGolden(t)
|
||||
primeCommandTreeForGolden()
|
||||
flagCounts := commandFlagCounts(rootCmd)
|
||||
got := renderCommandTreeGolden(rootCmd)
|
||||
// A renderer that iterated a map would pass on the run that regenerated
|
||||
// the golden and flake afterwards.
|
||||
if again := renderCommandTreeGolden(rootCmd); again != got {
|
||||
t.Fatalf("command tree rendering is not deterministic:\n%s", goldenLineDiff(got, again))
|
||||
}
|
||||
// Nor may rendering change the tree it reads: tests sharing this binary
|
||||
// pin a command's exact flag set (TestServeFlags). See goldenLocalFlags.
|
||||
if after := commandFlagCounts(rootCmd); after != flagCounts {
|
||||
t.Fatalf("rendering the command tree added flags to a command's own flag set:\n%s", goldenLineDiff(flagCounts, after))
|
||||
}
|
||||
checkCommandGolden(t, pkgDir, commandTreeGoldenPath, got)
|
||||
}
|
||||
|
||||
// TestCommandHelpGolden pins the exact `bd <command> --help` output of a
|
||||
// representative set of commands, executed in-process through the real root
|
||||
// command. --help returns before the root pre-run, so no store is opened.
|
||||
// Color escapes are stripped so the snapshot is independent of terminal
|
||||
// detection; otherwise the snapshots are byte-identical to what a built bd
|
||||
// prints.
|
||||
func TestCommandHelpGolden(t *testing.T) {
|
||||
pkgDir := enterOrdinaryWorkspaceForGolden(t)
|
||||
// Parsing `bd serve --help` merges the root's persistent flags into
|
||||
// serveCmd's own flag set, which TestServeFlags pins; restoreServeGlobals
|
||||
// re-registers that set afterwards.
|
||||
restoreServeGlobals(t)
|
||||
|
||||
want := map[string]bool{}
|
||||
for _, args := range commandHelpGoldenArgs {
|
||||
name := strings.Join(append([]string{"bd"}, args...), "_")
|
||||
file := name + ".golden"
|
||||
want[file] = true
|
||||
t.Run(name, func(t *testing.T) {
|
||||
checkCommandGolden(t, pkgDir, filepath.Join(commandHelpGoldenDir, file), renderCommandHelpGolden(t, args))
|
||||
})
|
||||
}
|
||||
|
||||
// The directory holds exactly the listed snapshots: a command dropped
|
||||
// from the list must not leave a stale file that still looks pinned.
|
||||
dir := filepath.Join(pkgDir, commandHelpGoldenDir)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", commandHelpGoldenDir, err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if want[e.Name()] {
|
||||
continue
|
||||
}
|
||||
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
|
||||
if err := os.Remove(filepath.Join(dir, e.Name())); err != nil {
|
||||
t.Fatalf("remove stale help golden %s: %v", e.Name(), err)
|
||||
}
|
||||
t.Logf("removed stale help golden %s", e.Name())
|
||||
continue
|
||||
}
|
||||
t.Errorf("%s/%s is not in commandHelpGoldenArgs; delete it or regenerate with %s", commandHelpGoldenDir, e.Name(), commandGoldenRegen)
|
||||
}
|
||||
}
|
||||
|
||||
// enterOrdinaryWorkspaceForGolden moves the test into a fresh ordinary
|
||||
// (dependency-mode) workspace: a .beads/metadata.json with no graph marker
|
||||
// and no database behind it, so nothing can be read from or written to a
|
||||
// store. It returns the package directory, where the goldens live.
|
||||
func enterOrdinaryWorkspaceForGolden(t *testing.T) string {
|
||||
t.Helper()
|
||||
isolateBeadsDirForTest(t)
|
||||
pkgDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := t.TempDir()
|
||||
beadsDir := filepath.Join(ws, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(ws)
|
||||
return pkgDir
|
||||
}
|
||||
|
||||
// primeCommandTreeForGolden completes the tree the way the bd binary does
|
||||
// before it dispatches: main() adds cobra's help command and its
|
||||
// --all/--doc/--list/--docs-root flags, and ExecuteC adds the completion
|
||||
// command. All three are idempotent, so the tree is the same whether or not
|
||||
// an earlier in-process test already executed rootCmd.
|
||||
func primeCommandTreeForGolden() {
|
||||
rootCmd.InitDefaultHelpCmd()
|
||||
registerHelpAllFlag()
|
||||
rootCmd.InitDefaultCompletionCmd()
|
||||
}
|
||||
|
||||
// renderCommandTreeGolden walks cmd's tree depth first, children sorted by
|
||||
// name, and renders one block per command.
|
||||
func renderCommandTreeGolden(root *cobra.Command) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("# bd command tree (cgo build), pinned by TestCommandTreeGolden.\n")
|
||||
b.WriteString("# Regenerate after an intentional CLI change:\n")
|
||||
b.WriteString("# " + commandGoldenRegen + "\n")
|
||||
|
||||
var walk func(*cobra.Command)
|
||||
walk = func(c *cobra.Command) {
|
||||
writeCommandGoldenBlock(&b, c)
|
||||
children := append([]*cobra.Command(nil), c.Commands()...)
|
||||
sort.Slice(children, func(i, j int) bool { return children[i].Name() < children[j].Name() })
|
||||
for _, sub := range children {
|
||||
// cobra adds the hidden shell-completion request commands only
|
||||
// for an execution that invokes them, and then never removes
|
||||
// them: whether they are present depends on test history, not
|
||||
// on the bd surface.
|
||||
if sub.Name() == cobra.ShellCompRequestCmd || sub.Name() == cobra.ShellCompNoDescRequestCmd {
|
||||
continue
|
||||
}
|
||||
walk(sub)
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func writeCommandGoldenBlock(b *strings.Builder, c *cobra.Command) {
|
||||
fmt.Fprintf(b, "\n%s\n", c.CommandPath())
|
||||
fmt.Fprintf(b, " use: %q\n", c.Use)
|
||||
if len(c.Aliases) > 0 {
|
||||
fmt.Fprintf(b, " aliases: %q\n", c.Aliases)
|
||||
}
|
||||
fmt.Fprintf(b, " short: %q\n", c.Short)
|
||||
if c.GroupID != "" {
|
||||
fmt.Fprintf(b, " group: %q\n", c.GroupID)
|
||||
}
|
||||
fmt.Fprintf(b, " hidden: %t\n", c.Hidden)
|
||||
if c.Deprecated != "" {
|
||||
fmt.Fprintf(b, " deprecated: %q\n", c.Deprecated)
|
||||
}
|
||||
fmt.Fprintf(b, " runnable: %t\n", c.Runnable())
|
||||
if c.DisableFlagParsing {
|
||||
b.WriteString(" disable-flag-parsing: true\n")
|
||||
}
|
||||
if len(c.ValidArgs) > 0 {
|
||||
fmt.Fprintf(b, " valid-args: %q\n", c.ValidArgs)
|
||||
}
|
||||
if len(c.Annotations) > 0 {
|
||||
fmt.Fprintf(b, " annotations: %s\n", formatGoldenAnnotations(c.Annotations))
|
||||
}
|
||||
writeGoldenTextBlock(b, "long", c.Long)
|
||||
writeGoldenTextBlock(b, "example", c.Example)
|
||||
for _, line := range commandGoldenFlagLines(c.PersistentFlags()) {
|
||||
fmt.Fprintf(b, " persistent-flag %s\n", line)
|
||||
}
|
||||
for _, line := range commandGoldenFlagLines(goldenLocalFlags(c)) {
|
||||
fmt.Fprintf(b, " flag %s\n", line)
|
||||
}
|
||||
}
|
||||
|
||||
// goldenLocalFlags returns the non-persistent flags c registers itself,
|
||||
// including any that shadow an inherited flag: the set
|
||||
// c.LocalNonPersistentFlags() reports, read without calling it. That
|
||||
// accessor, like LocalFlags and InheritedFlags, runs cobra's
|
||||
// mergePersistentFlags, which copies every inherited persistent flag into
|
||||
// c.Flags() for the rest of the process. Over the whole tree that would leave
|
||||
// `bd serve` carrying the root's --json, --db and the rest, and break
|
||||
// TestServeFlags (see TestNoSubcommandShadowsRootJSONFlag).
|
||||
//
|
||||
// c.Flags() may already hold such copies from an earlier in-process
|
||||
// execution. They are recognized by identity, the way cobra itself tells
|
||||
// them apart: an inherited flag is the nearest ancestor's own *pflag.Flag of
|
||||
// that name, and a shadowing flag is a different one.
|
||||
func goldenLocalFlags(c *cobra.Command) *pflag.FlagSet {
|
||||
local := pflag.NewFlagSet(c.Name(), pflag.ContinueOnError)
|
||||
c.Flags().VisitAll(func(f *pflag.Flag) {
|
||||
if c.PersistentFlags().Lookup(f.Name) != nil {
|
||||
return // rendered as a persistent-flag line
|
||||
}
|
||||
for p := c.Parent(); p != nil; p = p.Parent() {
|
||||
if inherited := p.PersistentFlags().Lookup(f.Name); inherited != nil {
|
||||
if inherited == f {
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
local.AddFlag(f)
|
||||
})
|
||||
return local
|
||||
}
|
||||
|
||||
// commandFlagCounts renders how many flags each command's own flag set holds,
|
||||
// one line per command, read without merging anything into it.
|
||||
func commandFlagCounts(root *cobra.Command) string {
|
||||
var b strings.Builder
|
||||
var walk func(*cobra.Command)
|
||||
walk = func(c *cobra.Command) {
|
||||
n := 0
|
||||
c.Flags().VisitAll(func(*pflag.Flag) { n++ })
|
||||
fmt.Fprintf(&b, "%s %d\n", c.CommandPath(), n)
|
||||
for _, sub := range c.Commands() {
|
||||
walk(sub)
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// writeGoldenTextBlock writes a multi-line field one source line per golden
|
||||
// line, behind a "|" gutter so leading whitespace and blank lines survive.
|
||||
func writeGoldenTextBlock(b *strings.Builder, name, text string) {
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(b, " %s:\n", name)
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
if line == "" {
|
||||
b.WriteString(" |\n")
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, " | %s\n", line)
|
||||
}
|
||||
}
|
||||
|
||||
// commandGoldenFlagLines renders each flag of fs on one line, sorted by name.
|
||||
// cobra's own lazily added --help flag (FlagSetByCobraAnnotation) is skipped:
|
||||
// it exists only on commands an earlier in-process execution reached.
|
||||
func commandGoldenFlagLines(fs *pflag.FlagSet) []string {
|
||||
var flags []*pflag.Flag
|
||||
fs.VisitAll(func(f *pflag.Flag) {
|
||||
if _, byCobra := f.Annotations[cobra.FlagSetByCobraAnnotation]; byCobra {
|
||||
return
|
||||
}
|
||||
flags = append(flags, f)
|
||||
})
|
||||
sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name })
|
||||
|
||||
lines := make([]string, 0, len(flags))
|
||||
for _, f := range flags {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "--%s", f.Name)
|
||||
if f.Shorthand != "" {
|
||||
fmt.Fprintf(&b, " -%s", f.Shorthand)
|
||||
}
|
||||
fmt.Fprintf(&b, " type=%s default=%q", f.Value.Type(), f.DefValue)
|
||||
if f.NoOptDefVal != "" && !implicitNoOptDefault(f) {
|
||||
fmt.Fprintf(&b, " no-opt-default=%q", f.NoOptDefVal)
|
||||
}
|
||||
if f.Hidden {
|
||||
b.WriteString(" hidden")
|
||||
}
|
||||
if f.Deprecated != "" {
|
||||
fmt.Fprintf(&b, " deprecated=%q", f.Deprecated)
|
||||
}
|
||||
if f.ShorthandDeprecated != "" {
|
||||
fmt.Fprintf(&b, " shorthand-deprecated=%q", f.ShorthandDeprecated)
|
||||
}
|
||||
if len(f.Annotations) > 0 {
|
||||
fmt.Fprintf(&b, " annotations=%s", formatGoldenAnnotations(f.Annotations))
|
||||
}
|
||||
fmt.Fprintf(&b, " usage=%q", f.Usage)
|
||||
lines = append(lines, b.String())
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// implicitNoOptDefault reports whether f's NoOptDefVal is the one pflag gives
|
||||
// every flag of its type (a bare --bool means true, a bare --count adds one),
|
||||
// which would only repeat the type on each line.
|
||||
func implicitNoOptDefault(f *pflag.Flag) bool {
|
||||
switch f.Value.Type() {
|
||||
case "bool":
|
||||
return f.NoOptDefVal == "true"
|
||||
case "count":
|
||||
return f.NoOptDefVal == "+1"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// formatGoldenAnnotations renders a command's or a flag's annotations sorted
|
||||
// by key.
|
||||
func formatGoldenAnnotations[V string | []string](m map[string]V) string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
parts = append(parts, fmt.Sprintf("%s=%q", k, m[k]))
|
||||
}
|
||||
return "{" + strings.Join(parts, " ") + "}"
|
||||
}
|
||||
|
||||
// renderCommandHelpGolden runs `bd <args> --help` through rootCmd in-process
|
||||
// and returns its stdout with color escapes stripped. cobra keeps the parsed
|
||||
// --help value on the shared tree, so every flag is put back afterwards: a
|
||||
// later in-process `bd create ...` must not print help instead.
|
||||
//
|
||||
// internal/ui decides color once, at init, from CLICOLOR_FORCE and whether the
|
||||
// test binary's stdout is a terminal. CI never gives it one, so there the
|
||||
// strip removes nothing; it is what keeps a run from a terminal matching the
|
||||
// goldens.
|
||||
func renderCommandHelpGolden(t *testing.T, args []string) string {
|
||||
t.Helper()
|
||||
argv := append(append([]string(nil), args...), "--help")
|
||||
primeCommandTreeForGolden()
|
||||
var execErr error
|
||||
out := captureStdout(t, func() error {
|
||||
rootCmd.SetArgs(argv)
|
||||
defer rootCmd.SetArgs(nil)
|
||||
defer resetCommandFlags(rootCmd)
|
||||
_, execErr = rootCmd.ExecuteC()
|
||||
return nil
|
||||
})
|
||||
if execErr != nil {
|
||||
t.Fatalf("bd %s: %v", strings.Join(argv, " "), execErr)
|
||||
}
|
||||
return ansi.Strip(out)
|
||||
}
|
||||
|
||||
// checkCommandGolden compares got with the golden at rel under pkgDir, or
|
||||
// rewrites the golden when BD_UPDATE_GOLDEN=1 (the package's shared golden
|
||||
// switch).
|
||||
func checkCommandGolden(t *testing.T, pkgDir, rel, got string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(pkgDir, rel)
|
||||
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", filepath.Dir(rel), err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
|
||||
t.Fatalf("write golden %s: %v", rel, err)
|
||||
}
|
||||
t.Logf("updated golden %s", rel)
|
||||
return
|
||||
}
|
||||
want, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read golden %s (regenerate with %s): %v", rel, commandGoldenRegen, err)
|
||||
}
|
||||
if bytes.Equal([]byte(got), want) {
|
||||
return
|
||||
}
|
||||
t.Errorf("bd command surface drifted from %s.\n%s\nIf the change is intended, regenerate with\n %s\nand review the testdata diff.",
|
||||
rel, goldenLineDiff(string(want), got), commandGoldenRegen)
|
||||
}
|
||||
|
||||
// goldenLineDiff reports the region where want and got differ: the common
|
||||
// leading and trailing lines are trimmed and the rest is shown as -/+ lines,
|
||||
// capped so a large drift stays readable (the reviewed artifact is the
|
||||
// regenerated testdata diff, not this message).
|
||||
func goldenLineDiff(want, got string) string {
|
||||
const maxLines = 40
|
||||
w := strings.Split(want, "\n")
|
||||
g := strings.Split(got, "\n")
|
||||
pre := 0
|
||||
for pre < len(w) && pre < len(g) && w[pre] == g[pre] {
|
||||
pre++
|
||||
}
|
||||
suf := 0
|
||||
for suf < len(w)-pre && suf < len(g)-pre && w[len(w)-1-suf] == g[len(g)-1-suf] {
|
||||
suf++
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "first difference at line %d:\n", pre+1)
|
||||
write := func(sign string, lines []string) {
|
||||
for i, line := range lines {
|
||||
if i == maxLines {
|
||||
fmt.Fprintf(&b, "%s ... (%d more lines)\n", sign, len(lines)-maxLines)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(&b, "%s %s\n", sign, line)
|
||||
}
|
||||
}
|
||||
write("-", w[pre:len(w)-suf])
|
||||
write("+", g[pre:len(g)-suf])
|
||||
return b.String()
|
||||
}
|
||||
|
|
@ -280,6 +280,12 @@ var configSetCmd = &cobra.Command{
|
|||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
// Per-key validation that needs the store rather than the key alone: turning
|
||||
// versioned history on refuses, writing nothing, while any issue holds a value a
|
||||
// version could not record. The store is open here, on whichever route this is.
|
||||
if err := checkVersionedHistoryCanBeEnabled(rootCtx, key, value); err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
result, err := settings.SetSetting(rootCtx, issueops.SetSettingRequest{Key: key, Value: value})
|
||||
if err != nil {
|
||||
return HandleError("setting config: %v", err)
|
||||
|
|
@ -1222,6 +1228,14 @@ Examples:
|
|||
return HandleError("%v", err)
|
||||
}
|
||||
}
|
||||
// The pre-enable check `bd config set` makes: turning versioned history
|
||||
// on refuses while any issue holds a value a version could not record.
|
||||
// This verb writes the same setting through a loop of its own, so it
|
||||
// makes the check itself, here and before any pair is written: a refusal
|
||||
// stores nothing from the batch.
|
||||
if err := checkVersionedHistoryCanBeEnabled(rootCtx, p.key, p.value); err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var yamlPairs, gitPairs, dbPairs []kvPair
|
||||
|
|
@ -1352,7 +1366,7 @@ var recognizedConfigPrefixes = []string{
|
|||
"status.", "types.", "doctor.suppress.", "routing.", "sync.", "git.",
|
||||
"directory.", "repos.", "external_projects.", "validation.",
|
||||
"lint.", "hierarchy.", "ai.", "backup.", "federation.", "metrics.",
|
||||
"agent.", "claim.", "storage-class.",
|
||||
"agent.", "claim.", "storage-class.", "versioned-history.",
|
||||
}
|
||||
|
||||
// validateStorageClassConfig validates a storage-class.<type> per-type
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/versionedhistory"
|
||||
)
|
||||
|
||||
// configSideEffect describes a hint or warning to show after a config change.
|
||||
|
|
@ -65,6 +67,11 @@ func checkConfigSetSideEffects(key, value string) []configSideEffect {
|
|||
Message: fmt.Sprintf("Git sync remote set to %q. Ensure this git remote exists.", value),
|
||||
Command: fmt.Sprintf("git remote -v | grep %s", value),
|
||||
})
|
||||
|
||||
case key == versionedHistorySettingKey && versionedhistory.ValueEnables(value):
|
||||
effects = append(effects, configSideEffect{
|
||||
Message: "Versioned history now records for this store. The setting replicates on 'bd dolt push' and 'bd dolt pull', so every clone that pulls it records too, and it is safe with a single writer only: keep one writer at a time per store (docs/reference/configuration.md#versioned-issue-history).",
|
||||
})
|
||||
}
|
||||
|
||||
return effects
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
|
@ -105,6 +106,34 @@ func TestCheckConfigSetSideEffects_UnknownKey(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// versioned-history.enabled is a row of the store's config table, which
|
||||
// replicates on `bd dolt push` and `bd dolt pull`, and the feature is single
|
||||
// writer only. `bd config set ... true` is the moment someone turns it on, so it
|
||||
// is where that caveat belongs -- said once, at the command that has the effect.
|
||||
func TestVersionedHistoryConfigSetHintsAboutReplicationAndSingleWriter(t *testing.T) {
|
||||
for _, on := range []string{"true", "TRUE", " true ", "1", "t"} {
|
||||
effects := checkConfigSetSideEffects(versionedHistorySettingKey, on)
|
||||
if len(effects) != 1 {
|
||||
t.Errorf("value %q turns recording on: expected 1 hint, got %d", on, len(effects))
|
||||
continue
|
||||
}
|
||||
for _, want := range []string{"replicates", "single writer"} {
|
||||
if !strings.Contains(strings.ToLower(effects[0].Message), want) {
|
||||
t.Errorf("value %q: the hint does not mention %q: %s", on, want, effects[0].Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Turning it off, or anything that does not turn it on, needs no caveat.
|
||||
for _, off := range []string{"false", "0", "", "off", "nonsense"} {
|
||||
if effects := checkConfigSetSideEffects(versionedHistorySettingKey, off); len(effects) != 0 {
|
||||
t.Errorf("value %q does not turn recording on: expected no hint, got %d", off, len(effects))
|
||||
}
|
||||
}
|
||||
if effects := checkConfigUnsetSideEffects(versionedHistorySettingKey); len(effects) != 0 {
|
||||
t.Errorf("unsetting the key needs no hint, got %d", len(effects))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckConfigUnsetSideEffects_FederationRemote(t *testing.T) {
|
||||
effects := checkConfigUnsetSideEffects("federation.remote")
|
||||
if len(effects) != 1 {
|
||||
|
|
|
|||
|
|
@ -373,6 +373,11 @@ var createCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
if dryRun && parentID == "" {
|
||||
// The preview opens no target, but it refuses a local one in a
|
||||
// format this build cannot open, as the create it previews would.
|
||||
if err := checkRepoTargetFormat(repoPath); err != nil {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
return renderDryRun()
|
||||
}
|
||||
|
||||
|
|
@ -402,6 +407,9 @@ var createCmd = &cobra.Command{
|
|||
// flag value can be ambiguous.
|
||||
allowCreate := !isAmbiguousRepoTarget(cmd.Flags().Changed("repo"), repoOverride)
|
||||
if err := ensureBeadsDirForPath(rootCtx, targetBeadsDir, store, allowCreate); err != nil {
|
||||
if isUnsupportedWorkspaceFormat(err) {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
return HandleError("failed to initialize target repo: %v", err)
|
||||
}
|
||||
|
||||
|
|
@ -969,8 +977,12 @@ func init() {
|
|||
}
|
||||
|
||||
// handleCreateTargetStoreError preserves the existing text path for ordinary
|
||||
// store failures while rendering capability refusals as typed JSON when asked.
|
||||
// store failures while rendering capability refusals as typed JSON when asked,
|
||||
// and a target in a format this build cannot open as the workspace refusal.
|
||||
func handleCreateTargetStoreError(err error, targetPath, fallbackFormat string) error {
|
||||
if isUnsupportedWorkspaceFormat(err) {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
var capErr *ProxyCapabilityError
|
||||
if !errors.As(err, &capErr) {
|
||||
return HandleError(fallbackFormat, err)
|
||||
|
|
@ -1020,6 +1032,12 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt
|
|||
|
||||
targetPath := routing.ExpandPath(repoPath)
|
||||
beadsDir := filepath.Join(targetPath, ".beads")
|
||||
// A target in a format this build cannot open is refused as that, even
|
||||
// one marked only by a legacy config.json, which the check below would
|
||||
// report as not initialized.
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadataPath := filepath.Join(beadsDir, "metadata.json")
|
||||
if _, err := os.Stat(metadataPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
|
|
@ -1035,6 +1053,17 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt
|
|||
return store, nil
|
||||
}
|
||||
|
||||
// checkRepoTargetFormat refuses a local create target in a format this build
|
||||
// cannot open, reading its metadata without opening or migrating it. The
|
||||
// command's own workspace (".") has passed admission already, and a remote
|
||||
// target has no local metadata to read, so both pass.
|
||||
func checkRepoTargetFormat(repoPath string) error {
|
||||
if repoPath == "." || remotecache.IsRemoteURL(repoPath) {
|
||||
return nil
|
||||
}
|
||||
return checkDiscoveredWorkspaceFormat(filepath.Join(routing.ExpandPath(repoPath), ".beads"))
|
||||
}
|
||||
|
||||
// isAmbiguousRepoTarget reports whether an explicit --repo value is a
|
||||
// bare/relative filesystem path (not absolute, not "~/"-prefixed). Such a
|
||||
// value silently resolves against the current working directory (see
|
||||
|
|
@ -1055,6 +1084,14 @@ func ensureBeadsDirForPath(ctx context.Context, targetPath string, sourceStore s
|
|||
beadsDir := filepath.Join(targetPath, ".beads")
|
||||
metadataPath := filepath.Join(beadsDir, "metadata.json")
|
||||
|
||||
// A target in a format this build cannot open is refused before anything
|
||||
// below: one marked only by a legacy config.json or by the graph format
|
||||
// marker file has no metadata.json, so it would otherwise be initialized
|
||||
// here, with an Issue database and a metadata.json written beside it.
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if beads directory already exists with a Dolt database.
|
||||
// metadata.json is the canonical marker for an initialized beads dir.
|
||||
if _, err := os.Stat(metadataPath); err == nil {
|
||||
|
|
|
|||
|
|
@ -390,6 +390,14 @@ func TestEmbeddedDepBTreeAndCycles(t *testing.T) {
|
|||
if !strings.Contains(out, "flowchart") && !strings.Contains(out, "graph") {
|
||||
t.Errorf("expected mermaid flowchart/graph syntax: %s", out)
|
||||
}
|
||||
// Mixed-case pins case-folding at the runDepTree dispatch site.
|
||||
// TestDepTreeFormatMermaidCaseInsensitive calls isMermaidTreeFormat
|
||||
// directly and would stay green if the call site went back to
|
||||
// formatStr == "mermaid" (the PR #6646 bug).
|
||||
mixed := bdDep(t, bd, dir, "tree", epic.ID, "--format", "Mermaid")
|
||||
if !strings.Contains(mixed, "flowchart") && !strings.Contains(mixed, "graph") {
|
||||
t.Errorf("expected mermaid flowchart/graph syntax for --format Mermaid: %s", mixed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("tree_json_output", func(t *testing.T) {
|
||||
|
|
|
|||
86
cmd/bd/discovery_refusal_pins_embedded_test.go
Normal file
86
cmd/bd/discovery_refusal_pins_embedded_test.go
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestEmbeddedDiscoveryPinsEnvFileReadonly is the store-backed member of the
|
||||
// before-parity discovery pins (discovery_refusal_pins_test.go holds the
|
||||
// store-less ones). It pins how an ordinary workspace applies a BD_READONLY
|
||||
// supplied by its own .beads/.env: a write is refused with the read-only text
|
||||
// and exit 1, also under --json, while reads still run; and a BD_READONLY the
|
||||
// caller exports wins over the file.
|
||||
func TestEmbeddedDiscoveryPinsEnvFileReadonly(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", "pin")
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, ".env"), []byte("BD_READONLY=true\n"), 0o600); err != nil {
|
||||
t.Fatalf("write .beads/.env: %v", err)
|
||||
}
|
||||
|
||||
run := func(extraEnv []string, args ...string) (exit int, stdout, stderr string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
// The store-less pins' closed environment: no BD_*/BEADS_* the caller
|
||||
// exports (BD_READONLY, BD_JSON_ENVELOPE, BD_OTEL_*, ...) reaches bd.
|
||||
// HOME stays dir, where bd init ran.
|
||||
cmd.Env = append(discoveryPinEnv(dir, filepath.Join(dir, "no-such-freeze-marker")),
|
||||
"BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1")
|
||||
cmd.Env = append(cmd.Env, extraEnv...)
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errOut
|
||||
if err := cmd.Run(); err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
t.Fatalf("run bd %v: %v", args, err)
|
||||
}
|
||||
exit = exitErr.ExitCode()
|
||||
}
|
||||
return exit, out.String(), discoveryPinSandboxNotice.ReplaceAllLiteralString(errOut.String(), "")
|
||||
}
|
||||
|
||||
exit, stdout, stderr := run(nil, "create", "refused by .env", "--json")
|
||||
if exit != 1 || stdout != "" || stderr != "Error: operation 'create' is not allowed in read-only mode\n" {
|
||||
t.Fatalf("create under .env BD_READONLY=true: exit=%d stdout=%q stderr=%q; want exit=1, no stdout, the read-only refusal", exit, stdout, stderr)
|
||||
}
|
||||
|
||||
exit, stdout, stderr = run(nil, "list", "--json")
|
||||
if exit != 0 || stdout != "[]\n" {
|
||||
t.Fatalf("list under .env BD_READONLY=true: exit=%d stdout=%q stderr=%q; want exit=0 and an empty list", exit, stdout, stderr)
|
||||
}
|
||||
|
||||
exit, stdout, stderr = run([]string{"BD_READONLY=false"}, "create", "allowed by the caller", "--json")
|
||||
if exit != 0 {
|
||||
t.Fatalf("create with exported BD_READONLY=false: exit=%d stdout=%q stderr=%q; want the caller's setting to win", exit, stdout, stderr)
|
||||
}
|
||||
var created struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &created); err != nil || created.Title != "allowed by the caller" {
|
||||
t.Fatalf("create with exported BD_READONLY=false printed %q (decode error %v)", stdout, err)
|
||||
}
|
||||
|
||||
exit, stdout, stderr = run(nil, "list", "--json")
|
||||
var listed []struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if exit != 0 {
|
||||
t.Fatalf("list after the allowed create: exit=%d stderr=%q", exit, stderr)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &listed); err != nil || len(listed) != 1 || listed[0].Title != "allowed by the caller" {
|
||||
t.Fatalf("list after the allowed create = %q (decode error %v); want only the allowed issue, the refused create wrote nothing", stdout, err)
|
||||
}
|
||||
}
|
||||
885
cmd/bd/discovery_refusal_pins_test.go
Normal file
885
cmd/bd/discovery_refusal_pins_test.go
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
// Before-parity pins for workspace discovery refusals.
|
||||
//
|
||||
// These tests hold the exact text and exit code an ordinary bd prints when
|
||||
// workspace discovery cannot select a usable workspace: a missing or corrupt
|
||||
// metadata.json, an explicit BEADS_DIR that names no workspace, selection
|
||||
// supplied by .beads/.env, .beads/redirect files, --db / BEADS_DB / BD_DB
|
||||
// selection, and the blocked backend environment variables. They pin what
|
||||
// origin/main does today, not what it ideally should do. A change that
|
||||
// reorders admission, discovery or checkBlockedEnvVars in the root
|
||||
// PersistentPreRunE has to change an expectation here, so it shows up in
|
||||
// review as a test diff rather than as an unexplained behavior change.
|
||||
//
|
||||
// Every case runs the real bd binary in a fresh fixture and stops before any
|
||||
// store is opened, so these need no Dolt server or database. Fixture
|
||||
// workspaces with a corrupt metadata.json double as sentinels: the refusal
|
||||
// names the metadata.json it failed to parse, so the text shows which
|
||||
// directory discovery selected without opening a database.
|
||||
//
|
||||
// The pinned no-database hints are an embedded-capable bd's. A CGO_ENABLED=0
|
||||
// bd is server-only and adds "run 'bd doctor' to diagnose" to them, so this
|
||||
// file builds only with cgo, and the bd it runs (built by
|
||||
// buildBDForInitTests, or BEADS_TEST_BD_BINARY) must be a cgo build too.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
)
|
||||
|
||||
// pinNoDatabaseRefusal is what a store-requiring command prints when
|
||||
// discovery finds no workspace with a database.
|
||||
const pinNoDatabaseRefusal = "Error: no beads database found\n" +
|
||||
"Hint: run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database\n" +
|
||||
" or set BEADS_DIR to point to your .beads directory\n"
|
||||
|
||||
// pinNoWorkspaceWhereRefusal is bd where's text refusal when no workspace is
|
||||
// selected.
|
||||
const pinNoWorkspaceWhereRefusal = "Error: No active beads workspace found.\n" +
|
||||
"Hint: check BEADS_DIR/worktree setup, or run 'bd init' to create a new database\n"
|
||||
|
||||
// pinNoWorkspaceWhereJSON is bd where --json's refusal. It goes to stdout.
|
||||
const pinNoWorkspaceWhereJSON = `{
|
||||
"error": "no_beads_directory",
|
||||
"hint": "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database",
|
||||
"message": "No active beads workspace found.",
|
||||
"schema_version": 1
|
||||
}
|
||||
`
|
||||
|
||||
// pinCorruptMetadata is the content of every corrupt metadata.json fixture.
|
||||
const pinCorruptMetadata = "{\n"
|
||||
|
||||
// pinCorruptMetadataWarning is the warning printed while the selected
|
||||
// workspace is bound, before the refusal itself.
|
||||
func pinCorruptMetadataWarning(beadsDir string) string {
|
||||
return "warning: load " + beadsDir + "/metadata.json: parsing config: unexpected end of JSON input; " +
|
||||
"no storage database was opened or modified (storage mode unknown; data commands refuse to fall back to the embedded store)\n"
|
||||
}
|
||||
|
||||
// pinCorruptMetadataRefusal is the full stderr of a command refused because
|
||||
// the selected workspace's metadata.json does not parse.
|
||||
func pinCorruptMetadataRefusal(beadsDir string) string {
|
||||
return pinCorruptMetadataWarning(beadsDir) +
|
||||
"Error: loading config: parsing config: unexpected end of JSON input\n"
|
||||
}
|
||||
|
||||
// pinBlockedEnvRefusal is checkBlockedEnvVars' refusal for name.
|
||||
func pinBlockedEnvRefusal(name string) string {
|
||||
return "Error: " + name + " env var is not supported and has been removed to prevent data fragmentation.\n" +
|
||||
"Unset " + name + "; storage selection comes from .beads/metadata.json. " +
|
||||
"To choose a different supported backend, follow 'bd help init-safety'; do not edit metadata.json by hand\n"
|
||||
}
|
||||
|
||||
// discoveryPinCase is one bd invocation and its exact expected result. The
|
||||
// arguments and the expected strings write the fixture root as $ROOT.
|
||||
type discoveryPinCase struct {
|
||||
name string
|
||||
// setup builds the fixture and returns the working directory and any
|
||||
// environment the invocation adds to the hermetic base.
|
||||
setup func(f *discoveryPinFixture) (cwd string, env []string)
|
||||
args []string
|
||||
exit int
|
||||
stdout string
|
||||
stderr string
|
||||
// stderrPrefix compares only the start of stderr. Use it only where the
|
||||
// rest of the output is not part of the pin.
|
||||
stderrPrefix bool
|
||||
}
|
||||
|
||||
func runDiscoveryPinCases(t *testing.T, cases []discoveryPinCase) {
|
||||
t.Helper()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the pinned texts embed POSIX paths")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildBDForInitTests(t)
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
f := newDiscoveryPinFixture(t)
|
||||
cwd, env := tc.setup(f)
|
||||
args := make([]string, len(tc.args))
|
||||
for i, arg := range tc.args {
|
||||
args[i] = strings.ReplaceAll(arg, "$ROOT", f.root)
|
||||
}
|
||||
exit, stdout, stderr := f.run(bd, cwd, env, args...)
|
||||
if exit != tc.exit {
|
||||
t.Errorf("bd %s: exit = %d, want %d", strings.Join(tc.args, " "), exit, tc.exit)
|
||||
}
|
||||
if stdout != tc.stdout {
|
||||
t.Errorf("bd %s: stdout differs\n got: %q\nwant: %q", strings.Join(tc.args, " "), stdout, tc.stdout)
|
||||
}
|
||||
gotStderr := stderr
|
||||
if tc.stderrPrefix && len(gotStderr) > len(tc.stderr) {
|
||||
gotStderr = gotStderr[:len(tc.stderr)]
|
||||
}
|
||||
if gotStderr != tc.stderr {
|
||||
t.Errorf("bd %s: stderr differs\n got: %q\nwant: %q", strings.Join(tc.args, " "), stderr, tc.stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type discoveryPinFixture struct {
|
||||
t *testing.T
|
||||
root string
|
||||
forms []string // spellings of root to rewrite as $ROOT, longest first
|
||||
}
|
||||
|
||||
func newDiscoveryPinFixture(t *testing.T) *discoveryPinFixture {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
forms := []string{root}
|
||||
if resolved, err := filepath.EvalSymlinks(root); err == nil && resolved != root {
|
||||
forms = append(forms, resolved)
|
||||
}
|
||||
sort.Slice(forms, func(i, j int) bool { return len(forms[i]) > len(forms[j]) })
|
||||
f := &discoveryPinFixture{t: t, root: root, forms: forms}
|
||||
f.mkdir("home")
|
||||
return f
|
||||
}
|
||||
|
||||
// path returns the absolute path of a root-relative slash path.
|
||||
func (f *discoveryPinFixture) path(rel string) string {
|
||||
return filepath.Join(f.root, filepath.FromSlash(rel))
|
||||
}
|
||||
|
||||
func (f *discoveryPinFixture) mkdir(rel string) string {
|
||||
f.t.Helper()
|
||||
dir := f.path(rel)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
f.t.Fatalf("mkdir %s: %v", dir, err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func (f *discoveryPinFixture) write(rel, content string) {
|
||||
f.t.Helper()
|
||||
if err := os.WriteFile(f.path(rel), []byte(content), 0o600); err != nil {
|
||||
f.t.Fatalf("write %s: %v", rel, err)
|
||||
}
|
||||
}
|
||||
|
||||
// project creates rel as a git repository with no .beads. The repository
|
||||
// root is the discovery walk's boundary, so nothing above the fixture leaks
|
||||
// into a case.
|
||||
func (f *discoveryPinFixture) project(rel string) string {
|
||||
f.t.Helper()
|
||||
dir := f.mkdir(rel)
|
||||
initGitRepoAt(f.t, dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
// workspace creates project rel with a .beads directory holding files, each
|
||||
// named relative to .beads.
|
||||
func (f *discoveryPinFixture) workspace(rel string, files map[string]string) string {
|
||||
f.t.Helper()
|
||||
dir := f.project(rel)
|
||||
f.mkdir(rel + "/.beads")
|
||||
for name, content := range files {
|
||||
f.write(rel+"/.beads/"+name, content)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// corruptWorkspace creates project rel whose metadata.json does not parse,
|
||||
// plus any extra .beads files.
|
||||
func (f *discoveryPinFixture) corruptWorkspace(rel string, extra map[string]string) string {
|
||||
f.t.Helper()
|
||||
files := map[string]string{"metadata.json": pinCorruptMetadata}
|
||||
for name, content := range extra {
|
||||
files[name] = content
|
||||
}
|
||||
return f.workspace(rel, files)
|
||||
}
|
||||
|
||||
// yamlWorkspace creates project rel whose .beads holds only a config.yaml
|
||||
// (no metadata.json and no database), plus any extra .beads files.
|
||||
func (f *discoveryPinFixture) yamlWorkspace(rel string, extra map[string]string) string {
|
||||
f.t.Helper()
|
||||
files := map[string]string{"config.yaml": "# discovery pin fixture\n"}
|
||||
for name, content := range extra {
|
||||
files[name] = content
|
||||
}
|
||||
return f.workspace(rel, files)
|
||||
}
|
||||
|
||||
// discoveryPinEnv is the caller environment without any BEADS_*/BD_*
|
||||
// selector or setting and without git repository-location variables, with
|
||||
// HOME and XDG_CONFIG_HOME under home, metrics and event flush off, and the
|
||||
// migration freeze marker pointed at freezeMarker, a path that does not exist.
|
||||
func discoveryPinEnv(home, freezeMarker string) []string {
|
||||
var env []string
|
||||
for _, kv := range testutil.WithoutGitRepoLocationEnv(os.Environ()) {
|
||||
key, _, _ := strings.Cut(kv, "=")
|
||||
if strings.HasPrefix(key, "BEADS_") || strings.HasPrefix(key, "BD_") ||
|
||||
key == "HOME" || key == "XDG_CONFIG_HOME" {
|
||||
continue
|
||||
}
|
||||
env = append(env, kv)
|
||||
}
|
||||
return append(env,
|
||||
"HOME="+home,
|
||||
"XDG_CONFIG_HOME="+filepath.Join(home, ".config"),
|
||||
"BD_DISABLE_METRICS=1",
|
||||
"BD_DISABLE_EVENT_FLUSH=1",
|
||||
"BD_MIGRATION_FREEZE_FILE="+freezeMarker,
|
||||
)
|
||||
}
|
||||
|
||||
func (f *discoveryPinFixture) run(bd, cwd string, extraEnv []string, args ...string) (exit int, stdout, stderr string) {
|
||||
f.t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = cwd
|
||||
cmd.Env = append(discoveryPinEnv(f.path("home"), f.path("no-such-freeze-marker")), extraEnv...)
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errOut
|
||||
if err := cmd.Run(); err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
f.t.Fatalf("run bd %s: %v", strings.Join(args, " "), err)
|
||||
}
|
||||
exit = exitErr.ExitCode()
|
||||
}
|
||||
return exit, f.normalize(out.String(), false), f.normalize(errOut.String(), true)
|
||||
}
|
||||
|
||||
var discoveryPinVersionLine = regexp.MustCompile(`(?m)^bd version .*$`)
|
||||
|
||||
// discoveryPinDuplicateBinaries matches the warning bd version appends when
|
||||
// the caller's PATH holds more than one distinct bd binary.
|
||||
var discoveryPinDuplicateBinaries = regexp.MustCompile(
|
||||
`\nWarning: multiple 'bd' binaries found in PATH:\n(?: [^\n]*\n)*` +
|
||||
`The first one is being used\. Remove duplicates to avoid confusion\.\n`)
|
||||
|
||||
// discoveryPinSandboxNotice matches the notice bd prints when it auto-detects
|
||||
// a sandbox, which it does when it is not allowed to signal its own process.
|
||||
var discoveryPinSandboxNotice = regexp.MustCompile(`(?m)^.*Sandbox detected, using direct mode\n`)
|
||||
|
||||
// normalize rewrites the fixture root as $ROOT and the build's version line
|
||||
// as "bd version $VERSION". For stderr it also drops the notices that depend
|
||||
// on the caller's environment rather than on the fixture (sandbox
|
||||
// auto-detection, and bd version's duplicate binaries in PATH) and collapses
|
||||
// consecutive repeats of a "Warning: redirect" line: discovery re-resolves
|
||||
// the same redirect several times per invocation and how many times it warns
|
||||
// is not part of the pin. Any other repeated line, such as a doubled
|
||||
// "Error:", is kept.
|
||||
func (f *discoveryPinFixture) normalize(s string, stderr bool) string {
|
||||
for _, form := range f.forms {
|
||||
s = strings.ReplaceAll(s, form, "$ROOT")
|
||||
}
|
||||
s = discoveryPinVersionLine.ReplaceAllLiteralString(s, "bd version $VERSION")
|
||||
if !stderr {
|
||||
return s
|
||||
}
|
||||
s = discoveryPinDuplicateBinaries.ReplaceAllLiteralString(s, "")
|
||||
s = discoveryPinSandboxNotice.ReplaceAllLiteralString(s, "")
|
||||
var b strings.Builder
|
||||
prev := ""
|
||||
for _, line := range strings.SplitAfter(s, "\n") {
|
||||
if line == prev && strings.HasPrefix(line, "Warning: redirect ") {
|
||||
continue
|
||||
}
|
||||
b.WriteString(line)
|
||||
prev = line
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsMissingMetadata pins discovery when no workspace,
|
||||
// a workspace without metadata.json and without a database, or a .beads that
|
||||
// is a regular file is found.
|
||||
func TestDiscoveryRefusalPinsMissingMetadata(t *testing.T) {
|
||||
noBeads := func(f *discoveryPinFixture) (string, []string) { return f.project("p"), nil }
|
||||
regularFileBeads := func(f *discoveryPinFixture) (string, []string) {
|
||||
cwd := f.project("p")
|
||||
f.write("p/.beads", "not a workspace\n")
|
||||
return cwd, nil
|
||||
}
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
name: "no-beads-dir/list",
|
||||
setup: noBeads,
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
// --json does not turn the refusal into a JSON document.
|
||||
name: "no-beads-dir/list-json",
|
||||
setup: noBeads,
|
||||
args: []string{"list", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "no-beads-dir/where",
|
||||
setup: noBeads,
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinNoWorkspaceWhereRefusal,
|
||||
},
|
||||
{
|
||||
name: "no-beads-dir/where-json",
|
||||
setup: noBeads,
|
||||
args: []string{"where", "--json"},
|
||||
exit: 1,
|
||||
stdout: pinNoWorkspaceWhereJSON,
|
||||
},
|
||||
{
|
||||
name: "empty-beads-dir/list",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.workspace("p", nil), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "config-yaml-only/list",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.yamlWorkspace("p", nil), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
// The same directory is a workspace to bd where.
|
||||
name: "config-yaml-only/where",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.yamlWorkspace("p", nil), nil
|
||||
},
|
||||
args: []string{"where"},
|
||||
stdout: "$ROOT/p/.beads\n",
|
||||
},
|
||||
{
|
||||
// The working-directory walk selects a .beads that is a regular
|
||||
// file, then fails to read its metadata.json (the BEADS_DIR form
|
||||
// is in TestDiscoveryRefusalPinsExplicitBeadsDir).
|
||||
name: "beads-is-regular-file/list",
|
||||
setup: regularFileBeads,
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: "Error: loading config: reading config: open $ROOT/p/.beads/metadata.json: not a directory\n",
|
||||
},
|
||||
{
|
||||
name: "beads-is-regular-file/where",
|
||||
setup: regularFileBeads,
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: "Error: loading config: reading config: open $ROOT/p/.beads/metadata.json: not a directory\n",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsCorruptMetadata pins the refusal for a discovered
|
||||
// workspace whose metadata.json does not parse.
|
||||
func TestDiscoveryRefusalPinsCorruptMetadata(t *testing.T) {
|
||||
corrupt := func(f *discoveryPinFixture) (string, []string) { return f.corruptWorkspace("p", nil), nil }
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
name: "list",
|
||||
setup: corrupt,
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "list-json",
|
||||
setup: corrupt,
|
||||
args: []string{"list", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
setup: corrupt,
|
||||
args: []string{"create", "must not be written", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
// bd where never opens a store, but it still refuses.
|
||||
name: "where",
|
||||
setup: corrupt,
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "where-json",
|
||||
setup: corrupt,
|
||||
args: []string{"where", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
// bd version warns and succeeds.
|
||||
name: "version",
|
||||
setup: corrupt,
|
||||
args: []string{"version"},
|
||||
stdout: "bd version $VERSION\n",
|
||||
stderr: pinCorruptMetadataWarning("$ROOT/p/.beads"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsExplicitBeadsDir pins an exported BEADS_DIR that
|
||||
// names no workspace. Each case runs from a corrupt workspace, so falling
|
||||
// back to discovery from the working directory would print that workspace's
|
||||
// refusal instead.
|
||||
func TestDiscoveryRefusalPinsExplicitBeadsDir(t *testing.T) {
|
||||
from := func(beadsDir func(f *discoveryPinFixture) string) func(f *discoveryPinFixture) (string, []string) {
|
||||
return func(f *discoveryPinFixture) (string, []string) {
|
||||
cwd := f.corruptWorkspace("cwd", nil)
|
||||
return cwd, []string{"BEADS_DIR=" + beadsDir(f)}
|
||||
}
|
||||
}
|
||||
missing := from(func(f *discoveryPinFixture) string { return f.path("missing/.beads") })
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
name: "missing-dir/list",
|
||||
setup: missing,
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "missing-dir/where",
|
||||
setup: missing,
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinNoWorkspaceWhereRefusal,
|
||||
},
|
||||
{
|
||||
name: "missing-dir/where-json",
|
||||
setup: missing,
|
||||
args: []string{"where", "--json"},
|
||||
exit: 1,
|
||||
stdout: pinNoWorkspaceWhereJSON,
|
||||
},
|
||||
{
|
||||
name: "empty-dir/list",
|
||||
setup: from(func(f *discoveryPinFixture) string { return f.mkdir("empty") }),
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "regular-file/list",
|
||||
setup: from(func(f *discoveryPinFixture) string {
|
||||
f.write("file", "not a workspace\n")
|
||||
return f.path("file")
|
||||
}),
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: "Error: loading config: reading config: open $ROOT/file/metadata.json: not a directory\n",
|
||||
},
|
||||
{
|
||||
name: "corrupt-workspace/list",
|
||||
setup: from(func(f *discoveryPinFixture) string {
|
||||
f.corruptWorkspace("other", nil)
|
||||
return f.path("other/.beads")
|
||||
}),
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/other/.beads"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsBeadsEnvFile pins settings supplied by the
|
||||
// discovered workspace's .beads/.env.
|
||||
func TestDiscoveryRefusalPinsBeadsEnvFile(t *testing.T) {
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
// A .env BEADS_DIR routes discovery to its target.
|
||||
name: "beads-dir-routes-to-target",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("target/.beads") + "\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// The routing workspace's own corrupt metadata.json causes no refusal.
|
||||
name: "beads-dir-route-skips-local-metadata",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("missing/.beads") + "\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
// An exported BEADS_DIR wins; the .env is never read.
|
||||
name: "exported-beads-dir-wins",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
cwd := f.yamlWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("target/.beads") + "\n"})
|
||||
return cwd, []string{"BEADS_DIR=" + f.path("missing/.beads")}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
// A .env BEADS_DB does not route a data command away from the
|
||||
// workspace that holds the .env (the shadowing
|
||||
// TestDiscoveryRefusalPinsDBSelection records for an exported
|
||||
// BEADS_DB) ...
|
||||
name: "beads-db-list",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DB=" + f.path("target/.beads/dolt") + "\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
// ... but it does route bd where.
|
||||
name: "beads-db-where",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DB=" + f.path("target/.beads/dolt") + "\n"}), nil
|
||||
},
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// Settings in the selected workspace's .env apply (BD_JSON here).
|
||||
name: "setting-applies-in-selected-workspace",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BD_JSON=true\n"}), nil
|
||||
},
|
||||
args: []string{"where"},
|
||||
stdout: "{\n \"path\": \"$ROOT/p/.beads\",\n \"schema_version\": 1\n}\n",
|
||||
},
|
||||
{
|
||||
// A .env that routes elsewhere contributes only its selector:
|
||||
// its other settings are not imported, so the refusal is text.
|
||||
name: "setting-not-imported-from-routing-source",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BD_JSON=true\nBEADS_DIR=" + f.path("missing/.beads") + "\n"}), nil
|
||||
},
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinNoWorkspaceWhereRefusal,
|
||||
},
|
||||
{
|
||||
// checkBlockedEnvVars sees only the exported environment, and runs
|
||||
// before any .env is loaded: a .env BD_BACKEND is not refused, here
|
||||
// or anywhere before discovery's own no-database refusal.
|
||||
name: "blocked-backend-not-checked",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.yamlWorkspace("p", map[string]string{".env": "BD_BACKEND=sqlite\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsRedirect pins .beads/redirect handling: the
|
||||
// warnings for unusable targets and which directory is selected afterwards.
|
||||
func TestDiscoveryRefusalPinsRedirect(t *testing.T) {
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
// A missing target is ignored and discovery keeps the source.
|
||||
name: "missing-target",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", map[string]string{"redirect": f.path("missing/.beads") + "\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: "Warning: redirect target does not exist or is not a directory: $ROOT/missing/.beads\n" +
|
||||
pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
// A target without project files is ignored the same way.
|
||||
name: "target-without-workspace",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.mkdir("bare/.beads")
|
||||
return f.corruptWorkspace("p", map[string]string{"redirect": "../bare/.beads\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: "Warning: ignoring redirect from $ROOT/p/.beads to $ROOT/bare/.beads because the target has no database or metadata.json; fix or delete the redirect file\n" +
|
||||
pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "corrupt-target",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.workspace("p", map[string]string{"redirect": "../target/.beads\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// Only one level is followed.
|
||||
name: "chain",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("final", nil)
|
||||
f.corruptWorkspace("middle", map[string]string{"redirect": "../final/.beads\n"})
|
||||
return f.workspace("p", map[string]string{"redirect": "../middle/.beads\n"}), nil
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: "Warning: redirect chains not allowed, ignoring redirect in $ROOT/middle/.beads\n" +
|
||||
pinCorruptMetadataRefusal("$ROOT/middle/.beads"),
|
||||
},
|
||||
{
|
||||
// An explicit BEADS_DIR is followed through its redirect.
|
||||
name: "explicit-beads-dir",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
f.workspace("source", map[string]string{"redirect": "../target/.beads\n"})
|
||||
return f.project("p"), []string{"BEADS_DIR=" + f.path("source/.beads")}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
name: "where-reports-source",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.yamlWorkspace("target", nil)
|
||||
return f.workspace("p", map[string]string{"redirect": "../target/.beads\n"}), nil
|
||||
},
|
||||
args: []string{"where"},
|
||||
stdout: "$ROOT/target/.beads\n (via redirect from $ROOT/p/.beads)\n",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsDBSelection pins database selection by --db and by
|
||||
// the BEADS_DB and BD_DB environment variables.
|
||||
//
|
||||
// Two of these record inconsistencies as they stand rather than endorse
|
||||
// them: a data command ignores BD_DB, and lets a discoverable workspace in
|
||||
// the working directory shadow BEADS_DB, while bd where honors both.
|
||||
func TestDiscoveryRefusalPinsDBSelection(t *testing.T) {
|
||||
target := func(f *discoveryPinFixture) string {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.path("target/.beads/dolt")
|
||||
}
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
// A --db path selects the workspace that owns it.
|
||||
name: "db-path",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
target(f)
|
||||
return f.project("p"), nil
|
||||
},
|
||||
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
name: "db-path-beats-beads-dir",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
target(f)
|
||||
f.corruptWorkspace("other", nil)
|
||||
return f.project("p"), []string{"BEADS_DIR=" + f.path("other/.beads")}
|
||||
},
|
||||
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
name: "db-path-beats-working-directory",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
target(f)
|
||||
return f.corruptWorkspace("p", nil), nil
|
||||
},
|
||||
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// A --db value that is a database name rather than an existing
|
||||
// path leaves discovery to the working directory.
|
||||
name: "db-name-without-workspace",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), nil
|
||||
},
|
||||
args: []string{"--db", "pindb", "list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "db-name-in-workspace",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", nil), nil
|
||||
},
|
||||
args: []string{"--db", "pindb", "list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "beads-db-env",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BEADS_DB=" + target(f)}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// Inconsistency: the working directory's workspace shadows BEADS_DB.
|
||||
name: "beads-db-env-shadowed-by-working-directory",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", nil), []string{"BEADS_DB=" + target(f)}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
|
||||
},
|
||||
{
|
||||
name: "beads-db-env-where",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", nil), []string{"BEADS_DB=" + target(f)}
|
||||
},
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
{
|
||||
// Inconsistency: a data command ignores BD_DB.
|
||||
name: "bd-db-env",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_DB=" + target(f)}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinNoDatabaseRefusal,
|
||||
},
|
||||
{
|
||||
name: "bd-db-env-where",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_DB=" + target(f)}
|
||||
},
|
||||
args: []string{"where"},
|
||||
exit: 1,
|
||||
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiscoveryRefusalPinsBlockedEnvVarsRunFirst pins that the blocked
|
||||
// backend variables are refused before any discovery, for every command.
|
||||
func TestDiscoveryRefusalPinsBlockedEnvVarsRunFirst(t *testing.T) {
|
||||
runDiscoveryPinCases(t, []discoveryPinCase{
|
||||
{
|
||||
name: "no-workspace",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
name: "corrupt-metadata",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", nil), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
name: "explicit-beads-dir",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite", "BEADS_DIR=" + f.path("missing/.beads")}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
// A BEADS_DIR that cannot even be read as a directory is still
|
||||
// reached only after the blocked variable is refused.
|
||||
name: "unreadable-beads-dir",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.write("file", "not a workspace\n")
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite", "BEADS_DIR=" + f.path("file")}
|
||||
},
|
||||
args: []string{"list"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
name: "db-path",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
f.corruptWorkspace("target", nil)
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
// --json does not turn the refusal into a JSON document.
|
||||
name: "database-backend-json",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.corruptWorkspace("p", nil), []string{"BD_DATABASE_BACKEND=dolt"}
|
||||
},
|
||||
args: []string{"list", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_DATABASE_BACKEND"),
|
||||
},
|
||||
{
|
||||
name: "where-json",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"where", "--json"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
name: "version-command",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"version"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
},
|
||||
{
|
||||
// The root command then prints cobra's error and usage; only the
|
||||
// refusal itself is pinned.
|
||||
name: "version-flag",
|
||||
setup: func(f *discoveryPinFixture) (string, []string) {
|
||||
return f.project("p"), []string{"BD_BACKEND=sqlite"}
|
||||
},
|
||||
args: []string{"--version"},
|
||||
exit: 1,
|
||||
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
|
||||
stderrPrefix: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -220,7 +220,7 @@ Examples:
|
|||
if err := validateDoctorWorkspaceBackend(absPath); isLegacyUpgradeRefusal(err) {
|
||||
return printLegacyUpgradeDiagnostic(err)
|
||||
} else if err != nil {
|
||||
return HandleError("%v", err)
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
|
||||
if doctorFix && isOrchestratorRoot(absPath) {
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ go_library(
|
|||
"//internal/storage/issueops",
|
||||
"//internal/types",
|
||||
"//internal/utils",
|
||||
"//internal/versionedhistory",
|
||||
"@com_github_burntsushi_toml//:toml",
|
||||
"@com_github_go_sql_driver_mysql//:mysql",
|
||||
"@in_gopkg_yaml_v3//:yaml_v3",
|
||||
|
|
@ -81,7 +82,11 @@ go_test(
|
|||
"testmain_cgo_test.go",
|
||||
"testmain_nocgo_test.go",
|
||||
"validation_test.go",
|
||||
"versioned_history_activation_test.go",
|
||||
],
|
||||
# versioned_history_activation_test.go parses store.go from its working
|
||||
# directory, and a Bazel test only sees its declared runfiles.
|
||||
data = ["store.go"],
|
||||
embed = [":fix"],
|
||||
deps = [
|
||||
"//internal/configfile",
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/eventsjournal"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/versionedhistory"
|
||||
)
|
||||
|
||||
// openBeadMutatingStore opens a repair handler's store WITH the workspace's
|
||||
// events-journal activation applied.
|
||||
// events-journal and versioned-history activation applied.
|
||||
//
|
||||
// Most of bd doctor inspects and repairs workspace state — schema cursors,
|
||||
// metadata, remotes, fingerprints, git — and none of that belongs in a journal
|
||||
|
|
@ -17,7 +18,10 @@ import (
|
|||
// fresh-clone import paths CREATE them. Those are ordinary bead mutations, and
|
||||
// a consumer whose mirror silently diverges because someone ran
|
||||
// `bd doctor --fix` is exactly the failure the journal exists to prevent — the
|
||||
// more so because a repair is unattended and nobody is watching the diff.
|
||||
// more so because a repair is unattended and nobody is watching the diff. The
|
||||
// same repairs are also ordinary issue mutations for version history, and an
|
||||
// issue_versions trail with a silent gap where `bd doctor --fix` ran is the same
|
||||
// failure one table over.
|
||||
//
|
||||
// The read-only and workspace-state handlers deliberately keep opening the
|
||||
// store directly; they carry their exemption in the construction guard, with a
|
||||
|
|
@ -27,7 +31,7 @@ import (
|
|||
// is what a repair path legitimately does.
|
||||
func openBeadMutatingStore(ctx context.Context, beadsDir string) (*dolt.DoltStore, error) {
|
||||
store, err := dolt.NewFromConfig(ctx, beadsDir)
|
||||
return activated(beadsDir, store, err)
|
||||
return activated(ctx, beadsDir, store, err)
|
||||
}
|
||||
|
||||
// openBeadMutatingStoreCreating is openBeadMutatingStore for the fresh-clone
|
||||
|
|
@ -36,15 +40,23 @@ func openBeadMutatingStore(ctx context.Context, beadsDir string) (*dolt.DoltStor
|
|||
// guard rather than failing on an absent database.
|
||||
func openBeadMutatingStoreCreating(ctx context.Context, beadsDir string) (*dolt.DoltStore, error) {
|
||||
store, err := dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true})
|
||||
return activated(beadsDir, store, err)
|
||||
return activated(ctx, beadsDir, store, err)
|
||||
}
|
||||
|
||||
// activated applies the workspace's journal setting and closes the store if it
|
||||
// cannot be honored. A failed open passes straight through, so the typed-nil
|
||||
// store never reaches the activation.
|
||||
func activated(beadsDir string, store *dolt.DoltStore, err error) (*dolt.DoltStore, error) {
|
||||
// activated applies the workspace's journal setting and the store's own
|
||||
// versioned-history setting, and closes the store if the journal cannot be
|
||||
// honored. A failed open passes straight through, so the typed-nil store never
|
||||
// reaches the activation.
|
||||
//
|
||||
// Versioned history cannot fail an open (a plumbing that cannot version simply
|
||||
// records nothing), so it needs no error handling of its own; it runs after the
|
||||
// journal so a store the journal refused is never activated. It is the shared
|
||||
// internal/versionedhistory rule, not a copy: package main cannot be imported
|
||||
// from here.
|
||||
func activated(ctx context.Context, beadsDir string, store *dolt.DoltStore, err error) (*dolt.DoltStore, error) {
|
||||
if _, err = eventsjournal.ActivateStore(beadsDir, store, err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, _ = versionedhistory.ActivateStore(ctx, store, nil)
|
||||
return store, nil
|
||||
}
|
||||
|
|
|
|||
87
cmd/bd/doctor/fix/versioned_history_activation_test.go
Normal file
87
cmd/bd/doctor/fix/versioned_history_activation_test.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
package fix
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
versionedHistoryPkg = "github.com/steveyegge/beads/internal/versionedhistory"
|
||||
// package main cannot be imported at all; the guard below is that the
|
||||
// activation this package applies lives in a package it CAN import, so the
|
||||
// repair handlers apply the identical rule as the command surface rather than
|
||||
// a copy of it.
|
||||
beadMutatingStoreFile = "store.go"
|
||||
)
|
||||
|
||||
// TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation holds the one
|
||||
// construction site the cmd/bd construction guard cannot see. bd doctor is exempted
|
||||
// from that guard as a package (its CHECKS are read-only), so the repair opener --
|
||||
// which opens the store the bead-mutating repairs (stale-closed cleanup, pollution
|
||||
// cleanup, the fresh-clone imports) write through -- is held to the property here.
|
||||
//
|
||||
// A repair that deletes or creates issues is an ordinary mutation for version
|
||||
// history: an issue_versions trail with a silent gap where `bd doctor --fix` ran is
|
||||
// the same failure the routed-write bug produced, one command over, and the more
|
||||
// dangerous for being unattended.
|
||||
//
|
||||
// The check is structural for the same reason the cmd/bd guard is: activation
|
||||
// failing is invisible from inside the process. It requires the activation that
|
||||
// `activated` applies to come from internal/versionedhistory -- the ONE
|
||||
// implementation of the rule, which this package can import and package main cannot
|
||||
// be.
|
||||
func TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, beadMutatingStoreFile, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", beadMutatingStoreFile, err)
|
||||
}
|
||||
|
||||
imports := map[string]string{}
|
||||
for _, spec := range file.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("unquote import %s: %v", spec.Path.Value, err)
|
||||
}
|
||||
name := path[strings.LastIndex(path, "/")+1:]
|
||||
if spec.Name != nil {
|
||||
name = spec.Name.Name
|
||||
}
|
||||
imports[name] = path
|
||||
}
|
||||
|
||||
var activated *ast.FuncDecl
|
||||
for _, decl := range file.Decls {
|
||||
if fn, ok := decl.(*ast.FuncDecl); ok && fn.Name.Name == "activated" {
|
||||
activated = fn
|
||||
}
|
||||
}
|
||||
if activated == nil {
|
||||
t.Fatalf("%s has no `activated` function: the repair opener's activation moved and this guard no longer looks at it", beadMutatingStoreFile)
|
||||
}
|
||||
|
||||
called := false
|
||||
ast.Inspect(activated, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if ident, ok := sel.X.(*ast.Ident); ok && imports[ident.Name] == versionedHistoryPkg && sel.Sel.Name == "ActivateStore" {
|
||||
called = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !called {
|
||||
t.Errorf("`activated` in %s never calls versionedhistory.ActivateStore: every repair that mutates issues through it "+
|
||||
"mints NO issue_versions row while `bd doctor --fix` reports success. Apply the shared activation there; "+
|
||||
"it is the same rule as the command surface and package main cannot be imported to reuse it.", beadMutatingStoreFile)
|
||||
}
|
||||
}
|
||||
|
|
@ -43,10 +43,10 @@ func runBDSplit(t *testing.T, bd, dir string, args ...string) (stdout, stderr st
|
|||
return stdoutBuf.String(), stderrBuf.String(), err
|
||||
}
|
||||
|
||||
// TestDoctorEmbeddedSupportedChecks verifies that --check=artifacts,
|
||||
// TestEmbeddedDoctorSupportedChecks verifies that --check=artifacts,
|
||||
// --check=conventions, and --check=pollution run in embedded mode rather
|
||||
// than hitting the "not yet supported" stub (GH#3597).
|
||||
func TestDoctorEmbeddedSupportedChecks(t *testing.T) {
|
||||
func TestEmbeddedDoctorSupportedChecks(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")
|
||||
}
|
||||
|
|
@ -83,11 +83,11 @@ func TestDoctorEmbeddedSupportedChecks(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoctorEmbeddedUnsupportedJSON verifies that variants which still require
|
||||
// TestEmbeddedDoctorUnsupportedJSON verifies that variants which still require
|
||||
// server mode (bare doctor, --check=validate) emit a structured JSON payload
|
||||
// when --json or --agent --json is set, rather than the prose stub. Tooling
|
||||
// can detect "unsupported" without text-matching (GH#3597).
|
||||
func TestDoctorEmbeddedUnsupportedJSON(t *testing.T) {
|
||||
func TestEmbeddedDoctorUnsupportedJSON(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")
|
||||
}
|
||||
|
|
@ -150,10 +150,10 @@ func TestDoctorEmbeddedUnsupportedJSON(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoctorEmbeddedUnsupportedProse verifies that bare bd doctor (without
|
||||
// TestEmbeddedDoctorUnsupportedProse verifies that bare bd doctor (without
|
||||
// --json) still emits the human-readable prose stub for terminal users,
|
||||
// pointing at the supported --check=* variants (GH#3597).
|
||||
func TestDoctorEmbeddedUnsupportedProse(t *testing.T) {
|
||||
func TestEmbeddedDoctorUnsupportedProse(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,16 +9,28 @@
|
|||
// beside the rest of the freeze suite; both halves share the helpers below and
|
||||
// the hermetic subprocess harness declared there.
|
||||
//
|
||||
// The same gate for `bd backup init`, `backup remove`, `backup sync` and
|
||||
// `bd import` sits further down, between the doctor tests it mirrors.
|
||||
//
|
||||
// This file MUST NOT carry a cgo build tag: it drives a bd binary built with
|
||||
// the gms_pure_go tag via subprocess, and asserts only on files and output.
|
||||
// the gms_pure_go tag via subprocess, and asserts on files and output (and, for
|
||||
// the server rows of the backup/import tests, on the Dolt test server's tables).
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/doltutil"
|
||||
)
|
||||
|
||||
// doctorMutationSurface is one class of doctor invocation that mutates the
|
||||
|
|
@ -122,6 +134,306 @@ func TestDoctorMutationBlockedInReadonlyMode(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// The backup and import commands: the same gate, a different failure.
|
||||
//
|
||||
// `bd backup init`, `backup remove`, `backup sync` and `bd import` never called
|
||||
// CheckReadonly, so strict --readonly only held as far as the store underneath
|
||||
// happened to refuse. An embedded store is opened read-only, so those commands
|
||||
// failed, but with the storage layer's text rather than the standard refusal,
|
||||
// and `backup sync` took the backup lock first and left .beads/backup.lock
|
||||
// behind. A server-mode store has no such floor: the same commands ran to
|
||||
// completion and rewrote or emptied the backup registry, wrote the backup
|
||||
// destination, or imported issues. So every row runs in both flavours, and the
|
||||
// checks go past the file tree: a server-mode import leaves .beads untouched
|
||||
// even when it succeeds, so the issue count and the registry are compared too.
|
||||
//
|
||||
// `backup status` and `list` only read, and stay allowed;
|
||||
// TestBackupStatusAndListWorkInReadonlyMode pins that. `bd backup` on its own is
|
||||
// a command group that only prints help, and is left as it is.
|
||||
|
||||
// backupImportSurface is one command that strict --readonly must refuse.
|
||||
type backupImportSurface struct {
|
||||
name string
|
||||
// args are the command and its arguments; the test appends the global flags.
|
||||
args []string
|
||||
// op is the operation label the gate reports.
|
||||
op string
|
||||
}
|
||||
|
||||
func backupImportSurfaces(w *readonlyGateWorkspace) []backupImportSurface {
|
||||
return []backupImportSurface{
|
||||
// A destination other than the registered one, so a run that goes
|
||||
// through shows up as a changed registry.
|
||||
{name: "backup-init", args: []string{"backup", "init", filepath.Join(w.dir, "other-backup-dest")}, op: "backup init"},
|
||||
{name: "backup-remove", args: []string{"backup", "remove"}, op: "backup remove"},
|
||||
{name: "backup-sync", args: []string{"backup", "sync"}, op: "backup sync"},
|
||||
{name: "import", args: []string{"import", w.importFile}, op: "import"},
|
||||
// A preview writes nothing, but strict --readonly already refuses
|
||||
// `create --dry-run`, so import's is refused the same way.
|
||||
{name: "import-dry-run", args: []string{"import", "--dry-run", w.importFile}, op: "import"},
|
||||
}
|
||||
}
|
||||
|
||||
// readonlyGateFlagSets are the global flag combinations every row runs under.
|
||||
// --sandbox changes how bd treats the store (it disables auto-push); the gate
|
||||
// has to hold with it as well.
|
||||
var readonlyGateFlagSets = []struct {
|
||||
name string
|
||||
flags []string
|
||||
}{
|
||||
{name: "readonly", flags: []string{"--readonly"}},
|
||||
{name: "readonly-sandbox", flags: []string{"--readonly", "--sandbox"}},
|
||||
}
|
||||
|
||||
// readonlyGateFlavours are the two stores the gate has to hold over.
|
||||
var readonlyGateFlavours = []struct {
|
||||
name string
|
||||
setup func(*testing.T) *readonlyGateWorkspace
|
||||
}{
|
||||
{name: "embedded", setup: newEmbeddedReadonlyGateWorkspace},
|
||||
{name: "server", setup: newServerReadonlyGateWorkspace},
|
||||
}
|
||||
|
||||
// readonlyGateWorkspace is an initialized workspace holding one issue and one
|
||||
// registered backup, plus what a refused command has to leave alone.
|
||||
type readonlyGateWorkspace struct {
|
||||
bd, dir string
|
||||
prefix string
|
||||
dest string // directory behind the registered default backup
|
||||
importFile string // a one-issue JSONL file for `bd import`
|
||||
// Server flavour only: the shared test server and this workspace's database
|
||||
// on it. A zero port means the embedded flavour.
|
||||
port int
|
||||
database string
|
||||
}
|
||||
|
||||
// readonlyGateState is everything a refused command could have changed.
|
||||
type readonlyGateState struct {
|
||||
tree readonlyTreeSnapshot // the whole .beads directory
|
||||
dest readonlyTreeSnapshot // the backup destination
|
||||
issues int // what `bd list` reports
|
||||
registry string // server flavour only: dolt_backups as name=url rows
|
||||
}
|
||||
|
||||
func newEmbeddedReadonlyGateWorkspace(t *testing.T) *readonlyGateWorkspace {
|
||||
t.Helper()
|
||||
bd, dir := setupMigrationFreezeWorkspace(t)
|
||||
w := &readonlyGateWorkspace{bd: bd, dir: dir, prefix: "test"}
|
||||
w.seed(t)
|
||||
return w
|
||||
}
|
||||
|
||||
// newServerReadonlyGateWorkspace is the same workspace on the shared Dolt test
|
||||
// server. The default lane starts none, so it skips there, as the other
|
||||
// server-mode readonly test in this package does.
|
||||
func newServerReadonlyGateWorkspace(t *testing.T) *readonlyGateWorkspace {
|
||||
t.Helper()
|
||||
port, err := strconv.Atoi(os.Getenv("BEADS_DOLT_PORT"))
|
||||
if err != nil || port <= 0 {
|
||||
t.Skip("shared Dolt test server is unavailable")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
bd := buildBDForInitTests(t)
|
||||
runGitForBootstrapTest(t, dir, "init", "-q")
|
||||
runGitForBootstrapTest(t, dir, "config", "core.hooksPath", ".git/hooks")
|
||||
|
||||
// The prefix names the database on the shared server, so it must be unique.
|
||||
prefix := "rog" + strings.TrimPrefix(uniqueTestDBName(t), "testdb_")
|
||||
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "init", "--server", "--server-host", "127.0.0.1",
|
||||
"--server-port", strconv.Itoa(port), "--external", "--prefix", prefix,
|
||||
"--quiet", "--non-interactive", "--skip-hooks", "--skip-agents")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd init --server failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
var meta struct {
|
||||
Database string `json:"dolt_database"`
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, ".beads", "metadata.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("reading metadata.json: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(data, &meta); err != nil || meta.Database == "" {
|
||||
t.Fatalf("metadata.json names no dolt_database (%v):\n%s", err, data)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
db, err := sql.Open("mysql", doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer db.Close()
|
||||
_, _ = db.ExecContext(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", meta.Database)) //nolint:gosec // generated test name
|
||||
})
|
||||
|
||||
w := &readonlyGateWorkspace{bd: bd, dir: dir, prefix: prefix, port: port, database: meta.Database}
|
||||
w.seed(t)
|
||||
return w
|
||||
}
|
||||
|
||||
// seed gives the workspace one issue, one registered backup and a JSONL file
|
||||
// whose single issue is not in the workspace yet.
|
||||
func (w *readonlyGateWorkspace) seed(t *testing.T) {
|
||||
t.Helper()
|
||||
w.dest = filepath.Join(w.dir, "backup-dest")
|
||||
w.importFile = filepath.Join(w.dir, "import.jsonl")
|
||||
record := fmt.Sprintf(`{"id":"%s-gate1","title":"imported under readonly","status":"open","priority":2,"issue_type":"task","created_at":"2026-01-01T00:00:00Z"}`+"\n", w.prefix)
|
||||
if err := os.WriteFile(w.importFile, []byte(record), 0o644); err != nil {
|
||||
t.Fatalf("writing %s: %v", w.importFile, err)
|
||||
}
|
||||
if stdout, stderr, code := w.run(t, "create", "seed issue", "-p", "2"); code != 0 {
|
||||
t.Fatalf("bd create failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
w.registerBackup(t)
|
||||
}
|
||||
|
||||
func (w *readonlyGateWorkspace) run(t *testing.T, args ...string) (stdout, stderr string, exitCode int) {
|
||||
t.Helper()
|
||||
return runBDMigrationFreeze(t, w.bd, w.dir, args...)
|
||||
}
|
||||
|
||||
// registerBackup points the default backup at w.dest. Rows call it before each
|
||||
// run: a row that went through when it should have been refused may have moved
|
||||
// or removed the backup, and the next row still needs one to be refused against.
|
||||
func (w *readonlyGateWorkspace) registerBackup(t *testing.T) {
|
||||
t.Helper()
|
||||
if stdout, stderr, code := w.run(t, "backup", "init", "file://"+w.dest); code != 0 {
|
||||
t.Fatalf("bd backup init failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *readonlyGateWorkspace) state(t *testing.T) readonlyGateState {
|
||||
t.Helper()
|
||||
// Count the issues first: that is itself a strict --readonly read, so
|
||||
// anything it creates lazily exists before the snapshot instead of showing
|
||||
// up in it as a change.
|
||||
s := readonlyGateState{issues: w.issueCount(t)}
|
||||
s.tree = snapshotReadonlyTree(t, filepath.Join(w.dir, ".beads"))
|
||||
s.dest = snapshotReadonlyTree(t, w.dest)
|
||||
if w.port != 0 {
|
||||
s.registry = w.backupRegistry(t)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (w *readonlyGateWorkspace) issueCount(t *testing.T) int {
|
||||
t.Helper()
|
||||
stdout, stderr, code := w.run(t, "list", "--json", "--readonly")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd list failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
var issues []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(stdout), &issues); err != nil {
|
||||
t.Fatalf("bd list --json is not a JSON array: %v\n%s", err, stdout)
|
||||
}
|
||||
return len(issues)
|
||||
}
|
||||
|
||||
// backupRegistry reads the backups the server has registered for this
|
||||
// workspace's database. No bd command prints them, and the file tree never
|
||||
// shows them, so a refused run is checked against the server itself.
|
||||
func (w *readonlyGateWorkspace) backupRegistry(t *testing.T) string {
|
||||
t.Helper()
|
||||
db, err := sql.Open("mysql", doltutil.ServerDSN{Host: "127.0.0.1", Port: w.port, User: "root", Database: w.database}.String())
|
||||
if err != nil {
|
||||
t.Fatalf("connecting to the test server: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
rows, err := db.QueryContext(context.Background(), "SELECT name, url FROM dolt_backups ORDER BY name")
|
||||
if err != nil {
|
||||
t.Fatalf("reading dolt_backups: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var lines []string
|
||||
for rows.Next() {
|
||||
var name, url string
|
||||
if err := rows.Scan(&name, &url); err != nil {
|
||||
t.Fatalf("scanning dolt_backups: %v", err)
|
||||
}
|
||||
lines = append(lines, name+"="+url)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("reading dolt_backups: %v", err)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// assertUnchanged proves a refusal happened before any mutation, not merely
|
||||
// that the refusal text was printed.
|
||||
func (w *readonlyGateWorkspace) assertUnchanged(t *testing.T, before readonlyGateState) {
|
||||
t.Helper()
|
||||
after := w.state(t)
|
||||
if diff := readonlyTreeDiff(before.tree, after.tree); len(diff) > 0 {
|
||||
t.Errorf("a refused run changed .beads:\n %s", strings.Join(diff, "\n "))
|
||||
}
|
||||
if diff := readonlyTreeDiff(before.dest, after.dest); len(diff) > 0 {
|
||||
t.Errorf("a refused run changed the backup destination:\n %s", strings.Join(diff, "\n "))
|
||||
}
|
||||
if after.issues != before.issues {
|
||||
t.Errorf("a refused run changed the issue count: %d -> %d", before.issues, after.issues)
|
||||
}
|
||||
if after.registry != before.registry {
|
||||
t.Errorf("a refused run changed the backup registry:\nbefore:\n%s\nafter:\n%s", before.registry, after.registry)
|
||||
}
|
||||
}
|
||||
|
||||
// readonlyTreeDiff names what differs between two snapshots, so a leaked
|
||||
// mutation reads as "+ backup.lock" rather than as two opaque hash maps.
|
||||
func readonlyTreeDiff(before, after readonlyTreeSnapshot) []string {
|
||||
var diff []string
|
||||
if before.Exists != after.Exists {
|
||||
diff = append(diff, fmt.Sprintf("exists: %t -> %t", before.Exists, after.Exists))
|
||||
}
|
||||
for path, was := range before.Entries {
|
||||
if now, ok := after.Entries[path]; !ok {
|
||||
diff = append(diff, "- "+path)
|
||||
} else if now != was {
|
||||
diff = append(diff, "~ "+path)
|
||||
}
|
||||
}
|
||||
for path := range after.Entries {
|
||||
if _, ok := before.Entries[path]; !ok {
|
||||
diff = append(diff, "+ "+path)
|
||||
}
|
||||
}
|
||||
sort.Strings(diff)
|
||||
return diff
|
||||
}
|
||||
|
||||
// TestBackupAndImportBlockedInReadonlyMode is the readonly gate for the backup
|
||||
// and import commands. One workspace per flavour serves every row; each row
|
||||
// re-registers the backup first, so none depends on what the previous one did.
|
||||
func TestBackupAndImportBlockedInReadonlyMode(t *testing.T) {
|
||||
for _, flavour := range readonlyGateFlavours {
|
||||
t.Run(flavour.name, func(t *testing.T) {
|
||||
w := flavour.setup(t)
|
||||
for _, tt := range backupImportSurfaces(w) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
for _, flagSet := range readonlyGateFlagSets {
|
||||
t.Run(flagSet.name, func(t *testing.T) {
|
||||
w.registerBackup(t)
|
||||
before := w.state(t)
|
||||
|
||||
args := append(append([]string{}, tt.args...), flagSet.flags...)
|
||||
stdout, stderr, code := w.run(t, args...)
|
||||
|
||||
want := "Error: operation '" + tt.op + "' is not allowed in read-only mode\n"
|
||||
if code != 1 {
|
||||
t.Errorf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if stderr != want {
|
||||
t.Errorf("stderr is not exactly the standard refusal\ngot: %q\nwant: %q", stderr, want)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Errorf("stdout should be empty when the command is refused, got:\n%s", stdout)
|
||||
}
|
||||
w.assertUnchanged(t, before)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctorDiagnosisWorksInReadonlyMode pins the other half of the contract:
|
||||
// the gate keys on --fix/--clean alone, so every diagnosis mode still runs
|
||||
// under --readonly. Diagnosing a sandboxed workspace is the whole point.
|
||||
|
|
@ -143,6 +455,25 @@ func TestDoctorDiagnosisWorksInReadonlyMode(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestBackupStatusAndListWorkInReadonlyMode is the control for the backup and
|
||||
// import gate: it keys on the commands that write, so `backup status` and
|
||||
// `list` still run under --readonly, in both flavours.
|
||||
func TestBackupStatusAndListWorkInReadonlyMode(t *testing.T) {
|
||||
for _, flavour := range readonlyGateFlavours {
|
||||
t.Run(flavour.name, func(t *testing.T) {
|
||||
w := flavour.setup(t)
|
||||
for _, args := range [][]string{{"backup", "status"}, {"list"}} {
|
||||
t.Run(strings.Join(args, "_"), func(t *testing.T) {
|
||||
stdout, stderr, code := w.run(t, append(append([]string{}, args...), "--readonly")...)
|
||||
if code != 0 || strings.Contains(stderr, "not allowed in read-only mode") {
|
||||
t.Errorf("bd %v under --readonly should run (exit %d):\nstdout:\n%s\nstderr:\n%s", args, code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctorMaintenanceSkippedInReadonlyMode is the readonly twin of
|
||||
// TestDoctorMaintenanceSkippedDuringMigrationFreeze — see that test for why
|
||||
// plain `bd doctor` had hidden writes at all, and for the shared-server setup.
|
||||
|
|
|
|||
|
|
@ -1124,6 +1124,11 @@ is shown as not running, and the next bd command launches it.`,
|
|||
if beadsDir == "" {
|
||||
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
|
||||
}
|
||||
// A workspace in a format this build cannot open is refused before
|
||||
// configfile.Load, which would first migrate a legacy config.json.
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
cfg, cfgErr := configfile.Load(beadsDir)
|
||||
if cfgErr != nil {
|
||||
return HandleError("loading config: %v", cfgErr)
|
||||
|
|
@ -2004,6 +2009,11 @@ func showDoltConfig(testConnection bool) error {
|
|||
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
|
||||
}
|
||||
|
||||
// A workspace in a format this build cannot open is refused before
|
||||
// configfile.Load, which would first migrate a legacy config.json.
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil {
|
||||
return HandleError("loading config: %v", err)
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ func bdDoltSeparate(t *testing.T, bd, dir string, args ...string) (string, strin
|
|||
|
||||
// -- push --
|
||||
|
||||
func TestDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
}
|
||||
|
|
@ -62,7 +62,7 @@ func TestDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
|
||||
// The push no-op message must include the "Your issues are stored locally" line.
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
|
|
@ -77,7 +77,7 @@ func TestDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
}
|
||||
|
|
@ -101,7 +101,7 @@ func TestDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
|
|||
|
||||
// -- pull --
|
||||
|
||||
func TestDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ func TestDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
}
|
||||
|
|
@ -146,7 +146,7 @@ func TestDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
|
|||
|
||||
// -- remote add --
|
||||
|
||||
func TestDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
}
|
||||
|
|
@ -169,7 +169,7 @@ func TestDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
|
||||
// The refusal must go to stderr (not stdout) so agents can distinguish errors.
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
|
|
@ -189,7 +189,7 @@ func TestDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
|
|||
|
||||
// -- config round-trip --
|
||||
|
||||
func TestDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
|
||||
// bd config set dolt.local-only true / unset must persist via config.yaml.
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
|
|
@ -215,7 +215,7 @@ func TestDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
|
|||
|
||||
// -- bd dolt status --
|
||||
|
||||
func TestDoltLocalOnly_DoltStatus_ShowsDisabled(t *testing.T) {
|
||||
func TestEmbeddedDoltLocalOnly_DoltStatus_ShowsDisabled(t *testing.T) {
|
||||
// When dolt.local-only=true, bd dolt status must include the indicator line.
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
|
||||
|
|
|
|||
|
|
@ -1,21 +1,19 @@
|
|||
//go:build embeddeddolt && cgo
|
||||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Integration tests for be-7eu1d: git-origin collision guard in bd dolt remote
|
||||
// add and bd doctor (FR-06 to FR-09).
|
||||
//
|
||||
// TDD gate tests — these fail before the implementation exists. Run with
|
||||
// BEADS_TEST_EMBEDDED_DOLT=1.
|
||||
// Integration tests for be-7eu1d's git-origin collision guard in bd dolt
|
||||
// remote add (FR-06, FR-07). Its bd doctor half (FR-08, FR-09:
|
||||
// doctor.CheckDoltRemoteGitOrigin) is server-mode only: bd doctor runs none of
|
||||
// its checks on an embedded workspace (GH#3794), so it cannot be driven here.
|
||||
|
||||
// remoteAdd runs "bd dolt remote add <args>" returning (stdout, stderr, error)
|
||||
// with separate buffers. Delegates to bdDoltSeparate (dolt_local_only_embedded_test.go).
|
||||
|
|
@ -34,25 +32,11 @@ func setGitOrigin(t *testing.T, dir, url string) {
|
|||
}
|
||||
}
|
||||
|
||||
// bdDoctorSeparate runs "bd doctor <args>" returning (stdout, stderr, error).
|
||||
func bdDoctorSeparate(t *testing.T, bd, dir string, args ...string) (string, string, error) {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"doctor"}, args...)
|
||||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
return stdout.String(), stderr.String(), err
|
||||
}
|
||||
|
||||
// -- bd dolt remote add: collision with git origin --
|
||||
|
||||
// TestDoltRemoteAdd_GitOriginCollision_Exits1 asserts that adding a Dolt remote
|
||||
// TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1 asserts that adding a Dolt remote
|
||||
// whose URL matches the git origin exits non-zero and prints the refusal message.
|
||||
func TestDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -75,9 +59,9 @@ func TestDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy verifies exact phrases
|
||||
// TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy verifies exact phrases
|
||||
// from the UX spec (be-fxwbm §2.1) appear in the refusal output.
|
||||
func TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -103,9 +87,9 @@ func TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_AllowGitOrigin_Exits0 asserts that --allow-git-origin
|
||||
// TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0 asserts that --allow-git-origin
|
||||
// bypasses the collision guard and exits 0.
|
||||
func TestDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -122,9 +106,9 @@ func TestDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr asserts the one-liner warning
|
||||
// TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr asserts the one-liner warning
|
||||
// from be-fxwbm §2.2 appears on stderr when --allow-git-origin is set.
|
||||
func TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -146,9 +130,9 @@ func TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally asserts no refusal fires when
|
||||
// TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally asserts no refusal fires when
|
||||
// the git repo has no 'origin' remote.
|
||||
func TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -167,9 +151,9 @@ func TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_DifferentURL_ProceedsNormally asserts the guard does not
|
||||
// TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally asserts the guard does not
|
||||
// fire when the Dolt remote URL is different from the git origin.
|
||||
func TestDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -190,10 +174,10 @@ func TestDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard verifies that when
|
||||
// TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard verifies that when
|
||||
// dolt.local-only=true is set, the local-only refusal fires before the
|
||||
// git-origin guard — the local-only guard takes priority (be-3v2ou ordering).
|
||||
func TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -218,130 +202,9 @@ func TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// -- bd doctor: Dolt remote matches git origin --
|
||||
|
||||
// TestDoctor_DoltRemoteMatchesGitOrigin_Warning verifies that bd doctor emits a
|
||||
// warning when a Dolt remote URL matches the git origin.
|
||||
func TestDoctor_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "dw")
|
||||
|
||||
originURL := "file:///tmp/origin-collision-for-doctor"
|
||||
setGitOrigin(t, dir, originURL)
|
||||
|
||||
// Add a Dolt remote that matches the git origin (using --allow-git-origin to bypass the guard).
|
||||
bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL)
|
||||
|
||||
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
|
||||
combined := stdout
|
||||
|
||||
// Doctor must surface the warning check.
|
||||
if !strings.Contains(combined, "warning") && !strings.Contains(combined, "Warning") {
|
||||
t.Errorf("bd doctor: expected warning when Dolt remote matches git origin\noutput:\n%s", combined)
|
||||
}
|
||||
if !strings.Contains(combined, "git origin") {
|
||||
t.Errorf("bd doctor: expected 'git origin' in warning output\noutput:\n%s", combined)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_DoltRemoteNoMatch_OK verifies that bd doctor does NOT emit a
|
||||
// git-origin warning when the Dolt remote URL differs from the git origin.
|
||||
func TestDoctor_DoltRemoteNoMatch_OK(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "dn")
|
||||
|
||||
setGitOrigin(t, dir, "https://github.com/org/repo.git")
|
||||
remoteDir := t.TempDir()
|
||||
bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir)
|
||||
|
||||
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
|
||||
if strings.Contains(stdout, "Dolt remote matches git origin") {
|
||||
t.Errorf("bd doctor: unexpected git-origin warning when URLs differ\noutput:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_NoGitOrigin_OK verifies that bd doctor shows OK for the git-origin
|
||||
// check when no git origin is configured.
|
||||
func TestDoctor_NoGitOrigin_OK(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "ng")
|
||||
// bdInit creates a git repo but no origin.
|
||||
|
||||
remoteDir := t.TempDir()
|
||||
bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir)
|
||||
|
||||
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
|
||||
// Should not emit a warning for the git-origin check.
|
||||
if strings.Contains(stdout, "Dolt remote matches git origin") {
|
||||
t.Errorf("bd doctor: unexpected git-origin warning when no git origin\noutput:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning verifies that
|
||||
// bd doctor --json exposes the git-origin warning check with "status":"warning".
|
||||
func TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "dj")
|
||||
|
||||
originURL := "file:///tmp/origin-collision-for-json"
|
||||
setGitOrigin(t, dir, originURL)
|
||||
bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL)
|
||||
|
||||
stdout, _, _ := bdDoctorSeparate(t, bd, dir, "--json")
|
||||
|
||||
// Output should be JSON array of checks.
|
||||
var checks []map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &checks); err != nil {
|
||||
// May be wrapped in an outer object — try extracting the checks array.
|
||||
var outer map[string]interface{}
|
||||
if jsonErr := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &outer); jsonErr != nil {
|
||||
t.Fatalf("bd doctor --json: not valid JSON: %v\noutput:\n%s", err, stdout)
|
||||
}
|
||||
if arr, ok := outer["checks"].([]interface{}); ok {
|
||||
data, _ := json.Marshal(arr)
|
||||
_ = json.Unmarshal(data, &checks)
|
||||
}
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, check := range checks {
|
||||
name, _ := check["name"].(string)
|
||||
if strings.Contains(name, "git origin") || strings.Contains(name, "Dolt remote") {
|
||||
found = true
|
||||
status, _ := check["status"].(string)
|
||||
if status != "warning" {
|
||||
t.Errorf("doctor JSON check %q: status = %q, want \"warning\"", name, status)
|
||||
}
|
||||
if _, hasFix := check["fix"]; !hasFix {
|
||||
t.Errorf("doctor JSON check %q: missing \"fix\" field", name)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("bd doctor --json: no git-origin check found in output\noutput:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr asserts that even in
|
||||
// TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr asserts that even in
|
||||
// --json mode, the override warning still appears on stderr (not stdout).
|
||||
func TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ func lsRemoteRef(t *testing.T, remoteDir, ref string) string {
|
|||
return fields[0]
|
||||
}
|
||||
|
||||
func TestDoltRemoteResetData_GitBacked(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteResetData_GitBacked(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -112,7 +112,7 @@ func TestDoltRemoteResetData_GitBacked(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltRemoteResetData_UnknownRemote(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteResetData_UnknownRemote(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
@ -129,7 +129,7 @@ func TestDoltRemoteResetData_UnknownRemote(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDoltRemoteResetData_CloudRemoteRefused(t *testing.T) {
|
||||
func TestEmbeddedDoltRemoteResetData_CloudRemoteRefused(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
// TestAutoPruneBoundsTheJournalAfterAMutatingCommand is the feature as a user
|
||||
// TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand is the feature as a user
|
||||
// meets it: enable the journal, write, and the journal stays inside its floors
|
||||
// without anyone running `bd events prune`.
|
||||
//
|
||||
|
|
@ -30,7 +30,7 @@ import (
|
|||
// because the throttle's persisted watermark is never stamped while auto-prune
|
||||
// is off, so the next command with it on is the first pass this workspace has
|
||||
// ever run.
|
||||
func TestAutoPruneBoundsTheJournalAfterAMutatingCommand(t *testing.T) {
|
||||
func TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand(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")
|
||||
}
|
||||
|
|
@ -117,12 +117,12 @@ func TestAutoPruneBoundsTheJournalAfterAMutatingCommand(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestAutoPruneLeavesAnUnboundedJournalAlone. Both floors at 0 is the documented
|
||||
// TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone. Both floors at 0 is the documented
|
||||
// way to keep every record, and it is also the configuration the truncation
|
||||
// tests run under — so a maintenance pass that ignored it would quietly delete
|
||||
// the history those tests (and any consumer that chose an unbounded ledger)
|
||||
// depend on.
|
||||
func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
|
||||
func TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone(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")
|
||||
}
|
||||
|
|
@ -158,7 +158,7 @@ func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestAutoPruneRespectsBdConfigSet drives the whole retention story through
|
||||
// TestEmbeddedAutoPruneRespectsBdConfigSet drives the whole retention story through
|
||||
// `bd config set` rather than the environment.
|
||||
//
|
||||
// The four events-journal keys are startup settings read through viper before
|
||||
|
|
@ -167,7 +167,7 @@ func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
|
|||
// `bd config set events-journal true` reported success and changed nothing.
|
||||
// A new key is one YamlOnlyKeys entry away from repeating it, and the symptom
|
||||
// is invisible: retention that silently keeps whatever the default was.
|
||||
func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
|
||||
func TestEmbeddedAutoPruneRespectsBdConfigSet(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")
|
||||
}
|
||||
|
|
@ -221,7 +221,7 @@ func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestAutoPruneDoesNotRunForReadOnlyCommands. The trigger is writer-pays, and
|
||||
// TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands. The trigger is writer-pays, and
|
||||
// three separate gates keep it that way — each one covered here by a command
|
||||
// that would prune the journal without it:
|
||||
//
|
||||
|
|
@ -236,7 +236,7 @@ func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
|
|||
// - `bd migrate --dry-run` is a PREVIEW. It promised not to mutate and holds
|
||||
// a write-refusing store; maintenance must not be the one write it
|
||||
// performs.
|
||||
func TestAutoPruneDoesNotRunForReadOnlyCommands(t *testing.T) {
|
||||
func TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ func runBDOut(t *testing.T, bd, dir string, env []string, args ...string) (strin
|
|||
return stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
// TestDeleteJournalsTheRequestingActor is #5985's repro, verbatim: create two
|
||||
// TestEmbeddedDeleteJournalsTheRequestingActor is #5985's repro, verbatim: create two
|
||||
// beads with an edge between them, delete the blocker with an explicit --actor,
|
||||
// and read the journal back. Both the delete record and the cascade dep_remove
|
||||
// record must name that actor.
|
||||
|
|
@ -42,7 +42,7 @@ func runBDOut(t *testing.T, bd, dir string, env []string, args ...string) (strin
|
|||
// The whole route is exercised — cobra flag to journal column — because the
|
||||
// actor is resolved, threaded through the role, and written by the storage
|
||||
// seam, and a unit test at any one of those cannot see the drop at the next.
|
||||
func TestDeleteJournalsTheRequestingActor(t *testing.T) {
|
||||
func TestEmbeddedDeleteJournalsTheRequestingActor(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")
|
||||
}
|
||||
|
|
@ -92,13 +92,13 @@ func TestDeleteJournalsTheRequestingActor(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestEventsReadNoticesADisabledJournal pins the "nothing to read and no way to
|
||||
// TestEmbeddedEventsReadNoticesADisabledJournal pins the "nothing to read and no way to
|
||||
// tell why" fix. A workspace that never enabled the journal serves an empty
|
||||
// export forever, which a consumer cannot distinguish from being caught up, so
|
||||
// the read says so on stderr — and keeps stdout clean and the exit status zero,
|
||||
// because exporting a historical ledger from a now-disabled workspace is
|
||||
// legitimate.
|
||||
func TestEventsReadNoticesADisabledJournal(t *testing.T) {
|
||||
func TestEmbeddedEventsReadNoticesADisabledJournal(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,7 +118,7 @@ func eventsJournalMaintenanceRunnerFor(plumbing any) issueops.EventsMaintenanceR
|
|||
// with OpenForReadOnlyCommand, which is "otherwise a normal writable
|
||||
// store", so nothing underneath refuses a maintenance delete. Drop this
|
||||
// check and `bd list` prunes the journal — which
|
||||
// TestAutoPruneDoesNotRunForReadOnlyCommands catches.
|
||||
// TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands catches.
|
||||
//
|
||||
// Two more gates are specific to this trigger:
|
||||
//
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ func TestProxiedServerServeActivatesTheEventsJournal(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestRoutedCreateJournalsIntoTheTargetWorkspace covers the cross-workspace
|
||||
// TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace covers the cross-workspace
|
||||
// store: `bd create --repo <other>` opens a SECOND store for another workspace
|
||||
// and writes the bead there.
|
||||
//
|
||||
|
|
@ -65,7 +65,7 @@ func TestProxiedServerServeActivatesTheEventsJournal(t *testing.T) {
|
|||
// TARGET's own config.yaml, so a workspace that enabled the journal gets its
|
||||
// mutations recorded no matter which directory bd was launched from — and the
|
||||
// launching workspace, which enabled nothing, records nothing of its own.
|
||||
func TestRoutedCreateJournalsIntoTheTargetWorkspace(t *testing.T) {
|
||||
func TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace(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")
|
||||
}
|
||||
|
|
@ -120,13 +120,13 @@ func TestRoutedCreateJournalsIntoTheTargetWorkspace(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig is the precedence
|
||||
// TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig is the precedence
|
||||
// half. BD_EVENTS_JOURNAL is the documented way to turn the journal on for a
|
||||
// process without editing a workspace, and a routed write is exactly where an
|
||||
// operator reaches for it — so a target whose config.yaml says false must not
|
||||
// be able to veto it. Getting this backwards makes the env var a suggestion,
|
||||
// and the operator finds out by discovering an empty journal later.
|
||||
func TestRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig(t *testing.T) {
|
||||
func TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,15 +89,21 @@ var qualifiedActivationCalls = map[string]map[string]bool{
|
|||
|
||||
// scannedPackages are the directories searched for construction sites: every
|
||||
// package that builds a store or provider for the bd binary, plus the standalone
|
||||
// embedded-Dolt utility so it is accounted for rather than merely unnoticed.
|
||||
// Each maps to the prefix its sites are keyed under.
|
||||
// embedded-Dolt utility and the Go SDK's own opens (the repository root), so they
|
||||
// are accounted for rather than merely unnoticed. Each maps to the prefix its
|
||||
// sites are keyed under.
|
||||
var scannedPackages = map[string]string{
|
||||
".": "",
|
||||
"doctor": "doctor/",
|
||||
"doctor/fix": "doctor/fix/",
|
||||
"../../internal/storage/embeddeddolt/cmd": "embeddeddolt-cmd/",
|
||||
"../..": "sdk/",
|
||||
}
|
||||
|
||||
// sdkOpenExemptionReason is the one reason the Go SDK's five opens share. It has
|
||||
// to be true of both per-store switches, because the exemption list is shared.
|
||||
const sdkOpenExemptionReason = "SDK entry point (library surface, not the bd binary): applies neither per-store switch, the events journal's or versioned history's; the bd binary's factories do"
|
||||
|
||||
// constructionExemptions are construction sites that legitimately do NOT
|
||||
// activate the events journal, each with a reason. Keyed by
|
||||
// "<pkg>/<file>:<Recv.Func>" so the two build-tag twins of a factory are
|
||||
|
|
@ -172,6 +178,17 @@ var constructionExemptions = map[string]string{
|
|||
// A standalone developer utility binary, not bd. It has no workspace config
|
||||
// to read and never runs as part of a bd command.
|
||||
"embeddeddolt-cmd/main.go:main": "standalone embeddeddolt debug utility, not the bd binary; no workspace config and no bd command context",
|
||||
|
||||
// The Go SDK's own opens (the repository root's beads package). They are a
|
||||
// library surface that embedders call directly, and they build stores without
|
||||
// applying either per-store switch. They are declared here so that a new SDK
|
||||
// open is noticed rather than missed. Making them apply the switches would
|
||||
// change the library's behavior for every embedder, so it is a separate change.
|
||||
"sdk/beads.go:Open": sdkOpenExemptionReason,
|
||||
"sdk/beads.go:OpenFromConfig": sdkOpenExemptionReason,
|
||||
"sdk/beads.go:OpenGated": sdkOpenExemptionReason,
|
||||
"sdk/beads_cgo.go:OpenBestAvailableWith": sdkOpenExemptionReason,
|
||||
"sdk/beads_nocgo.go:OpenBestAvailableWith": sdkOpenExemptionReason,
|
||||
}
|
||||
|
||||
func TestEveryStoreConstructionActivatesTheEventsJournal(t *testing.T) {
|
||||
|
|
@ -235,6 +252,9 @@ func exemptionFor(key string) (exemption, reason string, ok bool) {
|
|||
type constructionSite struct {
|
||||
constructors []string
|
||||
activates bool
|
||||
// activatesVersionedHistory is the same question for the versioned-history
|
||||
// guard, which reuses this scan (see versioned_history_construction_test.go).
|
||||
activatesVersionedHistory bool
|
||||
}
|
||||
|
||||
// scanStoreConstructionSites parses each scanned package and returns one entry
|
||||
|
|
@ -364,10 +384,16 @@ func inspectConstructionSite(node ast.Node, imports map[string]string) *construc
|
|||
if qualifiedActivationCalls[path][fun.Sel.Name] {
|
||||
site.activates = true
|
||||
}
|
||||
if qualifiedVersionedHistoryActivationCalls[path][fun.Sel.Name] {
|
||||
site.activatesVersionedHistory = true
|
||||
}
|
||||
case *ast.Ident:
|
||||
if activationCalls[fun.Name] {
|
||||
site.activates = true
|
||||
}
|
||||
if versionedHistoryActivationCalls[fun.Name] {
|
||||
site.activatesVersionedHistory = true
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
|
@ -16,7 +15,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
// TestEventsTailReportsTruncationToTheCLI is the end-to-end guard for the
|
||||
// TestEmbeddedEventsTailReportsTruncationToTheCLI is the end-to-end guard for the
|
||||
// retention boundary as a consumer actually meets it: through the binary, not
|
||||
// through the store API.
|
||||
//
|
||||
|
|
@ -27,7 +26,7 @@ import (
|
|||
// that; this one fails if either path regresses. It also proves the whole
|
||||
// config chain end to end: BD_EVENTS_JOURNAL turns the journal on, and the two
|
||||
// BD_EVENTS_JOURNAL_RETAIN_* floors reach the prune.
|
||||
func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
|
||||
func TestEmbeddedEventsTailReportsTruncationToTheCLI(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")
|
||||
}
|
||||
|
|
@ -109,7 +108,7 @@ func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestEventsTailFollowReportsTruncationOnTheStream covers the OTHER read call
|
||||
// TestEmbeddedEventsTailFollowReportsTruncationOnTheStream covers the OTHER read call
|
||||
// site: the --follow poll, which the one-shot test above cannot reach.
|
||||
//
|
||||
// A follower is the consumer most exposed to a prune — it is the one sitting
|
||||
|
|
@ -120,7 +119,7 @@ func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
|
|||
// it interrupts. The consumer on the other end is a line reader; a
|
||||
// pretty-printed multi-line object in the middle of its input is unparseable,
|
||||
// and it would see the stream stop with garbage after the last good record.
|
||||
func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
|
||||
func TestEmbeddedEventsTailFollowReportsTruncationOnTheStream(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")
|
||||
}
|
||||
|
|
@ -163,7 +162,7 @@ func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
|
|||
follow := exec.Command(bd, "events", "tail", "--since", "0", "--limit", "1", "--follow", "--json")
|
||||
follow.Dir = dir
|
||||
follow.Env = env
|
||||
var stdout, stderr bytes.Buffer
|
||||
var stdout, stderr syncBuffer
|
||||
follow.Stdout = &stdout
|
||||
follow.Stderr = &stderr
|
||||
if err := follow.Start(); err != nil {
|
||||
|
|
@ -226,11 +225,11 @@ func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestEventsPruneHonorsRetainRowsFloorFromConfig proves the shipped defaults
|
||||
// TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig proves the shipped defaults
|
||||
// reach the CLI: a `prune --before <huge>` on a workspace that configured no
|
||||
// floors of its own must be stopped by the built-in retain-rows floor rather
|
||||
// than deleting the whole journal and stranding its consumer.
|
||||
func TestEventsPruneHonorsRetainRowsFloorFromConfig(t *testing.T) {
|
||||
func TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,9 +47,9 @@ func parseExportedIssues(t *testing.T, jsonl string) []*types.Issue {
|
|||
return issues
|
||||
}
|
||||
|
||||
// TestExportExcludeOwner_flag verifies that bd export --exclude-owner=<name>
|
||||
// TestEmbeddedExportExcludeOwner_flag verifies that bd export --exclude-owner=<name>
|
||||
// filters out issues created_by that identity from the export.
|
||||
func TestExportExcludeOwner_flag(t *testing.T) {
|
||||
func TestEmbeddedExportExcludeOwner_flag(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")
|
||||
}
|
||||
|
|
@ -86,9 +86,9 @@ func TestExportExcludeOwner_flag(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestExportExcludeOwner_config verifies that export.exclude_owners config
|
||||
// TestEmbeddedExportExcludeOwner_config verifies that export.exclude_owners config
|
||||
// filters issues without a command-line flag.
|
||||
func TestExportExcludeOwner_config(t *testing.T) {
|
||||
func TestEmbeddedExportExcludeOwner_config(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")
|
||||
}
|
||||
|
|
@ -115,8 +115,8 @@ func TestExportExcludeOwner_config(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestExportExcludeOwner_verbose verifies that --verbose emits a filtered count message.
|
||||
func TestExportExcludeOwner_verbose(t *testing.T) {
|
||||
// TestEmbeddedExportExcludeOwner_verbose verifies that --verbose emits a filtered count message.
|
||||
func TestEmbeddedExportExcludeOwner_verbose(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")
|
||||
}
|
||||
|
|
@ -151,12 +151,12 @@ func TestExportExcludeOwner_verbose(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestAutoExportExcludeOwner_config is a regression test for the maphew review
|
||||
// TestEmbeddedAutoExportExcludeOwner_config is a regression test for the maphew review
|
||||
// of PR #4023 (be-e2nb): the export.exclude_owners safety net must also apply to
|
||||
// the git-committed auto-export (.beads/issues.jsonl), not only to manual
|
||||
// `bd export`. Before the fix, contributor/personal issues that the manual path
|
||||
// excludes could still leak into git history and PRs via auto-export.
|
||||
func TestAutoExportExcludeOwner_config(t *testing.T) {
|
||||
func TestEmbeddedAutoExportExcludeOwner_config(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")
|
||||
}
|
||||
|
|
|
|||
102
cmd/bd/format_json_alias_embedded_test.go
Normal file
102
cmd/bd/format_json_alias_embedded_test.go
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// bdRunStreams runs one bd process in dir with the hermetic test environment
|
||||
// and returns stdout, stderr and the exit status separately. A nonzero exit is
|
||||
// returned, not fatal, so a caller can pin the status itself; only a process
|
||||
// that could not be started fails the test here.
|
||||
func bdRunStreams(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exit int) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
var outBuf, errBuf bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &outBuf, &errBuf
|
||||
if err := cmd.Run(); err != nil {
|
||||
var ee *exec.ExitError
|
||||
if !errors.As(err, &ee) {
|
||||
t.Fatalf("bd %s did not run: %v", strings.Join(args, " "), err)
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), ee.ExitCode()
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), 0
|
||||
}
|
||||
|
||||
// TestEmbeddedFormatJSONAliasMatchesJSON pins the hidden root --format alias
|
||||
// (GH#2612): on show, list, ready and memories, `--format json` prints exactly
|
||||
// what `--json` prints, byte for byte, and exits 0 like it.
|
||||
//
|
||||
// The alias is a root persistent flag, so any subcommand that registers a
|
||||
// --format of its own shadows it (the GH#6278 hazard). `bd list` already has
|
||||
// its own --format and passes `json` through by hand (list_input.go). A
|
||||
// local --format added to show, ready or memories for another output
|
||||
// format would turn `bd show ID --format json` into a refusal or into a
|
||||
// different document. Both are regressions this test catches: it compares
|
||||
// the whole of stdout, not a parse of it.
|
||||
//
|
||||
// Each command is checked in three spellings: `--format json` and
|
||||
// `--format=json` after the subcommand, and `--format json` before it, where
|
||||
// the flag is plainly the root's.
|
||||
func TestEmbeddedFormatJSONAliasMatchesJSON(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, _, _ := bdInit(t, bd, "--prefix", "fj")
|
||||
|
||||
id := bdCreateSilent(t, bd, dir, "Format alias parity", "--type", "task", "--description", "read through --format json")
|
||||
bdRunOK(t, bd, dir, "remember", "the format alias is --json", "--key", "fj-alias")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
// mention is a value the --json document must contain, so two empty
|
||||
// documents cannot match each other.
|
||||
mention string
|
||||
}{
|
||||
{"show", []string{"show", id}, id},
|
||||
{"list", []string{"list"}, id},
|
||||
{"ready", []string{"ready"}, id},
|
||||
{"memories", []string{"memories"}, "fj-alias"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
wantArgs := slices.Concat(tc.args, []string{"--json"})
|
||||
want, wantErr, exit := bdRunStreams(t, bd, dir, wantArgs...)
|
||||
if exit != 0 {
|
||||
t.Fatalf("bd %s exited %d\nstdout:\n%s\nstderr:\n%s", strings.Join(wantArgs, " "), exit, want, wantErr)
|
||||
}
|
||||
if !json.Valid([]byte(want)) || !strings.Contains(want, tc.mention) {
|
||||
t.Fatalf("bd %s did not print one JSON document naming %s:\n%s", strings.Join(wantArgs, " "), tc.mention, want)
|
||||
}
|
||||
|
||||
for _, args := range [][]string{
|
||||
slices.Concat(tc.args, []string{"--format", "json"}),
|
||||
slices.Concat(tc.args, []string{"--format=json"}),
|
||||
slices.Concat([]string{"--format", "json"}, tc.args),
|
||||
} {
|
||||
got, gotErr, exit := bdRunStreams(t, bd, dir, args...)
|
||||
if exit != 0 {
|
||||
t.Errorf("bd %s exited %d, want 0 like bd %s\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, strings.Join(wantArgs, " "), got, gotErr)
|
||||
continue
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("bd %s printed a different document from bd %s\n--format:\n%s\n--json:\n%s", strings.Join(args, " "), strings.Join(wantArgs, " "), got, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
326
cmd/bd/graph_mode_admission_e2e_test.go
Normal file
326
cmd/bd/graph_mode_admission_e2e_test.go
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// graphModeAdmissionFixture is a workspace whose metadata or format marker
|
||||
// declares a format this build does not open.
|
||||
type graphModeAdmissionFixture struct {
|
||||
name string
|
||||
// filename is the metadata file; "" lays down no metadata.
|
||||
filename string
|
||||
metadata string
|
||||
// embedded adds the embedded Dolt root of a graph database. Without the
|
||||
// guard, an ordinary bd opens that database as an Issue store and
|
||||
// migrates it.
|
||||
embedded bool
|
||||
// marker adds the graph-preview-format sentinel graph-preview builds
|
||||
// write before metadata.json.
|
||||
marker bool
|
||||
// refusal lists what the refusal must mention besides "this bd build
|
||||
// does not support": the declared format and the start of its hint.
|
||||
refusal []string
|
||||
}
|
||||
|
||||
// write lays the fixture down under beadsDir and returns the metadata path,
|
||||
// or "" when the fixture has no metadata.
|
||||
func (f graphModeAdmissionFixture) write(t *testing.T, beadsDir string) string {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := ""
|
||||
if f.filename != "" {
|
||||
path = filepath.Join(beadsDir, f.filename)
|
||||
writeFile(t, path, []byte(f.metadata))
|
||||
}
|
||||
if f.embedded {
|
||||
if err := os.MkdirAll(filepath.Join(beadsDir, "embeddeddolt", "beads_graph_0123456789abcdef0123456789abcdef", ".dolt"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if f.marker {
|
||||
writeFile(t, filepath.Join(beadsDir, "graph-preview-format"), []byte("link-preview-v9\n"))
|
||||
}
|
||||
if err := os.Chmod(beadsDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func graphModeAdmissionFixtures() []graphModeAdmissionFixture {
|
||||
graphModeRefusal := func(mode string) []string {
|
||||
return []string{"graph_mode", mode, "use a bd build that supports graph_mode"}
|
||||
}
|
||||
var fixtures []graphModeAdmissionFixture
|
||||
fixtures = append(fixtures, graphModeAdmissionFixture{
|
||||
name: "metadata.json/link/embedded", filename: "metadata.json",
|
||||
metadata: graphLinkWorkspaceMetadata, embedded: true, marker: true,
|
||||
refusal: graphModeRefusal("link"),
|
||||
})
|
||||
for _, filename := range []string{"metadata.json", "config.json"} {
|
||||
for _, mode := range []string{"link", "future-format"} {
|
||||
fixtures = append(fixtures, graphModeAdmissionFixture{
|
||||
name: filename + "/" + mode + "/server", filename: filename,
|
||||
metadata: `{"backend":"dolt","dolt_mode":"server","graph_mode":"` + mode + `"}`,
|
||||
refusal: graphModeRefusal(mode),
|
||||
})
|
||||
}
|
||||
}
|
||||
// Only the format marker declares these: graph init stopped before
|
||||
// metadata.json, metadata.json was lost, or a bd that predates
|
||||
// graph_mode rewrote it without the field.
|
||||
markerRefusal := []string{"graph-preview-format", "restore metadata.json"}
|
||||
fixtures = append(fixtures,
|
||||
graphModeAdmissionFixture{
|
||||
name: "marker/only", marker: true,
|
||||
refusal: markerRefusal,
|
||||
},
|
||||
graphModeAdmissionFixture{
|
||||
name: "marker/metadata-lost/embedded", embedded: true, marker: true,
|
||||
refusal: markerRefusal,
|
||||
},
|
||||
graphModeAdmissionFixture{
|
||||
name: "marker/metadata-stripped/embedded", filename: "metadata.json",
|
||||
metadata: graphStrippedWorkspaceMetadata, embedded: true, marker: true,
|
||||
refusal: markerRefusal,
|
||||
},
|
||||
graphModeAdmissionFixture{
|
||||
name: "marker/dependency/server", filename: "metadata.json",
|
||||
metadata: `{"backend":"dolt","dolt_mode":"server","graph_mode":"dependency"}`, marker: true,
|
||||
refusal: markerRefusal,
|
||||
},
|
||||
)
|
||||
return fixtures
|
||||
}
|
||||
|
||||
// runGraphModeAdmissionBD runs bd in repoDir with a private HOME and no
|
||||
// ambient BEADS_* selection, and returns its combined output and exit code.
|
||||
func runGraphModeAdmissionBD(t *testing.T, bd, repoDir string, args ...string) (string, int) {
|
||||
t.Helper()
|
||||
return runGraphModeAdmissionBDEnv(t, bd, repoDir, nil, args...)
|
||||
}
|
||||
|
||||
// runGraphModeAdmissionBDEnv is runGraphModeAdmissionBD run in dir with env
|
||||
// added to bd's environment.
|
||||
func runGraphModeAdmissionBDEnv(t *testing.T, bd, dir string, env []string, args ...string) (string, int) {
|
||||
t.Helper()
|
||||
// A refused run takes well under a second. An unrefused one (what these
|
||||
// tests catch) goes on to create or open a database, which under load
|
||||
// can approach 10s; the bound leaves room for it to fail on the
|
||||
// assertion that names the regression rather than on the timeout.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(bdEnv(t.TempDir()),
|
||||
"BEADS_DOLT_SERVER_MODE=0",
|
||||
"BEADS_DOLT_SHARED_SERVER=0",
|
||||
)
|
||||
cmd.Env = append(cmd.Env, env...)
|
||||
var output bytes.Buffer
|
||||
cmd.Stdout = &output
|
||||
cmd.Stderr = &output
|
||||
err := cmd.Run()
|
||||
if ctx.Err() != nil {
|
||||
t.Fatalf("bd %s did not finish promptly: %v\n%s", strings.Join(args, " "), ctx.Err(), output.String())
|
||||
}
|
||||
var exitErr *exec.ExitError
|
||||
switch {
|
||||
case err == nil:
|
||||
return output.String(), 0
|
||||
case errors.As(err, &exitErr):
|
||||
return output.String(), exitErr.ExitCode()
|
||||
default:
|
||||
t.Fatalf("bd %s: %v", strings.Join(args, " "), err)
|
||||
return "", -1
|
||||
}
|
||||
}
|
||||
|
||||
// requireGraphModeRefusal fails unless bd args exited with the refusal of
|
||||
// fixture's workspace format and its hint.
|
||||
func requireGraphModeRefusal(t *testing.T, fixture graphModeAdmissionFixture, args []string, output string, code int) {
|
||||
t.Helper()
|
||||
if code != ExitUnsupportedWorkspaceFormat {
|
||||
t.Fatalf("bd %s exit = %d, want %d (ExitUnsupportedWorkspaceFormat)\n%s",
|
||||
strings.Join(args, " "), code, ExitUnsupportedWorkspaceFormat, output)
|
||||
}
|
||||
// --json renders the refusal as a JSON error, which escapes the quotes
|
||||
// around the mode, so match its parts.
|
||||
for _, want := range append([]string{"this bd build does not support"}, fixture.refusal...) {
|
||||
if !strings.Contains(output, want) {
|
||||
t.Fatalf("bd %s refusal does not mention %q:\n%s", strings.Join(args, " "), want, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal in a helper is insufficient: ordinary commands must reach it before
|
||||
// metadata migration, version tracking, or an attempt to provision/open storage.
|
||||
func TestGraphModeCLIRefusesLegacyStoreWithoutWorkspaceEffects(t *testing.T) {
|
||||
bd := buildBDUnderTest(t)
|
||||
commands := [][]string{
|
||||
{"show", "beads/plan"},
|
||||
{"list", "--json"},
|
||||
{"create", "graph fence probe"},
|
||||
{"context", "--json"},
|
||||
{"where"},
|
||||
{"dolt", "start"},
|
||||
{"doctor", "--json"},
|
||||
{"bootstrap", "--dry-run", "--yes"},
|
||||
{"init", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"},
|
||||
{"init", "--force", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"},
|
||||
// What the installed git hooks run; their shim passes exit 16 on.
|
||||
{"hooks", "run", "pre-commit"},
|
||||
}
|
||||
for _, fixture := range graphModeAdmissionFixtures() {
|
||||
for _, args := range commands {
|
||||
name := args[0]
|
||||
if name == "init" && args[1] == "--force" {
|
||||
name = "init-force"
|
||||
}
|
||||
t.Run(fixture.name+"/"+name, func(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
initGitRepoAt(t, repoDir)
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
metadataPath := fixture.write(t, beadsDir)
|
||||
before := legacyUpgradeTreeDigest(t, beadsDir)
|
||||
|
||||
output, code := runGraphModeAdmissionBD(t, bd, repoDir, args...)
|
||||
requireGraphModeRefusal(t, fixture, args, output, code)
|
||||
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
|
||||
t.Fatalf("refused bd %s changed the workspace\n%s", strings.Join(args, " "), output)
|
||||
}
|
||||
if metadataPath != "" {
|
||||
if got, err := os.ReadFile(metadataPath); err != nil || string(got) != fixture.metadata {
|
||||
t.Fatalf("refused bd %s rewrote %s: %q, %v", strings.Join(args, " "), fixture.filename, got, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Commands also reach a workspace they do not run in: create --repo, from
|
||||
// another workspace or from none and as a dry run, --db and BEADS_DB,
|
||||
// init --proxied-server, and bootstrap in a workspace with no metadata of its
|
||||
// own, which takes the nearest ancestor's (and refuses a graph ancestor even
|
||||
// when only its format marker declares it, rather than skip past it). Each must refuse a graph workspace
|
||||
// the same way, before resolving it migrates a legacy config.json or anything
|
||||
// opens its store.
|
||||
func TestGraphModeOutsideEntryPointsRefuseWithoutWorkspaceEffects(t *testing.T) {
|
||||
bd := buildBDUnderTest(t)
|
||||
sourceDir, _, _ := bdInit(t, bd, "--prefix", "src")
|
||||
outsideDir := t.TempDir()
|
||||
entries := []struct {
|
||||
name string
|
||||
// run returns where bd runs, what it adds to bd's environment and
|
||||
// bd's arguments, for a graph workspace in repoDir.
|
||||
run func(t *testing.T, repoDir string) (dir string, env, args []string)
|
||||
}{
|
||||
{"create --repo from a workspace", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
return sourceDir, nil, []string{"create", "--repo", repoDir, "graph fence probe"}
|
||||
}},
|
||||
{"create --repo from outside", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
return outsideDir, nil, []string{"create", "--repo", repoDir, "graph fence probe"}
|
||||
}},
|
||||
{"create --dry-run --repo", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
// Without --parent the preview opens no target at all.
|
||||
return sourceDir, nil, []string{"create", "--dry-run", "--repo", repoDir, "graph fence probe"}
|
||||
}},
|
||||
{"create --dry-run --parent --repo", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
// A dry run looks the parent up in the target's store.
|
||||
return sourceDir, nil, []string{"create", "--dry-run", "--parent", "src-abc", "--repo", repoDir, "graph fence probe"}
|
||||
}},
|
||||
{"--db", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
return outsideDir, nil, []string{"--db", filepath.Join(repoDir, ".beads"), "list", "--json"}
|
||||
}},
|
||||
{"BEADS_DB", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
return outsideDir, []string{"BEADS_DB=" + filepath.Join(repoDir, ".beads")}, []string{"list", "--json"}
|
||||
}},
|
||||
{"init --proxied-server", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
return repoDir, nil, []string{"init", "--proxied-server", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"}
|
||||
}},
|
||||
{"bootstrap below it", func(t *testing.T, repoDir string) (string, []string, []string) {
|
||||
innerDir := filepath.Join(repoDir, "inner")
|
||||
writeFile(t, filepath.Join(innerDir, ".beads", "config.yaml"), []byte("# bd workspace config\n"))
|
||||
initGitRepoAt(t, innerDir)
|
||||
return innerDir, nil, []string{"bootstrap", "--dry-run", "--yes"}
|
||||
}},
|
||||
}
|
||||
for _, fixture := range graphModeAdmissionFixtures() {
|
||||
for _, entry := range entries {
|
||||
t.Run(fixture.name+"/"+entry.name, func(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
initGitRepoAt(t, repoDir)
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
metadataPath := fixture.write(t, beadsDir)
|
||||
dir, env, args := entry.run(t, repoDir)
|
||||
before := legacyUpgradeTreeDigest(t, beadsDir)
|
||||
|
||||
output, code := runGraphModeAdmissionBDEnv(t, bd, dir, env, args...)
|
||||
requireGraphModeRefusal(t, fixture, args, output, code)
|
||||
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
|
||||
t.Fatalf("bd %s changed the graph workspace\n%s", strings.Join(args, " "), output)
|
||||
}
|
||||
if metadataPath != "" {
|
||||
if got, err := os.ReadFile(metadataPath); err != nil || string(got) != fixture.metadata {
|
||||
t.Fatalf("refused bd %s rewrote %s: %q, %v", strings.Join(args, " "), fixture.filename, got, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Commands that never open a store keep working in a workspace this build
|
||||
// refuses, and leave it untouched.
|
||||
func TestGraphModeWorkspaceAdmitsStorelessCommands(t *testing.T) {
|
||||
bd := buildBDUnderTest(t)
|
||||
var fixtures []graphModeAdmissionFixture
|
||||
for _, fixture := range graphModeAdmissionFixtures() {
|
||||
if fixture.name == "metadata.json/link/embedded" || fixture.name == "marker/only" {
|
||||
fixtures = append(fixtures, fixture)
|
||||
}
|
||||
}
|
||||
if len(fixtures) != 2 {
|
||||
t.Fatalf("store-less fixtures = %d, want 2", len(fixtures))
|
||||
}
|
||||
for _, fixture := range fixtures {
|
||||
for _, args := range [][]string{
|
||||
{"version"},
|
||||
{"--version"},
|
||||
{"help"},
|
||||
{"completion", "bash"},
|
||||
} {
|
||||
t.Run(fixture.name+"/"+strings.Join(args, " "), func(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
initGitRepoAt(t, repoDir)
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
fixture.write(t, beadsDir)
|
||||
before := legacyUpgradeTreeDigest(t, beadsDir)
|
||||
|
||||
output, code := runGraphModeAdmissionBD(t, bd, repoDir, args...)
|
||||
if code != 0 {
|
||||
t.Fatalf("bd %s exit = %d, want 0\n%s", strings.Join(args, " "), code, output)
|
||||
}
|
||||
if strings.Contains(output, "this bd build does not support") {
|
||||
t.Fatalf("store-less bd %s reported the workspace format:\n%s", strings.Join(args, " "), output)
|
||||
}
|
||||
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
|
||||
t.Fatalf("bd %s changed the workspace", strings.Join(args, " "))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
90
cmd/bd/graph_mode_dependency_embedded_test.go
Normal file
90
cmd/bd/graph_mode_dependency_embedded_test.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// readGraphKeys returns the graph_* keys of a metadata.json and their values.
|
||||
func readGraphKeys(t *testing.T, path string) map[string]any {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal(data, &doc); err != nil {
|
||||
t.Fatalf("parse %s: %v\n%s", path, err, data)
|
||||
}
|
||||
keys := map[string]any{}
|
||||
for key, value := range doc {
|
||||
if strings.HasPrefix(key, "graph_") {
|
||||
keys[key] = value
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// The graph-mode fence must not change ordinary workspaces: one without the
|
||||
// marker, and one whose metadata names the default "dependency" model
|
||||
// explicitly, open and write as before, and a command that rewrites
|
||||
// metadata.json keeps the marker exactly as it found it.
|
||||
func TestEmbeddedGraphModeDependencyWorkspaceUnaffected(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)
|
||||
|
||||
for _, marker := range []string{"absent", "dependency"} {
|
||||
t.Run(marker, func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "gm")
|
||||
metadataPath := filepath.Join(beadsDir, "metadata.json")
|
||||
if marker != "absent" {
|
||||
data, err := os.ReadFile(metadataPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal(data, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc["graph_mode"] = marker
|
||||
data, err = json.MarshalIndent(doc, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(metadataPath, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
wantKeys := readGraphKeys(t, metadataPath)
|
||||
before, err := os.ReadFile(metadataPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
issue := bdCreate(t, bd, dir, "ordinary workspace issue", "--type", "task")
|
||||
if out := bdList(t, bd, dir, "--json"); !strings.Contains(out, issue.ID) {
|
||||
t.Fatalf("bd list --json does not show %s:\n%s", issue.ID, out)
|
||||
}
|
||||
if after, err := os.ReadFile(metadataPath); err != nil || string(after) != string(before) {
|
||||
t.Fatalf("create/list changed metadata.json:\nbefore:\n%s\nafter:\n%s\n%v", before, after, err)
|
||||
}
|
||||
|
||||
// upgrade ack rewrites metadata.json through configfile.Save.
|
||||
if out, err := bdRunWithFlockRetry(t, bd, dir, "upgrade", "ack"); err != nil {
|
||||
t.Fatalf("bd upgrade ack: %v\n%s", err, out)
|
||||
}
|
||||
if got := readGraphKeys(t, metadataPath); len(got) != len(wantKeys) || got["graph_mode"] != wantKeys["graph_mode"] {
|
||||
data, _ := os.ReadFile(metadataPath)
|
||||
t.Fatalf("metadata rewrite changed graph keys: got %v, want %v\n%s", got, wantKeys, data)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,8 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
|
@ -403,3 +405,128 @@ func TestEmbeddedHistoryConcurrent(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doltCommitHashPattern is a full Dolt commit hash: 32 characters of Dolt's
|
||||
// base32 alphabet. It is what `bd show --as-of` takes, and a prefix is not.
|
||||
var doltCommitHashPattern = regexp.MustCompile(`^[0-9a-v]{32}$`)
|
||||
|
||||
// issueVersionOnlyKeys are fields of a recorded version (`bd versions --json`,
|
||||
// storage.IssueVersion) that neither the Dolt-commit history nor the Dolt AS OF
|
||||
// read has.
|
||||
var issueVersionOnlyKeys = []string{"local_revision", "epoch", "change_actor", "change_at", "attribution_status", "removed_restriction", "state_bytes"}
|
||||
|
||||
// TestEmbeddedHistoryAndShowAsOfReadDoltCommits pins what `bd history <id>` and
|
||||
// `bd show <id> --as-of <ref>` read in an ordinary workspace whose store records
|
||||
// versioned history, so both planes hold the same issue:
|
||||
// - `bd history <id> --json` is the Dolt-commit history: an array, newest first,
|
||||
// of {CommitHash, Committer, CommitDate, Issue} entries, each CommitHash a full
|
||||
// Dolt commit hash and each Issue the row as that commit left it. No field of a
|
||||
// recorded version appears, and the text output names the same full hashes.
|
||||
// - `bd show <id> --as-of <hash>`, with a hash from `bd history`, is the Dolt AS OF
|
||||
// read: the issue as that commit left it, in show's JSON shape (an array of
|
||||
// issues), not a recorded version. A branch name is a ref too: --as-of main
|
||||
// reads the branch head.
|
||||
//
|
||||
// Recorded versions are a separate plane with its own command (`bd versions`) and
|
||||
// its own as-of read (R7.1, over issue_versions), which takes an instant or a
|
||||
// version address and not a Dolt ref. Recording them must change neither answer.
|
||||
func TestEmbeddedHistoryAndShowAsOfReadDoltCommits(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, _, _ := bdInit(t, bd, "--prefix", "hd")
|
||||
bdConfig(t, bd, dir, "set", "versioned-history.enabled", "true")
|
||||
|
||||
id := bdCreateSilent(t, bd, dir, "Before title", "--type", "task")
|
||||
bdUpdate(t, bd, dir, id, "--title", "After title")
|
||||
|
||||
// Both planes hold this issue: versions were recorded for it.
|
||||
var recorded struct {
|
||||
Recording bool `json:"recording"`
|
||||
Versions []json.RawMessage `json:"versions"`
|
||||
}
|
||||
if out, stderr, exit := bdRunStreams(t, bd, dir, "versions", id, "--json"); exit != 0 || json.Unmarshal([]byte(out), &recorded) != nil || !recorded.Recording || len(recorded.Versions) == 0 {
|
||||
t.Fatalf("bd versions %s --json (exit %d) did not report recorded versions, so this test would not tell the planes apart\nstdout:\n%s\nstderr:\n%s", id, exit, out, stderr)
|
||||
}
|
||||
|
||||
historyJSON := bdHistory(t, bd, dir, id, "--json")
|
||||
var entries []map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(historyJSON), &entries); err != nil {
|
||||
t.Fatalf("bd history %s --json is not a JSON array: %v\n%s", id, err, historyJSON)
|
||||
}
|
||||
if len(entries) < 2 {
|
||||
t.Fatalf("bd history %s --json has %d entries, want one for each of the create and the update:\n%s", id, len(entries), historyJSON)
|
||||
}
|
||||
type snapshot struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
hashes := make([]string, len(entries))
|
||||
titles := make([]string, len(entries))
|
||||
for i, entry := range entries {
|
||||
keys := make([]string, 0, len(entry))
|
||||
for key := range entry {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
if got := strings.Join(keys, ","); got != "CommitDate,CommitHash,Committer,Issue" {
|
||||
t.Errorf("bd history entry %d has keys %s, want the Dolt-commit entry CommitDate,CommitHash,Committer,Issue", i, got)
|
||||
}
|
||||
if err := json.Unmarshal(entry["CommitHash"], &hashes[i]); err != nil || !doltCommitHashPattern.MatchString(hashes[i]) {
|
||||
t.Errorf("bd history entry %d CommitHash %s is not a full Dolt commit hash", i, entry["CommitHash"])
|
||||
}
|
||||
var issue snapshot
|
||||
if err := json.Unmarshal(entry["Issue"], &issue); err != nil || issue.ID != id {
|
||||
t.Errorf("bd history entry %d Issue %s is not a snapshot of %s", i, entry["Issue"], id)
|
||||
}
|
||||
titles[i] = issue.Title
|
||||
}
|
||||
if titles[0] != "After title" || titles[len(titles)-1] != "Before title" {
|
||||
t.Fatalf("bd history %s titles newest first are %q, want %q first and %q last", id, titles, "After title", "Before title")
|
||||
}
|
||||
for _, key := range issueVersionOnlyKeys {
|
||||
if strings.Contains(historyJSON, `"`+key+`"`) {
|
||||
t.Errorf("bd history %s --json carries %q, a field of a recorded version:\n%s", id, key, historyJSON)
|
||||
}
|
||||
}
|
||||
text := bdHistory(t, bd, dir, id)
|
||||
for _, hash := range hashes {
|
||||
if !strings.Contains(text, hash) {
|
||||
t.Errorf("bd history %s text output does not name the full commit hash %s:\n%s", id, hash, text)
|
||||
}
|
||||
}
|
||||
|
||||
// show --as-of reads the Dolt commit the history named.
|
||||
first := hashes[len(hashes)-1]
|
||||
asOfJSON := func(ref string) snapshot {
|
||||
t.Helper()
|
||||
out, stderr, exit := bdRunStreams(t, bd, dir, "show", id, "--as-of", ref, "--json")
|
||||
var shown []map[string]json.RawMessage
|
||||
if exit != 0 || json.Unmarshal([]byte(out), &shown) != nil || len(shown) != 1 {
|
||||
t.Fatalf("bd show %s --as-of %s --json exited %d, want an array of one issue\nstdout:\n%s\nstderr:\n%s", id, ref, exit, out, stderr)
|
||||
}
|
||||
for _, key := range issueVersionOnlyKeys {
|
||||
if _, ok := shown[0][key]; ok {
|
||||
t.Errorf("bd show %s --as-of %s --json carries %q, a field of a recorded version:\n%s", id, ref, key, out)
|
||||
}
|
||||
}
|
||||
var issues []snapshot
|
||||
if err := json.Unmarshal([]byte(out), &issues); err != nil {
|
||||
t.Fatalf("bd show %s --as-of %s --json: %v\n%s", id, ref, err, out)
|
||||
}
|
||||
return issues[0]
|
||||
}
|
||||
if got := asOfJSON(first); got.ID != id || got.Title != "Before title" {
|
||||
t.Errorf("bd show %s --as-of %s (its first commit) read %+v, want the issue titled %q", id, first, got, "Before title")
|
||||
}
|
||||
if got := asOfJSON("main"); got.ID != id || got.Title != "After title" {
|
||||
t.Errorf("bd show %s --as-of main read %+v, want the branch head's title %q", id, got, "After title")
|
||||
}
|
||||
human := bdShowRaw(t, bd, dir, id, "--as-of", first)
|
||||
if !strings.Contains(human, "as of "+first) || !strings.Contains(human, "Before title") || strings.Contains(human, "After title") {
|
||||
t.Errorf("bd show %s --as-of %s text output does not show the first commit's issue under that ref:\n%s", id, first, human)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace is
|
||||
// TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace is
|
||||
// the MINOR-criterion regression test for be-0gfcs round 2 (be-3bt2e): a
|
||||
// brand-new workspace -- metadata.json present, but no embedded database on
|
||||
// disk yet -- is the one previewErr case the identity check has always
|
||||
|
|
@ -32,7 +32,7 @@ import (
|
|||
// This exercises a real embedded-Dolt bootstrap (schema init on first open),
|
||||
// so it is opt-in like the other embedded-dolt integration tests in this
|
||||
// package: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
|
||||
func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *testing.T) {
|
||||
func TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(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")
|
||||
}
|
||||
|
|
@ -120,7 +120,7 @@ func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *t
|
|||
}
|
||||
}
|
||||
|
||||
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace pins the
|
||||
// TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace pins the
|
||||
// preview→skew WIRE, which TestRefuseUnverifiablePreviewOpenRendersTypedErrors
|
||||
// deliberately does not: that test hands refuseUnverifiablePreviewOpen a
|
||||
// hand-built *schema.SchemaSkewError, so it pins the renderer in isolation.
|
||||
|
|
@ -136,7 +136,7 @@ func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *t
|
|||
//
|
||||
// This bootstraps a real embedded-Dolt database, so it is opt-in on the same
|
||||
// tier as the sibling above: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
|
||||
func TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace(t *testing.T) {
|
||||
func TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,10 +55,10 @@ func bdShowRevision(t *testing.T, bd, dir, id string) int64 {
|
|||
|
||||
func revStr(rev int64) string { return strconv.FormatInt(rev, 10) }
|
||||
|
||||
// TestIfRevisionAdvertisedOnFourVerbs pins T4.1: --if-revision is a real,
|
||||
// TestEmbeddedIfRevisionAdvertisedOnFourVerbs pins T4.1: --if-revision is a real,
|
||||
// documented flag on all four verbs A8 adds it to, not an undocumented side
|
||||
// channel a caller has to discover by reading source.
|
||||
func TestIfRevisionAdvertisedOnFourVerbs(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionAdvertisedOnFourVerbs(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")
|
||||
}
|
||||
|
|
@ -77,11 +77,11 @@ func TestIfRevisionAdvertisedOnFourVerbs(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestIfRevisionMatchAndMismatch pins T4.2 across all four verbs: a stale
|
||||
// TestEmbeddedIfRevisionMatchAndMismatch pins T4.2 across all four verbs: a stale
|
||||
// --if-revision token exits ExitGuardMismatch (13) and writes nothing at all
|
||||
// (not the field, not the revision itself); the same token, once it is the
|
||||
// issue's CURRENT revision, applies the write and the revision moves again.
|
||||
func TestIfRevisionMatchAndMismatch(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionMatchAndMismatch(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")
|
||||
}
|
||||
|
|
@ -196,7 +196,7 @@ func TestIfRevisionMatchAndMismatch(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestIfRevisionDeletePreflightGoneIsPreconditionFailed pins mc-zndi7.81: `bd
|
||||
// TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed pins mc-zndi7.81: `bd
|
||||
// delete`'s single-id path resolves the row with resolveAndGetIssueForMutation
|
||||
// BEFORE calling deleter.Delete() and the per-id lock fence #7244 added. On a
|
||||
// real Dolt sql-server, a same-token --if-revision racer that loses that fence
|
||||
|
|
@ -211,7 +211,7 @@ func TestIfRevisionMatchAndMismatch(t *testing.T) {
|
|||
// winning racer's delete would), then present that now-stale token. The
|
||||
// pre-flight existence check must fail exactly the same way a mid-guard
|
||||
// version mismatch does.
|
||||
func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed(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")
|
||||
}
|
||||
|
|
@ -392,7 +392,7 @@ func TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb(t *testi
|
|||
})
|
||||
}
|
||||
|
||||
// TestIfRevisionCascadeDelete pins mc-zndi7.76 (gap 4): a single named id with
|
||||
// TestEmbeddedIfRevisionCascadeDelete pins mc-zndi7.76 (gap 4): a single named id with
|
||||
// --cascade takes the SAME deleteBatch path a multi-id delete does
|
||||
// (cmd/bd/delete.go:105, "len(issueIDs) > 1 || cascade"), which is the only
|
||||
// way a single-id --if-revision request ever reaches deleteBatch's own
|
||||
|
|
@ -405,7 +405,7 @@ func TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb(t *testi
|
|||
// concurrent delete removed before deleteBatch resolves it is
|
||||
// TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb's
|
||||
// delete_cascade row.
|
||||
func TestIfRevisionCascadeDelete(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionCascadeDelete(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")
|
||||
}
|
||||
|
|
@ -459,11 +459,11 @@ func TestIfRevisionCascadeDelete(t *testing.T) {
|
|||
bdShowFail(t, bd, dir, child.ID)
|
||||
}
|
||||
|
||||
// TestIfRevisionComposesWithIfAssigneeIfStatus pins T4.5: on `bd update`,
|
||||
// TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus pins T4.5: on `bd update`,
|
||||
// --if-revision composes with --if-assignee/--if-status as a conjunction —
|
||||
// every guard present must hold, not just one of them, regardless of which
|
||||
// guard happens to be the stale one.
|
||||
func TestIfRevisionComposesWithIfAssigneeIfStatus(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus(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")
|
||||
}
|
||||
|
|
@ -516,13 +516,13 @@ func TestIfRevisionComposesWithIfAssigneeIfStatus(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestIfRevisionRejectsLabelAndParentEdits pins T4.6: `bd update --if-revision`
|
||||
// TestEmbeddedIfRevisionRejectsLabelAndParentEdits pins T4.6: `bd update --if-revision`
|
||||
// (alone or composed with --if-assignee/--if-status) refuses when the ONLY
|
||||
// edit riding with it is a label or parent change, because those edits do not
|
||||
// run inside the guarded issues-row write. Refused before any write, exit 1
|
||||
// (a flag-validation refusal, never 13 — 13 is reserved for an actual stale
|
||||
// guard).
|
||||
func TestIfRevisionRejectsLabelAndParentEdits(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionRejectsLabelAndParentEdits(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")
|
||||
}
|
||||
|
|
@ -562,12 +562,12 @@ func TestIfRevisionRejectsLabelAndParentEdits(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestIfRevisionMultiIDRejected pins T4.8 on the three verbs that accept more
|
||||
// TestEmbeddedIfRevisionMultiIDRejected pins T4.8 on the three verbs that accept more
|
||||
// than one id (assign is cobra.ExactArgs(2): id + assignee, so it can never
|
||||
// carry a second id). A single --if-revision token names one row's version;
|
||||
// refused before any write rather than applying it to only the first id a
|
||||
// batch happens to resolve.
|
||||
func TestIfRevisionMultiIDRejected(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionMultiIDRejected(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")
|
||||
}
|
||||
|
|
@ -633,14 +633,14 @@ func TestIfRevisionMultiIDRejected(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestRevisionRemintMatrix pins T4.10: the revision is a token over the
|
||||
// TestEmbeddedRevisionRemintMatrix pins T4.10: the revision is a token over the
|
||||
// issues-row write, not over "anything happened to this id". A field update,
|
||||
// a metadata edit, a close and a reopen must each mint a fresh revision (so a
|
||||
// caller who read one of those as "no-op" cannot keep replaying a now-stale
|
||||
// --if-revision); a label edit, a dependency edit and the derived is_blocked
|
||||
// flag must NOT, because none of those touch the issues-row write the token
|
||||
// guards.
|
||||
func TestRevisionRemintMatrix(t *testing.T) {
|
||||
func TestEmbeddedRevisionRemintMatrix(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,9 +112,9 @@ func gcClassifyAsPrecondition(out []byte, errText string) (ok bool, expected, cu
|
|||
// cover, pinning the 2026-10 Opus-review BLOCKER fix end-to-end: gc's own
|
||||
// classifier logic, not just bd's JSON shape in isolation, must recognize the
|
||||
// refusal as a precondition with the caller's expected revision and bd's
|
||||
// current one. The TestEmbedded name in an *_embedded_test.go file is what
|
||||
// puts it in a CI lane: .github/scripts/embedded-test-shard.sh discovers
|
||||
// tests by exactly that pair, and under any other name it skips everywhere.
|
||||
// current one. The TestEmbedded name is what puts it in a CI lane:
|
||||
// .github/scripts/embedded-test-shard.sh discovers tests by that prefix, and
|
||||
// under any other name it skips everywhere.
|
||||
func TestEmbeddedGCConditionalMatcherDecode(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")
|
||||
|
|
|
|||
168
cmd/bd/if_revision_ordinary_cas_embedded_test.go
Normal file
168
cmd/bd/if_revision_ordinary_cas_embedded_test.go
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// ifRevisionStaleExit is a literal on purpose: the contract with gascity's
|
||||
// bdstore_conditional.go classifier is the number 13, not whatever name the
|
||||
// constant for it (ExitGuardMismatch) happens to have.
|
||||
const ifRevisionStaleExit = 13
|
||||
|
||||
// decodeIfRevisionBodyExact decodes the flat machine body a refused
|
||||
// --if-revision write puts on the last line of stderr, keeping numbers as
|
||||
// json.Number. Revisions are int64 values well past 2^53, so comparing them
|
||||
// as float64 would accept a neighbouring revision; a json.Number also proves
|
||||
// the field is a JSON number and not a string.
|
||||
func decodeIfRevisionBodyExact(t *testing.T, line string) map[string]any {
|
||||
t.Helper()
|
||||
dec := json.NewDecoder(strings.NewReader(line))
|
||||
dec.UseNumber()
|
||||
var body map[string]any
|
||||
if err := dec.Decode(&body); err != nil {
|
||||
t.Fatalf("decode the --if-revision refusal body: %v\nline: %s", err, line)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// TestEmbeddedIfRevisionOrdinaryCAS pins the ordinary --if-revision
|
||||
// compare-and-swap (#7203) end to end, as a gascity-style caller sees it:
|
||||
//
|
||||
// - a stale decimal token on update, close, assign and delete (preview and
|
||||
// --force) exits 13 with a precondition_failed body on the last line of
|
||||
// stderr naming the id and both revisions as JSON integers, prints
|
||||
// nothing on stdout and writes nothing;
|
||||
// - a token that is not a decimal exits 1 with the "invalid --if-revision"
|
||||
// refusal, never 13, and writes nothing;
|
||||
// - the current token applies on update, close, assign and delete, and
|
||||
// each write that leaves the issue in place moves its revision on.
|
||||
//
|
||||
// A second meaning for the same flag (an opaque token in some other kind of
|
||||
// workspace) must leave all of this unchanged in an ordinary one. This is
|
||||
// the ordinary-workspace half of the fork's
|
||||
// TestGraphPreviewIfRevisionOutsideLinkModeIsUpstreamCAS, ported onto this
|
||||
// package's embedded helpers and extended from update/delete to close and
|
||||
// assign.
|
||||
func TestEmbeddedIfRevisionOrdinaryCAS(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, _, _ := bdInit(t, bd, "--prefix", "ifrev")
|
||||
|
||||
id := bdCreateSilent(t, bd, dir, "Stale guard", "--type", "task", "--priority", "2")
|
||||
stale := bdShowRevision(t, bd, dir, id)
|
||||
bdRunOK(t, bd, dir, "update", id, "--notes", "bump", "--json")
|
||||
current := bdShowRevision(t, bd, dir, id)
|
||||
if current == stale {
|
||||
t.Fatal("an unguarded update did not advance the revision")
|
||||
}
|
||||
staleToken := strconv.FormatInt(stale, 10)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"update", []string{"update", id, "--priority", "3"}},
|
||||
{"close", []string{"close", id}},
|
||||
{"assign", []string{"assign", id, "worker"}},
|
||||
{"delete preview", []string{"delete", id}},
|
||||
{"delete force", []string{"delete", id, "--force"}},
|
||||
} {
|
||||
args := slices.Concat(tc.args, []string{"--if-revision", staleToken, "--json"})
|
||||
stdout, stderr, exit := bdRunStreams(t, bd, dir, args...)
|
||||
if exit != ifRevisionStaleExit {
|
||||
t.Fatalf("stale --if-revision %s exited %d, want %d\nstdout:\n%s\nstderr:\n%s", tc.name, exit, ifRevisionStaleExit, stdout, stderr)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Errorf("stale --if-revision %s printed on stdout, want nothing:\n%s", tc.name, stdout)
|
||||
}
|
||||
body := decodeIfRevisionBodyExact(t, lastJSONLine(t, stderr))
|
||||
if body["code"] != ifRevisionCodePreconditionFailed || body["id"] != id {
|
||||
t.Errorf("stale --if-revision %s reported %v, want code %q for %s", tc.name, body, ifRevisionCodePreconditionFailed, id)
|
||||
}
|
||||
if got := body["expected_revision"]; got != json.Number(staleToken) {
|
||||
t.Errorf("stale --if-revision %s reported expected_revision %#v, want the JSON integer %s", tc.name, got, staleToken)
|
||||
}
|
||||
if got := body["current_revision"]; got != json.Number(strconv.FormatInt(current, 10)) {
|
||||
t.Errorf("stale --if-revision %s reported current_revision %#v, want the JSON integer %d", tc.name, got, current)
|
||||
}
|
||||
if msg, _ := body["error"].(string); !strings.Contains(msg, "precondition failed") {
|
||||
t.Errorf("stale --if-revision %s error text %q lacks \"precondition failed\"", tc.name, msg)
|
||||
}
|
||||
if got := bdShowRevision(t, bd, dir, id); got != current {
|
||||
t.Fatalf("stale --if-revision %s wrote: revision %d -> %d", tc.name, current, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A token that is not a decimal is a typo refused before any write, with
|
||||
// exit 1 and not the guard's 13, in both output modes.
|
||||
for _, base := range [][]string{
|
||||
{"update", id, "--priority", "3"},
|
||||
{"close", id},
|
||||
{"assign", id, "worker"},
|
||||
{"delete", id},
|
||||
{"delete", id, "--force"},
|
||||
} {
|
||||
for _, mode := range [][]string{nil, {"--json"}} {
|
||||
args := slices.Concat(base, []string{"--if-revision", "observed"}, mode)
|
||||
stdout, stderr, exit := bdRunStreams(t, bd, dir, args...)
|
||||
out := stdout + stderr
|
||||
// The text refusal quotes the token; the --json one carries the
|
||||
// same text JSON-escaped.
|
||||
refused := strings.Contains(out, `invalid --if-revision "observed"`) ||
|
||||
strings.Contains(out, `invalid --if-revision \"observed\"`)
|
||||
if exit != 1 || !refused {
|
||||
t.Errorf("bd %s exited %d, want exit 1 refusing the non-decimal token\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, stdout, stderr)
|
||||
}
|
||||
if strings.Contains(out, ifRevisionCodePreconditionFailed) {
|
||||
t.Errorf("bd %s reported a stale revision for a token that is not one:\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got := bdShowRevision(t, bd, dir, id); got != current {
|
||||
t.Fatalf("a refused non-decimal token wrote: revision %d -> %d", current, got)
|
||||
}
|
||||
|
||||
// The current token applies, on each verb in turn.
|
||||
revision := current
|
||||
guarded := func(target string, args ...string) {
|
||||
t.Helper()
|
||||
bdRunOK(t, bd, dir, slices.Concat(args, []string{"--if-revision", strconv.FormatInt(revision, 10), "--json"})...)
|
||||
next := bdShowRevision(t, bd, dir, target)
|
||||
if next == revision {
|
||||
t.Fatalf("a matching --if-revision on bd %s did not advance the revision", strings.Join(args, " "))
|
||||
}
|
||||
revision = next
|
||||
}
|
||||
guarded(id, "update", id, "--priority", "3")
|
||||
if got := bdShow(t, bd, dir, id); got.Priority != 3 {
|
||||
t.Errorf("matching --if-revision update did not apply: priority = %d, want 3", got.Priority)
|
||||
}
|
||||
guarded(id, "close", id)
|
||||
if got := bdShow(t, bd, dir, id); got.Status != types.StatusClosed {
|
||||
t.Errorf("matching --if-revision close did not apply: status = %s, want closed", got.Status)
|
||||
}
|
||||
bdRunOK(t, bd, dir, "delete", id, "--force", "--if-revision", strconv.FormatInt(revision, 10), "--json")
|
||||
bdShowFail(t, bd, dir, id)
|
||||
|
||||
// assign gets an issue of its own: closing an issue assigned to someone
|
||||
// other than the actor is refused without --force, whatever the guard.
|
||||
other := bdCreateSilent(t, bd, dir, "Guarded assign", "--type", "task")
|
||||
revision = bdShowRevision(t, bd, dir, other)
|
||||
guarded(other, "assign", other, "worker")
|
||||
if got := bdShow(t, bd, dir, other); got.Assignee != "worker" {
|
||||
t.Errorf("matching --if-revision assign did not apply: assignee = %q, want worker", got.Assignee)
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"testing"
|
||||
)
|
||||
|
||||
// TestIfRevisionOutranksReassignFenceCLI pins mc-zndi7.74 on the direct
|
||||
// TestEmbeddedIfRevisionOutranksReassignFenceCLI pins mc-zndi7.74 on the direct
|
||||
// (embedded) route: a stale --if-revision guard on an assignee edit must
|
||||
// report precondition_failed/ExitGuardMismatch, never fall through to the
|
||||
// bd-98s5c live-claim reassign fence's "already claimed" policy refusal --
|
||||
|
|
@ -22,7 +22,7 @@ import (
|
|||
// the now-live foreign claim and reports the plain policy refusal (exit 1)
|
||||
// before the guarded write underneath ever gets a chance to report the
|
||||
// correctly-ordered precondition failure (exit 13).
|
||||
func TestIfRevisionOutranksReassignFenceCLI(t *testing.T) {
|
||||
func TestEmbeddedIfRevisionOutranksReassignFenceCLI(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ func proxiedRevStr(rev int64) string { return strconv.FormatInt(rev, 10) }
|
|||
// TestProxiedServerIfRevisionOutranksReassignFence pins mc-zndi7.74 on the
|
||||
// proxied-server route, the topology where this race actually happens: every
|
||||
// shared-dolt-server clone writes through it. See
|
||||
// TestIfRevisionOutranksReassignFenceCLI's doc for the full race shape —
|
||||
// TestEmbeddedIfRevisionOutranksReassignFenceCLI's doc for the full race shape —
|
||||
// this is the same scenario, proved against the real shared Dolt server
|
||||
// instead of embedded Dolt.
|
||||
func TestProxiedServerIfRevisionOutranksReassignFence(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -147,14 +147,20 @@ func bulkLoadPoolReadTimeout(cmd *cobra.Command) time.Duration {
|
|||
}
|
||||
|
||||
func runImport(cmd *cobra.Command, args []string) error {
|
||||
// Explicit call, not inherited from CheckReadonly: runImport doesn't call
|
||||
// CheckReadonly at all (a separate, pre-existing gap — readonlyMode
|
||||
// doesn't gate bd import either), so it can't pick up the freeze check
|
||||
// folded into CheckReadonly the way create/update/close/remember do.
|
||||
// The path that makes this call load-bearing rather than redundant is
|
||||
// `bd import --dry-run`: a preview sets useReadOnly, so it skips the early
|
||||
// gate in PersistentPreRunE, and runImport is the only chokepoint left.
|
||||
// Plain `bd import` is already stopped by that early gate.
|
||||
// Strict --readonly refuses import, a --dry-run preview included (it
|
||||
// refuses create --dry-run too). Guarded, unlike the write commands'
|
||||
// unconditional call, because CheckReadonly also answers a migration freeze
|
||||
// and does it by exiting the process. The freeze is answered below instead,
|
||||
// by returning the error, so that cleanup still runs.
|
||||
if readonlyMode {
|
||||
CheckReadonly("import")
|
||||
}
|
||||
|
||||
// The freeze check, not inherited from CheckReadonly for the reason above.
|
||||
// It is load-bearing rather than redundant on `bd import --dry-run`: a
|
||||
// preview sets useReadOnly, so it skips the early gate in
|
||||
// PersistentPreRunE, and runImport is the only chokepoint left. Plain
|
||||
// `bd import` is already stopped by that early gate.
|
||||
if err := migrationFreezeGateFor(cmd, "import"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ func provisionChunkStore(t *testing.T) storage.DoltStorage {
|
|||
// End-to-end against the real engine: a mid-import failure leaves a committed,
|
||||
// queryable prefix, and re-running the same import converges — every row
|
||||
// present, cross-chunk dependencies wired, no duplicated events.
|
||||
func TestImportChunkedRealStoreResumeConverges(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedRealStoreResumeConverges(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -179,7 +179,7 @@ func TestImportChunkedRealStoreResumeConverges(t *testing.T) {
|
|||
// edges its import file declares must be visible too. This is the red-team
|
||||
// ready-window finding: the previous two-phase layout committed every row
|
||||
// dep-less first, so `bd ready` mid-import offered blocked work for dispatch.
|
||||
func TestImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -251,7 +251,7 @@ func TestImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
|
|||
// but the no-ready-window invariant must hold there too — otherwise the
|
||||
// dependent commits ready-without-blocker for the rest of the import. Regression
|
||||
// for the attempt-1 review finding.
|
||||
func TestImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -339,7 +339,7 @@ func TestImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
|
|||
// Ordering the spawner inline with the waiter is not enough; every in-batch
|
||||
// child of a waited spawner must be emitted no later than the waiter. Regression
|
||||
// for the attempt-2 review blocker.
|
||||
func TestImportChunkedWaitsForChildImportedLaterStaysBlocked(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedWaitsForChildImportedLaterStaysBlocked(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -421,7 +421,7 @@ func (r *raceInjectingStore) CreateIssuesWithFullOptions(ctx context.Context, is
|
|||
// the row away). The dependency pass must wire edges for every row phase 1
|
||||
// accepted, regardless of later row-level updates, and must not clobber the
|
||||
// concurrent write.
|
||||
func TestImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -483,7 +483,7 @@ func TestImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
|
|||
// update racing the import must leave the blocking edge intact. With ordered
|
||||
// inline wiring the row and its edge commit atomically, so no interleaving of
|
||||
// row-level updates can separate them.
|
||||
func TestImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -532,7 +532,7 @@ func TestImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
|
|||
// the pre-filter read and the row's chunk), the snapshot's deferred deps must
|
||||
// stay out too. This is why the dependency pass cannot simply run everything
|
||||
// with ConflictSkip: it must be restricted to rows phase 1 accepted.
|
||||
func TestImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -593,7 +593,7 @@ func TestImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
|
|||
// straddling a chunk boundary must be wired, not skip-reported, and a
|
||||
// same-bucket wisp -> wisp edge straddling the same boundary must survive as
|
||||
// before. Every export→import used to lose such edges for good.
|
||||
func TestImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 5)
|
||||
recordImportPauses(t)
|
||||
|
|
@ -696,7 +696,7 @@ func TestImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
|
|||
// durable and the deferred one is not yet; re-running the same import must
|
||||
// backfill it with nothing skip-reported, and a further run must be a no-op
|
||||
// for the edges.
|
||||
func TestImportChunkedCrossBucketBlocksEdgesResumeBackfills(t *testing.T) {
|
||||
func TestEmbeddedImportChunkedCrossBucketBlocksEdgesResumeBackfills(t *testing.T) {
|
||||
requireEmbeddedDolt(t)
|
||||
setImportChunkSize(t, 4)
|
||||
recordImportPauses(t)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
|
|
@ -226,6 +227,40 @@ func shouldInitSharedGlobalDB(sharedServer, sharedServerMode, gateway bool) bool
|
|||
return (sharedServer || sharedServerMode) && !gateway
|
||||
}
|
||||
|
||||
// externalServerUnreachableMessage returns the message for an --external init
|
||||
// whose server could not be dialed, or "" when err is any other failure.
|
||||
//
|
||||
// --external declares the server managed outside bd, so init starts none. The
|
||||
// store's own advice for a dead local server, "bd dolt start", would start the
|
||||
// very server --external says bd must not, and the store words this failure
|
||||
// differently per route (shared server, socket, remote host, auto-start pinned
|
||||
// off). One message serves them all: it names the endpoint that was dialed and
|
||||
// says that bd did not start a server.
|
||||
//
|
||||
// A dial to port 0 is the exception. The store leaves a zero port zero for
|
||||
// auto-start to fill in, so it means nothing named a port: the address is a
|
||||
// placeholder, not an endpoint. The message says so and how to name one, and
|
||||
// offers no default, since on a shared machine whatever listens on a default
|
||||
// port may belong to another project (GH#2098, GH#2372).
|
||||
func externalServerUnreachableMessage(err error) string {
|
||||
var opErr *net.OpError
|
||||
if !errors.As(err, &opErr) || opErr.Op != "dial" {
|
||||
return ""
|
||||
}
|
||||
if addr, ok := opErr.Addr.(*net.TCPAddr); ok && addr.Port == 0 {
|
||||
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
|
||||
"--external declares the Dolt server externally managed, so bd did not start one, and no port was named for it.\n"+
|
||||
"Name the server's port with --server-port or BEADS_DOLT_SERVER_PORT.\n", opErr)
|
||||
}
|
||||
endpoint := "the configured endpoint"
|
||||
if opErr.Addr != nil {
|
||||
endpoint = opErr.Addr.String()
|
||||
}
|
||||
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
|
||||
"--external declares the Dolt server at %s externally managed, so bd did not start one.\n"+
|
||||
"Start that server, or point init at the right endpoint.\n", opErr, endpoint)
|
||||
}
|
||||
|
||||
// warnHalfIdentifiedSubstrate reports a substrate carrying one identity marker
|
||||
// and not the other.
|
||||
//
|
||||
|
|
@ -820,7 +855,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
if initProxiedServer {
|
||||
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
|
||||
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
||||
return err
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
}
|
||||
if err := runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{
|
||||
|
|
@ -970,8 +1005,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// before init's existing-workspace checks so even --force cannot create
|
||||
// or rewrite state beside a source that has not been preserved.
|
||||
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
|
||||
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
||||
return err
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, initServerMode); err != nil {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1554,7 +1589,9 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
}
|
||||
|
||||
// Build config. Beads always uses dolt sql-server.
|
||||
// AutoStart is always enabled during init — we need a server to initialize the database.
|
||||
// AutoStart is enabled during init — we need a server to initialize the database —
|
||||
// except under --external: that server is managed outside bd, so bd must not start
|
||||
// one of its own on the endpoint the caller named.
|
||||
//
|
||||
// Port resolution for init: use ONLY project-local sources (env var, port file)
|
||||
// to prevent cross-project data leakage (GH#2336). DefaultConfig falls through
|
||||
|
|
@ -1602,7 +1639,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
ProxiedServer: initProxiedServer,
|
||||
CreateIfMissing: true, // bd init is the only path that should create databases
|
||||
OpenedByInit: true, // shapes the identity-mismatch advice (GH#5558)
|
||||
AutoStart: initServerMode && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
|
||||
AutoStart: initServerMode && !externalServer && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
|
||||
ServerTLS: initDoltServerTLSFromEnv(),
|
||||
}
|
||||
if serverHost != "" {
|
||||
|
|
@ -1727,6 +1764,12 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
}
|
||||
return &exitError{Code: 1}
|
||||
}
|
||||
if externalServer {
|
||||
if msg := externalServerUnreachableMessage(err); msg != "" {
|
||||
fmt.Fprint(os.Stderr, msg)
|
||||
return &exitError{Code: 1}
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Error: failed to open Dolt store: %v\n", err)
|
||||
return &exitError{Code: 1}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,11 +49,11 @@ func updateAgentFile(filename string, verbose bool, templatePath string, profile
|
|||
}
|
||||
newContent = string(data)
|
||||
} else {
|
||||
newContent = agents.EmbeddedDefault()
|
||||
newContent = agents.EmbeddedDefaultWithOpts(opts)
|
||||
}
|
||||
|
||||
// Replace the beads section with the requested profile.
|
||||
// EmbeddedDefault() ships with profile:full; swap to the requested profile
|
||||
// The embedded template ships with profile:full; swap to the requested profile
|
||||
// (which defaults to minimal). Also handles legacy markers without profile metadata.
|
||||
if strings.Contains(newContent, "BEGIN BEADS INTEGRATION") {
|
||||
if replaced, changed, err := agents.ReplaceSectionWithOpts(newContent, profile, opts); err == nil && changed {
|
||||
|
|
|
|||
79
cmd/bd/init_agent_test.go
Normal file
79
cmd/bd/init_agent_test.go
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/templates/agents"
|
||||
)
|
||||
|
||||
// TestUpdateAgentFileQuickReferenceFollowsRemote pins that a new AGENTS.md
|
||||
// written by `bd init` lists `bd dolt push` in its Quick Reference exactly
|
||||
// when its managed section does: only with a Dolt remote configured and the
|
||||
// workspace not declared no-push. A custom --agents-template is the user's
|
||||
// own text and is written as given.
|
||||
func TestUpdateAgentFileQuickReferenceFollowsRemote(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
opts agents.RenderOpts
|
||||
wantPush bool
|
||||
}{
|
||||
{name: "remote", opts: agents.RenderOpts{HasRemote: true}, wantPush: true},
|
||||
{name: "no-remote", opts: agents.RenderOpts{}, wantPush: false},
|
||||
{name: "no-push", opts: agents.RenderOpts{HasRemote: true, NoPush: true}, wantPush: false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "AGENTS.md")
|
||||
if err := updateAgentFile(path, false, "", agents.ProfileMinimal, tc.opts); err != nil {
|
||||
t.Fatalf("updateAgentFile: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
content := string(data)
|
||||
begin := strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
|
||||
if begin < 0 {
|
||||
t.Fatalf("AGENTS.md has no managed section:\n%s", content)
|
||||
}
|
||||
if got := listsDoltPush(content[:begin]); got != tc.wantPush {
|
||||
t.Errorf("Quick Reference lists `bd dolt push` = %v, want %v", got, tc.wantPush)
|
||||
}
|
||||
if got := listsDoltPush(content[begin:]); got != tc.wantPush {
|
||||
t.Errorf("managed section lists `bd dolt push` = %v, want %v", got, tc.wantPush)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("custom-template", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
template := "# Ours\n\n```bash\nbd dolt push # our own reminder\n```\n"
|
||||
templatePath := filepath.Join(dir, "template.md")
|
||||
if err := os.WriteFile(templatePath, []byte(template), 0o644); err != nil {
|
||||
t.Fatalf("write template: %v", err)
|
||||
}
|
||||
path := filepath.Join(dir, "AGENTS.md")
|
||||
if err := updateAgentFile(path, false, templatePath, agents.ProfileMinimal, agents.RenderOpts{}); err != nil {
|
||||
t.Fatalf("updateAgentFile: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
if string(data) != template {
|
||||
t.Errorf("custom template was not written as given:\n got: %q\nwant: %q", data, template)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// listsDoltPush reports whether any line of s is a `bd dolt push` command.
|
||||
func listsDoltPush(s string) bool {
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), "bd dolt push") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
@ -482,6 +482,39 @@ func TestEmbeddedInitABasic(t *testing.T) {
|
|||
t.Errorf("issue_prefix: got %q, want %q", val, "alpha")
|
||||
}
|
||||
})
|
||||
|
||||
// The project's .claude/settings.json still carries the bare `bd prime`
|
||||
// SessionStart and PreCompact hooks an older bd registered. init's Claude
|
||||
// install migrates them, and --quiet drops the migration's "Removed
|
||||
// <event> hook" lines like the rest of the installers' progress.
|
||||
t.Run("quiet_legacy_claude_hooks", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
initGitRepoAt(t, dir)
|
||||
settingsPath := filepath.Join(dir, ".claude", "settings.json")
|
||||
if err := os.MkdirAll(filepath.Dir(settingsPath), 0o755); err != nil {
|
||||
t.Fatalf("mkdir .claude: %v", err)
|
||||
}
|
||||
legacyHook := `[{"matcher": "", "hooks": [{"type": "command", "command": "bd prime"}]}]`
|
||||
legacy := `{"hooks": {"SessionStart": ` + legacyHook + `, "PreCompact": ` + legacyHook + `}}`
|
||||
if err := os.WriteFile(settingsPath, []byte(legacy), 0o644); err != nil {
|
||||
t.Fatalf("seed settings.json: %v", err)
|
||||
}
|
||||
args := []string{"--prefix", "legacyhooks"}
|
||||
if database, seeded := seededInitDatabase(args); seeded {
|
||||
seedEmbeddedSchema(t, dir, database)
|
||||
}
|
||||
|
||||
if out := runBDInit(t, bd, dir, args...); out != "" {
|
||||
t.Errorf("bd init --quiet should print nothing, got:\n%s", out)
|
||||
}
|
||||
data, err := os.ReadFile(settingsPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read settings.json: %v", err)
|
||||
}
|
||||
if got := string(data); !strings.Contains(got, `"bd prime --hook-json"`) || strings.Contains(got, `"bd prime"`) || strings.Contains(got, "PreCompact") {
|
||||
t.Errorf("legacy hooks not migrated to the SessionStart --hook-json hook:\n%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmbeddedInitAForkAutoContributor(t *testing.T) {
|
||||
|
|
|
|||
430
cmd/bd/init_external_autostart_test.go
Normal file
430
cmd/bd/init_external_autostart_test.go
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
)
|
||||
|
||||
// `bd init --external` declares that the Dolt server is managed outside bd, so
|
||||
// init must never start one. These tests own one boundary risk that no lower
|
||||
// seam can show: init builds its dolt config by hand, so the flag reaches the
|
||||
// auto-start decision only if init carries it there. They run the real bd
|
||||
// binary against a dolt shim that records every launch, which makes the
|
||||
// outcome observable without a real server and leaves nothing running.
|
||||
|
||||
// externalInitFixture is one fresh project plus a dolt shim for `bd init`
|
||||
// attempts. The shim sits first on PATH, records every invocation and fails.
|
||||
type externalInitFixture struct {
|
||||
t *testing.T
|
||||
repoDir string
|
||||
home string
|
||||
shimDir string
|
||||
launches string
|
||||
}
|
||||
|
||||
type externalInitResult struct {
|
||||
output string // combined stdout and stderr
|
||||
failed bool // bd exited non-zero
|
||||
launches string // dolt invocations the shim saw, one per line
|
||||
}
|
||||
|
||||
func newExternalInitFixture(t *testing.T) *externalInitFixture {
|
||||
t.Helper()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the dolt shim is a POSIX shell script")
|
||||
}
|
||||
f := &externalInitFixture{t: t, repoDir: t.TempDir(), home: t.TempDir(), shimDir: t.TempDir()}
|
||||
f.launches = filepath.Join(f.shimDir, "invocations")
|
||||
shim := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$EXTERNAL_INIT_SHIM_LOG\"\nexit 1\n"
|
||||
if err := os.WriteFile(filepath.Join(f.shimDir, "dolt"), []byte(shim), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initGitRepo(t, f.repoDir)
|
||||
return f
|
||||
}
|
||||
|
||||
// run executes bd in the project. autoStart is the value of
|
||||
// BEADS_DOLT_AUTO_START, or "" to leave it unset: an unpinned environment is
|
||||
// what most callers run in, so it is the one that matters here.
|
||||
func (f *externalInitFixture) run(autoStart string, args ...string) externalInitResult {
|
||||
f.t.Helper()
|
||||
env := append(envWithoutBeadsStorageSettings(),
|
||||
"HOME="+f.home,
|
||||
"XDG_CONFIG_HOME="+filepath.Join(f.home, ".config"),
|
||||
"BEADS_TEST_IGNORE_REPO_CONFIG=1",
|
||||
"BD_DISABLE_METRICS=1",
|
||||
"PATH="+f.shimDir+string(os.PathListSeparator)+os.Getenv("PATH"),
|
||||
"EXTERNAL_INIT_SHIM_LOG="+f.launches,
|
||||
)
|
||||
if autoStart != "" {
|
||||
env = append(env, "BEADS_DOLT_AUTO_START="+autoStart)
|
||||
}
|
||||
out, err := runExternalServerBD(f.t, f.repoDir, env, args...)
|
||||
var exitErr *exec.ExitError
|
||||
if err != nil && !errors.As(err, &exitErr) {
|
||||
f.t.Fatalf("bd %s did not run: %v\n%s", strings.Join(args, " "), err, out)
|
||||
}
|
||||
launches, _ := os.ReadFile(f.launches)
|
||||
return externalInitResult{output: out, failed: err != nil, launches: strings.TrimSpace(string(launches))}
|
||||
}
|
||||
|
||||
// externalEndpoint is the server an --external init is pointed at.
|
||||
type externalEndpoint struct {
|
||||
flags []string // --server-host/--server-port, or --server-socket
|
||||
network string // "tcp" or "unix"
|
||||
addr string // host:port or the socket path, as bd reports it
|
||||
}
|
||||
|
||||
func tcpEndpoint(port int) externalEndpoint {
|
||||
return externalEndpoint{
|
||||
flags: []string{"--server-host", "127.0.0.1", "--server-port", strconv.Itoa(port)},
|
||||
network: "tcp",
|
||||
addr: net.JoinHostPort("127.0.0.1", strconv.Itoa(port)),
|
||||
}
|
||||
}
|
||||
|
||||
func unixEndpoint(path string) externalEndpoint {
|
||||
return externalEndpoint{flags: []string{"--server-socket", path}, network: "unix", addr: path}
|
||||
}
|
||||
|
||||
// externalInitSocketPath returns an unused unix socket path. Socket paths are
|
||||
// capped near 104 bytes and t.TempDir() nests too deeply under some runners.
|
||||
func externalInitSocketPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.MkdirTemp("", "bdx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(filepath.Join(dir, "dolt.sock")) > 100 {
|
||||
_ = os.RemoveAll(dir)
|
||||
if dir, err = os.MkdirTemp("/tmp", "bdx"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { _ = os.RemoveAll(dir) })
|
||||
return filepath.Join(dir, "dolt.sock")
|
||||
}
|
||||
|
||||
// serveUnixProxy listens on a fresh unix socket and forwards each connection
|
||||
// to target, so bd sees a reachable server at a socket path. The returned
|
||||
// func reports how many connections bd made through it.
|
||||
func serveUnixProxy(t *testing.T, target string) (string, func() int) {
|
||||
t.Helper()
|
||||
path := externalInitSocketPath(t)
|
||||
ln, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
t.Fatalf("listen on %s: %v", path, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
var mu sync.Mutex
|
||||
accepted := 0
|
||||
go func() {
|
||||
for {
|
||||
client, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
accepted++
|
||||
mu.Unlock()
|
||||
go func() {
|
||||
defer client.Close()
|
||||
upstream, err := net.Dial("tcp", target)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer upstream.Close()
|
||||
done := make(chan struct{}, 2)
|
||||
go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
|
||||
go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
|
||||
<-done // either side closing ends the session; the deferred closes release the other copy
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return path, func() int { mu.Lock(); defer mu.Unlock(); return accepted }
|
||||
}
|
||||
|
||||
// requireNoLaunch fails when bd tried to run dolt at all: an externally
|
||||
// managed server is never started by bd, and the shim is how a start shows.
|
||||
func requireNoLaunch(t *testing.T, res externalInitResult) {
|
||||
t.Helper()
|
||||
if res.launches != "" {
|
||||
t.Errorf("bd launched dolt although the server is externally managed (dolt %s):\n%s",
|
||||
strings.ReplaceAll(res.launches, "\n", "; dolt "), res.output)
|
||||
}
|
||||
}
|
||||
|
||||
// requireExternalUnreachableMessage checks the one wording an --external init
|
||||
// gives for an endpoint it cannot reach: it names the endpoint, says the server
|
||||
// is declared external and that bd did not start one, and never advises
|
||||
// `bd dolt start`, which would start the server --external says bd must not.
|
||||
func requireExternalUnreachableMessage(t *testing.T, output, endpoint string) {
|
||||
t.Helper()
|
||||
for _, want := range []string{endpoint, "externally managed", "did not start"} {
|
||||
if !strings.Contains(output, want) {
|
||||
t.Errorf("output does not contain %q:\n%s", want, output)
|
||||
}
|
||||
}
|
||||
if strings.Contains(output, "bd dolt start") {
|
||||
t.Errorf("output advises `bd dolt start`:\n%s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func requireNothingListening(t *testing.T, network, addr string) {
|
||||
t.Helper()
|
||||
conn, err := net.DialTimeout(network, addr, time.Second)
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
t.Errorf("something accepts connections on %s %s after init", network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// requireDoltRootEmpty fails when .beads/dolt holds anything: init leaves at
|
||||
// most an empty marker directory for an external server, so any entry is a
|
||||
// server root a local dolt created.
|
||||
func requireDoltRootEmpty(t *testing.T, repoDir string) {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(filepath.Join(repoDir, ".beads", "dolt"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) > 0 {
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Errorf(".beads/dolt holds %v, which init did not put there", names)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitServerExternalDeadPortStartsNoServer is the end-to-end boundary for
|
||||
// --external: a dead endpoint must fail loudly instead of making bd launch a
|
||||
// dolt of its own on the port the caller named.
|
||||
func TestInitServerExternalDeadPortStartsNoServer(t *testing.T) {
|
||||
f := newExternalInitFixture(t)
|
||||
ep := tcpEndpoint(freeLoopbackPort(t))
|
||||
|
||||
res := f.run("", append(append([]string{"init", "--quiet", "--server", "--external"}, ep.flags...),
|
||||
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
|
||||
|
||||
if !res.failed {
|
||||
t.Errorf("bd init --server --external succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
|
||||
}
|
||||
requireNoLaunch(t, res)
|
||||
requireExternalUnreachableMessage(t, res.output, ep.addr)
|
||||
requireNothingListening(t, ep.network, ep.addr)
|
||||
requireDoltRootEmpty(t, f.repoDir)
|
||||
}
|
||||
|
||||
// TestInitServerExternalNoPortStartsNoServer is the --external boundary that
|
||||
// rule 2c (#5934) cannot see: the argv and the environment name no port, so
|
||||
// nothing but the flag declares the server external. A server init in that
|
||||
// shape launches a repo-local dolt by design (see
|
||||
// TestInitServerWithoutNamedPortStillStartsServer), so with --external it must
|
||||
// fail instead, and say that bd did not start one. There is no endpoint to
|
||||
// name, so the wording is checked without one: the child inherits
|
||||
// BEADS_TEST_MODE, under which the store dials port 1 rather than leave an
|
||||
// unnamed port at 0, so the port-0 wording itself is pinned by
|
||||
// TestExternalServerUnreachableMessage.
|
||||
func TestInitServerExternalNoPortStartsNoServer(t *testing.T) {
|
||||
f := newExternalInitFixture(t)
|
||||
|
||||
res := f.run("", "init", "--quiet", "--server", "--external", "--prefix", "x", "--skip-hooks", "--skip-agents")
|
||||
|
||||
if !res.failed {
|
||||
t.Errorf("bd init --server --external succeeded with no server named:\n%s", res.output)
|
||||
}
|
||||
requireNoLaunch(t, res)
|
||||
requireDoltRootEmpty(t, f.repoDir)
|
||||
for _, want := range []string{"externally managed", "did not start"} {
|
||||
if !strings.Contains(res.output, want) {
|
||||
t.Errorf("output does not contain %q:\n%s", want, res.output)
|
||||
}
|
||||
}
|
||||
if strings.Contains(res.output, "bd dolt start") {
|
||||
t.Errorf("output advises `bd dolt start`:\n%s", res.output)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitSharedServerExternalDeadPortStillFails pins the sibling route that
|
||||
// already honors --external: the same dead endpoint under --shared-server
|
||||
// exits non-zero without launching dolt. Without it the test above could pass
|
||||
// because every init fails here, not because --server honors the flag.
|
||||
func TestInitSharedServerExternalDeadPortStillFails(t *testing.T) {
|
||||
f := newExternalInitFixture(t)
|
||||
ep := tcpEndpoint(freeLoopbackPort(t))
|
||||
|
||||
res := f.run("", append(append([]string{"init", "--quiet", "--shared-server", "--external"}, ep.flags...),
|
||||
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
|
||||
|
||||
if !res.failed {
|
||||
t.Errorf("bd init --shared-server --external succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
|
||||
}
|
||||
requireNoLaunch(t, res)
|
||||
}
|
||||
|
||||
// TestInitServerWithoutNamedPortStillStartsServer pins the other half of the
|
||||
// contract: a --server init that names no port is where bd starts a repo-local
|
||||
// dolt by design, so the no-launch assertions above cannot pass merely because
|
||||
// nothing can ever launch one. It names no port, in argv or in the environment
|
||||
// (envWithoutBeadsStorageSettings drops every BEADS_DOLT_* variable): a named
|
||||
// port is declared external by rule 2c (#5934) with or without --external, so
|
||||
// it would launch nothing here either way.
|
||||
func TestInitServerWithoutNamedPortStillStartsServer(t *testing.T) {
|
||||
f := newExternalInitFixture(t)
|
||||
|
||||
res := f.run("", "init", "--quiet", "--server", "--prefix", "x", "--skip-hooks", "--skip-agents")
|
||||
|
||||
if res.launches == "" {
|
||||
t.Errorf("bd init --server naming no port never reached dolt, so auto-start regressed:\n%s", res.output)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitExternalUnreachableMessage covers the wording across the routes an
|
||||
// --external init can take. Every one of them gives the same message, whether
|
||||
// auto-start is pinned off by the environment, the server is a shared one, or
|
||||
// the endpoint is a socket.
|
||||
func TestInitExternalUnreachableMessage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mode string
|
||||
autoStart string
|
||||
endpoint func(t *testing.T) externalEndpoint
|
||||
}{
|
||||
{"server host:port with auto-start pinned off", "--server", "0",
|
||||
func(t *testing.T) externalEndpoint { return tcpEndpoint(freeLoopbackPort(t)) }},
|
||||
{"shared-server host:port", "--shared-server", "",
|
||||
func(t *testing.T) externalEndpoint { return tcpEndpoint(freeLoopbackPort(t)) }},
|
||||
{"server socket", "--server", "",
|
||||
func(t *testing.T) externalEndpoint { return unixEndpoint(externalInitSocketPath(t)) }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newExternalInitFixture(t)
|
||||
ep := tc.endpoint(t)
|
||||
|
||||
res := f.run(tc.autoStart, append(append([]string{"init", "--quiet", tc.mode, "--external"}, ep.flags...),
|
||||
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
|
||||
|
||||
if !res.failed {
|
||||
t.Fatalf("bd init succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
|
||||
}
|
||||
requireExternalUnreachableMessage(t, res.output, ep.addr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitExternalProvisionerShape runs init with the argv a provisioner of an
|
||||
// externally managed server uses, in both endpoint forms, with auto-start
|
||||
// unset and pinned off, against a server that is up and one that is not. Every
|
||||
// cell is a control: a port named with --server-port is already declared
|
||||
// external by rule 2c (#5934), and a socket is never auto-started, so none of
|
||||
// them launched dolt before init honored --external either. They pin that the
|
||||
// provisioner shape keeps launching nothing, keeps failing against a dead
|
||||
// endpoint, and still records the endpoint it was given. The reachable cells
|
||||
// need the Dolt test server and skip without it.
|
||||
func TestInitExternalProvisionerShape(t *testing.T) {
|
||||
for _, form := range []string{"host-port", "socket"} {
|
||||
for _, autoStart := range []string{"unset", "0"} {
|
||||
for _, reachable := range []bool{false, true} {
|
||||
state := "unreachable"
|
||||
if reachable {
|
||||
state = "reachable"
|
||||
}
|
||||
t.Run(fmt.Sprintf("%s/auto-start=%s/%s", form, autoStart, state), func(t *testing.T) {
|
||||
runProvisionerCell(t, form, autoStart, reachable)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runProvisionerCell(t *testing.T, form, autoStart string, reachable bool) {
|
||||
t.Helper()
|
||||
if reachable {
|
||||
skipIfNoDolt(t)
|
||||
}
|
||||
f := newExternalInitFixture(t)
|
||||
|
||||
var ep externalEndpoint
|
||||
var socketConnections func() int
|
||||
switch {
|
||||
case form == "host-port" && reachable:
|
||||
ep = tcpEndpoint(testDoltServerPort)
|
||||
case form == "host-port":
|
||||
ep = tcpEndpoint(freeLoopbackPort(t))
|
||||
case reachable:
|
||||
var sock string
|
||||
sock, socketConnections = serveUnixProxy(t, net.JoinHostPort("127.0.0.1", strconv.Itoa(testDoltServerPort)))
|
||||
ep = unixEndpoint(sock)
|
||||
default:
|
||||
ep = unixEndpoint(externalInitSocketPath(t))
|
||||
}
|
||||
|
||||
database := "provisioned"
|
||||
if reachable {
|
||||
database = uniqueTestDBName(t)
|
||||
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
|
||||
}
|
||||
|
||||
args := append([]string{"init", "--init-if-missing", "--quiet", "--server", "--external"}, ep.flags...)
|
||||
args = append(args, "-p", "prov", "--skip-hooks", "--skip-agents", "--database", database, f.repoDir)
|
||||
pin := ""
|
||||
if autoStart == "0" {
|
||||
pin = "0"
|
||||
}
|
||||
|
||||
res := f.run(pin, args...)
|
||||
|
||||
requireNoLaunch(t, res)
|
||||
if !reachable {
|
||||
if !res.failed {
|
||||
t.Errorf("bd init succeeded against an unreachable endpoint %s:\n%s", ep.addr, res.output)
|
||||
}
|
||||
requireNothingListening(t, ep.network, ep.addr)
|
||||
return
|
||||
}
|
||||
if res.failed {
|
||||
t.Fatalf("bd init against the reachable server %s failed:\n%s", ep.addr, res.output)
|
||||
}
|
||||
requireDoltRootEmpty(t, f.repoDir)
|
||||
data, err := os.ReadFile(filepath.Join(f.repoDir, ".beads", "metadata.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("expected metadata.json after init: %v", err)
|
||||
}
|
||||
var meta configfile.Config
|
||||
if err := json.Unmarshal(data, &meta); err != nil {
|
||||
t.Fatalf("parse metadata.json: %v\n%s", err, data)
|
||||
}
|
||||
if form == "socket" {
|
||||
if meta.DoltServerSocket != ep.addr {
|
||||
t.Errorf("metadata.json dolt_server_socket = %q, want the socket init was given, %q", meta.DoltServerSocket, ep.addr)
|
||||
}
|
||||
if socketConnections() == 0 {
|
||||
t.Errorf("bd never connected through the socket %s", ep.addr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if meta.DoltServerHost != "127.0.0.1" || meta.DoltServerPort != testDoltServerPort {
|
||||
t.Errorf("metadata.json names %s:%d, want the endpoint init was given, %s", meta.DoltServerHost, meta.DoltServerPort, ep.addr)
|
||||
}
|
||||
}
|
||||
97
cmd/bd/init_external_message_test.go
Normal file
97
cmd/bd/init_external_message_test.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestExternalServerUnreachableMessage pins which failures get the --external
|
||||
// wording. Only a failed dial may: the message claims the server could not be
|
||||
// reached, so any other open failure (an identity mismatch, a handshake that
|
||||
// was reset) must keep its own text instead of being reported as "externally
|
||||
// managed".
|
||||
func TestExternalServerUnreachableMessage(t *testing.T) {
|
||||
refused := errors.New("connect: connection refused")
|
||||
dial := &net.OpError{
|
||||
Op: "dial",
|
||||
Net: "tcp",
|
||||
Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 3307},
|
||||
Err: refused,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
wantEndpoint string // "" means the error is not rewritten
|
||||
}{
|
||||
{"dial error", dial, "127.0.0.1:3307"},
|
||||
{
|
||||
// The store wraps the dial error with %w and its own advice.
|
||||
"dial error wrapped like the store does",
|
||||
fmt.Errorf("Dolt server unreachable at 127.0.0.1:3307: %w\n\nThe Dolt server may not be running.", dial),
|
||||
"127.0.0.1:3307",
|
||||
},
|
||||
{
|
||||
"unix socket dial error",
|
||||
&net.OpError{Op: "dial", Net: "unix", Addr: &net.UnixAddr{Name: "/run/dolt.sock", Net: "unix"}, Err: refused},
|
||||
"/run/dolt.sock",
|
||||
},
|
||||
{
|
||||
// A name that does not resolve has no address to report.
|
||||
"dial error without an address",
|
||||
&net.OpError{Op: "dial", Net: "tcp", Err: errors.New("no such host")},
|
||||
"the configured endpoint",
|
||||
},
|
||||
{"read error after connecting", &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")}, ""},
|
||||
{"not a network error", errors.New("project identity mismatch"), ""},
|
||||
}
|
||||
// Every rewritten message says the server is declared external and that bd
|
||||
// did not start one, and never advises `bd dolt start`.
|
||||
requireDeclaredExternal := func(t *testing.T, got string, wants ...string) {
|
||||
t.Helper()
|
||||
for _, want := range append(wants, "externally managed", "did not start") {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("message does not contain %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "bd dolt start") {
|
||||
t.Errorf("message advises `bd dolt start`:\n%s", got)
|
||||
}
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := externalServerUnreachableMessage(tt.err)
|
||||
if tt.wantEndpoint == "" {
|
||||
if got != "" {
|
||||
t.Fatalf("message = %q, want none for an error that is not a failed dial", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
requireDeclaredExternal(t, got, tt.wantEndpoint)
|
||||
})
|
||||
}
|
||||
|
||||
// A dial to port 0 is an init that was never told a port: the address is a
|
||||
// placeholder, not the server's endpoint, so the message must not offer it
|
||||
// as one. The first line quotes the dialled address, so it is cut out
|
||||
// before looking.
|
||||
t.Run("dial error with no port named", func(t *testing.T) {
|
||||
noPort := &net.OpError{
|
||||
Op: "dial",
|
||||
Net: "tcp",
|
||||
Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0},
|
||||
Err: refused,
|
||||
}
|
||||
got := externalServerUnreachableMessage(noPort)
|
||||
if got == "" {
|
||||
t.Fatal("message = none, want the --external wording for a failed dial")
|
||||
}
|
||||
requireDeclaredExternal(t, got)
|
||||
if strings.Contains(strings.ReplaceAll(got, noPort.Error(), ""), ":0") {
|
||||
t.Errorf("message offers port 0 as the endpoint:\n%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -19,17 +19,35 @@ import (
|
|||
)
|
||||
|
||||
// guardLegacyUpgradeWorkspace rejects the reviewed pre-Dolt and legacy-Dolt
|
||||
// workspace shapes before command setup can track a version, migrate metadata,
|
||||
// or construct a store. It intentionally classifies only metadata, regular
|
||||
// SQLite files, and the bounded local version witness; storage internals stay
|
||||
// behind the driver boundary.
|
||||
// workspace shapes, and workspaces whose metadata declares a format this build
|
||||
// cannot open (checkWorkspaceFormat), before command setup can track a version,
|
||||
// migrate metadata, or construct a store. It intentionally classifies only
|
||||
// metadata, regular SQLite files, and the bounded local version witness;
|
||||
// storage internals stay behind the driver boundary. Render its refusals with
|
||||
// handleWorkspaceGuardError.
|
||||
func guardLegacyUpgradeWorkspace(beadsDir string) error {
|
||||
return guardLegacyUpgradeWorkspaceForInit(beadsDir, false)
|
||||
}
|
||||
|
||||
// guardLegacyUpgradeWorkspaceForInit is guardLegacyUpgradeWorkspace for a caller
|
||||
// that has already resolved server intent from a source the workspace does not
|
||||
// yet record: `bd init --server`, whose flag is the only place that choice lives
|
||||
// until init has written it. The guard cannot see the flag, so initSelectsServer
|
||||
// carries it in. It is consulted for exactly one thing, the empty-root admission
|
||||
// below, and is deliberately not folded into the workspace's own server mode:
|
||||
// that would also move a non-empty root with an unreadable witness onto the
|
||||
// warn-and-open arm, and an embedded repository beside a non-empty .beads/dolt
|
||||
// onto the refusing one.
|
||||
func guardLegacyUpgradeWorkspaceForInit(beadsDir string, initSelectsServer bool) error {
|
||||
if beadsDir == "" {
|
||||
return nil
|
||||
}
|
||||
cfg, err := configfile.LoadForDiscovery(beadsDir)
|
||||
// This guard admits only the ordinary Issue store. A workspace in another
|
||||
// format is refused before any legacy classification, which could
|
||||
// otherwise admit it, or report it as a legacy store to migrate.
|
||||
cfg, err := loadAndCheckWorkspaceFormat(beadsDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading config: %w", err)
|
||||
return err
|
||||
}
|
||||
if isHistoricalSQLiteWorkspace(beadsDir, cfg) {
|
||||
return legacyUpgradeRefusal("historical SQLite workspace")
|
||||
|
|
@ -75,6 +93,15 @@ func guardLegacyUpgradeWorkspace(beadsDir string) error {
|
|||
// did not.
|
||||
return nil
|
||||
}
|
||||
if initSelectsServer && !present && isEmptyDirectory(filepath.Join(beadsDir, "dolt")) {
|
||||
// Init has already chosen a server, so this is the empty root the
|
||||
// serverMode arm below admits for a workspace that records the choice: it
|
||||
// holds no Dolt data a legacy release could have left, and bd makes it
|
||||
// itself on use, so a retry after a first attempt that could not reach a
|
||||
// server finds exactly this. A present witness, a root holding any entry,
|
||||
// and every caller that does not pass the flag are decided as before.
|
||||
return nil
|
||||
}
|
||||
if serverMode {
|
||||
if !present && isEmptyDirectory(filepath.Join(beadsDir, "dolt")) {
|
||||
// An empty .beads/dolt holds no Dolt data, so no legacy release
|
||||
|
|
@ -249,9 +276,34 @@ func onlyLegacySQLiteEntries(beadsDir string, entries []os.DirEntry, databaseNam
|
|||
// excludes vc.db, so this bounded fallback runs only after that discovery found
|
||||
// no current workspace.
|
||||
func guardUndiscoveredLegacyWorkspace() error {
|
||||
for _, beadsDir := range undiscoveredWorkspaceCandidates() {
|
||||
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkUndiscoveredWorkspaceFormat refuses a workspace in a format this build
|
||||
// cannot open (checkWorkspaceFormat) that discovery passed over, such as one
|
||||
// marked only by a legacy config.json, and nothing else. It reads metadata
|
||||
// without migrating it.
|
||||
func checkUndiscoveredWorkspaceFormat() error {
|
||||
for _, beadsDir := range undiscoveredWorkspaceCandidates() {
|
||||
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// undiscoveredWorkspaceCandidates lists, nearest first, the .beads directories
|
||||
// the undiscovered-workspace checks read: the one BEADS_DIR names or, without
|
||||
// it, each .beads from the working directory up to the repository root and
|
||||
// below BEADS_CEILING_DIRECTORIES.
|
||||
func undiscoveredWorkspaceCandidates() []string {
|
||||
if explicit := os.Getenv("BEADS_DIR"); explicit != "" {
|
||||
beadsDir := beads.FollowRedirect(utils.CanonicalizePath(explicit))
|
||||
return guardLegacyUpgradeWorkspace(beadsDir)
|
||||
return []string{beads.FollowRedirect(utils.CanonicalizePath(explicit))}
|
||||
}
|
||||
|
||||
cwd, err := os.Getwd()
|
||||
|
|
@ -261,19 +313,18 @@ func guardUndiscoveredLegacyWorkspace() error {
|
|||
dir := utils.CanonicalizePath(cwd)
|
||||
boundary := utils.CanonicalizePath(git.GetRepoRoot())
|
||||
bound := ceiling.For(dir)
|
||||
var candidates []string
|
||||
for {
|
||||
if bound.Excludes(dir) {
|
||||
return nil
|
||||
}
|
||||
if err := guardLegacyUpgradeWorkspace(filepath.Join(dir, ".beads")); err != nil {
|
||||
return err
|
||||
return candidates
|
||||
}
|
||||
candidates = append(candidates, filepath.Join(dir, ".beads"))
|
||||
if boundary != "" && utils.PathsEqual(dir, boundary) {
|
||||
return nil
|
||||
return candidates
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
return nil
|
||||
return candidates
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
|
|
|
|||
87
cmd/bd/legacy_upgrade_guard_init_flag_e2e_test.go
Normal file
87
cmd/bd/legacy_upgrade_guard_init_flag_e2e_test.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestInitServerFlagAdmitsEmptyDoltRootWithoutConfig reproduces the retry shape
|
||||
// with nothing on disk that records the server choice: an empty .beads/dolt and
|
||||
// neither config.yaml nor metadata.json, so the --server flag is the only place
|
||||
// the intent lives. The legacy guard used to refuse that init as a legacy Dolt
|
||||
// workspace, so the workspace was never created and no bd command could repair
|
||||
// it.
|
||||
func TestInitServerFlagAdmitsEmptyDoltRootWithoutConfig(t *testing.T) {
|
||||
skipIfNoDolt(t)
|
||||
env := externalServerTestEnv(t)
|
||||
|
||||
repoDir := t.TempDir()
|
||||
initGitRepo(t, repoDir)
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
if err := os.MkdirAll(filepath.Join(beadsDir, "dolt"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
database := uniqueTestDBName(t)
|
||||
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
|
||||
|
||||
out, err := runExternalServerBD(t, repoDir, env, externalServerInitArgs(database)...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd init --server over an empty .beads/dolt failed: %v\n%s", err, out)
|
||||
}
|
||||
assertCurrentVersionWitness(t, beadsDir)
|
||||
}
|
||||
|
||||
// TestInitServerFlagRetryAfterFailedFirstAttempt replays the reported sequence: a
|
||||
// first `bd init --server` that cannot reach a server fails after creating the
|
||||
// local Dolt root, leaving an empty .beads/dolt and no witness, and the same
|
||||
// command run again once the server is up must succeed instead of being refused
|
||||
// as a legacy workspace over the root the first attempt made itself.
|
||||
func TestInitServerFlagRetryAfterFailedFirstAttempt(t *testing.T) {
|
||||
skipIfNoDolt(t)
|
||||
env := externalServerTestEnv(t)
|
||||
// The first attempt has to fail without starting a server of its own: one
|
||||
// that started and then failed would leave a populated .beads/dolt, which
|
||||
// the guard refuses by design. externalServerTestEnv pins
|
||||
// BEADS_DOLT_AUTO_START=0 for exactly that, which keeps the attempt
|
||||
// deterministic even once init's separate --external handling stops trying
|
||||
// to start a per-project server. Fail here, naming the reason, if a change to
|
||||
// that helper drops it.
|
||||
if !slices.Contains(env, "BEADS_DOLT_AUTO_START=0") {
|
||||
t.Fatal("externalServerTestEnv must set BEADS_DOLT_AUTO_START=0: the failed first attempt must not start a server of its own")
|
||||
}
|
||||
|
||||
repoDir := t.TempDir()
|
||||
initGitRepo(t, repoDir)
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
|
||||
database := uniqueTestDBName(t)
|
||||
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
|
||||
|
||||
out, err := runExternalServerBD(t, repoDir, env,
|
||||
externalServerInitArgs(database, "--server-port", strconv.Itoa(freeLoopbackPort(t)))...)
|
||||
if err == nil {
|
||||
t.Fatalf("precondition: bd init --server against an unreachable server succeeded:\n%s", out)
|
||||
}
|
||||
// The retry only has something to fix if the failed attempt left exactly
|
||||
// this. Any other leftover is a finding about init, not a reason to loosen
|
||||
// what follows.
|
||||
entries, readErr := os.ReadDir(filepath.Join(beadsDir, "dolt"))
|
||||
if readErr != nil || len(entries) != 0 {
|
||||
t.Fatalf("precondition: the failed first attempt should leave an empty .beads/dolt, found %d entries (err %v)", len(entries), readErr)
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(beadsDir, localVersionFile)); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("precondition: the failed first attempt should leave no %s (stat err %v)", localVersionFile, statErr)
|
||||
}
|
||||
|
||||
out, err = runExternalServerBD(t, repoDir, env, externalServerInitArgs(database)...)
|
||||
if err != nil {
|
||||
t.Fatalf("retrying bd init --server over the empty .beads/dolt the first attempt left failed: %v\n%s", err, out)
|
||||
}
|
||||
assertCurrentVersionWitness(t, beadsDir)
|
||||
}
|
||||
143
cmd/bd/legacy_upgrade_guard_init_flag_test.go
Normal file
143
cmd/bd/legacy_upgrade_guard_init_flag_test.go
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestLegacyUpgradeGuardForInitAdmitsEmptyDoltRoot pins the one thing init's own
|
||||
// intent unlocks. `bd init --server` resolves server mode from the flag, a source
|
||||
// the workspace does not record until init has written it. A retry over the empty
|
||||
// .beads/dolt that a failed first attempt leaves behind therefore looks like an
|
||||
// embedded workspace with a local Dolt root, and the guard refuses it. Told what
|
||||
// init already knows, the guard gives that root the admission a config-selected
|
||||
// server workspace gets. Asked without it, in either form, it still refuses, so
|
||||
// the admission cannot pass vacuously.
|
||||
func TestLegacyUpgradeGuardForInitAdmitsEmptyDoltRoot(t *testing.T) {
|
||||
warnings := captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
|
||||
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); err != nil {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want nil", err)
|
||||
}
|
||||
if warnings.Len() != 0 {
|
||||
t.Fatalf("guard warned about an absent witness: %q", warnings.String())
|
||||
}
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, false); !isLegacyUpgradeRefusal(err) {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, false) = %v, want migration refusal", err)
|
||||
}
|
||||
if err := guardLegacyUpgradeWorkspace(beadsDir); !isLegacyUpgradeRefusal(err) {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspace(dir) = %v, want migration refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyUpgradeGuardForInitAdmissionStaysNarrow proves init's intent relaxes
|
||||
// nothing beyond an empty, witness-less .beads/dolt. With it set, anything that
|
||||
// could be legacy data still refuses, and the outcomes a broader reading of the
|
||||
// flag would move (treating it as if the workspace itself selected server mode)
|
||||
// stay where they are.
|
||||
func TestLegacyUpgradeGuardForInitAdmissionStaysNarrow(t *testing.T) {
|
||||
for _, entry := range []string{"beads", ".dolt", "stray-file", "symlink"} {
|
||||
t.Run("root holding "+entry, func(t *testing.T) {
|
||||
captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
|
||||
path := filepath.Join(beadsDir, "dolt", entry)
|
||||
var err error
|
||||
switch entry {
|
||||
case "stray-file":
|
||||
err = os.WriteFile(path, nil, 0o600)
|
||||
case "symlink":
|
||||
if err = os.Symlink(t.TempDir(), path); err != nil {
|
||||
t.Skipf("symlink capability unavailable: %v", err)
|
||||
}
|
||||
default:
|
||||
err = os.Mkdir(path, 0o700)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, version := range []string{"0.49.6", "0.62.0"} {
|
||||
t.Run("pre-1.0 witness "+version, func(t *testing.T) {
|
||||
captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", version)
|
||||
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("blank witness over a non-empty root", func(t *testing.T) {
|
||||
warnings := captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
|
||||
if err := os.Mkdir(filepath.Join(beadsDir, "dolt", "beads"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, localVersionFile), []byte("\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A workspace that selects server mode itself warns and opens over an
|
||||
// unreadable witness. Init's intent must not move this root onto that arm.
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
|
||||
}
|
||||
if warnings.Len() != 0 {
|
||||
t.Fatalf("guard took the unreadable-witness arm: %q", warnings.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("symlinked dolt root", func(t *testing.T) {
|
||||
captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
|
||||
root := filepath.Join(beadsDir, "dolt")
|
||||
if err := os.Remove(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(t.TempDir(), root); err != nil {
|
||||
t.Skipf("symlink capability unavailable: %v", err)
|
||||
}
|
||||
|
||||
// hasLegacyDoltRoot does not follow a symlink, so the guard never takes
|
||||
// such a root for a local Dolt root and it never reaches the empty-root
|
||||
// admission. Init's intent has to leave its outcome exactly where every
|
||||
// other caller finds it.
|
||||
want := fmt.Sprint(guardLegacyUpgradeWorkspace(beadsDir))
|
||||
if got := fmt.Sprint(guardLegacyUpgradeWorkspaceForInit(beadsDir, true)); got != want {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %s, want %s (unchanged by init's intent)", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("embedded repository beside a non-empty root", func(t *testing.T) {
|
||||
captureLegacyUpgradeWarnings(t)
|
||||
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
|
||||
repo := filepath.Join(beadsDir, "embeddeddolt", "beads", ".dolt")
|
||||
if err := os.MkdirAll(repo, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repo, "repo-entry"), []byte("opaque"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, "dolt", "stray-file"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An embedded repository admits the workspace before server intent is
|
||||
// consulted at all. Folding init's intent into the workspace's own mode
|
||||
// would send this one to the refusing arm.
|
||||
for _, initSelectsServer := range []bool{false, true} {
|
||||
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, initSelectsServer); err != nil {
|
||||
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, %t) = %v, want nil", initSelectsServer, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -5,7 +5,6 @@ import (
|
|||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
|
|
@ -64,8 +63,10 @@ Examples:
|
|||
defer toCleanup()
|
||||
|
||||
dt := types.DependencyType(depType)
|
||||
// bd link writes through the store's own dependency verb rather than
|
||||
// the DependencyEditor role, so it asks the role's rule directly.
|
||||
// link's own checks run before anything is written, and over http
|
||||
// before the dial: the dotted-child rule (the role raises it too) and
|
||||
// the type's length. Unlike `bd dep add`, link takes any type a
|
||||
// workspace spells, so it never asks validateDependencyType.
|
||||
if err := issueops.CheckDottedChildDependency(fromID, toID, dt); err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
|
@ -74,13 +75,25 @@ Examples:
|
|||
return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most %d characters", depType, types.MaxDependencyTypeLen)
|
||||
}
|
||||
|
||||
dep := &types.Dependency{
|
||||
IssueID: fromID,
|
||||
DependsOnID: toID,
|
||||
Type: dt,
|
||||
opsCtx, err := issueOpsContext(ctx)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
// Read the titles while the resolution's reads are fresh, as `bd dep
|
||||
// add` does: an edge changes neither title, and over http a lookup
|
||||
// after the write would be two more round trips.
|
||||
var fromTitle, toTitle string
|
||||
if !jsonOutput {
|
||||
fromTitle, toTitle = lookupTitle(fromID), lookupTitle(toID)
|
||||
}
|
||||
|
||||
if err := fromStore.AddDependencyWithOptions(ctx, dep, currentActor(), storage.DependencyAddOptions{EmitEvent: true}); err != nil {
|
||||
// The write goes through the DependencyEditor role, the route `bd dep
|
||||
// add` takes, so it is served on every backend: a local store and an
|
||||
// http workspace alike (the http client refuses the raw
|
||||
// AddDependencyWithOptions by design). The role records the
|
||||
// dependency_added event the raw verb's EmitEvent did.
|
||||
edge := issueops.DependencyEdge{IssueID: fromID, DependsOnID: toID, Type: dt}
|
||||
if err := addDependencyEdgesDirect(opsCtx, fromStore, []issueops.DependencyEdge{edge}, false); err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
|
|
@ -104,7 +117,7 @@ Examples:
|
|||
})
|
||||
}
|
||||
fmt.Printf("%s Linked: %s depends on %s (%s)\n",
|
||||
ui.RenderPass("✓"), formatFeedbackIDParen(fromID, lookupTitle(fromID)), formatFeedbackIDParen(toID, lookupTitle(toID)), depType)
|
||||
ui.RenderPass("✓"), formatFeedbackIDParen(fromID, fromTitle), formatFeedbackIDParen(toID, toTitle), depType)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -811,6 +811,7 @@ func TestEmbeddedListSearchAndOutputFormats(t *testing.T) {
|
|||
if !strings.Contains(out, "digraph") {
|
||||
t.Errorf("dot output should contain 'digraph' header, got: %s", out)
|
||||
}
|
||||
assertDotCanonicalOrder(t, out)
|
||||
})
|
||||
|
||||
t.Run("format_dot_output_error", func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -327,6 +327,50 @@ func TestListDisplayPrettyListHonorsSort(t *testing.T) {
|
|||
t.Fatalf("tree siblings ignore --sort closed:\n%s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deps scheduling", func(t *testing.T) {
|
||||
// At both levels the --deps tree orders (roots, and one parent's
|
||||
// children): late depends on dep, so dep prints first although --sort
|
||||
// closed alone would lead with the newer late; free has no edge, so
|
||||
// --sort closed puts it ahead of dep, where priority would put it last.
|
||||
oldest := time.Now().Add(-3 * time.Hour)
|
||||
parentAt := time.Now().Add(-4 * time.Hour)
|
||||
parent := &types.Issue{ID: "bd-parent", Title: "Parent", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeEpic, ClosedAt: &parentAt}
|
||||
rootDep := &types.Issue{ID: "bd-root-dep", Title: "Root dependency", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeTask, ClosedAt: &oldest}
|
||||
rootLate := &types.Issue{ID: "bd-root-late", Title: "Root dependent", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask, ClosedAt: &newer}
|
||||
rootFree := &types.Issue{ID: "bd-root-free", Title: "Root unlinked", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask, ClosedAt: &older}
|
||||
childDep := &types.Issue{ID: "bd-child-dep", Title: "Child dependency", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeTask, ClosedAt: &oldest}
|
||||
childLate := &types.Issue{ID: "bd-child-late", Title: "Child dependent", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask, ClosedAt: &newer}
|
||||
childFree := &types.Issue{ID: "bd-child-free", Title: "Child unlinked", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask, ClosedAt: &older}
|
||||
deps := map[string][]*types.Dependency{
|
||||
rootLate.ID: {{IssueID: rootLate.ID, DependsOnID: rootDep.ID, Type: types.DepBlocks}},
|
||||
childDep.ID: {{IssueID: childDep.ID, DependsOnID: parent.ID, Type: types.DepParentChild}},
|
||||
childFree.ID: {{IssueID: childFree.ID, DependsOnID: parent.ID, Type: types.DepParentChild}},
|
||||
childLate.ID: {
|
||||
{IssueID: childLate.ID, DependsOnID: parent.ID, Type: types.DepParentChild},
|
||||
{IssueID: childLate.ID, DependsOnID: childDep.ID, Type: types.DepBlocks},
|
||||
},
|
||||
}
|
||||
issues := []*types.Issue{parent, rootDep, rootLate, rootFree, childDep, childLate, childFree}
|
||||
|
||||
out := captureStdout(t, func() error {
|
||||
displayPrettyListWithDepsMode(issues, false, deps, "scheduling", false, false, "closed", "closed", false, nil)
|
||||
return nil
|
||||
})
|
||||
// A dependency's id also appears on its dependent's annotation row; the
|
||||
// first occurrence is still the dependency's own row whenever it prints first.
|
||||
for _, want := range [][]string{
|
||||
{rootFree.ID, rootDep.ID, rootLate.ID},
|
||||
{childFree.ID, childDep.ID, childLate.ID},
|
||||
} {
|
||||
for i := 1; i < len(want); i++ {
|
||||
before, after := strings.Index(out, want[i-1]), strings.Index(out, want[i])
|
||||
if before < 0 || after < 0 || before > after {
|
||||
t.Fatalf("--deps scheduling --sort closed: want %s before %s:\n%s", want[i-1], want[i], out)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestListDisplayPrettyList(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,11 @@ package main
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
|
|
@ -38,7 +40,27 @@ func composeTruncationHint(render func(string) string, text string) string {
|
|||
return "\n" + rendered + "\n"
|
||||
}
|
||||
|
||||
// outputDotFormat renders the listed issues, and the dependency edges between
|
||||
// them, as a Graphviz digraph.
|
||||
//
|
||||
// The bytes depend on the graph alone: nodes are declared in byte order of id,
|
||||
// and each node's edges in byte order of target id, then type (the order
|
||||
// issueops.EdgeReader pins). The page arrives in display order, by default
|
||||
// priority, then created_at DESC at one-second precision, then id, so two
|
||||
// equal-priority issues swapped places depending on whether they were created
|
||||
// in the same second; and the proxied route's edge query orders by source
|
||||
// only. Declaration order means nothing in the graph but steers Graphviz's
|
||||
// layout and shows in every diff, so it is pinned here, as bd graph --dot pins
|
||||
// its layers. --sort and --limit still choose which issues are listed.
|
||||
//
|
||||
// Byte order, not the utils.NaturalCompareIDs order --sort id uses: that
|
||||
// comparator is not a total order (x-9 < x-10 < x-1a < x-9; bd-01 ties bd-1),
|
||||
// so a sort under it could still depend on the order the page arrived in.
|
||||
// Both sorts work on copies; the caller's slices keep their order.
|
||||
func outputDotFormat(out io.Writer, issues []*types.Issue, depsByIssueID map[string][]*types.Dependency) error {
|
||||
issues = slices.Clone(issues)
|
||||
slices.SortFunc(issues, func(a, b *types.Issue) int { return cmp.Compare(a.ID, b.ID) })
|
||||
|
||||
w := &graphExportWriter{out: out}
|
||||
w.println("digraph dependencies {")
|
||||
w.println(" rankdir=TB;")
|
||||
|
|
@ -82,7 +104,11 @@ func outputDotFormat(out io.Writer, issues []*types.Issue, depsByIssueID map[str
|
|||
|
||||
// Output edges with labels for dependency type
|
||||
for _, issue := range issues {
|
||||
for _, dep := range depsByIssueID[issue.ID] {
|
||||
deps := slices.Clone(depsByIssueID[issue.ID])
|
||||
slices.SortFunc(deps, func(a, b *types.Dependency) int {
|
||||
return cmp.Or(cmp.Compare(a.DependsOnID, b.DependsOnID), cmp.Compare(a.Type, b.Type))
|
||||
})
|
||||
for _, dep := range deps {
|
||||
// Only output edges where both nodes are in the filtered list
|
||||
if issueMap[dep.DependsOnID] != nil {
|
||||
// Color code by dependency type
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@ package main
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
|
|
@ -65,6 +68,117 @@ func TestOutputDotFormatExactBytes(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestOutputDotFormatCanonicalOrder pins that the DOT rendering is a function
|
||||
// of the graph alone. The page it is handed is in display order (priority,
|
||||
// then created_at DESC at one-second precision, then id), so the same two
|
||||
// equal-priority issues arrive in either order depending on whether they were
|
||||
// created in the same second; and the proxied route's edge read does not order
|
||||
// one issue's edges. Every order of the page, with each issue's edges either
|
||||
// way round, must print these bytes: nodes by id, edges by source, target and
|
||||
// type, all in byte order (so dot-10 sorts before dot-2). It also pins that the
|
||||
// caller's page and edge slices are not reordered.
|
||||
func TestOutputDotFormatCanonicalOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
issues := []*types.Issue{
|
||||
{ID: "dot-2", Title: "Two", Status: types.StatusInProgress, Priority: 0, IssueType: types.TypeBug},
|
||||
{ID: "dot-10", Title: "Ten", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeEpic},
|
||||
{ID: "dot-1", Title: "One", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask},
|
||||
}
|
||||
edges := map[string][]*types.Dependency{
|
||||
"dot-2": {
|
||||
{IssueID: "dot-2", DependsOnID: "dot-10", Type: types.DepRelated},
|
||||
{IssueID: "dot-2", DependsOnID: "dot-unlisted", Type: types.DepBlocks},
|
||||
{IssueID: "dot-2", DependsOnID: "dot-1", Type: types.DepBlocks},
|
||||
},
|
||||
"dot-1": {{IssueID: "dot-1", DependsOnID: "dot-10", Type: types.DepParentChild}},
|
||||
}
|
||||
const want = `digraph dependencies {
|
||||
rankdir=TB;
|
||||
node [shape=box, style=rounded];
|
||||
|
||||
"dot-1" [label="dot-1\n[task P2]\nOne\n(closed)", style="rounded,filled", fillcolor="lightgray", fontcolor="dimgray"];
|
||||
"dot-10" [label="dot-10\n[epic P1]\nTen\n(open)", style="rounded,filled", fillcolor="white", fontcolor="black"];
|
||||
"dot-2" [label="dot-2\n[bug P0]\nTwo\n(in_progress)", style="rounded,filled", fillcolor="lightyellow", fontcolor="black"];
|
||||
|
||||
"dot-1" -> "dot-10" [label="parent-child", color=blue, style=solid];
|
||||
"dot-2" -> "dot-1" [label="blocks", color=red, style=bold];
|
||||
"dot-2" -> "dot-10" [label="related", color=gray, style=dashed];
|
||||
}
|
||||
`
|
||||
for _, perm := range [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} {
|
||||
for _, reversed := range []bool{false, true} {
|
||||
page := []*types.Issue{issues[perm[0]], issues[perm[1]], issues[perm[2]]}
|
||||
pageEdges := map[string][]*types.Dependency{}
|
||||
for id, deps := range edges {
|
||||
deps = slices.Clone(deps)
|
||||
if reversed {
|
||||
slices.Reverse(deps)
|
||||
}
|
||||
pageEdges[id] = deps
|
||||
}
|
||||
wantPage := slices.Clone(page)
|
||||
wantEdges := map[string][]*types.Dependency{}
|
||||
for id, deps := range pageEdges {
|
||||
wantEdges[id] = slices.Clone(deps)
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := outputDotFormat(&out, page, pageEdges); err != nil {
|
||||
t.Fatalf("outputDotFormat: %v", err)
|
||||
}
|
||||
name := fmt.Sprintf("page order %v, edges reversed %v", perm, reversed)
|
||||
if got := out.String(); got != want {
|
||||
t.Errorf("%s: DOT output bytes differ\ngot:\n%s\nwant:\n%s", name, got, want)
|
||||
}
|
||||
if !slices.Equal(page, wantPage) {
|
||||
t.Errorf("%s: outputDotFormat reordered the caller's page", name)
|
||||
}
|
||||
for id, deps := range wantEdges {
|
||||
if !slices.Equal(pageEdges[id], deps) {
|
||||
t.Errorf("%s: outputDotFormat reordered the caller's edges of %s", name, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dotNodeDecl and dotEdgeDecl match the node and edge lines outputDotFormat
|
||||
// writes.
|
||||
var (
|
||||
dotNodeDecl = regexp.MustCompile(`(?m)^ "([^"]+)" \[label=`)
|
||||
dotEdgeDecl = regexp.MustCompile(`(?m)^ "([^"]+)" -> "([^"]+)" \[label="([^"]+)"`)
|
||||
)
|
||||
|
||||
// assertDotCanonicalOrder is TestOutputDotFormatCanonicalOrder's check for a
|
||||
// real `bd list --format dot` run: nodes in byte order of id, edges in byte
|
||||
// order of source, target and type. The embedded and proxied list seeds mint
|
||||
// their ids across five priorities, so a rendering that followed the page's
|
||||
// priority order fails it.
|
||||
func assertDotCanonicalOrder(t *testing.T, out string) {
|
||||
t.Helper()
|
||||
var nodes []string
|
||||
for _, m := range dotNodeDecl.FindAllStringSubmatch(out, -1) {
|
||||
nodes = append(nodes, m[1])
|
||||
}
|
||||
if len(nodes) < 2 {
|
||||
t.Fatalf("dot output declares %d nodes, want every listed issue:\n%s", len(nodes), out)
|
||||
}
|
||||
if !slices.IsSorted(nodes) {
|
||||
t.Errorf("dot output declares its nodes out of id order: %v", nodes)
|
||||
}
|
||||
type edge struct{ from, to, typ string }
|
||||
var edges []edge
|
||||
for _, m := range dotEdgeDecl.FindAllStringSubmatch(out, -1) {
|
||||
edges = append(edges, edge{m[1], m[2], m[3]})
|
||||
}
|
||||
if !slices.IsSortedFunc(edges, func(a, b edge) int {
|
||||
return cmp.Or(cmp.Compare(a.from, b.from), cmp.Compare(a.to, b.to), cmp.Compare(a.typ, b.typ))
|
||||
}) {
|
||||
t.Errorf("dot output declares its edges out of (source, target, type) order: %v", edges)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputFormattedListExactBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
issues, deps := listOutputFixture()
|
||||
|
|
|
|||
|
|
@ -495,6 +495,7 @@ func TestProxiedServerList(t *testing.T) {
|
|||
if !strings.Contains(out, "digraph") {
|
||||
t.Errorf("dot output should contain 'digraph' header, got: %s", out)
|
||||
}
|
||||
assertDotCanonicalOrder(t, out)
|
||||
})
|
||||
|
||||
t.Run("format_digraph_output_error", func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
|
|
@ -83,6 +85,48 @@ func TestOrderSiblingsByDeps_OutOfGroupEdgeIgnored(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// closedSibling builds a sibling closed hoursAgo hours before a fixed instant,
|
||||
// so --sort closed (newest first) orders it independently of priority and ID.
|
||||
func closedSibling(id string, priority, hoursAgo int) *types.Issue {
|
||||
at := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC).Add(-time.Duration(hoursAgo) * time.Hour)
|
||||
return &types.Issue{ID: id, Priority: priority, ClosedAt: &at}
|
||||
}
|
||||
|
||||
func TestOrderSiblingsByDeps_ReadySetFollowsCallerCompare(t *testing.T) {
|
||||
// b depends on a. Newest-closed first is b, u, a, v; priority order is
|
||||
// v, a, u, b. The initial ready set {a, u, v} must follow the caller's
|
||||
// compare (u, a, v), and once a frees b the re-sorted ready set must put
|
||||
// the newer b ahead of v.
|
||||
a := closedSibling("pa-a", 1, 3)
|
||||
b := closedSibling("pa-b", 3, 1)
|
||||
u := closedSibling("pa-u", 2, 2)
|
||||
v := closedSibling("pa-v", 0, 4)
|
||||
deps := map[string][]*types.Dependency{"pa-b": {schedDep("pa-b", "pa-a")}}
|
||||
|
||||
got := idsOf(orderSiblingsByDeps([]*types.Issue{b, a, v, u}, deps, compareIssuesForTree("closed", false)))
|
||||
want := []string{"pa-u", "pa-a", "pa-b", "pa-v"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("--sort closed ready set: got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderSiblingsByDeps_CycleFallbackFollowsCallerCompare(t *testing.T) {
|
||||
// x <-> y cycle: x wins on priority and ID, but y closed more recently, so
|
||||
// the cycle fallback under --sort closed must emit y first.
|
||||
x := closedSibling("pa-x", 0, 2)
|
||||
y := closedSibling("pa-y", 1, 1)
|
||||
deps := map[string][]*types.Dependency{
|
||||
"pa-x": {schedDep("pa-x", "pa-y")},
|
||||
"pa-y": {schedDep("pa-y", "pa-x")},
|
||||
}
|
||||
|
||||
got := idsOf(orderSiblingsByDeps([]*types.Issue{x, y}, deps, compareIssuesForTree("closed", false)))
|
||||
want := []string{"pa-y", "pa-x"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("--sort closed cycle fallback: got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDepEdgeDisplay(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/hooks"
|
||||
"github.com/steveyegge/beads/internal/httpclient"
|
||||
"github.com/steveyegge/beads/internal/initprocs"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/migration"
|
||||
"github.com/steveyegge/beads/internal/molecules"
|
||||
|
|
@ -1578,6 +1579,9 @@ var rootCmd = &cobra.Command{
|
|||
}
|
||||
}
|
||||
if err := guardLegacyNoStoreCommand(cmd, beadsDir); err != nil {
|
||||
if isUnsupportedWorkspaceFormat(err) {
|
||||
return handleWorkspaceGuardError(err)
|
||||
}
|
||||
isMigrationCommand := false
|
||||
for current := cmd; current != nil; current = current.Parent() {
|
||||
if current.Name() == "migrate" {
|
||||
|
|
@ -1637,7 +1641,7 @@ var rootCmd = &cobra.Command{
|
|||
prepareSelectedCommandContext(bd, true)
|
||||
refreshBoundCommandConfig(cmd)
|
||||
if guardErr := guardLegacyUpgradeWorkspace(bd); guardErr != nil {
|
||||
return HandleError("%v", guardErr)
|
||||
return handleWorkspaceGuardError(guardErr)
|
||||
}
|
||||
cfg, cfgErr := configfile.LoadForDiscovery(bd)
|
||||
if cfgErr != nil || cfg != nil && (cfg.IsDoltProxiedServerMode() ||
|
||||
|
|
@ -1658,7 +1662,7 @@ var rootCmd = &cobra.Command{
|
|||
dbPath = bd
|
||||
}
|
||||
} else if guardErr := guardUndiscoveredLegacyWorkspace(); guardErr != nil {
|
||||
return HandleError("%v", guardErr)
|
||||
return handleWorkspaceGuardError(guardErr)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1743,7 +1747,7 @@ var rootCmd = &cobra.Command{
|
|||
prepareSelectedCommandContext(beadsDir, true)
|
||||
refreshBoundCommandConfig(cmd)
|
||||
if guardErr := guardLegacyUpgradeWorkspace(beadsDir); guardErr != nil {
|
||||
return HandleError("%v", guardErr)
|
||||
return handleWorkspaceGuardError(guardErr)
|
||||
}
|
||||
|
||||
// Workspace operation gate: every command that reaches this point
|
||||
|
|
@ -2782,7 +2786,7 @@ func isBootstrapPreviewErr(err error) bool {
|
|||
// Extracted from the gate's default arm so both halves are directly testable
|
||||
// without standing up a forward-drifted workspace; the wire itself is pinned on
|
||||
// the embedded tier by
|
||||
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace.
|
||||
// TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace.
|
||||
func refuseUnverifiablePreviewOpen(previewErr error) error {
|
||||
if handleFreshCloneError(previewErr) {
|
||||
return SilentExit()
|
||||
|
|
@ -2878,6 +2882,7 @@ func validateWorkspaceIdentity(ctx context.Context, s storage.DoltStorage, beads
|
|||
}
|
||||
|
||||
func main() {
|
||||
initprocs.Done()
|
||||
// BD_NAME overrides the binary name in help text (e.g. BD_NAME=ops makes
|
||||
// "ops --help" show "ops" instead of "bd"). Useful for multi-instance
|
||||
// setups where wrapper scripts set BEADS_DIR for routing.
|
||||
|
|
|
|||
|
|
@ -25,8 +25,10 @@ import (
|
|||
// workspace and then deletes them from the project. Those are ordinary bead
|
||||
// mutations in another workspace, so they belong in that workspace's events
|
||||
// journal if it has one enabled — and the setting is read from there, not from
|
||||
// the workspace bd was launched in.
|
||||
// the workspace bd was launched in. The same goes for its issue-version history,
|
||||
// which the store's own settings row decides.
|
||||
func openMigrationPlanningStore(ctx context.Context, planningBeadsDir string) (s storage.DoltStorage, err error) {
|
||||
defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }()
|
||||
defer func() { s, err = activateEventsJournalStore(planningBeadsDir, s, err) }()
|
||||
return dolt.New(ctx, &dolt.Config{
|
||||
Path: doltserver.ResolveDoltDir(planningBeadsDir),
|
||||
|
|
|
|||
|
|
@ -46,9 +46,9 @@ func setupContributorRouting(t *testing.T, bd, dir string) string {
|
|||
return planningDir
|
||||
}
|
||||
|
||||
// TestMigratePersonal_noopWhenEmpty verifies that migrate-personal with no
|
||||
// TestEmbeddedMigratePersonal_noopWhenEmpty verifies that migrate-personal with no
|
||||
// matching issues exits 0 and reports nothing to migrate.
|
||||
func TestMigratePersonal_noopWhenEmpty(t *testing.T) {
|
||||
func TestEmbeddedMigratePersonal_noopWhenEmpty(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")
|
||||
}
|
||||
|
|
@ -71,9 +71,9 @@ func TestMigratePersonal_noopWhenEmpty(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestMigratePersonal_movesIssues verifies that migrate-personal moves issues
|
||||
// TestEmbeddedMigratePersonal_movesIssues verifies that migrate-personal moves issues
|
||||
// matching the current git identity to the planning repo.
|
||||
func TestMigratePersonal_movesIssues(t *testing.T) {
|
||||
func TestEmbeddedMigratePersonal_movesIssues(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")
|
||||
}
|
||||
|
|
@ -119,9 +119,9 @@ func TestMigratePersonal_movesIssues(t *testing.T) {
|
|||
_ = planningDir
|
||||
}
|
||||
|
||||
// TestMigratePersonal_abortOnNoConfirm verifies that without --yes, the command
|
||||
// TestEmbeddedMigratePersonal_abortOnNoConfirm verifies that without --yes, the command
|
||||
// prompts and aborts when stdin signals no confirmation (EOF).
|
||||
func TestMigratePersonal_abortOnNoConfirm(t *testing.T) {
|
||||
func TestEmbeddedMigratePersonal_abortOnNoConfirm(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")
|
||||
}
|
||||
|
|
@ -162,13 +162,13 @@ func TestMigratePersonal_abortOnNoConfirm(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestMigratePersonal_preservesComments is a regression test for the maphew
|
||||
// TestEmbeddedMigratePersonal_preservesComments is a regression test for the maphew
|
||||
// review of PR #4023 (be-e2nb): migrate-personal must copy comments as
|
||||
// structured rows (ImportIssueComment) so they survive in the planning repo.
|
||||
// The pre-fix code used AddComment, which records an event-style entry that
|
||||
// GetIssueComments never returns — silently dropping the migrated issue's
|
||||
// comments.
|
||||
func TestMigratePersonal_preservesComments(t *testing.T) {
|
||||
func TestEmbeddedMigratePersonal_preservesComments(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")
|
||||
}
|
||||
|
|
@ -211,14 +211,14 @@ func TestMigratePersonal_preservesComments(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestCopyIssueRelations_preservesCommentWithTimestamp is the in-process proof
|
||||
// TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp is the in-process proof
|
||||
// for the maphew review of PR #4023 (be-e2nb). The full migrate-personal command
|
||||
// can't run in the embedded harness because its planning store uses the
|
||||
// server-based Dolt store, so this drives the helper directly against two
|
||||
// embedded stores: a comment must land in the destination as a structured row
|
||||
// (returned by GetIssueComments) preserving its original timestamp, not be lost
|
||||
// as an event-style AddComment entry.
|
||||
func TestCopyIssueRelations_preservesCommentWithTimestamp(t *testing.T) {
|
||||
func TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestMigrateSchema_IdentityMismatchRefusesBeforeApplying reproduces be-0gfcs:
|
||||
// TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying reproduces be-0gfcs:
|
||||
// bd migrate schema's workspace-identity guard (validateWorkspaceIdentity)
|
||||
// runs AFTER the shared pre-run has already opened the store and let the
|
||||
// smart gate auto-apply a pending schema migration as a side effect. The
|
||||
|
|
@ -22,7 +22,7 @@ import (
|
|||
// schema_migrations. The fix must make the identity check run before (or
|
||||
// otherwise gate) that auto-apply, so a refused migrate leaves the schema
|
||||
// cursor untouched.
|
||||
func TestMigrateSchema_IdentityMismatchRefusesBeforeApplying(t *testing.T) {
|
||||
func TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -743,8 +743,8 @@ func TestLabelAddBlockedDuringMigrationFreeze(t *testing.T) {
|
|||
// Plain `bd import` is stopped by the early gate in PersistentPreRunE, like
|
||||
// any other write. The `--dry-run` row is the one that pins runImport's OWN
|
||||
// call: a preview sets useReadOnly, so it skips the early gate, and runImport
|
||||
// never calls CheckReadonly — delete the check from import.go and only this
|
||||
// row goes red. It also pins the claim the PreRunE comment makes about
|
||||
// calls CheckReadonly only under strict --readonly, so its freeze check is the
|
||||
// only one left — delete that check from import.go and only this row goes red. It also pins the claim the PreRunE comment makes about
|
||||
// previews being re-blocked at the per-command chokepoint, which for import is
|
||||
// exactly that call and nothing else.
|
||||
func TestImportBlockedDuringMigrationFreeze(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -13,11 +13,11 @@ import (
|
|||
"github.com/steveyegge/beads/internal/validation"
|
||||
)
|
||||
|
||||
// TestSpawnMolecule_PreservesStepLabels verifies that a cooked formula with
|
||||
// TestEmbeddedSpawnMolecule_PreservesStepLabels verifies that a cooked formula with
|
||||
// per-step labels results in spawned issues whose labels are persisted to the
|
||||
// database. Regression for labels being silently dropped by cloneSubgraph in
|
||||
// the same shape as the metadata bug fixed by gastownhall/beads#3341.
|
||||
func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
|
||||
func TestEmbeddedSpawnMolecule_PreservesStepLabels(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")
|
||||
}
|
||||
|
|
@ -74,9 +74,9 @@ func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestSpawnMolecule_SubstitutesTemplatedStepFields is the cook -> pour
|
||||
// TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields is the cook -> pour
|
||||
// regression test for GH#5110 (labels, metadata) and GH#5754 (assignee).
|
||||
// TestSpawnMolecule_PreservesStepLabels above fixed labels being dropped
|
||||
// TestEmbeddedSpawnMolecule_PreservesStepLabels above fixed labels being dropped
|
||||
// entirely, but its labels carry no {{vars}}, so the missing substitution went
|
||||
// unnoticed: the labels ARE carried through - just literal, which silently
|
||||
// stops matching every label query downstream.
|
||||
|
|
@ -85,7 +85,7 @@ func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
|
|||
// spawned bead unclosable by the actor that poured it, so the molecule can
|
||||
// never advance - which is what the AssigneeMatches assertion pins, not just
|
||||
// the string value.
|
||||
func TestSpawnMolecule_SubstitutesTemplatedStepFields(t *testing.T) {
|
||||
func TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -281,12 +281,12 @@ func primeFirstDiff(got, want string) string {
|
|||
// subprocess parity tests. The TestEmbedded prefix is deliberate and
|
||||
// load-bearing in both directions: the fast `./...` lanes run
|
||||
// -skip '^TestEmbedded' (pr.yml, main.yml), and .github/scripts/embedded-test-shard.sh
|
||||
// discovers shard members by grepping ^func TestEmbedded in *_embedded_test.go.
|
||||
// discovers shard members by grepping ^func TestEmbedded in cmd/bd/*_test.go.
|
||||
// So they run in the full embedded tier, which ci-embedded-tier.sh enables
|
||||
// unconditionally for merge_group and pushes to main — i.e. in the merge queue
|
||||
// before this can land, not on every PR push. Renaming them out of the prefix
|
||||
// moves ~30s of subprocess work into every short lane; renaming the file out of
|
||||
// *_embedded_test.go drops them from the shard runner entirely.
|
||||
// moves ~30s of subprocess work into every short lane and drops them from the
|
||||
// shard runner entirely.
|
||||
//
|
||||
// TestEmbeddedPrimeChangeDirPrimesTarget is the issue's repro end to end
|
||||
// (#5509): from repo-a, `bd -C repo-b prime` must emit repo-b's PRIME.md,
|
||||
|
|
|
|||
|
|
@ -238,12 +238,12 @@ func TestEmbeddedPruneDryRunAndFilters(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestPrune_protectsBeadCitedByCustomStatusBead is a regression test for the
|
||||
// TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead is a regression test for the
|
||||
// maphew review of PR #4023 (be-e2nb): reference-aware prune must scan beads in
|
||||
// active *custom* statuses, not only the built-in non-closed statuses. A closed
|
||||
// bead cited by a bead in an active custom status must be protected from prune,
|
||||
// exactly like one cited by a built-in open bead.
|
||||
func TestPrune_protectsBeadCitedByCustomStatusBead(t *testing.T) {
|
||||
func TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead(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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -179,6 +179,9 @@ This is useful for agents executing molecules to see which steps can run next.`,
|
|||
return nil
|
||||
}
|
||||
|
||||
if jsonOutput && readyJSONPrintsNoTotal(activeStore) {
|
||||
return runReadyJSONWithoutTotal(ctx, activeStore, filter)
|
||||
}
|
||||
if jsonOutput {
|
||||
// The page and the size of the whole ready set come back from ONE
|
||||
// read transaction: the total rides the page's own ID query, so a
|
||||
|
|
@ -430,6 +433,65 @@ var blockedCmd = &cobra.Command{
|
|||
},
|
||||
}
|
||||
|
||||
// readyJSONPrintsNoTotal reports whether `bd ready --json` should skip sizing
|
||||
// the whole ready set. Without BD_JSON_ENVELOPE the total only decorates the
|
||||
// stderr hint. A local store takes it in the page's own transaction, so the
|
||||
// hint keeps it there; a remote backend pays a second request
|
||||
// (countReadyWork) for it, so the hint goes without.
|
||||
func readyJSONPrintsNoTotal(activeStore storage.DoltStorage) bool {
|
||||
return !jsonEnvelopeEnabled() && storeIsRemoteBackend(activeStore)
|
||||
}
|
||||
|
||||
// runReadyJSONWithoutTotal lists one row past the limit, which says whether
|
||||
// the limit hid anything: all the hint needs. A cap at or below the limit
|
||||
// would count that extra row against it, so such a listing keeps the counted
|
||||
// path and its refusal exactly as before.
|
||||
func runReadyJSONWithoutTotal(ctx context.Context, activeStore storage.DoltStorage, filter types.WorkFilter) error {
|
||||
limit := filter.Limit
|
||||
var results []*types.IssueWithCounts
|
||||
var total int
|
||||
var err error
|
||||
if limit > 0 && filter.MaxRows > 0 && filter.MaxRows <= limit {
|
||||
results, total, err = activeStore.GetReadyWorkWithCountsAndTotal(ctx, filter)
|
||||
} else {
|
||||
if limit > 0 {
|
||||
filter.Limit = limit + 1
|
||||
}
|
||||
results, err = activeStore.GetReadyWorkWithCounts(ctx, filter)
|
||||
total = len(results)
|
||||
}
|
||||
if err != nil {
|
||||
if capErr := handleMaxRowsError(err); capErr != nil {
|
||||
return capErr
|
||||
}
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
truncated := limit > 0 && len(results) >= limit && total > limit
|
||||
if len(results) > limit && limit > 0 {
|
||||
results = results[:limit]
|
||||
}
|
||||
if results == nil {
|
||||
results = []*types.IssueWithCounts{}
|
||||
}
|
||||
if err := outputJSON(results); err != nil {
|
||||
return err
|
||||
}
|
||||
if truncated {
|
||||
fmt.Fprintf(os.Stderr, "%s Use --limit 0 for all, or --limit N to raise the cap.\n", readyHiddenHint(len(results)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readyHiddenHint is the truncation hint for a page whose total is unknown:
|
||||
// how many rows are shown, and that the limit hid more.
|
||||
func readyHiddenHint(shown int) string {
|
||||
noun := "issues"
|
||||
if shown == 1 {
|
||||
noun = "issue"
|
||||
}
|
||||
return fmt.Sprintf("Showing %d ready %s; more matched but were hidden by --limit.", shown, noun)
|
||||
}
|
||||
|
||||
// readyTotal sizes the whole ready set for the request `bd ready` just listed
|
||||
// a page of, through the store's own ReadyCounter accessor.
|
||||
//
|
||||
|
|
|
|||
138
cmd/bd/ready_json_no_total_test.go
Normal file
138
cmd/bd/ready_json_no_total_test.go
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// readyPageFake serves GetReadyWorkWithCounts from a fixed ready set and
|
||||
// records the filters it was asked for. Its embedded DoltStorage is nil, so any
|
||||
// other read panics and the test says so.
|
||||
type readyPageFake struct {
|
||||
storage.DoltStorage
|
||||
ready []*types.IssueWithCounts
|
||||
limits []int
|
||||
totalCalls int
|
||||
}
|
||||
|
||||
func (f *readyPageFake) IsRemoteBackendStore() bool { return true }
|
||||
|
||||
func (f *readyPageFake) GetReadyWorkWithCounts(_ context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, error) {
|
||||
f.limits = append(f.limits, filter.Limit)
|
||||
if filter.Limit > 0 && filter.Limit < len(f.ready) {
|
||||
return f.ready[:filter.Limit], nil
|
||||
}
|
||||
return f.ready, nil
|
||||
}
|
||||
|
||||
func (f *readyPageFake) GetReadyWorkWithCountsAndTotal(_ context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, int, error) {
|
||||
f.totalCalls++
|
||||
if filter.Limit > 0 && filter.Limit < len(f.ready) {
|
||||
return f.ready[:filter.Limit], len(f.ready), nil
|
||||
}
|
||||
return f.ready, len(f.ready), nil
|
||||
}
|
||||
|
||||
func readyRows(n int) []*types.IssueWithCounts {
|
||||
rows := make([]*types.IssueWithCounts, n)
|
||||
for i := range rows {
|
||||
rows[i] = &types.IssueWithCounts{Issue: &types.Issue{ID: "bd-" + string(rune('a'+i)), Title: "t", Status: types.StatusOpen}}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
func runReadyJSONWithoutTotalForTest(t *testing.T, s storage.DoltStorage, filter types.WorkFilter) ([]types.IssueWithCounts, string) {
|
||||
t.Helper()
|
||||
stdioMutex.Lock()
|
||||
defer stdioMutex.Unlock()
|
||||
var err error
|
||||
stdout, stderr := captureStdio(t, func() {
|
||||
err = runReadyJSONWithoutTotal(context.Background(), s, filter)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("runReadyJSONWithoutTotal: %v\nstderr: %s", err, stderr)
|
||||
}
|
||||
var rows []types.IssueWithCounts
|
||||
if err := json.Unmarshal([]byte(stdout), &rows); err != nil {
|
||||
t.Fatalf("stdout is not a JSON array: %v\n%s", err, stdout)
|
||||
}
|
||||
return rows, stderr
|
||||
}
|
||||
|
||||
// TestReadyJSONOnARemoteBackendAsksForNoTotal pins `bd ready --json` against a
|
||||
// remote backend with no envelope: one listing one row past the limit, never
|
||||
// the counted listing (which costs a remote store a countReadyWork request),
|
||||
// and a hint that says more exist without saying how many.
|
||||
func TestReadyJSONOnARemoteBackendAsksForNoTotal(t *testing.T) {
|
||||
t.Run("truncated", func(t *testing.T) {
|
||||
s := &readyPageFake{ready: readyRows(5)}
|
||||
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2})
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("printed %d rows, want the 2 the limit allows", len(rows))
|
||||
}
|
||||
if len(s.limits) != 1 || s.limits[0] != 3 || s.totalCalls != 0 {
|
||||
t.Fatalf("listings asked for limits %v and %d counted listings, want one listing of 3 and none counted", s.limits, s.totalCalls)
|
||||
}
|
||||
if !strings.Contains(stderr, "Showing 2 ready issues; more matched but were hidden by --limit.") {
|
||||
t.Fatalf("stderr = %q, want the truncation hint without a total", stderr)
|
||||
}
|
||||
})
|
||||
t.Run("whole set", func(t *testing.T) {
|
||||
s := &readyPageFake{ready: readyRows(2)}
|
||||
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2})
|
||||
if len(rows) != 2 || stderr != "" {
|
||||
t.Fatalf("rows = %d, stderr = %q; want both rows and no hint", len(rows), stderr)
|
||||
}
|
||||
})
|
||||
t.Run("unlimited", func(t *testing.T) {
|
||||
s := &readyPageFake{ready: readyRows(3)}
|
||||
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{})
|
||||
if len(rows) != 3 || stderr != "" || len(s.limits) != 1 || s.limits[0] != 0 {
|
||||
t.Fatalf("rows = %d, stderr = %q, limits = %v; want every row, no hint, one unlimited listing", len(rows), stderr, s.limits)
|
||||
}
|
||||
})
|
||||
t.Run("cap at the limit keeps the counted listing", func(t *testing.T) {
|
||||
s := &readyPageFake{ready: readyRows(5)}
|
||||
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2, MaxRows: 2})
|
||||
if len(rows) != 2 || s.totalCalls != 1 || len(s.limits) != 0 {
|
||||
t.Fatalf("rows = %d, counted = %d, limits = %v; want the counted listing alone", len(rows), s.totalCalls, s.limits)
|
||||
}
|
||||
if !strings.Contains(stderr, "Showing 2 ready issues; more matched") {
|
||||
t.Fatalf("stderr = %q, want the truncation hint without a total", stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestReadyJSONPrintsNoTotalOnlyWithoutTheEnvelopeOnARemoteBackend pins when
|
||||
// the total is skipped: the envelope prints it as pagination.total, and a local
|
||||
// store takes it in the page's own transaction for the stderr hint.
|
||||
func TestReadyJSONPrintsNoTotalOnlyWithoutTheEnvelopeOnARemoteBackend(t *testing.T) {
|
||||
remote := &readyPageFake{}
|
||||
local := &routingSettingsFake{}
|
||||
|
||||
t.Setenv("BD_JSON_ENVELOPE", "")
|
||||
if !readyJSONPrintsNoTotal(remote) {
|
||||
t.Error("remote backend without the envelope: want the total skipped")
|
||||
}
|
||||
if readyJSONPrintsNoTotal(local) {
|
||||
t.Error("local store: want the total kept")
|
||||
}
|
||||
t.Setenv("BD_JSON_ENVELOPE", "1")
|
||||
if readyJSONPrintsNoTotal(remote) {
|
||||
t.Error("remote backend with the envelope: want the total kept for pagination.total")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyHiddenHintAgreesInNumber(t *testing.T) {
|
||||
if got := readyHiddenHint(1); got != "Showing 1 ready issue; more matched but were hidden by --limit." {
|
||||
t.Errorf("readyHiddenHint(1) = %q", got)
|
||||
}
|
||||
if got := readyHiddenHint(2); got != "Showing 2 ready issues; more matched but were hidden by --limit." {
|
||||
t.Errorf("readyHiddenHint(2) = %q", got)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue