Merge upstream/main into salvage/pr-3859 (fix-merge PR #3859)
PR #3859 (GraemeF): adopts standard OTel SDK env vars (OTEL_EXPORTER_OTLP_*, OTEL_TRACES_EXPORTER, OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES, OTEL_SDK_DISABLED) with BD_OTEL_* back-compat (BD_OTEL_ENABLED master switch, BD_OTEL_METRICS_URL/LOGS_URL/STDOUT legacy selectors that translate to their OTEL_* equivalent and emit a deprecation warning), and extracts the inline telemetry.Init()/commandSpan wiring in cmd/bd/main.go's PersistentPreRunE into cmd/bd/command_telemetry.go. internal/telemetry/{telemetry,otlp}.go and telemetry_test.go merged cleanly: upstream/main had not touched telemetry.go since the PR's base, so the PR's env-var precedence logic and tests land unchanged. cmd/bd/main.go conflicted with #3858 (fix(telemetry): wire WrapStorage decorator into bd storage chain, merged just before this fix-merge) plus an unrelated usage-metrics bootstrap block that landed on main after this PR's base. Reconciliation: - #3858's storage-chain change (wireStorageDecorators call around line 1229) is untouched by this PR and carries over as-is. - Current main splits telemetry setup around an early-return gate: the telemetry.Init() call runs unconditionally before the usage-metrics bootstrap block, but the bd.command.<name> span is only started *after* that block's early return for the internal send-metrics subcommand (so that subcommand never gets a root span). The PR's single startCommandTelemetry() call combines Init+Start and can't sit at either point without changing that behavior for the metrics-send subcommand. Split command_telemetry.go into three helpers to preserve main's exact ordering and behavior: - initTelemetry(ctx, version): the Init half, called where main used to inline it (unconditionally, before the metrics bootstrap block). - startCommandSpan(ctx, cmdName, version, args): the span-start half, called where main used to inline it (after the metrics bootstrap block's early return), using the PR's commandSpanAttrs() helper. - startCommandTelemetry(...): kept as the PR's original combined Init+Start call, now implemented in terms of the two halves above, for callers/tests that don't need to interleave other setup between them. Its existing wiring-contract test still exercises it directly. - storage_chain_test.go (from #3858) and command_telemetry_test.go (from this PR) each defined a package-level clearTelemetryEnv helper; kept the more complete OTEL_*-aware version from command_telemetry_test.go and removed the duplicate (narrower, legacy-only) one from storage_chain_test.go, along with its now-unused "os" import. - docs/OBSERVABILITY.md merged without conflicts: the PR's env-var-naming rewrite and #3858's added "Confirm storage instrumentation locally" section touch disjoint parts of the file. Env-var precedence in the merged code (unchanged from the PR): OTEL_SDK_DISABLED=true always wins; otherwise Enabled() is true when BD_OTEL_ENABLED=true or any legacy BD_OTEL_* selector is set (standard OTEL_* vars alone do not activate telemetry); legacy BD_OTEL_METRICS_URL/LOGS_URL/STDOUT are unconditionally translated into their OTEL_* equivalents (legacy wins over a pre-existing OTEL_* value) with a one-line deprecation warning on stderr. Validated: go build (CGO_ENABLED=0, gms_pure_go), go vet ./cmd/bd/... ./internal/telemetry/..., and the targeted telemetry/WireStorage/ CommandSpan test subsets in cmd/bd and internal/telemetry (all pass, see session report). Agent-Signature: claude-fable-5-high on behalf of matt wilkie Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
commit
def9f97a45
1759 changed files with 172780 additions and 22398 deletions
|
|
@ -7,7 +7,7 @@
|
|||
# Phases:
|
||||
# 1. Prep & Push: preflight -> push-tag (polecat work)
|
||||
# 2. Gate: await-ci (async wait for release.yml)
|
||||
# 3. Verify: verify-github, verify-npm, verify-pypi (parallel)
|
||||
# 3. Verify: verify-github, verify-npm, verify-pypi, verify-homebrew-core (parallel)
|
||||
# 4. Install: local-install -> cleanup-stale-dolt-orphans -> release-complete
|
||||
|
||||
formula = "beads-release"
|
||||
|
|
@ -26,7 +26,7 @@ Gate (Async Wait):
|
|||
5. await-ci: Gate on GitHub Actions release.yml completion
|
||||
|
||||
Phase 2 (Parallel Verification):
|
||||
6. Verify GitHub release, npm package, PyPI package (concurrent)
|
||||
6. Verify GitHub release, npm package, PyPI package, Homebrew core formula (concurrent)
|
||||
|
||||
Phase 3 (Installation):
|
||||
7. Local installation update
|
||||
|
|
@ -536,40 +536,18 @@ description = """
|
|||
Create or verify the Docusaurus snapshot for {{version}} so the published docs
|
||||
version dropdown, default docs route, and llms-full artifact match the release.
|
||||
|
||||
Install website dependencies if needed:
|
||||
This is a single, idempotent script so version.go and the docs snapshot cannot
|
||||
drift apart. It installs website deps if needed, creates the versioned snapshot
|
||||
(if missing), points `docusaurus.config.ts` lastVersion at it, regenerates the
|
||||
CLI reference and llms-full.txt, and verifies consistency.
|
||||
|
||||
```bash
|
||||
cd website
|
||||
npm ci
|
||||
./scripts/snapshot-release-docs.sh {{version}}
|
||||
```
|
||||
|
||||
Create the release snapshot if it does not exist yet:
|
||||
```bash
|
||||
test -d versioned_docs/version-{{version}} || npx docusaurus docs:version {{version}}
|
||||
cd ..
|
||||
```
|
||||
|
||||
Ensure `website/docusaurus.config.ts` selects the new release snapshot:
|
||||
```bash
|
||||
# macOS
|
||||
sed -i '' "s/lastVersion: '[^']*'/lastVersion: '{{version}}'/" website/docusaurus.config.ts
|
||||
|
||||
# Linux
|
||||
sed -i "s/lastVersion: '[^']*'/lastVersion: '{{version}}'/" website/docusaurus.config.ts
|
||||
```
|
||||
|
||||
Regenerate docs artifacts from the release snapshot:
|
||||
```bash
|
||||
CGO_ENABLED=0 go build -tags gms_pure_go -o ./bd-docs ./cmd/bd/
|
||||
./scripts/generate-cli-docs.sh ./bd-docs
|
||||
./scripts/generate-llms-full.sh
|
||||
```
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
./scripts/check-docs-version.sh
|
||||
./scripts/check-doc-flags.sh ./bd-docs
|
||||
rm -f ./bd-docs
|
||||
```
|
||||
If `scripts/update-versions.sh {{version}}` was used for the version bump, the
|
||||
docs snapshot has already run as part of that step (unless --skip-docs was
|
||||
passed) and this step just re-verifies.
|
||||
"""
|
||||
|
||||
[[steps]]
|
||||
|
|
@ -748,6 +726,66 @@ Should show {{version}}.
|
|||
Note: PyPI may have a small propagation delay (1-2 min).
|
||||
"""
|
||||
|
||||
[[steps]]
|
||||
id = "verify-homebrew-core"
|
||||
title = "Verify Homebrew core formula"
|
||||
needs = ["await-ci"]
|
||||
description = """
|
||||
Confirm Homebrew core has the stable formula update.
|
||||
|
||||
Release candidates are not published to Homebrew. If `{{version}}` contains a
|
||||
hyphen, record that Homebrew intentionally remains on the latest stable release
|
||||
and skip the rest of this step.
|
||||
|
||||
Stable releases:
|
||||
|
||||
1. Check whether Homebrew already opened the canonical bump PR:
|
||||
```bash
|
||||
gh pr list \
|
||||
--repo Homebrew/homebrew-core \
|
||||
--search "beads {{version}} in:title" \
|
||||
--state all
|
||||
```
|
||||
|
||||
2. If a BrewTestBot or `brew bump-formula-pr` PR already exists, track that PR.
|
||||
Do not open a duplicate manual PR. Do not push to the PR branch before
|
||||
Homebrew's bottle commits are pushed.
|
||||
|
||||
3. If no PR exists, open it with Homebrew's bump tool:
|
||||
```bash
|
||||
brew bump-formula-pr \
|
||||
--url="https://github.com/gastownhall/beads/archive/refs/tags/v{{version}}.tar.gz" \
|
||||
beads
|
||||
```
|
||||
|
||||
This computes the source checksum and lets Homebrew/BrewTestBot manage the
|
||||
bottle block. Do not remove or hand-edit the bottle block.
|
||||
|
||||
4. If a manual PR is unavoidable, fill in Homebrew's current PR template before
|
||||
opening or editing the PR:
|
||||
```bash
|
||||
gh api repos/Homebrew/homebrew-core/contents/.github/PULL_REQUEST_TEMPLATE.md \
|
||||
-H 'Accept: application/vnd.github.raw'
|
||||
```
|
||||
|
||||
Do not leave the checklist/body blank. An incomplete or stale template causes
|
||||
Homebrew automation to close the PR.
|
||||
|
||||
5. Verify the merged formula on `Homebrew/homebrew-core@main`:
|
||||
```bash
|
||||
gh api '/repos/Homebrew/homebrew-core/contents/Formula/b/beads.rb?ref=main' \
|
||||
-H 'Accept: application/vnd.github.raw' | tee /tmp/homebrew-beads.rb
|
||||
|
||||
grep -F 'homepage "https://github.com/gastownhall/beads"' /tmp/homebrew-beads.rb
|
||||
grep -F 'url "https://github.com/gastownhall/beads/archive/refs/tags/v{{version}}.tar.gz"' /tmp/homebrew-beads.rb
|
||||
grep -F 'bottle do' /tmp/homebrew-beads.rb
|
||||
```
|
||||
|
||||
6. Record the merged Homebrew PR on the release tracker. If a duplicate manual
|
||||
PR was closed by Homebrew automation after the canonical PR merged, leave it
|
||||
closed and note which PR is canonical.
|
||||
"""
|
||||
|
||||
# =============================================================================
|
||||
# Phase 3: Installation (Fan-in)
|
||||
# =============================================================================
|
||||
|
|
@ -755,7 +793,7 @@ Note: PyPI may have a small propagation delay (1-2 min).
|
|||
[[steps]]
|
||||
id = "local-install"
|
||||
title = "Update local installation"
|
||||
needs = ["verify-github", "verify-npm", "verify-pypi"]
|
||||
needs = ["verify-github", "verify-npm", "verify-pypi", "verify-homebrew-core"]
|
||||
description = """
|
||||
Update local bd to the new version.
|
||||
|
||||
|
|
@ -763,7 +801,7 @@ Step 1: Install release binary
|
|||
|
||||
Option A - Homebrew:
|
||||
```bash
|
||||
brew upgrade bd
|
||||
brew upgrade beads
|
||||
```
|
||||
|
||||
Option B - Install script:
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
"name": "beads",
|
||||
"source": "./plugins/beads",
|
||||
"description": "AI-supervised issue tracker for coding workflows",
|
||||
"version": "1.0.4"
|
||||
"version": "1.1.0"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
6
.gitattributes
vendored
6
.gitattributes
vendored
|
|
@ -8,3 +8,9 @@ cmd/bd/templates/hooks/* text eol=lf
|
|||
# bytes, which breaks LF-only marker stripping in templateBody() and produces
|
||||
# doubled BEGIN/END BEADS INTEGRATION markers in installed AGENTS.md (#3552).
|
||||
internal/templates/agents/defaults/*.md text eol=lf
|
||||
|
||||
# Migration SQL is embedded into the binary and content-hashed after apply
|
||||
# (schema_migrations.content_hash, PR 4270). Pin LF so from-source builds on
|
||||
# Windows checkouts (core.autocrlf=true) hash identically to release builds
|
||||
# instead of reporting false migration-content skew.
|
||||
internal/storage/schema/migrations/**/*.sql text eol=lf
|
||||
|
|
|
|||
38
.githooks/pre-push
Executable file
38
.githooks/pre-push
Executable file
|
|
@ -0,0 +1,38 @@
|
|||
#!/usr/bin/env bash
|
||||
# Pre-push hook: when pushing a release tag (refs/tags/v*), refuse the push if
|
||||
# version constants and the Docusaurus docs snapshot disagree. This stops a
|
||||
# release from being tagged/published with drifted docs (the failure mode that
|
||||
# left main red after the 1.0.5 release) before it ever reaches CI.
|
||||
#
|
||||
# Installed via: git config core.hooksPath .githooks
|
||||
# See also: make install (sets hooksPath automatically)
|
||||
#
|
||||
# Bypass (not recommended for release tags): git push --no-verify
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# git feeds "<local ref> <local sha> <remote ref> <remote sha>" lines on stdin.
|
||||
pushing_version_tag=0
|
||||
while read -r local_ref _local_sha _remote_ref _remote_sha; do
|
||||
case "$local_ref" in
|
||||
refs/tags/v[0-9]*) pushing_version_tag=1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ "$pushing_version_tag" -eq 0 ] && exit 0
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel)"
|
||||
if [ ! -x "$repo_root/scripts/check-versions.sh" ]; then
|
||||
# Older checkout without the consistency check; do not block.
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Release tag push detected — verifying version + docs consistency..."
|
||||
if ! (cd "$repo_root" && ./scripts/check-versions.sh); then
|
||||
echo ""
|
||||
echo "❌ Refusing to push release tag: version/docs are inconsistent." >&2
|
||||
echo " Fix with: scripts/update-versions.sh <version>" >&2
|
||||
echo " (or scripts/snapshot-release-docs.sh <version> for the docs side)." >&2
|
||||
echo " Override with --no-verify only if you know what you are doing." >&2
|
||||
exit 1
|
||||
fi
|
||||
12
.github/CODEOWNERS
vendored
12
.github/CODEOWNERS
vendored
|
|
@ -12,3 +12,15 @@ cmd/bd/init.go @gastownhall/beads-maintainers
|
|||
cmd/bd/init_*.go @gastownhall/beads-maintainers
|
||||
cmd/bd/init_safety*.go @gastownhall/beads-maintainers
|
||||
docs/adr/0002-init-safety-invariants.md @gastownhall/beads-maintainers
|
||||
|
||||
# Schema-migration critical path (bd-6dnrw.15). The 2026 Apr-Jun window
|
||||
# shipped a corrupting migration (PR 4039, DEFAULT (UUID()) PK, zero reviews,
|
||||
# self-merged), a duplicate version number (PR 4027), and in-place edits to
|
||||
# released migrations (PRs 3991/3918/3942). Migration changes get at least
|
||||
# one human maintainer review; scripts/check-migration-hygiene.sh enforces
|
||||
# the mechanical invariants in CI, and reviewers should treat allowlist
|
||||
# additions and hygiene-script changes with the same suspicion as the
|
||||
# migrations themselves. NOTE: GitHub only enforces CODEOWNERS when branch
|
||||
# protection has "require review from Code Owners" enabled (bd-6dnrw.23).
|
||||
internal/storage/schema/migrations/ @gastownhall/beads-maintainers
|
||||
scripts/check-migration-hygiene.sh @gastownhall/beads-maintainers
|
||||
|
|
|
|||
56
.github/scripts/ci-gate.sh
vendored
Executable file
56
.github/scripts/ci-gate.sh
vendored
Executable file
|
|
@ -0,0 +1,56 @@
|
|||
#!/usr/bin/env bash
|
||||
# Evaluate an aggregate GitHub Actions gate from needs.*.result values.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
gate_name="${CI_GATE_NAME:-CI Gate}"
|
||||
required_vars="${CI_GATE_REQUIRED:-}"
|
||||
skipped_ok_vars=" ${CI_GATE_SKIPPED_OK:-} "
|
||||
failed=0
|
||||
|
||||
is_skipped_ok() {
|
||||
local var="$1"
|
||||
[[ "$skipped_ok_vars" == *" $var "* ]]
|
||||
}
|
||||
|
||||
report_failure() {
|
||||
local message="$1"
|
||||
echo "::error::$message"
|
||||
failed=1
|
||||
}
|
||||
|
||||
if [[ -z "$required_vars" ]]; then
|
||||
report_failure "CI_GATE_REQUIRED is empty for $gate_name"
|
||||
fi
|
||||
|
||||
for var in $required_vars; do
|
||||
result="${!var:-}"
|
||||
case "$result" in
|
||||
success)
|
||||
echo "ok: $var=$result"
|
||||
;;
|
||||
skipped)
|
||||
if is_skipped_ok "$var"; then
|
||||
echo "ok: $var=$result (allowed)"
|
||||
else
|
||||
report_failure "$var was skipped"
|
||||
fi
|
||||
;;
|
||||
failure|cancelled)
|
||||
report_failure "$var=$result"
|
||||
;;
|
||||
"")
|
||||
report_failure "$var is unset"
|
||||
;;
|
||||
*)
|
||||
report_failure "$var has unexpected result: $result"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ "$failed" -ne 0 ]]; then
|
||||
echo "$gate_name failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "$gate_name passed"
|
||||
791
.github/workflows/ci-measurements.yml
vendored
Normal file
791
.github/workflows/ci-measurements.yml
vendored
Normal file
|
|
@ -0,0 +1,791 @@
|
|||
name: CI Measurements
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
suite:
|
||||
description: "Suite to measure"
|
||||
required: true
|
||||
type: string
|
||||
smoke_version:
|
||||
description: "Optional previous release for cross-version-smoke"
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
suite:
|
||||
description: "Suite to measure"
|
||||
required: true
|
||||
type: choice
|
||||
default: pr-linux
|
||||
options:
|
||||
- pr-linux
|
||||
- macos-short
|
||||
- macos-candidates
|
||||
- linux-integration
|
||||
- linux-integration-sharded
|
||||
- linux-integration-hybrid-sharded
|
||||
- linux-integration-hybrid-16-sharded
|
||||
- linux-integration-hybrid-prebuilt-sharded
|
||||
- linux-integration-coverage
|
||||
- cross-version-smoke
|
||||
- nix
|
||||
- mcp-package
|
||||
- npm-package
|
||||
- website
|
||||
smoke_version:
|
||||
description: "Optional previous release for cross-version-smoke"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.suite }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
pr-linux:
|
||||
name: Measure PR Linux commands
|
||||
if: ${{ inputs.suite == 'pr-linux' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
source ./.buildflags
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
ci_time "install golangci-lint" -- go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9.0
|
||||
status=0
|
||||
ci_time "pr-policy wrapper" -- make ci-pr-policy || status=$?
|
||||
ci_time "pr-core gotestsum" -- gotestsum --junitfile artifacts/pr-core-junit.xml --format testdox -- -race -short -skip '^TestEmbedded' ./... || status=$?
|
||||
ci_time "pr-lint wrapper" -- make ci-pr-lint || status=$?
|
||||
exit "$status"
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-pr-linux
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
macos-short:
|
||||
name: Measure macOS short Go tests
|
||||
if: ${{ inputs.suite == 'macos-short' }}
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
source ./.buildflags
|
||||
|
||||
ci_time "macos short go test" -- go test -v -race -short -skip '^TestEmbedded' ./...
|
||||
|
||||
macos-candidates:
|
||||
name: Measure macOS no-short candidates
|
||||
if: ${{ inputs.suite == 'macos-candidates' }}
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
status=0
|
||||
ci_time "macos no-short go test" -- go test -tags=gms_pure_go -v -race -timeout=30m -skip '^TestEmbedded' ./... || status=$?
|
||||
ci_time "macos integration go test" -- go test -tags=integration,gms_pure_go -v -race -timeout=30m -skip '^TestEmbedded' ./... || status=$?
|
||||
exit "$status"
|
||||
|
||||
linux-integration:
|
||||
name: Measure Linux integration tests
|
||||
if: ${{ inputs.suite == 'linux-integration' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
ci_time "linux integration go test" -- env BEADS_TEST_SKIP=dolt gotestsum --junitfile artifacts/linux-integration-junit.xml --format testdox -- -v -race -tags=integration,gms_pure_go -timeout=30m ./...
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-sharded:
|
||||
name: Measure Linux integration shard ${{ matrix.shard }}/6
|
||||
if: ${{ inputs.suite == 'linux-integration-sharded' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 6
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
mapfile -t packages < <(
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS"
|
||||
)
|
||||
package_manifest="artifacts/linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
printf '%s\n' "${packages[@]}" | tee "$package_manifest"
|
||||
|
||||
if [[ "${#packages[@]}" -eq 0 ]]; then
|
||||
echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ci_time "linux integration shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/linux-integration-shard-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}"
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-shard-${{ matrix.shard }}-of-6
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-hybrid-packages:
|
||||
name: Measure Linux integration package shard ${{ matrix.shard }}/6 (no cmd/bd)
|
||||
if: ${{ inputs.suite == 'linux-integration-hybrid-sharded' || inputs.suite == 'linux-integration-hybrid-16-sharded' || inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 6
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
package_manifest="artifacts/linux-integration-hybrid-packages-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_package_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
GO_TEST_SHARD_EXCLUDE_REGEX="^github.com/steveyegge/beads/cmd/bd$" \
|
||||
scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS" > "$package_manifest"
|
||||
}
|
||||
ci_time "list integration package shard ${SHARD}/${TOTAL_SHARDS}" -- write_package_manifest
|
||||
cat "$package_manifest"
|
||||
mapfile -t packages < "$package_manifest"
|
||||
|
||||
if [[ "${#packages[@]}" -eq 0 ]]; then
|
||||
echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ci_time "linux integration package shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/linux-integration-hybrid-packages-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}"
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-hybrid-packages-${{ matrix.shard }}-of-6
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-hybrid-cmd-bd:
|
||||
name: Measure Linux integration cmd/bd shard ${{ matrix.shard }}/8
|
||||
if: ${{ inputs.suite == 'linux-integration-hybrid-sharded' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 8
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_test_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest"
|
||||
}
|
||||
ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest
|
||||
cat "$test_manifest"
|
||||
mapfile -t tests < "$test_manifest"
|
||||
|
||||
if [[ "${#tests[@]}" -eq 0 ]]; then
|
||||
echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_regex="^($(IFS='|'; echo "${tests[*]}"))$"
|
||||
ci_time "linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-cmd-bd-${{ matrix.shard }}-of-8
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-hybrid-16-cmd-bd:
|
||||
name: Measure Linux integration cmd/bd shard ${{ matrix.shard }}/16
|
||||
if: ${{ inputs.suite == 'linux-integration-hybrid-16-sharded' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 16
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_test_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest"
|
||||
}
|
||||
ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest
|
||||
cat "$test_manifest"
|
||||
mapfile -t tests < "$test_manifest"
|
||||
|
||||
if [[ "${#tests[@]}" -eq 0 ]]; then
|
||||
echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_regex="^($(IFS='|'; echo "${tests[*]}"))$"
|
||||
ci_time "linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-cmd-bd-${{ matrix.shard }}-of-16
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-hybrid-prebuilt-bd:
|
||||
name: Measure Linux integration prebuild cmd/bd binary
|
||||
if: ${{ inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Measure build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
source ./.buildflags
|
||||
|
||||
ci_time "build cmd/bd subprocess binary" -- go build -tags "$BEADS_BUILD_TAGS" -o artifacts/bd ./cmd/bd
|
||||
|
||||
- name: Upload prebuilt bd
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-prebuilt-bd
|
||||
path: artifacts/bd
|
||||
retention-days: 7
|
||||
if-no-files-found: error
|
||||
|
||||
linux-integration-hybrid-prebuilt-cmd-bd:
|
||||
name: Measure Linux integration prebuilt cmd/bd shard ${{ matrix.shard }}/8
|
||||
if: ${{ inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }}
|
||||
needs: linux-integration-hybrid-prebuilt-bd
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Download prebuilt bd
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-measure-linux-integration-prebuilt-bd
|
||||
path: prebuilt-bd
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 8
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/prebuilt-bd/bd
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
chmod +x "$BEADS_TEST_BD_BINARY"
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_test_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest"
|
||||
}
|
||||
ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest
|
||||
cat "$test_manifest"
|
||||
mapfile -t tests < "$test_manifest"
|
||||
|
||||
if [[ "${#tests[@]}" -eq 0 ]]; then
|
||||
echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_regex="^($(IFS='|'; echo "${tests[*]}"))$"
|
||||
ci_time "linux integration prebuilt cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/linux-integration-prebuilt-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-prebuilt-cmd-bd-${{ matrix.shard }}-of-8
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-integration-coverage:
|
||||
name: Measure Linux integration coverage
|
||||
if: ${{ inputs.suite == 'linux-integration-coverage' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
status=0
|
||||
ci_time "linux integration coverage go test" -- env BEADS_TEST_SKIP=dolt gotestsum --junitfile artifacts/linux-integration-coverage-junit.xml --format testdox -- -v -race -tags=integration,gms_pure_go -coverprofile=artifacts/coverage.out -timeout=30m ./... || status=$?
|
||||
if [[ -f artifacts/coverage.out ]]; then
|
||||
ci_time "coverage summary" -- go tool cover -func=artifacts/coverage.out || status=$?
|
||||
else
|
||||
echo "coverage.out was not generated; skipping coverage summary"
|
||||
fi
|
||||
exit "$status"
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-linux-integration-coverage
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
cross-version-smoke:
|
||||
name: Measure cross-version smoke
|
||||
if: ${{ inputs.suite == 'cross-version-smoke' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Cache previous release binaries
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
with:
|
||||
path: ~/.cache/beads-regression
|
||||
key: smoke-binaries-measure-${{ runner.os }}
|
||||
|
||||
- name: Measure commands
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SMOKE_VERSION: ${{ inputs.smoke_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
source ./.buildflags
|
||||
|
||||
ci_time "build candidate binary" -- go build -o /tmp/bd-candidate ./cmd/bd
|
||||
export CANDIDATE_BIN=/tmp/bd-candidate
|
||||
if [[ -z "$SMOKE_VERSION" ]]; then
|
||||
SMOKE_VERSION="$(gh release list --repo "$GITHUB_REPOSITORY" --limit 1 --json tagName --jq '.[0].tagName')"
|
||||
fi
|
||||
if [[ -z "$SMOKE_VERSION" ]]; then
|
||||
echo "Could not resolve a previous release tag for cross-version smoke"
|
||||
exit 1
|
||||
fi
|
||||
ci_time "upgrade smoke ${SMOKE_VERSION}" -- ./scripts/upgrade-smoke-test.sh "$SMOKE_VERSION"
|
||||
|
||||
nix:
|
||||
name: Measure nix build
|
||||
if: ${{ inputs.suite == 'nix' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "nix build .#default" -- nix build .#default --print-build-logs
|
||||
|
||||
mcp-package:
|
||||
name: Measure MCP package checks
|
||||
if: ${{ inputs.suite == 'mcp-package' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install uv" -- pip install uv==0.11.16
|
||||
ci_time "mcp package gate" -- make ci-package-mcp
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-mcp-package
|
||||
path: integrations/beads-mcp/dist/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
npm-package:
|
||||
name: Measure npm package checks
|
||||
if: ${{ inputs.suite == 'npm-package' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
ci_time "npm package gate" -- make ci-package-npm
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-npm-package
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
website:
|
||||
name: Measure website checks
|
||||
if: ${{ inputs.suite == 'website' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Measure commands
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "website package gate" -- make ci-website
|
||||
|
||||
- name: Upload measurement artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-measure-website
|
||||
path: website/build/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
394
.github/workflows/ci.yml
vendored
394
.github/workflows/ci.yml
vendored
|
|
@ -1,394 +0,0 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
detect-ci-tier:
|
||||
name: Detect CI tier
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
full_embedded: ${{ steps.tier.outputs.full_embedded }}
|
||||
reason: ${{ steps.tier.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide embedded Dolt coverage
|
||||
id: tier
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: bash .github/scripts/ci-embedded-tier.sh
|
||||
|
||||
# Fast check: every `go build|test|run|generate|install` invocation in
|
||||
# tracked scripts/hooks/CI carries -tags=gms_pure_go. Prevents ICU-linkage
|
||||
# regressions from re-entering the build (see docs/ICU-POLICY.md).
|
||||
check-build-tags:
|
||||
name: Check build-tag policy
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- run: ./scripts/check-build-tags.sh
|
||||
- run: ./scripts/check-go-install-guidance.sh
|
||||
|
||||
# Lock in the cgo-test-contamination fix (mybd-ycx / GH#3683 follow-up).
|
||||
# cmd/bd carries a mix of cgo-only test helpers (embedded Dolt, sql.DB) and
|
||||
# pure-Go tests. Untagged test files that reach for cgo-only helpers break
|
||||
# the entire package's CGO_ENABLED=0 compile, silently neutering pure-Go
|
||||
# tests (the original symptom in PR #3704). This job compiles the cmd/bd
|
||||
# test binary with CGO_ENABLED=0 and runs the pure-Go subset, so a
|
||||
# regression that re-introduces cgo coupling fails fast.
|
||||
check-cmd-bd-puregeo-tests:
|
||||
name: Check cmd/bd pure-Go tests compile (CGO_ENABLED=0)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build cmd/bd (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: go build -tags gms_pure_go -o /tmp/bd-puregeo ./cmd/bd
|
||||
|
||||
- name: Compile cmd/bd test binary (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: go test -tags gms_pure_go -c -o /tmp/bd-cmd-puregeo-test ./cmd/bd
|
||||
|
||||
- name: Run pure-Go cmd/bd test subset (CGO_ENABLED=0)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
# Restrict to tests that exercise pure-Go code paths. Tests that
|
||||
# need a Dolt store skip themselves at runtime when no test server
|
||||
# is available; the goal here is to catch compile-time contamination,
|
||||
# not run the full suite.
|
||||
run: |
|
||||
go test -tags gms_pure_go -count=1 -short -run '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir)' ./cmd/bd
|
||||
|
||||
# Fast check to ensure all version files are in sync
|
||||
check-version-consistency:
|
||||
name: Check version consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Check all versions match
|
||||
run: ./scripts/check-versions.sh
|
||||
|
||||
# Check documentation references match actual CLI flags
|
||||
check-doc-flags:
|
||||
name: Check doc flags freshness
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build bd
|
||||
run: CGO_ENABLED=0 go build -tags gms_pure_go -o bd ./cmd/bd/
|
||||
|
||||
- name: Validate docs against CLI
|
||||
run: ./scripts/check-doc-flags.sh ./bd
|
||||
|
||||
# Fast check to catch accidental .beads/issues.jsonl changes from contributors
|
||||
check-no-beads-changes:
|
||||
name: Check for .beads changes
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check for .beads/issues.jsonl changes
|
||||
run: |
|
||||
if git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -q "^\.beads/issues\.jsonl$"; then
|
||||
echo "This PR includes changes to .beads/issues.jsonl"
|
||||
echo ""
|
||||
echo "This file is the project's issue database and should not be modified in PRs."
|
||||
echo ""
|
||||
echo "To fix, run:"
|
||||
echo " git checkout origin/main -- .beads/issues.jsonl"
|
||||
echo " git commit --amend"
|
||||
echo " git push --force"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
echo "No .beads/issues.jsonl changes detected"
|
||||
|
||||
# Cross-platform test matrix (Linux/macOS only - Windows uses smoke tests)
|
||||
test:
|
||||
name: Test (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
include:
|
||||
# Linux: full test suite with coverage
|
||||
- os: ubuntu-latest
|
||||
coverage: true
|
||||
test-flags: '-v -race -short -coverprofile=coverage.out'
|
||||
# macOS: full test suite, no coverage (faster)
|
||||
- os: macos-latest
|
||||
coverage: false
|
||||
test-flags: '-v -race -short'
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt (Linux/macOS)
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Verify dolt on PATH
|
||||
run: dolt version
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Install gotestsum
|
||||
if: matrix.coverage
|
||||
run: go install gotest.tools/gotestsum@latest
|
||||
|
||||
- name: Build
|
||||
run: go build -v -tags gms_pure_go ./cmd/bd
|
||||
|
||||
- name: Test (with coverage + JUnit XML)
|
||||
if: matrix.coverage
|
||||
run: |
|
||||
gotestsum \
|
||||
--junitfile junit.xml \
|
||||
--format testdox \
|
||||
-- -tags gms_pure_go -race -short -coverprofile=coverage.out -skip '^TestEmbedded' ./...
|
||||
|
||||
- name: Test
|
||||
if: ${{ !matrix.coverage }}
|
||||
run: go test -tags gms_pure_go ${{ matrix.test-flags }} -skip '^TestEmbedded' ./...
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
if: matrix.coverage && !cancelled()
|
||||
uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
files: coverage.out
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
fail_ci_if_error: false
|
||||
|
||||
- name: Upload test results to Codecov
|
||||
if: matrix.coverage && !cancelled()
|
||||
uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
files: junit.xml
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
report_type: test_results
|
||||
fail_ci_if_error: false
|
||||
|
||||
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
|
||||
#
|
||||
# Split into: build → storage tests + parallel cmd test shards.
|
||||
# cmd/bd embedded tests use a committed shard manifest; newly-added tests
|
||||
# still auto-distribute via hash fallback until the manifest is updated.
|
||||
|
||||
build-embedded:
|
||||
name: Build (Embedded Dolt)
|
||||
needs: detect-ci-tier
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build embedded bd binary
|
||||
run: go build -tags gms_pure_go -race -o /tmp/bd-embedded-test ./cmd/bd/
|
||||
|
||||
- name: Build embedded storage test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/embeddeddolt-test ./internal/storage/embeddeddolt/
|
||||
|
||||
- name: Build embedded cmd test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/
|
||||
|
||||
- name: Upload binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: |
|
||||
/tmp/bd-embedded-test
|
||||
/tmp/embeddeddolt-test
|
||||
/tmp/bd-cmd-test
|
||||
retention-days: 1
|
||||
|
||||
test-embedded-storage:
|
||||
name: Test (Embedded Dolt Storage)
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/embeddeddolt-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test
|
||||
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=10m
|
||||
|
||||
test-embedded-cmd:
|
||||
name: Test (Embedded Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }})
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/bd-embedded-test /tmp/embeddeddolt-test /tmp/bd-cmd-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_BD_BINARY: /tmp/bd-embedded-test
|
||||
run: bash .github/scripts/embedded-test-shard.sh ${{ matrix.shard }} 20
|
||||
|
||||
# Windows smoke tests only - full test suite times out (see bd-bmev)
|
||||
# Linux/macOS run comprehensive tests; Windows just verifies binary works
|
||||
#
|
||||
# Windows uses -tags gms_pure_go to avoid the ICU regex dependency.
|
||||
# go-icu-regex's regex_windows.go also uses Go stdlib regexp (build tag: windows).
|
||||
# CGO is still required for gozstd (bundled C source) and the embedded dolt engine.
|
||||
test-windows:
|
||||
name: Test (Windows - smoke)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Build (pure Go regex)
|
||||
run: go build -v -tags gms_pure_go -o bd.exe ./cmd/bd
|
||||
|
||||
- name: Smoke test - version
|
||||
run: ./bd.exe version
|
||||
|
||||
- name: Smoke test - help
|
||||
run: ./bd.exe help
|
||||
|
||||
fmt-check:
|
||||
name: Check formatting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Check gofmt
|
||||
run: make fmt-check
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # v9
|
||||
with:
|
||||
version: latest
|
||||
args: --timeout=5m --build-tags=gms_pure_go
|
||||
|
||||
test-nix:
|
||||
name: Test Nix Flake
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- uses: DeterminateSystems/determinate-nix-action@f4c468f2287f0f14a113841b41f2dc8957119519 # v3
|
||||
- name: Run bd help via Nix
|
||||
id: nix_help
|
||||
run: |
|
||||
nix run .#default -- --help > help.txt
|
||||
- name: Verify help text
|
||||
if: steps.nix_help.outcome == 'success'
|
||||
run: |
|
||||
FIRST_LINE=$(head -n 1 help.txt)
|
||||
EXPECTED="Issues chained together like beads. A lightweight issue tracker with first-class dependency support."
|
||||
if [ "$FIRST_LINE" != "$EXPECTED" ]; then
|
||||
echo "First line of help.txt doesn't match expected output"
|
||||
echo "Expected: $EXPECTED"
|
||||
echo "Got: $FIRST_LINE"
|
||||
exit 1
|
||||
fi
|
||||
echo "Help text first line is correct"
|
||||
6
.github/workflows/cross-version-smoke.yml
vendored
6
.github/workflows/cross-version-smoke.yml
vendored
|
|
@ -22,6 +22,10 @@ concurrency:
|
|||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
smoke:
|
||||
name: Upgrade smoke (${{ matrix.prev_version }} → candidate)
|
||||
|
|
@ -36,7 +40,7 @@ jobs:
|
|||
needs: versions
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
|
||||
|
|
|
|||
21
.github/workflows/deploy-docs.yml
vendored
21
.github/workflows/deploy-docs.yml
vendored
|
|
@ -6,6 +6,13 @@ on:
|
|||
- main
|
||||
paths:
|
||||
- 'website/**'
|
||||
- 'docs/ANTIVIRUS.md'
|
||||
- 'docs/COMMUNITY_TOOLS.md'
|
||||
- 'docs/LABELS.md'
|
||||
- 'docs/METADATA.md'
|
||||
- 'docs/SYNC_CONCEPTS.md'
|
||||
- 'docs/UNINSTALLING.md'
|
||||
- 'scripts/sync-website-docs.sh'
|
||||
- 'scripts/generate-llms-full.sh'
|
||||
workflow_dispatch:
|
||||
|
||||
|
|
@ -25,7 +32,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
|
|
@ -34,16 +41,8 @@ jobs:
|
|||
cache: 'npm'
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: website
|
||||
run: npm ci
|
||||
|
||||
- name: Generate llms-full.txt
|
||||
run: ./scripts/generate-llms-full.sh
|
||||
|
||||
- name: Build website
|
||||
working-directory: website
|
||||
run: npm run build
|
||||
- name: Run website package gate
|
||||
run: make ci-website
|
||||
|
||||
- name: Prepare link check (map baseUrl /beads/ to build output)
|
||||
run: |
|
||||
|
|
|
|||
978
.github/workflows/main.yml
vendored
Normal file
978
.github/workflows/main.yml
vendored
Normal file
|
|
@ -0,0 +1,978 @@
|
|||
name: Main
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
detect-ci-tier:
|
||||
name: Detect CI tier
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
full_embedded: ${{ steps.tier.outputs.full_embedded }}
|
||||
reason: ${{ steps.tier.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide embedded Dolt coverage
|
||||
id: tier
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: bash .github/scripts/ci-embedded-tier.sh
|
||||
|
||||
# Same guard as pr.yml's check-migration-hygiene: direct pushes to main
|
||||
# (and PR merges whose base moved) must not bypass the migration lints.
|
||||
# BASE_SHA is the pre-push tip; on force pushes or history rewrites the
|
||||
# script warns and skips the frozen-migrations diff but still runs the
|
||||
# duplicate-version and nondeterministic-SQL checks.
|
||||
check-migration-hygiene:
|
||||
name: Check migration hygiene
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run migration hygiene checks
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.before }}
|
||||
run: ./scripts/check-migration-hygiene.sh
|
||||
|
||||
build-artifacts:
|
||||
name: Build Artifacts
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install golangci-lint
|
||||
run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9.0
|
||||
|
||||
- name: Run policy checks
|
||||
run: make ci-pr-policy
|
||||
|
||||
- name: Run lint checks
|
||||
run: make ci-pr-lint
|
||||
|
||||
- name: Build reusable Linux artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source ./.buildflags
|
||||
go_version="$(go version)"
|
||||
commit="$(git rev-parse HEAD)"
|
||||
go build -tags "$BEADS_BUILD_TAGS" -o artifacts/bd-linux-gms-pure ./cmd/bd
|
||||
chmod +x artifacts/bd-linux-gms-pure
|
||||
(
|
||||
cd artifacts
|
||||
sha256sum bd-linux-gms-pure > SHA256SUMS
|
||||
)
|
||||
{
|
||||
echo "commit=${commit}"
|
||||
echo "go_version=${go_version}"
|
||||
echo "build_tags=${BEADS_BUILD_TAGS}"
|
||||
echo "artifact=bd-linux-gms-pure"
|
||||
} > artifacts/build-manifest.txt
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: artifacts/
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
|
||||
# Fast check: every `go build|test|run|generate|install` invocation in
|
||||
# tracked scripts/hooks/CI carries -tags=gms_pure_go. Prevents ICU-linkage
|
||||
# regressions from re-entering the build (see docs/ICU-POLICY.md).
|
||||
check-build-tags:
|
||||
name: Check build-tag policy
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
- run: ./scripts/check-build-tags.sh
|
||||
- run: ./scripts/check-go-install-guidance.sh
|
||||
|
||||
# Lock in the cgo-test-contamination fix (mybd-ycx / GH#3683 follow-up).
|
||||
# cmd/bd carries a mix of cgo-only test helpers (embedded Dolt, sql.DB) and
|
||||
# pure-Go tests. Untagged test files that reach for cgo-only helpers break
|
||||
# the entire package's CGO_ENABLED=0 compile, silently neutering pure-Go
|
||||
# tests (the original symptom in PR #3704). This job compiles the cmd/bd
|
||||
# test binary with CGO_ENABLED=0 and runs the pure-Go subset, so a
|
||||
# regression that re-introduces cgo coupling fails fast.
|
||||
check-cmd-bd-puregeo-tests:
|
||||
name: Check cmd/bd pure-Go tests compile (CGO_ENABLED=0)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build cmd/bd (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: go build -tags gms_pure_go -o /tmp/bd-puregeo ./cmd/bd
|
||||
|
||||
- name: Compile pure-Go test binaries (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-cmd-puregeo-test ./cmd/bd
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-embeddeddolt-puregeo-test ./internal/storage/embeddeddolt
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-tracker-puregeo-test ./internal/tracker
|
||||
|
||||
- name: Run pure-Go cmd/bd test subset (CGO_ENABLED=0)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
# Restrict to tests that exercise pure-Go code paths. Tests that
|
||||
# need a Dolt store skip themselves at runtime when no test server
|
||||
# is available; the goal here is to catch compile-time contamination,
|
||||
# not run the full suite.
|
||||
run: |
|
||||
go test -tags gms_pure_go -count=1 -short -run '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir)' ./cmd/bd
|
||||
|
||||
# Fast check to ensure all version files are in sync
|
||||
check-version-consistency:
|
||||
name: Check version consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Check all versions match
|
||||
run: ./scripts/check-versions.sh
|
||||
|
||||
# Catch duplicate migration version numbers before any Go build.
|
||||
# Two long-lived branches both claiming 'the next number' produce a silent
|
||||
# under-apply when merged; this job fails at PR time with the conflicting
|
||||
# filenames so it is caught before any test even compiles.
|
||||
check-no-duplicate-migrations:
|
||||
name: Check no duplicate migration versions
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Check for duplicate migration version numbers
|
||||
run: |
|
||||
dup=$(
|
||||
find internal/storage/schema/migrations -maxdepth 1 -name '*.up.sql' -printf '%f\n' \
|
||||
| sed 's/^\([0-9]*\)_.*/\1/' \
|
||||
| sort | uniq -d
|
||||
)
|
||||
if [ -n "$dup" ]; then
|
||||
echo "Duplicate migration version(s) detected: $dup"
|
||||
echo "Conflicting files:"
|
||||
while IFS= read -r v; do
|
||||
find internal/storage/schema/migrations -name "${v}_*.up.sql" -print
|
||||
done <<< "$dup"
|
||||
echo "Renumber one of the colliding files before merging."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check documentation references match actual CLI flags
|
||||
check-doc-flags:
|
||||
name: Check doc flags freshness
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build bd
|
||||
run: CGO_ENABLED=0 go build -tags gms_pure_go -o bd ./cmd/bd/
|
||||
|
||||
- name: Validate docs against CLI
|
||||
run: |
|
||||
./scripts/check-doc-flags.sh ./bd
|
||||
./scripts/check-doc-freshness.sh
|
||||
|
||||
detect-package-gates:
|
||||
name: Detect package gates
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
mcp_package: ${{ steps.detect.outputs.mcp_package }}
|
||||
npm_package: ${{ steps.detect.outputs.npm_package }}
|
||||
website: ${{ steps.detect.outputs.website }}
|
||||
reason: ${{ steps.detect.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide package gates
|
||||
id: detect
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ github.event.before }}
|
||||
PUSH_AFTER_SHA: ${{ github.sha }}
|
||||
run: ./scripts/ci/detect-package-gates.sh
|
||||
|
||||
package-mcp:
|
||||
name: Package Gate (MCP)
|
||||
runs-on: ubuntu-latest
|
||||
needs: [detect-package-gates, build-artifacts]
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.mcp_package }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.mcp_package }}" != "true" ]]; then
|
||||
echo "MCP package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Python
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: python -m pip install uv==0.11.16
|
||||
|
||||
- name: Download build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run MCP package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-package-mcp
|
||||
|
||||
package-npm:
|
||||
name: Package Gate (npm)
|
||||
runs-on: ubuntu-latest
|
||||
needs: [detect-package-gates, build-artifacts]
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.npm_package }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.npm_package }}" != "true" ]]; then
|
||||
echo "npm package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Node.js
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Download build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run npm package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-package-npm
|
||||
|
||||
package-website:
|
||||
name: Package Gate (website)
|
||||
runs-on: ubuntu-latest
|
||||
needs: detect-package-gates
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.website }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.website }}" != "true" ]]; then
|
||||
echo "website package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Node.js
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Run website package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: make ci-website
|
||||
|
||||
pr-policy-wrapper:
|
||||
name: PR Policy (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Run PR policy wrapper
|
||||
run: make ci-pr-policy
|
||||
|
||||
pr-core-wrapper:
|
||||
name: PR Core (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run PR core wrapper
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-pr-core
|
||||
|
||||
pr-lint-wrapper:
|
||||
name: PR Lint (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install golangci-lint
|
||||
run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9.0
|
||||
|
||||
- name: Run PR lint wrapper
|
||||
run: make ci-pr-lint
|
||||
|
||||
# Cross-platform test matrix (Linux/macOS only - Windows uses smoke tests)
|
||||
test:
|
||||
name: Test (${{ matrix.os }})
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: build-artifacts
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
include:
|
||||
# Linux: full test suite with coverage
|
||||
- os: ubuntu-latest
|
||||
coverage: true
|
||||
test-flags: '-v -race -short -coverprofile=coverage.out'
|
||||
# macOS: full test suite, no coverage (faster)
|
||||
- os: macos-latest
|
||||
coverage: false
|
||||
test-flags: '-v -race -short'
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt (Linux/macOS)
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Verify dolt on PATH
|
||||
run: dolt version
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Install gotestsum
|
||||
if: matrix.coverage
|
||||
run: go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
- name: Download build artifacts
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Build
|
||||
if: matrix.os != 'ubuntu-latest'
|
||||
run: go build -v -tags gms_pure_go ./cmd/bd
|
||||
|
||||
- name: Test (with coverage + JUnit XML)
|
||||
if: matrix.coverage
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: |
|
||||
gotestsum \
|
||||
--junitfile junit.xml \
|
||||
--format testdox \
|
||||
-- -tags gms_pure_go -race -short -coverprofile=coverage.out -skip '^TestEmbedded' ./...
|
||||
|
||||
- name: Test
|
||||
if: ${{ !matrix.coverage }}
|
||||
run: go test -tags gms_pure_go ${{ matrix.test-flags }} -skip '^TestEmbedded' ./...
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
if: matrix.coverage && !cancelled()
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
files: coverage.out
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
fail_ci_if_error: false
|
||||
|
||||
- name: Upload test results to Codecov
|
||||
if: matrix.coverage && !cancelled()
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
files: junit.xml
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
report_type: test_results
|
||||
fail_ci_if_error: false
|
||||
|
||||
# Focused job for the hexagonal storage layer (internal/storage/domain/* and
|
||||
# internal/storage/uow). These packages back the proxied-server init path and
|
||||
# also live behind the existing ./... matrix, but TestDomainDB requires the
|
||||
# Dolt sql-server image cached locally (testcontainers checks `docker image
|
||||
# inspect` and skips otherwise). Pulling the image up front guarantees the
|
||||
# suite actually runs and surfaces failures here with a clear job name.
|
||||
test-domain-uow:
|
||||
name: Test (storage domain + uow)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt CLI
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Verify dolt on PATH
|
||||
run: dolt version
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Pull Dolt sql-server image
|
||||
# Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
# Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips.
|
||||
run: docker pull dolthub/dolt-sql-server:2.1.10
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Test domain + uow + tracker
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: go test -tags gms_pure_go -race -count=1 -v ./internal/storage/domain/... ./internal/storage/uow/... ./internal/tracker/...
|
||||
|
||||
main-linux-integration-packages:
|
||||
name: Main Linux integration packages (${{ matrix.shard }}/6)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Test package shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 6
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
package_manifest="artifacts/main-linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_package_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
GO_TEST_SHARD_EXCLUDE_REGEX="^github.com/steveyegge/beads/cmd/bd$" \
|
||||
scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS" > "$package_manifest"
|
||||
}
|
||||
ci_time "list integration package shard ${SHARD}/${TOTAL_SHARDS}" -- write_package_manifest
|
||||
cat "$package_manifest"
|
||||
mapfile -t packages < "$package_manifest"
|
||||
|
||||
if [[ "${#packages[@]}" -eq 0 ]]; then
|
||||
echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ci_time "main linux integration package shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/main-linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}"
|
||||
|
||||
- name: Upload integration artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: main-linux-integration-packages-${{ matrix.shard }}-of-6
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
main-linux-integration-cmd-bd:
|
||||
name: Main Linux integration cmd/bd (${{ matrix.shard }}/8)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Test cmd/bd shard
|
||||
env:
|
||||
SHARD: ${{ matrix.shard }}
|
||||
TOTAL_SHARDS: 8
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source scripts/ci/lib/timing.sh
|
||||
|
||||
ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0
|
||||
|
||||
test_manifest="artifacts/main-linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt"
|
||||
write_test_manifest() {
|
||||
GO_TEST_SHARD_TAGS=integration,gms_pure_go \
|
||||
scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest"
|
||||
}
|
||||
ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest
|
||||
cat "$test_manifest"
|
||||
mapfile -t tests < "$test_manifest"
|
||||
|
||||
if [[ "${#tests[@]}" -eq 0 ]]; then
|
||||
echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_regex="^($(IFS='|'; echo "${tests[*]}"))$"
|
||||
ci_time "main linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \
|
||||
env BEADS_TEST_SKIP=dolt gotestsum \
|
||||
--junitfile "artifacts/main-linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \
|
||||
--format testdox \
|
||||
-- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd
|
||||
|
||||
- name: Upload integration artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: main-linux-integration-cmd-bd-${{ matrix.shard }}-of-8
|
||||
path: artifacts/
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
# # End-to-end coverage for proxied-server CLI subcommands. Each sub-test
|
||||
# # spawns a real dolt sql-server via the proxy and exercises the bd CLI
|
||||
# # subprocess against it (see cmd/bd/*_proxied_integration_test.go).
|
||||
# #
|
||||
# # The -run pattern intentionally matches the TestProxiedServer* prefix so
|
||||
# # new proxied integration suites (TestProxiedServerCreate, ...Update,
|
||||
# # ...Show, etc.) are auto-included without further CI edits. Adopt the
|
||||
# # `TestProxiedServer<Subcommand>` naming convention for any new entry
|
||||
# # points and they will be picked up here.
|
||||
# #
|
||||
# # Companion to test-domain-uow (which tests the storage/uow layer); this
|
||||
# # job is the CLI-side gate that ensures the proxied path stays at parity
|
||||
# # with the embedded path's behavior.
|
||||
# #
|
||||
# # The package-level testcontainers Dolt singleton (started by
|
||||
# # cmd/bd/test_dolt_server_cgo_test.go) is automatically skipped when
|
||||
# # BEADS_TEST_PROXIED_SERVER=1 is set, so this lane is ~50s faster than
|
||||
# # it would otherwise be.
|
||||
# test-proxied-server-cmd:
|
||||
# name: Test (proxied-server cmd)
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
#
|
||||
# - name: Set up Go
|
||||
# uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
# with:
|
||||
# go-version-file: 'go.mod'
|
||||
#
|
||||
# - name: Install Dolt CLI
|
||||
# run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
#
|
||||
# - name: Verify dolt on PATH
|
||||
# run: dolt version
|
||||
#
|
||||
# - name: Configure Git and Dolt identity
|
||||
# run: |
|
||||
# git config --global user.name "CI Bot"
|
||||
# git config --global user.email "ci@beads.test"
|
||||
# dolt config --global --add user.name "CI Bot"
|
||||
# dolt config --global --add user.email "ci@beads.test"
|
||||
#
|
||||
# - name: Pre-build bd binary for proxied integration tests
|
||||
# # The test's buildEmbeddedBD helper picks up BEADS_TEST_BD_BINARY,
|
||||
# # skipping a per-test ~45s rebuild for each invocation.
|
||||
# run: go build -tags gms_pure_go -o /tmp/bd-proxied-test ./cmd/bd
|
||||
#
|
||||
# - name: Test proxied-server bd subcommands
|
||||
# env:
|
||||
# BEADS_TEST_PROXIED_SERVER: "1"
|
||||
# BEADS_TEST_BD_BINARY: /tmp/bd-proxied-test
|
||||
# # ^TestProxiedServer matches every proxied-server top-level test
|
||||
# # (Create today; future Update/Show/etc. auto-join without edits).
|
||||
# run: go test -tags gms_pure_go -count=1 -timeout=10m -v -run '^TestProxiedServer' ./cmd/bd/
|
||||
|
||||
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
|
||||
#
|
||||
# Split into: build → storage tests + parallel cmd test shards.
|
||||
# cmd/bd embedded tests use a committed shard manifest; newly-added tests
|
||||
# still auto-distribute via hash fallback until the manifest is updated.
|
||||
|
||||
build-embedded:
|
||||
name: Build (Embedded Dolt)
|
||||
needs: detect-ci-tier
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build embedded bd binary
|
||||
run: go build -tags gms_pure_go -race -o /tmp/bd-embedded-test ./cmd/bd/
|
||||
|
||||
- name: Build embedded storage test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/embeddeddolt-test ./internal/storage/embeddeddolt/
|
||||
|
||||
- name: Build embedded cmd test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/
|
||||
|
||||
- name: Upload binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: |
|
||||
/tmp/bd-embedded-test
|
||||
/tmp/embeddeddolt-test
|
||||
/tmp/bd-cmd-test
|
||||
retention-days: 1
|
||||
|
||||
test-embedded-storage:
|
||||
name: Test (Embedded Dolt Storage)
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/embeddeddolt-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test
|
||||
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=20m
|
||||
|
||||
test-embedded-cmd:
|
||||
name: Test (Embedded Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }})
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/bd-embedded-test /tmp/embeddeddolt-test /tmp/bd-cmd-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_BD_BINARY: /tmp/bd-embedded-test
|
||||
run: bash .github/scripts/embedded-test-shard.sh ${{ matrix.shard }} 20
|
||||
|
||||
# Windows smoke tests only - full test suite times out (see bd-bmev)
|
||||
# Linux/macOS run comprehensive tests; Windows just verifies binary works
|
||||
#
|
||||
# Windows uses -tags gms_pure_go to avoid the ICU regex dependency.
|
||||
# go-icu-regex's regex_windows.go also uses Go stdlib regexp (build tag: windows).
|
||||
# CGO is still required for gozstd (bundled C source) and the embedded dolt engine.
|
||||
test-windows:
|
||||
name: Test (Windows - smoke)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Build (pure Go regex)
|
||||
run: go build -v -tags gms_pure_go -o bd.exe ./cmd/bd
|
||||
|
||||
- name: Smoke test - version
|
||||
run: ./bd.exe version
|
||||
|
||||
- name: Smoke test - help
|
||||
run: ./bd.exe help
|
||||
|
||||
fmt-check:
|
||||
name: Check formatting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Check gofmt
|
||||
run: make fmt-check
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@82606bf257cbaff209d206a39f5134f0cfbfd2ee # v9
|
||||
with:
|
||||
version: latest
|
||||
args: --timeout=5m --build-tags=gms_pure_go
|
||||
|
||||
test-nix:
|
||||
name: Test Nix Flake
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
- uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
- name: Run bd help via Nix
|
||||
id: nix_help
|
||||
run: |
|
||||
nix run .#default -- --help > help.txt
|
||||
- name: Verify help text
|
||||
if: steps.nix_help.outcome == 'success'
|
||||
run: |
|
||||
FIRST_LINE=$(head -n 1 help.txt)
|
||||
EXPECTED="Issues chained together like beads. A lightweight issue tracker with first-class dependency support."
|
||||
if [ "$FIRST_LINE" != "$EXPECTED" ]; then
|
||||
echo "First line of help.txt doesn't match expected output"
|
||||
echo "Expected: $EXPECTED"
|
||||
echo "Got: $FIRST_LINE"
|
||||
exit 1
|
||||
fi
|
||||
echo "Help text first line is correct"
|
||||
6
.github/workflows/migration-test.yml
vendored
6
.github/workflows/migration-test.yml
vendored
|
|
@ -19,13 +19,17 @@ on:
|
|||
- direct-only
|
||||
- stepping-only
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
migration-test:
|
||||
name: Migration fidelity
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
|
|||
45
.github/workflows/nightly.yml
vendored
45
.github/workflows/nightly.yml
vendored
|
|
@ -4,15 +4,54 @@ on:
|
|||
schedule:
|
||||
# Run at 2am UTC daily
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
suite:
|
||||
description: "Nightly suite or measurement suite"
|
||||
required: true
|
||||
type: choice
|
||||
default: full-test
|
||||
options:
|
||||
- full-test
|
||||
- pr-linux
|
||||
- macos-short
|
||||
- macos-candidates
|
||||
- linux-integration
|
||||
- linux-integration-sharded
|
||||
- linux-integration-hybrid-sharded
|
||||
- linux-integration-hybrid-16-sharded
|
||||
- linux-integration-hybrid-prebuilt-sharded
|
||||
- linux-integration-coverage
|
||||
- cross-version-smoke
|
||||
- nix
|
||||
- mcp-package
|
||||
- npm-package
|
||||
- website
|
||||
smoke_version:
|
||||
description: "Optional previous release for cross-version-smoke"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
measure:
|
||||
name: Measure selected CI suite
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.suite != 'full-test' }}
|
||||
uses: ./.github/workflows/ci-measurements.yml
|
||||
with:
|
||||
suite: ${{ inputs.suite }}
|
||||
smoke_version: ${{ inputs.smoke_version }}
|
||||
|
||||
full-test:
|
||||
name: Full Test Suite
|
||||
if: ${{ github.event_name == 'schedule' || inputs.suite == 'full-test' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
|
|
@ -58,7 +97,7 @@ jobs:
|
|||
fi
|
||||
|
||||
- name: Upload coverage
|
||||
uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6
|
||||
if: success()
|
||||
continue-on-error: true
|
||||
with:
|
||||
|
|
|
|||
8
.github/workflows/nix-build.yml
vendored
8
.github/workflows/nix-build.yml
vendored
|
|
@ -18,6 +18,10 @@ on:
|
|||
- 'flake.lock'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
nix-build:
|
||||
name: nix build .#default
|
||||
|
|
@ -25,8 +29,8 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@f4c468f2287f0f14a113841b41f2dc8957119519 # v3
|
||||
uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
- name: Build
|
||||
run: nix build .#default --print-build-logs
|
||||
|
|
|
|||
339
.github/workflows/pr-risk.yml
vendored
Normal file
339
.github/workflows/pr-risk.yml
vendored
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
name: PR Risk
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
detect-ci-tier:
|
||||
name: Detect CI tier
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
full_embedded: ${{ steps.tier.outputs.full_embedded }}
|
||||
reason: ${{ steps.tier.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide embedded Dolt coverage
|
||||
id: tier
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: bash .github/scripts/ci-embedded-tier.sh
|
||||
|
||||
# # End-to-end coverage for proxied-server CLI subcommands. Each sub-test
|
||||
# # spawns a real dolt sql-server via the proxy and exercises the bd CLI
|
||||
# # subprocess against it (see cmd/bd/*_proxied_integration_test.go).
|
||||
# #
|
||||
# # The -run pattern intentionally matches the TestProxiedServer* prefix so
|
||||
# # new proxied integration suites (TestProxiedServerCreate, ...Update,
|
||||
# # ...Show, etc.) are auto-included without further CI edits. Adopt the
|
||||
# # `TestProxiedServer<Subcommand>` naming convention for any new entry
|
||||
# # points and they will be picked up here.
|
||||
# #
|
||||
# # Companion to test-domain-uow (which tests the storage/uow layer); this
|
||||
# # job is the CLI-side gate that ensures the proxied path stays at parity
|
||||
# # with the embedded path's behavior.
|
||||
# #
|
||||
# # The package-level testcontainers Dolt singleton (started by
|
||||
# # cmd/bd/test_dolt_server_cgo_test.go) is automatically skipped when
|
||||
# # BEADS_TEST_PROXIED_SERVER=1 is set, so this lane is ~50s faster than
|
||||
# # it would otherwise be.
|
||||
# test-proxied-server-cmd:
|
||||
# name: Test (proxied-server cmd)
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
#
|
||||
# - name: Set up Go
|
||||
# uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
# with:
|
||||
# go-version-file: 'go.mod'
|
||||
#
|
||||
# - name: Install Dolt CLI
|
||||
# run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
#
|
||||
# - name: Verify dolt on PATH
|
||||
# run: dolt version
|
||||
#
|
||||
# - name: Configure Git and Dolt identity
|
||||
# run: |
|
||||
# git config --global user.name "CI Bot"
|
||||
# git config --global user.email "ci@beads.test"
|
||||
# dolt config --global --add user.name "CI Bot"
|
||||
# dolt config --global --add user.email "ci@beads.test"
|
||||
#
|
||||
# - name: Pre-build bd binary for proxied integration tests
|
||||
# # The test's buildEmbeddedBD helper picks up BEADS_TEST_BD_BINARY,
|
||||
# # skipping a per-test ~45s rebuild for each invocation.
|
||||
# run: go build -tags gms_pure_go -o /tmp/bd-proxied-test ./cmd/bd
|
||||
#
|
||||
# - name: Test proxied-server bd subcommands
|
||||
# env:
|
||||
# BEADS_TEST_PROXIED_SERVER: "1"
|
||||
# BEADS_TEST_BD_BINARY: /tmp/bd-proxied-test
|
||||
# # ^TestProxiedServer matches every proxied-server top-level test
|
||||
# # (Create today; future Update/Show/etc. auto-join without edits).
|
||||
# run: go test -tags gms_pure_go -count=1 -timeout=10m -v -run '^TestProxiedServer' ./cmd/bd/
|
||||
|
||||
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
|
||||
#
|
||||
# Split into: build → storage tests + parallel cmd test shards.
|
||||
# cmd/bd embedded tests use a committed shard manifest; newly-added tests
|
||||
# still auto-distribute via hash fallback until the manifest is updated.
|
||||
|
||||
build-embedded:
|
||||
name: Build (Embedded Dolt)
|
||||
needs: detect-ci-tier
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build embedded bd binary
|
||||
run: go build -tags gms_pure_go -race -o /tmp/bd-embedded-test ./cmd/bd/
|
||||
|
||||
- name: Build embedded storage test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/embeddeddolt-test ./internal/storage/embeddeddolt/
|
||||
|
||||
- name: Build embedded cmd test binary
|
||||
run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/
|
||||
|
||||
# Server-Dolt conformance binary. No -race: the Dolt server runs
|
||||
# out-of-process in a container, and omitting it keeps the run inside the
|
||||
# job's timeout. The dolt package self-skips without the docker image, so
|
||||
# the binary is harmless if its job is gated off.
|
||||
- name: Build server Dolt conformance test binary
|
||||
run: go test -tags=integration,gms_pure_go -c -o /tmp/dolt-conformance-test ./internal/storage/dolt/
|
||||
|
||||
- name: Upload binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: |
|
||||
/tmp/bd-embedded-test
|
||||
/tmp/embeddeddolt-test
|
||||
/tmp/bd-cmd-test
|
||||
/tmp/dolt-conformance-test
|
||||
retention-days: 1
|
||||
|
||||
test-embedded-storage:
|
||||
name: Test (Embedded Dolt Storage)
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/embeddeddolt-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test
|
||||
# Conformance runs in the dedicated test-embedded-conformance job; skip
|
||||
# it here. Keeps upstream's 20m bump (base embedded tests grew) while
|
||||
# this job stays inside its envelope without the conformance suite.
|
||||
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=20m -test.skip '^TestConformance$'
|
||||
|
||||
test-embedded-conformance:
|
||||
name: Test (Embedded Dolt Conformance)
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/embeddeddolt-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test
|
||||
# Conformance suite (conformance.RunAll via TestConformance) against the
|
||||
# embedded Dolt backend. Split from test-embedded-storage so each job
|
||||
# stays well under its timeout; the server twin runs in mybd-665b's job.
|
||||
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=15m -test.run '^TestConformance$'
|
||||
|
||||
test-server-storage:
|
||||
name: Test (Server Dolt Conformance)
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/dolt-conformance-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Dolt
|
||||
run: |
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
dolt version
|
||||
|
||||
- name: Pull Dolt sql-server image
|
||||
# Presence of this image flips isDoltImageCached() true, so the suite
|
||||
# exercises server Dolt instead of self-skipping. Keep the tag in sync
|
||||
# with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
run: docker pull dolthub/dolt-sql-server:2.1.10
|
||||
|
||||
- name: Test
|
||||
# Server twin of test-embedded-conformance: same conformance.RunAll, but
|
||||
# against the container-backed server-mode Dolt backend. No -short / no
|
||||
# BEADS_TEST_SKIP=dolt, so TestMain starts the shared server and the
|
||||
# suite runs instead of self-skipping.
|
||||
run: /tmp/dolt-conformance-test -test.v -test.count=1 -test.timeout=15m -test.run '^TestConformance$'
|
||||
|
||||
test-embedded-cmd:
|
||||
name: Test (Embedded Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }})
|
||||
needs: [detect-ci-tier, build-embedded]
|
||||
if: needs.detect-ci-tier.outputs.full_embedded == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: embedded-test-binaries
|
||||
path: /tmp/
|
||||
|
||||
- name: Fix permissions
|
||||
run: chmod +x /tmp/bd-embedded-test /tmp/embeddeddolt-test /tmp/bd-cmd-test
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
BEADS_TEST_EMBEDDED_DOLT: "1"
|
||||
BEADS_TEST_BD_BINARY: /tmp/bd-embedded-test
|
||||
run: bash .github/scripts/embedded-test-shard.sh ${{ matrix.shard }} 20
|
||||
|
||||
test-nix:
|
||||
name: Test Nix Flake
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
- uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
- name: Run bd help via Nix
|
||||
id: nix_help
|
||||
run: |
|
||||
nix run .#default -- --help > help.txt
|
||||
- name: Verify help text
|
||||
if: steps.nix_help.outcome == 'success'
|
||||
run: |
|
||||
FIRST_LINE=$(head -n 1 help.txt)
|
||||
EXPECTED="Issues chained together like beads. A lightweight issue tracker with first-class dependency support."
|
||||
if [ "$FIRST_LINE" != "$EXPECTED" ]; then
|
||||
echo "First line of help.txt doesn't match expected output"
|
||||
echo "Expected: $EXPECTED"
|
||||
echo "Got: $FIRST_LINE"
|
||||
exit 1
|
||||
fi
|
||||
echo "Help text first line is correct"
|
||||
|
||||
ci-gate:
|
||||
name: CI Gate / Required
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- detect-ci-tier
|
||||
- build-embedded
|
||||
- test-embedded-storage
|
||||
- test-embedded-conformance
|
||||
- test-server-storage
|
||||
- test-embedded-cmd
|
||||
- test-nix
|
||||
if: ${{ always() }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Evaluate CI gate
|
||||
env:
|
||||
CI_GATE_NAME: PR risk gate
|
||||
CI_GATE_REQUIRED: >-
|
||||
DETECT_CI_TIER
|
||||
BUILD_EMBEDDED
|
||||
TEST_EMBEDDED_STORAGE
|
||||
TEST_EMBEDDED_CONFORMANCE
|
||||
TEST_SERVER_STORAGE
|
||||
TEST_EMBEDDED_CMD
|
||||
TEST_NIX
|
||||
FULL_EMBEDDED: ${{ needs.detect-ci-tier.outputs.full_embedded }}
|
||||
DETECT_CI_TIER: ${{ needs.detect-ci-tier.result }}
|
||||
BUILD_EMBEDDED: ${{ needs.build-embedded.result }}
|
||||
TEST_EMBEDDED_STORAGE: ${{ needs.test-embedded-storage.result }}
|
||||
TEST_EMBEDDED_CONFORMANCE: ${{ needs.test-embedded-conformance.result }}
|
||||
TEST_SERVER_STORAGE: ${{ needs.test-server-storage.result }}
|
||||
TEST_EMBEDDED_CMD: ${{ needs.test-embedded-cmd.result }}
|
||||
TEST_NIX: ${{ needs.test-nix.result }}
|
||||
run: |
|
||||
skipped_ok=""
|
||||
if [[ "$FULL_EMBEDDED" != "true" ]]; then
|
||||
skipped_ok="BUILD_EMBEDDED TEST_EMBEDDED_STORAGE TEST_EMBEDDED_CONFORMANCE TEST_SERVER_STORAGE TEST_EMBEDDED_CMD"
|
||||
fi
|
||||
export CI_GATE_SKIPPED_OK="$skipped_ok"
|
||||
bash .github/scripts/ci-gate.sh
|
||||
619
.github/workflows/pr.yml
vendored
Normal file
619
.github/workflows/pr.yml
vendored
Normal file
|
|
@ -0,0 +1,619 @@
|
|||
name: PR
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
|
||||
build-artifacts:
|
||||
name: Build Artifacts
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install golangci-lint
|
||||
run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9.0
|
||||
|
||||
- name: Run policy checks
|
||||
run: make ci-pr-policy
|
||||
|
||||
- name: Run lint checks
|
||||
run: make ci-pr-lint
|
||||
|
||||
- name: Build reusable Linux artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
source ./.buildflags
|
||||
go_version="$(go version)"
|
||||
commit="$(git rev-parse HEAD)"
|
||||
go build -tags "$BEADS_BUILD_TAGS" -o artifacts/bd-linux-gms-pure ./cmd/bd
|
||||
chmod +x artifacts/bd-linux-gms-pure
|
||||
(
|
||||
cd artifacts
|
||||
sha256sum bd-linux-gms-pure > SHA256SUMS
|
||||
)
|
||||
{
|
||||
echo "commit=${commit}"
|
||||
echo "go_version=${go_version}"
|
||||
echo "build_tags=${BEADS_BUILD_TAGS}"
|
||||
echo "artifact=bd-linux-gms-pure"
|
||||
} > artifacts/build-manifest.txt
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: artifacts/
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
|
||||
# Fast check: every `go build|test|run|generate|install` invocation in
|
||||
# tracked scripts/hooks/CI carries -tags=gms_pure_go. Prevents ICU-linkage
|
||||
# regressions from re-entering the build (see docs/ICU-POLICY.md).
|
||||
check-build-tags:
|
||||
name: Check build-tag policy
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
- run: ./scripts/check-build-tags.sh
|
||||
- run: ./scripts/check-go-install-guidance.sh
|
||||
|
||||
# Lock in the cgo-test-contamination fix (mybd-ycx / GH#3683 follow-up).
|
||||
# cmd/bd carries a mix of cgo-only test helpers (embedded Dolt, sql.DB) and
|
||||
# pure-Go tests. Untagged test files that reach for cgo-only helpers break
|
||||
# the entire package's CGO_ENABLED=0 compile, silently neutering pure-Go
|
||||
# tests (the original symptom in PR #3704). This job compiles the cmd/bd
|
||||
# test binary with CGO_ENABLED=0 and runs the pure-Go subset, so a
|
||||
# regression that re-introduces cgo coupling fails fast.
|
||||
check-cmd-bd-puregeo-tests:
|
||||
name: Check cmd/bd pure-Go tests compile (CGO_ENABLED=0)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build cmd/bd (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: go build -tags gms_pure_go -o /tmp/bd-puregeo ./cmd/bd
|
||||
|
||||
- name: Compile pure-Go test binaries (CGO_ENABLED=0, gms_pure_go)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-cmd-puregeo-test ./cmd/bd
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-embeddeddolt-puregeo-test ./internal/storage/embeddeddolt
|
||||
go test -tags gms_pure_go -c -o /tmp/bd-tracker-puregeo-test ./internal/tracker
|
||||
|
||||
- name: Run pure-Go cmd/bd test subset (CGO_ENABLED=0)
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
# Restrict to tests that exercise pure-Go code paths. Tests that
|
||||
# need a Dolt store skip themselves at runtime when no test server
|
||||
# is available; the goal here is to catch compile-time contamination,
|
||||
# not run the full suite.
|
||||
run: |
|
||||
go test -tags gms_pure_go -count=1 -short -run '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir)' ./cmd/bd
|
||||
|
||||
# Fast check to ensure all version files are in sync
|
||||
check-version-consistency:
|
||||
name: Check version consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Check all versions match
|
||||
run: ./scripts/check-versions.sh
|
||||
|
||||
# Migration hygiene: duplicate version numbers, nondeterministic SQL
|
||||
# (UUID()/NOW()/RAND(), the #4259 root-cause class), and edits to migration
|
||||
# files that already exist on the base branch (shipped migrations are
|
||||
# frozen; fix forward with a new version). Fails at PR time, before any
|
||||
# test even compiles. Details: scripts/check-migration-hygiene.sh.
|
||||
check-migration-hygiene:
|
||||
name: Check migration hygiene
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run migration hygiene checks
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||
run: ./scripts/check-migration-hygiene.sh
|
||||
|
||||
# Check documentation references match actual CLI flags
|
||||
check-doc-flags:
|
||||
name: Check doc flags freshness
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
# Full history so check-cli-docs-drift.sh can regenerate docs at the
|
||||
# merge-base and only fail PRs for drift they actually introduced.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build bd
|
||||
run: CGO_ENABLED=0 go build -tags gms_pure_go -o bd ./cmd/bd/
|
||||
|
||||
- name: Validate docs against CLI
|
||||
env:
|
||||
DOC_DRIFT_PATCH_OUT: ${{ runner.temp }}/cli-docs-freshness.patch
|
||||
run: |
|
||||
./scripts/check-doc-flags.sh ./bd
|
||||
./scripts/check-doc-freshness.sh
|
||||
|
||||
# When the drift check fails, it writes the exact regenerated-docs fix
|
||||
# (produced with CI's canonical build) so contributors can apply it with
|
||||
# `git apply` instead of reproducing CI's environment locally.
|
||||
- name: Upload docs fix patch
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: cli-docs-freshness-patch
|
||||
path: ${{ runner.temp }}/cli-docs-freshness.patch
|
||||
if-no-files-found: ignore
|
||||
|
||||
# Fast check to catch accidental .beads/issues.jsonl changes from contributors
|
||||
check-no-beads-changes:
|
||||
name: Check for .beads changes
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check for .beads/issues.jsonl changes
|
||||
run: |
|
||||
if git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -q "^\.beads/issues\.jsonl$"; then
|
||||
echo "This PR includes changes to .beads/issues.jsonl"
|
||||
echo ""
|
||||
echo "This file is the project's issue database and should not be modified in PRs."
|
||||
echo ""
|
||||
echo "To fix, run:"
|
||||
echo " git checkout origin/main -- .beads/issues.jsonl"
|
||||
echo " git commit --amend"
|
||||
echo " git push --force"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
echo "No .beads/issues.jsonl changes detected"
|
||||
|
||||
detect-package-gates:
|
||||
name: Detect package gates
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
mcp_package: ${{ steps.detect.outputs.mcp_package }}
|
||||
npm_package: ${{ steps.detect.outputs.npm_package }}
|
||||
website: ${{ steps.detect.outputs.website }}
|
||||
reason: ${{ steps.detect.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide package gates
|
||||
id: detect
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ github.event.before }}
|
||||
PUSH_AFTER_SHA: ${{ github.sha }}
|
||||
run: ./scripts/ci/detect-package-gates.sh
|
||||
|
||||
package-mcp:
|
||||
name: Package Gate (MCP)
|
||||
runs-on: ubuntu-latest
|
||||
needs: [detect-package-gates, build-artifacts]
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.mcp_package }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.mcp_package }}" != "true" ]]; then
|
||||
echo "MCP package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Python
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: python -m pip install uv==0.11.16
|
||||
|
||||
- name: Download build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run MCP package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-package-mcp
|
||||
|
||||
package-npm:
|
||||
name: Package Gate (npm)
|
||||
runs-on: ubuntu-latest
|
||||
needs: [detect-package-gates, build-artifacts]
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.npm_package }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.npm_package }}" != "true" ]]; then
|
||||
echo "npm package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Node.js
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Download build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run npm package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-package-npm
|
||||
|
||||
package-website:
|
||||
name: Package Gate (website)
|
||||
runs-on: ubuntu-latest
|
||||
needs: detect-package-gates
|
||||
steps:
|
||||
- name: Check applicability
|
||||
id: applicability
|
||||
run: |
|
||||
echo "run=${{ needs.detect-package-gates.outputs.website }}" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ needs.detect-package-gates.outputs.website }}" != "true" ]]; then
|
||||
echo "website package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
|
||||
- name: Set up Node.js
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Run website package gate
|
||||
if: steps.applicability.outputs.run == 'true'
|
||||
run: make ci-website
|
||||
|
||||
pr-policy-wrapper:
|
||||
name: PR Policy (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Run PR policy wrapper
|
||||
run: make ci-pr-policy
|
||||
|
||||
pr-core-wrapper:
|
||||
name: PR Core (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Run PR core wrapper
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: make ci-pr-core
|
||||
|
||||
pr-lint-wrapper:
|
||||
name: PR Lint (wrapper timing)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install golangci-lint
|
||||
run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9.0
|
||||
|
||||
- name: Run PR lint wrapper
|
||||
run: make ci-pr-lint
|
||||
|
||||
# Focused job for the hexagonal storage layer (internal/storage/domain/* and
|
||||
# internal/storage/uow). These packages back the proxied-server init path and
|
||||
# also live behind the existing ./... matrix, but TestDomainDB requires the
|
||||
# Dolt sql-server image cached locally (testcontainers checks `docker image
|
||||
# inspect` and skips otherwise). Pulling the image up front guarantees the
|
||||
# suite actually runs and surfaces failures here with a clear job name.
|
||||
test-domain-uow:
|
||||
name: Test (storage domain + uow)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-artifacts
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt CLI
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Verify dolt on PATH
|
||||
run: dolt version
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Pull Dolt sql-server image
|
||||
# Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
# Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips.
|
||||
run: docker pull dolthub/dolt-sql-server:2.1.10
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ci-build-artifacts
|
||||
path: ci-build-artifacts
|
||||
|
||||
- name: Verify build artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ci-build-artifacts
|
||||
sha256sum -c SHA256SUMS
|
||||
chmod +x bd-linux-gms-pure
|
||||
|
||||
- name: Test domain + uow + tracker
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
|
||||
run: go test -tags gms_pure_go -race -count=1 -v ./internal/storage/domain/... ./internal/storage/uow/... ./internal/tracker/...
|
||||
|
||||
# Producer-side guard for the Beads<->Gas City contract corpus. Regenerates
|
||||
# the canonicalized golden corpus from this branch's bd and byte-compares it
|
||||
# to the committed testdata/corpus/; an unreviewed wire change is a hard
|
||||
# failure (run `make corpus-regen`). The double-run test proves determinism.
|
||||
# Needs the Dolt sql-server image (the protocol harness spins a container).
|
||||
contract-corpus:
|
||||
name: Contract corpus (golden + determinism)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt CLI
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Pull Dolt sql-server image
|
||||
# Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
run: docker pull dolthub/dolt-sql-server:2.1.10
|
||||
|
||||
- name: Corpus golden + determinism
|
||||
# Require a live Dolt store here: this is the gate that must exercise the
|
||||
# golden + double-run checks, so a failed container is a hard failure,
|
||||
# not a silent skip (see requireDoltStore in cmd/bd/protocol tests).
|
||||
env:
|
||||
BEADS_PROTOCOL_REQUIRE_DOLT: "1"
|
||||
run: go test -tags gms_pure_go -count=1 -run 'TestCorpusGolden|TestCanonicalize|TestCorpusDoubleRunByteIdentical|TestCheckCaptureExit' ./cmd/bd/protocol
|
||||
|
||||
fmt-check:
|
||||
name: Check formatting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Check gofmt
|
||||
run: make fmt-check
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@82606bf257cbaff209d206a39f5134f0cfbfd2ee # v9
|
||||
with:
|
||||
version: latest
|
||||
args: --timeout=5m --build-tags=gms_pure_go
|
||||
|
||||
ci-gate:
|
||||
name: CI Gate / Required
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build-artifacts
|
||||
- check-build-tags
|
||||
- check-cmd-bd-puregeo-tests
|
||||
- check-version-consistency
|
||||
- check-migration-hygiene
|
||||
- check-doc-flags
|
||||
- check-no-beads-changes
|
||||
- detect-package-gates
|
||||
- package-mcp
|
||||
- package-npm
|
||||
- package-website
|
||||
- pr-policy-wrapper
|
||||
- pr-core-wrapper
|
||||
- pr-lint-wrapper
|
||||
- test-domain-uow
|
||||
- contract-corpus
|
||||
- fmt-check
|
||||
- lint
|
||||
if: ${{ always() }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Evaluate CI gate
|
||||
env:
|
||||
CI_GATE_NAME: PR baseline gate
|
||||
CI_GATE_REQUIRED: >-
|
||||
BUILD_ARTIFACTS
|
||||
CHECK_BUILD_TAGS
|
||||
CHECK_CMD_BD_PUREGEO_TESTS
|
||||
CHECK_VERSION_CONSISTENCY
|
||||
CHECK_MIGRATION_HYGIENE
|
||||
CHECK_DOC_FLAGS
|
||||
CHECK_NO_BEADS_CHANGES
|
||||
DETECT_PACKAGE_GATES
|
||||
PACKAGE_MCP
|
||||
PACKAGE_NPM
|
||||
PACKAGE_WEBSITE
|
||||
PR_POLICY_WRAPPER
|
||||
PR_CORE_WRAPPER
|
||||
PR_LINT_WRAPPER
|
||||
TEST_DOMAIN_UOW
|
||||
CONTRACT_CORPUS
|
||||
FMT_CHECK
|
||||
LINT
|
||||
BUILD_ARTIFACTS: ${{ needs.build-artifacts.result }}
|
||||
CHECK_BUILD_TAGS: ${{ needs.check-build-tags.result }}
|
||||
CHECK_CMD_BD_PUREGEO_TESTS: ${{ needs.check-cmd-bd-puregeo-tests.result }}
|
||||
CHECK_VERSION_CONSISTENCY: ${{ needs.check-version-consistency.result }}
|
||||
CHECK_MIGRATION_HYGIENE: ${{ needs.check-migration-hygiene.result }}
|
||||
CHECK_DOC_FLAGS: ${{ needs.check-doc-flags.result }}
|
||||
CHECK_NO_BEADS_CHANGES: ${{ needs.check-no-beads-changes.result }}
|
||||
DETECT_PACKAGE_GATES: ${{ needs.detect-package-gates.result }}
|
||||
PACKAGE_MCP: ${{ needs.package-mcp.result }}
|
||||
PACKAGE_NPM: ${{ needs.package-npm.result }}
|
||||
PACKAGE_WEBSITE: ${{ needs.package-website.result }}
|
||||
PR_POLICY_WRAPPER: ${{ needs.pr-policy-wrapper.result }}
|
||||
PR_CORE_WRAPPER: ${{ needs.pr-core-wrapper.result }}
|
||||
PR_LINT_WRAPPER: ${{ needs.pr-lint-wrapper.result }}
|
||||
TEST_DOMAIN_UOW: ${{ needs.test-domain-uow.result }}
|
||||
CONTRACT_CORPUS: ${{ needs.contract-corpus.result }}
|
||||
FMT_CHECK: ${{ needs.fmt-check.result }}
|
||||
LINT: ${{ needs.lint.result }}
|
||||
run: |
|
||||
skipped_ok=""
|
||||
if [[ "$GITHUB_EVENT_NAME" == "merge_group" ]]; then
|
||||
skipped_ok="CHECK_NO_BEADS_CHANGES"
|
||||
fi
|
||||
export CI_GATE_SKIPPED_OK="$skipped_ok"
|
||||
bash .github/scripts/ci-gate.sh
|
||||
77
.github/workflows/regression.yml
vendored
77
.github/workflows/regression.yml
vendored
|
|
@ -4,16 +4,85 @@ on:
|
|||
# Run on merges to main
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
# Allow manual trigger
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
detect-regression-need:
|
||||
name: Detect regression need
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run_regression: ${{ steps.detect.outputs.run_regression }}
|
||||
reason: ${{ steps.detect.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Decide whether to run differential regression tests
|
||||
id: detect
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$EVENT_NAME" != "pull_request" ]]; then
|
||||
echo "run_regression=true" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=$EVENT_NAME event always runs regression tests" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
labels="$(jq -r '.pull_request.labels[].name // empty' "$GITHUB_EVENT_PATH")"
|
||||
if grep -Fxq "run-regression" <<<"$labels"; then
|
||||
echo "run_regression=true" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=run-regression label present" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
if grep -Fxq "skip-regression" <<<"$labels"; then
|
||||
echo "run_regression=false" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=skip-regression label present" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
changed="$(git diff --name-only "$PR_BASE_SHA" "$PR_HEAD_SHA")"
|
||||
echo "Changed files:"
|
||||
printf '%s\n' "$changed"
|
||||
|
||||
regression_candidates="$(
|
||||
printf '%s\n' "$changed" |
|
||||
grep -Ev '^(cmd/bd|internal/storage|internal/types)/.*_test\.go$' ||
|
||||
true
|
||||
)"
|
||||
|
||||
risky_pattern='^(\.github/workflows/regression\.yml|Makefile|go\.(mod|sum)|cmd/bd/|internal/storage/|internal/types/|tests/regression/)'
|
||||
if grep -Eq "$risky_pattern" <<<"$regression_candidates"; then
|
||||
echo "run_regression=true" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=PR changes CLI, storage, types, regression, or build inputs" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "run_regression=false" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=PR does not touch regression-sensitive paths" >> "$GITHUB_OUTPUT"
|
||||
|
||||
regression:
|
||||
name: Differential Regression (v0.49.6 baseline)
|
||||
needs: detect-regression-need
|
||||
if: needs.detect-regression-need.outputs.run_regression == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- name: Show regression trigger reason
|
||||
run: echo "${{ needs.detect-regression-need.outputs.reason }}"
|
||||
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
|
|
@ -40,7 +109,7 @@ jobs:
|
|||
# has a known cleanup race (see beads issue: TestCreateWithParentFlag
|
||||
# TempDir RemoveAll "directory not empty" flake). Keep the tag in sync
|
||||
# with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
run: docker pull dolthub/dolt-sql-server:1.86.0
|
||||
run: docker pull dolthub/dolt-sql-server:2.1.10
|
||||
|
||||
- name: Cache baseline binary
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
|
|
@ -49,4 +118,4 @@ jobs:
|
|||
key: regression-baseline-${{ hashFiles('tests/regression/BASELINE_VERSION') }}
|
||||
|
||||
- name: Run regression tests
|
||||
run: go test -tags=regression,gms_pure_go -timeout=10m -v ./tests/regression/...
|
||||
run: go test -tags=regression,gms_pure_go -timeout=20m -v ./tests/regression/...
|
||||
|
|
|
|||
282
.github/workflows/release.yml
vendored
282
.github/workflows/release.yml
vendored
|
|
@ -17,14 +17,129 @@ permissions:
|
|||
id-token: write
|
||||
attestations: write
|
||||
|
||||
env:
|
||||
BD_DISABLE_METRICS: "1"
|
||||
BD_DISABLE_EVENT_FLUSH: "1"
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
# Guard: only run goreleaser in the canonical repository (not in forks)
|
||||
# Pre-publish gate: refuse to publish a release whose version constants and
|
||||
# Docusaurus docs snapshot disagree. This blocks the failure mode where a tag
|
||||
# ships with version.go bumped but the docs snapshot missing (which otherwise
|
||||
# only surfaces as a red main after the artifacts are already published).
|
||||
verify-version-consistency:
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify tag matches version.go
|
||||
run: |
|
||||
tag_version="${GITHUB_REF_NAME#v}"
|
||||
code_version="$(grep 'Version = ' cmd/bd/version.go | sed 's/.*"\(.*\)".*/\1/')"
|
||||
if [ "$tag_version" != "$code_version" ]; then
|
||||
echo "ERROR: tag v$tag_version does not match cmd/bd/version.go ($code_version)" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "OK: tag and version.go agree on $code_version"
|
||||
|
||||
- name: Check version + docs consistency
|
||||
run: |
|
||||
tag_version="${GITHUB_REF_NAME#v}"
|
||||
if [[ "$tag_version" == *-* ]]; then
|
||||
echo "Prerelease tag detected; stable docs snapshot may remain on latest stable release."
|
||||
./scripts/check-versions.sh
|
||||
else
|
||||
BEADS_REQUIRE_RELEASE_DOCS=1 ./scripts/check-versions.sh
|
||||
fi
|
||||
|
||||
release-package-mcp:
|
||||
name: Release Package Gate (MCP)
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: verify-version-consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
run: python -m pip install uv==0.11.16
|
||||
|
||||
- name: Run MCP package gate
|
||||
run: make ci-package-mcp
|
||||
|
||||
- name: Upload validated MCP dist
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: release-mcp-dist
|
||||
path: integrations/beads-mcp/dist/*
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
release-package-npm:
|
||||
name: Release Package Gate (npm)
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: verify-version-consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Run npm package gate
|
||||
run: make ci-package-npm
|
||||
|
||||
release-package-website:
|
||||
name: Release Package Gate (website)
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: verify-version-consistency
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Run website package gate
|
||||
run: make ci-website
|
||||
|
||||
goreleaser:
|
||||
# Guard: only run goreleaser in the canonical repository (not in forks)
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs:
|
||||
- release-package-mcp
|
||||
- release-package-npm
|
||||
- release-package-website
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -42,7 +157,7 @@ jobs:
|
|||
run: go install github.com/tc-hib/go-winres@latest
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@1a80836c5c9d9e5755a25cb59ec6f45a3b5f41a8 # v7
|
||||
uses: goreleaser/goreleaser-action@5daf1e915a5f0af01ddbcd89a43b8061ff4f1a89 # v7
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: '~> v2'
|
||||
|
|
@ -67,6 +182,35 @@ jobs:
|
|||
echo "OK: $bin has no ICU runtime dependency"
|
||||
done
|
||||
|
||||
- name: Publish the contract corpus as a release artifact
|
||||
# Ships the canonicalized golden corpus (cmd/bd/protocol/testdata/corpus)
|
||||
# with each release and appends its checksum to the release checksums.txt,
|
||||
# so Gas City can anchor its vendored-corpus drift-check to a signed
|
||||
# beads release rather than a self-recomputed manifest. Runs before the
|
||||
# macOS job's serial checksums.txt append (goreleaser-macos needs this
|
||||
# job), so the entry is preserved.
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
version="${tag#v}"
|
||||
archive="beads_${version}_contract_corpus.tar.gz"
|
||||
tar -czf "$archive" -C cmd/bd/protocol/testdata corpus
|
||||
shasum -a 256 "$archive" | tee corpus-checksum.txt
|
||||
gh release upload "$tag" "$archive" --clobber
|
||||
gh release download "$tag" --pattern checksums.txt --dir /tmp/corpus-sums
|
||||
sums=/tmp/corpus-sums/checksums.txt
|
||||
# Idempotent on a job re-run (manual retry or flake): drop any prior
|
||||
# entry for this archive before appending the fresh checksum, so the
|
||||
# re-download+append never leaves a duplicate (or stale) corpus row.
|
||||
if [ -f "$sums" ]; then
|
||||
grep -vF "$archive" "$sums" > "$sums.tmp" || true
|
||||
mv "$sums.tmp" "$sums"
|
||||
fi
|
||||
cat corpus-checksum.txt >> "$sums"
|
||||
gh release upload "$tag" "$sums" --clobber
|
||||
|
||||
goreleaser-macos:
|
||||
# Build macOS binaries with CGO_ENABLED=1 for embedded Dolt support.
|
||||
# Runs on native macOS to avoid zig/osxcross cross-compilation issues.
|
||||
|
|
@ -75,7 +219,7 @@ jobs:
|
|||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -188,7 +332,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Resolve release asset paths
|
||||
id: assets
|
||||
|
|
@ -227,113 +371,13 @@ jobs:
|
|||
subject-checksums: ${{ steps.assets.outputs.checksums }}
|
||||
sbom-path: ${{ steps.assets.outputs.sbom }}
|
||||
|
||||
update-homebrew-formula:
|
||||
# Generate Homebrew formula after all archives (Linux + macOS) are uploaded.
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: [goreleaser, goreleaser-macos, attest-release]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Mint Homebrew tap token
|
||||
id: homebrew-token
|
||||
uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3
|
||||
with:
|
||||
app-id: ${{ secrets.HOMEBREW_TAP_APP_ID }}
|
||||
private-key: ${{ secrets.HOMEBREW_TAP_APP_PRIVATE_KEY }}
|
||||
owner: gastownhall
|
||||
repositories: homebrew-beads
|
||||
permission-contents: write
|
||||
|
||||
- name: Generate and push Homebrew formula
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
HOMEBREW_TAP_TOKEN: ${{ steps.homebrew-token.outputs.token }}
|
||||
run: |
|
||||
version="${{ steps.version.outputs.version }}"
|
||||
tag="v${version}"
|
||||
base_url="https://github.com/gastownhall/beads/releases/download/${tag}"
|
||||
|
||||
# Download checksums (same repo, no --repo needed)
|
||||
gh release download "${tag}" --pattern checksums.txt --dir /tmp
|
||||
checksums_file="/tmp/checksums.txt"
|
||||
|
||||
get_sha256() {
|
||||
local sha
|
||||
sha=$(grep "$1" "$checksums_file" | awk '{print $1}')
|
||||
if [ -z "$sha" ]; then
|
||||
echo "ERROR: missing checksum for $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "$sha"
|
||||
}
|
||||
|
||||
darwin_arm64_sha=$(get_sha256 "beads_${version}_darwin_arm64.tar.gz")
|
||||
darwin_amd64_sha=$(get_sha256 "beads_${version}_darwin_amd64.tar.gz")
|
||||
linux_amd64_sha=$(get_sha256 "beads_${version}_linux_amd64.tar.gz")
|
||||
linux_arm64_sha=$(get_sha256 "beads_${version}_linux_arm64.tar.gz")
|
||||
|
||||
cat > /tmp/bd.rb <<FORMULA
|
||||
# typed: false
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Bd < Formula
|
||||
desc "AI-supervised issue tracker for coding workflows"
|
||||
homepage "https://github.com/gastownhall/beads"
|
||||
version "${version}"
|
||||
license "MIT"
|
||||
|
||||
on_macos do
|
||||
if Hardware::CPU.arm?
|
||||
url "${base_url}/beads_${version}_darwin_arm64.tar.gz"
|
||||
sha256 "${darwin_arm64_sha}"
|
||||
else
|
||||
url "${base_url}/beads_${version}_darwin_amd64.tar.gz"
|
||||
sha256 "${darwin_amd64_sha}"
|
||||
end
|
||||
end
|
||||
|
||||
on_linux do
|
||||
if Hardware::CPU.arm?
|
||||
url "${base_url}/beads_${version}_linux_arm64.tar.gz"
|
||||
sha256 "${linux_arm64_sha}"
|
||||
else
|
||||
url "${base_url}/beads_${version}_linux_amd64.tar.gz"
|
||||
sha256 "${linux_amd64_sha}"
|
||||
end
|
||||
end
|
||||
|
||||
def install
|
||||
bin.install "bd"
|
||||
end
|
||||
end
|
||||
FORMULA
|
||||
# Strip leading whitespace from heredoc (YAML run: block indentation)
|
||||
sed -i 's/^ //' /tmp/bd.rb
|
||||
|
||||
# Push formula to homebrew tap
|
||||
cd /tmp
|
||||
git clone "https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/gastownhall/homebrew-beads.git"
|
||||
cp bd.rb homebrew-beads/Formula/bd.rb
|
||||
cd homebrew-beads
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add Formula/bd.rb
|
||||
git commit -m "bd ${version}" || echo "No changes to commit"
|
||||
git push
|
||||
|
||||
publish-pypi:
|
||||
runs-on: ubuntu-latest
|
||||
needs: goreleaser
|
||||
if: ${{ always() && github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: [release-package-mcp, goreleaser]
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') && !contains(github.ref_name, '-') }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
|
|
@ -341,12 +385,18 @@ jobs:
|
|||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
run: pip install uv
|
||||
run: python -m pip install uv==0.11.16
|
||||
|
||||
- name: Build package
|
||||
- name: Download validated MCP dist
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: release-mcp-dist
|
||||
path: integrations/beads-mcp/dist
|
||||
|
||||
- name: Verify validated MCP dist
|
||||
run: |
|
||||
cd integrations/beads-mcp
|
||||
uv build
|
||||
test -n "$(find integrations/beads-mcp/dist -maxdepth 1 -type f -print -quit)"
|
||||
ls -la integrations/beads-mcp/dist
|
||||
|
||||
- name: Publish to PyPI
|
||||
env:
|
||||
|
|
@ -358,14 +408,14 @@ jobs:
|
|||
|
||||
publish-npm:
|
||||
runs-on: ubuntu-latest
|
||||
needs: goreleaser
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') }}
|
||||
needs: [release-package-npm, goreleaser, goreleaser-macos]
|
||||
if: ${{ github.repository == 'gastownhall/beads' && startsWith(github.ref, 'refs/tags/v') && !contains(github.ref_name, '-') }}
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # Required for npm provenance/trusted publishing
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
|
|
|
|||
2
.github/workflows/test-pypi.yml
vendored
2
.github/workflows/test-pypi.yml
vendored
|
|
@ -10,7 +10,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
|
|
|
|||
64
.github/workflows/update-flake-lock.yml
vendored
64
.github/workflows/update-flake-lock.yml
vendored
|
|
@ -6,21 +6,61 @@ on:
|
|||
- cron: '0 0 * * 0' # Weekly on Sunday at midnight UTC
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
update-flake-lock:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@f4c468f2287f0f14a113841b41f2dc8957119519 # v3
|
||||
- name: Update flake.lock
|
||||
uses: DeterminateSystems/update-flake-lock@3d82c7e1a46ddcc239881a2ac62b0d9d970dc96b # main
|
||||
- name: Mint flake update token
|
||||
id: flake-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3
|
||||
with:
|
||||
pr-title: "chore(nix): update flake.lock"
|
||||
pr-labels: |
|
||||
dependencies
|
||||
nix
|
||||
app-id: ${{ secrets.FLAKE_UPDATE_APP_ID }}
|
||||
private-key: ${{ secrets.FLAKE_UPDATE_APP_PRIVATE_KEY }}
|
||||
owner: gastownhall
|
||||
repositories: beads
|
||||
permission-contents: write
|
||||
permission-pull-requests: write
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
ref: main
|
||||
token: ${{ steps.flake-token.outputs.token }}
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
|
||||
- name: Update flake.lock
|
||||
run: nix flake update
|
||||
|
||||
- name: Verify update scope
|
||||
run: |
|
||||
changed_files="$(git diff --name-only)"
|
||||
untracked_files="$(git ls-files --others --exclude-standard)"
|
||||
|
||||
if [ -n "$untracked_files" ]; then
|
||||
echo "Unexpected untracked files:"
|
||||
echo "$untracked_files"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -n "$changed_files" ] && [ "$changed_files" != "flake.lock" ]; then
|
||||
echo "Unexpected changed files:"
|
||||
echo "$changed_files"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create pull request
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
with:
|
||||
token: ${{ steps.flake-token.outputs.token }}
|
||||
commit-message: "flake.lock: Update"
|
||||
base: main
|
||||
branch: update_flake_lock_action
|
||||
delete-branch: true
|
||||
add-paths: flake.lock
|
||||
title: "chore(nix): update flake.lock"
|
||||
body: |
|
||||
Automated flake.lock update generated by the scheduled Nix workflow.
|
||||
|
|
|
|||
107
.github/workflows/update-vendor-hash.yml
vendored
Normal file
107
.github/workflows/update-vendor-hash.yml
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
name: Update vendorHash for dependabot Go bumps
|
||||
|
||||
# Dependabot bumps to go.mod/go.sum invalidate the proxyVendor FOD hash in
|
||||
# default.nix, which fails the nix-build CI gate. This workflow detects the
|
||||
# drift, computes the new hash via scripts/update-nix-vendorhash.sh, and
|
||||
# pushes the update back to the dependabot branch so the gate goes green
|
||||
# without a maintainer round-trip.
|
||||
#
|
||||
# Tracked under beads-bz5.
|
||||
#
|
||||
# Why pull_request_target (not pull_request):
|
||||
# GitHub gives the GITHUB_TOKEN read-only permissions on `pull_request`
|
||||
# workflows triggered by dependabot, regardless of declared `permissions:`.
|
||||
# `pull_request_target` runs in the trusted context of the base branch with
|
||||
# full token permissions, which is required to push back to the PR branch.
|
||||
#
|
||||
# Safety against pull_request_target abuse:
|
||||
# - The job only runs when github.actor is dependabot[bot] AND the PR head
|
||||
# is on the upstream repo (head.repo.full_name == github.repository).
|
||||
# Dependabot never opens PRs from forks, so this combination is not
|
||||
# reachable from an external contributor.
|
||||
# - We explicitly check out the PR head SHA to operate on dependabot's
|
||||
# bumped go.mod/go.sum. Because dependabot is the only allowed actor and
|
||||
# never modifies scripts/, the trust boundary is the dependabot bot
|
||||
# itself — this is the same trust posture the project already accepts
|
||||
# when merging dependabot PRs.
|
||||
# - No force-push. Single commit with attribution.
|
||||
#
|
||||
# Caveat:
|
||||
# GitHub does not retrigger pull_request workflow runs for commits
|
||||
# authored by GITHUB_TOKEN. After this workflow pushes, the existing
|
||||
# nix-build.yml check on this PR will remain stuck on the pre-fix commit.
|
||||
# Maintainers either re-run nix-build manually, or this workflow's own
|
||||
# success acts as the green signal that the hash is correct.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: update-vendor-hash-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
update-vendor-hash:
|
||||
name: Update default.nix vendorHash
|
||||
if: >-
|
||||
github.actor == 'dependabot[bot]' &&
|
||||
github.event.pull_request.user.login == 'dependabot[bot]' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout PR head
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
with:
|
||||
# pull_request_target defaults to the base ref. Explicitly check
|
||||
# out the PR head so we operate on dependabot's bumped go.mod/sum.
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@9adf02b41cfdac2632e1c16f0480ff5bf3b05dd6 # v3
|
||||
|
||||
- name: Capture pre-update vendorHash
|
||||
id: pre
|
||||
run: |
|
||||
set -euo pipefail
|
||||
OLD_HASH=$(grep 'vendorHash = ' default.nix | sed 's/.*"\(.*\)".*/\1/')
|
||||
echo "old_hash=$OLD_HASH" >>"$GITHUB_OUTPUT"
|
||||
echo "Pre-update vendorHash: $OLD_HASH"
|
||||
|
||||
- name: Update vendorHash
|
||||
run: ./scripts/update-nix-vendorhash.sh
|
||||
|
||||
- name: Detect whether hash changed
|
||||
id: changed
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if git diff --quiet -- default.nix; then
|
||||
echo "changed=false" >>"$GITHUB_OUTPUT"
|
||||
echo "vendorHash already matched; nothing to commit."
|
||||
else
|
||||
echo "changed=true" >>"$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Commit and push hash update
|
||||
if: steps.changed.outputs.changed == 'true'
|
||||
env:
|
||||
# Push to the PR branch on the upstream repo. dependabot branches
|
||||
# live on the same repo, so the default GITHUB_TOKEN suffices.
|
||||
BRANCH: ${{ github.event.pull_request.head.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add default.nix
|
||||
git commit \
|
||||
-m "chore(nix): update vendorHash for go.sum changes" \
|
||||
-m "Auto-generated by .github/workflows/update-vendor-hash.yml in response to a dependabot Go-module bump (beads-bz5)."
|
||||
git push origin "HEAD:${BRANCH}"
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -135,3 +135,6 @@ bd_test
|
|||
|
||||
# Beads / Dolt files (added by bd init)
|
||||
.beads-credential-key
|
||||
|
||||
# Beads / Dolt files (added by bd init)
|
||||
.beads/proxieddb/
|
||||
|
|
|
|||
|
|
@ -30,8 +30,10 @@ linters:
|
|||
- (os).Chdir
|
||||
- (os).MkdirAll
|
||||
- (fmt).Sscanf
|
||||
- (fmt).Fprint
|
||||
- (fmt).Fprintf
|
||||
- (fmt).Fprintln
|
||||
- fmt.Fprint
|
||||
- fmt.Fprintf
|
||||
- fmt.Fprintln
|
||||
misspell:
|
||||
|
|
|
|||
|
|
@ -159,22 +159,6 @@ archives:
|
|||
- README.md
|
||||
- CHANGELOG.md
|
||||
|
||||
brews:
|
||||
- name: bd
|
||||
repository:
|
||||
owner: gastownhall
|
||||
name: homebrew-beads
|
||||
directory: Formula
|
||||
# Disabled: macOS archives are built by a separate CI job (goreleaser-macos),
|
||||
# so goreleaser can't generate a complete formula. The update-homebrew-formula
|
||||
# job in release.yml generates the formula after all archives are uploaded.
|
||||
skip_upload: true
|
||||
homepage: "https://github.com/gastownhall/beads"
|
||||
description: "AI-supervised issue tracker for coding workflows"
|
||||
license: "MIT"
|
||||
install: |
|
||||
bin.install "bd"
|
||||
|
||||
checksum:
|
||||
name_template: "checksums.txt"
|
||||
algorithm: sha256
|
||||
|
|
@ -212,7 +196,28 @@ release:
|
|||
## beads v{{.Version}}
|
||||
|
||||
Pre-compiled binaries for Linux, macOS (Intel & Apple Silicon), Windows (AMD64 & ARM64), Android/Termux (ARM64), and FreeBSD.
|
||||
{{ if .Prerelease }}
|
||||
### Installation (release candidate)
|
||||
|
||||
> **This is a prerelease for validation.** The stable install channels —
|
||||
> Homebrew, the `install.sh` / `install.ps1` scripts, npm, and PyPI —
|
||||
> intentionally keep serving the latest **stable** release, so they will **not**
|
||||
> install this RC. Use one of the methods below.
|
||||
|
||||
**Manual download (recommended):**
|
||||
Download the archive for your platform from the **Assets** below, extract it,
|
||||
and place `bd` on your PATH.
|
||||
|
||||
**Go install (pinned to this RC):**
|
||||
```bash
|
||||
go install github.com/steveyegge/beads/cmd/bd@v{{ .Version }}
|
||||
# For embedded Dolt support:
|
||||
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@v{{ .Version }}
|
||||
```
|
||||
|
||||
When you are done validating, return to the stable release through your normal
|
||||
channel (e.g. `brew upgrade beads`).
|
||||
{{ else }}
|
||||
### Installation
|
||||
|
||||
**Homebrew (macOS/Linux):**
|
||||
|
|
@ -232,6 +237,7 @@ release:
|
|||
|
||||
**Manual Install:**
|
||||
Download the appropriate binary for your platform below, extract it, and place it in your PATH.
|
||||
{{ end }}
|
||||
|
||||
# Announce the release
|
||||
announce:
|
||||
|
|
|
|||
101
AGENTS.md
101
AGENTS.md
|
|
@ -14,10 +14,18 @@ expected and should not be flagged.
|
|||
|
||||
- **Issue Tracking** - How to use bd for work management
|
||||
- **Development Guidelines** - Code standards and testing
|
||||
- **Project Scope** - Read [docs/PROJECT_CHARTER.md](docs/PROJECT_CHARTER.md) before adding new feature surface area
|
||||
- **Visual Design System** - Status icons, colors, and semantic styling for CLI output
|
||||
- **Contributor Protection** - Read [CONTRIBUTING.md](CONTRIBUTING.md) before handling external PRs
|
||||
- **Maintainer PR Guidelines** - Read [PR_MAINTAINER_GUIDELINES.md](PR_MAINTAINER_GUIDELINES.md) before triaging, landing, or closing PRs
|
||||
|
||||
## Project Scope
|
||||
|
||||
Before adding new feature surface area, read
|
||||
[docs/PROJECT_CHARTER.md](docs/PROJECT_CHARTER.md). Beads owns issue tracking
|
||||
primitives and should not encode orchestration-layer policy, become a storage
|
||||
engine, or casually expand the database schema when metadata would work.
|
||||
|
||||
## PR Safety for Agents
|
||||
|
||||
Before triaging, reviewing, landing, closing, or otherwise maintaining PRs, read
|
||||
|
|
@ -50,25 +58,13 @@ See [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md) for full development guidelin
|
|||
|
||||
## Storage Boundary
|
||||
|
||||
The canonical storage boundary is in
|
||||
[docs/PROJECT_CHARTER.md](docs/PROJECT_CHARTER.md#storage-boundary). In short:
|
||||
Beads talks to storage through a driver interface (`dolthub/driver` for Dolt).
|
||||
Beads code should not reach across that boundary — no flocks, no engine
|
||||
introspection, no storage-engine-specific retry or crash-recovery logic in
|
||||
beads packages. Concurrency, locking, and crash-safety are the driver's job.
|
||||
|
||||
If you find yourself adding storage-implementation details to beads code —
|
||||
especially anywhere on the public SDK surface (`OpenBestAvailable`, the
|
||||
`Storage` interface, return types crossing `pkg/`) — stop and reconsider.
|
||||
That is a signal the driver interface needs widening, not that beads needs
|
||||
more storage logic.
|
||||
|
||||
**Roadmap target:** all storage interaction lives behind the driver. Beads
|
||||
stays storage-agnostic.
|
||||
|
||||
**Filing storage issues is still encouraged** — but flag them clearly so
|
||||
they can be routed to the driver (`dolthub/driver`) rather than patched
|
||||
beads-side. Reflexive workarounds in beads (extra locks, retries, schema
|
||||
poking) are exactly the kind of cross-boundary leak this direction is
|
||||
removing. When in doubt, file the issue and ask which side owns the fix.
|
||||
Do not add beads-side flocks, engine introspection, storage-specific retry or
|
||||
crash-recovery logic, or public SDK return types that leak driver internals.
|
||||
If the boundary is too narrow, widen the interface or route the issue to the
|
||||
driver instead of patching around it in beads.
|
||||
|
||||
## Agent Warning: Interactive Commands
|
||||
|
||||
|
|
@ -147,7 +143,7 @@ cp -rf source dest # NOT: cp -r source dest
|
|||
- NEVER say "ready to push when you are" - YOU must push
|
||||
- If push fails, resolve and retry until it succeeds
|
||||
|
||||
<!-- BEGIN BEADS INTEGRATION -->
|
||||
<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:19cc25d9 -->
|
||||
## Issue Tracking with bd (beads)
|
||||
|
||||
**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods.
|
||||
|
|
@ -172,9 +168,6 @@ bd ready --json
|
|||
```bash
|
||||
bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json
|
||||
bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json
|
||||
|
||||
# Use stdin for descriptions with special characters (backticks, !, nested quotes)
|
||||
echo 'Description with `backticks` and "quotes"' | bd create "Title" --description=- --json
|
||||
```
|
||||
|
||||
**Claim and update:**
|
||||
|
|
@ -209,24 +202,31 @@ bd close bd-42 --reason "Completed" --json
|
|||
### Workflow for AI Agents
|
||||
|
||||
1. **Check ready work**: `bd ready` shows unblocked issues
|
||||
2. **Read execution metadata first**: before deciding local vs delegated work, model, or reasoning level, inspect structured metadata:
|
||||
```bash
|
||||
bd show <id> --json | jq '.[0] | {id,title,metadata,description,notes}'
|
||||
```
|
||||
The execution metadata keys `execution_agent_type`, `execution_suggested_model`, `execution_reasoning_effort`, `execution_mode`, and `execution_parallel_group` are authoritative hints when present. Use description and notes as fallback context.
|
||||
3. **Claim your task atomically**: `bd update <id> --claim`
|
||||
4. **Work on it**: Implement, test, document
|
||||
5. **Discover new work?** Create linked issue:
|
||||
2. **Claim your task atomically**: `bd update <id> --claim`
|
||||
3. **Work on it**: Implement, test, document
|
||||
4. **Discover new work?** Create linked issue:
|
||||
- `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:<parent-id>`
|
||||
6. **Complete**: `bd close <id> --reason "Done"`
|
||||
5. **Complete**: `bd close <id> --reason "Done"`
|
||||
|
||||
### Auto-Sync
|
||||
### Quality
|
||||
- Use `--acceptance` and `--design` fields when creating issues
|
||||
- Use `--validate` to check description completeness
|
||||
|
||||
bd automatically syncs via Dolt:
|
||||
### Lifecycle
|
||||
- `bd defer <id>` / `bd supersede <id>` for issue management
|
||||
- `bd stale` / `bd orphans` / `bd lint` for hygiene
|
||||
- `bd human <id>` to flag for human decisions
|
||||
- `bd formula list` / `bd mol pour <name>` for structured workflows
|
||||
|
||||
### Sync
|
||||
|
||||
bd stores issue history in Dolt:
|
||||
|
||||
- Each write auto-commits to Dolt history
|
||||
- Use `bd dolt push`/`bd dolt pull` for remote sync
|
||||
- No manual export/import needed!
|
||||
- Do not treat `.beads/issues.jsonl` as the sync protocol
|
||||
|
||||
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns.
|
||||
|
||||
### Important Rules
|
||||
|
||||
|
|
@ -240,4 +240,37 @@ bd automatically syncs via Dolt:
|
|||
|
||||
For more details, see README.md and docs/QUICKSTART.md.
|
||||
|
||||
## Agent Context Profiles
|
||||
|
||||
The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions.
|
||||
|
||||
- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands.
|
||||
- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise.
|
||||
- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins.
|
||||
|
||||
## Session Completion
|
||||
|
||||
This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions.
|
||||
|
||||
1. **File issues for remaining work** - Create beads for anything that needs follow-up
|
||||
2. **Run quality gates** (if code changed) - Tests, linters, builds
|
||||
3. **Update issue status** - Close finished work, update in-progress items
|
||||
4. **Handle git/sync by active profile**:
|
||||
```bash
|
||||
# Conservative/minimal/default: report status and proposed commands; wait for approval.
|
||||
git status
|
||||
|
||||
# Team-maintainer opt-in only, unless current instructions forbid it:
|
||||
git pull --rebase
|
||||
bd dolt push
|
||||
git push
|
||||
git status
|
||||
```
|
||||
5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step
|
||||
|
||||
**Critical rules:**
|
||||
- Explicit user or orchestrator instructions override this Beads block.
|
||||
- Do not commit or push without clear authority from the active profile or the current user request.
|
||||
- If a required sync or push is blocked, stop and report the exact command and error.
|
||||
|
||||
<!-- END BEADS INTEGRATION -->
|
||||
|
|
|
|||
|
|
@ -63,6 +63,12 @@ into temp repos and produce flaky test behavior.
|
|||
|
||||
**Warning:** bd will warn you when creating issues with "Test" prefix in the production database. Always use `BEADS_DB` for manual testing.
|
||||
|
||||
**Tmpfs hosts:** the `cmd/bd` test suite creates an isolated `$HOME` and several
|
||||
test binaries under `$TMPDIR`. They are normally cleaned by the test process,
|
||||
but a SIGKILLed or OOMed run can leave orphans behind. On hosts where `/tmp`
|
||||
is tmpfs (e.g. Fedora Atomic / Bluefin), run `make clean-test-tmp` between
|
||||
test runs if `du -sh /tmp/beads-* /tmp/bd-*` shows accumulation. See bd-3q2u.
|
||||
|
||||
### Before Committing
|
||||
|
||||
1. **Run tests**: `make test` (or `./scripts/test.sh`)
|
||||
|
|
@ -82,11 +88,16 @@ git commit -m "Add retry logic for database locks (bd-xyz)"
|
|||
|
||||
This enables `bd doctor` to detect **orphaned issues** - work that was committed but the issue wasn't closed. The doctor check cross-references open issues against git history to find these orphans.
|
||||
|
||||
For agent-prepared commits, also include the
|
||||
`Agent-Signature:` trailer described in
|
||||
[docs/AGENT_SIGNING.md](docs/AGENT_SIGNING.md). Use `unknown-model` or
|
||||
`unknown-reasoning` when reliable runtime metadata is unavailable.
|
||||
|
||||
### Git Workflow
|
||||
|
||||
bd uses **Dolt** as its primary database. Changes are committed to Dolt history automatically (one Dolt commit per write command).
|
||||
|
||||
**Install git hooks** for automatic sync:
|
||||
**Install git hooks** for commit integration and legacy fallback behavior:
|
||||
```bash
|
||||
bd hooks install
|
||||
```
|
||||
|
|
@ -121,6 +132,9 @@ maintainer policy is to maximize community throughput: find useful contributor
|
|||
value, absorb or transform it locally when practical, preserve attribution, and
|
||||
use request-changes only as a last resort.
|
||||
|
||||
Sign agent-written GitHub comments and reviews using
|
||||
[docs/AGENT_SIGNING.md](docs/AGENT_SIGNING.md).
|
||||
|
||||
### External Contributor PRs: Check Before You Build
|
||||
|
||||
**Read [CONTRIBUTING.md](CONTRIBUTING.md)** — it contains promises we've made to contributors. Violating them damages trust and community.
|
||||
|
|
@ -278,6 +292,11 @@ echo 'Updated description with $variables' | bd update <id> --description=-
|
|||
bd create "Title" --body-file=description.md
|
||||
```
|
||||
|
||||
**GitHub body hygiene.** For GitHub PR, issue, comment, and review bodies,
|
||||
write Markdown to a file and pass it with `gh ... --body-file`. Run
|
||||
`scripts/gh-body-lint <body-file>` first to catch literal `\n` sequences and
|
||||
non-linking `GH#123` references.
|
||||
|
||||
**Example agent session:**
|
||||
|
||||
```bash
|
||||
|
|
@ -296,7 +315,7 @@ bd dolt push
|
|||
This installs:
|
||||
|
||||
- **pre-commit** — Commits pending Dolt changes
|
||||
- **post-merge** — Pulls remote Dolt changes after git merge
|
||||
- **post-merge** — Runs chained hooks and a legacy JSONL import fallback only when no Dolt remote is configured
|
||||
|
||||
**Note:** Hooks are embedded in the bd binary and work for all bd users (not just source repo users).
|
||||
|
||||
|
|
@ -532,7 +551,7 @@ This handles the entire release workflow automatically, including waiting ~5 min
|
|||
6. Update Homebrew: `./scripts/update-homebrew.sh <version>` (waits for GitHub Actions)
|
||||
7. Verify: `brew update && brew upgrade beads && bd version`
|
||||
|
||||
See [docs/RELEASING.md](docs/RELEASING.md) for complete manual instructions.
|
||||
See [RELEASING.md](RELEASING.md) for complete manual instructions.
|
||||
|
||||
## Checking GitHub Issues and PRs
|
||||
|
||||
|
|
@ -567,6 +586,20 @@ gh issue view 201
|
|||
|
||||
**Do NOT use:** `browser_navigate`, `browser_snapshot`, or other playwright tools for GitHub PR/issue reviews unless specifically requested by the user.
|
||||
|
||||
## Telemetry
|
||||
|
||||
`bd` collects anonymous command-usage metrics. Each event is a `cli_command`
|
||||
record carrying only the command name; each batch also carries the bd version
|
||||
and OS platform, keyed by a machine-derived, HMAC-protected distinct ID. No
|
||||
email, repo path, remote URL, issue content, or user-supplied strings are
|
||||
collected. Events are written under `~/.beads/eventsData` and POSTed to
|
||||
`https://gastownhall-eventsapi.com/mp/collect`.
|
||||
|
||||
Metrics are enabled by default (opt-out). The friendliest way to see or change
|
||||
them is `bd metrics` (`bd metrics on` / `bd metrics off` / `bd metrics example`),
|
||||
which takes effect on the next command with no restart. `BD_DISABLE_METRICS=1`
|
||||
still works as a one-off, shell-scoped override.
|
||||
|
||||
## Questions?
|
||||
|
||||
- Check existing issues: `bd list`
|
||||
|
|
|
|||
|
|
@ -41,6 +41,8 @@ Tests on graphs with different topologies (linear chains, trees, dense graphs):
|
|||
### Search Operations
|
||||
- **BenchmarkSearchIssues_Large_NoFilter** - Search all open issues (10K dataset)
|
||||
- **BenchmarkSearchIssues_Large_ComplexFilter** - Search with priority/status filters (10K dataset)
|
||||
- **BenchmarkPerfSearchTypedLabelFilter_5K** - Label/type search over a 5K issue/label catalog
|
||||
- **BenchmarkPerfResolvePartialIDInvalidInput_5K** - Invalid partial-ID rejection without a broad fallback scan
|
||||
|
||||
### CRUD Operations
|
||||
- **BenchmarkCreateIssue_Large** - Create new issue in 10K database
|
||||
|
|
@ -51,6 +53,54 @@ Tests on graphs with different topologies (linear chains, trees, dense graphs):
|
|||
- **BenchmarkLargeDescription** - Handling 100KB+ issue descriptions (NEW)
|
||||
- **BenchmarkSyncMerge** - Simulate sync cycle with create/update operations (NEW)
|
||||
|
||||
### Recent Perf Regression References
|
||||
|
||||
These benchmarks cover the May 2026 Dolt hot-path changes so future perf PRs can run before/after checks against the same fixture shapes:
|
||||
|
||||
| PR / change | Benchmark |
|
||||
|-------------|-----------|
|
||||
| #3966 `perf(deps): narrow recursive cycle checks` | `BenchmarkPerfAddDependencyCycleCheck_DiamondDAG` |
|
||||
| #3967 `perf(search): tighten label and partial-id queries` | `BenchmarkPerfSearchTypedLabelFilter_5K`, `BenchmarkPerfResolvePartialIDInvalidInput_5K` |
|
||||
| #3968 `perf(ready): page blocked checks for limited ready work` | `BenchmarkPerfReadyWorkLimited_LargeBlockedGraph` |
|
||||
| #4001 `perf(ready): narrow deferred-parent child filtering` | `BenchmarkPerfReadyWorkDeferredParentExclusion_5K` |
|
||||
| #4002 `perf(ready): restrict blocked dependency scans to active IDs` | `BenchmarkPerfBlockedIssues_ClosedDependencySkew` |
|
||||
| #4003 `perf(get): query primary issues before wisp fallback` | `BenchmarkPerfGetIssuePrimaryFirst_PermanentWithWisps` |
|
||||
| #4004 `perf(deps): scan one cycle table for same-storage edges` | No standalone executable perf diff in the landed squash; covered by the cycle-check benchmark above |
|
||||
|
||||
Measured with `-benchtime=1x -benchmem -count=1` on the same host, copying this benchmark file onto each before/after ref:
|
||||
|
||||
| PR / path | Benchmark | Before | After | Time gain | Alloc gain |
|
||||
|-----------|-----------|--------|-------|-----------|------------|
|
||||
| #3967 label/type search | `BenchmarkPerfSearchTypedLabelFilter_5K` | 134.8 ms | 51.8 ms | 61.6% | -0.1% |
|
||||
| #3967 invalid partial-ID fallback | `BenchmarkPerfResolvePartialIDInvalidInput_5K` | 124.3 ms | 22.5 ms | 81.9% | 43.6% |
|
||||
| #3966 dependency cycle check | `BenchmarkPerfAddDependencyCycleCheck_DiamondDAG` | 80.0 ms | 25.8 ms | 67.7% | 1.4% |
|
||||
| #3968 limited ready work | `BenchmarkPerfReadyWorkLimited_LargeBlockedGraph` | 1677.4 ms | 341.7 ms | 79.6% | 85.4% |
|
||||
| #4001 deferred parent exclusion | `BenchmarkPerfReadyWorkDeferredParentExclusion_5K` | 3257.3 ms | 130.8 ms | 96.0% | 83.1% |
|
||||
| #4002 active blocked-dep scan | `BenchmarkPerfBlockedIssues_ClosedDependencySkew` | 44.3 ms | 36.2 ms | 18.1% | 96.0% |
|
||||
| #4003 primary issue lookup | `BenchmarkPerfGetIssuePrimaryFirst_PermanentWithWisps` | 9.0 ms | 6.4 ms | 28.7% | 10.7% |
|
||||
|
||||
Run the recent perf reference set with:
|
||||
|
||||
```bash
|
||||
go test -run=^$ -bench='BenchmarkPerf(SearchTypedLabelFilter|ResolvePartialIDInvalidInput|AddDependencyCycleCheck|ReadyWorkLimited|BlockedIssues|ReadyWorkDeferredParentExclusion|GetIssuePrimaryFirst)' -benchtime=1x -benchmem ./internal/storage/dolt
|
||||
```
|
||||
|
||||
For production-shaped CLI timeout and index experiments, use:
|
||||
|
||||
```bash
|
||||
go run ./scripts/repro-dolt-prod-timeouts --bd ./bd --scenario all
|
||||
go run ./scripts/bench-ready-indexes --dsn 'root@tcp(127.0.0.1:33307)/mc?timeout=30s&readTimeout=30s&writeTimeout=30s'
|
||||
```
|
||||
|
||||
When `repro-dolt-prod-timeouts` targets an existing workspace with
|
||||
`--workspace`, fixture seeding defaults to `--seed-mode=none`; pass
|
||||
`--seed-mode=full` or `--seed-mode=dep-only` only when intentionally writing
|
||||
and committing synthetic fixture rows into that workspace.
|
||||
|
||||
`bench-ready-indexes` drops its candidate indexes again before exit by default;
|
||||
pass `--keep-indexes` only when intentionally leaving the final index set
|
||||
installed.
|
||||
|
||||
## Performance Targets
|
||||
|
||||
### Typical Results (M2 Pro)
|
||||
|
|
|
|||
336
CHANGELOG.md
336
CHANGELOG.md
|
|
@ -7,9 +7,335 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.0] - 2026-07-04
|
||||
|
||||
First stable release of the 1.1.0 line. It consolidates everything from
|
||||
[1.1.0-rc.1] and [1.1.0-rc.2] (see those sections below for the full feature
|
||||
set) plus the post-rc.2 migration-recovery fixes listed here. The theme of
|
||||
1.1.0 is a safe schema-migration and upgrade path: it repairs the v52/v53
|
||||
drift classes that broke real-world rc.1/rc.2 upgrades, makes an interrupted
|
||||
migration recoverable in-tool instead of a dead end, and turns the
|
||||
remote-migrate gate from a blunt block into a state-aware one.
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
- **Back up before migrating** (`bd export --all -o backup.jsonl`) before
|
||||
running `bd migrate` on an older, especially remote-backed, database. The
|
||||
fixes below repair databases that reached a migration with drifted state;
|
||||
an export is cheap insurance while such drift is being repaired.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The state-aware remote-migrate gate is now on by default.** rc.2 shipped
|
||||
the smart gate behind an opt-in env var, but nothing in the gate's block
|
||||
message or docs surfaced that the var existed, so in practice everyone kept
|
||||
hitting the blunt always-block behavior. The provably-safe first-mover case
|
||||
(remote at the same schema version as this clone) now auto-migrates without
|
||||
`BD_ALLOW_REMOTE_MIGRATE`; remote-ahead still stops with an adopt directive
|
||||
and content skew still stops for a human. Set `BD_SMART_GATE=0` to opt out
|
||||
and restore the unconditional block
|
||||
([#4516](https://github.com/gastownhall/beads/issues/4516)).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A failed v53 migration no longer traps the database, and the v53 repair
|
||||
now covers `wisp_dependencies` split-column drift.** rc.2 repaired the
|
||||
`issues` rig columns, but a database coming from schema v49 could still fail
|
||||
v53 when its `wisp_dependencies` table was missing the split target columns
|
||||
(`depends_on_issue_id`, `depends_on_wisp_id`, `depends_on_external`) — and a
|
||||
half-applied v53 then bricked every subsequent command on open
|
||||
([#4555](https://github.com/gastownhall/beads/issues/4555)). The migration
|
||||
runner now adds and backfills the missing split columns before v53, and a
|
||||
narrow recovery gate lets an already-failed-v53 database self-heal on the
|
||||
next open — including the `issue_snapshots` / `compaction_snapshots` tables
|
||||
that migration 0051 leaves dirty during a single-pass v49→v53 upgrade
|
||||
([#4558](https://github.com/gastownhall/beads/pull/4558)).
|
||||
- **A dirty working set no longer deadlocks migration recovery in embedded
|
||||
mode.** Every store open runs the migration, which correctly refuses to
|
||||
alter tables that have uncommitted working-set changes — but the documented
|
||||
recovery (commit the working set) is itself a command that opens the store
|
||||
and hits the same refusal, a deadlock with no in-tool escape
|
||||
([#4566](https://github.com/gastownhall/beads/issues/4566)). `bd dolt commit`
|
||||
and `bd vc commit` now open past that guard, commit at the current schema,
|
||||
after which a normal `bd migrate` applies cleanly; the refusal message now
|
||||
names the recovery path
|
||||
([#4567](https://github.com/gastownhall/beads/pull/4567)).
|
||||
|
||||
## [1.1.0-rc.2] - 2026-07-02
|
||||
|
||||
Second release candidate for 1.1.0. Fixes the two upgrade-breaking migration
|
||||
regressions reported against rc.1 (#4502, #4534), hardens the remote-migrate
|
||||
gate that rc.1 introduced, and ships the validated upgrade documentation.
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
- **Back up before migrating.** The upgrade guide's remote-backed recipes now
|
||||
start with a JSONL export (`bd export --all -o ...`) before
|
||||
`BD_ALLOW_REMOTE_MIGRATE=1 bd migrate`. The two fixes below repair real
|
||||
databases that reached a migration with drifted state; an export is the
|
||||
cheap insurance while such drift is being repaired.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **v53 migration no longer fails on pre-rig `issues` tables.** The rig/agent
|
||||
columns (`hook_bead`, `role_bead`, `agent_state`, `last_activity`,
|
||||
`role_type`, `rig`) were only ever added to the squashed bootstrap
|
||||
`0001_create_issues`, so a database bootstrapped before they existed sits at
|
||||
schema v52 without them — and migration 0053, which copies those columns
|
||||
from `wisps`, failed with `Unknown column 'agent_state' in 'issues'` even
|
||||
with zero rig wisps to repair
|
||||
([#4502](https://github.com/gastownhall/beads/issues/4502)). The migration
|
||||
runner now repairs the drift in code immediately before applying v53,
|
||||
adding whichever of the six columns are missing (databases in the wild may
|
||||
have some but not all). Shipped migration files stay frozen — the repair
|
||||
lives in the runner because a failing migration can never be fixed forward
|
||||
by a later migration file.
|
||||
- **One orphaned `child_counters` row no longer bricks every `bd create`.**
|
||||
Migration 0039 dropped `fk_counter_parent` and clone-local migration 0002
|
||||
re-added it under `FOREIGN_KEY_CHECKS = 0`, so a counter row orphaned during
|
||||
the FK-less window (an interrupted create, a parent deleted without cascade)
|
||||
survived the constraint's return — and Dolt then failed constraint
|
||||
validation on every subsequent insert, including brand-new top-level issues,
|
||||
on an otherwise healthy database
|
||||
([#4534](https://github.com/gastownhall/beads/issues/4534)). A new
|
||||
clone-local migration moves any live-wisp counters to `wisp_child_counters`
|
||||
and deletes rows dangling from `issues` — the same rows the FK's
|
||||
`ON DELETE CASCADE` would have removed had it been in force. Runs
|
||||
automatically on the next command with the new binary; already-bitten
|
||||
databases are healed in place.
|
||||
- **Old binaries fail fast on writable opens of a schema-newer database**
|
||||
instead of proceeding against a schema they do not understand
|
||||
([#4531](https://github.com/gastownhall/beads/pull/4531)) — the guard rail
|
||||
for the mixed-version window during multi-clone upgrades.
|
||||
- **Prerelease GitHub releases now ship prerelease-correct install
|
||||
instructions.** The release notes header previously showed the stable
|
||||
install methods (brew, install scripts), three of which do not deliver a
|
||||
prerelease ([#4530](https://github.com/gastownhall/beads/pull/4530)).
|
||||
- **`bd remember` no longer clobbers a memory whose content is its own key**,
|
||||
and a bare `bd remember <existing-key>` now recalls instead of overwriting.
|
||||
|
||||
### Added
|
||||
|
||||
- **Smarter remote-migrate gate.** The gate introduced in rc.1 is now
|
||||
state-aware and agent-safe: cases that are provably safe to migrate
|
||||
auto-resolve instead of stopping every agent at the wall, while genuinely
|
||||
risky states still require the designated migrator
|
||||
([#4515](https://github.com/gastownhall/beads/pull/4515),
|
||||
[#4516](https://github.com/gastownhall/beads/pull/4516)).
|
||||
- **Backend-agnostic storage conformance test suite**
|
||||
([#4414](https://github.com/gastownhall/beads/pull/4414)).
|
||||
|
||||
### Documentation
|
||||
|
||||
- **Validated upgrade recipe for remote-backed / multi-clone databases** in
|
||||
the upgrade guide, exercised end-to-end on a live database
|
||||
([#4514](https://github.com/gastownhall/beads/pull/4514)), plus a
|
||||
consolidated Homebrew tap-migration snippet across install docs, a README
|
||||
pointer to the upgrade guide, and a pre-migrate backup step in the
|
||||
recipes (this release).
|
||||
|
||||
## [1.1.0-rc.1] - 2026-06-23
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
- **Mixed bd versions sharing one Dolt remote.** Pre-1.0.6 binaries record
|
||||
applied migrations as `(version, NULL)` while 1.0.6+ records
|
||||
`(version, sha256)` in `schema_migrations`, so two clones applying the same
|
||||
migration with different bd vintages used to produce a row conflict on
|
||||
`bd dolt pull`. The pull auto-resolver now resolves this class by keeping
|
||||
whichever side recorded the hash. Two *different* recorded hashes for the
|
||||
same version are the real [#4259](https://github.com/gastownhall/beads/issues/4259)
|
||||
schema fork and are still surfaced to the operator (see the `bd doctor`
|
||||
Migration Content Skew check). To avoid the mixed-vintage window entirely,
|
||||
upgrade all clones of a shared remote together, letting one designated
|
||||
machine migrate and `bd dolt push` first.
|
||||
|
||||
- **Upgrading a remote-backed database: one machine migrates, the rest adopt.**
|
||||
This release reshapes the `dependencies` primary key (migration `0050`), and
|
||||
`bd` now refuses to silently migrate a database that has a Dolt remote
|
||||
configured. If two clones cross the `0050` boundary with un-synced dependency
|
||||
edits on both sides, their histories become permanently un-mergeable — Dolt
|
||||
refuses the merge outright (`cannot merge because table dependencies has
|
||||
different primary keys in its common ancestor`) before the pull auto-resolver
|
||||
can run. Replacing the binary alone is not enough; follow the ordered recipe:
|
||||
|
||||
1. With your **current** binary, on **every** clone: `bd dolt push` +
|
||||
`bd dolt pull` until all are in sync, then stop editing. Once the new
|
||||
binary is installed, `push`/`pull` are gated too, so this must happen
|
||||
first.
|
||||
2. Designated migrator **only**: install the new binary, then
|
||||
`BD_ALLOW_REMOTE_MIGRATE=1 bd migrate` and `bd dolt push`.
|
||||
3. Every **other** clone: install the new binary, then `bd bootstrap` to adopt
|
||||
the migrated database (`bd dolt pull` is refused while the clone still has
|
||||
pending migrations; do not migrate on these clones).
|
||||
4. Confirm with `bd version`; in server mode, `bd doctor` adds a
|
||||
migration-content-skew check (not available in embedded mode).
|
||||
|
||||
A single clone with a remote follows the same gate (push with the old binary,
|
||||
then migrate and push). Full recipe and the single-clone variant:
|
||||
[Upgrading bd — remote-backed databases and multiple clones](website/docs/getting-started/upgrading.md#remote-backed-databases-and-multiple-clones).
|
||||
If clones have already forked, see the recovery playbook:
|
||||
[docs/RECOVERY.md#pk-fork-refused](docs/RECOVERY.md#pk-fork-refused).
|
||||
|
||||
### Added
|
||||
|
||||
- **perf(schema):** composite `(status, updated_at)` and standalone `defer_until` indexes on `issues` (migration 0052). Speeds up `bd stale` and `bd ready` on large rigs. First run after upgrade applies the migration — expect a one-time 10–25 s pause on rigs with >10K issues. Do not interrupt.
|
||||
- **Per-migration content hash.** `schema_migrations` now records the SHA-256 of each migration's file content alongside its version (`content_hash`), so two clones at the same `MAX(version)` but with divergent migration content become detectable (reporter fix No.2 for [#4259](https://github.com/gastownhall/beads/issues/4259)). The column is added to fresh databases via the bootstrap schema and idempotently to existing databases at migrate time; already-applied rows keep a NULL hash. The column definition and the hashes are deterministic, so `schema_migrations` still merges cleanly across clones.
|
||||
- **`bd doctor` migration-content-skew check.** Using the recorded hashes, `bd doctor` now compares the local `schema_migrations` against the cached remote-tracking ref (no network fetch) and warns when this database and its remote applied different content for the same migration version — the silent schema fork from [#4259](https://github.com/gastownhall/beads/issues/4259), surfaced as a clear advisory instead of a cryptic merge failure. Read-only diagnostic (it does not gate push/pull); the comparison primitive (`schema.ContentHashSkew`) is reusable.
|
||||
- **Remote-migrate prevention gate.** `bd` now refuses to silently auto-apply pending schema migrations to an existing database that has a remote configured (in both server and embedded mode), and tells the operator to choose: migrate (as the single designated migrator, then `bd dolt push`) or adopt the already-migrated database from the remote (`bd bootstrap`). Migrating each clone independently forks the schema and breaks `bd dolt pull` ([#4259](https://github.com/gastownhall/beads/issues/4259)). The gate is a no-op for fresh databases, databases already at the binary's version, databases with no remote, and read-only opens. The designated migrator proceeds with `BD_ALLOW_REMOTE_MIGRATE=1`. In server mode the gate also detects remotes persisted on disk in `.dolt/config`, so a freshly (auto-)started server — whose in-memory `dolt_remotes` table is not yet populated — cannot slip a remote-backed database past the gate.
|
||||
|
||||
- **Recovery guidance for Dolt primary-key merge refusals.** When `bd dolt pull` (or `push`) fails with Dolt's hard refusal `cannot merge because table X has different primary keys [in its common ancestor]` — the un-mergeable schema fork left behind by independently-migrated clones straddling a PK-reshaping migration ([#4259](https://github.com/gastownhall/beads/issues/4259)) — `bd` now recognizes the error class and prints the bootstrap-from-canonical-clone recovery recipe instead of just the raw error. Full playbook: [docs/RECOVERY.md#pk-fork-refused](docs/RECOVERY.md#pk-fork-refused).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Cross-clone issue-delete vs child-row-insert merges now converge.** The
|
||||
synced child tables (`dependencies`, `labels`, `comments`, `events`,
|
||||
snapshots) carry `FOREIGN KEY ... ON DELETE CASCADE` to `issues` (migrations
|
||||
`0041`/`0042`), but Dolt merges row-wise and never re-executes cascades: if
|
||||
clone A deleted an issue while clone B added a dependency, label, or comment
|
||||
referencing it, `bd dolt pull` failed outright with a foreign-key constraint
|
||||
violation ("transaction rolled back"), recorded nothing in `dolt_conflicts`,
|
||||
and could never converge on retry. The pull auto-resolver (SQL and CLI
|
||||
routes) now repairs this class by applying the foreign key's own cascade
|
||||
semantics — deleting the merged-in rows whose issue reference dangles — and
|
||||
refuses, exactly as before, any constraint violation it does not recognize
|
||||
(different constraint type, table bd does not own, FK to another parent).
|
||||
The repair converges across clones: it deletes precisely the rows the
|
||||
cascade already removed on the deleting clone. (bd-6dnrw.4)
|
||||
|
||||
- **`is_blocked` recompute no longer misses auto-resolved merges.** A pull
|
||||
whose merge bd auto-resolved (conflicts) or cascade-repaired (constraint
|
||||
violations) lands in the working set without advancing HEAD — the merge
|
||||
commit is created later — so the bd-6dnrw.3 post-pull recompute mistook it
|
||||
for "nothing merged" and skipped, leaving `is_blocked` stale exactly when
|
||||
the merge had needed intervention. The recompute now diffs to the working
|
||||
set and skips only when `issues`/`dependencies` are clean too. (bd-6dnrw.39)
|
||||
|
||||
- **`is_blocked` recomputed after `bd dolt pull`.** The denormalized
|
||||
`is_blocked` column (migration `0046`) was maintained only by local write
|
||||
paths, so a pull that merged another clone's writes silently left it stale —
|
||||
e.g. clone A closes blocker X while clone B adds an edge W→X, and the merged
|
||||
result carries `W.is_blocked=1` with a closed blocker, hiding W from
|
||||
`bd ready`. Every pull path (server SQL and CLI routes, peer pulls, embedded
|
||||
mode) now recomputes the column for exactly the rows the merge changed,
|
||||
scoped via `dolt_diff` between the pre- and post-pull HEADs and expanded
|
||||
through the same affected-set logic the local write paths use. Oversized or
|
||||
schema-reshaping merges fall back to a full recompute; conflicted pulls skip
|
||||
it until the operator resolves. (bd-6dnrw.3, PR 4107 follow-up)
|
||||
|
||||
- **Stale `is_blocked` is now repairable — `bd recompute-blocked`.** The
|
||||
post-pull recompute above is scoped to the merge diff and is skipped when a
|
||||
re-pull merges nothing (`HEAD` unchanged), so a recompute that failed *after*
|
||||
its merge committed — or a conflicted pull resolved by hand (which skips the
|
||||
recompute) — could leave `is_blocked` stale with no way to repair it: rerunning
|
||||
`bd dolt pull` merged nothing and recomputed nothing. The new
|
||||
`bd recompute-blocked` command runs a full, unconditional recompute over every
|
||||
issue and wisp and commits the result; it is idempotent and works in **both**
|
||||
embedded and server mode (unlike `bd doctor`, which is server-mode only).
|
||||
Server-mode `bd doctor` also gains a read-only **Blocked State** check that
|
||||
reports stale rows and a `bd doctor --fix` that runs the same repair.
|
||||
(bd-6dnrw.37)
|
||||
|
||||
- **Deterministic history-table primary keys (cross-clone merge-safety).**
|
||||
Migration `0037` converted the legacy BIGINT primary keys of `events`,
|
||||
`comments`, `issue_snapshots` and `compaction_snapshots` by backfilling
|
||||
`UUID()` — a different random value on every clone, the same hazard class as
|
||||
the `dependencies` fork below. Two legacy clones that upgraded independently
|
||||
held identical history rows under different primary keys, so their merges
|
||||
duplicated every pre-upgrade event and comment (or refused outright). A
|
||||
one-time-per-clone upgrade backfill now rewrites those ids to deterministic
|
||||
values derived from each row's content (`internal/storage/rowid`), so
|
||||
independently-migrated clones converge to byte-identical history tables;
|
||||
exact-duplicate rows are kept distinct via per-duplicate ordinals. The pass
|
||||
is gated on a clone-local marker (ignored migration `0009`), so steady-state
|
||||
opens never re-key — rows inserted after the pass are minted once and reach
|
||||
other clones by merge, so their ids are already consistent. (bd-6dnrw.2,
|
||||
the history-table sibling of
|
||||
[#4259](https://github.com/gastownhall/beads/issues/4259))
|
||||
|
||||
- **Deterministic dependency primary keys (cross-clone merge-safety).** `dependencies.id` (and `wisp_dependencies.id`) were filled by `DEFAULT (UUID())`, a per-clone-random value. Two clones that created the same edge — or that applied migration `0043` independently — diverged on the primary key, so `bd dolt pull` failed unrecoverably (`cannot merge because table dependencies has different primary keys in its common ancestor`, or a `uk_dep_*` unique-key violation). `id` is now derived deterministically from the natural edge key `(issue_id, target)` at every insert site (`internal/storage/depid`); migration `0050` drops the random default and idempotently re-asserts the natural-identity unique keys; and an upgrade backfill rewrites existing rows. Independently-migrated clones now converge to byte-identical, merge-safe `dependencies`. And because the same edge now has the same primary key on every clone, `bd dolt pull` **auto-resolves** a same-edge dependency conflict that differs only in audit columns (created_at/created_by/metadata/thread_id) the same way it already does for the metadata table — so two machines that each run `bd dep add X Y` between syncs merge cleanly. A conflict where the dependency *type* differs is still surfaced for the operator. ([#4259](https://github.com/gastownhall/beads/issues/4259))
|
||||
|
||||
## [1.0.5] - 2026-05-28
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
- **JSONL auto-export and auto-staging are now opt-in.** Repositories that
|
||||
relied on the previous implicit default should set it explicitly before or
|
||||
after upgrading:
|
||||
|
||||
```bash
|
||||
bd config set export.auto true
|
||||
bd config set export.git-add true
|
||||
```
|
||||
|
||||
Dolt is the primary datastore. `.beads/issues.jsonl` is now treated as an
|
||||
optional export for viewers such as `bv`, interchange, and issue-level
|
||||
migration. It is not the canonical git-tracked source of truth, not
|
||||
cross-machine sync, and not a full database backup. Use `bd dolt push` /
|
||||
`bd dolt pull` for sync and `bd backup` for restorable database backups.
|
||||
Existing repositories that already have `export.auto: true` or
|
||||
`export.git-add: true` configured keep that behavior.
|
||||
|
||||
### Added
|
||||
|
||||
- **Foreign keys across issue and wisp tables.** Migrations `0040`–`0042` and the new `ignored/0001`–`ignored/0004` add explicit FKs with `ON DELETE CASCADE ON UPDATE CASCADE` on `dependencies`, `labels`, `comments`, `events`, `issue_snapshots`, `compaction_snapshots`, `child_counters`, and the matching `wisp_*` tables. Deleting or renaming a parent row now cascades automatically — the manual cleanup loops in `issueops/delete.go`, `dolt/wisps.go`, `dolt/ephemeral_routing.go`, and `cmd/bd/rename_prefix.go` have been removed (net ~300 lines down). ([#3952](https://github.com/gastownhall/beads/pull/3952))
|
||||
- **`issueops.DeleteWispFromDependenciesInTx` / `UpdateWispIDInDependenciesInTx`.** Because Dolt forbids foreign keys from tracked tables (`dependencies`) to `dolt_ignore`'d tables (`wisps`), wisp deletion and rename now invoke these helpers explicitly to keep `dependencies.depends_on_wisp_id` consistent. The standard store APIs (`DeleteIssue`, `UpdateIssueID`, `deleteWispBatch`, etc.) wire them up automatically; only call them directly if you bypass those entry points. ([#3952](https://github.com/gastownhall/beads/pull/3952))
|
||||
- **Forward schema-skew guard.** `bd` now hard-fails when it opens a database that has been migrated to a *newer* schema version than the binary understands, instead of operating blindly on forward-migrated data. ([#4152](https://github.com/gastownhall/beads/pull/4152))
|
||||
- **`dolt.mode` config key.** New `dolt.mode` (`server` | `embedded`) configuration key with validation; `bd init` now warns on ambiguous configs and hard-fails when `dolt.host`/`dolt.port` are set without server mode.
|
||||
- **`bd list --skip-labels`.** New toggle to skip label hydration for faster listings; honored in both text and JSON output.
|
||||
- **`bd show` count-only JSON details.** `bd show --json` can return count-only relationship details with opt-in streamed payloads, avoiding large hydrations when only counts are needed.
|
||||
- **Server-side custom type validation.** Storage now honors `.beads/config.yaml` `types.custom` during server-side validation. ([#4024](https://github.com/gastownhall/beads/pull/4024), [#4026](https://github.com/gastownhall/beads/pull/4026))
|
||||
- **`bd init` contributor routing.** On fork detection, `bd init` auto-configures contributor routing. ([#4028](https://github.com/gastownhall/beads/pull/4028))
|
||||
|
||||
### Changed
|
||||
|
||||
- **Large content columns widened to `LONGTEXT`.** Issue content and event/wisp-event value columns are migrated from `TEXT` to `LONGTEXT`, lifting the previous ~64 KB per-field ceiling. ([#4027](https://github.com/gastownhall/beads/pull/4027), [#3682](https://github.com/gastownhall/beads/pull/3682))
|
||||
|
||||
- **`dependencies.depends_on_id` is now a STORED generated column.** The polymorphic target has been split into three typed columns: `depends_on_issue_id`, `depends_on_wisp_id`, `depends_on_external`. `depends_on_id` remains as `COALESCE(...) STORED` for read paths; **writes to `depends_on_id` will fail** — code that inserts dependencies must populate exactly one typed column (enforced by a new `ck_dep_one_target` CHECK). Same split mirrored to `wisp_dependencies` with a corresponding `ck_wisp_dep_one_target`. Migrations `0041` (tracked) and `ignored/0003` (wisps) perform the column split, copy existing rows by classifying their targets against `issues` / `wisps`, and add the new typed-target indexes. ([#3952](https://github.com/gastownhall/beads/pull/3952))
|
||||
- **Most existing dependency-table FKs now use `ON UPDATE CASCADE`.** Migration `0042` rebuilds `fk_dep_issue`, `fk_labels_issue`, `fk_comments_issue`, `fk_events_issue`, `fk_snapshots_issue`, and `fk_comp_snap_issue` to cascade on both delete and update. Same treatment for the wisp-side FKs in `ignored/0003`. Prefix rename and ID-update paths rely on this cascade instead of touching aux tables manually. ([#3952](https://github.com/gastownhall/beads/pull/3952))
|
||||
- **Migrations `0041` and `0042` are intentionally irreversible.** The matching `.down.sql` files are documented no-ops because rebuilding the polymorphic column from typed columns would require schema-aware backfill that the storage layer no longer performs. Restore from a prior `dolt` commit if rollback is required. ([#3952](https://github.com/gastownhall/beads/pull/3952))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Symlinked `CLAUDE.md` repair guidance** - troubleshooting docs now include
|
||||
a tested `git update-index --cacheinfo` recipe for repositories that already
|
||||
contain a corrupted `mode 120000` `CLAUDE.md` entry with Markdown content.
|
||||
The setup bug was fixed in [#4192](https://github.com/gastownhall/beads/pull/4192);
|
||||
this note is for repairing affected clones.
|
||||
- **Codex hook metadata isolation** - Codex hook metadata now lives under
|
||||
`.codex-plugin/hooks/`, preventing Claude from loading Codex-only hooks from
|
||||
the shared plugin root while keeping Codex setup pointed at `bd codex-hook`.
|
||||
([#3924](https://github.com/gastownhall/beads/issues/3924))
|
||||
- **Hook and prime wait bounds** - generated git hooks now fall back from
|
||||
`timeout` to `gtimeout` to Perl `alarm`, and `bd prime` memory loading is
|
||||
bounded by `BEADS_PRIME_TIMEOUT` (default 10s). Non-positive
|
||||
`BEADS_PRIME_TIMEOUT` values fall back to the default instead of silently
|
||||
disabling the safety bound. Internal beads-repo git operations also run with
|
||||
hooks suppressed via `core.hooksPath=` so automated `.beads/` commits and
|
||||
pushes cannot recurse through user hook managers. `GitCmdCWD()` remains for
|
||||
user-working-repo status/ref operations and does not perform beads commits.
|
||||
([#4172](https://github.com/gastownhall/beads/pull/4172))
|
||||
- **JSONL auto-export shrink guard** - when opt-in `export.auto` is enabled,
|
||||
auto-export now refuses to overwrite an existing `.beads/issues.jsonl` that
|
||||
contains records outside the auto-export scope (memories, infrastructure
|
||||
beads, templates, ephemeral wisps, or unknown record types). This prevents
|
||||
a viewer/interchange refresh from silently replacing a richer JSONL file
|
||||
with the filtered auto-export subset. ([#4069](https://github.com/gastownhall/beads/issues/4069))
|
||||
- `bd quick` now treats label insertion as part of issue creation: label
|
||||
failures abort the create instead of being silently dropped.
|
||||
- **`bd dolt status` reports externally-managed local servers truthfully** - when a rig is configured as `dolt_mode: server` pointing at a local host but `dolt.auto-start: false` (so an orchestrator or systemd owns the sql-server lifecycle), `bd dolt status` previously said `not running` because no PID file existed. It now SQL-probes the configured endpoint, matching the path already used for non-local hosts, and reports `running (external)` with host/port/database/version when the server answers. **JSON output shape change**: on affected rigs, `bd dolt status --json` now emits `{"running": true, "mode": "external", ...}` instead of `{"running": false, "pid": 0, ...}`. Automation that parsed the old `running:false` as a "needs restart" sentinel should switch to checking `running` directly. (be-0eyj, [#3550](https://github.com/gastownhall/beads/pull/3550))
|
||||
- **Migrations run on a connection with no read timeout**, so large or slow schema migrations no longer fail under the default query timeout. ([#4154](https://github.com/gastownhall/beads/pull/4154))
|
||||
- **Duplicate migration version numbers now hard-fail** instead of silently under-applying a release's migrations. ([#4197](https://github.com/gastownhall/beads/pull/4197))
|
||||
- **`bd close` supports per-id reasons** when closing multiple issues at once ([#4194](https://github.com/gastownhall/beads/pull/4194)), and **re-closing an already-closed issue is now an idempotent success** instead of an error. ([#4025](https://github.com/gastownhall/beads/issues/4025))
|
||||
- **`bd create --defer <future-date>` creates a deferred issue** (status `deferred`) rather than an open one. ([#4071](https://github.com/gastownhall/beads/issues/4071))
|
||||
- **`bd create` commits labels atomically** during initial issue creation; label-insertion failures abort the create instead of being silently dropped. ([#4149](https://github.com/gastownhall/beads/pull/4149))
|
||||
- **JSONL import preserves comment IDs and skips stale issue snapshots.** ([#4103](https://github.com/gastownhall/beads/pull/4103), [#4204](https://github.com/gastownhall/beads/pull/4204))
|
||||
- **`bd init` Dolt wiring hardening** - honor local-only remote wiring ([#4227](https://github.com/gastownhall/beads/pull/4227)), apply config server mode before validation, platform-accurate config-path warnings, and tighter Dolt marker handling ([#4083](https://github.com/gastownhall/beads/pull/4083)).
|
||||
- **MCP `validate` and `detect-pollution` route to `bd doctor`.** ([#4037](https://github.com/gastownhall/beads/issues/4037))
|
||||
- **`bd dolt` detects managed handoff port conflicts.** ([#4217](https://github.com/gastownhall/beads/pull/4217))
|
||||
- **`bd list` keeps `relates-to` out of dependency tree mode** and honors `--skip-labels` in JSON output. ([#3936](https://github.com/gastownhall/beads/pull/3936))
|
||||
- **Audit `newID` entropy widened** to reduce ID-collision risk under high create volume. ([#4046](https://github.com/gastownhall/beads/pull/4046))
|
||||
- **Performance:** `bd count` uses a SQL `COUNT(*)` aggregate instead of fetching and counting rows; `bd ready` narrows deferred-parent child filtering; `bd get` queries primary issues before falling back to wisps; and `bd search` gains skip-wisps merge and wisp-count caching.
|
||||
|
||||
## [1.0.4] - 2026-05-07
|
||||
|
||||
|
|
@ -32,7 +358,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- **Init refusal messages follow What/Why/Next structure** — runtime error text no longer echoes copy-pasteable destructive invocations. Token values and exact override commands live in `bd help init-safety` and `docs/RECOVERY.md` only. Closes the failure class where an AI agent destroyed 247 issues by pattern-matching on the tool's own error output (`58f5989bf`).
|
||||
- **`beads.OpenBestAvailable` signature changed (breaking)** — returns `(Storage, error)` instead of `(Storage, Unlocker, error)`. The per-open flock and `Unlocker` return value were removed; the embedded Dolt engine handles its own concurrency internally. External SDK consumers that call `OpenBestAvailable` must drop the second return value. ([PR #3614](https://github.com/gastownhall/beads/pull/3614))
|
||||
- **Embedded-mode flock removed** — the process-lifetime exclusive flock on `.beads/embeddeddolt/` has been removed. Concurrent `bd` processes now open the embedded engine independently. If the GH#2571 nil-deref stack (`NewConnector` → `DoltDB.SetCrashOnFatalError` → `CollectDBs`) resurfaces under concurrent access, it should be filed and fixed in `dolthub/driver`, not reintroduced as a beads-side flock. ([PR #3614](https://github.com/gastownhall/beads/pull/3614))
|
||||
- **Auto-export is now on by default** — pending Dolt changes are committed automatically and exported to JSONL when configured, reducing manual sync drift in coordinated repos.
|
||||
- **Auto-export is now opt-in by default** — repositories without explicit
|
||||
`export.auto` / `export.git-add` settings leave JSONL refresh and staging
|
||||
disabled unless a viewer or JSONL integration explicitly enables them. This
|
||||
keeps `.beads/issues.jsonl` as an optional export surface, not the default
|
||||
mutation path. ([GH#4062](https://github.com/gastownhall/beads/issues/4062))
|
||||
Thanks [Kevin Glynn](https://github.com/kevglynn) for surfacing the JSONL
|
||||
source-of-truth mismatch through the export cleanup work that led to this
|
||||
change.
|
||||
|
||||
- **Release workflow uses the checked-in beads-release formula** — the old release shell path now delegates to the formula-backed release workflow with CI gates.
|
||||
|
||||
### Deprecated
|
||||
|
|
|
|||
|
|
@ -89,6 +89,13 @@ CI will automatically run linting on all pull requests.
|
|||
|
||||
## Making Changes
|
||||
|
||||
### Project Scope
|
||||
|
||||
Before adding new feature surface area, read
|
||||
[docs/PROJECT_CHARTER.md](docs/PROJECT_CHARTER.md). Beads owns issue tracking
|
||||
primitives. It should not encode orchestration-layer policy, become a storage
|
||||
engine, or expand the database schema when issue metadata is sufficient.
|
||||
|
||||
### Workflow
|
||||
|
||||
1. Fork the repository
|
||||
|
|
@ -378,9 +385,9 @@ docker run --rm -v $(pwd):/workspace -w /workspace nixos/nix \
|
|||
sh -c 'echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf && nix build .#default && ./result/bin/bd version'
|
||||
```
|
||||
|
||||
If the build fails with a `vendorHash` mismatch, update `default.nix` with the `got:` hash from the error message and rebuild.
|
||||
If the build fails with a `vendorHash` mismatch, run `./scripts/update-nix-vendorhash.sh` to recompute and update `default.nix`, or update it manually with the `got:` hash from the error message and rebuild.
|
||||
|
||||
The `nix build` CI job (`.github/workflows/nix-build.yml`) runs on any PR that touches `go.mod`, `go.sum`, `default.nix`, `flake.nix`, or `flake.lock`, so dependabot bumps that invalidate `vendorHash` fail loudly instead of silently breaking Nix users on main.
|
||||
The `nix build` CI job (`.github/workflows/nix-build.yml`) runs on any PR that touches `go.mod`, `go.sum`, `default.nix`, `flake.nix`, or `flake.lock`, so dependabot bumps that invalidate `vendorHash` fail loudly instead of silently breaking Nix users on main. For dependabot Go-module bumps specifically, `.github/workflows/update-vendor-hash.yml` runs the same `update-nix-vendorhash.sh` script and pushes the hash bump back to the dependabot branch automatically (note: GitHub does not retrigger `pull_request` workflows for `GITHUB_TOKEN`-authored commits, so a maintainer may need to re-run `nix build .#default` once after the auto-fix push to mark the gate green).
|
||||
|
||||
### Debugging
|
||||
|
||||
|
|
|
|||
39
CONTRIBUTING_PR_GUIDELINES.md
Normal file
39
CONTRIBUTING_PR_GUIDELINES.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# Contributor PR Guidelines
|
||||
|
||||
This is the source of truth for agents and humans filing pull requests to beads.
|
||||
|
||||
## Philosophy
|
||||
|
||||
beads is small and clean. PRs that respect the existing layering land fastest. The codebase has clear layers — schema, storage/issueops, application (cmd/bd) — and the reviewer optimizes for keeping those layers clean and the diff reviewable. The most common rejection reasons are fixable before opening a PR.
|
||||
|
||||
## Before Opening a PR
|
||||
|
||||
**Prove the bug in beads itself.** Include a beads-only minimal repro test or benchmark that demonstrates the bug or performance regression exists with stock beads and no orchestrator (no gascity, no factory, no external agent framework). Without this, the PR will likely be rejected as an orchestrator bug.
|
||||
|
||||
**Verify with stock beads.** Before claiming any bug, reproduce it with no orchestrator running. Many apparent beads bugs turn out to be orchestrator-layer issues.
|
||||
|
||||
**Add benchmarks for performance claims.** If your PR claims a speedup, include a bench test that shows it. The reviewer will not assume the new code is faster.
|
||||
|
||||
## Sizing and Scoping
|
||||
|
||||
**One layer per PR.** If a fix needs changes at both the storage/issueops layer and the application (cmd/bd) layer, file them as separate stacked PRs: the storage primitive first, then the application wiring on top.
|
||||
|
||||
**Stack when a fix spans layers.** A PR that touches issueops primitives AND cmd/bd code at the same time is hard to review. Split it. The primitive PR unblocks the application PR.
|
||||
|
||||
**Keep diffs reviewable.** If your PR is over a few hundred lines, look for ways to split it. A 13K-line diff will not be reviewed.
|
||||
|
||||
## Layering Rules
|
||||
|
||||
**Primitives at the lowest layer first.** New capabilities belong at storage/issueops before the application calls them. If you are adding a new query, add it to issueops first, expose it on the storage.Storage interface, and implement it there. The application layer (cmd/bd) then calls the new method without reaching across layers itself.
|
||||
|
||||
**Do not reach across layers from above.** If cmd/bd is doing SQL-like work that belongs in issueops, that is a sign the abstraction boundary is wrong. File a storage primitive PR first.
|
||||
|
||||
## Code Style
|
||||
|
||||
**Minimize inline code comments.** The reviewer routinely asks for inline comments to be removed. Let the commit message and PR description carry the why. Use comments only for non-obvious invariants that cannot be expressed in the code itself.
|
||||
|
||||
**Commit messages over inline comments.** If you feel the need to explain a block of code with a comment, write that explanation in the commit message instead.
|
||||
|
||||
## When in Doubt
|
||||
|
||||
Read PR_MAINTAINER_GUIDELINES.md to understand what the maintainer optimizes for — it explains the review philosophy, triage groups, and outcome types. Understanding the maintainer perspective makes it easier to anticipate feedback before opening a PR.
|
||||
47
Makefile
47
Makefile
|
|
@ -9,7 +9,8 @@ SHELL := $(subst cmd,bin,$(subst git.exe,bash.exe,$(GIT_BASH)))
|
|||
endif
|
||||
endif
|
||||
|
||||
.PHONY: all build test test-icu-path test-full-cgo test-regression test-upgrade test-cross-version test-migration bench bench-quick clean install install-force help check-up-to-date fmt fmt-check
|
||||
.PHONY: all build test test-icu-path test-full-cgo test-regression test-upgrade test-cross-version test-migration corpus-regen bench bench-quick clean clean-test-tmp install install-force help check-up-to-date fmt fmt-check check-testing-short
|
||||
.PHONY: ci-pr-core ci-pr-policy ci-pr-lint ci-package-mcp ci-package-npm ci-website
|
||||
|
||||
# Default target
|
||||
all: build
|
||||
|
|
@ -79,6 +80,24 @@ test-full-cgo:
|
|||
@echo "WARNING: make test-full-cgo is deprecated; use make test-icu-path for the explicit ICU-only path." >&2
|
||||
@$(MAKE) test-icu-path
|
||||
|
||||
ci-pr-core:
|
||||
@./scripts/ci/pr-core.sh
|
||||
|
||||
ci-pr-policy:
|
||||
@./scripts/ci/pr-policy.sh
|
||||
|
||||
ci-pr-lint:
|
||||
@./scripts/ci/pr-lint.sh
|
||||
|
||||
ci-package-mcp:
|
||||
@./scripts/ci/package-mcp.sh
|
||||
|
||||
ci-package-npm:
|
||||
@./scripts/ci/package-npm.sh
|
||||
|
||||
ci-website:
|
||||
@./scripts/ci/website.sh
|
||||
|
||||
# Run differential regression tests (baseline v0.49.6 vs current worktree).
|
||||
# Downloads baseline binary on first run; cached in ~/Library/Caches/beads-regression/.
|
||||
# Override baseline: BD_REGRESSION_BASELINE_BIN=/path/to/bd make test-regression
|
||||
|
|
@ -110,6 +129,13 @@ test-migration: build
|
|||
@echo "Running migration test harness..."
|
||||
@CANDIDATE_BIN=./bd ./scripts/migration-test/run.sh
|
||||
|
||||
# Regenerate the golden-JSON contract corpus (cmd/bd/protocol/testdata/corpus/).
|
||||
# Run after any deliberate bd --json wire change; review the diff, then commit.
|
||||
# Gas City vendors this corpus to detect cross-version drift. Needs Docker (Dolt).
|
||||
corpus-regen:
|
||||
@echo "Regenerating contract corpus..."
|
||||
go test -tags "$(BUILD_TAGS)" ./cmd/bd/protocol -run TestCorpusGolden -corpus.update -count=1
|
||||
|
||||
|
||||
# Run performance benchmarks against Dolt storage backend
|
||||
# Requires CGO and Dolt; generates CPU profile files
|
||||
|
|
@ -188,6 +214,11 @@ check-docs:
|
|||
@echo "Building bd for docs checks..."
|
||||
@CGO_ENABLED=0 go build -tags "$(BUILD_TAGS)" -ldflags="-X main.Build=$(GIT_BUILD)" -o $(BUILD_DIR)/bd ./cmd/bd
|
||||
@./scripts/check-doc-flags.sh ./bd
|
||||
@./scripts/check-doc-freshness.sh
|
||||
|
||||
# Ensure -short is not used as an implicit CI tier boundary.
|
||||
check-testing-short:
|
||||
@./scripts/check-testing-short.sh
|
||||
|
||||
# Clean build artifacts and benchmark profiles
|
||||
clean:
|
||||
|
|
@ -197,6 +228,13 @@ clean:
|
|||
rm -f internal/storage/dolt/bench-cpu-*.prof
|
||||
rm -f beads-perf-*.prof
|
||||
|
||||
# Sweep orphaned cmd/bd test temp dirs (e.g. when a test run was SIGKILLed
|
||||
# before its TestMain cleanup ran). Safe to run between test runs; will
|
||||
# skip dirs in use by a live test process. See bd-3q2u.
|
||||
clean-test-tmp:
|
||||
@echo "Sweeping orphaned cmd/bd test temp dirs from $${TMPDIR:-/tmp}..."
|
||||
@./scripts/clean-test-tmp.sh
|
||||
|
||||
# Show help
|
||||
help:
|
||||
@echo "Beads Makefile targets:"
|
||||
|
|
@ -204,6 +242,12 @@ help:
|
|||
@echo " make test - Run all tests"
|
||||
@echo " make test-icu-path - Run opt-in ICU regex path tests (maintainer-only)"
|
||||
@echo " make test-full-cgo - Deprecated alias for make test-icu-path"
|
||||
@echo " make ci-pr-core - Run required PR core Go test wrapper"
|
||||
@echo " make ci-pr-policy - Run required PR policy wrapper"
|
||||
@echo " make ci-pr-lint - Run required PR formatting and lint wrapper"
|
||||
@echo " make ci-package-mcp - Run MCP Python package gate"
|
||||
@echo " make ci-package-npm - Run npm package gate"
|
||||
@echo " make ci-website - Run website typecheck/build gate"
|
||||
@echo " make test-regression - Run differential regression tests (baseline vs candidate)"
|
||||
@echo " make test-upgrade - Run upgrade smoke tests (release stability gate)"
|
||||
@echo " make test-cross-version - Run cross-version smoke tests (last 30 tags)"
|
||||
|
|
@ -216,4 +260,5 @@ help:
|
|||
@echo " make fmt-check - Check Go formatting (for CI)"
|
||||
@echo " make check-docs - Validate docs against CLI flags"
|
||||
@echo " make clean - Remove build artifacts and profile files"
|
||||
@echo " make clean-test-tmp - Sweep orphaned cmd/bd test temp dirs from \$$TMPDIR"
|
||||
@echo " make help - Show this help message"
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ Contributors: coffeegoddd (Dustin Brown / DoltHub), matt wilkie (maphew), harry-
|
|||
## Upgrade
|
||||
|
||||
```bash
|
||||
brew upgrade bd
|
||||
brew upgrade beads
|
||||
# or
|
||||
curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash
|
||||
```
|
||||
|
|
|
|||
173
PROPOSAL-pull-config-wedge.md
Normal file
173
PROPOSAL-pull-config-wedge.md
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
# Proposal: fix `bd dolt pull` "cannot merge with uncommitted changes" wedge
|
||||
|
||||
**Status:** for review (diagnosis + patch). Authored 2026-06-14 from a live repro in
|
||||
the Wyvern beads DB (server mode, git-protocol remote on Bitbucket).
|
||||
|
||||
## Symptom
|
||||
|
||||
`bd dolt pull` always fails:
|
||||
|
||||
```
|
||||
Error 1105 (HY000): cannot merge with uncommitted changes
|
||||
```
|
||||
|
||||
`bd doctor` reports `Dolt Locks: config: modified` immediately after every command,
|
||||
even right after `bd dolt commit`, and even with `--dolt-auto-commit on`. Tracked as
|
||||
Wyvern wy-71t. Push is unaffected; only pull (the cross-clone *receive* path) is wedged.
|
||||
|
||||
## Root cause — two correct PRs collide over the `config` table
|
||||
|
||||
1. **Memories live in `config`.** `bd remember` stores each persistent memory as a
|
||||
`kv.memory.<slug>` row in the **synced** `config` table. Confirmed via the working
|
||||
set on the live DB — the only dirty rows were exactly the 5 memories:
|
||||
|
||||
```
|
||||
SELECT to_key, diff_type FROM dolt_diff('main','WORKING','config');
|
||||
kv.memory.beads-jsonl-sync-procedure added
|
||||
kv.memory.bitbucket-altssh-dead added
|
||||
kv.memory.local-dev-ssl-posture added
|
||||
kv.memory.react-client-e2e-against-the-local-game-server added
|
||||
kv.memory.react-e2e-same-character-parallel-logins added
|
||||
```
|
||||
|
||||
2. **`Commit` deliberately excludes `config`** (GH#2455, `store.go` ~1731):
|
||||
`DOLT_COMMIT('-Am', …)` once swept stale `issue_prefix` changes from concurrent
|
||||
operations into commits, so `Commit` now stages every dirty table *except* `config`.
|
||||
|
||||
3. **The pre-pull auto-commit uses `Commit`** (GH#2474). Both pull paths try to clean
|
||||
the working set before merging, but call `s.Commit`, which skips `config`:
|
||||
|
||||
- `internal/storage/dolt/store.go:2309` — `pullFromRemote` (default remote; what
|
||||
`bd dolt pull` invokes via `st.Pull`)
|
||||
- `internal/storage/dolt/federation.go:65` — `PullFrom` (named-peer pull)
|
||||
|
||||
**Net effect:** once any memory exists, the `kv.memory.*` rows sit permanently
|
||||
uncommitted (nothing ever commits `config`), so the pre-pull "clean the working set"
|
||||
step leaves `config` dirty, and `DOLT_MERGE` refuses to start — the exact case
|
||||
`abortMerge`'s comment already calls out: *"a merge that REFUSED TO START on a dirty
|
||||
working set."* GH#2474's intent is silently defeated by GH#2455 whenever `config` is
|
||||
the dirty table, which is always after the first `bd remember`.
|
||||
|
||||
This is independent of the v42→v51 schema-migration fork (#4259) seen in the same DB;
|
||||
that was a separate, newer problem. Migrating + force-publishing fixed the fork and
|
||||
restored `push`, but `pull` stays wedged because of this config issue.
|
||||
|
||||
## Empirical validation (live DB)
|
||||
|
||||
Confirmed the mechanism end-to-end without any source change:
|
||||
|
||||
1. The only dirty table was `config`; the only dirty rows were the 5 `kv.memory.*`
|
||||
entries (see query above).
|
||||
2. Explicitly committing config — `CALL DOLT_ADD('config'); CALL DOLT_COMMIT('-m', …)` —
|
||||
left the working set **clean** (`dolt_diff('HEAD','WORKING','config')` → 0 rows).
|
||||
3. Running ordinary commands afterward (`bd list`, `bd show`) kept it clean (still 0).
|
||||
So bd's per-command memory re-sync is **idempotent**: once the rows match HEAD,
|
||||
re-writing identical values produces no diff. The "re-dirties after every command"
|
||||
symptom existed *only* because the rows were never committed (Commit skips config),
|
||||
so they showed as permanently uncommitted. Committing config once breaks the cycle.
|
||||
|
||||
This proves a clean `config` working set is the *only* thing the merge needs, and that
|
||||
a pre-merge commit of config is a permanent fix, not a per-command band-aid.
|
||||
|
||||
**Confirmed:** after committing config, `bd dolt pull` succeeds ("Pull complete.")
|
||||
repeatably, `bd dolt push` still works, and `bd doctor` no longer reports
|
||||
`config: modified`. The wedge is entirely the uncommitted-config condition; the patch
|
||||
just makes the pull path establish it automatically. (Without the patch the wedge
|
||||
returns on the next `bd remember`, which adds a fresh uncommitted `kv.memory.*` row.)
|
||||
|
||||
**One wrinkle to verify in the patch:** a standalone `bd dolt commit` (which already
|
||||
routes through `CommitWithConfig` → `DOLT_COMMIT('-Am', …)`) did **not** visibly clean
|
||||
`config` in this server-mode DB, whereas the explicit `DOLT_ADD('config')` +
|
||||
`DOLT_COMMIT('-m', …)` did. That suggests `-Am` may not be staging `config` reliably
|
||||
under the SQL stored-procedure path here. The patch author should confirm `CommitWithConfig`
|
||||
actually commits `config` in server mode; if not, the pre-pull step should stage config
|
||||
explicitly (`CALL DOLT_ADD('config')` then commit) rather than rely on `-Am`. A regression
|
||||
test should assert `dolt_status` is empty immediately after the pre-pull commit.
|
||||
|
||||
## Fix (primary) — pre-pull commit must include `config`
|
||||
|
||||
`CommitWithConfig` already exists (`store.go:1780`) for exactly this "commit everything,
|
||||
including intentional config" case — `CommitPending` (`bd dolt commit`) already uses it.
|
||||
Use it in the two pre-pull sites:
|
||||
|
||||
```diff
|
||||
--- a/internal/storage/dolt/store.go
|
||||
+++ b/internal/storage/dolt/store.go
|
||||
@@ pullFromRemote (GH#2474 pre-pull auto-commit)
|
||||
- if err := s.Commit(ctx, "auto-commit before pull"); err != nil {
|
||||
+ // Include config: persistent memories live in config as kv.memory.* rows,
|
||||
+ // and Commit() excludes config (GH#2455), so they never commit and leave
|
||||
+ // the working set permanently dirty — DOLT_MERGE then refuses to start.
|
||||
+ if err := s.CommitWithConfig(ctx, "auto-commit before pull"); err != nil {
|
||||
if !isDoltNothingToCommit(err) {
|
||||
return fmt.Errorf("failed to commit pending changes before pull: %w", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```diff
|
||||
--- a/internal/storage/dolt/federation.go
|
||||
+++ b/internal/storage/dolt/federation.go
|
||||
@@ PullFrom (GH#2474 pre-pull auto-commit)
|
||||
- if err := s.Commit(ctx, "auto-commit before pull"); err != nil {
|
||||
+ if err := s.CommitWithConfig(ctx, "auto-commit before pull"); err != nil {
|
||||
if !isDoltNothingToCommit(err) {
|
||||
return nil, fmt.Errorf("failed to commit pending changes before pull: %w", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Why this does not reintroduce GH#2455
|
||||
|
||||
GH#2455 guards against `-Am` sweeping a *concurrent writer's* half-applied `issue_prefix`
|
||||
change into an unrelated commit. The pre-pull commit is different in kind: it is an
|
||||
explicit user action (`bd dolt pull`) that **requires** a clean working set, and it is
|
||||
committing *this clone's own* config state as the basis for the merge — exactly what
|
||||
`CommitPending` already does for `bd dolt commit`. The race window GH#2455 worried about
|
||||
(another bd process mutating `issue_prefix` at the same instant) is not meaningfully
|
||||
widened by committing config here versus letting the user's next `bd dolt commit` do it.
|
||||
|
||||
## Fix (optional hardening) — auto-resolve convergent `config` merge conflicts
|
||||
|
||||
With the primary fix, `config` (incl. `kv.memory.*`) becomes a committed, synced table,
|
||||
so two clones that edit the *same* memory will produce a `config` merge conflict.
|
||||
`TryAutoResolveMergeConflicts` (`mergesettle.go`) currently handles only `metadata`,
|
||||
`dependencies`, and `schema_migrations` — **not** `config` — so such a conflict would
|
||||
stop the pull for the operator.
|
||||
|
||||
Recommend a follow-up that teaches the resolver to auto-resolve `config` conflicts on
|
||||
machine-convergent keys (e.g. `kv.memory.*`) with `--theirs`, the same convergent policy
|
||||
already used for the `metadata` table. Out of scope for the wedge fix itself; the primary
|
||||
change resolves the reported bug. (Until then, divergent same-memory edits are a rare,
|
||||
operator-visible case rather than a silent wedge.)
|
||||
|
||||
## Alternative considered — move memories to a `dolt_ignore`'d table
|
||||
|
||||
Rejected: memories are meant to **sync** (they round-trip through `bd export | bd import`,
|
||||
and are part of cross-clone shared state). `dolt_ignore` (as used for wisps) would make
|
||||
them machine-local and stop syncing them via Dolt — a behavior change, not a fix.
|
||||
|
||||
## Test plan
|
||||
|
||||
Regression test (alongside `pull_conflict_test.go` / `federation_pull_settle_test.go`):
|
||||
|
||||
1. Two clones of a tiny remote-backed DB.
|
||||
2. On clone A: `bd remember --key t "x"` (dirties `config` with a `kv.memory.*` row,
|
||||
committing nothing via the normal path).
|
||||
3. On clone B: create+push an issue.
|
||||
4. On clone A: `Pull` — **must succeed** (today it returns
|
||||
`cannot merge with uncommitted changes`), and clone A must end with B's issue *and*
|
||||
its own memory intact.
|
||||
|
||||
Manual repro on the Wyvern DB: a fresh `bd dolt pull` fails today purely on the 5
|
||||
`kv.memory.*` rows; with the patch the pre-pull `CommitWithConfig` commits them and the
|
||||
merge proceeds.
|
||||
|
||||
## Files
|
||||
|
||||
- `internal/storage/dolt/store.go:2309` (`pullFromRemote`) — primary
|
||||
- `internal/storage/dolt/federation.go:65` (`PullFrom`) — primary
|
||||
- `internal/storage/dolt/store.go:1780` (`CommitWithConfig`) — reused, unchanged
|
||||
- `internal/storage/versioncontrolops/mergesettle.go` (`TryAutoResolveMergeConflicts`)
|
||||
— optional hardening
|
||||
```
|
||||
|
|
@ -10,15 +10,20 @@ For every PR, look for the value in it and choose the action that moves useful w
|
|||
|
||||
The goal is not to block contributors unnecessarily. The goal is to identify useful work, preserve it, and keep the project moving.
|
||||
|
||||
Read [docs/PROJECT_CHARTER.md](docs/PROJECT_CHARTER.md) when a PR changes
|
||||
Beads' product surface area. Scope boundaries should guide where value lands:
|
||||
core, metadata, integration, plugin, orchestration layer, or external tool.
|
||||
|
||||
## Contributor Protection
|
||||
|
||||
External contributor PRs have priority. Before implementing related work, opening a competing PR, or closing a PR, check whether an existing contributor PR already addresses the same area.
|
||||
|
||||
- Review contributor work first. Read the PR description, changed files, linked issues, tests, CI status, and latest discussion.
|
||||
- Build on the contributor branch when practical instead of rewriting the same work in parallel.
|
||||
- Build on the contributor branch by default. If the PR branch allows maintainer edits, push maintainer fix commits directly to that branch instead of opening a replacement PR.
|
||||
- Preserve contributor tests unless they are actually wrong.
|
||||
- Preserve attribution with original commits when possible, or with `Co-authored-by:` and PR references when transforming the work locally.
|
||||
- Preserve attribution with original commits when possible. Maintainer commits on a contributor branch should keep the contributor's original commits intact; transformed local commits must use `Co-authored-by:` and PR references.
|
||||
- Never close, supersede, or replace a contributor PR silently. Explain what was preserved, what changed, and why.
|
||||
- Open a replacement PR only when in-place maintainer edits are not possible or would create a larger risk, such as when the contributor branch is not writable, the branch history is unusable, or the accepted change must be substantially reimplemented. Document that reason in both PR threads.
|
||||
- If a rewrite is unavoidable, credit the contributor's design, tests, bug report, or use case in the replacement commit or PR.
|
||||
|
||||
## Triage Groups
|
||||
|
|
@ -40,9 +45,10 @@ Use these recommendations after review:
|
|||
- **Easy win**: The PR turns out to fit easy-win criteria after all.
|
||||
- **Merge**: Recommend merge. The PR is well-tested, broadly useful, well-documented, and ready as-is.
|
||||
- **Merge-fix**: Merge the PR as-is, then push a follow-up fix to `main`. Use when the remaining issues are safe to repair afterward.
|
||||
- **Fix-merge**: Pull the PR locally, make substantial fixes, then push with contributor attribution. Use when the PR is busted but valuable.
|
||||
- **Fix-merge**: Pull the PR locally, make substantial fixes on the contributor branch, then push the branch so the original PR can merge. Use when the PR is busted but valuable and maintainer edits are possible.
|
||||
- **Cherry-pick**: Keep only selected items from a PR with multiple features or fixes. Commit the useful parts locally with attribution, then close the PR with an explanation.
|
||||
- **Split-merge**: Split a multi-concern PR into separate commits, then push all accepted parts with attribution to the original contributor.
|
||||
- **Replacement PR**: Carry useful work into a new maintainer PR only after confirming the original branch cannot reasonably be fixed in place. Preserve attribution with original commits where possible, otherwise use `Co-authored-by:` trailers and PR references, and explain the reason replacement was necessary.
|
||||
- **Redesign/reimplement**: Reject the submitted design but solve the underlying problem another way. Close the PR with thanks and an explanation.
|
||||
- **Retire**: Close an obsolete PR with thanks because it was superseded or already fixed elsewhere.
|
||||
- **Reject**: Close politely when the feature does not pay its weight in tech debt, is too niche for core, or the design does not meet project standards.
|
||||
|
|
@ -50,12 +56,48 @@ Use these recommendations after review:
|
|||
|
||||
Other outcomes are possible, including rerouting a PR to the right project or banning a contributor, but the list above covers the normal cases.
|
||||
|
||||
## Merge Discipline and Review Requirements
|
||||
|
||||
These rules apply to everyone who can merge — human maintainers and agents alike. They exist because a two-month audit of 440 merged PRs (epic bd-6dnrw) found the project's worst defects entered through merges that skipped review, hid their real contents, or overrode an outstanding objection. A merge is an irreversible act of trust; treat it as one.
|
||||
|
||||
### Self-merge and outstanding objections
|
||||
|
||||
- Do not self-merge a nontrivial PR. "Nontrivial" is anything beyond a typo, comment, or pure-docs fix: any code, schema, migration, build, CI, dependency, or sync-path change. Nontrivial work authored by a maintainer or agent must be merged by a different reviewer.
|
||||
- Never merge over an unresolved `CHANGES_REQUESTED` review. The requested changes must be addressed and the reviewer's objection withdrawn (or explicitly overridden by the project owner, recorded in the thread) before merge. A new approval does not erase a standing change request from someone else.
|
||||
- A WIP- or draft-titled branch is not mergeable. Finish it, retitle it, and get it reviewed.
|
||||
|
||||
### The PR body must match the diff
|
||||
|
||||
- The title and body must describe the riskiest thing the diff actually does. A docs or test title may not carry a storage-, schema-, migration-, or sync-layer change underneath it.
|
||||
- One PR, one coherent concern. Do not bundle unrelated commits behind a small-sounding claim ("19-line fix" that drags in six commits). Split grab-bags before merge.
|
||||
- If the body and the diff disagree, the PR is not ready — fix the body or shrink the diff. Reviewers and future auditors rely on the body being true.
|
||||
|
||||
### Review must be real and accountable
|
||||
|
||||
- A merge needs a substantive human review, not a rubber stamp. An approval that engaged with the change is required; an empty approval or a bot-only approval does not satisfy the review requirement for nontrivial PRs.
|
||||
- Reviews posted by an automated agent must say so plainly and must not impersonate a maintainer. If a review was posted in error by an agent under a human's account, it does not count and must be retracted.
|
||||
- Approvals from unidentified or unestablished accounts do not satisfy the review requirement. The reviewer must be a known, accountable participant.
|
||||
|
||||
### Schema, migration, and sync paths are protected
|
||||
|
||||
- Any change touching `migrations/`, the schema, destructive data paths, or the Dolt sync/clone/merge paths requires a filled-out PR template and a real human review before merge — no exceptions, no self-merge, no bot-only approval.
|
||||
- These paths should be enforced by branch protection (review-required), not just convention. (Configuring branch protection and defining which agent identities may merge are owner actions tracked in bd-6dnrw.23.)
|
||||
|
||||
### Revert ping-pong
|
||||
|
||||
- If a change to a sync-critical file is reverted, stop merging in that area. Do not re-merge, re-revert, and re-merge in a tight loop; that pattern (five merges in two hours on the same sync files) is how regressions get laundered into `main`.
|
||||
- After a revert, open an issue, diagnose the root cause, and land a single reviewed fix. Escalate to the project owner rather than continuing a revert cycle.
|
||||
|
||||
## Operating Rules
|
||||
|
||||
- Prefer landing or transforming useful work over asking the contributor to do more rounds.
|
||||
- Preserve contributor attribution when absorbing, fixing, cherry-picking, splitting, or reimplementing PR value.
|
||||
- Before opening a competing or replacement PR, attempt the contributor-branch path first: fetch the PR, test it, make maintainer fix commits on that branch when permitted, and push back to the same PR.
|
||||
- Be explicit when closing a PR: thank the contributor, state the outcome, and explain what was accepted, rejected, superseded, or implemented differently.
|
||||
- Treat request-changes as exceptional because it can strand contributor work.
|
||||
- Consider the entire PR thread. Valuable clarifying info are often in the comments.
|
||||
- File follow-up work as beads issues instead of hidden notes.
|
||||
- When code changes result from PR maintenance, follow repo quality gates and session completion rules in `AGENTS.md`.
|
||||
- Post multi-line PR comments from a real Markdown body file or a shell heredoc, not from strings with escaped `\n` sequences. After posting or editing, verify the rendered body with `gh pr view --comments --json comments --jq ...` before moving on.
|
||||
- Post multi-line PR comments from a real Markdown body file or a shell heredoc, not from strings with escaped `\n` sequences. Run `scripts/gh-body-lint <body-file>` before posting body files; after posting or editing, verify the rendered body with `gh pr view --comments --json comments --jq ...` before moving on.
|
||||
- Sign agent-written GitHub comments, reviews, and commits using [docs/AGENT_SIGNING.md](docs/AGENT_SIGNING.md).
|
||||
- Before finishing, re-read the PR, latest comments, review threads, and linked issues; address or explicitly note any unresolved action items.
|
||||
|
|
|
|||
57
README.md
57
README.md
|
|
@ -24,15 +24,15 @@ curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/inst
|
|||
cd your-project
|
||||
bd init
|
||||
|
||||
# Optional: install richer instructions for your agent
|
||||
bd setup codex # Codex CLI - creates/updates AGENTS.md
|
||||
# Optional: refresh or install richer instructions for your agent
|
||||
bd setup codex # Codex CLI - installs skill, AGENTS.md guidance, and hooks
|
||||
bd setup claude # Claude Code - installs hooks/settings
|
||||
bd setup factory # Factory.ai Droid - creates/updates AGENTS.md
|
||||
```
|
||||
|
||||
**Note:** Beads is a CLI tool you install once and use everywhere. You don't need to clone this repository into your project.
|
||||
|
||||
`bd init` creates or updates `AGENTS.md` by default so agents can discover the beads workflow. It skips agent files only when you pass `--skip-agents` or `--stealth`, or when you configure a custom agent file. Use `bd setup --list` to see supported integrations, including `bd setup codex`, `bd setup factory`, `bd setup claude`, `bd setup mux`, `bd setup cursor`, and more. See [Agent and IDE setup](docs/SETUP.md).
|
||||
`bd init` creates or updates `AGENTS.md` by default so agents can discover the beads workflow, and also installs project Claude/Codex integrations unless you pass `--skip-agents` or `--stealth`. Use `bd setup --list` to see supported integrations, including `bd setup codex`, `bd setup factory`, `bd setup claude`, `bd setup mux`, `bd setup cursor`, and more. See [Agent and IDE setup](docs/SETUP.md).
|
||||
|
||||
Manual copy-paste is only for unsupported agents, existing projects where you cannot rerun `bd init`/`bd setup`, or custom instruction files. In those cases, run `bd onboard` and paste the printed snippet into the file your agent reads.
|
||||
|
||||
|
|
@ -94,6 +94,12 @@ npm install -g @beads/bd # Node.js users
|
|||
|
||||
**Requirements:** macOS, Linux, Windows, or FreeBSD. See [docs/INSTALLING.md](docs/INSTALLING.md) for complete installation guide.
|
||||
|
||||
**Upgrading?** Replacing the binary is not always the whole story: releases can
|
||||
carry schema migrations, and a database that syncs to a Dolt remote must be
|
||||
migrated by exactly one designated clone. Back up first (`bd export --all`),
|
||||
then follow the [upgrade guide](https://gastownhall.github.io/beads/docs/getting-started/upgrading)
|
||||
(also summarized in [docs/INSTALLING.md](docs/INSTALLING.md#updating-bd)).
|
||||
|
||||
### Security And Verification
|
||||
|
||||
Before trusting any downloaded binary, verify its checksum against the release `checksums.txt`.
|
||||
|
|
@ -119,6 +125,12 @@ Dolt runs in-process — no external server needed. Data lives in
|
|||
`.beads/embeddeddolt/`. Single-writer only (file locking enforced).
|
||||
This is the recommended mode for most users.
|
||||
|
||||
When the git repo has an `origin` remote, `bd init` configures a Dolt remote
|
||||
named `origin` automatically. Cross-machine sync uses `bd dolt push` and
|
||||
`bd dolt pull` against `refs/dolt/data`; `.beads/issues.jsonl` is an export
|
||||
for viewers and interchange, not the source of truth or a full database
|
||||
backup.
|
||||
|
||||
### Server Mode
|
||||
|
||||
```bash
|
||||
|
|
@ -136,7 +148,6 @@ or environment variables:
|
|||
| `--server-socket` | `BEADS_DOLT_SERVER_SOCKET` | (none; uses TCP) |
|
||||
| `--server-user` | `BEADS_DOLT_SERVER_USER` | `root` |
|
||||
| | `BEADS_DOLT_PASSWORD` | (none) |
|
||||
| | `BEADS_DOLT_CLI_DIR` | local Dolt database path for CLI push/pull |
|
||||
|
||||
**Unix domain sockets:** Use `--server-socket` to connect via a Unix socket
|
||||
instead of TCP. This avoids port conflicts between concurrent projects and
|
||||
|
|
@ -145,11 +156,30 @@ access control is simpler than network allowlists. The Dolt server must be
|
|||
started with `dolt sql-server --socket <path>`. Auto-start is not supported
|
||||
in socket mode.
|
||||
|
||||
When `BEADS_DOLT_SERVER_MODE=1` points at a Dolt server managed outside
|
||||
Beads, set `BEADS_DOLT_CLI_DIR` if `bd dolt push` / `bd dolt pull` must use
|
||||
the local `dolt` CLI (for example git-protocol remotes or credentials that
|
||||
only exist in the current shell). Use the actual Dolt database directory, not
|
||||
the server root.
|
||||
### Maintenance — `bd prune` and `bd purge`
|
||||
|
||||
`bd prune` permanently deletes closed non-ephemeral beads to reclaim storage
|
||||
and shrink auto-exports. `bd purge` does the same for ephemeral beads (wisps,
|
||||
transient molecules). Both require `--force` to execute.
|
||||
|
||||
```bash
|
||||
bd prune --older-than 30d # Preview closed beads >30d old
|
||||
bd prune --older-than 30d --force # Delete them
|
||||
bd prune --older-than 90d --dry-run # Detailed preview with stats
|
||||
bd purge --force # Delete all closed ephemeral beads
|
||||
```
|
||||
|
||||
**Reference-aware protection:** `bd prune` automatically skips closed beads
|
||||
whose ID appears in the description, notes, or comments of any open or
|
||||
in-progress bead. This prevents accidental deletion of ADR, decision, and
|
||||
verification beads that downstream work still cites. Use `--ignore-references`
|
||||
to override when cleaning up known-stale references:
|
||||
|
||||
```bash
|
||||
bd prune --older-than 90d --ignore-references --force
|
||||
```
|
||||
|
||||
`bd purge` is unaffected — ephemeral beads' references are themselves transient.
|
||||
|
||||
### Backup & Migration
|
||||
|
||||
|
|
@ -168,10 +198,17 @@ bd backup restore --force /path/to/backup
|
|||
See [docs/DOLT.md](docs/DOLT.md#migrating-between-backends) for full
|
||||
migration instructions.
|
||||
|
||||
`bd export` and `.beads/issues.jsonl` are issue-table exports. They are useful
|
||||
for review, migration, and interoperability, but they do not capture Dolt
|
||||
branches, commit history, working-set state, or non-issue tables. Use
|
||||
`bd backup` or a manual Dolt backup when you need a restorable database backup.
|
||||
|
||||
## 🌐 Community Tools
|
||||
|
||||
See [docs/COMMUNITY_TOOLS.md](docs/COMMUNITY_TOOLS.md) for a curated list of community-built UIs, extensions, and integrations—including terminal interfaces, web UIs, editor extensions, and native apps.
|
||||
|
||||
See [docs/RELATED_PROJECTS.md](docs/RELATED_PROJECTS.md) for adjacent or complementary projects that solve different problems in the same neighborhood.
|
||||
|
||||
## 🚀 Git-Free Usage
|
||||
|
||||
Beads works without git. The Dolt database is the storage backend — git
|
||||
|
|
@ -205,5 +242,5 @@ For daemon mode without git, use `bd daemon start --local`
|
|||
|
||||
## 📝 Documentation
|
||||
|
||||
* [Documentation site](https://gastownhall.github.io/beads/) (versioned) | [Installing](docs/INSTALLING.md) | [Agent Workflow](AGENT_INSTRUCTIONS.md) | [Copilot Setup](docs/COPILOT_INTEGRATION.md) | [Articles](ARTICLES.md) | [Sync Branch Mode](docs/PROTECTED_BRANCHES.md) | [Troubleshooting](docs/TROUBLESHOOTING.md) | [FAQ](docs/FAQ.md)
|
||||
* [Documentation site](https://gastownhall.github.io/beads/) (versioned) | [Installing](docs/INSTALLING.md) | [Sync Concepts](docs/SYNC_CONCEPTS.md) | [Agent Workflow](AGENT_INSTRUCTIONS.md) | [Copilot CLI Setup](docs/COPILOT_CLI_INTEGRATION.md) | [Copilot VS Code MCP](docs/COPILOT_INTEGRATION.md) | [Articles](ARTICLES.md) | [Sync Branch Mode](docs/PROTECTED_BRANCHES.md) | [Troubleshooting](docs/TROUBLESHOOTING.md) | [FAQ](docs/FAQ.md)
|
||||
* [](https://deepwiki.com/gastownhall/beads)
|
||||
|
|
|
|||
127
RELEASING.md
127
RELEASING.md
|
|
@ -13,6 +13,7 @@ This document describes the complete release process for beads, including GitHub
|
|||
- [4. PyPI Release (MCP Server)](#4-pypi-release-mcp-server)
|
||||
- [5. npm Package Release](#5-npm-package-release)
|
||||
- [6. Verify Release](#6-verify-release)
|
||||
- [Prerelease / Release Candidate (RC) Workflow](#prerelease--release-candidate-rc-workflow)
|
||||
- [Hotfix Releases](#hotfix-releases)
|
||||
- [Rollback Procedure](#rollback-procedure)
|
||||
|
||||
|
|
@ -25,6 +26,20 @@ A beads release involves multiple distribution channels:
|
|||
3. **PyPI** - Python MCP server (`beads-mcp`)
|
||||
4. **npm** - Node.js package for Claude Code for Web (`@beads/bd`)
|
||||
|
||||
### The Easy Way (Recommended)
|
||||
|
||||
For routine releases, use the fully automated release script:
|
||||
|
||||
```bash
|
||||
./scripts/release.sh 0.22.0
|
||||
```
|
||||
|
||||
This handles version bump, tests, git tag, Homebrew update, and local
|
||||
installation in one shot. See [scripts/README.md](scripts/README.md#releasesh--the-easy-button)
|
||||
for details. The rest of this document is the manual / step-by-step process,
|
||||
useful for understanding what `release.sh` does and for handling edge cases
|
||||
(hotfixes, rollbacks, manual PyPI/npm publishes).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Required Tools
|
||||
|
|
@ -155,6 +170,18 @@ The `--commit --tag --push` flags will:
|
|||
|
||||
This triggers GitHub Actions to build release artifacts automatically.
|
||||
|
||||
The tag workflow re-runs release-critical package gates before publishing:
|
||||
|
||||
- `make ci-package-mcp` builds and validates the MCP package, then the PyPI job
|
||||
publishes the validated `dist/*` artifact from that gate.
|
||||
- `make ci-package-npm` validates the npm wrapper package before npm publish.
|
||||
- `make ci-website` validates the release docs/website build before GoReleaser
|
||||
publishes GitHub release assets.
|
||||
|
||||
The npm publish job also waits for the macOS release assets, because the npm
|
||||
`postinstall` script downloads platform-specific archives from the GitHub
|
||||
release.
|
||||
|
||||
**Recommended workflow:**
|
||||
|
||||
```bash
|
||||
|
|
@ -241,7 +268,13 @@ gh release create v0.22.0 \
|
|||
|
||||
## 3. Homebrew Update
|
||||
|
||||
Homebrew formula is now in homebrew-core. Updates are handled automatically via GitHub Release artifacts.
|
||||
Homebrew uses the `beads` formula in homebrew-core. Do not publish or revive
|
||||
the old `bd` formula in `gastownhall/homebrew-beads`; having two independently
|
||||
updated Homebrew formulas causes version drift and installs the wrong binary for
|
||||
some users.
|
||||
|
||||
Updates to the supported Homebrew formula are handled through Homebrew core
|
||||
after GitHub Release artifacts are available.
|
||||
|
||||
### Verify Homebrew
|
||||
|
||||
|
|
@ -333,6 +366,25 @@ git commit -m "chore: Update plugin marketplaces to v0.22.0"
|
|||
|
||||
**Note:** These files define how beads appears in Claude Code and Codex plugin marketplaces. Version should match the release version.
|
||||
|
||||
### Documentation Site (Docusaurus)
|
||||
|
||||
The published docs at GitHub Pages are versioned. Unreleased edits live in
|
||||
`website/docs/` (**Next**); each release should add a snapshot:
|
||||
|
||||
```bash
|
||||
cd website
|
||||
npm ci
|
||||
npm run docusaurus docs:version X.Y.Z
|
||||
```
|
||||
|
||||
Then set `lastVersion` in `website/docusaurus.config.ts` to `X.Y.Z` so
|
||||
visitors default to the latest stable docs (not **Next**).
|
||||
|
||||
Commit `website/versioned_docs/`, `website/versioned_sidebars/`, and
|
||||
`website/versions.json` with the release. The
|
||||
`scripts/generate-llms-full.sh` script pulls from the latest entry in
|
||||
`versions.json` so `llms-full.txt` stays aligned with that snapshot.
|
||||
|
||||
## 6. npm Package Release
|
||||
|
||||
The npm package wraps the native binary for Node.js environments.
|
||||
|
|
@ -462,6 +514,74 @@ curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/inst
|
|||
bd version
|
||||
```
|
||||
|
||||
## Prerelease / Release Candidate (RC) Workflow
|
||||
|
||||
Release candidates let a build be validated through the full release pipeline
|
||||
without promoting it to the stable channels. An RC carries a SemVer prerelease
|
||||
identifier (e.g. `1.1.0-rc.1`); Python tooling normalizes this to PEP 440 form
|
||||
(`1.1.0rc1`).
|
||||
|
||||
**How a prerelease tag differs from a stable release:**
|
||||
|
||||
- **GitHub release** is published and **marked as a prerelease** (goreleaser
|
||||
`release.prerelease: auto`), with binaries for all platforms.
|
||||
- **Homebrew** is not updated (goreleaser `brews.skip_upload: true`; the core
|
||||
formula only tracks stable releases).
|
||||
- **PyPI** and **npm** publish jobs are **skipped**. The `publish-pypi` and
|
||||
`publish-npm` jobs are gated with `!contains(github.ref_name, '-')`, so a tag
|
||||
containing a `-` never reaches the stable package channels.
|
||||
- **The stable docs snapshot is not required.** `verify-version-consistency`
|
||||
runs `scripts/check-versions.sh` without `BEADS_REQUIRE_RELEASE_DOCS=1` for
|
||||
prerelease tags, and `scripts/check-docs-version.sh` treats a prerelease
|
||||
canonical version as non-strict. The versioned docs stay on the latest stable
|
||||
release until the base `X.Y.Z` ships.
|
||||
|
||||
### Cut an RC
|
||||
|
||||
```bash
|
||||
# 1. Update CHANGELOG.md and cmd/bd/info.go with the RC notes (manual step),
|
||||
# same as a stable release. Date the CHANGELOG section.
|
||||
|
||||
# 2. Bump versions. update-versions.sh accepts a prerelease identifier and,
|
||||
# for prereleases, skips the Docusaurus docs snapshot automatically.
|
||||
./scripts/update-versions.sh 1.1.0-rc.1
|
||||
# Windows PE numeric fields (winres file_version/product_version and the
|
||||
# manifest <assemblyIdentity> version) are set to the base version 1.1.0,
|
||||
# because PE versions must be purely numeric; gen-winres.sh strips the
|
||||
# prerelease suffix the same way at build time.
|
||||
|
||||
# 3. Keep the MCP lockfile in sync (PEP 440 normalizes to 1.1.0rc1), or the
|
||||
# Package Gate (MCP) check goes red:
|
||||
(cd integrations/beads-mcp && uv lock)
|
||||
|
||||
# 4. Validate locally.
|
||||
./scripts/check-versions.sh
|
||||
|
||||
# 5. Open a PR for the RC prep and have it reviewed. RC prep should land
|
||||
# through normal review, not auto-merge.
|
||||
```
|
||||
|
||||
After the RC prep is merged to `main`, cut the tag from the merge commit:
|
||||
|
||||
```bash
|
||||
git checkout main && git pull
|
||||
git tag -a v1.1.0-rc.1 -m "Release candidate v1.1.0-rc.1"
|
||||
git push origin v1.1.0-rc.1
|
||||
```
|
||||
|
||||
Pushing the `v*` tag triggers the release workflow with the prerelease behavior
|
||||
above. Tag creation is restricted to release maintainers; see
|
||||
[Prerequisites](#prerequisites).
|
||||
|
||||
### Validate and promote
|
||||
|
||||
- Install the RC from the GitHub prerelease assets and exercise the changes it
|
||||
is gating before promoting.
|
||||
- To promote to stable, bump to the base version with no suffix
|
||||
(`./scripts/update-versions.sh 1.1.0`). The stable bump **does** require the
|
||||
docs snapshot and **does** publish to Homebrew/PyPI/npm, so follow the
|
||||
standard [Prepare Release](#1-prepare-release) steps from there.
|
||||
|
||||
## Hotfix Releases
|
||||
|
||||
For urgent bug fixes:
|
||||
|
|
@ -665,6 +785,11 @@ Examples:
|
|||
- `0.22.0` → `0.22.1`: Bug fix (patch bump)
|
||||
- `0.22.1` → `1.0.0`: Stable release (major bump)
|
||||
|
||||
**Prereleases:** append a SemVer prerelease identifier for release candidates,
|
||||
e.g. `1.1.0-rc.1`. Prerelease tags publish a GitHub prerelease only and stay
|
||||
off the stable Homebrew/PyPI/npm channels — see
|
||||
[Prerelease / Release Candidate (RC) Workflow](#prerelease--release-candidate-rc-workflow).
|
||||
|
||||
## Release Cadence
|
||||
|
||||
- **Minor releases**: Every 2-4 weeks (new features)
|
||||
|
|
|
|||
|
|
@ -143,16 +143,13 @@ func TestOpenFromConfig_DefaultsToEmbedded(t *testing.T) {
|
|||
|
||||
func TestOpenFromConfig_ServerModeFailsWithoutServer(t *testing.T) {
|
||||
// Server mode should fail-fast when no server is listening.
|
||||
// Temporarily unset BEADS_DOLT_PORT/BEADS_TEST_MODE so the config port
|
||||
// isn't overridden by applyConfigDefaults to the test server.
|
||||
if prev := os.Getenv("BEADS_DOLT_PORT"); prev != "" {
|
||||
os.Unsetenv("BEADS_DOLT_PORT")
|
||||
t.Cleanup(func() { os.Setenv("BEADS_DOLT_PORT", prev) })
|
||||
}
|
||||
if prev := os.Getenv("BEADS_TEST_MODE"); prev != "" {
|
||||
os.Unsetenv("BEADS_TEST_MODE")
|
||||
t.Cleanup(func() { os.Setenv("BEADS_TEST_MODE", prev) })
|
||||
}
|
||||
// Clear port env vars so the config port from metadata.json is used —
|
||||
// BEADS_DOLT_SERVER_PORT takes priority over BEADS_DOLT_PORT in
|
||||
// GetDoltServerPort, so both must be cleared. Keep BEADS_TEST_MODE=1
|
||||
// so auto-start is suppressed and the connection uses the free port
|
||||
// from metadata.json (which has nothing listening).
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
||||
t.Setenv("BEADS_DOLT_PORT", "")
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
|
|
@ -233,14 +230,11 @@ func TestOpenBestAvailable_ServerMode(t *testing.T) {
|
|||
|
||||
func TestOpenBestAvailable_ServerMode_FailsWithoutServer(t *testing.T) {
|
||||
// OpenBestAvailable in server mode should propagate the fail-fast error.
|
||||
if prev := os.Getenv("BEADS_DOLT_PORT"); prev != "" {
|
||||
os.Unsetenv("BEADS_DOLT_PORT")
|
||||
t.Cleanup(func() { os.Setenv("BEADS_DOLT_PORT", prev) })
|
||||
}
|
||||
if prev := os.Getenv("BEADS_TEST_MODE"); prev != "" {
|
||||
os.Unsetenv("BEADS_TEST_MODE")
|
||||
t.Cleanup(func() { os.Setenv("BEADS_TEST_MODE", prev) })
|
||||
}
|
||||
// Clear port env vars (both BEADS_DOLT_SERVER_PORT and BEADS_DOLT_PORT)
|
||||
// so the config port from metadata.json is used. Keep BEADS_TEST_MODE=1
|
||||
// so auto-start is suppressed.
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
||||
t.Setenv("BEADS_DOLT_PORT", "")
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ import (
|
|||
// requireServerMode returns an error if bd is running in embedded mode.
|
||||
// Used by admin subcommands to guard against embedded-mode execution.
|
||||
// This must be called inside RunE (after store init), not in PersistentPreRunE,
|
||||
// because isEmbeddedMode() reads cmdCtx.ServerMode which is only populated
|
||||
// because !usesSQLServer() reads cmdCtx.ServerMode which is only populated
|
||||
// after main.go's PersistentPreRun completes (cobra runs child PreRunE before
|
||||
// parent PreRun, so the check fires too early if placed on adminCmd itself).
|
||||
func requireServerMode(cmdName string) error {
|
||||
if isEmbeddedMode() {
|
||||
if !usesSQLServer() {
|
||||
return fmt.Errorf("'bd admin %s' is not yet supported in embedded mode", cmdName)
|
||||
}
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/ado"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/tracker"
|
||||
|
|
@ -355,6 +356,13 @@ type adoStatusResult struct {
|
|||
|
||||
// runADOStatus implements the ado status command.
|
||||
func runADOStatus(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("ado-status")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
cfg := getADOConfig()
|
||||
|
||||
if jsonOutput {
|
||||
|
|
@ -371,8 +379,7 @@ func runADOStatus(cmd *cobra.Command, _ []string) error {
|
|||
} else {
|
||||
result.Configured = true
|
||||
}
|
||||
outputJSON(result)
|
||||
return nil
|
||||
return outputJSON(result)
|
||||
}
|
||||
|
||||
out := cmd.OutOrStdout()
|
||||
|
|
@ -402,6 +409,13 @@ func runADOStatus(cmd *cobra.Command, _ []string) error {
|
|||
|
||||
// runADOProjects implements the ado projects command.
|
||||
func runADOProjects(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("ado-projects")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
cfg := getADOConfig()
|
||||
if cfg.PAT == "" {
|
||||
return fmt.Errorf("ado.pat not configured: set via 'bd config set ado.pat <token>' or AZURE_DEVOPS_PAT env var")
|
||||
|
|
@ -423,8 +437,7 @@ func runADOProjects(cmd *cobra.Command, _ []string) error {
|
|||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(projects)
|
||||
return nil
|
||||
return outputJSON(projects)
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintln(out, "Azure DevOps Projects")
|
||||
|
|
@ -465,6 +478,13 @@ type adoSyncResult struct {
|
|||
// runADOSync implements the ado sync command.
|
||||
// Uses the tracker.Engine for all sync operations.
|
||||
func runADOSync(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("ado-sync")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
cfg := getADOConfig()
|
||||
if err := validateADOConfig(cfg); err != nil {
|
||||
return err
|
||||
|
|
@ -667,8 +687,7 @@ func runADOSync(cmd *cobra.Command, _ []string) error {
|
|||
syncResult.ReconcileDeleted = len(reconcileResult.Deleted)
|
||||
syncResult.ReconcileDenied = len(reconcileResult.Denied)
|
||||
}
|
||||
outputJSON(syncResult)
|
||||
return nil
|
||||
return outputJSON(syncResult)
|
||||
}
|
||||
|
||||
// Human-readable output
|
||||
|
|
@ -748,6 +767,24 @@ func pushADOLinks(ctx context.Context, resolver *ado.LinkResolver, at *ado.Track
|
|||
var warnings []string
|
||||
linkCount := 0
|
||||
|
||||
// Build the set of ADO work item IDs beads tracks. PushLinks only removes a
|
||||
// current relation when its target is in this set, so links to items beads
|
||||
// does not track (e.g. human-created Related / Predecessor-Successor links)
|
||||
// are preserved rather than clobbered. See GH#4522.
|
||||
managedTargets := make(map[int]bool)
|
||||
for _, issue := range allIssues {
|
||||
if issue.ExternalRef == nil {
|
||||
continue
|
||||
}
|
||||
ref := *issue.ExternalRef
|
||||
if !at.IsExternalRef(ref) {
|
||||
continue
|
||||
}
|
||||
if id, cerr := strconv.Atoi(at.ExtractIdentifier(ref)); cerr == nil {
|
||||
managedTargets[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, issue := range allIssues {
|
||||
if issue.ExternalRef == nil {
|
||||
continue
|
||||
|
|
@ -803,7 +840,7 @@ func pushADOLinks(ctx context.Context, resolver *ado.LinkResolver, at *ado.Track
|
|||
continue
|
||||
}
|
||||
|
||||
errs := resolver.PushLinks(ctx, workItemID, items[0].Relations, desired)
|
||||
errs := resolver.PushLinks(ctx, workItemID, items[0].Relations, desired, managedTargets)
|
||||
for _, e := range errs {
|
||||
msg := fmt.Sprintf("Link sync ADO #%d: %v", workItemID, e)
|
||||
warnings = append(warnings, msg)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//go:build cgo
|
||||
//go:build cgo && integration
|
||||
|
||||
package main
|
||||
|
||||
|
|
@ -266,9 +266,6 @@ func adoTestStore(t *testing.T, prefix string) *dolt.DoltStore {
|
|||
// TestADORoundTripCoreFields tests push→pull fidelity for core fields:
|
||||
// title, description, priority, status, type, and external_ref.
|
||||
func TestADORoundTripCoreFields(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
project := "TestProject"
|
||||
|
|
@ -449,9 +446,6 @@ func TestADORoundTripCoreFields(t *testing.T) {
|
|||
// TestADORoundTripBlockedStatus tests that blocked status survives a round-trip
|
||||
// via the beads:blocked tag mechanism (ADO has no native blocked state).
|
||||
func TestADORoundTripBlockedStatus(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
project := "TestProject"
|
||||
|
|
@ -533,9 +527,6 @@ func TestADORoundTripBlockedStatus(t *testing.T) {
|
|||
// - P3 survives round-trip (ADO 4 → beads 3)
|
||||
// - P4 degrades to P3 (ADO 4 → beads 3) — this is a known lossy mapping
|
||||
func TestADORoundTripLossyPriority(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
project := "TestProject"
|
||||
|
|
@ -630,9 +621,6 @@ func TestADORoundTripLossyPriority(t *testing.T) {
|
|||
// TestADORoundTripLabels tests that user labels survive a round-trip and
|
||||
// internal beads:* tags are correctly filtered on pull.
|
||||
func TestADORoundTripLabels(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
project := "TestProject"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
|
|
@ -18,48 +20,61 @@ Shorthand for 'bd update <id> --assignee <name>'.
|
|||
Examples:
|
||||
bd assign bd-123 alice
|
||||
bd assign bd-123 "" # unassign`,
|
||||
Args: cobra.ExactArgs(2),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.ExactArgs(2),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("assign")
|
||||
|
||||
id := args[0]
|
||||
assignee := args[1]
|
||||
|
||||
evt := metrics.NewCommandEvent("assign")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
result, err := resolveAndGetIssueWithRouting(ctx, store, id)
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, id)
|
||||
if err != nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("resolving %s: %v", id, err)
|
||||
return HandleErrorRespectJSON("resolving %s: %v", id, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("issue %s not found", id)
|
||||
return HandleErrorRespectJSON("issue %s not found", id)
|
||||
}
|
||||
defer result.Close()
|
||||
|
||||
issueStore := result.Store
|
||||
|
||||
if err := validateIssueUpdatable(id, result.Issue); err != nil {
|
||||
FatalErrorRespectJSON("%s", err)
|
||||
return HandleErrorRespectJSON("%s", err)
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"assignee": assignee,
|
||||
}
|
||||
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil {
|
||||
FatalErrorRespectJSON("updating %s: %v", id, err)
|
||||
return HandleErrorRespectJSON("updating %s: %v", id, err)
|
||||
}
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
|
||||
Command: "assign",
|
||||
IssueIDs: []string{result.ResolvedID},
|
||||
}); err != nil {
|
||||
return HandleErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
|
||||
SetLastTouchedID(result.ResolvedID)
|
||||
|
||||
// Re-fetch for display
|
||||
updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID)
|
||||
title := ""
|
||||
if updatedIssue != nil {
|
||||
|
|
@ -67,7 +82,9 @@ Examples:
|
|||
}
|
||||
if jsonOutput {
|
||||
if updatedIssue != nil {
|
||||
outputJSON(updatedIssue)
|
||||
if err := outputJSON(updatedIssue); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if assignee == "" {
|
||||
|
|
@ -76,6 +93,7 @@ Examples:
|
|||
fmt.Printf("%s Assigned %s to %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, title), assignee)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/audit"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
@ -38,14 +39,21 @@ Entries are append-only. Labeling creates a new "label" entry that references a
|
|||
}
|
||||
|
||||
var auditRecordCmd = &cobra.Command{
|
||||
Use: "record",
|
||||
Short: "Append an audit interaction entry",
|
||||
Run: func(cmd *cobra.Command, _ []string) {
|
||||
Use: "record",
|
||||
Short: "Append an audit interaction entry",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("audit-record")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
var e audit.Entry
|
||||
|
||||
// If stdin is piped and no explicit record fields were provided, assume stdin JSON.
|
||||
// This matches "or pipe JSON via stdin" without requiring a flag.
|
||||
fi, _ := os.Stdin.Stat() // Best effort: nil FileInfo means not a pipe, use default behavior
|
||||
fi, _ := os.Stdin.Stat()
|
||||
stdinPiped := fi != nil && (fi.Mode()&os.ModeCharDevice) == 0
|
||||
noFieldsProvided := auditRecordKind == "" &&
|
||||
auditRecordModel == "" &&
|
||||
|
|
@ -59,21 +67,17 @@ var auditRecordCmd = &cobra.Command{
|
|||
if auditRecordStdin || (stdinPiped && noFieldsProvided) {
|
||||
b, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: failed to read stdin: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("failed to read stdin: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(b, &e); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid JSON on stdin: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid JSON on stdin: %v", err)
|
||||
}
|
||||
// Allow --actor to override/augment stdin.
|
||||
if actor != "" {
|
||||
e.Actor = actor
|
||||
}
|
||||
} else {
|
||||
if auditRecordKind == "" {
|
||||
fmt.Fprintf(os.Stderr, "Error: --kind is required\n")
|
||||
os.Exit(1)
|
||||
return HandleError("--kind is required")
|
||||
}
|
||||
e = audit.Entry{
|
||||
Kind: auditRecordKind,
|
||||
|
|
@ -93,31 +97,38 @@ var auditRecordCmd = &cobra.Command{
|
|||
|
||||
id, err := audit.Append(&e)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]any{
|
||||
return outputJSON(map[string]any{
|
||||
"id": id,
|
||||
"kind": e.Kind,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(id)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var auditLabelCmd = &cobra.Command{
|
||||
Use: "label <entry-id>",
|
||||
Short: "Append a label entry referencing an existing interaction",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(_ *cobra.Command, args []string) {
|
||||
Use: "label <entry-id>",
|
||||
Short: "Append a label entry referencing an existing interaction",
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("audit-label")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
parentID := args[0]
|
||||
if auditLabelValue == "" {
|
||||
fmt.Fprintf(os.Stderr, "Error: --label is required\n")
|
||||
os.Exit(1)
|
||||
return HandleError("--label is required")
|
||||
}
|
||||
e := audit.Entry{
|
||||
Kind: "label",
|
||||
|
|
@ -129,20 +140,19 @@ var auditLabelCmd = &cobra.Command{
|
|||
|
||||
id, err := audit.Append(&e)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]any{
|
||||
return outputJSON(map[string]any{
|
||||
"id": id,
|
||||
"parent_id": parentID,
|
||||
"label": auditLabelValue,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(id)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -160,7 +170,6 @@ func init() {
|
|||
auditLabelCmd.Flags().StringVar(&auditLabelValue, "label", "", `Label value (e.g. "good" or "bad")`)
|
||||
auditLabelCmd.Flags().StringVar(&auditLabelReason, "reason", "", "Reason for label")
|
||||
|
||||
// Issue ID completions
|
||||
auditCmd.ValidArgsFunction = issueIDCompletion
|
||||
|
||||
auditCmd.AddCommand(auditRecordCmd)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -21,33 +22,75 @@ type jsonlImporter interface {
|
|||
// that do not implement jsonlImporter (server-mode dolt). It exists as a
|
||||
// package-level variable so tests can substitute a counter and verify the
|
||||
// top-level emptiness guard prevents the fallback path from running on a
|
||||
// non-empty database. Production builds always use importFromLocalJSONLFull.
|
||||
var fallbackImporter = importFromLocalJSONLFull
|
||||
// non-empty database.
|
||||
//
|
||||
// Production builds use importFromLocalJSONLConflictSkip (GH#3955): this is
|
||||
// upgrade-recovery into an empty DB, so insert-if-new and UPSERT are
|
||||
// equivalent on the legitimate path — but if the emptiness guard above ever
|
||||
// regresses again (cf. PR #3630), conflict-skip makes the fallback a
|
||||
// harmless no-op instead of clobbering live rows. Explicit `bd import`,
|
||||
// `bd bootstrap`, and `bd init --from-jsonl` are unaffected and keep UPSERT.
|
||||
var fallbackImporter = importFromLocalJSONLConflictSkip
|
||||
|
||||
// maybeAutoImportJSONL checks whether the database is empty and a
|
||||
// issues.jsonl file exists in beadsDir. When both conditions are true it
|
||||
type autoImportStamp struct {
|
||||
Size int64 `json:"size"`
|
||||
ModTimeNano int64 `json:"mtime_ns"`
|
||||
}
|
||||
|
||||
func autoImportStampPath(beadsDir string) string {
|
||||
return filepath.Join(beadsDir, ".auto-import-issues.jsonl")
|
||||
}
|
||||
|
||||
func autoImportStampMatches(beadsDir string, info os.FileInfo) bool {
|
||||
data, err := os.ReadFile(autoImportStampPath(beadsDir))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var stamp autoImportStamp
|
||||
if err := json.Unmarshal(data, &stamp); err != nil {
|
||||
return false
|
||||
}
|
||||
return stamp.Size == info.Size() && stamp.ModTimeNano == info.ModTime().UnixNano()
|
||||
}
|
||||
|
||||
func writeAutoImportStamp(beadsDir string, info os.FileInfo) {
|
||||
stamp := autoImportStamp{Size: info.Size(), ModTimeNano: info.ModTime().UnixNano()}
|
||||
data, err := json.Marshal(stamp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(autoImportStampPath(beadsDir), data, 0o600)
|
||||
}
|
||||
|
||||
// maybeAutoImportJSONL checks whether the database is empty and the configured
|
||||
// import.path JSONL file exists in beadsDir. When both conditions are true it
|
||||
// auto-imports the JSONL data so users upgrading from pre-0.56 (which used
|
||||
// .beads/dolt/) to 1.0+ (which uses .beads/embeddeddolt/) don't appear to
|
||||
// lose their issues. See GH#2994.
|
||||
//
|
||||
// The top-level emptiness guard (GetStatistics) protects BOTH the
|
||||
// embedded fast-path and the server-mode fallback. The embedded
|
||||
// jsonlImporter has its own in-transaction emptiness check as a
|
||||
// concurrency-safe second line of defense; the fallback path's
|
||||
// importFromLocalJSONLFull uses INSERT … ON DUPLICATE KEY UPDATE
|
||||
// semantics under the hood, so without this guard a stale
|
||||
// issues.jsonl would be re-imposed on top of live Dolt rows on
|
||||
// every command, clobbering recent partial-update writes.
|
||||
// The top-level emptiness guard (GetStatistics) is the primary
|
||||
// protection for BOTH the embedded fast-path and the server-mode
|
||||
// fallback. Defense in depth backs each path up: the embedded
|
||||
// jsonlImporter has its own in-transaction emptiness check (and is
|
||||
// also insert-if-new, GH#3955), and the fallback path imports via
|
||||
// importFromLocalJSONLConflictSkip, which is insert-if-new rather than
|
||||
// UPSERT. So if this guard ever regresses again (cf. PR #3630), a stale
|
||||
// issues.jsonl can no longer be re-imposed on top of live Dolt rows —
|
||||
// the worst case degrades to a harmless no-op instead of clobbering
|
||||
// recent writes.
|
||||
//
|
||||
// The function is best-effort: failures are logged as warnings but do not
|
||||
// prevent the store from being used.
|
||||
func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir string) {
|
||||
// Quick check: does the JSONL file exist and have content?
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
jsonlPath := configuredImportJSONLPath(beadsDir)
|
||||
info, err := os.Stat(jsonlPath)
|
||||
if err != nil || info.Size() == 0 {
|
||||
return // no JSONL file or empty — nothing to import
|
||||
}
|
||||
if autoImportStampMatches(beadsDir, info) {
|
||||
return // already attempted for this exact JSONL version — retry only when issues.jsonl changes
|
||||
}
|
||||
|
||||
// Top-level emptiness guard (covers both embedded and fallback paths).
|
||||
// Without this, the fallback path silently re-imposes stale JSONL on
|
||||
|
|
@ -68,6 +111,7 @@ func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir s
|
|||
// Parse the JSONL file without touching the store.
|
||||
issues, configEntries, err := parseJSONLFile(jsonlPath)
|
||||
if err != nil {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
fmt.Fprintf(os.Stderr, "warning: auto-import: failed to parse %s: %v\n", jsonlPath, err)
|
||||
return
|
||||
}
|
||||
|
|
@ -80,6 +124,7 @@ func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir s
|
|||
if importer, ok := s.(jsonlImporter); ok {
|
||||
imported, err := importer.ImportJSONLData(ctx, issues, configEntries, "auto-import")
|
||||
if err != nil {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
fmt.Fprintf(os.Stderr, "warning: auto-import from %s failed: %v\n", jsonlPath, err)
|
||||
fmt.Fprintf(os.Stderr, "\nYour issues are still safe in %s.\n", jsonlPath)
|
||||
fmt.Fprintf(os.Stderr, "Try: bd init --from-jsonl (re-initialize and import from the JSONL file)\n")
|
||||
|
|
@ -87,6 +132,7 @@ func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir s
|
|||
return
|
||||
}
|
||||
if imported > 0 {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
// Signal PersistentPostRun to auto-commit (no explicit DOLT_COMMIT here).
|
||||
commandDidWrite.Store(true)
|
||||
fmt.Fprintf(os.Stderr, "auto-imported %d issues", imported)
|
||||
|
|
@ -98,11 +144,12 @@ func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir s
|
|||
return
|
||||
}
|
||||
|
||||
// Fallback for non-embedded stores: multi-call path (original behavior).
|
||||
// Fallback for stores without a single-transaction importer.
|
||||
fmt.Fprintf(os.Stderr, "auto-importing %d bytes from %s into empty database...\n", info.Size(), jsonlPath)
|
||||
|
||||
result, err := fallbackImporter(ctx, s, jsonlPath)
|
||||
if err != nil {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
fmt.Fprintf(os.Stderr, "warning: auto-import from %s failed: %v\n", jsonlPath, err)
|
||||
fmt.Fprintf(os.Stderr, "\nYour issues are still safe in %s.\n", jsonlPath)
|
||||
fmt.Fprintf(os.Stderr, "Try: bd init --from-jsonl (re-initialize and import from the JSONL file)\n")
|
||||
|
|
@ -116,9 +163,13 @@ func maybeAutoImportJSONL(ctx context.Context, s storage.DoltStorage, beadsDir s
|
|||
commitMsg = fmt.Sprintf("auto-import: %d issues, %d memories from %s (upgrade recovery, GH#2994)", result.Issues, result.Memories, filepath.Base(jsonlPath))
|
||||
}
|
||||
if err := s.Commit(ctx, commitMsg); err != nil {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
fmt.Fprintf(os.Stderr, "warning: auto-import: dolt commit failed: %v\n", err)
|
||||
return
|
||||
}
|
||||
if result.Issues > 0 || result.Memories > 0 {
|
||||
writeAutoImportStamp(beadsDir, info)
|
||||
}
|
||||
|
||||
if result.Memories > 0 {
|
||||
fmt.Fprintf(os.Stderr, "auto-imported %d issues and %d memories from %s\n", result.Issues, result.Memories, jsonlPath)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
|
@ -264,3 +265,123 @@ func bdListJSONAllowError(t *testing.T, bd, dir string, args ...string) []*types
|
|||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
// TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber asserts the
|
||||
// GH#3955 Layer 2 guarantee against a real embedded store: the auto-import
|
||||
// server-mode fallback importer (importFromLocalJSONLConflictSkip, the
|
||||
// production fallbackImporter) never overwrites an existing issue row.
|
||||
//
|
||||
// We invoke it directly against a NON-empty store — deliberately modelling
|
||||
// a regressed emptiness guard — and verify the live row is untouched while
|
||||
// a brand-new id from the JSONL is still inserted.
|
||||
func TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber(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", "cs")
|
||||
|
||||
live := bdCreate(t, bd, dir, "live issue title", "--type", "task")
|
||||
if live.ID == "" {
|
||||
t.Fatal("expected a created issue ID")
|
||||
}
|
||||
|
||||
const newID = "cs-new-9999"
|
||||
now := time.Now().UTC()
|
||||
jsonlIssues := []types.Issue{
|
||||
// Mutated copy of the live issue: UPSERT would clobber it.
|
||||
{ID: live.ID, Title: "CLOBBERED", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeBug, CreatedAt: now, UpdatedAt: now},
|
||||
// Brand-new issue: must still be inserted.
|
||||
{ID: newID, Title: "freshly imported", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: now, UpdatedAt: now},
|
||||
}
|
||||
var lines []string
|
||||
for _, issue := range jsonlIssues {
|
||||
b, err := json.Marshal(issue)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal fixture: %v", err)
|
||||
}
|
||||
lines = append(lines, string(b))
|
||||
}
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
if err := os.WriteFile(jsonlPath, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
store := openStore(t, beadsDir, "cs")
|
||||
ctx := context.Background()
|
||||
|
||||
// Exactly the code path fallbackImporter points at; running it on a
|
||||
// non-empty store models a guard regression (GH#3955 / PR #3630).
|
||||
if _, err := importFromLocalJSONLConflictSkip(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("importFromLocalJSONLConflictSkip: %v", err)
|
||||
}
|
||||
|
||||
got, err := store.GetIssue(ctx, live.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue(%s): %v", live.ID, err)
|
||||
}
|
||||
if got.Title != "live issue title" {
|
||||
t.Errorf("live issue title was clobbered: got %q, want %q", got.Title, "live issue title")
|
||||
}
|
||||
if got.Status != types.StatusOpen {
|
||||
t.Errorf("live issue status was clobbered: got %q, want %q", got.Status, types.StatusOpen)
|
||||
}
|
||||
|
||||
inserted, err := store.GetIssue(ctx, newID)
|
||||
if err != nil {
|
||||
t.Fatalf("brand-new issue %s was not inserted by conflict-skip import: %v", newID, err)
|
||||
}
|
||||
if inserted.Title != "freshly imported" {
|
||||
t.Errorf("new issue title: got %q, want %q", inserted.Title, "freshly imported")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll is the
|
||||
// negative control for GH#3955: conflict-skip must NOT regress the
|
||||
// legitimate upgrade-recovery path. Against an empty store the fallback
|
||||
// still imports every issue from the JSONL.
|
||||
func TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll(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)
|
||||
_, beadsDir, _ := bdInit(t, bd, "--prefix", "ce")
|
||||
|
||||
now := time.Now().UTC()
|
||||
jsonlIssues := []types.Issue{
|
||||
{ID: "ce-1", Title: "recovered one", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: now, UpdatedAt: now},
|
||||
{ID: "ce-2", Title: "recovered two", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug, CreatedAt: now, UpdatedAt: now},
|
||||
}
|
||||
var lines []string
|
||||
for _, issue := range jsonlIssues {
|
||||
b, err := json.Marshal(issue)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal fixture: %v", err)
|
||||
}
|
||||
lines = append(lines, string(b))
|
||||
}
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
if err := os.WriteFile(jsonlPath, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
store := openStore(t, beadsDir, "ce")
|
||||
ctx := context.Background()
|
||||
|
||||
res, err := importFromLocalJSONLConflictSkip(ctx, store, jsonlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("importFromLocalJSONLConflictSkip: %v", err)
|
||||
}
|
||||
if res.Issues != 2 {
|
||||
t.Errorf("expected 2 issues imported, got %d", res.Issues)
|
||||
}
|
||||
for _, id := range []string{"ce-1", "ce-2"} {
|
||||
if _, err := store.GetIssue(ctx, id); err != nil {
|
||||
t.Errorf("empty-DB recovery dropped issue %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,11 @@ import (
|
|||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
|
@ -15,28 +19,39 @@ import (
|
|||
// fakeFallbackStore satisfies storage.DoltStorage via an embedded nil
|
||||
// interface (any unimplemented method panics) and returns a configurable
|
||||
// Statistics. It does NOT implement jsonlImporter, so the type assertion
|
||||
// in maybeAutoImportJSONL fails and the server-mode fallback path is taken
|
||||
// in maybeAutoImportJSONL fails and the fallback importer path is taken
|
||||
// — exactly the path that lacked an emptiness guard prior to the fix.
|
||||
type fakeFallbackStore struct {
|
||||
storage.DoltStorage // nil — panics on any non-overridden method
|
||||
statsTotalIssues int
|
||||
statsNil bool
|
||||
getStatistics func(context.Context) (*types.Statistics, error)
|
||||
}
|
||||
|
||||
func (f *fakeFallbackStore) GetStatistics(_ context.Context) (*types.Statistics, error) {
|
||||
func (f *fakeFallbackStore) GetStatistics(ctx context.Context) (*types.Statistics, error) {
|
||||
if f.getStatistics != nil {
|
||||
return f.getStatistics(ctx)
|
||||
}
|
||||
if f.statsNil {
|
||||
return nil, nil
|
||||
}
|
||||
return &types.Statistics{TotalIssues: f.statsTotalIssues}, nil
|
||||
}
|
||||
|
||||
func (f *fakeFallbackStore) Commit(_ context.Context, _ string) error { return nil }
|
||||
|
||||
func writeAutoImportFixtureJSONL(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
writeAutoImportFixtureJSONLNamed(t, dir, "issues.jsonl")
|
||||
}
|
||||
|
||||
func writeAutoImportFixtureJSONLNamed(t *testing.T, dir, name string) {
|
||||
t.Helper()
|
||||
// Minimal valid issue line. Contents are irrelevant for the
|
||||
// skip-when-non-empty test (returns before parseJSONLFile) and are
|
||||
// only required to be parseable for the negative-control test.
|
||||
line := `{"_type":"issue","id":"unit-1","title":"unit-test-fixture","status":"open","priority":2,"issue_type":"task"}`
|
||||
if err := os.WriteFile(filepath.Join(dir, "issues.jsonl"), []byte(line+"\n"), 0o600); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(line+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -56,20 +71,20 @@ func swapFallbackImporter(t *testing.T, returnErr error) *atomic.Int32 {
|
|||
return &count
|
||||
}
|
||||
|
||||
// TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenNonEmpty is the
|
||||
// TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenNonEmpty is the
|
||||
// regression test for the auto-import-on-non-empty data-clobber bug
|
||||
// introduced upstream by PR #3630.
|
||||
//
|
||||
// Pre-fix, maybeAutoImportJSONL had no top-level emptiness guard for
|
||||
// stores that did not implement jsonlImporter (i.e. server-mode dolt).
|
||||
// Every command unconditionally invoked importFromLocalJSONLFull, which
|
||||
// UPSERTs JSONL contents on top of live Dolt rows — silently clobbering
|
||||
// recent partial-update writes whose values had not yet been re-exported
|
||||
// to JSONL.
|
||||
// stores that did not implement jsonlImporter. Every command
|
||||
// unconditionally invoked importFromLocalJSONLFull, which UPSERTs JSONL
|
||||
// contents on top of live Dolt rows — silently clobbering recent
|
||||
// partial-update writes whose values had not yet been re-exported to
|
||||
// JSONL.
|
||||
//
|
||||
// This test fails on the buggy code (counter == 1) and passes after the
|
||||
// guard is restored (counter == 0).
|
||||
func TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenNonEmpty(t *testing.T) {
|
||||
func TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenNonEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
count := swapFallbackImporter(t, errors.New("test importer should not run"))
|
||||
|
|
@ -78,14 +93,110 @@ func TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenNonEmpty(t *testing.T)
|
|||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 0 {
|
||||
t.Fatalf("regression: server-mode fallback importer was invoked %d time(s) on a non-empty store; expected 0 (top-level emptiness guard missing or broken)", got)
|
||||
t.Fatalf("regression: fallback importer was invoked %d time(s) on a non-empty store; expected 0 (top-level emptiness guard missing or broken)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenStatisticsNil covers
|
||||
// TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenStatisticsReportNonEmptyLate
|
||||
// asserts the top-level emptiness guard still fires when GetStatistics returns
|
||||
// late (e.g. blocked on a busy store) rather than instantly. It is a timing
|
||||
// variant of SkipsWhenNonEmpty: GetStatistics ultimately reports a populated
|
||||
// store, so the fallback UPSERT path must not run.
|
||||
//
|
||||
// Scope note — this does NOT cover the gastownhall/beads#3948 root cause. #3948
|
||||
// is the case where GetStatistics wrongly returns TotalIssues=0 on a populated
|
||||
// DB (a count/transaction-isolation defect), which defeats the guard entirely;
|
||||
// the dangerous fallback TOCTOU is empty-at-check -> concurrent writer commits
|
||||
// -> UPSERT clobbers the new rows. This test feeds a *correct* non-empty count,
|
||||
// so it exercises the happy path of the guard, not that hazard. The #3948 root
|
||||
// cause is tracked separately (mybd-w02o); maybeAutoImportJSONL makes a single
|
||||
// synchronous GetStatistics call, so there is no second observation point a
|
||||
// writer could race against at this layer.
|
||||
func TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenStatisticsReportNonEmptyLate(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
count := swapFallbackImporter(t, errors.New("test importer should not run"))
|
||||
|
||||
statsCalled := make(chan struct{})
|
||||
statsUnblocked := make(chan struct{})
|
||||
|
||||
store := &fakeFallbackStore{
|
||||
getStatistics: func(ctx context.Context) (*types.Statistics, error) {
|
||||
close(statsCalled)
|
||||
select {
|
||||
case <-statsUnblocked:
|
||||
return &types.Statistics{TotalIssues: 1}, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
maybeAutoImportJSONL(ctx, store, dir)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-statsCalled:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("auto-import did not check store statistics before considering fallback import")
|
||||
}
|
||||
|
||||
// Release the delayed GetStatistics so it reports a populated store.
|
||||
close(statsUnblocked)
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("auto-import did not return after statistics reported a non-empty store")
|
||||
}
|
||||
|
||||
if got := count.Load(); got != 0 {
|
||||
t.Fatalf("regression: fallback importer was invoked %d time(s) after statistics reported a non-empty store; expected 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldRunAutoImportJSONL(t *testing.T) {
|
||||
store := &fakeFallbackStore{}
|
||||
writeCmd := &cobra.Command{Use: "update"}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cmd *cobra.Command
|
||||
store storage.DoltStorage
|
||||
useReadOnly bool
|
||||
globalFlag bool
|
||||
serverMode bool
|
||||
want bool
|
||||
}{
|
||||
{name: "write command embedded", cmd: writeCmd, store: store, want: true},
|
||||
{name: "server mode", cmd: writeCmd, store: store, serverMode: true, want: false},
|
||||
{name: "read only", cmd: writeCmd, store: store, useReadOnly: true, want: false},
|
||||
{name: "global", cmd: writeCmd, store: store, globalFlag: true, want: false},
|
||||
{name: "import command", cmd: &cobra.Command{Use: "import"}, store: store, want: false},
|
||||
{name: "nil store", cmd: writeCmd, want: false},
|
||||
{name: "nil command", store: store, want: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := shouldRunAutoImportJSONL(tt.cmd, tt.store, tt.useReadOnly, tt.globalFlag, tt.serverMode)
|
||||
if got != tt.want {
|
||||
t.Fatalf("shouldRunAutoImportJSONL() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenStatisticsNil covers
|
||||
// the defensive nil-statistics guard: if the store reports no error but also
|
||||
// no counts, auto-import should skip rather than panic or assume emptiness.
|
||||
func TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenStatisticsNil(t *testing.T) {
|
||||
func TestMaybeAutoImportJSONL_FallbackImporter_SkipsWhenStatisticsNil(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
count := swapFallbackImporter(t, errors.New("test importer should not run"))
|
||||
|
|
@ -94,18 +205,18 @@ func TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenStatisticsNil(t *testi
|
|||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 0 {
|
||||
t.Fatalf("server-mode fallback importer was invoked %d time(s) when statistics were nil; expected 0", got)
|
||||
t.Fatalf("fallback importer was invoked %d time(s) when statistics were nil; expected 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaybeAutoImportJSONL_ServerModeFallback_RunsWhenEmpty is the negative
|
||||
// TestMaybeAutoImportJSONL_FallbackImporter_RunsWhenEmpty is the negative
|
||||
// control. Without it, a future change that always short-circuits would
|
||||
// leave the regression test above passing vacuously.
|
||||
//
|
||||
// The substituted importer returns an error to short-circuit before
|
||||
// s.Commit is called, so the bare fakeFallbackStore (which panics on
|
||||
// every other method) does not need the full DoltStorage surface.
|
||||
func TestMaybeAutoImportJSONL_ServerModeFallback_RunsWhenEmpty(t *testing.T) {
|
||||
func TestMaybeAutoImportJSONL_FallbackImporter_RunsWhenEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
count := swapFallbackImporter(t, errors.New("test importer: short-circuit before s.Commit"))
|
||||
|
|
@ -114,6 +225,179 @@ func TestMaybeAutoImportJSONL_ServerModeFallback_RunsWhenEmpty(t *testing.T) {
|
|||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 1 {
|
||||
t.Fatalf("server-mode fallback importer invoked %d time(s) on empty store; expected exactly 1", got)
|
||||
t.Fatalf("fallback importer invoked %d time(s) on empty store; expected exactly 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeAutoImportJSONL_UsesConfiguredImportPath(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
config.Set("import.path", "beads.jsonl")
|
||||
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONLNamed(t, dir, "beads.jsonl")
|
||||
|
||||
orig := fallbackImporter
|
||||
var gotPath string
|
||||
fallbackImporter = func(_ context.Context, _ storage.DoltStorage, path string) (*importLocalResult, error) {
|
||||
gotPath = path
|
||||
return nil, errors.New("test importer: short-circuit before s.Commit")
|
||||
}
|
||||
t.Cleanup(func() { fallbackImporter = orig })
|
||||
|
||||
store := &fakeFallbackStore{statsTotalIssues: 0}
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
wantPath := filepath.Join(dir, "beads.jsonl")
|
||||
if gotPath != wantPath {
|
||||
t.Fatalf("auto-import path = %q, want %q", gotPath, wantPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeAutoImportJSONL_FailedImportStampPreventsRepeatedImport(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
count := swapFallbackImporter(t, errors.New("test importer failed"))
|
||||
|
||||
store := &fakeFallbackStore{statsTotalIssues: 0}
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 1 {
|
||||
t.Fatalf("fallback importer invoked %d time(s), want 1 for unchanged JSONL after failed attempt stamp", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeAutoImportJSONL_SuccessStampPreventsRepeatedImport(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
orig := fallbackImporter
|
||||
var count atomic.Int32
|
||||
fallbackImporter = func(_ context.Context, _ storage.DoltStorage, _ string) (*importLocalResult, error) {
|
||||
count.Add(1)
|
||||
return &importLocalResult{Issues: 1}, nil
|
||||
}
|
||||
t.Cleanup(func() { fallbackImporter = orig })
|
||||
|
||||
store := &fakeFallbackStore{statsTotalIssues: 0}
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 1 {
|
||||
t.Fatalf("fallback importer invoked %d time(s), want 1 for unchanged JSONL after success stamp", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeAutoImportJSONL_ChangedJSONLBypassesSuccessStamp(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
orig := fallbackImporter
|
||||
var count atomic.Int32
|
||||
fallbackImporter = func(_ context.Context, _ storage.DoltStorage, _ string) (*importLocalResult, error) {
|
||||
count.Add(1)
|
||||
return &importLocalResult{Issues: 1}, nil
|
||||
}
|
||||
t.Cleanup(func() { fallbackImporter = orig })
|
||||
|
||||
store := &fakeFallbackStore{statsTotalIssues: 0}
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
if err := os.WriteFile(filepath.Join(dir, "issues.jsonl"), []byte(`{"_type":"issue","id":"unit-2","title":"changed","status":"open","priority":2,"issue_type":"task"}`+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
maybeAutoImportJSONL(context.Background(), store, dir)
|
||||
|
||||
if got := count.Load(); got != 2 {
|
||||
t.Fatalf("fallback importer invoked %d time(s), want 2 after JSONL changed", got)
|
||||
}
|
||||
}
|
||||
|
||||
// captureOptsStore is a storage.DoltStorage that records the
|
||||
// BatchCreateOptions handed to CreateIssuesWithFullOptions. Every other
|
||||
// method panics (embedded nil interface); the import plumbing under test
|
||||
// only touches CreateIssuesWithFullOptions, GetConfig and SetConfig.
|
||||
type captureOptsStore struct {
|
||||
storage.DoltStorage // nil — panics on any non-overridden method
|
||||
prefix string
|
||||
gotOpts storage.BatchCreateOptions
|
||||
}
|
||||
|
||||
func (c *captureOptsStore) CreateIssuesWithFullOptions(_ context.Context, _ []*types.Issue, _ string, opts storage.BatchCreateOptions) error {
|
||||
c.gotOpts = opts
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *captureOptsStore) GetConfig(_ context.Context, _ string) (string, error) {
|
||||
return c.prefix, nil
|
||||
}
|
||||
|
||||
func (c *captureOptsStore) SetConfig(_ context.Context, _, _ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetIssuesByIDs reports no existing rows so importIssuesCore's stale-import
|
||||
// filter (filterStaleImportIssues) is a no-op and the import proceeds to
|
||||
// CreateIssuesWithFullOptions, where the options under test are recorded.
|
||||
func (c *captureOptsStore) GetIssuesByIDs(_ context.Context, _ []string) ([]*types.Issue, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// TestImportIssuesCoreThreadsConflictSkip verifies the GH#3955 plumbing:
|
||||
// ImportOptions.ConflictSkip maps onto storage.BatchCreateOptions.ConflictSkip,
|
||||
// and the default (explicit `bd import`) path keeps UPSERT semantics.
|
||||
func TestImportIssuesCoreThreadsConflictSkip(t *testing.T) {
|
||||
issues := []*types.Issue{{ID: "unit-1", Title: "t", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}}
|
||||
|
||||
t.Run("ConflictSkip true threads through", func(t *testing.T) {
|
||||
s := &captureOptsStore{}
|
||||
if _, err := importIssuesCore(context.Background(), "", s, issues, ImportOptions{SkipPrefixValidation: true, ConflictSkip: true}); err != nil {
|
||||
t.Fatalf("importIssuesCore: %v", err)
|
||||
}
|
||||
if !s.gotOpts.ConflictSkip {
|
||||
t.Fatalf("ConflictSkip not threaded into BatchCreateOptions: got %+v", s.gotOpts)
|
||||
}
|
||||
if !s.gotOpts.SkipPrefixValidation {
|
||||
t.Errorf("SkipPrefixValidation should still thread through: got %+v", s.gotOpts)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("default keeps UPSERT", func(t *testing.T) {
|
||||
s := &captureOptsStore{}
|
||||
if _, err := importIssuesCore(context.Background(), "", s, issues, ImportOptions{SkipPrefixValidation: true}); err != nil {
|
||||
t.Fatalf("importIssuesCore: %v", err)
|
||||
}
|
||||
if s.gotOpts.ConflictSkip {
|
||||
t.Fatalf("explicit-import path must keep UPSERT (ConflictSkip=false); got true")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAutoImportFallbackSeamUsesConflictSkip verifies which importer each
|
||||
// caller is wired to: the auto-import server-mode fallback
|
||||
// (importFromLocalJSONLConflictSkip, the fallbackImporter seam) requests
|
||||
// conflict-skip, while importFromLocalJSONLFull — used by `bd bootstrap`
|
||||
// and `bd init --from-jsonl` — keeps UPSERT. This is the scope boundary
|
||||
// for GH#3955.
|
||||
func TestAutoImportFallbackSeamUsesConflictSkip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeAutoImportFixtureJSONL(t, dir)
|
||||
jsonlPath := filepath.Join(dir, "issues.jsonl")
|
||||
|
||||
t.Run("auto-import fallback uses conflict-skip", func(t *testing.T) {
|
||||
s := &captureOptsStore{prefix: "unit"}
|
||||
if _, err := importFromLocalJSONLConflictSkip(context.Background(), s, jsonlPath); err != nil {
|
||||
t.Fatalf("importFromLocalJSONLConflictSkip: %v", err)
|
||||
}
|
||||
if !s.gotOpts.ConflictSkip {
|
||||
t.Fatalf("auto-import fallback must set ConflictSkip=true; got %+v", s.gotOpts)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit recovery path keeps UPSERT", func(t *testing.T) {
|
||||
s := &captureOptsStore{prefix: "unit"}
|
||||
if _, err := importFromLocalJSONLFull(context.Background(), s, jsonlPath); err != nil {
|
||||
t.Fatalf("importFromLocalJSONLFull: %v", err)
|
||||
}
|
||||
if s.gotOpts.ConflictSkip {
|
||||
t.Fatalf("bd bootstrap / init --from-jsonl must keep UPSERT (ConflictSkip=false); got true")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
358
cmd/bd/autocommit_embedded_test.go
Normal file
358
cmd/bd/autocommit_embedded_test.go
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func bdCommand(t *testing.T, bd, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
out, err := bdRunWithFlockRetry(t, bd, dir, args...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func assertEmbeddedHeadUnchanged(t *testing.T, beadsDir, database, before, command string) {
|
||||
t.Helper()
|
||||
after := embeddedCurrentCommit(t, beadsDir, database)
|
||||
if after != before {
|
||||
t.Fatalf("%s advanced HEAD in batch mode; before=%s after=%s", command, before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEmbeddedHeadAdvanced(t *testing.T, beadsDir, database, before, command string) {
|
||||
t.Helper()
|
||||
after := embeddedCurrentCommit(t, beadsDir, database)
|
||||
if after == before {
|
||||
t.Fatalf("%s did not advance target HEAD; before=%s after=%s", command, before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func setupRoutedEmbeddedRepo(t *testing.T, bd string, sourcePrefix, targetPrefix string) (sourceDir, targetDir, targetBeadsDir string) {
|
||||
t.Helper()
|
||||
|
||||
sourceDir, _, _ = bdInit(t, bd, "--prefix", sourcePrefix)
|
||||
targetDir = filepath.Join(sourceDir, "target-repo")
|
||||
if err := os.MkdirAll(targetDir, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initGitRepoAt(t, targetDir)
|
||||
runBDInit(t, bd, targetDir, "--prefix", targetPrefix)
|
||||
|
||||
route := `{"prefix":"` + targetPrefix + `-","path":"target-repo"}` + "\n"
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, ".beads", "routes.jsonl"), []byte(route), 0644); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
return sourceDir, targetDir, filepath.Join(targetDir, ".beads")
|
||||
}
|
||||
|
||||
func TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt auto-commit tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("dep_add", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "da")
|
||||
from := bdCreate(t, bd, dir, "Dependent issue")
|
||||
to := bdCreate(t, bd, dir, "Blocking issue")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "da")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "dep", "add", from.ID, to.ID)
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "da", before, "dep add")
|
||||
})
|
||||
|
||||
t.Run("dep_blocks", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "db")
|
||||
blocker := bdCreate(t, bd, dir, "Blocking issue")
|
||||
blocked := bdCreate(t, bd, dir, "Blocked issue")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "db")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "dep", blocker.ID, "--blocks", blocked.ID)
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "db", before, "dep --blocks")
|
||||
})
|
||||
|
||||
t.Run("dep_remove", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dr")
|
||||
from := bdCreate(t, bd, dir, "Dependent issue")
|
||||
to := bdCreate(t, bd, dir, "Blocking issue")
|
||||
bdDep(t, bd, dir, "add", from.ID, to.ID)
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dr")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "dep", "remove", from.ID, to.ID)
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dr", before, "dep remove")
|
||||
})
|
||||
|
||||
t.Run("link", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dl")
|
||||
from := bdCreate(t, bd, dir, "Dependent issue")
|
||||
to := bdCreate(t, bd, dir, "Blocking issue")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dl")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "link", from.ID, to.ID)
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dl", before, "link")
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmbeddedDirectCommitPathsBatchAutoCommitDoesNotAdvanceHead(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt auto-commit tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("create", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dc")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dc")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "create", "Deferred create")
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dc", before, "create")
|
||||
})
|
||||
|
||||
t.Run("markdown_create", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dm")
|
||||
mdFile := filepath.Join(dir, "issues.md")
|
||||
mdContent := `## Markdown batch issue
|
||||
|
||||
### Priority
|
||||
2
|
||||
|
||||
### Type
|
||||
task
|
||||
|
||||
### Description
|
||||
Created while Dolt auto-commit is in batch mode.
|
||||
`
|
||||
if err := os.WriteFile(mdFile, []byte(mdContent), 0644); err != nil {
|
||||
t.Fatalf("write markdown fixture: %v", err)
|
||||
}
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dm")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "create", "-f", mdFile)
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dm", before, "markdown create")
|
||||
})
|
||||
|
||||
t.Run("label_add", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dlb")
|
||||
issue := bdCreate(t, bd, dir, "Batch label target")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dlb")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "label", "add", issue.ID, "batched")
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dlb", before, "label add")
|
||||
labels := showLabels(t, bd, dir, issue.ID)
|
||||
if !slices.Contains(labels, "batched") {
|
||||
t.Fatalf("labels = %v, want batched", labels)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dd")
|
||||
issue := bdCreate(t, bd, dir, "Batch delete target")
|
||||
before := embeddedCurrentCommit(t, beadsDir, "dd")
|
||||
|
||||
bdCommand(t, bd, dir, "--dolt-auto-commit", "batch", "delete", issue.ID, "--force")
|
||||
|
||||
assertEmbeddedHeadUnchanged(t, beadsDir, "dd", before, "delete")
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmbeddedRoutedSiblingWritesCommitTargetHead(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt auto-commit tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("comment", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sc", "tc")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed comment target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tc")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "comment", issue.ID, "routed comment")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tc", before, "routed comment")
|
||||
targetStore := openStore(t, targetBeadsDir, "tc")
|
||||
comments, err := targetStore.GetIssueComments(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssueComments: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, c := range comments {
|
||||
if c.Text == "routed comment" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("routed comment was not persisted in target store")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("note", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sn", "tn")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed note target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tn")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "note", issue.ID, "routed note")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tn", before, "routed note")
|
||||
targetStore := openStore(t, targetBeadsDir, "tn")
|
||||
got, err := targetStore.GetIssue(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue: %v", err)
|
||||
}
|
||||
if !strings.Contains(got.Notes, "routed note") {
|
||||
t.Fatalf("target notes = %q, want routed note", got.Notes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("reopen", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sr", "tr")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed reopen target")
|
||||
bdClose(t, bd, targetDir, issue.ID)
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tr")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "reopen", issue.ID, "--reason", "routed reopen")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tr", before, "routed reopen")
|
||||
targetStore := openStore(t, targetBeadsDir, "tr")
|
||||
got, err := targetStore.GetIssue(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue: %v", err)
|
||||
}
|
||||
if got.Status != types.StatusOpen {
|
||||
t.Fatalf("target status = %s, want %s", got.Status, types.StatusOpen)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestEmbeddedRoutedMutatingSiblingWritesCommitTargetHead pins the rest of the
|
||||
// prefix-routed mutating command surface to the same write-through contract as
|
||||
// comment/note/reopen above. These commands (the assign/tag shorthands plus
|
||||
// dep/delete/close) resolve a prefix-routed target through the write-intent
|
||||
// router and must commit on the target head, not fail "store is read-only"
|
||||
// (#4141). Each subtest creates the bead in the target rig, runs the command
|
||||
// from the source rig so resolution must route, and asserts both that the
|
||||
// target HEAD advanced and that the mutation persisted in the target store.
|
||||
func TestEmbeddedRoutedMutatingSiblingWritesCommitTargetHead(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt auto-commit tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("assign", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sas", "tas")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed assign target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tas")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "assign", issue.ID, "alice")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tas", before, "routed assign")
|
||||
targetStore := openStore(t, targetBeadsDir, "tas")
|
||||
got, err := targetStore.GetIssue(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue: %v", err)
|
||||
}
|
||||
if got.Assignee != "alice" {
|
||||
t.Fatalf("target assignee = %q, want alice", got.Assignee)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("tag", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "stg", "ttg")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed tag target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "ttg")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "tag", issue.ID, "routed-label")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "ttg", before, "routed tag")
|
||||
targetStore := openStore(t, targetBeadsDir, "ttg")
|
||||
labels, err := targetStore.GetLabelsForIssues(t.Context(), []string{issue.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("GetLabelsForIssues: %v", err)
|
||||
}
|
||||
if !slices.Contains(labels[issue.ID], "routed-label") {
|
||||
t.Fatalf("target labels = %v, want routed-label", labels[issue.ID])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dep_add", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sdp", "tdp")
|
||||
from := bdCreate(t, bd, targetDir, "Routed dep source")
|
||||
to := bdCreate(t, bd, targetDir, "Routed dep target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tdp")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "dep", "add", from.ID, to.ID)
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tdp", before, "routed dep add")
|
||||
targetStore := openStore(t, targetBeadsDir, "tdp")
|
||||
deps, err := targetStore.GetDependencies(t.Context(), from.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetDependencies: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, d := range deps {
|
||||
if d.ID == to.ID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("routed dep add did not persist %s -> %s in target store (deps=%v)", from.ID, to.ID, deps)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "sdl", "tdl")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed delete target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tdl")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "delete", issue.ID, "--force")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tdl", before, "routed delete")
|
||||
targetStore := openStore(t, targetBeadsDir, "tdl")
|
||||
if _, err := targetStore.GetIssue(t.Context(), issue.ID); err == nil {
|
||||
t.Fatalf("routed delete did not remove %s from target store", issue.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close", func(t *testing.T) {
|
||||
sourceDir, targetDir, targetBeadsDir := setupRoutedEmbeddedRepo(t, bd, "scl", "tcl")
|
||||
issue := bdCreate(t, bd, targetDir, "Routed close target")
|
||||
before := embeddedCurrentCommit(t, targetBeadsDir, "tcl")
|
||||
|
||||
bdCommand(t, bd, sourceDir, "close", issue.ID, "--reason", "routed close")
|
||||
|
||||
assertEmbeddedHeadAdvanced(t, targetBeadsDir, "tcl", before, "routed close")
|
||||
targetStore := openStore(t, targetBeadsDir, "tcl")
|
||||
got, err := targetStore.GetIssue(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue: %v", err)
|
||||
}
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Fatalf("target status = %s, want %s", got.Status, types.StatusClosed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import (
|
|||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
)
|
||||
|
||||
var backupCmd = &cobra.Command{
|
||||
|
|
@ -14,6 +15,11 @@ var backupCmd = &cobra.Command{
|
|||
Short: "Back up your beads database",
|
||||
Long: `Back up your beads database for off-machine recovery.
|
||||
|
||||
This is a Dolt-native database backup. It preserves the database state,
|
||||
including tables, branches, commit history, and working-set data. This is
|
||||
different from 'bd export', which writes issue records to JSONL for migration
|
||||
and interoperability.
|
||||
|
||||
Commands:
|
||||
bd backup init <path> Set up a backup destination (filesystem or DoltHub)
|
||||
bd backup sync Push to configured backup destination
|
||||
|
|
@ -31,6 +37,13 @@ var backupStatusCmd = &cobra.Command{
|
|||
Use: "status",
|
||||
Short: "Show last backup status",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("backup-status")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
dir, err := backupDir()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
|
|
@ -21,6 +22,43 @@ func isBackupAutoEnabled() bool {
|
|||
return primeHasGitRemote()
|
||||
}
|
||||
|
||||
// clientServerShareFilesystem reports whether the configured Dolt
|
||||
// server runs on a filesystem the bd client can also see — i.e.
|
||||
// whether a file:// URL constructed on the client is meaningful to
|
||||
// the server.
|
||||
//
|
||||
// Returns true when the host is empty / localhost (embedded mode or
|
||||
// local server), false when the host is set to a non-localhost
|
||||
// value (external server in a container or remote machine).
|
||||
//
|
||||
// Used by maybeAutoBackup to skip the file:// auto-register that
|
||||
// would otherwise fail every command (GH#3523). External-server
|
||||
// operators who want auto-backup must configure an URL scheme that
|
||||
// works cross-filesystem (s3://, gs://, etc.) — auto-backup's
|
||||
// hardcoded file:// path can't help them.
|
||||
//
|
||||
// Detection bypasses Config.IsDoltServerMode() so it works correctly
|
||||
// regardless of whether GH#3545's host-mode-inference fix is in
|
||||
// place — the operator's intent is unambiguous from the host value
|
||||
// alone.
|
||||
func clientServerShareFilesystem() bool {
|
||||
host := os.Getenv("BEADS_DOLT_SERVER_HOST")
|
||||
if host == "" {
|
||||
// Fall back to in-struct config (config.yaml dolt.host etc.).
|
||||
host = config.GetString("dolt.host")
|
||||
}
|
||||
switch host {
|
||||
case "", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// autoBackupSkipNoticeOnce ensures the "auto-backup skipped" INFO
|
||||
// message fires at most once per process — operators running long
|
||||
// bd sessions don't need a chatty repeat on every command.
|
||||
var autoBackupSkipNoticeOnce sync.Once
|
||||
|
||||
// maybeAutoBackup runs a Dolt-native backup if enabled and the throttle interval has passed.
|
||||
// Called from PersistentPostRun after auto-commit.
|
||||
func maybeAutoBackup(ctx context.Context) {
|
||||
|
|
@ -42,6 +80,26 @@ func maybeAutoBackup(ctx context.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// GH#3523: when the Dolt server runs on a different filesystem
|
||||
// from this client (operator's BEADS_DOLT_SERVER_HOST points at a
|
||||
// non-localhost value), the file:// URL the auto-backup path
|
||||
// constructs is meaningless to the server — register fails on
|
||||
// every command. Skip cleanly with a one-time INFO so operators
|
||||
// know auto-backup is silent on purpose.
|
||||
if !clientServerShareFilesystem() {
|
||||
autoBackupSkipNoticeOnce.Do(func() {
|
||||
if !isQuiet() && !jsonOutput {
|
||||
fmt.Fprintln(os.Stderr,
|
||||
"Info: auto-backup skipped — server filesystem differs "+
|
||||
"from client (BEADS_DOLT_SERVER_HOST is non-localhost).\n"+
|
||||
" Configure backup.url=s3://... or run `bd backup` "+
|
||||
"manually for cross-filesystem backups.")
|
||||
}
|
||||
})
|
||||
debug.Logf("backup: skipping — server on remote filesystem\n")
|
||||
return
|
||||
}
|
||||
|
||||
dir, err := backupDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: auto-backup skipped: %v\n", err)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ package main
|
|||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
|
|
@ -84,3 +85,98 @@ func TestIsBackupAutoEnabled(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientServerShareFilesystem_GH3523 pins the gating logic that
|
||||
// suppresses auto-backup's file:// register when the Dolt server
|
||||
// runs on a different filesystem from the client. Pre-fix every
|
||||
// command emitted "auto-backup failed: register backup remote: ...
|
||||
// failed to create directory ..." for operators with an external
|
||||
// (non-localhost) Dolt server.
|
||||
func TestClientServerShareFilesystem_GH3523(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envHost string // "\x00" = unset
|
||||
yamlHost string // "\x00" = unset
|
||||
wantShare bool
|
||||
}{
|
||||
{
|
||||
name: "no env, no yaml → embedded/local, share=true",
|
||||
envHost: "\x00",
|
||||
yamlHost: "\x00",
|
||||
wantShare: true,
|
||||
},
|
||||
{
|
||||
name: "env=localhost → local, share=true",
|
||||
envHost: "localhost",
|
||||
yamlHost: "\x00",
|
||||
wantShare: true,
|
||||
},
|
||||
{
|
||||
name: "env=127.0.0.1 → local, share=true",
|
||||
envHost: "127.0.0.1",
|
||||
yamlHost: "\x00",
|
||||
wantShare: true,
|
||||
},
|
||||
{
|
||||
name: "env=non-localhost IP → external, share=false",
|
||||
envHost: "192.0.2.10",
|
||||
yamlHost: "\x00",
|
||||
wantShare: false,
|
||||
},
|
||||
{
|
||||
name: "env=non-localhost FQDN → external, share=false",
|
||||
envHost: "dolt-primary.tailnet.example.com",
|
||||
yamlHost: "\x00",
|
||||
wantShare: false,
|
||||
},
|
||||
{
|
||||
name: "yaml dolt.host=non-localhost → external, share=false",
|
||||
envHost: "\x00",
|
||||
yamlHost: "10.0.0.5",
|
||||
wantShare: false,
|
||||
},
|
||||
{
|
||||
name: "env=empty (set to empty), yaml=non-localhost → external, share=false",
|
||||
envHost: "",
|
||||
yamlHost: "10.0.0.5",
|
||||
wantShare: false,
|
||||
},
|
||||
{
|
||||
name: "env=localhost overrides yaml=non-localhost → share=true",
|
||||
envHost: "localhost",
|
||||
yamlHost: "10.0.0.5",
|
||||
wantShare: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.envHost == "\x00" {
|
||||
os.Unsetenv("BEADS_DOLT_SERVER_HOST")
|
||||
} else {
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", tt.envHost)
|
||||
}
|
||||
|
||||
// Construct a fresh config.yaml for the dolt.host case.
|
||||
configDir := t.TempDir()
|
||||
if tt.yamlHost != "\x00" {
|
||||
yamlPath := filepath.Join(configDir, "config.yaml")
|
||||
content := "dolt:\n host: " + tt.yamlHost + "\n"
|
||||
if err := os.WriteFile(yamlPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Setenv("BEADS_DIR", configDir)
|
||||
config.ResetForTesting()
|
||||
t.Cleanup(config.ResetForTesting)
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize: %v", err)
|
||||
}
|
||||
|
||||
got := clientServerShareFilesystem()
|
||||
if got != tt.wantShare {
|
||||
t.Errorf("clientServerShareFilesystem() = %v, want %v", got, tt.wantShare)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/versioncontrolops"
|
||||
)
|
||||
|
|
@ -20,7 +21,7 @@ import (
|
|||
// These wrap Dolt's built-in backup feature (CALL DOLT_BACKUP(...)) for standalone
|
||||
// users who want their beads database backed up to a filesystem path, NAS, or DoltHub.
|
||||
//
|
||||
// Unlike the JSONL backup (bd backup), Dolt backups preserve full commit history
|
||||
// Unlike issue JSONL exports, Dolt-native backups preserve full commit history
|
||||
// and are faster for large databases.
|
||||
|
||||
const defaultDoltBackupName = "default"
|
||||
|
|
@ -45,6 +46,13 @@ DoltHub (recommended for cloud backup):
|
|||
After adding, run 'bd backup sync' to push your data.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("backup-init")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
rawPath := args[0]
|
||||
|
||||
|
|
@ -88,12 +96,11 @@ After adding, run 'bd backup sync' to push your data.`,
|
|||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"backup_url": backupURL,
|
||||
"backup_name": defaultDoltBackupName,
|
||||
"initialized": true,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("Backup destination configured: %s\n", backupURL)
|
||||
|
|
@ -114,6 +121,13 @@ The backup is atomic — if the sync fails, the previous backup state is preserv
|
|||
|
||||
Run 'bd backup init <path>' first to configure a destination.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("backup-sync")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
if store == nil {
|
||||
return fmt.Errorf("no store available")
|
||||
|
|
@ -149,11 +163,10 @@ Run 'bd backup init <path>' first to configure a destination.`,
|
|||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"synced": true,
|
||||
"duration": elapsed.String(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("Backup synced in %s\n", elapsed.Round(time.Millisecond))
|
||||
|
|
@ -390,6 +403,13 @@ This unregisters the backup remote from Dolt and removes the local
|
|||
backup configuration. The backup data at the destination is not deleted.`,
|
||||
Aliases: []string{"rm"},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("backup-remove")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
if store == nil {
|
||||
return fmt.Errorf("no store available")
|
||||
|
|
@ -419,8 +439,7 @@ backup configuration. The backup data at the destination is not deleted.`,
|
|||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{"removed": true})
|
||||
return nil
|
||||
return outputJSON(map[string]interface{}{"removed": true})
|
||||
}
|
||||
|
||||
fmt.Println("Backup destination removed.")
|
||||
|
|
|
|||
|
|
@ -19,11 +19,11 @@ func bdBackup(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd backup %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd backup %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
// bdBackupFail runs "bd backup" expecting failure. Returns combined output.
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
|
@ -21,12 +22,23 @@ var backupRestoreCmd = &cobra.Command{
|
|||
By default, reads from .beads/backup/ (or the configured backup directory).
|
||||
Optionally specify a path to a directory containing a Dolt backup.
|
||||
|
||||
This restores a full database backup created by 'bd backup sync' or an
|
||||
equivalent Dolt backup. JSONL files produced by 'bd export' are issue exports,
|
||||
not restore targets for this command.
|
||||
|
||||
Use --force to overwrite an existing database with the backup contents.
|
||||
|
||||
The database must already be initialized (run 'bd init' first if needed).
|
||||
To initialize and restore in one step, use: bd init && bd backup restore`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("backup-restore")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
var dir string
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package main
|
|||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
|
@ -10,6 +11,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
|
@ -78,6 +80,13 @@ normal 'bd' subcommands for interactive/read operations.`,
|
|||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("batch")
|
||||
|
||||
evt := metrics.NewCommandEvent("batch")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if store == nil {
|
||||
return fmt.Errorf("no database connection available (%s)", diagHint())
|
||||
}
|
||||
|
|
@ -110,10 +119,12 @@ normal 'bd' subcommands for interactive/read operations.`,
|
|||
fmt.Fprintf(cmd.OutOrStdout(), "line %d: %s\n", op.line, op.raw)
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"dry_run": true,
|
||||
"operations": len(ops),
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%d operations parsed (dry-run, nothing executed)\n", len(ops))
|
||||
}
|
||||
|
|
@ -124,10 +135,12 @@ normal 'bd' subcommands for interactive/read operations.`,
|
|||
// Empty input is a no-op success, matching 'bd list | bd batch' on
|
||||
// an empty list.
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"operations": 0,
|
||||
"status": "ok",
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "batch: 0 operations (no-op)")
|
||||
}
|
||||
|
|
@ -156,7 +169,9 @@ normal 'bd' subcommands for interactive/read operations.`,
|
|||
})
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSONError(err, "batch_error")
|
||||
if jerr := outputJSONError(err, "batch_error"); jerr != nil {
|
||||
return errors.Join(err, jerr)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
@ -164,11 +179,13 @@ normal 'bd' subcommands for interactive/read operations.`,
|
|||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"operations": len(results),
|
||||
"status": "ok",
|
||||
"results": results,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "batch: %d operations committed\n", len(results))
|
||||
for _, r := range results {
|
||||
|
|
|
|||
|
|
@ -27,12 +27,12 @@ func TestEmbeddedBlocked(t *testing.T) {
|
|||
cmd := exec.Command(bd, "blocked")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd blocked failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
// No blocked issues on fresh db
|
||||
_ = out
|
||||
_ = stdout.String()
|
||||
})
|
||||
|
||||
// ===== With Blocked Issue =====
|
||||
|
|
@ -52,12 +52,12 @@ func TestEmbeddedBlocked(t *testing.T) {
|
|||
cmd = exec.Command(bd, "blocked")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd blocked failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(string(out), blocked.ID) {
|
||||
t.Errorf("expected %s in blocked output: %s", blocked.ID, out)
|
||||
if !strings.Contains(stdout.String(), blocked.ID) {
|
||||
t.Errorf("expected %s in blocked output: %s", blocked.ID, stdout.String())
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -67,11 +67,11 @@ func TestEmbeddedBlocked(t *testing.T) {
|
|||
cmd := exec.Command(bd, "blocked", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd blocked --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.IndexAny(s, "[{")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON in blocked --json output: %s", s)
|
||||
|
|
|
|||
124
cmd/bd/blocked_proxied_integration_test.go
Normal file
124
cmd/bd/blocked_proxied_integration_test.go
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func bdProxiedBlockedJSON(t *testing.T, bd string, p proxiedProject, args ...string) []*types.BlockedIssue {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"blocked", "--json"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked --json %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
s := strings.TrimSpace(stdout)
|
||||
start := strings.Index(s, "[")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON array in blocked --json output: %s", stdout)
|
||||
}
|
||||
var out []*types.BlockedIssue
|
||||
if err := json.Unmarshal([]byte(s[start:]), &out); err != nil {
|
||||
t.Fatalf("parse blocked JSON: %v\n%s", err, s[start:])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func bdProxiedBlockedCapture(t *testing.T, bd string, p proxiedProject, args ...string) (string, string) {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"blocked"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
return stdout, stderr
|
||||
}
|
||||
|
||||
func TestProxiedServerBlocked(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("json_and_text_with_blockers", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "bk1")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "The blocker")
|
||||
dependent := bdProxiedCreate(t, bd, p.dir, "I am blocked", "--deps", "depends-on:"+blocker.ID)
|
||||
|
||||
got := bdProxiedBlockedJSON(t, bd, p)
|
||||
var entry *types.BlockedIssue
|
||||
for _, bi := range got {
|
||||
if bi.ID == dependent.ID {
|
||||
entry = bi
|
||||
break
|
||||
}
|
||||
}
|
||||
if entry == nil {
|
||||
out, _ := json.Marshal(got)
|
||||
t.Fatalf("expected %s in blocked listing, got: %s", dependent.ID, out)
|
||||
}
|
||||
if entry.BlockedByCount != 1 {
|
||||
t.Errorf("BlockedByCount = %d, want 1", entry.BlockedByCount)
|
||||
}
|
||||
if len(entry.BlockedBy) != 1 || entry.BlockedBy[0] != blocker.ID {
|
||||
t.Errorf("BlockedBy = %v, want [%s]", entry.BlockedBy, blocker.ID)
|
||||
}
|
||||
|
||||
stdout, _ := bdProxiedBlockedCapture(t, bd, p)
|
||||
if !strings.Contains(stdout, "Blocked issues") {
|
||||
t.Errorf("expected heading in text output, got: %s", stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, "Blocked by 1 open dependencies") {
|
||||
t.Errorf("expected blocker summary line, got: %s", stdout)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty_case", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "bk2")
|
||||
bdProxiedCreate(t, bd, p.dir, "Nothing blocked here")
|
||||
|
||||
out, err := bdProxiedRun(t, bd, p.dir, "blocked", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd blocked --json failed: %v\n%s", err, out)
|
||||
}
|
||||
var empty []*types.BlockedIssue
|
||||
if err := json.Unmarshal(bytes.TrimSpace(out), &empty); err != nil {
|
||||
t.Fatalf("parse empty blocked JSON: %v\n%s", err, out)
|
||||
}
|
||||
if len(empty) != 0 {
|
||||
t.Errorf("expected [] for no blockers, got %d entries", len(empty))
|
||||
}
|
||||
|
||||
stdout, _ := bdProxiedBlockedCapture(t, bd, p)
|
||||
if !strings.Contains(stdout, "No blocked issues") {
|
||||
t.Errorf("expected 'No blocked issues' message, got: %s", stdout)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("parent_filter_restricts_to_descendants", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "bk3")
|
||||
parent := bdProxiedCreate(t, bd, p.dir, "Parent epic", "--type", "epic")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Inside blocker")
|
||||
inside := bdProxiedCreate(t, bd, p.dir, "Inside blocked", "--parent", parent.ID, "--deps", "depends-on:"+blocker.ID)
|
||||
outsideBlocker := bdProxiedCreate(t, bd, p.dir, "Outside blocker")
|
||||
outside := bdProxiedCreate(t, bd, p.dir, "Outside blocked", "--deps", "depends-on:"+outsideBlocker.ID)
|
||||
|
||||
got := bdProxiedBlockedJSON(t, bd, p, "--parent", parent.ID)
|
||||
ids := map[string]bool{}
|
||||
for _, bi := range got {
|
||||
ids[bi.ID] = true
|
||||
}
|
||||
if !ids[inside.ID] {
|
||||
t.Errorf("expected descendant %s in --parent result", inside.ID)
|
||||
}
|
||||
if ids[outside.ID] {
|
||||
t.Errorf("non-descendant %s leaked into --parent result", outside.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -4,7 +4,9 @@ import (
|
|||
"bufio"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
|
@ -13,14 +15,17 @@ import (
|
|||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor/fix"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/storage/doltutil"
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
"github.com/steveyegge/beads/internal/storage/versioncontrolops"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
|
@ -98,7 +103,7 @@ Unlike 'bd init --force', bootstrap will never delete existing issues.
|
|||
|
||||
Bootstrap auto-detects the right action:
|
||||
• If sync.remote is configured: clones from the remote
|
||||
• If git origin has Dolt data (refs/dolt/data): clones from git
|
||||
• If git origin has Dolt data (refs/dolt/data): clones from git and wires origin for future push/pull
|
||||
• If .beads/backup/*.jsonl exists: restores from backup
|
||||
• If .beads/issues.jsonl exists: imports from git-tracked JSONL
|
||||
• If no database exists: creates a fresh one
|
||||
|
|
@ -119,7 +124,16 @@ Examples:
|
|||
bd bootstrap --json # Output plan as JSON
|
||||
bd bootstrap --yes # Skip confirmation prompt
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("bootstrap")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
||||
yesFlag, _ := cmd.Flags().GetBool("yes")
|
||||
nonInteractiveFlag, _ := cmd.Flags().GetBool("non-interactive")
|
||||
|
|
@ -149,7 +163,7 @@ Examples:
|
|||
} else {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
FatalError("failed to get working directory: %v", err)
|
||||
return HandleError("failed to get working directory: %v", err)
|
||||
}
|
||||
beadsDir = filepath.Join(cwd, ".beads")
|
||||
}
|
||||
|
|
@ -159,15 +173,15 @@ Examples:
|
|||
}
|
||||
|
||||
if beadsDir == "" {
|
||||
// No .beads and no remote data — nothing to bootstrap from.
|
||||
if jsonOutput {
|
||||
outputJSON(noWorkspaceBootstrapPayload())
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", activeWorkspaceNotFoundMessage())
|
||||
fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint())
|
||||
fmt.Fprintf(os.Stderr, "Bootstrap is for existing projects that need database setup.\n")
|
||||
if err := outputJSON(noWorkspaceBootstrapPayload()); err != nil {
|
||||
return err
|
||||
}
|
||||
return SilentExit()
|
||||
}
|
||||
os.Exit(1)
|
||||
fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint())
|
||||
fmt.Fprintf(os.Stderr, "Bootstrap is for existing projects that need database setup.\n")
|
||||
return HandleError("%s", activeWorkspaceNotFoundMessage())
|
||||
}
|
||||
|
||||
// Load config from .beads/metadata.json. When the beadsDir was
|
||||
|
|
@ -186,7 +200,7 @@ Examples:
|
|||
|
||||
resolvedCfg, repairMsg, err := applyBootstrapMetadataRepair(beadsDir, cfg, !dryRun)
|
||||
if err != nil {
|
||||
FatalError("failed to reconcile shared-server metadata: %v", err)
|
||||
return HandleError("failed to reconcile shared-server metadata: %v", err)
|
||||
}
|
||||
if resolvedCfg != nil {
|
||||
cfg = resolvedCfg
|
||||
|
|
@ -196,9 +210,11 @@ Examples:
|
|||
plan := detectBootstrapAction(beadsDir, cfg)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(plan)
|
||||
if err := outputJSON(plan); err != nil {
|
||||
return err
|
||||
}
|
||||
if plan.Action == "none" || dryRun {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if repairMsg != "" {
|
||||
|
|
@ -206,14 +222,14 @@ Examples:
|
|||
}
|
||||
printBootstrapPlan(plan)
|
||||
if plan.Action == "none" || dryRun {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the plan
|
||||
if err := executeBootstrapPlan(plan, cfg, nonInteractive); err != nil {
|
||||
FatalError("Bootstrap failed: %v", err)
|
||||
return HandleError("Bootstrap failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -458,7 +474,7 @@ func printBootstrapPlan(plan BootstrapPlan) {
|
|||
switch plan.Action {
|
||||
case "none":
|
||||
fmt.Printf("✓ Database already exists: %s\n", plan.BeadsDir)
|
||||
if isEmbeddedMode() {
|
||||
if !usesSQLServer() {
|
||||
fmt.Printf(" Nothing to do.\n")
|
||||
} else {
|
||||
fmt.Printf(" Nothing to do. Use 'bd doctor' to check health.\n")
|
||||
|
|
@ -643,17 +659,65 @@ func executeSyncAction(ctx context.Context, plan BootstrapPlan, cfg *configfile.
|
|||
// Both embedded and server mode handle this in their store init paths.
|
||||
warmupStore, err := newDoltStoreFromConfig(ctx, plan.BeadsDir)
|
||||
if err != nil {
|
||||
// #4259: the cloned remote is behind this binary, so the remote-migrate
|
||||
// gate held migration for an explicit operator decision. Surface that
|
||||
// now with bootstrap-specific guidance and a non-zero exit. Returning
|
||||
// silent success here (as this path once did) sent operators in a
|
||||
// loop: the first real command failed with the gate message, whose
|
||||
// generic "adopt" remedy is `bd bootstrap` — which re-clones the same
|
||||
// behind database and silently "succeeds" again (bd-6dnrw.31).
|
||||
var gateErr *schema.RemoteMigrateGateError
|
||||
if errors.As(err, &gateErr) {
|
||||
if !jsonOutput {
|
||||
printBootstrapRemoteBehindGuidance(os.Stderr, gateErr, plan.SyncRemote, "bd bootstrap")
|
||||
}
|
||||
unit := "migrations"
|
||||
if gateErr.Pending == 1 {
|
||||
unit = "migration"
|
||||
}
|
||||
return fmt.Errorf("clone from %s succeeded, but the database needs %d schema %s (v%d -> v%d) that bd will not auto-apply to a remote-backed database (#4259)",
|
||||
plan.SyncRemote, gateErr.Pending, unit, gateErr.CurrentVersion, gateErr.LatestVersion)
|
||||
}
|
||||
// Non-fatal: wisp tables will be created on the next command that
|
||||
// opens the store. Warn so the user knows to retry if they hit
|
||||
// "table not found: wisp_*" errors.
|
||||
fmt.Fprintf(os.Stderr, "Warning: post-clone store init failed (wisp tables may be missing): %v\n", err)
|
||||
return nil
|
||||
}
|
||||
configureInitDoltRemote(ctx, warmupStore, plan.SyncRemote, false)
|
||||
_ = warmupStore.Close()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// printBootstrapRemoteBehindGuidance explains a remote-migrate gate refusal in
|
||||
// bootstrap terms. The gate's generic remedy ("adopt the migrated database:
|
||||
// bd bootstrap") is wrong from inside a bootstrap-style clone — the database
|
||||
// was just cloned from the remote, so the REMOTE is what is behind this binary
|
||||
// and re-cloning can never help. The way out is exactly one designated machine
|
||||
// migrating and pushing. rerunCmd is the command the operator just ran ("bd
|
||||
// bootstrap", "bd init") so the don't-bother-retrying line names it.
|
||||
func printBootstrapRemoteBehindGuidance(w io.Writer, e *schema.RemoteMigrateGateError, syncRemote, rerunCmd string) {
|
||||
unit := "migrations"
|
||||
if e.Pending == 1 {
|
||||
unit = "migration"
|
||||
}
|
||||
fmt.Fprintf(w, "\nThe database cloned from %s needs %d schema %s (v%d -> v%d).\n",
|
||||
syncRemote, e.Pending, unit, e.CurrentVersion, e.LatestVersion)
|
||||
fmt.Fprint(w,
|
||||
" bd will not migrate it automatically: migrating clones independently forks\n"+
|
||||
" the schema so `bd dolt pull` can no longer merge (#4259).\n"+
|
||||
"\n"+
|
||||
" Re-running `"+rerunCmd+"` will NOT fix this — the remote itself is behind.\n"+
|
||||
" Choose one:\n"+
|
||||
" • This machine is the designated migrator (exactly ONE machine should be):\n"+
|
||||
" "+schema.AllowRemoteMigrateEnv+"=1 bd migrate\n"+
|
||||
" bd dolt push\n"+
|
||||
" then other machines re-run `bd bootstrap` to adopt the migrated database.\n"+
|
||||
" • Another machine is the designated migrator: wait for it to push, then\n"+
|
||||
" re-run `bd bootstrap`, or keep using a bd version that matches the remote.\n\n")
|
||||
}
|
||||
|
||||
// finalizeSyncedBootstrap writes metadata.json and config.yaml after a
|
||||
// successful sync clone, matching the on-disk layout that bd init produces.
|
||||
// It is idempotent: re-running over an already-finalized workspace leaves
|
||||
|
|
@ -666,9 +730,12 @@ func finalizeSyncedBootstrap(beadsDir, syncRemote string, cfg *configfile.Config
|
|||
// required by configfile.Load consumers.
|
||||
cfg.Backend = configfile.BackendDolt
|
||||
cfg.DoltDatabase = dbName
|
||||
if cfg.IsDoltServerMode() || doltserver.IsSharedServerMode() {
|
||||
switch {
|
||||
case cfg.IsDoltProxiedServerMode():
|
||||
cfg.DoltMode = configfile.DoltModeProxiedServer
|
||||
case cfg.IsDoltServerMode() || doltserver.IsSharedServerMode():
|
||||
cfg.DoltMode = configfile.DoltModeServer
|
||||
} else {
|
||||
default:
|
||||
cfg.DoltMode = configfile.DoltModeEmbedded
|
||||
}
|
||||
// Mirror init's convention: metadata.json database points at the Dolt
|
||||
|
|
@ -684,6 +751,9 @@ func finalizeSyncedBootstrap(beadsDir, syncRemote string, cfg *configfile.Config
|
|||
if err := createConfigYaml(beadsDir, false, ""); err != nil {
|
||||
return fmt.Errorf("create config.yaml: %w", err)
|
||||
}
|
||||
if err := doctor.EnsureGitignoreForBeadsDir(beadsDir); err != nil {
|
||||
return fmt.Errorf("ensure .beads/.gitignore: %w", err)
|
||||
}
|
||||
|
||||
// Persist sync.remote so subsequent fresh clones (and bd bootstrap
|
||||
// retries) can rediscover the remote without re-probing origin refs.
|
||||
|
|
@ -776,7 +846,7 @@ func cloneViaEmbedded(ctx context.Context, beadsDir, remoteURL, dbName string) e
|
|||
}
|
||||
defer func() { _ = cleanup() }()
|
||||
|
||||
if err := versioncontrolops.DoltClone(ctx, db, remoteURL, dbName); err != nil {
|
||||
if err := versioncontrolops.DoltClone(ctx, db, remoteURL, dbName, os.Getenv("DOLT_REMOTE_USER")); err != nil {
|
||||
return fmt.Errorf("clone from remote: %w", err)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Synced database from %s\n", remoteURL)
|
||||
|
|
@ -813,7 +883,7 @@ func cloneViaServer(ctx context.Context, beadsDir, remoteURL, dbName string, cfg
|
|||
cfg.GetDoltServerHost(), port, err)
|
||||
}
|
||||
|
||||
if err := versioncontrolops.DoltClone(cloneCtx, db, remoteURL, dbName); err != nil {
|
||||
if err := versioncontrolops.DoltClone(cloneCtx, db, remoteURL, dbName, os.Getenv("DOLT_REMOTE_USER")); err != nil {
|
||||
return fmt.Errorf("clone from remote via server: %w", err)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Synced database from %s (via server at %s:%d)\n",
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ func bdBootstrap(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd bootstrap %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd bootstrap %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
func bdBootstrapAllowError(t *testing.T, bd, dir string, args ...string) (string, error) {
|
||||
|
|
@ -57,20 +57,23 @@ func TestBootstrapNoWorkspace(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("json_output", func(t *testing.T) {
|
||||
out, err := bdBootstrapAllowError(t, bd, dir, "--json")
|
||||
cmd := exec.Command(bd, "bootstrap", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err == nil {
|
||||
t.Fatal("expected bd bootstrap --json to exit non-zero without a workspace")
|
||||
}
|
||||
|
||||
s := strings.TrimSpace(out)
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
t.Fatalf("expected JSON object in output, got: %s", out)
|
||||
t.Fatalf("expected JSON object in output:\nstdout: %s\nstderr: %s", s, stderr.String())
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(s[start:]), &payload); err != nil {
|
||||
t.Fatalf("parse bootstrap JSON: %v\n%s", err, s)
|
||||
t.Fatalf("parse bootstrap JSON: %v\nstdout: %s", err, s)
|
||||
}
|
||||
if action, _ := payload["action"].(string); action != "none" {
|
||||
t.Fatalf("action = %q, want %q", action, "none")
|
||||
|
|
@ -147,12 +150,13 @@ func TestEmbeddedBootstrap(t *testing.T) {
|
|||
bcmd.Dir = dir
|
||||
bcmd.Env = bdEnv(dir)
|
||||
bcmd.Stdin = strings.NewReader("y\n")
|
||||
out, err := bcmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, bcmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bootstrap init failed: %v\n%s", err, out)
|
||||
t.Fatalf("bootstrap init failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(string(out), "Created fresh database") {
|
||||
t.Errorf("expected 'Created fresh database': %s", out)
|
||||
combined := stdout.String() + stderr.String()
|
||||
if !strings.Contains(combined, "Created fresh database") {
|
||||
t.Errorf("expected 'Created fresh database':\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -193,12 +197,50 @@ func TestEmbeddedBootstrap(t *testing.T) {
|
|||
bcmd.Dir = dir
|
||||
bcmd.Env = bdEnv(dir)
|
||||
bcmd.Stdin = strings.NewReader("y\n")
|
||||
out, err := bcmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, bcmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bootstrap jsonl-import failed: %v\n%s", err, out)
|
||||
t.Fatalf("bootstrap jsonl-import failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(string(out), "Imported") {
|
||||
t.Errorf("expected 'Imported' in output: %s", out)
|
||||
combined := stdout.String() + stderr.String()
|
||||
if !strings.Contains(combined, "Imported") {
|
||||
t.Errorf("expected 'Imported' in output:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bootstrap_from_git_origin_wires_remote", func(t *testing.T) {
|
||||
bareDir := filepath.Join(t.TempDir(), "origin.git")
|
||||
runGitForBootstrapTest(t, "", "init", "--bare", "--initial-branch=main", bareDir)
|
||||
remoteURL := "file://" + bareDir
|
||||
|
||||
sourceDir := t.TempDir()
|
||||
initGitRepoAt(t, sourceDir)
|
||||
runGitForBootstrapTest(t, sourceDir, "branch", "-M", "main")
|
||||
runGitForBootstrapTest(t, sourceDir, "remote", "add", "origin", remoteURL)
|
||||
runGitForBootstrapTest(t, sourceDir, "commit", "--allow-empty", "-m", "init")
|
||||
runGitForBootstrapTest(t, sourceDir, "push", "-u", "origin", "main")
|
||||
runBDInit(t, bd, sourceDir, "--prefix", "beads", "--skip-hooks", "--skip-agents")
|
||||
bdCreate(t, bd, sourceDir, "Seed remote data", "--type", "task")
|
||||
bdDolt(t, bd, sourceDir, "push")
|
||||
|
||||
cloneDir := t.TempDir()
|
||||
runGitForBootstrapTest(t, cloneDir, "init", "-b", "main")
|
||||
runGitForBootstrapTest(t, cloneDir, "remote", "add", "origin", remoteURL)
|
||||
|
||||
out := bdBootstrap(t, bd, cloneDir, "--yes")
|
||||
if !strings.Contains(out, "clone from remote") {
|
||||
t.Fatalf("expected bootstrap sync plan, got:\n%s", out)
|
||||
}
|
||||
|
||||
remotes := bdDolt(t, bd, cloneDir, "remote", "list")
|
||||
if !strings.Contains(remotes, "origin") || !strings.Contains(remotes, remoteURL) {
|
||||
t.Fatalf("bootstrap should leave origin configured as a Dolt remote %q; remote list:\n%s", remoteURL, remotes)
|
||||
}
|
||||
configYAML, err := os.ReadFile(filepath.Join(cloneDir, ".beads", "config.yaml"))
|
||||
if err != nil {
|
||||
t.Fatalf("read config.yaml: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(configYAML), remoteURL) {
|
||||
t.Fatalf("bootstrap should persist sync.remote; config.yaml:\n%s", configYAML)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestIsNonInteractiveBootstrap tests the non-interactive detection logic for bootstrap.
|
||||
|
|
@ -111,3 +115,43 @@ func TestConfirmPromptNonInteractive(t *testing.T) {
|
|||
t.Error("confirmPrompt should return true when nonInteractive=true")
|
||||
}
|
||||
}
|
||||
|
||||
// bd-6dnrw.31: a remote-migrate gate refusal during the bootstrap warmup open
|
||||
// must produce bootstrap-specific guidance — the gate's generic "adopt: bd
|
||||
// bootstrap" remedy loops forever when the remote itself is behind.
|
||||
func TestPrintBootstrapRemoteBehindGuidance(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
printBootstrapRemoteBehindGuidance(&buf, &schema.RemoteMigrateGateError{
|
||||
CurrentVersion: 49,
|
||||
LatestVersion: 50,
|
||||
Pending: 1,
|
||||
}, "https://doltremoteapi.example.com/org/beads", "bd bootstrap")
|
||||
|
||||
out := buf.String()
|
||||
for _, want := range []string{
|
||||
"needs 1 schema migration (v49 -> v50)",
|
||||
"Re-running `bd bootstrap` will NOT fix this",
|
||||
schema.AllowRemoteMigrateEnv + "=1",
|
||||
"bd dolt push",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("guidance missing %q in:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// bd-4mpy7: bd init's bootstrap path reuses the same guidance but must name
|
||||
// the command the operator actually ran in the don't-bother-retrying line.
|
||||
func TestPrintBootstrapRemoteBehindGuidance_InitWording(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
printBootstrapRemoteBehindGuidance(&buf, &schema.RemoteMigrateGateError{
|
||||
CurrentVersion: 49,
|
||||
LatestVersion: 50,
|
||||
Pending: 1,
|
||||
}, "git+https://github.com/example/dotfiles.git", "bd init")
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "Re-running `bd init` will NOT fix this") {
|
||||
t.Errorf("guidance missing init-specific retry line in:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1214,6 +1214,17 @@ func TestFinalizeSyncedBootstrapWritesConfigFiles(t *testing.T) {
|
|||
if !strings.Contains(yaml, syncRemote) {
|
||||
t.Errorf("config.yaml does not contain sync remote URL %q:\n%s", syncRemote, yaml)
|
||||
}
|
||||
|
||||
gitignoreBytes, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore"))
|
||||
if err != nil {
|
||||
t.Fatalf(".beads/.gitignore missing after finalize: %v", err)
|
||||
}
|
||||
gitignore := string(gitignoreBytes)
|
||||
for _, pattern := range []string{".local_version", "backup/", "export-state.json", "last-touched"} {
|
||||
if !strings.Contains(gitignore, pattern) {
|
||||
t.Errorf(".beads/.gitignore missing runtime pattern %q:\n%s", pattern, gitignore)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeSyncedBootstrap_WorktreeStubDoesNotShadowTargetConfig(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
|
|
@ -19,29 +20,35 @@ it lists all branches. With an argument, it creates a new branch.
|
|||
Examples:
|
||||
bd branch # List all branches
|
||||
bd branch feature-xyz # Create a new branch named feature-xyz`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("branch")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
// If no args, list branches
|
||||
if len(args) == 0 {
|
||||
branches, err := store.ListBranches(ctx)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("failed to list branches: %v", err)
|
||||
return HandleErrorRespectJSON("failed to list branches: %v", err)
|
||||
}
|
||||
|
||||
currentBranch, err := store.CurrentBranch(ctx)
|
||||
if err != nil {
|
||||
// Non-fatal, just don't show current marker
|
||||
currentBranch = ""
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"current": currentBranch,
|
||||
"branches": branches,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s Branches:\n\n", ui.RenderAccent("🌿"))
|
||||
|
|
@ -53,23 +60,22 @@ Examples:
|
|||
}
|
||||
}
|
||||
fmt.Println()
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create new branch
|
||||
branchName := args[0]
|
||||
if err := store.Branch(ctx, branchName); err != nil {
|
||||
FatalErrorRespectJSON("failed to create branch: %v", err)
|
||||
return HandleErrorRespectJSON("failed to create branch: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"created": branchName,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Created branch: %s\n", ui.RenderAccent(branchName))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,11 +19,11 @@ func bdBranch(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd branch %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd branch %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
func TestEmbeddedBranch(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -2,11 +2,10 @@ package main
|
|||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
)
|
||||
|
||||
// childrenCmd lists child beads of a parent.
|
||||
// This is a convenience alias for 'bd list --parent <id> --status all'.
|
||||
// Unlike plain 'bd list', children includes closed issues by default (GH#2477).
|
||||
var childrenCmd = &cobra.Command{
|
||||
Use: "children <parent-id>",
|
||||
GroupID: "issues",
|
||||
|
|
@ -21,22 +20,38 @@ Examples:
|
|||
bd children hq-abc123 # List all children of hq-abc123
|
||||
bd children hq-abc123 --json # List children in JSON format
|
||||
bd children hq-abc123 --pretty # Show children in tree format`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("children")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
parentID := args[0]
|
||||
pretty, _ := cmd.Flags().GetBool("pretty")
|
||||
|
||||
// Set the parent flag on listCmd, run it, then reset
|
||||
_ = listCmd.Flags().Set("parent", parentID)
|
||||
defer func() { _ = listCmd.Flags().Set("parent", "") }()
|
||||
|
||||
// Include all statuses by default so closed children are visible (GH#2477).
|
||||
_ = listCmd.Flags().Set("status", "all")
|
||||
defer func() { _ = listCmd.Flags().Set("status", "") }()
|
||||
|
||||
listCmd.Run(listCmd, []string{})
|
||||
if pretty {
|
||||
_ = listCmd.Flags().Set("pretty", "true")
|
||||
defer func() { _ = listCmd.Flags().Set("pretty", "false") }()
|
||||
}
|
||||
|
||||
// Reuse the shared, non-emitting list core so a single `bd children`
|
||||
// records exactly one cli_command event ("children"), not also "list".
|
||||
return runListCore(listCmd, []string{})
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
childrenCmd.Flags().Bool("pretty", false, "Show children in tree format")
|
||||
rootCmd.AddCommand(childrenCmd)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,11 +19,11 @@ func bdChildren(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd children %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd children %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
func TestEmbeddedChildren(t *testing.T) {
|
||||
|
|
@ -59,11 +59,11 @@ func TestEmbeddedChildren(t *testing.T) {
|
|||
cmd := exec.Command(bd, "children", parent.ID, "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd children --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd children --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "[")
|
||||
if start >= 0 {
|
||||
var issues []map[string]interface{}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
|
@ -45,9 +46,18 @@ SAFETY:
|
|||
SEE ALSO:
|
||||
bd doctor --fix Automatic health checks and repairs (recommended for routine maintenance)
|
||||
bd admin compact Compact old closed issues to save space`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("admin-cleanup")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := requireServerMode("cleanup"); err != nil {
|
||||
FatalError("%v", err)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
force, _ := cmd.Flags().GetBool("force")
|
||||
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
||||
|
|
@ -55,40 +65,34 @@ SEE ALSO:
|
|||
olderThanDays, _ := cmd.Flags().GetInt("older-than")
|
||||
wispOnly, _ := cmd.Flags().GetBool("ephemeral")
|
||||
|
||||
// Ensure we have storage
|
||||
if store == nil {
|
||||
if err := ensureStoreActive(); err != nil {
|
||||
FatalError("%v", err)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
// Build filter for closed issues
|
||||
statusClosed := types.StatusClosed
|
||||
filter := types.IssueFilter{
|
||||
Status: &statusClosed,
|
||||
}
|
||||
|
||||
// Add age filter if specified
|
||||
if olderThanDays > 0 {
|
||||
cutoffTime := time.Now().AddDate(0, 0, -olderThanDays)
|
||||
filter.ClosedBefore = &cutoffTime
|
||||
}
|
||||
|
||||
// Add wisp filter if specified (bd-kwro.9)
|
||||
if wispOnly {
|
||||
wispTrue := true
|
||||
filter.Ephemeral = &wispTrue
|
||||
}
|
||||
|
||||
// Get all closed issues matching filter
|
||||
closedIssues, err := store.SearchIssues(ctx, "", filter)
|
||||
if err != nil {
|
||||
FatalError("listing issues: %v", err)
|
||||
return HandleError("listing issues: %v", err)
|
||||
}
|
||||
|
||||
// Filter out pinned issues - they are protected from cleanup (bd-b2k)
|
||||
pinnedCount := 0
|
||||
filteredIssues := make([]*types.Issue, 0, len(closedIssues))
|
||||
for _, issue := range closedIssues {
|
||||
|
|
@ -116,7 +120,9 @@ SEE ALSO:
|
|||
if wispOnly {
|
||||
result.Ephemeral = true
|
||||
}
|
||||
outputJSON(result)
|
||||
if err := outputJSON(result); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
msg := "No closed issues to delete"
|
||||
if wispOnly && olderThanDays > 0 {
|
||||
|
|
@ -128,22 +134,20 @@ SEE ALSO:
|
|||
}
|
||||
fmt.Println(msg)
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Extract IDs
|
||||
issueIDs := make([]string, len(closedIssues))
|
||||
for i, issue := range closedIssues {
|
||||
issueIDs[i] = issue.ID
|
||||
}
|
||||
|
||||
// Show preview
|
||||
if !force && !dryRun {
|
||||
issueType := "closed"
|
||||
if wispOnly {
|
||||
issueType = "closed wisp"
|
||||
}
|
||||
FatalErrorWithHint(
|
||||
return HandleErrorWithHint(
|
||||
fmt.Sprintf("would delete %d %s issue(s)", len(issueIDs), issueType),
|
||||
"Use --force to confirm or --dry-run to preview.")
|
||||
}
|
||||
|
|
@ -164,8 +168,10 @@ SEE ALSO:
|
|||
fmt.Println()
|
||||
}
|
||||
|
||||
// Use the existing batch deletion logic
|
||||
deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, "cleanup")
|
||||
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, "cleanup"); err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -171,9 +171,6 @@ func parseCreatedIssueID(t *testing.T, out string) string {
|
|||
}
|
||||
|
||||
func TestCoverage_ShowUpdateClose(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping CLI coverage test in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
runBDForCoverage(t, dir, "init", "--prefix", "test", "--quiet")
|
||||
|
|
@ -248,9 +245,6 @@ func TestCoverage_ShowUpdateClose(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCoverage_TemplateAndPinnedProtections(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping CLI coverage test in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
runBDForCoverage(t, dir, "init", "--prefix", "test", "--quiet")
|
||||
|
|
@ -344,9 +338,6 @@ func TestCoverage_TemplateAndPinnedProtections(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCoverage_ShowThread(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping CLI coverage test in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
runBDForCoverage(t, dir, "init", "--prefix", "test", "--quiet")
|
||||
|
|
|
|||
|
|
@ -218,9 +218,6 @@ func runBDInProcess(t *testing.T, dir string, args ...string) string {
|
|||
}
|
||||
|
||||
func TestCLI_Ready(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
runBDInProcess(t, tmpDir, "create", "Ready issue", "-p", "1")
|
||||
|
|
@ -231,9 +228,6 @@ func TestCLI_Ready(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Create(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Test issue", "-p", "1", "--json")
|
||||
|
|
@ -255,9 +249,6 @@ func TestCLI_Create(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_List(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
runBDInProcess(t, tmpDir, "create", "First", "-p", "1")
|
||||
|
|
@ -274,9 +265,6 @@ func TestCLI_List(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Update(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue to update", "-p", "1", "--json")
|
||||
|
|
@ -296,9 +284,6 @@ func TestCLI_Update(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdateLabels(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue for label testing", "-p", "2", "--json")
|
||||
|
|
@ -361,9 +346,6 @@ func TestCLI_UpdateLabels(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdateEphemeral(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue for ephemeral testing", "-p", "2", "--json")
|
||||
|
|
@ -388,9 +370,6 @@ func TestCLI_UpdateEphemeral(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdatePersistent(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -427,9 +406,6 @@ func TestCLI_UpdatePersistent(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdateEphemeralMutualExclusion(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue for mutual exclusion test", "-p", "2", "--json")
|
||||
|
|
@ -449,9 +425,6 @@ func TestCLI_UpdateEphemeralMutualExclusion(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdateAppendNotes(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue for append-notes test", "-p", "2", "--notes", "Original notes", "--json")
|
||||
|
||||
|
|
@ -486,9 +459,6 @@ func TestCLI_UpdateAppendNotes(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_UpdateAppendNotesMutualExclusion(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue for notes mutual exclusion", "-p", "2", "--json")
|
||||
|
||||
|
|
@ -507,9 +477,6 @@ func TestCLI_UpdateAppendNotesMutualExclusion(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_NoteCommand(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
// Create an issue with initial notes
|
||||
|
|
@ -561,9 +528,6 @@ func TestCLI_NoteCommand(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Close(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Issue to close", "-p", "1", "--json")
|
||||
|
|
@ -586,9 +550,6 @@ func TestCLI_Close(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_DepAdd(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -609,9 +570,6 @@ func TestCLI_DepAdd(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_DepRemove(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -633,9 +591,6 @@ func TestCLI_DepRemove(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_DepTree(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -657,9 +612,6 @@ func TestCLI_DepTree(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Blocked(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -681,9 +633,6 @@ func TestCLI_Blocked(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Stats(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
runBDInProcess(t, tmpDir, "create", "Issue 1", "-p", "1")
|
||||
|
|
@ -696,9 +645,6 @@ func TestCLI_Stats(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Show(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Show test", "-p", "1", "--json")
|
||||
|
|
@ -714,9 +660,6 @@ func TestCLI_Show(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Export(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
runBDInProcess(t, tmpDir, "create", "Export test", "-p", "1")
|
||||
|
|
@ -730,9 +673,6 @@ func TestCLI_Export(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Import(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
runBDInProcess(t, tmpDir, "create", "Import test", "-p", "1")
|
||||
|
|
@ -815,9 +755,6 @@ func runBDExecAllowErrorWithEnv(t *testing.T, dir string, env []string, args ...
|
|||
// TestCLI_EndToEnd performs end-to-end testing using the actual binary
|
||||
// This ensures the compiled binary works correctly when executed normally
|
||||
func TestCLI_EndToEnd(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
if testDoltServerPort == 0 {
|
||||
t.Skip("skipping: Dolt test container not available")
|
||||
}
|
||||
|
|
@ -855,9 +792,6 @@ func TestCLI_EndToEnd(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Labels(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Label test", "-p", "1", "--json")
|
||||
|
|
@ -887,9 +821,6 @@ func TestCLI_Labels(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_PriorityFormats(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -925,9 +856,6 @@ func TestCLI_PriorityFormats(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCLI_Reopen(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
||||
tmpDir := setupCLITestDB(t)
|
||||
out := runBDInProcess(t, tmpDir, "create", "Reopen test", "-p", "1", "--json")
|
||||
|
|
@ -1010,9 +938,6 @@ func runBDInProcessAllowError(t *testing.T, dir string, args ...string) (string,
|
|||
|
||||
// TestCLI_CreateDryRun tests the --dry-run flag for bd create command (bd-nib2)
|
||||
func TestCLI_CreateDryRun(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
if testDoltServerPort == 0 {
|
||||
t.Skip("skipping: Dolt test container not available")
|
||||
}
|
||||
|
|
@ -1232,9 +1157,6 @@ func TestCLI_CommentsListMisplacedSyntax(t *testing.T) {
|
|||
//
|
||||
// Note: Short IDs work because the code calls utils.ResolvePartialID().
|
||||
func TestCLI_CommentsAddShortID(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
|
||||
t.Run("ShortIDWithCommentsAdd", func(t *testing.T) {
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
|
@ -1350,9 +1272,6 @@ func TestCLI_CommentsAddShortID(t *testing.T) {
|
|||
// TestCLI_CreateRejectsFlagLikeTitles verifies that positional arguments starting
|
||||
// with - or -- are rejected as likely misinterpreted flags (bd-2c0).
|
||||
func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
if testDoltServerPort == 0 {
|
||||
t.Skip("skipping: Dolt test container not available")
|
||||
}
|
||||
|
|
@ -1410,9 +1329,6 @@ func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) {
|
|||
// to the created issue (GH#2619). A storage-layer test already covers the DB
|
||||
// semantics; this test verifies the CLI flag is actually parsed and passed.
|
||||
func TestCLI_CreateNoHistory(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
|
||||
t.Run("NoHistoryFlagSetOnCreatedIssue", func(t *testing.T) {
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
|
@ -1468,9 +1384,6 @@ func TestCLI_CreateNoHistory(t *testing.T) {
|
|||
|
||||
// TestCLI_WispListTypeFilter tests that bd mol wisp list --type filters correctly.
|
||||
func TestCLI_WispListTypeFilter(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -1531,9 +1444,6 @@ func TestCLI_WispListTypeFilter(t *testing.T) {
|
|||
// TestCLI_WispGCExcludeType tests that bd mol wisp gc --exclude-type skips
|
||||
// wisps of the excluded type during garbage collection.
|
||||
func TestCLI_WispGCExcludeType(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow CLI test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
|
|||
306
cmd/bd/close.go
306
cmd/bd/close.go
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/audit"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
|
|
@ -24,62 +25,46 @@ var closeCmd = &cobra.Command{
|
|||
Long: `Close one or more issues.
|
||||
|
||||
If no issue ID is provided, closes the last touched issue (from most recent
|
||||
create, update, show, or close operation).`,
|
||||
Args: cobra.MinimumNArgs(0),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
create, update, show, or close operation).
|
||||
|
||||
When closing multiple issues, provide one --reason for all IDs or repeat
|
||||
--reason once per ID. Reasons map positionally: the first --reason applies
|
||||
to the first ID, the second --reason to the second ID, regardless of where
|
||||
the flags appear in the command line.`,
|
||||
Args: cobra.MinimumNArgs(0),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("close")
|
||||
|
||||
evt := metrics.NewCommandEvent("close")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if usesProxiedServer() {
|
||||
runCloseProxiedServer(cmd, rootCtx, args)
|
||||
return nil
|
||||
}
|
||||
|
||||
// If no IDs provided, use last touched issue
|
||||
if len(args) == 0 {
|
||||
lastTouched := GetLastTouchedID()
|
||||
if lastTouched == "" {
|
||||
FatalErrorRespectJSON("no issue ID provided and no last touched issue")
|
||||
return HandleErrorRespectJSON("no issue ID provided and no last touched issue")
|
||||
}
|
||||
args = []string{lastTouched}
|
||||
}
|
||||
reason, _ := cmd.Flags().GetString("reason")
|
||||
if reason == "" {
|
||||
// Check --resolution alias (Jira CLI convention)
|
||||
reason, _ = cmd.Flags().GetString("resolution")
|
||||
}
|
||||
if reason == "" {
|
||||
// Check -m alias (git commit convention)
|
||||
reason, _ = cmd.Flags().GetString("message")
|
||||
}
|
||||
if reason == "" {
|
||||
// Check --comment alias (desire-path from hq-ftpg)
|
||||
reason, _ = cmd.Flags().GetString("comment")
|
||||
reasons, updatedArgs, err := resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
args = updatedArgs
|
||||
|
||||
// --reason-file <path> (with - for stdin) mirrors `bd create --body-file`,
|
||||
// so agents can pass structured close templates without shell-escaping hell (#3512).
|
||||
if fileReason, ok, err := resolveReasonFile(cmd, reason); err != nil {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
} else if ok {
|
||||
reason = fileReason
|
||||
}
|
||||
|
||||
// Desire-path: "bd done <id> <message>" treats last positional arg as reason
|
||||
// when no reason flag was explicitly provided (hq-pe8ce)
|
||||
if reason == "" && cmd.CalledAs() == "done" && len(args) >= 2 {
|
||||
reason = args[len(args)-1]
|
||||
args = args[:len(args)-1]
|
||||
}
|
||||
|
||||
if reason == "" {
|
||||
reason = "Closed"
|
||||
}
|
||||
|
||||
// Validate close reason if configured
|
||||
closeValidation := config.GetString("validation.on-close")
|
||||
if closeValidation == "error" || closeValidation == "warn" {
|
||||
if err := validation.ValidateCloseReason(reason); err != nil {
|
||||
if closeValidation == "error" {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
}
|
||||
// warn mode: print warning but proceed
|
||||
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
|
||||
}
|
||||
if err := validateCloseReasons(reasons); err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
force, _ := cmd.Flags().GetBool("force")
|
||||
|
|
@ -89,7 +74,6 @@ create, update, show, or close operation).`,
|
|||
|
||||
claimNext, _ := cmd.Flags().GetBool("claim-next")
|
||||
|
||||
// Get session ID from flag or environment variable
|
||||
session, _ := cmd.Flags().GetString("session")
|
||||
if session == "" {
|
||||
session = os.Getenv("CLAUDE_SESSION_ID")
|
||||
|
|
@ -97,21 +81,18 @@ create, update, show, or close operation).`,
|
|||
|
||||
ctx := rootCtx
|
||||
|
||||
// --continue only works with a single issue
|
||||
if continueFlag && len(args) > 1 {
|
||||
FatalErrorRespectJSON("--continue only works when closing a single issue")
|
||||
return HandleErrorRespectJSON("--continue only works when closing a single issue")
|
||||
}
|
||||
|
||||
// --suggest-next only works with a single issue
|
||||
if suggestNext && len(args) > 1 {
|
||||
FatalErrorRespectJSON("--suggest-next only works when closing a single issue")
|
||||
return HandleErrorRespectJSON("--suggest-next only works when closing a single issue")
|
||||
}
|
||||
|
||||
// Resolve partial IDs with routing fallback (beads-0km).
|
||||
results, cleanup, resolveErr := resolveCloseTargets(ctx, store, args)
|
||||
defer cleanup()
|
||||
if resolveErr != nil {
|
||||
FatalErrorRespectJSON("%v", resolveErr)
|
||||
return HandleErrorRespectJSON("%v", resolveErr)
|
||||
}
|
||||
resolvedIDs := make([]string, 0, len(results))
|
||||
for _, r := range results {
|
||||
|
|
@ -120,7 +101,7 @@ create, update, show, or close operation).`,
|
|||
|
||||
// Track which stores were mutated so routed closes can commit before
|
||||
// cleanup closes the routed handle. Deduped by pointer.
|
||||
mutatedStores := map[storage.DoltStorage]struct{}{}
|
||||
mutatedStores := map[storage.DoltStorage][]string{}
|
||||
|
||||
// Direct mode
|
||||
closedIssues := []*types.Issue{}
|
||||
|
|
@ -129,20 +110,27 @@ create, update, show, or close operation).`,
|
|||
for i, id := range resolvedIDs {
|
||||
result := results[i]
|
||||
activeStore := result.Store
|
||||
reason := reasonForCloseIndex(reasons, i)
|
||||
// Get issue for checks (nil issue is handled by validateIssueClosable)
|
||||
issue := result.Issue
|
||||
|
||||
if err := validateIssueClosable(id, issue, force); err != nil {
|
||||
if err := validateIssueClosable(id, issue, actor, force); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Epic close guard: prevent closing epics with open children (mw-local-4so.5.2)
|
||||
if !force && issue != nil && issue.IssueType == types.TypeEpic {
|
||||
openChildren := countEpicOpenChildren(ctx, activeStore, id)
|
||||
// Open-children close guard: prevent closing any issue with open
|
||||
// parent-child dependents (GH#3681). With --force the close proceeds
|
||||
// but a warning is emitted so orphaned children are never silent.
|
||||
if issue != nil {
|
||||
openChildren := countOpenChildren(ctx, activeStore, id)
|
||||
if openChildren > 0 {
|
||||
fmt.Fprintf(os.Stderr, "cannot close epic %s: %d open child issue(s); close children first or use --force to override\n", id, openChildren)
|
||||
continue
|
||||
if force {
|
||||
fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", id, openChildren)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "cannot close %s: %d open child issue(s); close children first or use --force to override\n", id, openChildren)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -171,7 +159,7 @@ create, update, show, or close operation).`,
|
|||
fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err)
|
||||
continue
|
||||
}
|
||||
mutatedStores[activeStore] = struct{}{}
|
||||
mutatedStores[activeStore] = append(mutatedStores[activeStore], id)
|
||||
|
||||
// Audit log the close (survives Dolt GC flatten)
|
||||
oldStatus := "open"
|
||||
|
|
@ -207,16 +195,14 @@ create, update, show, or close operation).`,
|
|||
postCloseStore = results[0].Store
|
||||
}
|
||||
|
||||
// Handle --suggest-next flag in direct mode
|
||||
if suggestNext && len(resolvedIDs) == 1 && closedCount > 0 {
|
||||
unblocked, err := postCloseStore.GetNewlyUnblockedByClose(ctx, resolvedIDs[0])
|
||||
if err == nil && len(unblocked) > 0 {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"closed": closedIssues,
|
||||
"unblocked": unblocked,
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("\nNewly unblocked:\n")
|
||||
for _, issue := range unblocked {
|
||||
|
|
@ -225,20 +211,25 @@ create, update, show, or close operation).`,
|
|||
}
|
||||
}
|
||||
|
||||
// Handle --continue flag
|
||||
if continueFlag && len(resolvedIDs) == 1 && closedCount > 0 {
|
||||
autoClaim := !noAuto
|
||||
result, err := AdvanceToNextStep(ctx, postCloseStore, resolvedIDs[0], autoClaim, actor)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
|
||||
} else if result != nil {
|
||||
// Mirror --claim-next: when AdvanceToNextStep auto-claims the
|
||||
// next step, update .beads/last-touched so subsequent default-
|
||||
// target commands (e.g. bare `bd update`, `bd close`) target
|
||||
// it. Without this, last-touched stays pointed at the just-
|
||||
// closed step. See gastownhall/beads#3769.
|
||||
if result.AutoAdvanced && result.NextStep != nil {
|
||||
SetLastTouchedID(result.NextStep.ID)
|
||||
}
|
||||
if jsonOutput {
|
||||
// Include continue result in JSON output
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"closed": closedIssues,
|
||||
"continue": result,
|
||||
})
|
||||
return
|
||||
}
|
||||
PrintContinueResult(result)
|
||||
}
|
||||
|
|
@ -259,7 +250,7 @@ create, update, show, or close operation).`,
|
|||
err := postCloseStore.ClaimIssue(ctx, nextIssue.ID, actor)
|
||||
if err == nil {
|
||||
claimedNextIssue = nextIssue
|
||||
mutatedStores[postCloseStore] = struct{}{}
|
||||
mutatedStores[postCloseStore] = append(mutatedStores[postCloseStore], nextIssue.ID)
|
||||
if jsonOutput {
|
||||
// JSON handled below
|
||||
} else {
|
||||
|
|
@ -276,52 +267,43 @@ create, update, show, or close operation).`,
|
|||
|
||||
if jsonOutput && len(closedIssues) > 0 {
|
||||
if claimedNextIssue != nil {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"closed": closedIssues,
|
||||
"claimed": claimedNextIssue,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
outputJSON(closedIssues)
|
||||
if err := outputJSON(closedIssues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if closedCount > 0 {
|
||||
hasRoutedMutation := false
|
||||
for s := range mutatedStores {
|
||||
if s != nil && s != store {
|
||||
hasRoutedMutation = true
|
||||
break
|
||||
for s, ids := range mutatedStores {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hasRoutedMutation {
|
||||
for s := range mutatedStores {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
if err := maybeAutoCommitStore(ctx, s, doltAutoCommitParams{
|
||||
Command: cmd.Name(),
|
||||
IssueIDs: resolvedIDs,
|
||||
}); err != nil {
|
||||
FatalErrorRespectJSON("dolt auto-commit failed: %v", err)
|
||||
}
|
||||
if err := commitPendingIfEmbedded(ctx, s, actor, doltAutoCommitParams{
|
||||
Command: "close",
|
||||
IssueIDs: ids,
|
||||
}); err != nil {
|
||||
return HandleErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
commandDidExplicitDoltCommit = true
|
||||
} else {
|
||||
commandDidWrite.Store(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Exit non-zero if no issues were actually closed (close guard
|
||||
// and other soft failures should surface as non-zero exit codes for scripting)
|
||||
totalAttempted := len(resolvedIDs)
|
||||
if totalAttempted > 0 && closedCount == 0 {
|
||||
os.Exit(1)
|
||||
return SilentExit()
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
closeCmd.Flags().StringP("reason", "r", "", "Reason for closing")
|
||||
registerCloseReasonFlag(closeCmd)
|
||||
closeCmd.Flags().String("resolution", "", "Alias for --reason (Jira CLI convention)")
|
||||
_ = closeCmd.Flags().MarkHidden("resolution") // Hidden alias for agent/CLI ergonomics
|
||||
closeCmd.Flags().StringP("message", "m", "", "Alias for --reason (git commit convention)")
|
||||
|
|
@ -339,6 +321,120 @@ func init() {
|
|||
rootCmd.AddCommand(closeCmd)
|
||||
}
|
||||
|
||||
type closeReasonFlagValue struct {
|
||||
values []string
|
||||
}
|
||||
|
||||
func registerCloseReasonFlag(cmd *cobra.Command) {
|
||||
cmd.Flags().VarP(&closeReasonFlagValue{}, "reason", "r", "Reason for closing")
|
||||
}
|
||||
|
||||
func (v *closeReasonFlagValue) Set(s string) error {
|
||||
v.values = append(v.values, s)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *closeReasonFlagValue) String() string {
|
||||
if len(v.values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return v.values[len(v.values)-1]
|
||||
}
|
||||
|
||||
func (v *closeReasonFlagValue) Type() string {
|
||||
return "string"
|
||||
}
|
||||
|
||||
func (v *closeReasonFlagValue) Values() []string {
|
||||
out := make([]string, len(v.values))
|
||||
copy(out, v.values)
|
||||
return out
|
||||
}
|
||||
|
||||
func resolveCloseReasons(cmd *cobra.Command, args []string) ([]string, []string, error) {
|
||||
reasons, err := collectCloseReasonFlags(cmd)
|
||||
if err != nil {
|
||||
return nil, args, err
|
||||
}
|
||||
|
||||
if fileReason, ok, err := resolveReasonFile(cmd, len(reasons) > 0); err != nil {
|
||||
return nil, args, err
|
||||
} else if ok {
|
||||
reasons = []string{fileReason}
|
||||
}
|
||||
|
||||
// Desire-path: "bd done <id> <message>" treats last positional arg as reason
|
||||
// when no reason flag was explicitly provided (hq-pe8ce)
|
||||
if len(reasons) == 0 && cmd.CalledAs() == "done" && len(args) >= 2 {
|
||||
reasons = []string{args[len(args)-1]}
|
||||
args = args[:len(args)-1]
|
||||
}
|
||||
|
||||
if len(reasons) == 0 {
|
||||
reasons = []string{"Closed"}
|
||||
}
|
||||
if len(reasons) > 1 && len(reasons) != len(args) {
|
||||
return nil, args, fmt.Errorf("got %d close reasons for %d issue IDs; provide exactly one shared reason or one reason per issue", len(reasons), len(args))
|
||||
}
|
||||
return reasons, args, nil
|
||||
}
|
||||
|
||||
func collectCloseReasonFlags(cmd *cobra.Command) ([]string, error) {
|
||||
if flag := cmd.Flags().Lookup("reason"); flag != nil {
|
||||
if v, ok := flag.Value.(interface{ Values() []string }); ok {
|
||||
if reasons := nonEmptyCloseReasons(v.Values()); len(reasons) > 0 {
|
||||
return reasons, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range []string{"resolution", "message", "comment"} {
|
||||
reason, err := cmd.Flags().GetString(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reason != "" {
|
||||
return []string{reason}, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func nonEmptyCloseReasons(reasons []string) []string {
|
||||
out := make([]string, 0, len(reasons))
|
||||
for _, reason := range reasons {
|
||||
if reason != "" {
|
||||
out = append(out, reason)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func reasonForCloseIndex(reasons []string, i int) string {
|
||||
if len(reasons) == 1 {
|
||||
return reasons[0]
|
||||
}
|
||||
return reasons[i]
|
||||
}
|
||||
|
||||
func validateCloseReasons(reasons []string) error {
|
||||
closeValidation := config.GetString("validation.on-close")
|
||||
if closeValidation != "error" && closeValidation != "warn" {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, reason := range reasons {
|
||||
if err := validation.ValidateCloseReason(reason); err != nil {
|
||||
if closeValidation == "error" {
|
||||
return err
|
||||
}
|
||||
// warn mode: print warning but proceed
|
||||
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isMachineCheckableGate returns true if the issue is a gate with a machine-checkable await type.
|
||||
func isMachineCheckableGate(issue *types.Issue) bool {
|
||||
if issue == nil || issue.IssueType != "gate" {
|
||||
|
|
@ -471,11 +567,11 @@ func shouldAutoCloseCompletedRoot(root *types.Issue) bool {
|
|||
// Returns an error on conflict with an existing reason, file read failure, or empty content.
|
||||
// Mirrors the --body-file pattern from `bd create` so agents can pass structured close
|
||||
// templates without shell-escaping hell.
|
||||
func resolveReasonFile(cmd *cobra.Command, existingReason string) (string, bool, error) {
|
||||
func resolveReasonFile(cmd *cobra.Command, hasExistingReason bool) (string, bool, error) {
|
||||
if !cmd.Flags().Changed("reason-file") {
|
||||
return "", false, nil
|
||||
}
|
||||
if existingReason != "" {
|
||||
if hasExistingReason {
|
||||
return "", false, fmt.Errorf("cannot specify both --reason-file and --reason/--resolution/--message/--comment")
|
||||
}
|
||||
path, _ := cmd.Flags().GetString("reason-file")
|
||||
|
|
@ -540,7 +636,10 @@ func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, id
|
|||
cleanup()
|
||||
return nil, func() {}, fmt.Errorf("resolving ID %s: %w", id, err)
|
||||
}
|
||||
if r, err := resolveViaPrefixRouting(ctx, id); err == nil {
|
||||
// Write-intent: a prefix-routed target opens writable so the close
|
||||
// commits on the target head (#4141). Contributor auto-routing below
|
||||
// stays read-only: it hydrates foreign projects that must not be mutated.
|
||||
if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true); err == nil {
|
||||
results = append(results, r)
|
||||
continue
|
||||
}
|
||||
|
|
@ -558,12 +657,13 @@ func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, id
|
|||
return results, cleanup, nil
|
||||
}
|
||||
|
||||
// countEpicOpenChildren returns the number of open (non-closed) children for an epic.
|
||||
// countOpenChildren returns the number of open (non-closed) parent-child
|
||||
// dependents for any issue (epics, tasks, etc.).
|
||||
// Uses GetDependentsWithMetadata to find parent-child relationships.
|
||||
// Takes an explicit store so callers can route to the store actually holding the epic
|
||||
// (relevant for contributor auto-routing where the epic lives in the planning repo).
|
||||
func countEpicOpenChildren(ctx context.Context, s storage.DoltStorage, epicID string) int {
|
||||
dependents, err := s.GetDependentsWithMetadata(ctx, epicID)
|
||||
// Takes an explicit store so callers can route to the store actually holding the issue
|
||||
// (relevant for contributor auto-routing where the issue lives in the planning repo).
|
||||
func countOpenChildren(ctx context.Context, s storage.DoltStorage, issueID string) int {
|
||||
dependents, err := s.GetDependentsWithMetadata(ctx, issueID)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
|
|
|||
|
|
@ -178,6 +178,22 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
t.Run("close_multiple_ids_with_per_id_reasons", func(t *testing.T) {
|
||||
issue1 := bdCreate(t, bd, dir, "Multi close reason 1", "--type", "task")
|
||||
issue2 := bdCreate(t, bd, dir, "Multi close reason 2", "--type", "task")
|
||||
|
||||
bdClose(t, bd, dir, issue1.ID, "--reason", "fixed A", issue2.ID, "--reason", "fixed B")
|
||||
|
||||
got1 := bdShow(t, bd, dir, issue1.ID)
|
||||
got2 := bdShow(t, bd, dir, issue2.ID)
|
||||
if got1.CloseReason != "fixed A" {
|
||||
t.Errorf("issue1 close_reason = %q, want %q", got1.CloseReason, "fixed A")
|
||||
}
|
||||
if got2.CloseReason != "fixed B" {
|
||||
t.Errorf("issue2 close_reason = %q, want %q", got2.CloseReason, "fixed B")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_already_closed", func(t *testing.T) {
|
||||
issue := bdCreate(t, bd, dir, "Double close", "--type", "task")
|
||||
bdClose(t, bd, dir, issue.ID)
|
||||
|
|
@ -239,6 +255,66 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
// be-035: silent-data-loss bug. Without an authority check, actor A could
|
||||
// close a bead claimed by actor B and bd would print "✓ Closed" with no
|
||||
// indication the actor mismatched. The fix refuses the close (non-zero
|
||||
// exit, stderr message) unless --force is set.
|
||||
t.Run("close_assignee_mismatch_refuses_without_force", func(t *testing.T) {
|
||||
issue := bdCreate(t, bd, dir, "Mismatch guard", "--type", "task")
|
||||
// Bob claims the bead.
|
||||
bdUpdate(t, bd, dir, issue.ID, "--actor", "bob", "--claim")
|
||||
|
||||
// Alice tries to close it — must fail loudly, not silently succeed.
|
||||
out := bdCloseFail(t, bd, dir, issue.ID, "--actor", "alice")
|
||||
if !strings.Contains(out, "assignee is") {
|
||||
t.Errorf("expected stderr to mention assignee mismatch, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "bob") || !strings.Contains(out, "alice") {
|
||||
t.Errorf("expected stderr to name both assignee and actor, got: %s", out)
|
||||
}
|
||||
|
||||
// Bead must remain open.
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.Status == types.StatusClosed {
|
||||
t.Error("expected bead to remain open after refused close")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_assignee_mismatch_with_force", func(t *testing.T) {
|
||||
issue := bdCreate(t, bd, dir, "Mismatch force", "--type", "task")
|
||||
bdUpdate(t, bd, dir, issue.ID, "--actor", "bob", "--claim")
|
||||
|
||||
// --force overrides the authority check.
|
||||
bdClose(t, bd, dir, issue.ID, "--actor", "alice", "--force")
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("expected closed with --force despite mismatch, got %s", got.Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_same_actor_succeeds", func(t *testing.T) {
|
||||
issue := bdCreate(t, bd, dir, "Same actor", "--type", "task")
|
||||
bdUpdate(t, bd, dir, issue.ID, "--actor", "alice", "--claim")
|
||||
|
||||
// Same actor — no authority issue.
|
||||
bdClose(t, bd, dir, issue.ID, "--actor", "alice")
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("expected closed when actor matches assignee, got %s", got.Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_unassigned_bead_succeeds", func(t *testing.T) {
|
||||
// Lots of bd's normal flow involves closing unclaimed beads;
|
||||
// the authority check must not break this.
|
||||
issue := bdCreate(t, bd, dir, "Unassigned", "--type", "task")
|
||||
bdClose(t, bd, dir, issue.ID, "--actor", "carol")
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("expected unassigned bead to close, got %s", got.Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_epic_open_children_refuses", func(t *testing.T) {
|
||||
epic := bdCreate(t, bd, dir, "Epic guard", "--type", "epic")
|
||||
child := bdCreate(t, bd, dir, "Epic child", "--type", "task")
|
||||
|
|
@ -256,11 +332,33 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
child := bdCreate(t, bd, dir, "Epic child force", "--type", "task")
|
||||
bdDepAdd(t, bd, dir, child.ID, epic.ID, "--type", "parent-child")
|
||||
|
||||
bdClose(t, bd, dir, epic.ID, "--force")
|
||||
cmd := exec.Command(bd, "close", epic.ID, "--force")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --force failed: %v\n%s", err, out)
|
||||
}
|
||||
got := bdShow(t, bd, dir, epic.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("expected epic closed with --force, got %s", got.Status)
|
||||
}
|
||||
if !strings.Contains(string(out), "warning:") || !strings.Contains(string(out), "open child") {
|
||||
t.Errorf("expected warning about open children on --force, got: %s", out)
|
||||
}
|
||||
_ = child
|
||||
})
|
||||
|
||||
t.Run("close_non_epic_parent_open_children_refuses", func(t *testing.T) {
|
||||
parent := bdCreate(t, bd, dir, "Task parent guard", "--type", "task")
|
||||
child := bdCreate(t, bd, dir, "Task child guard", "--type", "task")
|
||||
bdDepAdd(t, bd, dir, child.ID, parent.ID, "--type", "parent-child")
|
||||
|
||||
bdCloseFail(t, bd, dir, parent.ID)
|
||||
got := bdShow(t, bd, dir, parent.ID)
|
||||
if got.Status == types.StatusClosed {
|
||||
t.Error("expected non-epic parent with open children to remain open without --force")
|
||||
}
|
||||
_ = child
|
||||
})
|
||||
|
||||
|
|
@ -314,11 +412,11 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
cmd := exec.Command(bd, "close", blocker.ID, "--suggest-next", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --suggest-next --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd close --suggest-next --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := string(out)
|
||||
s := stdout.String()
|
||||
if !strings.Contains(s, "unblocked") {
|
||||
t.Logf("JSON output did not contain 'unblocked' key: %s", s)
|
||||
}
|
||||
|
|
@ -354,11 +452,11 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
cmd := exec.Command(bd, "close", toClose.ID, "--claim-next", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --claim-next --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd close --claim-next --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := string(out)
|
||||
s := stdout.String()
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
start = strings.Index(s, "[")
|
||||
|
|
@ -386,9 +484,9 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
env := bdEnv(dir)
|
||||
env = append(env, "CLAUDE_SESSION_ID=env-sess")
|
||||
cmd.Env = env
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close with env session failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd close with env session failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
session := querySessionSQL(t, beadsDir, issue.ID)
|
||||
if session != "env-sess" {
|
||||
|
|
@ -403,11 +501,11 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
cmd := exec.Command(bd, "close", issue.ID, "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd close --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := string(out)
|
||||
s := stdout.String()
|
||||
start := strings.Index(s, "[")
|
||||
if start < 0 {
|
||||
start = strings.Index(s, "{")
|
||||
|
|
@ -425,9 +523,9 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
cmd := exec.Command(bd, "done", issue.ID)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd done failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd done failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
|
|
@ -440,9 +538,9 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
cmd := exec.Command(bd, "done", issue.ID, "the reason")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd done with reason failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd done with reason failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
got := bdShow(t, bd, dir, issue.ID)
|
||||
if got.CloseReason != "the reason" {
|
||||
|
|
@ -491,6 +589,39 @@ func TestEmbeddedClose(t *testing.T) {
|
|||
bdCloseFail(t, bd, dir, issue1.ID, issue2.ID, "--continue")
|
||||
})
|
||||
|
||||
// Reproduces gastownhall/beads#3769: --continue auto-advances + claims
|
||||
// the next molecule step inside AdvanceToNextStep, but only --claim-next
|
||||
// was calling SetLastTouchedID. Without the fix, .beads/last-touched
|
||||
// stayed pointed at the just-closed step.
|
||||
t.Run("close_continue_updates_last_touched", func(t *testing.T) {
|
||||
// Template-shaped epic so AdvanceToNextStep recognizes it as a molecule.
|
||||
root := bdCreate(t, bd, dir, "Continue last-touched root", "--type", "epic", "--labels", "template")
|
||||
step1 := bdCreate(t, bd, dir, "Step one", "--type", "task", "--parent", root.ID)
|
||||
step2 := bdCreate(t, bd, dir, "Step two", "--type", "task", "--parent", root.ID)
|
||||
// step2 blocks on step1, so step1 closes first and step2 becomes ready.
|
||||
bdDepAdd(t, bd, dir, step2.ID, step1.ID)
|
||||
|
||||
// Claim step1 first (mirrors the natural workflow); this seeds last-touched
|
||||
// with step1's ID via the update --claim path, isolating the close-flow's
|
||||
// responsibility for advancing it.
|
||||
_, err := bdRunWithFlockRetry(t, bd, dir, "update", step1.ID, "--claim")
|
||||
if err != nil {
|
||||
t.Fatalf("seed claim failed: %v", err)
|
||||
}
|
||||
|
||||
_ = bdClose(t, bd, dir, step1.ID, "--reason", "test", "--continue")
|
||||
|
||||
got, err := os.ReadFile(filepath.Join(beadsDir, "last-touched"))
|
||||
if err != nil {
|
||||
t.Fatalf("read .beads/last-touched: %v", err)
|
||||
}
|
||||
gotID := strings.TrimSpace(string(got))
|
||||
if gotID != step2.ID {
|
||||
t.Errorf(".beads/last-touched = %q after `bd close %s --continue`, want %q (the auto-advanced step)",
|
||||
gotID, step1.ID, step2.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_suggest_next_multiple_ids_fails", func(t *testing.T) {
|
||||
issue1 := bdCreate(t, bd, dir, "Suggest multi 1", "--type", "task")
|
||||
issue2 := bdCreate(t, bd, dir, "Suggest multi 2", "--type", "task")
|
||||
|
|
@ -534,10 +665,7 @@ func TestEmbeddedCloseConcurrent(t *testing.T) {
|
|||
for i := 0; i < issuesPerWorker; i++ {
|
||||
// Create an issue.
|
||||
title := fmt.Sprintf("w%d-close-%d", worker, i)
|
||||
cmd := exec.Command(bd, "create", "--silent", title)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
out, err := bdRunWithFlockRetry(t, bd, dir, "create", "--silent", title)
|
||||
if err != nil {
|
||||
r.err = fmt.Errorf("create %d: %v\n%s", i, err, out)
|
||||
results[worker] = r
|
||||
|
|
@ -567,13 +695,13 @@ func TestEmbeddedCloseConcurrent(t *testing.T) {
|
|||
listCmd := exec.Command(bd, "list", "--json", "--limit", "0", "--all")
|
||||
listCmd.Dir = dir
|
||||
listCmd.Env = bdEnv(dir)
|
||||
listOut, err := listCmd.CombinedOutput()
|
||||
listStdout, listStderr, err := runCommandBuffers(t, listCmd)
|
||||
if err != nil {
|
||||
r.err = fmt.Errorf("list after close %d: %v\n%s", i, err, listOut)
|
||||
r.err = fmt.Errorf("list after close %d: %v\nstdout:\n%s\nstderr:\n%s", i, err, listStdout.String(), listStderr.String())
|
||||
results[worker] = r
|
||||
return
|
||||
}
|
||||
s := string(listOut)
|
||||
s := listStdout.String()
|
||||
start := strings.Index(s, "[")
|
||||
if start < 0 {
|
||||
r.listCounts = append(r.listCounts, 0)
|
||||
|
|
@ -581,7 +709,7 @@ func TestEmbeddedCloseConcurrent(t *testing.T) {
|
|||
}
|
||||
var issues []json.RawMessage
|
||||
if jsonErr := json.Unmarshal([]byte(s[start:]), &issues); jsonErr != nil {
|
||||
r.err = fmt.Errorf("list parse %d: %v\nraw: %s", i, jsonErr, s)
|
||||
r.err = fmt.Errorf("list parse %d: %v\nstdout:\n%s\nstderr:\n%s", i, jsonErr, s, listStderr.String())
|
||||
results[worker] = r
|
||||
return
|
||||
}
|
||||
|
|
|
|||
791
cmd/bd/close_proxied_integration_test.go
Normal file
791
cmd/bd/close_proxied_integration_test.go
Normal file
|
|
@ -0,0 +1,791 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func bdProxiedClose(t *testing.T, bd, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"close"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
return stdout
|
||||
}
|
||||
|
||||
func bdProxiedCloseFail(t *testing.T, bd, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"close"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err == nil {
|
||||
t.Fatalf("expected bd close %s to fail, got:\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), stdout, stderr)
|
||||
}
|
||||
return stdout + stderr
|
||||
}
|
||||
|
||||
func bdProxiedCloseJSON(t *testing.T, bd, dir string, args ...string) []*types.Issue {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"close", "--json"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --json %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
start := strings.Index(stdout, "[")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON array in close output:\n%s", stdout)
|
||||
}
|
||||
var issues []*types.Issue
|
||||
if err := json.Unmarshal([]byte(stdout[start:]), &issues); err != nil {
|
||||
t.Fatalf("parse close JSON: %v\nraw: %s", err, stdout[start:])
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func bdProxiedCloseJSONEnvelope(t *testing.T, bd, dir string, args ...string) map[string]json.RawMessage {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"close", "--json"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close --json %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
start := strings.Index(stdout, "{")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON object in close output:\n%s", stdout)
|
||||
}
|
||||
var env map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(stdout[start:]), &env); err != nil {
|
||||
t.Fatalf("parse close JSON envelope: %v\nraw: %s", err, stdout[start:])
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func readClosedBySession(t *testing.T, db *sql.DB, id string) string {
|
||||
t.Helper()
|
||||
var got sql.NullString
|
||||
err := db.QueryRowContext(context.Background(),
|
||||
"SELECT closed_by_session FROM issues WHERE id = ?", id).Scan(&got)
|
||||
if err == sql.ErrNoRows {
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT closed_by_session FROM wisps WHERE id = ?", id).Scan(&got); err != nil {
|
||||
t.Fatalf("read closed_by_session for %s: %v", id, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("read closed_by_session for %s: %v", id, err)
|
||||
}
|
||||
if !got.Valid {
|
||||
return ""
|
||||
}
|
||||
return got.String
|
||||
}
|
||||
|
||||
func readCloseReason(t *testing.T, db *sql.DB, id string) string {
|
||||
t.Helper()
|
||||
var got sql.NullString
|
||||
err := db.QueryRowContext(context.Background(),
|
||||
"SELECT close_reason FROM issues WHERE id = ?", id).Scan(&got)
|
||||
if err == sql.ErrNoRows {
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT close_reason FROM wisps WHERE id = ?", id).Scan(&got); err != nil {
|
||||
t.Fatalf("read close_reason for %s: %v", id, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("read close_reason for %s: %v", id, err)
|
||||
}
|
||||
if !got.Valid {
|
||||
return ""
|
||||
}
|
||||
return got.String
|
||||
}
|
||||
|
||||
func readStatus(t *testing.T, db *sql.DB, id string) types.Status {
|
||||
t.Helper()
|
||||
var got string
|
||||
err := db.QueryRowContext(context.Background(),
|
||||
"SELECT status FROM issues WHERE id = ?", id).Scan(&got)
|
||||
if err == sql.ErrNoRows {
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT status FROM wisps WHERE id = ?", id).Scan(&got); err != nil {
|
||||
t.Fatalf("read status for %s: %v", id, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("read status for %s: %v", id, err)
|
||||
}
|
||||
return types.Status(got)
|
||||
}
|
||||
|
||||
func readAssignee(t *testing.T, db *sql.DB, id string) string {
|
||||
t.Helper()
|
||||
var got sql.NullString
|
||||
err := db.QueryRowContext(context.Background(),
|
||||
"SELECT assignee FROM issues WHERE id = ?", id).Scan(&got)
|
||||
if err == sql.ErrNoRows {
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT assignee FROM wisps WHERE id = ?", id).Scan(&got); err != nil {
|
||||
t.Fatalf("read assignee for %s: %v", id, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("read assignee for %s: %v", id, err)
|
||||
}
|
||||
if !got.Valid {
|
||||
return ""
|
||||
}
|
||||
return got.String
|
||||
}
|
||||
|
||||
func readDoltHead(t *testing.T, db *sql.DB) string {
|
||||
t.Helper()
|
||||
var h string
|
||||
if err := db.QueryRowContext(context.Background(), "SELECT HASHOF('HEAD')").Scan(&h); err != nil {
|
||||
t.Fatalf("read HEAD: %v", err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func readDoltLogTopMessage(t *testing.T, db *sql.DB) string {
|
||||
t.Helper()
|
||||
var msg string
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT message FROM dolt_log ORDER BY date DESC LIMIT 1").Scan(&msg); err != nil {
|
||||
t.Fatalf("read latest dolt_log message: %v", err)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func readDoltLogCountSince(t *testing.T, db *sql.DB, sinceHash string) int {
|
||||
t.Helper()
|
||||
rows, err := db.QueryContext(context.Background(),
|
||||
"SELECT commit_hash FROM dolt_log ORDER BY date DESC")
|
||||
if err != nil {
|
||||
t.Fatalf("read dolt_log: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
n := 0
|
||||
for rows.Next() {
|
||||
var h string
|
||||
if err := rows.Scan(&h); err != nil {
|
||||
t.Fatalf("scan dolt_log: %v", err)
|
||||
}
|
||||
if h == sinceHash {
|
||||
return n
|
||||
}
|
||||
n++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("iter dolt_log: %v", err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestProxiedServerClose(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("basic_close", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cb")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Close me")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID)
|
||||
got := bdProxiedShow(t, bd, p.dir, issue.ID)
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("status: got %q, want closed", got.Status)
|
||||
}
|
||||
if got.ClosedAt == nil {
|
||||
t.Error("closed_at should be set")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_default_reason", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cdr")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Default reason")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "Closed" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "Closed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_reason", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwr")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Reason test")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--reason", "done")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "done" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "done")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_reason_short", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwrs")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Short reason")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "-r", "fixed")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "fixed" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "fixed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_message_alias", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwma")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Message alias")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "-m", "via message")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "via message" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "via message")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_resolution_alias", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwra")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Resolution alias")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--resolution", "wontfix")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "wontfix" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "wontfix")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_comment_alias", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwca")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Comment alias")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--comment", "duplicate")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "duplicate" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "duplicate")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_multiple_ids", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cmi")
|
||||
a := bdProxiedCreate(t, bd, p.dir, "Multi A")
|
||||
b := bdProxiedCreate(t, bd, p.dir, "Multi B")
|
||||
bdProxiedClose(t, bd, p.dir, a.ID, b.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, a.ID); got != types.StatusClosed {
|
||||
t.Errorf("a status: got %q, want closed", got)
|
||||
}
|
||||
if got := readStatus(t, db, b.ID); got != types.StatusClosed {
|
||||
t.Errorf("b status: got %q, want closed", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_multiple_ids_with_per_id_reasons", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cmpr")
|
||||
a := bdProxiedCreate(t, bd, p.dir, "Multi reason A")
|
||||
b := bdProxiedCreate(t, bd, p.dir, "Multi reason B")
|
||||
bdProxiedClose(t, bd, p.dir, a.ID, "--reason", "fixed A", b.ID, "--reason", "fixed B")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, a.ID); got != "fixed A" {
|
||||
t.Errorf("a reason: got %q, want %q", got, "fixed A")
|
||||
}
|
||||
if got := readCloseReason(t, db, b.ID); got != "fixed B" {
|
||||
t.Errorf("b reason: got %q, want %q", got, "fixed B")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_already_closed", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cac")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Double close")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--reason", "first")
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "close", issue.ID, "--reason", "second")
|
||||
_ = stdout
|
||||
_ = stderr
|
||||
_ = err
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "first" {
|
||||
t.Errorf("re-close must not overwrite reason: got %q, want %q", got, "first")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_nonexistent_id", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cni")
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, "cni-does-not-exist")
|
||||
if !strings.Contains(out, "not found") {
|
||||
t.Errorf("expected 'not found' error, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_blocked_refuses_without_force", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cbr")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker")
|
||||
blocked := bdProxiedCreate(t, bd, p.dir, "Blocked", "--deps", "depends-on:"+blocker.ID)
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, blocked.ID)
|
||||
if !strings.Contains(out, "blocked by") {
|
||||
t.Errorf("expected blocker error, got: %s", out)
|
||||
}
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, blocked.ID); got == types.StatusClosed {
|
||||
t.Error("blocked issue should remain open without --force")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_blocked_with_force", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cbf")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker force")
|
||||
blocked := bdProxiedCreate(t, bd, p.dir, "Blocked force", "--deps", "depends-on:"+blocker.ID)
|
||||
bdProxiedClose(t, bd, p.dir, blocked.ID, "--force")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, blocked.ID); got != types.StatusClosed {
|
||||
t.Errorf("status with --force: got %q, want closed", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_pinned_refuses_without_force", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cpr")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Pinned")
|
||||
bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "-s", "pinned")
|
||||
bdProxiedCloseFail(t, bd, p.dir, issue.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, issue.ID); got == types.StatusClosed {
|
||||
t.Error("pinned issue should remain pinned without --force")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_pinned_with_force", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cpf")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Pinned force")
|
||||
bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "-s", "pinned")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--force")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, issue.ID); got != types.StatusClosed {
|
||||
t.Errorf("status: got %q, want closed", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_epic_open_children_refuses", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ceor")
|
||||
epic := bdProxiedCreate(t, bd, p.dir, "Epic", "-t", "epic")
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Child", "--parent", epic.ID)
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, epic.ID)
|
||||
if !strings.Contains(out, "open child") {
|
||||
t.Errorf("expected 'open child' error, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_epic_open_children_force", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ceof")
|
||||
epic := bdProxiedCreate(t, bd, p.dir, "Epic force", "-t", "epic")
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Child force", "--parent", epic.ID)
|
||||
bdProxiedClose(t, bd, p.dir, epic.ID, "--force")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, epic.ID); got != types.StatusClosed {
|
||||
t.Errorf("status: got %q, want closed", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_last_child_keeps_regular_epic_open", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "clce")
|
||||
epic := bdProxiedCreate(t, bd, p.dir, "Regular epic", "-t", "epic")
|
||||
child := bdProxiedCreate(t, bd, p.dir, "Last child", "--parent", epic.ID)
|
||||
bdProxiedClose(t, bd, p.dir, child.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, epic.ID); got != types.StatusOpen {
|
||||
t.Errorf("regular epic should stay open after last child closes, got %q", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_unblocks_dependent", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cud")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Unblock blocker")
|
||||
blocked := bdProxiedCreate(t, bd, p.dir, "Unblock blocked", "--deps", "depends-on:"+blocker.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if !readIsBlocked(t, db, blocked.ID) {
|
||||
t.Fatal("dependent should be blocked before blocker closes")
|
||||
}
|
||||
bdProxiedClose(t, bd, p.dir, blocker.ID)
|
||||
if readIsBlocked(t, db, blocked.ID) {
|
||||
t.Error("dependent should be unblocked after blocker closes")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_suggest_next", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "csn")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Suggest blocker")
|
||||
blocked := bdProxiedCreate(t, bd, p.dir, "Suggest blocked", "--deps", "depends-on:"+blocker.ID)
|
||||
out := bdProxiedClose(t, bd, p.dir, blocker.ID, "--suggest-next")
|
||||
if !strings.Contains(out, blocked.ID) {
|
||||
t.Errorf("suggest-next output missing unblocked id %s:\n%s", blocked.ID, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_suggest_next_json", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "csnj")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Suggest JSON blocker")
|
||||
blocked := bdProxiedCreate(t, bd, p.dir, "Suggest JSON blocked", "--deps", "depends-on:"+blocker.ID)
|
||||
env := bdProxiedCloseJSONEnvelope(t, bd, p.dir, blocker.ID, "--suggest-next")
|
||||
raw, ok := env["unblocked"]
|
||||
if !ok {
|
||||
t.Fatalf("envelope missing 'unblocked' key: %v", env)
|
||||
}
|
||||
var unblocked []*types.Issue
|
||||
if err := json.Unmarshal(raw, &unblocked); err != nil {
|
||||
t.Fatalf("parse unblocked: %v\n%s", err, string(raw))
|
||||
}
|
||||
if len(unblocked) != 1 || unblocked[0].ID != blocked.ID {
|
||||
t.Errorf("unblocked: got %+v, want [%s]", unblocked, blocked.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_claim_next", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ccn")
|
||||
toClose := bdProxiedCreate(t, bd, p.dir, "Claim next close")
|
||||
nextIssue := bdProxiedCreate(t, bd, p.dir, "Claim next target")
|
||||
bdProxiedClose(t, bd, p.dir, toClose.ID, "--claim-next")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, nextIssue.ID); got != types.StatusInProgress {
|
||||
t.Errorf("next issue status: got %q, want in_progress", got)
|
||||
}
|
||||
if got := readAssignee(t, db, nextIssue.ID); got == "" {
|
||||
t.Error("next issue assignee should be set after --claim-next")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_claim_next_no_ready", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ccnr")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Only issue")
|
||||
out := bdProxiedClose(t, bd, p.dir, issue.ID, "--claim-next")
|
||||
if !strings.Contains(out, "No ready issues") {
|
||||
t.Errorf("expected 'No ready issues', got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_claim_next_json", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ccnj")
|
||||
toClose := bdProxiedCreate(t, bd, p.dir, "Claim JSON close")
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Claim JSON target")
|
||||
env := bdProxiedCloseJSONEnvelope(t, bd, p.dir, toClose.ID, "--claim-next")
|
||||
if _, ok := env["closed"]; !ok {
|
||||
t.Errorf("envelope missing 'closed' key: %v", env)
|
||||
}
|
||||
if _, ok := env["claimed"]; !ok {
|
||||
t.Errorf("envelope missing 'claimed' key: %v", env)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_with_session", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cws")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Session flag")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID, "--session", "sess-456")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readClosedBySession(t, db, issue.ID); got != "sess-456" {
|
||||
t.Errorf("closed_by_session: got %q, want %q", got, "sess-456")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_session_from_env", func(t *testing.T) {
|
||||
t.Setenv("CLAUDE_SESSION_ID", "sess-env")
|
||||
p := bdProxiedInit(t, bd, "cse")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Session env")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readClosedBySession(t, db, issue.ID); got != "sess-env" {
|
||||
t.Errorf("closed_by_session: got %q, want %q", got, "sess-env")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_json_output", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cjo")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "JSON close")
|
||||
issues := bdProxiedCloseJSON(t, bd, p.dir, issue.ID)
|
||||
if len(issues) != 1 || issues[0].ID != issue.ID {
|
||||
t.Errorf("close JSON: got %+v, want [%s]", issues, issue.ID)
|
||||
}
|
||||
if issues[0].Status != types.StatusClosed {
|
||||
t.Errorf("returned issue status: got %q, want closed", issues[0].Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("done_alias", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "da")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Done alias")
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "done", issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("bd done failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
|
||||
}
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, issue.ID); got != types.StatusClosed {
|
||||
t.Errorf("status via done alias: got %q, want closed", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("done_positional_reason", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "dpr")
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Done reason")
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "done", issue.ID, "the reason")
|
||||
if err != nil {
|
||||
t.Fatalf("bd done with reason failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
|
||||
}
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readCloseReason(t, db, issue.ID); got != "the reason" {
|
||||
t.Errorf("close_reason: got %q, want %q", got, "the reason")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_continue_multiple_ids_fails", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ccmi")
|
||||
a := bdProxiedCreate(t, bd, p.dir, "Continue multi A")
|
||||
b := bdProxiedCreate(t, bd, p.dir, "Continue multi B")
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, a.ID, b.ID, "--continue")
|
||||
if !strings.Contains(out, "single issue") {
|
||||
t.Errorf("expected single-issue error, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_suggest_next_multiple_ids_fails", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "csmi")
|
||||
a := bdProxiedCreate(t, bd, p.dir, "Suggest multi A")
|
||||
b := bdProxiedCreate(t, bd, p.dir, "Suggest multi B")
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, a.ID, b.ID, "--suggest-next")
|
||||
if !strings.Contains(out, "single issue") {
|
||||
t.Errorf("expected single-issue error, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("single_transaction_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "stdc")
|
||||
a := bdProxiedCreate(t, bd, p.dir, "Tx A")
|
||||
b := bdProxiedCreate(t, bd, p.dir, "Tx B")
|
||||
c := bdProxiedCreate(t, bd, p.dir, "Tx C")
|
||||
db := openProxiedDB(t, p)
|
||||
before := readDoltHead(t, db)
|
||||
bdProxiedClose(t, bd, p.dir, a.ID, b.ID, c.ID)
|
||||
count := readDoltLogCountSince(t, db, before)
|
||||
if count != 1 {
|
||||
t.Errorf("expected exactly 1 new dolt commit for batch close, got %d", count)
|
||||
}
|
||||
msg := readDoltLogTopMessage(t, db)
|
||||
for _, id := range []string{a.ID, b.ID, c.ID} {
|
||||
if !strings.Contains(msg, id) {
|
||||
t.Errorf("dolt commit message %q should contain id %s", msg, id)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(msg, "bd: close ") {
|
||||
t.Errorf("dolt commit message should begin with 'bd: close ', got: %q", msg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no_ids_errors", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "nie")
|
||||
out := bdProxiedCloseFail(t, bd, p.dir)
|
||||
if !strings.Contains(out, "no issue ID provided") {
|
||||
t.Errorf("expected 'no issue ID provided', got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("last_touched_not_supported", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "ltns")
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Recent create")
|
||||
out := bdProxiedCloseFail(t, bd, p.dir)
|
||||
if !strings.Contains(out, "no issue ID provided") {
|
||||
t.Errorf("proxied mode must not fall back to last-touched; got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_wisp_issue", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwi")
|
||||
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp close", "--ephemeral")
|
||||
bdProxiedClose(t, bd, p.dir, wisp.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
var status string
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT status FROM wisps WHERE id = ?", wisp.ID).Scan(&status); err != nil {
|
||||
t.Fatalf("read wisp status: %v", err)
|
||||
}
|
||||
if types.Status(status) != types.StatusClosed {
|
||||
t.Errorf("wisp status: got %q, want closed", status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_wisp_epic_open_children", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cweoc")
|
||||
wispEpic := bdProxiedCreate(t, bd, p.dir, "Wisp epic", "-t", "epic", "--ephemeral")
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Wisp child", "--ephemeral", "--parent", wispEpic.ID)
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, wispEpic.ID)
|
||||
if !strings.Contains(out, "open child") {
|
||||
t.Errorf("expected 'open child' error for wisp epic, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close_wisp_blocked_refuses", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cwbr")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker for wisp")
|
||||
wisp := bdProxiedCreate(t, bd, p.dir, "Blocked wisp", "--ephemeral", "--deps", "depends-on:"+blocker.ID)
|
||||
out := bdProxiedCloseFail(t, bd, p.dir, wisp.ID)
|
||||
if !strings.Contains(out, "blocked by") {
|
||||
t.Errorf("expected wisp blocker error, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("continue_advances_to_next_ready_step", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cantrs")
|
||||
root := bdProxiedCreate(t, bd, p.dir, "Molecule root", "-t", "epic", "--labels", "template")
|
||||
step1 := bdProxiedCreate(t, bd, p.dir, "Step 1", "--parent", root.ID)
|
||||
step2 := bdProxiedCreate(t, bd, p.dir, "Step 2", "--parent", root.ID, "--deps", "depends-on:"+step1.ID)
|
||||
_ = bdProxiedCreate(t, bd, p.dir, "Step 3", "--parent", root.ID, "--deps", "depends-on:"+step2.ID)
|
||||
bdProxiedClose(t, bd, p.dir, step1.ID, "--continue")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, step2.ID); got != types.StatusInProgress {
|
||||
t.Errorf("step2 status after --continue: got %q, want in_progress", got)
|
||||
}
|
||||
if readAssignee(t, db, step2.ID) == "" {
|
||||
t.Error("step2 assignee should be set after --continue auto-claim")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("continue_no_auto_does_not_claim", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "cnac")
|
||||
root := bdProxiedCreate(t, bd, p.dir, "Molecule root", "-t", "epic", "--labels", "template")
|
||||
step1 := bdProxiedCreate(t, bd, p.dir, "Step 1", "--parent", root.ID)
|
||||
step2 := bdProxiedCreate(t, bd, p.dir, "Step 2", "--parent", root.ID, "--deps", "depends-on:"+step1.ID)
|
||||
bdProxiedClose(t, bd, p.dir, step1.ID, "--continue", "--no-auto")
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, step2.ID); got != types.StatusOpen {
|
||||
t.Errorf("step2 status with --no-auto: got %q, want open", got)
|
||||
}
|
||||
if readAssignee(t, db, step2.ID) != "" {
|
||||
t.Error("step2 assignee should NOT be set with --no-auto")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("auto_close_completed_molecule", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "accm")
|
||||
root := bdProxiedCreate(t, bd, p.dir, "Molecule root", "-t", "epic", "--labels", "template")
|
||||
s1 := bdProxiedCreate(t, bd, p.dir, "Step 1", "--parent", root.ID)
|
||||
s2 := bdProxiedCreate(t, bd, p.dir, "Step 2", "--parent", root.ID)
|
||||
bdProxiedClose(t, bd, p.dir, s1.ID, s2.ID)
|
||||
db := openProxiedDB(t, p)
|
||||
if got := readStatus(t, db, root.ID); got != types.StatusClosed {
|
||||
t.Errorf("template-labeled molecule root should auto-close after all steps complete, got %q", got)
|
||||
}
|
||||
if got := readCloseReason(t, db, root.ID); got != "all steps complete" {
|
||||
t.Errorf("auto-close reason: got %q, want %q", got, "all steps complete")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("hooks_fire_on_close", func(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "on_close_marker")
|
||||
script := "#!/bin/sh\nprintf '%s\\n' \"$1\" > " + shellQuote(marker) + "\n"
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("hook script form is POSIX shell")
|
||||
}
|
||||
p := bdProxiedInitWithHooks(t, bd, "hfc", map[string]string{"on_close": script})
|
||||
issue := bdProxiedCreate(t, bd, p.dir, "Hook fire")
|
||||
bdProxiedClose(t, bd, p.dir, issue.ID)
|
||||
data, err := os.ReadFile(marker)
|
||||
if err != nil {
|
||||
t.Fatalf("hook marker not written: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(data), issue.ID) {
|
||||
t.Errorf("hook marker missing issue ID; got: %q", string(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func shellQuote(s string) string {
|
||||
return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
|
||||
}
|
||||
|
||||
func TestProxiedServerCloseConcurrent(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
p := bdProxiedInit(t, bd, "cxc")
|
||||
|
||||
const (
|
||||
numWorkers = 10
|
||||
issuesPerWorker = 5
|
||||
)
|
||||
|
||||
type ws struct {
|
||||
closed int
|
||||
errs []string
|
||||
}
|
||||
results := make([]ws, numWorkers)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numWorkers)
|
||||
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
w := w
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r := &results[w]
|
||||
for i := 0; i < issuesPerWorker; i++ {
|
||||
title := fmt.Sprintf("worker-%d-issue-%d", w, i)
|
||||
cmd := exec.Command(bd, "create", "--json", title)
|
||||
cmd.Dir = p.dir
|
||||
cmd.Env = bdProxiedEnv(p.dir)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
r.errs = append(r.errs, fmt.Sprintf("create %s: %v\n%s", title, err, stderr.String()))
|
||||
continue
|
||||
}
|
||||
out := stdout.Bytes()
|
||||
start := bytes.Index(out, []byte("{"))
|
||||
if start < 0 {
|
||||
r.errs = append(r.errs, "no JSON in create output")
|
||||
continue
|
||||
}
|
||||
var issue types.Issue
|
||||
if err := json.Unmarshal(out[start:], &issue); err != nil {
|
||||
r.errs = append(r.errs, fmt.Sprintf("parse create JSON: %v", err))
|
||||
continue
|
||||
}
|
||||
|
||||
closeCmd := exec.Command(bd, "close", issue.ID)
|
||||
closeCmd.Dir = p.dir
|
||||
closeCmd.Env = bdProxiedEnv(p.dir)
|
||||
var cstdout, cstderr bytes.Buffer
|
||||
closeCmd.Stdout = &cstdout
|
||||
closeCmd.Stderr = &cstderr
|
||||
if err := closeCmd.Run(); err != nil {
|
||||
r.errs = append(r.errs, fmt.Sprintf("close %s: %v\n%s", issue.ID, err, cstderr.String()))
|
||||
continue
|
||||
}
|
||||
r.closed++
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
totalClosed := 0
|
||||
for w, r := range results {
|
||||
totalClosed += r.closed
|
||||
for _, e := range r.errs {
|
||||
t.Errorf("worker %d: %s", w, e)
|
||||
}
|
||||
}
|
||||
want := numWorkers * issuesPerWorker
|
||||
if totalClosed != want {
|
||||
t.Errorf("closed count: got %d, want %d", totalClosed, want)
|
||||
}
|
||||
|
||||
db := openProxiedDB(t, p)
|
||||
var openCount int
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT COUNT(*) FROM issues WHERE status != 'closed'").Scan(&openCount); err != nil {
|
||||
t.Fatalf("query open count: %v", err)
|
||||
}
|
||||
if openCount != 0 {
|
||||
t.Errorf("open issues remain after concurrent close: %d", openCount)
|
||||
}
|
||||
}
|
||||
579
cmd/bd/close_proxied_server.go
Normal file
579
cmd/bd/close_proxied_server.go
Normal file
|
|
@ -0,0 +1,579 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/audit"
|
||||
"github.com/steveyegge/beads/internal/hooks"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
type closeProxiedInput struct {
|
||||
force bool
|
||||
continueOn bool
|
||||
noAuto bool
|
||||
suggestNext bool
|
||||
claimNext bool
|
||||
session string
|
||||
jsonOut bool
|
||||
}
|
||||
|
||||
type closeProxiedOutcome struct {
|
||||
id string
|
||||
before *types.Issue
|
||||
after *types.Issue
|
||||
closed bool
|
||||
}
|
||||
|
||||
func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
|
||||
if len(args) == 0 {
|
||||
FatalErrorRespectJSON("no issue ID provided")
|
||||
}
|
||||
|
||||
reasons, updatedArgs, err := resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
}
|
||||
args = updatedArgs
|
||||
if err := validateCloseReasons(reasons); err != nil {
|
||||
FatalErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
in := gatherCloseProxiedInput(cmd)
|
||||
|
||||
if in.continueOn && len(args) > 1 {
|
||||
FatalErrorRespectJSON("--continue only works when closing a single issue")
|
||||
}
|
||||
if in.suggestNext && len(args) > 1 {
|
||||
FatalErrorRespectJSON("--suggest-next only works when closing a single issue")
|
||||
}
|
||||
|
||||
if uowProvider == nil {
|
||||
FatalError("proxied-server UOW provider not initialized")
|
||||
}
|
||||
uw, err := uowProvider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("open unit of work: %v", err)
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
outcomes := make([]closeProxiedOutcome, 0, len(args))
|
||||
closedIssues := []*types.Issue{}
|
||||
for i, id := range args {
|
||||
reason := reasonForCloseIndex(reasons, i)
|
||||
outcome, ok := closeProxiedOne(ctx, uw, id, reason, in)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
outcomes = append(outcomes, outcome)
|
||||
if in.jsonOut {
|
||||
closedIssues = append(closedIssues, outcome.after)
|
||||
} else {
|
||||
fmt.Printf("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(outcome.after.ID, outcome.after.Title), reason)
|
||||
}
|
||||
}
|
||||
|
||||
var unblocked []*types.Issue
|
||||
if in.suggestNext && len(args) == 1 && len(outcomes) > 0 {
|
||||
unblocked = closeProxiedSuggestNext(ctx, uw, args[0])
|
||||
}
|
||||
|
||||
var continueResult *ContinueResult
|
||||
if in.continueOn && len(args) == 1 && len(outcomes) > 0 {
|
||||
continueResult = closeProxiedContinue(ctx, uw, args[0], !in.noAuto)
|
||||
}
|
||||
|
||||
var claimedNextIssue *types.Issue
|
||||
if in.claimNext && len(outcomes) > 0 && !in.continueOn {
|
||||
claimedNextIssue = closeProxiedClaimNext(ctx, uw, in.jsonOut)
|
||||
}
|
||||
|
||||
if len(outcomes) > 0 {
|
||||
msg := closeProxiedCommitMessage(outcomes, claimedNextIssue, continueResult)
|
||||
if err := uw.Commit(ctx, msg); err != nil && !isDoltNothingToCommit(err) {
|
||||
FatalErrorRespectJSON("commit close: %v", err)
|
||||
}
|
||||
for _, o := range outcomes {
|
||||
if !o.closed {
|
||||
continue
|
||||
}
|
||||
if err := fireProxiedCloseHooks(ctx, o.before, o.after); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: %s: %v\n", o.id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !in.jsonOut {
|
||||
if len(unblocked) > 0 {
|
||||
fmt.Printf("\nNewly unblocked:\n")
|
||||
for _, issue := range unblocked {
|
||||
fmt.Printf(" • %s (P%d)\n", formatFeedbackID(issue.ID, issue.Title), issue.Priority)
|
||||
}
|
||||
}
|
||||
if continueResult != nil {
|
||||
PrintContinueResult(continueResult)
|
||||
}
|
||||
if claimedNextIssue != nil {
|
||||
fmt.Printf("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(claimedNextIssue.ID, claimedNextIssue.Title), claimedNextIssue.Priority)
|
||||
}
|
||||
}
|
||||
|
||||
if in.jsonOut && len(closedIssues) > 0 {
|
||||
switch {
|
||||
case len(unblocked) > 0:
|
||||
_ = outputJSON(map[string]interface{}{"closed": closedIssues, "unblocked": unblocked})
|
||||
case continueResult != nil:
|
||||
_ = outputJSON(map[string]interface{}{"closed": closedIssues, "continue": continueResult})
|
||||
case claimedNextIssue != nil:
|
||||
_ = outputJSON(map[string]interface{}{"closed": closedIssues, "claimed": claimedNextIssue})
|
||||
default:
|
||||
_ = outputJSON(closedIssues)
|
||||
}
|
||||
}
|
||||
|
||||
if len(args) > 0 && len(outcomes) == 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func gatherCloseProxiedInput(cmd *cobra.Command) closeProxiedInput {
|
||||
in := closeProxiedInput{}
|
||||
in.force, _ = cmd.Flags().GetBool("force")
|
||||
in.continueOn, _ = cmd.Flags().GetBool("continue")
|
||||
in.noAuto, _ = cmd.Flags().GetBool("no-auto")
|
||||
in.suggestNext, _ = cmd.Flags().GetBool("suggest-next")
|
||||
in.claimNext, _ = cmd.Flags().GetBool("claim-next")
|
||||
in.session, _ = cmd.Flags().GetString("session")
|
||||
if in.session == "" {
|
||||
in.session = os.Getenv("CLAUDE_SESSION_ID")
|
||||
}
|
||||
in.jsonOut, _ = cmd.Flags().GetBool("json")
|
||||
return in
|
||||
}
|
||||
|
||||
func closeProxiedOne(ctx context.Context, uw uow.UnitOfWork, id, reason string, in closeProxiedInput) (closeProxiedOutcome, bool) {
|
||||
current, isWisp := proxiedResolveIssueOrWisp(ctx, uw, id)
|
||||
if current == nil {
|
||||
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
|
||||
if err := validateIssueClosable(id, current, actor, in.force); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
|
||||
if !in.force && current.IssueType == types.TypeEpic {
|
||||
var openChildren int
|
||||
var err error
|
||||
if isWisp {
|
||||
openChildren, err = uw.IssueUseCase().CountOpenWispChildren(ctx, id)
|
||||
} else {
|
||||
openChildren, err = uw.IssueUseCase().CountOpenChildren(ctx, id)
|
||||
}
|
||||
if err == nil && openChildren > 0 {
|
||||
fmt.Fprintf(os.Stderr, "cannot close epic %s: %d open child issue(s); close children first or use --force to override\n", id, openChildren)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
}
|
||||
|
||||
if !in.force {
|
||||
if err := checkGateSatisfaction(current); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cannot close %s: %s\n", id, err)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
}
|
||||
|
||||
if !in.force {
|
||||
var blocked bool
|
||||
var blockers []string
|
||||
var err error
|
||||
if isWisp {
|
||||
blocked, blockers, err = uw.DependencyUseCase().IsWispBlocked(ctx, id)
|
||||
} else {
|
||||
blocked, blockers, err = uw.DependencyUseCase().IsBlocked(ctx, id)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error checking blockers for %s: %v\n", id, err)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
if blocked && len(blockers) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "cannot close %s: blocked by open issues %v (use --force to override)\n", id, blockers)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
}
|
||||
|
||||
params := domain.CloseIssueParams{Reason: reason, Session: in.session}
|
||||
var (
|
||||
res domain.CloseIssueResult
|
||||
err error
|
||||
)
|
||||
if isWisp {
|
||||
res, err = uw.IssueUseCase().CloseWisp(ctx, id, params, actor)
|
||||
} else {
|
||||
res, err = uw.IssueUseCase().CloseIssue(ctx, id, params, actor)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err)
|
||||
return closeProxiedOutcome{}, false
|
||||
}
|
||||
|
||||
oldStatus := string(current.Status)
|
||||
if oldStatus == "" {
|
||||
oldStatus = "open"
|
||||
}
|
||||
audit.LogFieldChange(id, "status", oldStatus, "closed", actor, reason)
|
||||
|
||||
autoCloseProxiedCompletedMolecule(ctx, uw, id, actor, in.session, in.jsonOut)
|
||||
|
||||
return closeProxiedOutcome{id: id, before: current, after: res.Issue, closed: res.Closed}, true
|
||||
}
|
||||
|
||||
func closeProxiedCommitMessage(outcomes []closeProxiedOutcome, claimed *types.Issue, cont *ContinueResult) string {
|
||||
ids := make([]string, 0, len(outcomes))
|
||||
for _, o := range outcomes {
|
||||
ids = append(ids, o.id)
|
||||
}
|
||||
msg := "bd: close " + strings.Join(ids, ", ")
|
||||
if cont != nil && cont.AutoAdvanced && cont.NextStep != nil {
|
||||
msg += "; advance to " + cont.NextStep.ID
|
||||
}
|
||||
if claimed != nil {
|
||||
msg += "; claim " + claimed.ID
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func proxiedResolveIssueOrWisp(ctx context.Context, uw uow.UnitOfWork, id string) (*types.Issue, bool) {
|
||||
issue, err := uw.IssueUseCase().GetIssue(ctx, id)
|
||||
if err == nil && issue != nil {
|
||||
return issue, false
|
||||
}
|
||||
wisp, err := uw.IssueUseCase().GetWisp(ctx, id)
|
||||
if err == nil && wisp != nil {
|
||||
return wisp, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func fireProxiedCloseHooks(ctx context.Context, before, after *types.Issue) error {
|
||||
if after == nil {
|
||||
return nil
|
||||
}
|
||||
runner, err := proxiedHookRunner(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hook runner: %w", err)
|
||||
}
|
||||
if runner == nil {
|
||||
return nil
|
||||
}
|
||||
if err := runner.RunSync(hooks.EventUpdate, after); err != nil {
|
||||
return fmt.Errorf("on_update hook: %w", err)
|
||||
}
|
||||
if before != nil && before.Status != types.StatusClosed && after.Status == types.StatusClosed {
|
||||
if err := runner.RunSync(hooks.EventClose, after); err != nil {
|
||||
return fmt.Errorf("on_close hook: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeProxiedSuggestNext(ctx context.Context, uw uow.UnitOfWork, closedID string) []*types.Issue {
|
||||
unblocked, err := uw.IssueUseCase().GetNewlyUnblockedByClose(ctx, closedID)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not compute newly unblocked: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
return unblocked
|
||||
}
|
||||
|
||||
func closeProxiedClaimNext(ctx context.Context, uw uow.UnitOfWork, jsonOut bool) *types.Issue {
|
||||
page, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{
|
||||
Status: "open",
|
||||
Limit: 1,
|
||||
SortPolicy: types.SortPolicy("priority"),
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not get ready issues: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
if len(page.Items) == 0 {
|
||||
if !jsonOut {
|
||||
fmt.Printf("\n%s No ready issues available to claim.\n", ui.RenderWarn("✨"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
nextIssue := page.Items[0]
|
||||
if _, err := uw.IssueUseCase().ClaimIssue(ctx, nextIssue.ID, actor); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not claim next issue %s: %v\n", nextIssue.ID, err)
|
||||
return nil
|
||||
}
|
||||
return nextIssue
|
||||
}
|
||||
|
||||
func closeProxiedContinue(ctx context.Context, uw uow.UnitOfWork, closedID string, autoClaim bool) *ContinueResult {
|
||||
result, err := proxiedAdvanceToNextStep(ctx, uw, closedID, autoClaim, actor)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func autoCloseProxiedCompletedMolecule(ctx context.Context, uw uow.UnitOfWork, closedStepID string, actorName, session string, jsonOut bool) {
|
||||
moleculeID := proxiedFindParentMolecule(ctx, uw, closedStepID)
|
||||
if moleculeID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
root, err := uw.IssueUseCase().GetIssue(ctx, moleculeID)
|
||||
if err != nil || root == nil || root.Status == types.StatusClosed {
|
||||
return
|
||||
}
|
||||
if labels, err := uw.LabelUseCase().GetLabels(ctx, moleculeID); err == nil {
|
||||
root.Labels = labels
|
||||
}
|
||||
if !shouldAutoCloseCompletedRoot(root) {
|
||||
return
|
||||
}
|
||||
|
||||
progress, err := proxiedGetMoleculeProgress(ctx, uw, moleculeID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if progress.Completed < progress.Total {
|
||||
return
|
||||
}
|
||||
|
||||
params := domain.CloseIssueParams{Reason: "all steps complete", Session: session}
|
||||
if _, err := uw.IssueUseCase().CloseIssue(ctx, moleculeID, params, actorName); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule %s: %v\n", moleculeID, err)
|
||||
return
|
||||
}
|
||||
if !jsonOut {
|
||||
fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(moleculeID, root.Title))
|
||||
}
|
||||
}
|
||||
|
||||
func proxiedFindParentMolecule(ctx context.Context, uw uow.UnitOfWork, issueID string) string {
|
||||
current := issueID
|
||||
for depth := 0; depth < 50; depth++ {
|
||||
deps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, []string{current})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var parent string
|
||||
for _, dep := range deps[current] {
|
||||
if dep.Type == types.DepParentChild {
|
||||
parent = dep.DependsOnID
|
||||
break
|
||||
}
|
||||
}
|
||||
if parent == "" {
|
||||
if current == issueID {
|
||||
return ""
|
||||
}
|
||||
return current
|
||||
}
|
||||
current = parent
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func proxiedLoadTemplateSubgraph(ctx context.Context, uw uow.UnitOfWork, templateID string) (*TemplateSubgraph, error) {
|
||||
root, err := uw.IssueUseCase().GetIssue(ctx, templateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get template: %w", err)
|
||||
}
|
||||
if root == nil {
|
||||
return nil, fmt.Errorf("template %s not found", templateID)
|
||||
}
|
||||
|
||||
subgraph := &TemplateSubgraph{
|
||||
Root: root,
|
||||
Issues: []*types.Issue{root},
|
||||
IssueMap: map[string]*types.Issue{root.ID: root},
|
||||
}
|
||||
|
||||
visited := map[string]bool{root.ID: true}
|
||||
if err := proxiedLoadDescendants(ctx, uw, subgraph, root.ID, visited); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, issue := range subgraph.Issues {
|
||||
deps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, []string{issue.ID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get dependencies for %s: %w", issue.ID, err)
|
||||
}
|
||||
for _, dep := range deps[issue.ID] {
|
||||
if _, ok := subgraph.IssueMap[dep.DependsOnID]; ok {
|
||||
subgraph.Dependencies = append(subgraph.Dependencies, dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return subgraph, nil
|
||||
}
|
||||
|
||||
func proxiedLoadDescendants(ctx context.Context, uw uow.UnitOfWork, subgraph *TemplateSubgraph, parentID string, visited map[string]bool) error {
|
||||
dependents, err := uw.DependencyUseCase().ListWithIssueMetadata(ctx, parentID, domain.DepListFilter{
|
||||
Direction: domain.DepDirectionIn,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get dependents of %s: %w", parentID, err)
|
||||
}
|
||||
|
||||
for _, dependent := range dependents {
|
||||
if dependent.DependencyType != types.DepParentChild {
|
||||
continue
|
||||
}
|
||||
if _, exists := subgraph.IssueMap[dependent.ID]; exists {
|
||||
continue
|
||||
}
|
||||
if visited[dependent.ID] {
|
||||
continue
|
||||
}
|
||||
child := dependent.Issue
|
||||
subgraph.Issues = append(subgraph.Issues, &child)
|
||||
subgraph.IssueMap[child.ID] = &child
|
||||
visited[child.ID] = true
|
||||
if err := proxiedLoadDescendants(ctx, uw, subgraph, child.ID, visited); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func proxiedGetMoleculeProgress(ctx context.Context, uw uow.UnitOfWork, moleculeID string) (*MoleculeProgress, error) {
|
||||
subgraph, err := proxiedLoadTemplateSubgraph(ctx, uw, moleculeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
progress := &MoleculeProgress{
|
||||
MoleculeID: subgraph.Root.ID,
|
||||
MoleculeTitle: subgraph.Root.Title,
|
||||
Assignee: subgraph.Root.Assignee,
|
||||
Total: len(subgraph.Issues) - 1,
|
||||
}
|
||||
|
||||
analysis := analyzeMoleculeParallel(subgraph)
|
||||
readyIDs := make(map[string]bool)
|
||||
for id, info := range analysis.Steps {
|
||||
if info.IsReady {
|
||||
readyIDs[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
var steps []*StepStatus
|
||||
for _, issue := range subgraph.Issues {
|
||||
if issue.ID == subgraph.Root.ID {
|
||||
continue
|
||||
}
|
||||
step := &StepStatus{Issue: issue}
|
||||
switch issue.Status {
|
||||
case types.StatusClosed:
|
||||
step.Status = "done"
|
||||
progress.Completed++
|
||||
case types.StatusInProgress:
|
||||
step.Status = "current"
|
||||
step.IsCurrent = true
|
||||
progress.CurrentStep = issue
|
||||
case types.StatusBlocked:
|
||||
step.Status = "blocked"
|
||||
default:
|
||||
if readyIDs[issue.ID] {
|
||||
step.Status = "ready"
|
||||
if progress.NextStep == nil {
|
||||
progress.NextStep = issue
|
||||
}
|
||||
} else {
|
||||
step.Status = "pending"
|
||||
}
|
||||
}
|
||||
steps = append(steps, step)
|
||||
}
|
||||
|
||||
sortStepsByDependencyOrder(steps, subgraph)
|
||||
progress.Steps = steps
|
||||
|
||||
if progress.CurrentStep == nil && progress.NextStep == nil {
|
||||
for _, step := range steps {
|
||||
if step.Status == "ready" {
|
||||
progress.NextStep = step.Issue
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return progress, nil
|
||||
}
|
||||
|
||||
func proxiedAdvanceToNextStep(ctx context.Context, uw uow.UnitOfWork, closedStepID string, autoClaim bool, actorName string) (*ContinueResult, error) {
|
||||
closedStep, err := uw.IssueUseCase().GetIssue(ctx, closedStepID)
|
||||
if err != nil || closedStep == nil {
|
||||
wisp, wErr := uw.IssueUseCase().GetWisp(ctx, closedStepID)
|
||||
if wErr != nil || wisp == nil {
|
||||
return nil, fmt.Errorf("could not get closed step: %w", err)
|
||||
}
|
||||
closedStep = wisp
|
||||
}
|
||||
|
||||
result := &ContinueResult{ClosedStep: closedStep}
|
||||
|
||||
moleculeID := proxiedFindParentMolecule(ctx, uw, closedStepID)
|
||||
if moleculeID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
result.MoleculeID = moleculeID
|
||||
|
||||
progress, err := proxiedGetMoleculeProgress(ctx, uw, moleculeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not load molecule: %w", err)
|
||||
}
|
||||
|
||||
if progress.Completed >= progress.Total {
|
||||
result.MolComplete = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
var readySteps []*types.Issue
|
||||
for _, step := range progress.Steps {
|
||||
if step.Status == "ready" {
|
||||
readySteps = append(readySteps, step.Issue)
|
||||
}
|
||||
}
|
||||
if len(readySteps) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
result.NextStep = readySteps[0]
|
||||
|
||||
if !autoClaim {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
for _, candidate := range readySteps {
|
||||
_, claimErr := uw.IssueUseCase().ClaimIssueIfOpen(ctx, candidate.ID, actorName)
|
||||
if claimErr == nil {
|
||||
result.NextStep = candidate
|
||||
result.AutoAdvanced = true
|
||||
return result, nil
|
||||
}
|
||||
if errors.Is(claimErr, storage.ErrAlreadyClaimed) || errors.Is(claimErr, storage.ErrNotClaimable) {
|
||||
continue
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ package main
|
|||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
|
|
@ -17,7 +18,7 @@ func newCloseLikeCmd() *cobra.Command {
|
|||
Use: "close",
|
||||
Run: func(cmd *cobra.Command, args []string) {},
|
||||
}
|
||||
cmd.Flags().StringP("reason", "r", "", "Reason for closing")
|
||||
registerCloseReasonFlag(cmd)
|
||||
cmd.Flags().String("resolution", "", "")
|
||||
cmd.Flags().StringP("message", "m", "", "")
|
||||
cmd.Flags().String("comment", "", "")
|
||||
|
|
@ -38,7 +39,7 @@ func TestCloseResolveReasonFile_FileWithContent(t *testing.T) {
|
|||
t.Fatalf("parse flags: %v", err)
|
||||
}
|
||||
|
||||
got, ok, err := resolveReasonFile(cmd, "")
|
||||
got, ok, err := resolveReasonFile(cmd, false)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveReasonFile: %v", err)
|
||||
}
|
||||
|
|
@ -70,7 +71,7 @@ func TestCloseResolveReasonFile_StdinDash(t *testing.T) {
|
|||
t.Fatalf("parse flags: %v", err)
|
||||
}
|
||||
|
||||
got, ok, err := resolveReasonFile(cmd, "")
|
||||
got, ok, err := resolveReasonFile(cmd, false)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveReasonFile: %v", err)
|
||||
}
|
||||
|
|
@ -89,7 +90,7 @@ func TestCloseResolveReasonFile_FileNotFound(t *testing.T) {
|
|||
t.Fatalf("parse flags: %v", err)
|
||||
}
|
||||
|
||||
_, ok, err := resolveReasonFile(cmd, "")
|
||||
_, ok, err := resolveReasonFile(cmd, false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing file, got nil")
|
||||
}
|
||||
|
|
@ -116,7 +117,7 @@ func TestCloseResolveReasonFile_ConflictWithReason(t *testing.T) {
|
|||
|
||||
// Caller has already collected the inline reason from the various aliases,
|
||||
// so we pass it in directly to mirror how close.go invokes the helper.
|
||||
_, ok, err := resolveReasonFile(cmd, "from flag")
|
||||
_, ok, err := resolveReasonFile(cmd, true)
|
||||
if err == nil {
|
||||
t.Fatal("expected conflict error, got nil")
|
||||
}
|
||||
|
|
@ -140,7 +141,7 @@ func TestCloseResolveReasonFile_EmptyFile(t *testing.T) {
|
|||
t.Fatalf("parse flags: %v", err)
|
||||
}
|
||||
|
||||
_, ok, err := resolveReasonFile(cmd, "")
|
||||
_, ok, err := resolveReasonFile(cmd, false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for whitespace-only file, got nil")
|
||||
}
|
||||
|
|
@ -158,7 +159,7 @@ func TestCloseResolveReasonFile_FlagNotSet(t *testing.T) {
|
|||
t.Fatalf("parse flags: %v", err)
|
||||
}
|
||||
|
||||
got, ok, err := resolveReasonFile(cmd, "inline")
|
||||
got, ok, err := resolveReasonFile(cmd, true)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
|
@ -169,3 +170,123 @@ func TestCloseResolveReasonFile_FlagNotSet(t *testing.T) {
|
|||
t.Errorf("expected empty content, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseResolveReasons_PerIDReasons(t *testing.T) {
|
||||
cmd := newCloseLikeCmd()
|
||||
cmd.SetArgs([]string{"issue-a", "--reason", "reason A", "issue-b", "--reason", "reason B"})
|
||||
|
||||
var gotReasons, gotArgs []string
|
||||
cmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
var err error
|
||||
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCloseReasons: %v", err)
|
||||
}
|
||||
}
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
|
||||
if !slices.Equal(gotArgs, []string{"issue-a", "issue-b"}) {
|
||||
t.Fatalf("args = %v, want [issue-a issue-b]", gotArgs)
|
||||
}
|
||||
if !slices.Equal(gotReasons, []string{"reason A", "reason B"}) {
|
||||
t.Fatalf("reasons = %v, want per-ID reasons", gotReasons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseResolveReasons_SharedReasonForMultipleIDs(t *testing.T) {
|
||||
cmd := newCloseLikeCmd()
|
||||
cmd.SetArgs([]string{"issue-a", "issue-b", "--reason", "same reason"})
|
||||
|
||||
var gotReasons, gotArgs []string
|
||||
cmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
var err error
|
||||
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCloseReasons: %v", err)
|
||||
}
|
||||
}
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
|
||||
if !slices.Equal(gotArgs, []string{"issue-a", "issue-b"}) {
|
||||
t.Fatalf("args = %v, want [issue-a issue-b]", gotArgs)
|
||||
}
|
||||
if !slices.Equal(gotReasons, []string{"same reason"}) {
|
||||
t.Fatalf("reasons = %v, want one shared reason", gotReasons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseResolveReasons_EmptyReasonFallsBackToDefault(t *testing.T) {
|
||||
cmd := newCloseLikeCmd()
|
||||
cmd.SetArgs([]string{"issue-a", "--reason", ""})
|
||||
|
||||
var gotReasons, gotArgs []string
|
||||
cmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
var err error
|
||||
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCloseReasons: %v", err)
|
||||
}
|
||||
}
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
|
||||
if !slices.Equal(gotArgs, []string{"issue-a"}) {
|
||||
t.Fatalf("args = %v, want [issue-a]", gotArgs)
|
||||
}
|
||||
if !slices.Equal(gotReasons, []string{"Closed"}) {
|
||||
t.Fatalf("reasons = %v, want default reason", gotReasons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseResolveReasons_EmptyReasonDoesNotConflictWithReasonFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "reason.md")
|
||||
if err := os.WriteFile(path, []byte("from file"), 0644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
|
||||
cmd := newCloseLikeCmd()
|
||||
cmd.SetArgs([]string{"issue-a", "--reason", "", "--reason-file", path})
|
||||
|
||||
var gotReasons, gotArgs []string
|
||||
cmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
var err error
|
||||
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCloseReasons: %v", err)
|
||||
}
|
||||
}
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
|
||||
if !slices.Equal(gotArgs, []string{"issue-a"}) {
|
||||
t.Fatalf("args = %v, want [issue-a]", gotArgs)
|
||||
}
|
||||
if !slices.Equal(gotReasons, []string{"from file"}) {
|
||||
t.Fatalf("reasons = %v, want file reason", gotReasons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseResolveReasons_RejectsMismatchedPerIDReasons(t *testing.T) {
|
||||
cmd := newCloseLikeCmd()
|
||||
cmd.SetArgs([]string{"issue-a", "--reason", "reason A", "issue-b", "--reason", "reason B", "issue-c"})
|
||||
|
||||
cmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
_, _, err := resolveCloseReasons(cmd, args)
|
||||
if err == nil {
|
||||
t.Fatal("expected mismatch error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "2 close reasons for 3 issue IDs") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
63
cmd/bd/closed_delete_candidates.go
Normal file
63
cmd/bd/closed_delete_candidates.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
type closedDeletionCandidateStats struct {
|
||||
PinnedSkipped int
|
||||
NilSkipped int
|
||||
NonClosedSkipped int
|
||||
MissingClosedAtSkipped int
|
||||
RecentClosedAtSkipped int
|
||||
}
|
||||
|
||||
func (s closedDeletionCandidateStats) SafetySkipped() int {
|
||||
return s.NilSkipped + s.NonClosedSkipped + s.MissingClosedAtSkipped + s.RecentClosedAtSkipped
|
||||
}
|
||||
|
||||
func filterClosedDeletionCandidates(issues []*types.Issue, cutoff *time.Time) ([]*types.Issue, closedDeletionCandidateStats) {
|
||||
filtered := make([]*types.Issue, 0, len(issues))
|
||||
var stats closedDeletionCandidateStats
|
||||
|
||||
for _, issue := range issues {
|
||||
if issue == nil {
|
||||
stats.NilSkipped++
|
||||
continue
|
||||
}
|
||||
if issue.Pinned {
|
||||
stats.PinnedSkipped++
|
||||
continue
|
||||
}
|
||||
if issue.Status != types.StatusClosed {
|
||||
stats.NonClosedSkipped++
|
||||
continue
|
||||
}
|
||||
if issue.ClosedAt == nil {
|
||||
stats.MissingClosedAtSkipped++
|
||||
continue
|
||||
}
|
||||
if cutoff != nil && !issue.ClosedAt.Before(*cutoff) {
|
||||
stats.RecentClosedAtSkipped++
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, issue)
|
||||
}
|
||||
|
||||
return filtered, stats
|
||||
}
|
||||
|
||||
func warnClosedDeletionSafetySkips(stats closedDeletionCandidateStats) {
|
||||
if stats.SafetySkipped() == 0 {
|
||||
return
|
||||
}
|
||||
WarnError("skipped %d deletion candidate(s) after closed_at safety recheck (nil=%d, non_closed=%d, missing_closed_at=%d, too_recent=%d)",
|
||||
stats.SafetySkipped(),
|
||||
stats.NilSkipped,
|
||||
stats.NonClosedSkipped,
|
||||
stats.MissingClosedAtSkipped,
|
||||
stats.RecentClosedAtSkipped,
|
||||
)
|
||||
}
|
||||
72
cmd/bd/closed_delete_candidates_test.go
Normal file
72
cmd/bd/closed_delete_candidates_test.go
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestFilterClosedDeletionCandidatesRechecksClosedAtCutoff(t *testing.T) {
|
||||
cutoff := time.Date(2026, 3, 27, 20, 1, 44, 0, time.UTC)
|
||||
oldClosedAt := cutoff.Add(-time.Second)
|
||||
recentClosedAt := cutoff.Add(time.Second)
|
||||
|
||||
candidates := []*types.Issue{
|
||||
{ID: "old-closed", Status: types.StatusClosed, ClosedAt: &oldClosedAt},
|
||||
{ID: "recent-closed", Status: types.StatusClosed, ClosedAt: &recentClosedAt},
|
||||
{ID: "missing-closed-at", Status: types.StatusClosed},
|
||||
{ID: "open-with-old-closed-at", Status: types.StatusOpen, ClosedAt: &oldClosedAt},
|
||||
{ID: "pinned-old", Status: types.StatusClosed, ClosedAt: &oldClosedAt, Pinned: true},
|
||||
nil,
|
||||
}
|
||||
|
||||
filtered, stats := filterClosedDeletionCandidates(candidates, &cutoff)
|
||||
|
||||
if len(filtered) != 1 || filtered[0].ID != "old-closed" {
|
||||
t.Fatalf("filtered IDs = %v, want only old-closed", closedDeletionCandidateIDs(filtered))
|
||||
}
|
||||
if stats.PinnedSkipped != 1 {
|
||||
t.Fatalf("PinnedSkipped = %d, want 1", stats.PinnedSkipped)
|
||||
}
|
||||
if stats.RecentClosedAtSkipped != 1 {
|
||||
t.Fatalf("RecentClosedAtSkipped = %d, want 1", stats.RecentClosedAtSkipped)
|
||||
}
|
||||
if stats.MissingClosedAtSkipped != 1 {
|
||||
t.Fatalf("MissingClosedAtSkipped = %d, want 1", stats.MissingClosedAtSkipped)
|
||||
}
|
||||
if stats.NonClosedSkipped != 1 {
|
||||
t.Fatalf("NonClosedSkipped = %d, want 1", stats.NonClosedSkipped)
|
||||
}
|
||||
if stats.NilSkipped != 1 {
|
||||
t.Fatalf("NilSkipped = %d, want 1", stats.NilSkipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterClosedDeletionCandidatesWithoutCutoffStillRequiresClosedAt(t *testing.T) {
|
||||
closedAt := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
|
||||
candidates := []*types.Issue{
|
||||
{ID: "closed", Status: types.StatusClosed, ClosedAt: &closedAt},
|
||||
{ID: "closed-missing-time", Status: types.StatusClosed},
|
||||
}
|
||||
|
||||
filtered, stats := filterClosedDeletionCandidates(candidates, nil)
|
||||
|
||||
if len(filtered) != 1 || filtered[0].ID != "closed" {
|
||||
t.Fatalf("filtered IDs = %v, want only closed", closedDeletionCandidateIDs(filtered))
|
||||
}
|
||||
if stats.MissingClosedAtSkipped != 1 {
|
||||
t.Fatalf("MissingClosedAtSkipped = %d, want 1", stats.MissingClosedAtSkipped)
|
||||
}
|
||||
if stats.RecentClosedAtSkipped != 0 {
|
||||
t.Fatalf("RecentClosedAtSkipped = %d, want 0 without cutoff", stats.RecentClosedAtSkipped)
|
||||
}
|
||||
}
|
||||
|
||||
func closedDeletionCandidateIDs(issues []*types.Issue) []string {
|
||||
ids := make([]string, len(issues))
|
||||
for i, issue := range issues {
|
||||
ids[i] = issue.ID
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
|
|
@ -23,14 +24,22 @@ Examples:
|
|||
bd comment bd-123 Working on this now
|
||||
echo "comment from pipe" | bd comment bd-123 --stdin
|
||||
bd comment bd-123 --file notes.txt`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("comment")
|
||||
|
||||
evt := metrics.NewCommandEvent("comment")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
id := args[0]
|
||||
textArgs := args[1:]
|
||||
|
||||
// Determine comment text from args, stdin, or file
|
||||
stdinFlag, _ := cmd.Flags().GetBool("stdin")
|
||||
fileFlag, _ := cmd.Flags().GetString("file")
|
||||
|
||||
|
|
@ -39,64 +48,68 @@ Examples:
|
|||
case stdinFlag:
|
||||
content, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("reading from stdin: %v", err)
|
||||
return HandleErrorRespectJSON("reading from stdin: %v", err)
|
||||
}
|
||||
commentText = strings.TrimRight(string(content), "\n")
|
||||
case fileFlag != "":
|
||||
content, err := readBodyFile(fileFlag)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("reading file: %v", err)
|
||||
return HandleErrorRespectJSON("reading file: %v", err)
|
||||
}
|
||||
commentText = content
|
||||
case len(textArgs) > 0:
|
||||
commentText = strings.Join(textArgs, " ")
|
||||
default:
|
||||
FatalErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)")
|
||||
return HandleErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(commentText) == "" {
|
||||
FatalErrorRespectJSON("comment text cannot be empty")
|
||||
return HandleErrorRespectJSON("comment text cannot be empty")
|
||||
}
|
||||
|
||||
author := getActorWithGit()
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
result, err := resolveAndGetIssueWithRouting(ctx, store, id)
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, id)
|
||||
if err != nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("resolving %s: %v", id, err)
|
||||
return HandleErrorRespectJSON("resolving %s: %v", id, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("issue %s not found", id)
|
||||
return HandleErrorRespectJSON("issue %s not found", id)
|
||||
}
|
||||
defer result.Close()
|
||||
|
||||
issueStore := result.Store
|
||||
|
||||
if err := validateIssueUpdatable(id, result.Issue); err != nil {
|
||||
FatalErrorRespectJSON("%s", err)
|
||||
return HandleErrorRespectJSON("%s", err)
|
||||
}
|
||||
|
||||
comment, err := issueStore.AddIssueComment(ctx, result.ResolvedID, author, commentText)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("adding comment: %v", err)
|
||||
return HandleErrorRespectJSON("adding comment: %v", err)
|
||||
}
|
||||
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
|
||||
Command: "comment",
|
||||
IssueIDs: []string{result.ResolvedID},
|
||||
}); err != nil {
|
||||
return HandleErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
SetLastTouchedID(result.ResolvedID)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(comment)
|
||||
} else {
|
||||
fmt.Printf("%s Comment added to %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, result.Issue.Title))
|
||||
return outputJSON(comment)
|
||||
}
|
||||
fmt.Printf("%s Comment added to %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, result.Issue.Title))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,11 +16,11 @@ func bdComment(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments add %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd comments add %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
// bdCommentList runs "bd comments list" and returns stdout.
|
||||
|
|
@ -29,11 +29,11 @@ func bdCommentList(t *testing.T, bd, dir, issueID string) string {
|
|||
cmd := exec.Command(bd, "comments", "list", issueID)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments list %s failed: %v\n%s", issueID, err, out)
|
||||
t.Fatalf("bd comments list %s failed: %v\nstdout:\n%s\nstderr:\n%s", issueID, err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
func TestEmbeddedComments(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -6,8 +6,9 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/internal/uimd"
|
||||
)
|
||||
|
||||
var commentsCmd = &cobra.Command{
|
||||
|
|
@ -28,13 +29,22 @@ Examples:
|
|||
|
||||
# Add a comment from a file
|
||||
bd comments add bd-123 -f notes.txt`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("comments")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
localTime, _ := cmd.Flags().GetBool("local-time")
|
||||
issueID := args[0]
|
||||
|
||||
if err := ensureStoreActive(); err != nil {
|
||||
FatalErrorRespectJSON("getting comments: %v", err)
|
||||
return HandleErrorRespectJSON("getting comments: %v", err)
|
||||
}
|
||||
ctx := rootCtx
|
||||
|
||||
|
|
@ -43,36 +53,33 @@ Examples:
|
|||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("resolving %s: %v", issueID, err)
|
||||
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("issue %s not found", issueID)
|
||||
return HandleErrorRespectJSON("issue %s not found", issueID)
|
||||
}
|
||||
defer result.Close()
|
||||
issueID = result.ResolvedID
|
||||
|
||||
comments, err := result.Store.GetIssueComments(ctx, issueID)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("getting comments: %v", err)
|
||||
return HandleErrorRespectJSON("getting comments: %v", err)
|
||||
}
|
||||
|
||||
// Normalize nil to empty slice for consistent JSON output
|
||||
if comments == nil {
|
||||
comments = make([]*types.Comment, 0)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(comments)
|
||||
return
|
||||
return outputJSON(comments)
|
||||
}
|
||||
|
||||
// Human-readable output
|
||||
if len(comments) == 0 {
|
||||
fmt.Printf("No comments on %s\n", issueID)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("\nComments on %s:\n\n", issueID)
|
||||
|
|
@ -82,23 +89,23 @@ Examples:
|
|||
ts = ts.Local()
|
||||
}
|
||||
fmt.Printf("[%s] at %s\n", comment.Author, ts.Format("2006-01-02 15:04"))
|
||||
rendered := ui.RenderMarkdown(comment.Text)
|
||||
// TrimRight removes trailing newlines that Glamour adds, preventing extra blank lines
|
||||
rendered := uimd.RenderMarkdown(comment.Text)
|
||||
for _, line := range strings.Split(strings.TrimRight(rendered, "\n"), "\n") {
|
||||
fmt.Printf(" %s\n", line)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// commentsMisplacedListCmd catches the reflexive "bd comments list" invocation (GH#3542).
|
||||
// Listing comments always requires an issue id: bd comments <issue-id>.
|
||||
var commentsMisplacedListCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "Invalid — use bd comments <issue-id> to list comments",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
FatalErrorRespectJSON(`"bd comments list" is not valid.
|
||||
Use: "list",
|
||||
Short: "Invalid — use bd comments <issue-id> to list comments",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return HandleErrorRespectJSON(`"bd comments list" is not valid.
|
||||
|
||||
To list comments on an issue, run:
|
||||
bd comments <issue-id>
|
||||
|
|
@ -121,70 +128,81 @@ Examples:
|
|||
|
||||
# Add a comment from a file
|
||||
bd comments add bd-123 -f notes.txt`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
CheckReadonly("comment add")
|
||||
|
||||
evt := metrics.NewCommandEvent("comments-add")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
issueID := args[0]
|
||||
|
||||
// Get comment text from flag or argument
|
||||
commentText, _ := cmd.Flags().GetString("file")
|
||||
if commentText != "" {
|
||||
// Read from file
|
||||
data, err := os.ReadFile(commentText) // #nosec G304 - user-provided file path is intentional
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("reading file: %v", err)
|
||||
return HandleErrorRespectJSON("reading file: %v", err)
|
||||
}
|
||||
commentText = string(data)
|
||||
} else if len(args) < 2 {
|
||||
FatalErrorRespectJSON("comment text required (use -f to read from file)")
|
||||
return HandleErrorRespectJSON("comment text required (use -f to read from file)")
|
||||
} else {
|
||||
commentText = args[1]
|
||||
}
|
||||
|
||||
if strings.TrimSpace(commentText) == "" {
|
||||
FatalErrorRespectJSON("comment text cannot be empty")
|
||||
return HandleErrorRespectJSON("comment text cannot be empty")
|
||||
}
|
||||
|
||||
// Get author from author flag, or use git-aware default
|
||||
author, _ := cmd.Flags().GetString("author")
|
||||
if author == "" {
|
||||
author = getActorWithGit()
|
||||
}
|
||||
|
||||
if err := ensureStoreActive(); err != nil {
|
||||
FatalErrorRespectJSON("adding comment: %v", err)
|
||||
return HandleErrorRespectJSON("adding comment: %v", err)
|
||||
}
|
||||
ctx := rootCtx
|
||||
|
||||
result, err := resolveAndGetIssueWithRouting(ctx, store, issueID)
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
||||
if err != nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("resolving %s: %v", issueID, err)
|
||||
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
FatalErrorRespectJSON("issue %s not found", issueID)
|
||||
return HandleErrorRespectJSON("issue %s not found", issueID)
|
||||
}
|
||||
defer result.Close()
|
||||
issueID = result.ResolvedID
|
||||
|
||||
comment, err := result.Store.AddIssueComment(ctx, issueID, author, commentText)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("adding comment: %v", err)
|
||||
return HandleErrorRespectJSON("adding comment: %v", err)
|
||||
}
|
||||
if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{
|
||||
Command: "comments add",
|
||||
IssueIDs: []string{issueID},
|
||||
}); err != nil {
|
||||
return HandleErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(comment)
|
||||
return
|
||||
return outputJSON(comment)
|
||||
}
|
||||
|
||||
fmt.Printf("Comment added to %s\n", issueID)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ func bdComments(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd comments %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
func TestEmbeddedCommentsCLI(t *testing.T) {
|
||||
|
|
@ -51,11 +51,11 @@ func TestEmbeddedCommentsCLI(t *testing.T) {
|
|||
cmd := exec.Command(bd, "comments", "add", issue.ID, "JSON comment text", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments add --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd comments add --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON in output: %s", s)
|
||||
|
|
@ -115,11 +115,11 @@ func TestEmbeddedCommentsCLI(t *testing.T) {
|
|||
cmd := exec.Command(bd, "comments", issue.ID, "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments list --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd comments list --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "[")
|
||||
if start >= 0 {
|
||||
var comments []map[string]interface{}
|
||||
|
|
@ -146,11 +146,11 @@ func TestEmbeddedCommentsCLI(t *testing.T) {
|
|||
cmd := exec.Command(bd, "comments", issue.ID, "--local-time")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd comments list --local-time failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd comments list --local-time failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
_ = out
|
||||
_ = stdout.String()
|
||||
})
|
||||
|
||||
// ===== Round-trip =====
|
||||
|
|
@ -162,11 +162,11 @@ func TestEmbeddedCommentsCLI(t *testing.T) {
|
|||
cmd := exec.Command(bd, "comments", issue.ID, "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("list failed: %v\n%s", err, out)
|
||||
t.Fatalf("list failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "[")
|
||||
if start >= 0 {
|
||||
var comments []map[string]interface{}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ Modes:
|
|||
|
||||
Tiers:
|
||||
- Tier 1: Semantic compression (30 days closed, 70% reduction)
|
||||
- Tier 2: Ultra compression (90 days closed, 95% reduction)
|
||||
- Tier 2: Ultra compression (90 days closed) - planned, not yet implemented
|
||||
|
||||
Dolt Garbage Collection:
|
||||
With auto-commit per mutation, Dolt commit history grows over time. Use
|
||||
|
|
@ -125,6 +125,13 @@ Examples:
|
|||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Only Tier 1 compaction is implemented. Reject other tiers up front with
|
||||
// a clear message rather than failing deep inside a mode.
|
||||
if compactTier != 1 {
|
||||
fmt.Fprintf(os.Stderr, "Error: Tier %d compaction is not yet implemented; only --tier 1 is available\n", compactTier)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Handle analyze mode (requires direct database access)
|
||||
if compactAnalyze {
|
||||
if err := ensureDirectMode("compact --analyze requires direct database access"); err != nil {
|
||||
|
|
@ -252,7 +259,9 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s
|
|||
"total_content_bytes": originalSize,
|
||||
},
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -301,7 +310,9 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s
|
|||
"reduction_pct": float64(savingBytes) / float64(originalSize) * 100,
|
||||
"elapsed_ms": elapsed.Milliseconds(),
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -338,11 +349,13 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor
|
|||
|
||||
if len(candidates) == 0 {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"success": true,
|
||||
"count": 0,
|
||||
"message": "No eligible candidates",
|
||||
})
|
||||
}); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
fmt.Println("No eligible candidates for compaction")
|
||||
|
|
@ -394,7 +407,9 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor
|
|||
"total_content_bytes": totalSize,
|
||||
},
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -453,7 +468,9 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor
|
|||
"original_size": totalOriginal,
|
||||
"elapsed_ms": elapsed.Milliseconds(),
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -496,11 +513,14 @@ func runCompactStats(ctx context.Context, store storage.DoltStorage) {
|
|||
"total_size": tier1Size,
|
||||
},
|
||||
"tier2": map[string]interface{}{
|
||||
"candidates": len(tier2),
|
||||
"total_size": tier2Size,
|
||||
"candidates": len(tier2),
|
||||
"total_size": tier2Size,
|
||||
"implemented": false,
|
||||
},
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -512,12 +532,9 @@ func runCompactStats(ctx context.Context, store storage.DoltStorage) {
|
|||
fmt.Printf(" Estimated savings: %d bytes (70%%)\n\n", tier1Size*7/10)
|
||||
}
|
||||
|
||||
fmt.Printf("Tier 2 (90+ days closed, Tier 1 compacted):\n")
|
||||
fmt.Printf("Tier 2 (90+ days closed, Tier 1 compacted): not yet implemented\n")
|
||||
fmt.Printf(" Candidates: %d\n", len(tier2))
|
||||
fmt.Printf(" Total size: %d bytes\n", tier2Size)
|
||||
if tier2Size > 0 {
|
||||
fmt.Printf(" Estimated savings: %d bytes (95%%)\n", tier2Size*95/100)
|
||||
}
|
||||
}
|
||||
|
||||
func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) {
|
||||
|
|
@ -617,7 +634,9 @@ func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) {
|
|||
"total_content_bytes": totalSize,
|
||||
},
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -740,7 +759,9 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) {
|
|||
"reduction_pct": reductionPct,
|
||||
"elapsed_ms": elapsed.Milliseconds(),
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -769,7 +790,9 @@ func runCompactDolt() {
|
|||
"dolt_path": doltPath,
|
||||
"available": false,
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
fmt.Printf("DRY RUN - Dolt garbage collection\n\n")
|
||||
|
|
@ -797,7 +820,9 @@ func runCompactDolt() {
|
|||
"size_before": sizeBefore,
|
||||
"size_display": formatBytes(sizeBefore),
|
||||
}
|
||||
outputJSON(output)
|
||||
if err := outputJSON(output); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
fmt.Printf("DRY RUN - Dolt garbage collection\n\n")
|
||||
|
|
@ -853,7 +878,9 @@ func runCompactDolt() {
|
|||
"freed_display": formatBytes(freed),
|
||||
"elapsed_ms": elapsed.Milliseconds(),
|
||||
}
|
||||
outputJSON(result)
|
||||
if err := outputJSON(result); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -911,7 +938,7 @@ func progressBar(current, total int) string {
|
|||
|
||||
func init() {
|
||||
compactCmd.Flags().BoolVar(&compactDryRun, "dry-run", false, "Preview without compacting")
|
||||
compactCmd.Flags().IntVar(&compactTier, "tier", 1, "Compaction tier (1 or 2)")
|
||||
compactCmd.Flags().IntVar(&compactTier, "tier", 1, "Compaction tier (only tier 1 is implemented)")
|
||||
compactCmd.Flags().BoolVar(&compactAll, "all", false, "Process all candidates")
|
||||
compactCmd.Flags().StringVar(&compactID, "id", "", "Compact specific issue")
|
||||
compactCmd.Flags().BoolVar(&compactForce, "force", false, "Force compact (bypass checks, requires --id)")
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
|
|
@ -39,7 +40,16 @@ Examples:
|
|||
bd compact --force # Squash commits older than 30 days
|
||||
bd compact --days 7 --force # Keep only last 7 days of history
|
||||
bd compact --days 90 --force # Conservative: squash 90+ day old commits`,
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(_ *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("compact")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if !compactDoltDryRun {
|
||||
CheckReadonly("compact")
|
||||
}
|
||||
|
|
@ -47,58 +57,50 @@ Examples:
|
|||
start := time.Now()
|
||||
|
||||
if compactDoltDays < 0 {
|
||||
FatalError("--days must be non-negative")
|
||||
return HandleError("--days must be non-negative")
|
||||
}
|
||||
|
||||
// Get commit log via store interface
|
||||
logEntries, logErr := store.Log(ctx, 0)
|
||||
if logErr != nil {
|
||||
FatalError("failed to read commit log: %v", logErr)
|
||||
return HandleError("failed to read commit log: %v", logErr)
|
||||
}
|
||||
|
||||
totalCommits := len(logEntries)
|
||||
if totalCommits <= 1 {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "nothing to compact",
|
||||
"total_commits": totalCommits,
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("Only %d commit(s). Nothing to compact.\n", totalCommits)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Find cutoff and partition commits
|
||||
cutoff := time.Now().AddDate(0, 0, -compactDoltDays)
|
||||
|
||||
var oldCommits int
|
||||
var recentHashes []string
|
||||
var initialHash, boundaryHash string
|
||||
|
||||
// Log is ordered newest-first (ORDER BY date DESC)
|
||||
for _, entry := range logEntries {
|
||||
if entry.Date.Before(cutoff) {
|
||||
oldCommits++
|
||||
boundaryHash = entry.Hash // keeps getting overwritten; last = most recent old
|
||||
boundaryHash = entry.Hash
|
||||
} else {
|
||||
recentHashes = append(recentHashes, entry.Hash)
|
||||
}
|
||||
}
|
||||
// Initial hash is the oldest commit (last in DESC-ordered log)
|
||||
initialHash = logEntries[totalCommits-1].Hash
|
||||
// boundaryHash is the most recent old commit — but we iterated DESC,
|
||||
// so the first old commit we saw is the most recent. Re-scan:
|
||||
boundaryHash = ""
|
||||
for _, entry := range logEntries {
|
||||
if entry.Date.Before(cutoff) {
|
||||
boundaryHash = entry.Hash
|
||||
break // first match in DESC order = most recent old commit
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Recent hashes need to be in chronological order (oldest first) for cherry-pick
|
||||
for i, j := 0, len(recentHashes)-1; i < j; i, j = i+1, j-1 {
|
||||
recentHashes[i], recentHashes[j] = recentHashes[j], recentHashes[i]
|
||||
}
|
||||
|
|
@ -107,7 +109,7 @@ Examples:
|
|||
|
||||
if compactDoltDryRun {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"dry_run": true,
|
||||
"total_commits": totalCommits,
|
||||
"old_commits": oldCommits,
|
||||
|
|
@ -117,7 +119,6 @@ Examples:
|
|||
"initial_hash": initialHash,
|
||||
"boundary_hash": boundaryHash,
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("DRY RUN — Compact preview\n\n")
|
||||
fmt.Printf(" Total commits: %d\n", totalCommits)
|
||||
|
|
@ -130,29 +131,28 @@ Examples:
|
|||
fmt.Printf("\n Result: %d commits → %d commits\n", totalCommits, recentCommits+1)
|
||||
fmt.Printf(" Run with --force to proceed.\n")
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if oldCommits <= 1 {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "nothing to compact",
|
||||
"total_commits": totalCommits,
|
||||
"old_commits": oldCommits,
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("Only %d old commit(s). Nothing to compact.\n", oldCommits)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if boundaryHash == "" {
|
||||
FatalError("could not find boundary commit for compaction")
|
||||
return HandleError("could not find boundary commit for compaction")
|
||||
}
|
||||
|
||||
if !compactDoltForce {
|
||||
FatalErrorWithHint(
|
||||
return HandleErrorWithHint(
|
||||
fmt.Sprintf("would squash %d old commits into 1, preserving %d recent commits",
|
||||
oldCommits, recentCommits),
|
||||
"Use --force to confirm or --dry-run to preview.")
|
||||
|
|
@ -165,11 +165,11 @@ Examples:
|
|||
|
||||
compactor, ok := storage.UnwrapStore(store).(storage.Compactor)
|
||||
if !ok {
|
||||
FatalError("storage backend does not support compact")
|
||||
return HandleError("storage backend does not support compact")
|
||||
}
|
||||
|
||||
if err := compactor.Compact(ctx, initialHash, boundaryHash, oldCommits, recentHashes); err != nil {
|
||||
FatalError("compact failed: %v", err)
|
||||
return HandleError("compact failed: %v", err)
|
||||
}
|
||||
|
||||
// Reclaim disk space from orphaned old history
|
||||
|
|
@ -183,7 +183,7 @@ Examples:
|
|||
resultCommits := len(recentHashes) + 1
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"success": true,
|
||||
"commits_before": totalCommits,
|
||||
"commits_after": resultCommits,
|
||||
|
|
@ -191,12 +191,12 @@ Examples:
|
|||
"recent_kept": len(recentHashes),
|
||||
"elapsed_ms": elapsed.Milliseconds(),
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("✓ Compacted %d commits → %d\n", totalCommits, resultCommits)
|
||||
fmt.Printf(" Squashed: %d old commits → 1 base\n", oldCommits)
|
||||
fmt.Printf(" Preserved: %d recent commits\n", len(recentHashes))
|
||||
fmt.Printf(" Time: %v\n", elapsed.Round(time.Millisecond))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,11 +18,11 @@ func bdCompact(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd compact %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd compact %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
// bdCompactFail runs "bd compact" expecting failure.
|
||||
|
|
@ -139,12 +139,12 @@ func TestEmbeddedCompact(t *testing.T) {
|
|||
cmd := exec.Command(bd, "--json", "compact", "--dry-run")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd --json compact --dry-run failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd --json compact --dry-run failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
// Should produce some output without crashing
|
||||
_ = out
|
||||
_ = stdout.String()
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
54
cmd/bd/compact_tier2_embedded_test.go
Normal file
54
cmd/bd/compact_tier2_embedded_test.go
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestEmbeddedAdminCompactTier2Honesty verifies that the unimplemented Tier 2
|
||||
// is not advertised as a working capability: invoking it errors with a clear
|
||||
// "not yet implemented" message, and --stats does not promise Tier 2 savings.
|
||||
func TestEmbeddedAdminCompactTier2Honesty(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", "t2")
|
||||
|
||||
t.Run("tier2_rejected", func(t *testing.T) {
|
||||
// --analyze reaches the tier guard (read-only, direct-mode path).
|
||||
cmd := exec.Command(bd, "admin", "compact", "--analyze", "--tier", "2")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("expected --tier 2 to fail, but succeeded:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(string(out), "not yet implemented") {
|
||||
t.Errorf("expected 'not yet implemented' message, got:\n%s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stats_does_not_advertise_tier2", func(t *testing.T) {
|
||||
cmd := exec.Command(bd, "admin", "compact", "--stats")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd admin compact --stats failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "not yet implemented") {
|
||||
t.Errorf("expected Tier 2 to be marked 'not yet implemented' in --stats, got:\n%s", out)
|
||||
}
|
||||
if strings.Contains(out, "95%") {
|
||||
t.Errorf("--stats still advertises a Tier 2 savings estimate (95%%):\n%s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
461
cmd/bd/config.go
461
cmd/bd/config.go
|
|
@ -14,6 +14,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/remotecache"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
|
@ -28,6 +29,7 @@ Configuration is stored per-project in the beads database and is version-control
|
|||
|
||||
Common namespaces:
|
||||
- export.* Auto-export settings (stored in config.yaml)
|
||||
- import.* JSONL import settings (stored in config.yaml)
|
||||
- jira.* Jira integration settings
|
||||
- linear.* Linear integration settings
|
||||
- github.* GitHub integration settings
|
||||
|
|
@ -36,14 +38,25 @@ Common namespaces:
|
|||
- doctor.suppress.* Suppress specific bd doctor warnings (GH#1095)
|
||||
|
||||
Auto-Export (config.yaml):
|
||||
Writes .beads/issues.jsonl after every write command (throttled).
|
||||
Enabled by default. Useful for viewers (bv) and git-based sync.
|
||||
Optional JSONL export to .beads/issues.jsonl after write commands (throttled).
|
||||
Useful for viewers (bv), interchange, and issue-level migration; not a backup.
|
||||
It is not cross-machine sync; use bd dolt push/pull with a Dolt remote.
|
||||
Disabled by default. Enable only for integrations that need fresh JSONL.
|
||||
Auto-staging is separate and disabled by default.
|
||||
|
||||
Keys:
|
||||
export.auto Enable/disable auto-export (default: true)
|
||||
export.auto Enable/disable auto-export (default: false)
|
||||
export.path Output filename relative to .beads/ (default: issues.jsonl)
|
||||
export.interval Minimum time between exports (default: 60s)
|
||||
export.git-add Auto-stage the export file (default: true)
|
||||
export.git-add Auto-stage the export file (default: false)
|
||||
|
||||
Auto-Import (config.yaml):
|
||||
Reads .beads/issues.jsonl by default when a JSONL import path is implied.
|
||||
Use a relative filename/path so the import stays within the project .beads/
|
||||
directory and remains portable across machines.
|
||||
|
||||
Keys:
|
||||
import.path Input filename relative to .beads/ (default: issues.jsonl)
|
||||
|
||||
Custom Status States:
|
||||
You can define custom status states for multi-step pipelines using the
|
||||
|
|
@ -64,12 +77,16 @@ Suppressing Doctor Warnings:
|
|||
To unsuppress: bd config unset doctor.suppress.<slug>
|
||||
|
||||
Examples:
|
||||
bd config set export.auto false # Disable auto-export
|
||||
bd config set export.auto true # Enable auto-export for viewer integrations
|
||||
bd config set export.path "beads.jsonl" # Custom export filename
|
||||
bd config set import.path "beads.jsonl" # Custom import filename
|
||||
bd config set export.git-add true # Also stage the export file
|
||||
bd config set jira.url "https://company.atlassian.net"
|
||||
bd config set jira.project "PROJ"
|
||||
bd config set status.custom "awaiting_review,awaiting_testing"
|
||||
bd config set doctor.suppress.pending-migrations true
|
||||
bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu)
|
||||
bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init
|
||||
bd config get export.auto
|
||||
bd config list
|
||||
bd config unset jira.url`,
|
||||
|
|
@ -78,26 +95,33 @@ Examples:
|
|||
var forceGitTracked bool
|
||||
|
||||
var configSetCmd = &cobra.Command{
|
||||
Use: "set <key> <value>",
|
||||
Short: "Set a configuration value",
|
||||
Args: cobra.ExactArgs(2),
|
||||
Run: func(_ *cobra.Command, args []string) {
|
||||
Use: "set <key> <value>",
|
||||
Short: "Set a configuration value",
|
||||
Args: cobra.ExactArgs(2),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-set")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
key := args[0]
|
||||
value := args[1]
|
||||
|
||||
// Reject keys that look like init-only state so the user does not
|
||||
// silently land a write in a store that 'bd create' never reads.
|
||||
// 'bd config set issue-prefix' used to write DB key "issue-prefix"
|
||||
// (dash) while 'bd create' only reads YAML "issue-prefix" or DB
|
||||
// "issue_prefix" (underscore) — three divergent stores, write never
|
||||
// visible.
|
||||
if msg, rejected := rejectProtectedConfigKey(key); rejected {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
os.Exit(1)
|
||||
return SilentExit()
|
||||
}
|
||||
|
||||
if key == "dolt.debug" && !usesSQLServer() {
|
||||
fmt.Fprintln(os.Stderr, "Error: dolt.debug requires a sql-server-backed project (embedded mode has no managed server).")
|
||||
fmt.Fprintln(os.Stderr, " To migrate: re-init with 'bd init --server' or 'bd init --shared-server'.")
|
||||
return SilentExit()
|
||||
}
|
||||
|
||||
// Warn on unrecognized config keys so typos don't silently become
|
||||
// no-ops. The custom.* namespace is exempt (user-extensible). GH#3293.
|
||||
if !isRecognizedConfigKey(key) {
|
||||
suggestion := suggestConfigKey(key)
|
||||
if suggestion != "" {
|
||||
|
|
@ -108,126 +132,158 @@ var configSetCmd = &cobra.Command{
|
|||
fmt.Fprintf(os.Stderr, "Run 'bd config --help' for valid namespaces.\n")
|
||||
}
|
||||
|
||||
// Refuse to write secret keys to git-tracked config files unless
|
||||
// --force-git-tracked is set. This prevents accidental exposure of
|
||||
// API keys and tokens in git history.
|
||||
if !forceGitTracked {
|
||||
if err := config.CheckSecretKeyGitSafety(key); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is a yaml-only key (startup settings like no-db, etc.)
|
||||
// These must be written to config.yaml, not SQLite, because they're read
|
||||
// before the database is opened. (GH#536)
|
||||
if config.IsYamlOnlyKey(key) {
|
||||
if err := config.SetYamlConfig(key, value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting config: %v\n", err)
|
||||
os.Exit(1)
|
||||
var setErr error
|
||||
location := "config.yaml"
|
||||
if config.IsUserGlobalKey(key) {
|
||||
setErr = config.SetUserYamlConfig(key, value)
|
||||
location = config.UserConfigYamlPath()
|
||||
} else {
|
||||
setErr = config.SetYamlConfig(key, value)
|
||||
}
|
||||
if setErr != nil {
|
||||
return HandleError("setting config: %v", setErr)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"value": value,
|
||||
"location": "config.yaml",
|
||||
})
|
||||
"location": location,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Set %s = %s (in config.yaml)\n", key, value)
|
||||
fmt.Printf("Set %s = %s (in %s)\n", key, value, location)
|
||||
}
|
||||
printConfigSideEffects(checkConfigSetSideEffects(key, value))
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// beads.role is stored in git config, not SQLite (GH#1531).
|
||||
// bd doctor reads it from git config, so we write there for consistency.
|
||||
if key == "beads.role" {
|
||||
validRoles := map[string]bool{"maintainer": true, "contributor": true}
|
||||
if !validRoles[value] {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid role %q (valid values: maintainer, contributor)\n", value)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid role %q (valid values: maintainer, contributor)", value)
|
||||
}
|
||||
cmd := exec.Command("git", "config", "beads.role", value) //nolint:gosec // value is validated against allowlist above
|
||||
if err := cmd.Run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting beads.role in git config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("setting beads.role in git config: %v", err)
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"value": value,
|
||||
"location": "git config",
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Set %s = %s (in git config)\n", key, value)
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if usesProxiedServer() {
|
||||
runConfigSetProxiedServer(rootCtx, key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Database-stored config requires direct mode
|
||||
if err := ensureDirectMode("config set requires direct database access"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
// Validate status.custom config before writing
|
||||
if key == "status.custom" && value != "" {
|
||||
if _, err := types.ParseCustomStatusConfig(value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid status.custom value: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid status.custom value: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := store.SetConfig(ctx, key, value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("setting config: %v", err)
|
||||
}
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{
|
||||
if err := outputJSON(map[string]string{
|
||||
"key": key,
|
||||
"value": value,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Set %s = %s\n", key, value)
|
||||
}
|
||||
printConfigSideEffects(checkConfigSetSideEffects(key, value))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var configGetCmd = &cobra.Command{
|
||||
Use: "get <key>",
|
||||
Short: "Get a configuration value",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Use: "get <key>",
|
||||
Short: "Get a configuration value",
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-get")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
key := args[0]
|
||||
|
||||
// Check if this is a yaml-only key (startup settings)
|
||||
// These are read from config.yaml via viper, not SQLite. (GH#536)
|
||||
if config.IsYamlOnlyKey(key) {
|
||||
// User-global keys (e.g. metrics.*) must be read from the user-global
|
||||
// config.yaml only — the same source the runtime uses for metrics
|
||||
// consent and endpoint. Reading the merged value here would let a
|
||||
// project's .beads/config.yaml shadow the effective value and report the
|
||||
// opposite of what `bd metrics` actually honors.
|
||||
if config.IsUserGlobalKey(key) {
|
||||
value := config.GetUserYamlConfig(key)
|
||||
location := config.UserConfigYamlPath()
|
||||
if jsonOutput {
|
||||
return outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"value": value,
|
||||
"location": location,
|
||||
})
|
||||
}
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set in %s)\n", key, location)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
value := config.GetYamlConfig(key)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"value": value,
|
||||
"location": "config.yaml",
|
||||
})
|
||||
} else {
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set in config.yaml)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
}
|
||||
return
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set in config.yaml)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// beads.role is stored in git config, not SQLite (GH#1531).
|
||||
if key == "beads.role" {
|
||||
cmd := exec.Command("git", "config", "--get", "beads.role")
|
||||
output, err := cmd.Output()
|
||||
|
|
@ -236,25 +292,28 @@ var configGetCmd = &cobra.Command{
|
|||
value = ""
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"value": value,
|
||||
"location": "git config",
|
||||
})
|
||||
} else {
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set in git config)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
}
|
||||
return
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set in git config)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if usesProxiedServer() {
|
||||
runConfigGetProxiedServer(rootCtx, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Database-stored config requires direct mode
|
||||
if err := ensureDirectMode("config get requires direct database access"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
|
@ -264,53 +323,62 @@ var configGetCmd = &cobra.Command{
|
|||
value, err = store.GetConfig(ctx, key)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error getting config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("getting config: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{
|
||||
return outputJSON(map[string]string{
|
||||
"key": key,
|
||||
"value": value,
|
||||
})
|
||||
} else {
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var configListCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List all configuration",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Use: "list",
|
||||
Short: "List all configuration",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-list")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if usesProxiedServer() {
|
||||
runConfigListProxiedServer(rootCtx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Config operations work in direct mode only
|
||||
if err := ensureDirectMode("config list requires direct database access"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
config, err := store.GetAllConfig(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error listing config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("listing config: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(config)
|
||||
return
|
||||
return outputJSON(config)
|
||||
}
|
||||
|
||||
if len(config) == 0 {
|
||||
fmt.Println("No configuration set")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sort keys for consistent output
|
||||
keys := make([]string, 0, len(config))
|
||||
for k := range config {
|
||||
keys = append(keys, k)
|
||||
|
|
@ -322,9 +390,8 @@ var configListCmd = &cobra.Command{
|
|||
fmt.Printf(" %s = %s\n", k, config[k])
|
||||
}
|
||||
|
||||
// Check for config.yaml overrides that take precedence (bd-20j)
|
||||
// This helps diagnose when effective config differs from database config
|
||||
showConfigYAMLOverrides(config)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -401,71 +468,93 @@ func showConfigYAMLOverrides(dbConfig map[string]string) {
|
|||
}
|
||||
|
||||
var configUnsetCmd = &cobra.Command{
|
||||
Use: "unset <key>",
|
||||
Short: "Delete a configuration value",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
Use: "unset <key>",
|
||||
Short: "Delete a configuration value",
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-unset")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
key := args[0]
|
||||
|
||||
// Check if this is a yaml-only key (startup settings like backup.*, routing.*, etc.)
|
||||
// These must be removed from config.yaml, not the database. (GH#2727)
|
||||
if config.IsYamlOnlyKey(key) {
|
||||
if err := config.UnsetYamlConfig(key); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error unsetting config: %v\n", err)
|
||||
os.Exit(1)
|
||||
location := "config.yaml"
|
||||
var unsetErr error
|
||||
if config.IsUserGlobalKey(key) {
|
||||
unsetErr = config.UnsetUserYamlConfig(key)
|
||||
location = config.UserConfigYamlPath()
|
||||
} else {
|
||||
unsetErr = config.UnsetYamlConfig(key)
|
||||
}
|
||||
if unsetErr != nil {
|
||||
return HandleError("unsetting config: %v", unsetErr)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"location": "config.yaml",
|
||||
})
|
||||
"location": location,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Unset %s (in config.yaml)\n", key)
|
||||
fmt.Printf("Unset %s (in %s)\n", key, location)
|
||||
}
|
||||
printConfigSideEffects(checkConfigUnsetSideEffects(key))
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// beads.role is stored in git config, not the database (GH#1531).
|
||||
if key == "beads.role" {
|
||||
gitCmd := exec.Command("git", "config", "--unset", "beads.role")
|
||||
if err := gitCmd.Run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error unsetting beads.role in git config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("unsetting beads.role in git config: %v", err)
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]interface{}{
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
"location": "git config",
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Unset %s (in git config)\n", key)
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if usesProxiedServer() {
|
||||
runConfigUnsetProxiedServer(rootCtx, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Database-stored config requires direct mode
|
||||
if err := ensureDirectMode("config unset requires direct database access"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
if err := store.DeleteConfig(ctx, key); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error deleting config: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("deleting config: %v", err)
|
||||
}
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{
|
||||
if err := outputJSON(map[string]string{
|
||||
"key": key,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Unset %s\n", key)
|
||||
}
|
||||
printConfigSideEffects(checkConfigUnsetSideEffects(key))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -483,38 +572,41 @@ Checks:
|
|||
Examples:
|
||||
bd config validate
|
||||
bd config validate --json`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-validate")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
repoPath, err := resolvedConfigRepoRoot()
|
||||
if err != nil {
|
||||
FatalErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint())
|
||||
return HandleErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint())
|
||||
}
|
||||
|
||||
// Run the existing doctor config values check
|
||||
doctorCheck := doctor.CheckConfigValues(repoPath)
|
||||
|
||||
// Run additional sync-related validations
|
||||
syncIssues := validateSyncConfig(repoPath)
|
||||
|
||||
// Combine results
|
||||
allIssues := []string{}
|
||||
if doctorCheck.Detail != "" {
|
||||
allIssues = append(allIssues, strings.Split(doctorCheck.Detail, "\n")...)
|
||||
}
|
||||
allIssues = append(allIssues, syncIssues...)
|
||||
|
||||
// Output results
|
||||
if jsonOutput {
|
||||
result := map[string]interface{}{
|
||||
return outputJSON(map[string]interface{}{
|
||||
"valid": len(allIssues) == 0,
|
||||
"issues": allIssues,
|
||||
}
|
||||
outputJSON(result)
|
||||
return
|
||||
})
|
||||
}
|
||||
|
||||
if len(allIssues) == 0 {
|
||||
fmt.Println("✓ All sync-related configuration is valid")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println("Configuration validation found issues:")
|
||||
|
|
@ -524,7 +616,7 @@ Checks:
|
|||
}
|
||||
}
|
||||
fmt.Println("\nRun 'bd config set <key> <value>' to fix configuration issues.")
|
||||
os.Exit(1)
|
||||
return SilentExit()
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -634,9 +726,17 @@ calls, especially in CI.
|
|||
Examples:
|
||||
bd config set-many ado.state_map.open=New ado.state_map.closed=Closed
|
||||
bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(_ *cobra.Command, args []string) {
|
||||
// Phase 1: Parse all key=value pairs
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("config-set-many")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
type kvPair struct {
|
||||
key, value string
|
||||
}
|
||||
|
|
@ -644,30 +744,25 @@ Examples:
|
|||
for _, arg := range args {
|
||||
idx := strings.Index(arg, "=")
|
||||
if idx <= 0 {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid argument %q (expected key=value format)\n", arg)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid argument %q (expected key=value format)", arg)
|
||||
}
|
||||
pairs = append(pairs, kvPair{key: arg[:idx], value: arg[idx+1:]})
|
||||
}
|
||||
|
||||
// Phase 2: Validate all pairs before writing any
|
||||
for _, p := range pairs {
|
||||
if p.key == "beads.role" {
|
||||
validRoles := map[string]bool{"maintainer": true, "contributor": true}
|
||||
if !validRoles[p.value] {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid role %q (valid values: maintainer, contributor)\n", p.value)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid role %q (valid values: maintainer, contributor)", p.value)
|
||||
}
|
||||
}
|
||||
if p.key == "status.custom" && p.value != "" {
|
||||
if _, err := types.ParseCustomStatusConfig(p.value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid status.custom value: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("invalid status.custom value: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3: Separate into categories
|
||||
var yamlPairs, gitPairs, dbPairs []kvPair
|
||||
for _, p := range pairs {
|
||||
if config.IsYamlOnlyKey(p.key) {
|
||||
|
|
@ -679,56 +774,64 @@ Examples:
|
|||
}
|
||||
}
|
||||
|
||||
// Phase 3b: Check git-tracked secret safety for yaml keys
|
||||
if !forceGitTracked {
|
||||
for _, p := range yamlPairs {
|
||||
if err := config.CheckSecretKeyGitSafety(p.key); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 4: Write yaml-only keys
|
||||
for _, p := range yamlPairs {
|
||||
if err := config.SetYamlConfig(p.key, p.value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting config %s: %v\n", p.key, err)
|
||||
os.Exit(1)
|
||||
var setErr error
|
||||
if config.IsUserGlobalKey(p.key) {
|
||||
setErr = config.SetUserYamlConfig(p.key, p.value)
|
||||
} else {
|
||||
setErr = config.SetYamlConfig(p.key, p.value)
|
||||
}
|
||||
if setErr != nil {
|
||||
return HandleError("setting config %s: %v", p.key, setErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: Write git config keys
|
||||
for _, p := range gitPairs {
|
||||
cmd := exec.Command("git", "config", "beads.role", p.value) //nolint:gosec // value is validated against allowlist above
|
||||
if err := cmd.Run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting %s in git config: %v\n", p.key, err)
|
||||
os.Exit(1)
|
||||
return HandleError("setting %s in git config: %v", p.key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 6: Write DB keys in batch
|
||||
if len(dbPairs) > 0 {
|
||||
if err := ensureDirectMode("config set-many requires direct database access"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
for _, p := range dbPairs {
|
||||
if err := store.SetConfig(ctx, p.key, p.value); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error setting config %s: %v\n", p.key, err)
|
||||
os.Exit(1)
|
||||
if usesProxiedServer() {
|
||||
keys := make([]string, len(dbPairs))
|
||||
values := make([]string, len(dbPairs))
|
||||
for i, p := range dbPairs {
|
||||
keys[i] = p.key
|
||||
values[i] = p.value
|
||||
}
|
||||
runConfigSetManyProxiedServer(rootCtx, keys, values)
|
||||
} else {
|
||||
if err := ensureDirectMode("config set-many requires direct database access"); err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
for _, p := range dbPairs {
|
||||
if err := store.SetConfig(ctx, p.key, p.value); err != nil {
|
||||
return HandleError("setting config %s: %v", p.key, err)
|
||||
}
|
||||
}
|
||||
commandDidWrite.Store(true)
|
||||
}
|
||||
commandDidWrite.Store(true)
|
||||
}
|
||||
|
||||
// Phase 7: Output results
|
||||
if jsonOutput {
|
||||
results := make([]map[string]string, 0, len(pairs))
|
||||
for _, p := range pairs {
|
||||
location := "database"
|
||||
if config.IsYamlOnlyKey(p.key) {
|
||||
if config.IsUserGlobalKey(p.key) {
|
||||
location = config.UserConfigYamlPath()
|
||||
} else if config.IsYamlOnlyKey(p.key) {
|
||||
location = "config.yaml"
|
||||
} else if p.key == "beads.role" {
|
||||
location = "git config"
|
||||
|
|
@ -739,11 +842,15 @@ Examples:
|
|||
"location": location,
|
||||
})
|
||||
}
|
||||
outputJSON(results)
|
||||
if err := outputJSON(results); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
for _, p := range pairs {
|
||||
location := ""
|
||||
if config.IsYamlOnlyKey(p.key) {
|
||||
if config.IsUserGlobalKey(p.key) {
|
||||
location = fmt.Sprintf(" (in %s)", config.UserConfigYamlPath())
|
||||
} else if config.IsYamlOnlyKey(p.key) {
|
||||
location = " (in config.yaml)"
|
||||
} else if p.key == "beads.role" {
|
||||
location = " (in git config)"
|
||||
|
|
@ -751,16 +858,17 @@ Examples:
|
|||
fmt.Printf("Set %s = %s%s\n", p.key, p.value, location)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// recognizedConfigPrefixes lists valid top-level config namespaces.
|
||||
// Keys under custom.* are always accepted (user-extensible).
|
||||
var recognizedConfigPrefixes = []string{
|
||||
"export.", "dolt.", "jira.", "linear.", "github.", "custom.",
|
||||
"export.", "import.", "dolt.", "jira.", "linear.", "github.", "custom.",
|
||||
"status.", "doctor.suppress.", "routing.", "sync.", "git.",
|
||||
"directory.", "repos.", "external_projects.", "validation.",
|
||||
"hierarchy.", "ai.", "backup.", "federation.",
|
||||
"hierarchy.", "ai.", "backup.", "federation.", "metrics.",
|
||||
}
|
||||
|
||||
// recognizedConfigKeys lists valid non-namespaced config keys.
|
||||
|
|
@ -770,6 +878,7 @@ var recognizedConfigKeys = map[string]bool{
|
|||
"create.require-description": true, "beads.role": true,
|
||||
"auto_compact_enabled": true, "schema_version": true,
|
||||
"output.title-length": true,
|
||||
"prime.max-memories": true, "prime.max-memory-chars": true,
|
||||
}
|
||||
|
||||
func isRecognizedConfigKey(key string) bool {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/storage/doltutil"
|
||||
)
|
||||
|
||||
|
|
@ -47,21 +51,33 @@ Examples:
|
|||
bd config apply
|
||||
bd config apply --dry-run
|
||||
bd config apply --json`,
|
||||
Run: func(cmd *cobra.Command, _ []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("config-apply")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
||||
results := runApply(dryRun)
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(results)
|
||||
if err := outputJSON(results); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
printApplyResults(results)
|
||||
}
|
||||
|
||||
for _, r := range results {
|
||||
if r.Status == applyStatusError {
|
||||
os.Exit(1)
|
||||
return SilentExit()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -76,20 +92,82 @@ func runApply(dryRun bool) []ApplyResult {
|
|||
|
||||
// Group drift items by check domain to avoid duplicate actions
|
||||
// (e.g., multiple hook items should trigger only one reinstall).
|
||||
hasDrift := map[string]bool{}
|
||||
for _, item := range driftItems {
|
||||
if item.Status == driftStatusDrift {
|
||||
hasDrift[item.Check] = true
|
||||
}
|
||||
}
|
||||
hasDrift := driftDomains(driftItems)
|
||||
|
||||
var results []ApplyResult
|
||||
results = append(results, applyHooks(hasDrift["hooks"], dryRun))
|
||||
results = append(results, applyRemote(hasDrift["remote"], dryRun))
|
||||
results = append(results, applyServer(hasDrift["server"], dryRun))
|
||||
serverResult := applyServer(hasDrift["server"], dryRun)
|
||||
results = append(results, serverResult)
|
||||
results = append(results, remoteApplyResult(driftItems, serverResult, dryRun, checkRemoteDrift))
|
||||
return results
|
||||
}
|
||||
|
||||
func shouldRecheckRemoteAfterServerStart(remoteSkipped bool, serverResult ApplyResult) bool {
|
||||
return remoteSkipped && serverResult.Check == "server" && serverResult.Status == applyStatusApplied
|
||||
}
|
||||
|
||||
func remoteApplyResult(driftItems []DriftItem, serverResult ApplyResult, dryRun bool, recheckRemote func() []DriftItem) ApplyResult {
|
||||
remoteItems := driftItems
|
||||
if shouldRecheckRemoteAfterServerStart(skippedDriftDomain(remoteItems, "remote"), serverResult) {
|
||||
remoteItems = recheckRemote()
|
||||
}
|
||||
if skipped := skippedDriftItem(remoteItems, "remote"); skipped != nil {
|
||||
return skippedRemoteApplyResult(*skipped)
|
||||
}
|
||||
return applyRemote(driftDomains(remoteItems)["remote"], dryRun)
|
||||
}
|
||||
|
||||
func driftDomains(items []DriftItem) map[string]bool {
|
||||
hasDrift := map[string]bool{}
|
||||
for _, item := range items {
|
||||
if item.Status == driftStatusDrift {
|
||||
hasDrift[driftDomain(item.Check)] = true
|
||||
}
|
||||
}
|
||||
return hasDrift
|
||||
}
|
||||
|
||||
func skippedDriftDomain(items []DriftItem, domain string) bool {
|
||||
return skippedDriftItem(items, domain) != nil
|
||||
}
|
||||
|
||||
func skippedDriftItem(items []DriftItem, domain string) *DriftItem {
|
||||
for _, item := range items {
|
||||
if item.Status == driftStatusSkipped && driftDomain(item.Check) == domain {
|
||||
skipped := item
|
||||
return &skipped
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func driftDomain(check string) string {
|
||||
if before, _, ok := strings.Cut(check, "."); ok {
|
||||
return before
|
||||
}
|
||||
return check
|
||||
}
|
||||
|
||||
func skippedRemoteApplyResult(item DriftItem) ApplyResult {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "none",
|
||||
Status: applyStatusSkipped,
|
||||
Message: item.Message,
|
||||
}
|
||||
}
|
||||
|
||||
func remoteApplyStoreConfig(dryRun bool) *dolt.Config {
|
||||
return &dolt.Config{
|
||||
ReadOnly: dryRun,
|
||||
DisableAutoStart: true,
|
||||
}
|
||||
}
|
||||
|
||||
func remoteURLMatchesConfig(currentURL, configuredURL string) bool {
|
||||
return doltutil.RemoteURLsMatch(currentURL, configuredURL)
|
||||
}
|
||||
|
||||
// applyHooks reinstalls git hooks if drift was detected.
|
||||
func applyHooks(drifted bool, dryRun bool) ApplyResult {
|
||||
if !drifted {
|
||||
|
|
@ -169,8 +247,36 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
|
|||
}
|
||||
}
|
||||
|
||||
doltDir := doltserver.ResolveDoltDir(beadsDir)
|
||||
currentURL := doltutil.FindCLIRemote(doltDir, "origin")
|
||||
ctx := context.Background()
|
||||
st, err := dolt.NewFromConfigWithOptions(ctx, beadsDir, remoteApplyStoreConfig(dryRun))
|
||||
if err != nil {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "configure",
|
||||
Status: applyStatusError,
|
||||
Message: "Failed to open Dolt store",
|
||||
Error: err.Error(),
|
||||
}
|
||||
}
|
||||
defer func() { _ = st.Close() }()
|
||||
|
||||
remotes, err := st.ListRemotes(ctx)
|
||||
if err != nil {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "configure",
|
||||
Status: applyStatusError,
|
||||
Message: "Failed to list Dolt remotes",
|
||||
Error: err.Error(),
|
||||
}
|
||||
}
|
||||
var currentURL string
|
||||
for _, r := range remotes {
|
||||
if r.Name == "origin" {
|
||||
currentURL = r.URL
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if dryRun {
|
||||
if currentURL == "" {
|
||||
|
|
@ -181,6 +287,14 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
|
|||
Message: fmt.Sprintf("Would add Dolt origin remote: %s", federationRemote),
|
||||
}
|
||||
}
|
||||
if remoteURLMatchesConfig(currentURL, federationRemote) {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "none",
|
||||
Status: applyStatusOK,
|
||||
Message: "Dolt remote configuration is consistent",
|
||||
}
|
||||
}
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "update_remote",
|
||||
|
|
@ -190,8 +304,7 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
|
|||
}
|
||||
|
||||
if currentURL == "" {
|
||||
// No origin exists — add it
|
||||
if err := doltutil.AddCLIRemote(doltDir, "origin", federationRemote); err != nil {
|
||||
if err := st.AddRemote(ctx, "origin", federationRemote); err != nil {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "add_remote",
|
||||
|
|
@ -208,10 +321,17 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
|
|||
}
|
||||
}
|
||||
|
||||
// Origin exists but wrong URL — remove then re-add
|
||||
// Save old URL in case we need to report it
|
||||
if remoteURLMatchesConfig(currentURL, federationRemote) {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "none",
|
||||
Status: applyStatusOK,
|
||||
Message: "Dolt remote configuration is consistent",
|
||||
}
|
||||
}
|
||||
|
||||
oldURL := currentURL
|
||||
if err := doltutil.RemoveCLIRemote(doltDir, "origin"); err != nil {
|
||||
if err := st.RemoveRemote(ctx, "origin"); err != nil {
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "update_remote",
|
||||
|
|
@ -221,9 +341,8 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
|
|||
}
|
||||
}
|
||||
|
||||
if err := doltutil.AddCLIRemote(doltDir, "origin", federationRemote); err != nil {
|
||||
// Try to restore the old remote on failure
|
||||
_ = doltutil.AddCLIRemote(doltDir, "origin", oldURL)
|
||||
if err := st.AddRemote(ctx, "origin", federationRemote); err != nil {
|
||||
_ = st.AddRemote(ctx, "origin", oldURL)
|
||||
return ApplyResult{
|
||||
Check: "remote",
|
||||
Action: "update_remote",
|
||||
|
|
|
|||
|
|
@ -43,6 +43,60 @@ func TestApplyRemoteDryRun(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRemoteApplyStoreConfigUsesReadOnlyForDryRun(t *testing.T) {
|
||||
dryRunConfig := remoteApplyStoreConfig(true)
|
||||
if !dryRunConfig.ReadOnly {
|
||||
t.Fatal("dry-run remote apply must open the Dolt store read-only")
|
||||
}
|
||||
if !dryRunConfig.DisableAutoStart {
|
||||
t.Fatal("remote apply diagnostics must not auto-start Dolt")
|
||||
}
|
||||
|
||||
applyConfig := remoteApplyStoreConfig(false)
|
||||
if applyConfig.ReadOnly {
|
||||
t.Fatal("non-dry-run remote apply must remain writable")
|
||||
}
|
||||
if !applyConfig.DisableAutoStart {
|
||||
t.Fatal("remote apply writes must not auto-start Dolt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteURLMatchesConfigNormalizesEquivalentGitURLs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
current string
|
||||
configured string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "https normalized to git https",
|
||||
current: "git+https://github.com/gastownhall/beads.git",
|
||||
configured: "https://github.com/gastownhall/beads.git",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "ssh normalized to git ssh",
|
||||
current: "git+ssh://github.com/gastownhall/beads.git",
|
||||
configured: "ssh://github.com/gastownhall/beads.git",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "different repos still differ",
|
||||
current: "git+https://github.com/gastownhall/beads.git",
|
||||
configured: "https://github.com/gastownhall/other.git",
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := remoteURLMatchesConfig(tt.current, tt.configured); got != tt.want {
|
||||
t.Fatalf("remoteURLMatchesConfig(%q, %q) = %v, want %v", tt.current, tt.configured, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyServerNoDrift(t *testing.T) {
|
||||
result := applyServer(false, false)
|
||||
if result.Status != applyStatusOK {
|
||||
|
|
@ -101,6 +155,118 @@ func TestRunApplyDryRun(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestDriftDomainsGroupsDottedChecks(t *testing.T) {
|
||||
items := []DriftItem{
|
||||
{Check: "hooks.missing", Status: driftStatusDrift},
|
||||
{Check: "remote", Status: driftStatusDrift},
|
||||
{Check: "server", Status: driftStatusOK},
|
||||
}
|
||||
got := driftDomains(items)
|
||||
if !got["hooks"] {
|
||||
t.Fatal("expected hooks.missing drift to mark hooks domain drifted")
|
||||
}
|
||||
if !got["remote"] {
|
||||
t.Fatal("expected remote drift to mark remote domain drifted")
|
||||
}
|
||||
if got["server"] {
|
||||
t.Fatal("did not expect ok server check to mark server domain drifted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldRecheckRemoteAfterServerStart(t *testing.T) {
|
||||
appliedServer := ApplyResult{Check: "server", Status: applyStatusApplied}
|
||||
if !shouldRecheckRemoteAfterServerStart(true, appliedServer) {
|
||||
t.Fatal("expected remote recheck after skipped remote drift and applied server start")
|
||||
}
|
||||
dryRunServer := ApplyResult{Check: "server", Status: applyStatusDryRun}
|
||||
if shouldRecheckRemoteAfterServerStart(true, dryRunServer) {
|
||||
t.Fatal("did not expect remote recheck when server was not actually started")
|
||||
}
|
||||
if shouldRecheckRemoteAfterServerStart(false, appliedServer) {
|
||||
t.Fatal("did not expect remote recheck when initial remote drift was not skipped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteApplyResultPreservesSkippedRemoteWithoutRecheck(t *testing.T) {
|
||||
skippedRemote := DriftItem{
|
||||
Check: "remote",
|
||||
Status: driftStatusSkipped,
|
||||
Message: "Cannot open Dolt store: server unavailable",
|
||||
}
|
||||
serverOK := ApplyResult{Check: "server", Status: applyStatusOK}
|
||||
|
||||
result := remoteApplyResult([]DriftItem{skippedRemote}, serverOK, false, func() []DriftItem {
|
||||
t.Fatal("remote should not be rechecked unless the server was started")
|
||||
return nil
|
||||
})
|
||||
|
||||
if result.Check != "remote" {
|
||||
t.Fatalf("expected remote result, got %q", result.Check)
|
||||
}
|
||||
if result.Status != applyStatusSkipped {
|
||||
t.Fatalf("expected skipped remote result, got %q", result.Status)
|
||||
}
|
||||
if result.Message != skippedRemote.Message {
|
||||
t.Fatalf("message = %q, want %q", result.Message, skippedRemote.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteApplyResultPreservesSkippedRemoteAfterRecheck(t *testing.T) {
|
||||
initialSkipped := DriftItem{
|
||||
Check: "remote",
|
||||
Status: driftStatusSkipped,
|
||||
Message: "Cannot open Dolt store: server unavailable",
|
||||
}
|
||||
recheckedSkipped := DriftItem{
|
||||
Check: "remote",
|
||||
Status: driftStatusSkipped,
|
||||
Message: "Cannot list remotes: access denied",
|
||||
}
|
||||
serverApplied := ApplyResult{Check: "server", Status: applyStatusApplied}
|
||||
rechecked := false
|
||||
|
||||
result := remoteApplyResult([]DriftItem{initialSkipped}, serverApplied, false, func() []DriftItem {
|
||||
rechecked = true
|
||||
return []DriftItem{recheckedSkipped}
|
||||
})
|
||||
|
||||
if !rechecked {
|
||||
t.Fatal("expected remote recheck after server start")
|
||||
}
|
||||
if result.Status != applyStatusSkipped {
|
||||
t.Fatalf("expected skipped remote result, got %q", result.Status)
|
||||
}
|
||||
if result.Message != recheckedSkipped.Message {
|
||||
t.Fatalf("message = %q, want %q", result.Message, recheckedSkipped.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteApplyResultUsesSuccessfulRemoteRecheck(t *testing.T) {
|
||||
initialSkipped := DriftItem{
|
||||
Check: "remote",
|
||||
Status: driftStatusSkipped,
|
||||
Message: "Cannot open Dolt store: server unavailable",
|
||||
}
|
||||
serverApplied := ApplyResult{Check: "server", Status: applyStatusApplied}
|
||||
rechecked := false
|
||||
|
||||
result := remoteApplyResult([]DriftItem{initialSkipped}, serverApplied, false, func() []DriftItem {
|
||||
rechecked = true
|
||||
return []DriftItem{{
|
||||
Check: "remote",
|
||||
Status: driftStatusOK,
|
||||
Message: "Dolt origin remote matches federation.remote",
|
||||
}}
|
||||
})
|
||||
|
||||
if !rechecked {
|
||||
t.Fatal("expected remote recheck after server start")
|
||||
}
|
||||
if result.Status != applyStatusOK {
|
||||
t.Fatalf("expected ok remote result after successful recheck, got %q", result.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintApplyResults(t *testing.T) {
|
||||
// Smoke test — just ensure no panic
|
||||
results := []ApplyResult{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -13,7 +14,8 @@ import (
|
|||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/doltutil"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
)
|
||||
|
||||
// DriftItem represents a single drift check result.
|
||||
|
|
@ -52,21 +54,32 @@ Exit codes:
|
|||
Examples:
|
||||
bd config drift
|
||||
bd config drift --json`,
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(_ *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("config-drift")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
items := runDriftChecks()
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(items)
|
||||
if err := outputJSON(items); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
printDriftItems(items)
|
||||
}
|
||||
|
||||
// Exit 1 if any drift detected
|
||||
for _, item := range items {
|
||||
if item.Status == driftStatusDrift {
|
||||
os.Exit(1)
|
||||
return SilentExit()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -153,9 +166,21 @@ func checkRemoteDrift() []DriftItem {
|
|||
}}
|
||||
}
|
||||
|
||||
doltDir := doltserver.ResolveDoltDir(beadsDir)
|
||||
ctx := context.Background()
|
||||
st, err := dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{
|
||||
ReadOnly: true,
|
||||
DisableAutoStart: true,
|
||||
})
|
||||
if err != nil {
|
||||
return []DriftItem{{
|
||||
Check: "remote",
|
||||
Status: driftStatusSkipped,
|
||||
Message: fmt.Sprintf("Cannot open Dolt store: %v", err),
|
||||
}}
|
||||
}
|
||||
defer func() { _ = st.Close() }()
|
||||
|
||||
cliRemotes, err := doltutil.ListCLIRemotes(doltDir)
|
||||
remotes, err := st.ListRemotes(ctx)
|
||||
if err != nil {
|
||||
return []DriftItem{{
|
||||
Check: "remote",
|
||||
|
|
@ -164,9 +189,8 @@ func checkRemoteDrift() []DriftItem {
|
|||
}}
|
||||
}
|
||||
|
||||
// Find the "origin" remote (the conventional default)
|
||||
var originURL string
|
||||
for _, r := range cliRemotes {
|
||||
for _, r := range remotes {
|
||||
if r.Name == "origin" {
|
||||
originURL = r.URL
|
||||
break
|
||||
|
|
@ -185,7 +209,7 @@ func checkRemoteDrift() []DriftItem {
|
|||
}
|
||||
|
||||
// Case 2: federation.remote set, origin exists but doesn't match
|
||||
if federationRemote != "" && originURL != "" && originURL != federationRemote {
|
||||
if federationRemote != "" && originURL != "" && !remoteURLMatchesConfig(originURL, federationRemote) {
|
||||
return []DriftItem{{
|
||||
Check: "remote",
|
||||
Status: driftStatusDrift,
|
||||
|
|
@ -196,7 +220,7 @@ func checkRemoteDrift() []DriftItem {
|
|||
}
|
||||
|
||||
// Case 3: federation.remote set and matches origin
|
||||
if federationRemote != "" && originURL == federationRemote {
|
||||
if federationRemote != "" && remoteURLMatchesConfig(originURL, federationRemote) {
|
||||
return []DriftItem{{
|
||||
Check: "remote",
|
||||
Status: driftStatusOK,
|
||||
|
|
@ -205,9 +229,9 @@ func checkRemoteDrift() []DriftItem {
|
|||
}
|
||||
|
||||
// Case 4: federation.remote not set but remotes exist
|
||||
if federationRemote == "" && len(cliRemotes) > 0 {
|
||||
names := make([]string, len(cliRemotes))
|
||||
for i, r := range cliRemotes {
|
||||
if federationRemote == "" && len(remotes) > 0 {
|
||||
names := make([]string, len(remotes))
|
||||
for i, r := range remotes {
|
||||
names[i] = r.Name
|
||||
}
|
||||
return []DriftItem{{
|
||||
|
|
|
|||
|
|
@ -5,11 +5,20 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
)
|
||||
|
||||
func chdirForDriftTest(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
t.Chdir(dir)
|
||||
git.ResetCaches()
|
||||
t.Cleanup(git.ResetCaches)
|
||||
}
|
||||
|
||||
// TestCheckHooksDriftNotGitRepo verifies hooks check skips when not in a git repo.
|
||||
func TestCheckHooksDriftNotGitRepo(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
chdirForDriftTest(t, t.TempDir())
|
||||
|
||||
items := checkHooksDrift()
|
||||
if len(items) != 1 {
|
||||
|
|
@ -25,7 +34,7 @@ func TestCheckHooksDriftNotGitRepo(t *testing.T) {
|
|||
|
||||
// TestCheckServerDriftNoBeadsDir verifies server check skips when no .beads exists.
|
||||
func TestCheckServerDriftNoBeadsDir(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
chdirForDriftTest(t, t.TempDir())
|
||||
|
||||
items := checkServerDrift()
|
||||
if len(items) != 1 {
|
||||
|
|
@ -38,7 +47,7 @@ func TestCheckServerDriftNoBeadsDir(t *testing.T) {
|
|||
|
||||
// TestCheckRemoteDriftNoBeadsDir verifies remote check skips when no .beads exists.
|
||||
func TestCheckRemoteDriftNoBeadsDir(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
chdirForDriftTest(t, t.TempDir())
|
||||
|
||||
items := checkRemoteDrift()
|
||||
if len(items) != 1 {
|
||||
|
|
@ -117,7 +126,7 @@ func TestDriftItemStatuses(t *testing.T) {
|
|||
// TestRunDriftChecksReturnsResults verifies the aggregator returns results from all checks.
|
||||
func TestRunDriftChecksReturnsResults(t *testing.T) {
|
||||
// When run from a non-beads directory, we should still get results (skipped checks)
|
||||
t.Chdir(t.TempDir())
|
||||
chdirForDriftTest(t, t.TempDir())
|
||||
|
||||
items := runDriftChecks()
|
||||
if len(items) == 0 {
|
||||
|
|
|
|||
|
|
@ -19,11 +19,11 @@ func bdConfig(t *testing.T, bd, dir string, args ...string) string {
|
|||
cmd := exec.Command(bd, fullArgs...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd config %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
t.Fatalf("bd config %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
|
||||
}
|
||||
return string(out)
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
// bdConfigFail runs "bd config" expecting failure.
|
||||
|
|
@ -46,11 +46,11 @@ func bdConfigListJSON(t *testing.T, bd, dir string) map[string]string {
|
|||
cmd := exec.Command(bd, "config", "list", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd config list --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd config list --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
s := strings.TrimSpace(stdout.String())
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON object in config list output: %s", s)
|
||||
|
|
|
|||
407
cmd/bd/config_proxied_integration_test.go
Normal file
407
cmd/bd/config_proxied_integration_test.go
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func bdProxiedConfig(t *testing.T, bd, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"config"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err != nil {
|
||||
t.Fatalf("bd config %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), err, stdout, stderr)
|
||||
}
|
||||
return stdout
|
||||
}
|
||||
|
||||
func bdProxiedConfigFail(t *testing.T, bd, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
fullArgs := append([]string{"config"}, args...)
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
||||
if err == nil {
|
||||
t.Fatalf("expected bd config %s to fail; got stdout:\n%s\nstderr:\n%s",
|
||||
strings.Join(args, " "), stdout, stderr)
|
||||
}
|
||||
return stdout + stderr
|
||||
}
|
||||
|
||||
func bdProxiedConfigListJSON(t *testing.T, bd, dir string) map[string]string {
|
||||
t.Helper()
|
||||
out := bdProxiedConfig(t, bd, dir, "list", "--json")
|
||||
s := strings.TrimSpace(out)
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON object in config list output: %s", s)
|
||||
}
|
||||
var raw map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(s[start:]), &raw); err != nil {
|
||||
t.Fatalf("parse config list JSON: %v\n%s", err, s)
|
||||
}
|
||||
m := make(map[string]string, len(raw))
|
||||
for k, v := range raw {
|
||||
if k == "schema_version" {
|
||||
continue
|
||||
}
|
||||
if sv, ok := v.(string); ok {
|
||||
m[k] = sv
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func proxiedDoltHead(t *testing.T, db *sql.DB) string {
|
||||
t.Helper()
|
||||
var h string
|
||||
if err := db.QueryRowContext(context.Background(), "SELECT HASHOF('HEAD')").Scan(&h); err != nil {
|
||||
t.Fatalf("read HEAD: %v", err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func proxiedDoltCommitCountSince(t *testing.T, db *sql.DB, sinceHash string) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT COUNT(*) FROM DOLT_LOG('HEAD', '--not', ?)", sinceHash).Scan(&n); err != nil {
|
||||
t.Fatalf("count commits since %s: %v", sinceHash, err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestProxiedServerConfig(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("config_set_and_get", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcs")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.key1", "hello")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "test.key1")
|
||||
if !strings.Contains(out, "hello") {
|
||||
t.Errorf("expected 'hello' in get output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_set_overwrite", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pco")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.overwrite", "first")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.overwrite", "second")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "test.overwrite")
|
||||
if !strings.Contains(out, "second") {
|
||||
t.Errorf("expected 'second' after overwrite: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_set_namespaced", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcn")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "jira.url", "https://example.atlassian.net")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "jira.url")
|
||||
if !strings.Contains(out, "https://example.atlassian.net") {
|
||||
t.Errorf("expected jira URL in output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_set_and_get_linear_state_map_dotted_key", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcd")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "linear.state_map.closed", "Done")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "linear.state_map.closed")
|
||||
if strings.TrimSpace(out) != "Done" {
|
||||
t.Errorf("expected exact state_map value, got: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_list", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcl")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "list")
|
||||
if !strings.Contains(out, "issue_prefix") {
|
||||
t.Errorf("expected issue_prefix in list output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_list_json", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcj")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.key1", "hello")
|
||||
m := bdProxiedConfigListJSON(t, bd, p.dir)
|
||||
if _, ok := m["issue_prefix"]; !ok {
|
||||
t.Error("expected issue_prefix in JSON config list")
|
||||
}
|
||||
if v, ok := m["test.key1"]; !ok || v != "hello" {
|
||||
t.Errorf("expected test.key1=hello, got %q", v)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_unset", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcu")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.removeme", "temp")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "test.removeme")
|
||||
if !strings.Contains(out, "temp") {
|
||||
t.Fatalf("expected 'temp' before unset: %s", out)
|
||||
}
|
||||
bdProxiedConfig(t, bd, p.dir, "unset", "test.removeme")
|
||||
out = bdProxiedConfig(t, bd, p.dir, "get", "test.removeme")
|
||||
if !strings.Contains(out, "not set") {
|
||||
t.Errorf("expected 'not set' after unset: %s", out)
|
||||
}
|
||||
m := bdProxiedConfigListJSON(t, bd, p.dir)
|
||||
if _, ok := m["test.removeme"]; ok {
|
||||
t.Error("expected test.removeme to be absent from config list after unset")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_get_missing_key", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcm")
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "nonexistent.key.xyz")
|
||||
if !strings.Contains(out, "not set") {
|
||||
t.Errorf("expected 'not set' for missing key: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_set_no_args", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcsna")
|
||||
bdProxiedConfigFail(t, bd, p.dir, "set")
|
||||
})
|
||||
|
||||
t.Run("config_unset_no_args", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcuna")
|
||||
bdProxiedConfigFail(t, bd, p.dir, "unset")
|
||||
})
|
||||
|
||||
t.Run("config_set_creates_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcsc")
|
||||
db := openProxiedDB(t, p)
|
||||
before := proxiedDoltHead(t, db)
|
||||
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.commit", "v1")
|
||||
|
||||
after := proxiedDoltHead(t, db)
|
||||
if after == before {
|
||||
t.Errorf("HEAD did not advance: before=%s after=%s", before, after)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_unset_creates_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcuc")
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "test.commit", "v1")
|
||||
|
||||
db := openProxiedDB(t, p)
|
||||
before := proxiedDoltHead(t, db)
|
||||
|
||||
bdProxiedConfig(t, bd, p.dir, "unset", "test.commit")
|
||||
|
||||
after := proxiedDoltHead(t, db)
|
||||
if after == before {
|
||||
t.Errorf("HEAD did not advance on unset: before=%s after=%s", before, after)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_yaml_only_key_skips_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcy")
|
||||
db := openProxiedDB(t, p)
|
||||
before := proxiedDoltHead(t, db)
|
||||
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "export.auto", "true")
|
||||
|
||||
after := proxiedDoltHead(t, db)
|
||||
if after != before {
|
||||
t.Errorf("yaml-only set should not advance HEAD: before=%s after=%s", before, after)
|
||||
}
|
||||
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", "export.auto")
|
||||
if !strings.Contains(out, "true") {
|
||||
t.Errorf("expected export.auto=true via get: %s", out)
|
||||
}
|
||||
|
||||
yamlPath := filepath.Join(p.beadsDir, "config.yaml")
|
||||
body, err := os.ReadFile(yamlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", yamlPath, err)
|
||||
}
|
||||
if !strings.Contains(string(body), "auto") {
|
||||
t.Errorf("expected export.auto written to config.yaml, got:\n%s", body)
|
||||
}
|
||||
|
||||
before = proxiedDoltHead(t, db)
|
||||
bdProxiedConfig(t, bd, p.dir, "unset", "export.auto")
|
||||
after = proxiedDoltHead(t, db)
|
||||
if after != before {
|
||||
t.Errorf("yaml-only unset should not advance HEAD: before=%s after=%s", before, after)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config_beads_role_skips_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcr")
|
||||
db := openProxiedDB(t, p)
|
||||
before := proxiedDoltHead(t, db)
|
||||
|
||||
bdProxiedConfig(t, bd, p.dir, "set", "beads.role", "contributor")
|
||||
|
||||
after := proxiedDoltHead(t, db)
|
||||
if after != before {
|
||||
t.Errorf("beads.role set should not advance HEAD: before=%s after=%s", before, after)
|
||||
}
|
||||
|
||||
gitCmd := exec.Command("git", "config", "--get", "beads.role")
|
||||
gitCmd.Dir = p.dir
|
||||
out, err := gitCmd.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("git config --get beads.role: %v", err)
|
||||
}
|
||||
if strings.TrimSpace(string(out)) != "contributor" {
|
||||
t.Errorf("expected beads.role=contributor in git config, got %q", out)
|
||||
}
|
||||
|
||||
before = proxiedDoltHead(t, db)
|
||||
bdProxiedConfig(t, bd, p.dir, "unset", "beads.role")
|
||||
after = proxiedDoltHead(t, db)
|
||||
if after != before {
|
||||
t.Errorf("beads.role unset should not advance HEAD: before=%s after=%s", before, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestProxiedServerConfigSetMany(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
t.Run("set_many_single_dolt_commit", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcsm")
|
||||
db := openProxiedDB(t, p)
|
||||
before := proxiedDoltHead(t, db)
|
||||
|
||||
bdProxiedConfig(t, bd, p.dir, "set-many",
|
||||
"ado.state_map.open=New",
|
||||
"ado.state_map.in_progress=Active",
|
||||
"ado.state_map.closed=Closed",
|
||||
)
|
||||
|
||||
after := proxiedDoltHead(t, db)
|
||||
if after == before {
|
||||
t.Fatalf("HEAD did not advance for set-many: before=%s after=%s", before, after)
|
||||
}
|
||||
n := proxiedDoltCommitCountSince(t, db, before)
|
||||
if n != 1 {
|
||||
t.Errorf("expected exactly 1 Dolt commit for set-many with 3 keys, got %d", n)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("set_many_cli_round_trip", func(t *testing.T) {
|
||||
p := bdProxiedInit(t, bd, "pcsmr")
|
||||
bdProxiedConfig(t, bd, p.dir, "set-many",
|
||||
"jira.url=https://example.atlassian.net",
|
||||
"jira.project=PROJ",
|
||||
"linear.state_map.closed=Done",
|
||||
)
|
||||
|
||||
want := map[string]string{
|
||||
"jira.url": "https://example.atlassian.net",
|
||||
"jira.project": "PROJ",
|
||||
"linear.state_map.closed": "Done",
|
||||
}
|
||||
for k, v := range want {
|
||||
out := bdProxiedConfig(t, bd, p.dir, "get", k)
|
||||
if strings.TrimSpace(out) != v {
|
||||
t.Errorf("get %s: expected %q, got %q", k, v, out)
|
||||
}
|
||||
}
|
||||
|
||||
m := bdProxiedConfigListJSON(t, bd, p.dir)
|
||||
for k, v := range want {
|
||||
if got, ok := m[k]; !ok || got != v {
|
||||
t.Errorf("list --json: %s expected %q, got %q (exists=%v)", k, v, got, ok)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestProxiedServerConfigConcurrent(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
p := bdProxiedInit(t, bd, "pcc")
|
||||
|
||||
const numWorkers = 8
|
||||
|
||||
type workerResult struct {
|
||||
worker int
|
||||
err error
|
||||
}
|
||||
|
||||
results := make([]workerResult, numWorkers)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numWorkers)
|
||||
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
go func(worker int) {
|
||||
defer wg.Done()
|
||||
r := workerResult{worker: worker}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
key := fmt.Sprintf("worker%d.key%d", worker, i)
|
||||
value := fmt.Sprintf("value-%d-%d", worker, i)
|
||||
if _, err := bdProxiedRun(t, bd, p.dir, "config", "set", key, value); err != nil {
|
||||
r.err = fmt.Errorf("set %s: %v", key, err)
|
||||
results[worker] = r
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
key := fmt.Sprintf("worker%d.key%d", worker, i)
|
||||
expected := fmt.Sprintf("value-%d-%d", worker, i)
|
||||
out, err := bdProxiedRun(t, bd, p.dir, "config", "get", key)
|
||||
if err != nil {
|
||||
r.err = fmt.Errorf("get %s: %v\n%s", key, err, out)
|
||||
results[worker] = r
|
||||
return
|
||||
}
|
||||
if !strings.Contains(string(out), expected) {
|
||||
r.err = fmt.Errorf("worker %d: key %s expected %q, got %q", worker, key, expected, string(out))
|
||||
results[worker] = r
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
results[worker] = r
|
||||
}(w)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for _, r := range results {
|
||||
if r.err != nil &&
|
||||
!strings.Contains(r.err.Error(), "serialization failure") &&
|
||||
!strings.Contains(r.err.Error(), "Error 1213") {
|
||||
t.Errorf("worker %d failed: %v", r.worker, r.err)
|
||||
}
|
||||
}
|
||||
|
||||
m := bdProxiedConfigListJSON(t, bd, p.dir)
|
||||
var successCount int
|
||||
for _, r := range results {
|
||||
if r.err != nil {
|
||||
continue
|
||||
}
|
||||
successCount++
|
||||
w := r.worker
|
||||
for i := 0; i < 5; i++ {
|
||||
key := fmt.Sprintf("worker%d.key%d", w, i)
|
||||
expected := fmt.Sprintf("value-%d-%d", w, i)
|
||||
if v, ok := m[key]; !ok || v != expected {
|
||||
t.Errorf("after concurrent writes: key %s expected %q, got %q (exists=%v)", key, expected, v, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
if successCount == 0 {
|
||||
t.Fatal("expected at least 1 worker to succeed")
|
||||
}
|
||||
}
|
||||
147
cmd/bd/config_proxied_server.go
Normal file
147
cmd/bd/config_proxied_server.go
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func openConfigProxiedUOW(ctx context.Context) uow.UnitOfWork {
|
||||
if uowProvider == nil {
|
||||
FatalErrorRespectJSON("proxied-server UOW provider not initialized")
|
||||
}
|
||||
uw, err := uowProvider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("open unit of work: %v", err)
|
||||
}
|
||||
return uw
|
||||
}
|
||||
|
||||
func runConfigSetProxiedServer(ctx context.Context, key, value string) {
|
||||
if key == "status.custom" && value != "" {
|
||||
if _, err := types.ParseCustomStatusConfig(value); err != nil {
|
||||
FatalErrorRespectJSON("invalid status.custom value: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
uw := openConfigProxiedUOW(ctx)
|
||||
defer uw.Close(ctx)
|
||||
|
||||
if err := uw.ConfigUseCase().SetConfig(ctx, key, value); err != nil {
|
||||
FatalErrorRespectJSON("Error setting config: %v", err)
|
||||
}
|
||||
|
||||
if err := uw.Commit(ctx, fmt.Sprintf("bd: config set %s", key)); err != nil && !isDoltNothingToCommit(err) {
|
||||
FatalErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
_ = outputJSON(map[string]string{
|
||||
"key": key,
|
||||
"value": value,
|
||||
})
|
||||
} else {
|
||||
fmt.Printf("Set %s = %s\n", key, value)
|
||||
}
|
||||
printConfigSideEffects(checkConfigSetSideEffects(key, value))
|
||||
}
|
||||
|
||||
func runConfigGetProxiedServer(ctx context.Context, key string) {
|
||||
uw := openConfigProxiedUOW(ctx)
|
||||
defer uw.Close(ctx)
|
||||
|
||||
value, err := uw.ConfigUseCase().GetConfig(ctx, key)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("Error getting config: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
_ = outputJSON(map[string]string{
|
||||
"key": key,
|
||||
"value": value,
|
||||
})
|
||||
return
|
||||
}
|
||||
if value == "" {
|
||||
fmt.Printf("%s (not set)\n", key)
|
||||
} else {
|
||||
fmt.Printf("%s\n", value)
|
||||
}
|
||||
}
|
||||
|
||||
func runConfigListProxiedServer(ctx context.Context) {
|
||||
uw := openConfigProxiedUOW(ctx)
|
||||
defer uw.Close(ctx)
|
||||
|
||||
cfg, err := uw.ConfigUseCase().GetAllConfig(ctx)
|
||||
if err != nil {
|
||||
FatalErrorRespectJSON("Error listing config: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
_ = outputJSON(cfg)
|
||||
return
|
||||
}
|
||||
|
||||
if len(cfg) == 0 {
|
||||
fmt.Println("No configuration set")
|
||||
return
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(cfg))
|
||||
for k := range cfg {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
fmt.Println("\nConfiguration:")
|
||||
for _, k := range keys {
|
||||
fmt.Printf(" %s = %s\n", k, cfg[k])
|
||||
}
|
||||
|
||||
showConfigYAMLOverrides(cfg)
|
||||
}
|
||||
|
||||
func runConfigUnsetProxiedServer(ctx context.Context, key string) {
|
||||
uw := openConfigProxiedUOW(ctx)
|
||||
defer uw.Close(ctx)
|
||||
|
||||
if err := uw.ConfigUseCase().DeleteConfig(ctx, key); err != nil {
|
||||
FatalErrorRespectJSON("Error deleting config: %v", err)
|
||||
}
|
||||
|
||||
if err := uw.Commit(ctx, fmt.Sprintf("bd: config unset %s", key)); err != nil && !isDoltNothingToCommit(err) {
|
||||
FatalErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
_ = outputJSON(map[string]string{
|
||||
"key": key,
|
||||
})
|
||||
} else {
|
||||
fmt.Printf("Unset %s\n", key)
|
||||
}
|
||||
printConfigSideEffects(checkConfigUnsetSideEffects(key))
|
||||
}
|
||||
|
||||
func runConfigSetManyProxiedServer(ctx context.Context, keys, values []string) {
|
||||
if len(keys) == 0 {
|
||||
return
|
||||
}
|
||||
uw := openConfigProxiedUOW(ctx)
|
||||
defer uw.Close(ctx)
|
||||
|
||||
cfgUC := uw.ConfigUseCase()
|
||||
for i, k := range keys {
|
||||
if err := cfgUC.SetConfig(ctx, k, values[i]); err != nil {
|
||||
FatalErrorRespectJSON("Error setting config %s: %v", k, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := uw.Commit(ctx, fmt.Sprintf("bd: config set-many (%d keys)", len(keys))); err != nil && !isDoltNothingToCommit(err) {
|
||||
FatalErrorRespectJSON("failed to commit: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -53,7 +53,7 @@ func TestConfigSetManyArgParsing(t *testing.T) {
|
|||
// TestConfigSetManyYamlKeyDetection tests that yaml-only keys are correctly identified
|
||||
// for routing in the set-many command.
|
||||
func TestConfigSetManyYamlKeyDetection(t *testing.T) {
|
||||
yamlKeys := []string{"no-db", "json", "routing.mode", "routing.default", "no-push"}
|
||||
yamlKeys := []string{"no-db", "json", "routing.mode", "routing.default", "no-push", "import.path"}
|
||||
for _, key := range yamlKeys {
|
||||
if !config.IsYamlOnlyKey(key) {
|
||||
t.Errorf("expected %q to be yaml-only", key)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
)
|
||||
|
||||
// configEntry represents a single configuration key with its effective value and source.
|
||||
|
|
@ -40,7 +41,16 @@ Examples:
|
|||
bd config show
|
||||
bd config show --json
|
||||
bd config show --source config.yaml`,
|
||||
Run: func(cmd *cobra.Command, _ []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
evt := metrics.NewCommandEvent("config-show")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
sourceFilter, _ := cmd.Flags().GetString("source")
|
||||
|
||||
entries := collectConfigEntries()
|
||||
|
|
@ -50,16 +60,16 @@ Examples:
|
|||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(entries)
|
||||
return
|
||||
return outputJSON(entries)
|
||||
}
|
||||
|
||||
if len(entries) == 0 {
|
||||
fmt.Println("No configuration found")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
printConfigEntries(entries)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -120,9 +130,24 @@ func collectViperEntries() []configEntry {
|
|||
|
||||
value := formatViperValue(config.GetString(key))
|
||||
source := config.GetValueSource(key)
|
||||
|
||||
sourceLabel := viperSourceLabel(key, source)
|
||||
|
||||
// User-global keys (metrics.*) are honored at runtime from the user-global
|
||||
// config.yaml only, never merged project config; report that authoritative
|
||||
// value AND its user-global source so the listing matches what bd actually
|
||||
// uses (and `bd config get`), not a project value/source that has no
|
||||
// runtime effect. The viper source label alone is ambiguous: a project
|
||||
// .beads/config.yaml that also sets a metrics key makes GetValueSource
|
||||
// report SourceConfigFile ("config.yaml"), which would attribute the
|
||||
// displayed user-global value to the project file the runtime ignores.
|
||||
if config.IsUserGlobalKey(key) {
|
||||
value = formatViperValue(config.GetUserYamlConfig(key))
|
||||
if value == "" {
|
||||
continue // unset in user-global; runtime uses the built-in default
|
||||
}
|
||||
sourceLabel = config.UserConfigYamlPath()
|
||||
}
|
||||
|
||||
// Skip empty defaults — they add noise without information
|
||||
if source == config.SourceDefault && value == "" {
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
|
|
@ -305,3 +307,92 @@ func TestCollectViperEntriesWithEnvOverride(t *testing.T) {
|
|||
}
|
||||
t.Error("expected actor key in Viper entries")
|
||||
}
|
||||
|
||||
// TestCollectViperEntriesMetricsUserGlobalProvenance verifies that user-global
|
||||
// metrics.* keys report the user-global value AND the user-global config path as
|
||||
// their source, even when a project .beads/config.yaml sets a conflicting value
|
||||
// that the runtime ignores. This is the provenance contract `bd config show`
|
||||
// shares with `bd config get`: metrics consent/endpoint live in the user-global
|
||||
// config only, so the displayed value must never be attributed to a project file.
|
||||
func TestCollectViperEntriesMetricsUserGlobalProvenance(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
|
||||
// User-global config opts out of metrics; this is the value the runtime honors.
|
||||
userCfgDir := filepath.Join(home, ".config", "bd")
|
||||
if err := os.MkdirAll(userCfgDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir user config dir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(userCfgDir, "config.yaml"), []byte("metrics:\n disabled: true\n"), 0o600); err != nil {
|
||||
t.Fatalf("write user config: %v", err)
|
||||
}
|
||||
|
||||
// A project config tries to flip metrics back on through the highest-precedence
|
||||
// BEADS_DIR config. The runtime ignores it, but it makes GetValueSource report
|
||||
// SourceConfigFile so the regression covers the misattribution case.
|
||||
projectBeadsDir := filepath.Join(t.TempDir(), ".beads")
|
||||
if err := os.MkdirAll(projectBeadsDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir project .beads: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(projectBeadsDir, "config.yaml"), []byte("metrics.disabled: false\n"), 0o644); err != nil {
|
||||
t.Fatalf("write project config: %v", err)
|
||||
}
|
||||
t.Setenv("BEADS_DIR", projectBeadsDir)
|
||||
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() failed: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
|
||||
// Precondition: the project override is live in the merged config, so the
|
||||
// generic "config.yaml" source label would otherwise misattribute the value.
|
||||
if config.GetBool("metrics.disabled") {
|
||||
t.Fatalf("precondition: merged metrics.disabled should be false (project override), got true")
|
||||
}
|
||||
|
||||
var entry *configEntry
|
||||
entries := collectViperEntries()
|
||||
for i := range entries {
|
||||
if entries[i].Key == "metrics.disabled" {
|
||||
entry = &entries[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if entry == nil {
|
||||
t.Fatal("expected metrics.disabled in Viper entries")
|
||||
}
|
||||
|
||||
// Value comes from the user-global file, not the project override.
|
||||
if entry.Value != "true" {
|
||||
t.Errorf("metrics.disabled value = %q, want %q (user-global, not project override)", entry.Value, "true")
|
||||
}
|
||||
// Source is the explicit user-global path, matching `bd config get`, not the
|
||||
// generic project "config.yaml" label.
|
||||
wantSource := config.UserConfigYamlPath()
|
||||
if entry.Source != wantSource {
|
||||
t.Errorf("metrics.disabled source = %q, want %q (user-global path)", entry.Source, wantSource)
|
||||
}
|
||||
if entry.Source == "config.yaml" {
|
||||
t.Error("metrics.disabled source must not be the generic project config.yaml label")
|
||||
}
|
||||
|
||||
// The `config show --json` output serializes exactly these fields, so assert
|
||||
// the marshaled entry reports the user-global value and never the project
|
||||
// "config.yaml" provenance the runtime ignores.
|
||||
encoded, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(entry): %v", err)
|
||||
}
|
||||
if !strings.Contains(string(encoded), `"value":"true"`) {
|
||||
t.Errorf("config show --json entry %s missing user-global value", encoded)
|
||||
}
|
||||
if strings.Contains(string(encoded), `"source":"config.yaml"`) {
|
||||
t.Errorf("config show --json entry %s misattributes user-global value to project config.yaml", encoded)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,18 @@ func checkConfigSetSideEffects(key, value string) []configSideEffect {
|
|||
Command: "bd dolt server stop",
|
||||
})
|
||||
|
||||
case key == "dolt.debug" && strings.EqualFold(value, "true"):
|
||||
effects = append(effects, configSideEffect{
|
||||
Message: "Debug mode will apply on the next Dolt server start (loglevel=debug, --prof cpu).",
|
||||
Command: "bd dolt stop && bd dolt start",
|
||||
})
|
||||
|
||||
case key == "dolt.debug" && !strings.EqualFold(value, "true"):
|
||||
effects = append(effects, configSideEffect{
|
||||
Message: "Debug mode disabled. Restart the server to drop --prof and --loglevel=debug.",
|
||||
Command: "bd dolt stop && bd dolt start",
|
||||
})
|
||||
|
||||
case key == "routing.mode":
|
||||
validModes := map[string]bool{"maintainer": true, "contributor": true, "auto": true, "explicit": true}
|
||||
if !validModes[value] {
|
||||
|
|
@ -75,6 +87,12 @@ func checkConfigUnsetSideEffects(key string) []configSideEffect {
|
|||
Command: "bd dolt server stop",
|
||||
})
|
||||
|
||||
case "dolt.debug":
|
||||
effects = append(effects, configSideEffect{
|
||||
Message: "Debug config removed. Restart the server to drop --prof and --loglevel=debug.",
|
||||
Command: "bd dolt stop && bd dolt start",
|
||||
})
|
||||
|
||||
case "backup.enabled":
|
||||
effects = append(effects, configSideEffect{
|
||||
Message: "Backup config removed. Automatic backups will no longer run.",
|
||||
|
|
|
|||
|
|
@ -35,6 +35,36 @@ func TestCheckConfigSetSideEffects_SharedServerFalse(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestCheckConfigSetSideEffects_DoltDebugTrue(t *testing.T) {
|
||||
effects := checkConfigSetSideEffects("dolt.debug", "true")
|
||||
if len(effects) != 1 {
|
||||
t.Fatalf("expected 1 effect, got %d", len(effects))
|
||||
}
|
||||
if effects[0].Command != "bd dolt stop && bd dolt start" {
|
||||
t.Errorf("expected restart command, got %q", effects[0].Command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckConfigSetSideEffects_DoltDebugFalse(t *testing.T) {
|
||||
effects := checkConfigSetSideEffects("dolt.debug", "false")
|
||||
if len(effects) != 1 {
|
||||
t.Fatalf("expected 1 effect, got %d", len(effects))
|
||||
}
|
||||
if effects[0].Command != "bd dolt stop && bd dolt start" {
|
||||
t.Errorf("expected restart command, got %q", effects[0].Command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckConfigUnsetSideEffects_DoltDebug(t *testing.T) {
|
||||
effects := checkConfigUnsetSideEffects("dolt.debug")
|
||||
if len(effects) != 1 {
|
||||
t.Fatalf("expected 1 effect, got %d", len(effects))
|
||||
}
|
||||
if effects[0].Command != "bd dolt stop && bd dolt start" {
|
||||
t.Errorf("expected restart command, got %q", effects[0].Command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckConfigSetSideEffects_RoutingModeInvalid(t *testing.T) {
|
||||
effects := checkConfigSetSideEffects("routing.mode", "bogus")
|
||||
if len(effects) != 1 {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,8 @@ func TestIsRecognizedConfigKey(t *testing.T) {
|
|||
recognized := []string{
|
||||
"export.auto", "dolt.auto-push", "jira.url", "custom.anything",
|
||||
"doctor.suppress.git-hooks", "no-git-ops", "beads.role",
|
||||
"status.custom", "ai.model", "backup.enabled",
|
||||
"status.custom", "ai.model", "backup.enabled", "import.path",
|
||||
"dolt.local-only",
|
||||
}
|
||||
for _, key := range recognized {
|
||||
if !isRecognizedConfigKey(key) {
|
||||
|
|
@ -27,6 +28,12 @@ func TestIsRecognizedConfigKey(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestConfigHelpMentionsDoltLocalOnly(t *testing.T) {
|
||||
if !strings.Contains(configCmd.Long, "bd config set dolt.local-only true") {
|
||||
t.Fatalf("config help missing dolt.local-only example:\n%s", configCmd.Long)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestConfigKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ type CommandContext struct {
|
|||
Verbose bool
|
||||
Quiet bool
|
||||
|
||||
// Storage mode — true when connected to an external dolt sql-server.
|
||||
ServerMode bool
|
||||
ServerMode bool
|
||||
ProxiedServerMode bool
|
||||
|
||||
// Runtime state
|
||||
Store storage.DoltStorage
|
||||
|
|
@ -363,6 +363,10 @@ func syncCommandContext() {
|
|||
cmdCtx.Verbose = verboseFlag
|
||||
cmdCtx.Quiet = quietFlag
|
||||
|
||||
// Storage mode
|
||||
cmdCtx.ServerMode = serverMode
|
||||
cmdCtx.ProxiedServerMode = proxiedServerMode
|
||||
|
||||
// Runtime state
|
||||
cmdCtx.Store = store
|
||||
cmdCtx.RootCtx = rootCtx
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ func filteredEnvForContextBinding(keys ...string) []string {
|
|||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
return append(filtered, "BD_DISABLE_METRICS=1", "BD_DISABLE_EVENT_FLUSH=1")
|
||||
}
|
||||
|
||||
func TestListExplicitDBPathRebindsTargetContext(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@ package main
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/doltserver"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
)
|
||||
|
||||
// ContextInfo contains the effective backend identity and repository context.
|
||||
|
|
@ -21,6 +21,7 @@ type ContextInfo struct {
|
|||
DoltMode string `json:"dolt_mode"`
|
||||
ServerHost string `json:"server_host,omitempty"`
|
||||
ServerPort int `json:"server_port,omitempty"`
|
||||
ProxiedDir string `json:"proxied_dir,omitempty"`
|
||||
Database string `json:"database"`
|
||||
DataDir string `json:"data_dir,omitempty"`
|
||||
ProjectID string `json:"project_id,omitempty"`
|
||||
|
|
@ -44,13 +45,25 @@ Examples:
|
|||
bd context # Show context information
|
||||
bd context --json # Output in JSON format
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
evt := metrics.NewCommandEvent("context")
|
||||
defer func() {
|
||||
if c := metrics.Global(); c != nil {
|
||||
c.CloseEventAndAdd(evt)
|
||||
}
|
||||
}()
|
||||
|
||||
if usesProxiedServer() {
|
||||
return runContextProxiedServer(cmd, rootCtx)
|
||||
}
|
||||
|
||||
info := ContextInfo{
|
||||
Backend: configfile.BackendDolt,
|
||||
BdVersion: Version,
|
||||
}
|
||||
|
||||
// Resolve repo context (works without DB open)
|
||||
if selected := selectedNoDBBeadsDir(cmd); selected != "" {
|
||||
prepareSelectedNoDBContext(selected)
|
||||
}
|
||||
|
|
@ -58,11 +71,12 @@ Examples:
|
|||
rc, err := beads.GetRepoContext()
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve repo context: %v", err)})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: cannot resolve repo context: %v\n", err)
|
||||
if jerr := outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve repo context: %v", err)}); jerr != nil {
|
||||
return jerr
|
||||
}
|
||||
return SilentExit()
|
||||
}
|
||||
os.Exit(1)
|
||||
return HandleError("cannot resolve repo context: %v", err)
|
||||
}
|
||||
|
||||
info.BeadsDir = rc.BeadsDir
|
||||
|
|
@ -71,12 +85,10 @@ Examples:
|
|||
info.IsRedirected = rc.IsRedirected
|
||||
info.IsWorktree = rc.IsWorktree
|
||||
|
||||
// Read role from repo context
|
||||
if role, ok := rc.Role(); ok {
|
||||
info.Role = string(role)
|
||||
}
|
||||
|
||||
// Load metadata.json config (does not require DB)
|
||||
cfg, err := configfile.Load(rc.BeadsDir)
|
||||
if err != nil {
|
||||
cfg = configfile.DefaultConfig()
|
||||
|
|
@ -91,28 +103,31 @@ Examples:
|
|||
|
||||
if cfg.IsDoltServerMode() {
|
||||
info.ServerHost = cfg.GetDoltServerHost()
|
||||
// Use doltserver.DefaultConfig to resolve the actual runtime port
|
||||
// (from port file, env var, etc.) instead of the static config default.
|
||||
// This matches what "bd dolt show" does (GH#2555).
|
||||
dsCfg := doltserver.DefaultConfig(rc.BeadsDir)
|
||||
info.ServerPort = dsCfg.Port
|
||||
}
|
||||
if cfg.IsDoltProxiedServerMode() {
|
||||
p, err := resolveProxiedServerRootPath(rc.BeadsDir)
|
||||
if err != nil {
|
||||
return HandleError("resolve proxied server root: %v", err)
|
||||
}
|
||||
info.ProxiedDir = p
|
||||
}
|
||||
|
||||
if dataDir := cfg.GetDoltDataDir(); dataDir != "" {
|
||||
info.DataDir = dataDir
|
||||
}
|
||||
|
||||
// Read sync remote from the selected repo's config.yaml.
|
||||
if remote := resolveSyncRemoteFromDir(rc.BeadsDir); remote != "" {
|
||||
info.SyncRemote = remote
|
||||
info.SyncGitRemote = remote // Deprecated: kept for backwards compat
|
||||
info.SyncGitRemote = remote
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(info)
|
||||
} else {
|
||||
printContextText(info)
|
||||
return outputJSON(info)
|
||||
}
|
||||
printContextText(info)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -146,6 +161,9 @@ func printContextText(info ContextInfo) {
|
|||
if info.ServerHost != "" {
|
||||
fmt.Printf(" server: %s:%d\n", info.ServerHost, info.ServerPort)
|
||||
}
|
||||
if info.ProxiedDir != "" {
|
||||
fmt.Printf(" proxied dir: %s\n", info.ProxiedDir)
|
||||
}
|
||||
if info.DataDir != "" {
|
||||
fmt.Printf(" data dir: %s\n", info.DataDir)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,12 +24,12 @@ func TestEmbeddedContext(t *testing.T) {
|
|||
cmd := exec.Command(bd, "context")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd context failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd context failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(string(out), "embedded") && !strings.Contains(string(out), ".beads") {
|
||||
t.Errorf("expected embedded mode or .beads in context output: %s", out)
|
||||
if !strings.Contains(stdout.String(), "embedded") && !strings.Contains(stdout.String(), ".beads") {
|
||||
t.Errorf("expected embedded mode or .beads in context output: %s", stdout.String())
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -37,11 +37,11 @@ func TestEmbeddedContext(t *testing.T) {
|
|||
cmd := exec.Command(bd, "context", "--json")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd context --json failed: %v\n%s", err, out)
|
||||
t.Fatalf("bd context --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
if len(strings.TrimSpace(string(out))) == 0 {
|
||||
if len(strings.TrimSpace(stdout.String())) == 0 {
|
||||
t.Error("expected non-empty context --json output")
|
||||
}
|
||||
})
|
||||
|
|
|
|||
107
cmd/bd/context_proxied_integration_test.go
Normal file
107
cmd/bd/context_proxied_integration_test.go
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
)
|
||||
|
||||
func TestProxiedServerContext(t *testing.T) {
|
||||
requireProxiedServerEnv(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
p := bdProxiedInit(t, bd, "ctx")
|
||||
|
||||
t.Run("default_text", func(t *testing.T) {
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "context")
|
||||
if err != nil {
|
||||
t.Fatalf("bd context failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, configfile.DoltModeProxiedServer) {
|
||||
t.Errorf("expected mode %q in context output:\n%s", configfile.DoltModeProxiedServer, stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, ".beads") {
|
||||
t.Errorf("expected .beads in context output:\n%s", stdout)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("json_fields", func(t *testing.T) {
|
||||
info := proxiedContextJSON(t, bd, p)
|
||||
|
||||
if info.DoltMode != configfile.DoltModeProxiedServer {
|
||||
t.Errorf("dolt_mode = %q, want %q", info.DoltMode, configfile.DoltModeProxiedServer)
|
||||
}
|
||||
if info.ProxiedDir == "" {
|
||||
t.Error("proxied_dir should be populated in proxied-server mode")
|
||||
}
|
||||
if info.Database != p.database {
|
||||
t.Errorf("database = %q, want %q", info.Database, p.database)
|
||||
}
|
||||
if filepath.Base(info.BeadsDir) != ".beads" {
|
||||
t.Errorf("beads_dir = %q, want a path ending in .beads", info.BeadsDir)
|
||||
}
|
||||
if info.Backend != configfile.BackendDolt {
|
||||
t.Errorf("backend = %q, want %q", info.Backend, configfile.BackendDolt)
|
||||
}
|
||||
if info.BdVersion == "" {
|
||||
t.Error("bd_version should be populated")
|
||||
}
|
||||
if info.ServerHost != "" || info.ServerPort != 0 {
|
||||
t.Errorf("server host/port must be empty in proxied-server mode: host=%q port=%d", info.ServerHost, info.ServerPort)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("concurrent", func(t *testing.T) {
|
||||
const numWorkers = 8
|
||||
errs := make([]error, numWorkers)
|
||||
modes := make([]string, numWorkers)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < numWorkers; i++ {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "context", "--json")
|
||||
if err != nil {
|
||||
errs[idx] = err
|
||||
return
|
||||
}
|
||||
var info ContextInfo
|
||||
if jerr := json.Unmarshal([]byte(stdout), &info); jerr != nil {
|
||||
errs[idx] = jerr
|
||||
return
|
||||
}
|
||||
modes[idx] = info.DoltMode
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i := 0; i < numWorkers; i++ {
|
||||
if errs[i] != nil {
|
||||
t.Errorf("worker %d: bd context failed: %v", i, errs[i])
|
||||
continue
|
||||
}
|
||||
if modes[i] != configfile.DoltModeProxiedServer {
|
||||
t.Errorf("worker %d: dolt_mode = %q, want %q", i, modes[i], configfile.DoltModeProxiedServer)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func proxiedContextJSON(t *testing.T, bd string, p proxiedProject) ContextInfo {
|
||||
t.Helper()
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "context", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd context --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
|
||||
}
|
||||
var info ContextInfo
|
||||
if jerr := json.Unmarshal([]byte(stdout), &info); jerr != nil {
|
||||
t.Fatalf("decoding context JSON: %v\noutput:\n%s", jerr, stdout)
|
||||
}
|
||||
return info
|
||||
}
|
||||
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