Merge remote-tracking branch 'origin/main' into wip/merge-4833

# Conflicts:
#	cmd/bd/create.go
This commit is contained in:
Vishnu Jayavel 2026-07-19 20:52:31 -07:00
commit b956262dab
460 changed files with 16515 additions and 16470 deletions

View file

@ -190,6 +190,14 @@ style, nav), edit `tools/docsmint` and its tests. The drift gates
(`generate-cli-docs.sh --check`, `scripts/check-cli-docs-drift.sh` in PR CI,
and the docs-autofix bot) fail or auto-fix any hand edit.
**The docs describe the pinned release, not main.** `docs/cli-docs.pin`
names the release tag the whole docs corpus targets; the pipeline builds bd
from that tag and validates against it, so a Go-source edit on main shows up
in the committed docs only after the pin is bumped (at release time,
followed by a regeneration). Hand-written pages follow the same policy:
document what the pinned release does, never main-only features. See
`engdocs/decisions/2026-07-17-docs-release-pin.md`.
## 9. Verify before you call it done
Run the gates in [references/verification.md](references/verification.md).

View file

@ -29,7 +29,7 @@
# Test specific package
./scripts/test.sh ./cmd/bd/...
./scripts/test.sh ./internal/storage/sqlite/...
./scripts/test.sh ./internal/storage/embeddeddolt/...
# Test specific feature
./scripts/test.sh -run TestCreate ./cmd/bd/...

View file

@ -0,0 +1,64 @@
# Proxied-server cmd test shard manifest.
#
# Format: <total_shards> <shard_number> <top_level_test_name>
#
# There is no committed recent duration artifact for these tests. This manifest
# pins a conservative, duration-weighted split for the 8-shard CI matrix while
# proxied-test-shard.sh continues to hash-distribute newly-added tests that are
# not listed here.
#
# TestProxiedServerUpdate (~55 subtests) dominates runtime and cannot be split
# below its own wall-clock, so it owns shard 1 alone; the remaining suites are
# greedily packed to keep shards 2-8 roughly even.
8 1 TestProxiedServerUpdate
8 2 TestProxiedServerDep
8 2 TestProxiedServerDeleteWisp
8 2 TestProxiedServerReadyConcurrent
8 2 TestProxiedServerQuick
8 2 TestProxiedServerSQL
8 3 TestProxiedServerClose
8 3 TestProxiedServerComment
8 3 TestProxiedServerExternalCreate
8 3 TestProxiedServerState
8 3 TestProxiedServerGateList
8 3 TestProxiedServerPriority
8 4 TestProxiedServerReady
8 4 TestProxiedServerReopen
8 4 TestProxiedServerDeleteConcurrent
8 4 TestProxiedServerReadyWisp
8 4 TestProxiedServerBlocked
8 4 TestProxiedServerTag
8 4 TestProxiedServerPathHelpers
8 5 TestProxiedServerShow
8 5 TestProxiedServerCloseConcurrent
8 5 TestProxiedServerConfigConcurrent
8 5 TestProxiedServerUpdateConcurrentClaim
8 5 TestProxiedServerTodo
8 5 TestProxiedServerEdit
8 6 TestProxiedServerCreate
8 6 TestProxiedServerQuery
8 6 TestProxiedServerUpdateWisp
8 6 TestProxiedServerDepConcurrent
8 6 TestProxiedServerUpdateHooks
8 6 TestProxiedServerLink
8 6 TestProxiedServerContext
8 7 TestProxiedServerDelete
8 7 TestProxiedServerLabel
8 7 TestProxiedServerPrune
8 7 TestProxiedServerReadyClaimConcurrent
8 7 TestProxiedServerAssign
8 7 TestProxiedServerConfigSetMany
8 7 TestProxiedServerNote
8 8 TestProxiedServerList
8 8 TestProxiedServerSearch
8 8 TestProxiedServerConfig
8 8 TestProxiedServerReopenConcurrent
8 8 TestProxiedServerDoltRemoteRemove
8 8 TestProxiedServerChildren

141
.github/scripts/proxied-test-shard.sh vendored Executable file
View file

@ -0,0 +1,141 @@
#!/usr/bin/env bash
# proxied-test-shard.sh — run a shard of proxied-server dolt cmd/bd tests.
#
# Usage: proxied-test-shard.sh <shard_number> <total_shards>
#
# Discovers all TestProxiedServer* top-level functions across cmd/bd/*_test.go
# (the proxied integration suites plus TestProxiedServerExternalCreate and the
# TestProxiedServerPathHelpers unit test, matching the lane's historical
# `-run '^TestProxiedServer'`). Tests listed in proxied-cmd-test-shards.txt for
# the requested shard count use that committed assignment; newly-added tests
# fall back to hash(name) % total. Runs the matching subset using the pre-built
# test binary at BEADS_TEST_CMD_BINARY (or /tmp/bd-cmd-test).
#
# Environment:
# BEADS_TEST_PROXIED_SERVER=1 required (tests skip without it)
# BEADS_TEST_BD_BINARY=<path> pre-built bd binary used as the subprocess
# BEADS_TEST_CMD_BINARY=<path> pre-built cmd/bd test binary (default: /tmp/bd-cmd-test)
# BEADS_TEST_SHARD_MANIFEST=<path> override committed manifest path
# BEADS_TEST_SHARD_LIST_ONLY=1 print selected tests without running them
set -euo pipefail
SHARD_NUMBER="${1:?usage: $0 <shard_number> <total_shards>}"
TOTAL_SHARDS="${2:?usage: $0 <shard_number> <total_shards>}"
shift 2
if ! [[ "$SHARD_NUMBER" =~ ^[0-9]+$ ]] || ! [[ "$TOTAL_SHARDS" =~ ^[0-9]+$ ]]; then
echo "Shard number and total shards must be positive integers" >&2
exit 1
fi
if (( TOTAL_SHARDS < 1 || SHARD_NUMBER < 1 || SHARD_NUMBER > TOTAL_SHARDS )); then
echo "Invalid shard ${SHARD_NUMBER}/${TOTAL_SHARDS}" >&2
exit 1
fi
SHARD_INDEX=$(( SHARD_NUMBER - 1 ))
MANIFEST="${BEADS_TEST_SHARD_MANIFEST:-.github/scripts/proxied-cmd-test-shards.txt}"
# Discover all top-level TestProxiedServer* functions across every cmd/bd test
# file (integration suites live in *_proxied_integration_test.go, but
# TestProxiedServerExternalCreate and TestProxiedServerPathHelpers do not, so
# match by name rather than by file glob).
ALL_TESTS=$(grep -rh '^func TestProxiedServer' cmd/bd/*_test.go \
| sed 's/func \(TestProxiedServer[A-Za-z0-9_]*\).*/\1/' \
| sort -u)
if [ -z "$ALL_TESTS" ]; then
echo "No TestProxiedServer* functions found" >&2
exit 1
fi
declare -A ALL_TEST_SET=()
while IFS= read -r name; do
ALL_TEST_SET["$name"]=1
done <<< "$ALL_TESTS"
declare -A MANIFEST_SHARDS=()
if [ -f "$MANIFEST" ]; then
while IFS= read -r line || [ -n "$line" ]; do
line="${line%%#*}"
read -r manifest_total manifest_shard test_name extra <<< "$line"
if [ -z "${manifest_total:-}" ]; then
continue
fi
if [ -n "${extra:-}" ] || ! [[ "$manifest_total" =~ ^[0-9]+$ ]] || ! [[ "$manifest_shard" =~ ^[0-9]+$ ]] || ! [[ "$test_name" =~ ^TestProxiedServer[A-Za-z0-9_]+$ ]]; then
echo "Invalid shard manifest line: $line" >&2
exit 1
fi
if (( manifest_total != TOTAL_SHARDS )); then
continue
fi
if (( manifest_shard < 1 || manifest_shard > TOTAL_SHARDS )); then
echo "Invalid shard ${manifest_shard}/${manifest_total} for $test_name in $MANIFEST" >&2
exit 1
fi
if [ -n "${MANIFEST_SHARDS[$test_name]:-}" ]; then
echo "Duplicate shard manifest entry for $test_name in $MANIFEST" >&2
exit 1
fi
MANIFEST_SHARDS["$test_name"]="$manifest_shard"
done < "$MANIFEST"
fi
for name in "${!MANIFEST_SHARDS[@]}"; do
if [ -z "${ALL_TEST_SET[$name]:-}" ]; then
echo "Shard manifest entry does not match a discovered test: $name" >&2
exit 1
fi
done
SHARD_TESTS=()
MANIFEST_COUNT=0
FALLBACK_COUNT=0
while IFS= read -r name; do
assigned_shard="${MANIFEST_SHARDS[$name]:-}"
if [ -n "$assigned_shard" ]; then
if (( assigned_shard == SHARD_NUMBER )); then
SHARD_TESTS+=("$name")
MANIFEST_COUNT=$(( MANIFEST_COUNT + 1 ))
fi
continue
fi
# Use cksum for a portable numeric hash fallback for newly-added tests.
hash=$(printf %s "$name" | cksum | cut -d ' ' -f 1)
if (( hash % TOTAL_SHARDS == SHARD_INDEX )); then
SHARD_TESTS+=("$name")
FALLBACK_COUNT=$(( FALLBACK_COUNT + 1 ))
fi
done <<< "$ALL_TESTS"
if [ ${#SHARD_TESTS[@]} -eq 0 ]; then
echo "Shard ${SHARD_NUMBER}/${TOTAL_SHARDS}: no tests assigned (all hashed to other shards)"
exit 0
fi
# Build the -run regex: "^(TestA|TestB|TestC)$"
RUN_REGEX="^($(IFS='|'; echo "${SHARD_TESTS[*]}"))$"
echo "Shard ${SHARD_NUMBER}/${TOTAL_SHARDS}: running ${#SHARD_TESTS[@]} test(s)"
echo " manifest: ${MANIFEST_COUNT}, fallback: ${FALLBACK_COUNT}"
printf " %s\n" "${SHARD_TESTS[@]}"
echo ""
# Use pre-built test binary if available, otherwise fall back to go test.
CMD_BINARY="${BEADS_TEST_CMD_BINARY:-/tmp/bd-cmd-test}"
if [ "${BEADS_TEST_SHARD_LIST_ONLY:-}" = "1" ]; then
exit 0
fi
if [ -x "$CMD_BINARY" ]; then
exec "$CMD_BINARY" -test.v -test.count=1 -test.timeout=15m \
-test.run "$RUN_REGEX" \
"$@"
else
echo "Warning: pre-built test binary not found at $CMD_BINARY, falling back to go test"
exec go test -tags=gms_pure_go -v -count=1 -timeout 15m \
-run "$RUN_REGEX" \
"$@" \
./cmd/bd/
fi

View file

@ -1,12 +1,7 @@
name: Conformance
# Runs the two-tier storage-backend conformance suite against REAL databases —
# the same scripts/conformance.sh developers run locally, so local == CI. Tier 1
# is the in-process store suite plus the wedge gates; Tier 2 is the end-to-end
# `bd init` + CLI differential (every SQL backend compared to the Dolt reference).
# Postgres and MySQL run as service containers; Dolt (embedded) and SQLite are
# in-process. The deep bts-rs 523-scenario oracle stays on-demand (CONFORMANCE_DEEP),
# not in this per-PR job.
# Runs the same two-tier storage conformance suite developers run locally:
# the in-process store corpus and the real-binary CLI harness.
on:
pull_request:
@ -23,40 +18,8 @@ env:
jobs:
conformance:
name: Storage backend conformance (real DBs)
name: Storage backend conformance (embedded Dolt oracle)
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: bts
POSTGRES_PASSWORD: bts
POSTGRES_DB: bdwedge
# Code-point collation parity with Dolt (utf8mb4_0900_bin). The pg backend
# provisions per-workspace SCHEMAS inside this one database and can't set
# per-column COLLATE "C" (it breaks the shared recursive CTEs; see
# internal/storage/postgres/schema.go), so byte-order parity has to be
# guaranteed at DB-creation time via a C-locale cluster.
POSTGRES_INITDB_ARGS: "--lc-collate=C --lc-ctype=C"
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U bts -d bdwedge"
--health-interval 5s
--health-timeout 5s
--health-retries 20
mysql:
image: mysql:8
env:
MYSQL_ROOT_PASSWORD: bts
MYSQL_DATABASE: bdwedge
ports:
- 3306:3306
options: >-
--health-cmd "mysqladmin ping -uroot -pbts --silent"
--health-interval 5s
--health-timeout 5s
--health-retries 30
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
@ -65,23 +28,5 @@ jobs:
with:
go-version-file: 'go.mod'
# The MySQL image's root only auths from localhost inside the container; the
# backend connects over TCP as a distinct host, so create a TCP-reachable user
# matching BEADS_MYSQL_TEST_URL.
- name: Provision MySQL user
run: |
mysql -h 127.0.0.1 -P 3306 -uroot -pbts -e "
CREATE USER IF NOT EXISTS 'bts'@'%' IDENTIFIED BY 'bts';
GRANT ALL PRIVILEGES ON *.* TO 'bts'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;"
- name: Run conformance (Dolt + Postgres + MySQL + SQLite)
env:
BEADS_PG_TEST_URL: "postgres://bts:bts@127.0.0.1:5432/bdwedge"
BEADS_PG_PASSWORD: "bts"
BEADS_MYSQL_TEST_URL: "bts:bts@tcp(127.0.0.1:3306)/"
# Hard-fail (Tier 1 run_sql_conformance + Tier 2 e2e) if either real backend
# is absent, so removing/renaming a *_TEST_URL can't silently drop coverage
# while the gate still reports green.
BEADS_CONFORMANCE_REQUIRE: "postgres,mysql"
- name: Run conformance (embedded Dolt oracle)
run: ./scripts/conformance.sh

View file

@ -80,6 +80,8 @@ jobs:
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
go test -tags "$BEADS_BUILD_TAGS" -c -o artifacts/bd-cmd-test ./cmd/bd
chmod +x artifacts/bd-cmd-test
(
cd artifacts
sha256sum bd-linux-gms-pure > SHA256SUMS
@ -709,60 +711,67 @@ jobs:
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
# End-to-end coverage for proxied-server CLI subcommands, sharded across the
# CI matrix. Each sub-test drives the bd CLI subprocess against a real dolt
# sql-server started via testcontainers by the shared proxied harness
# (cmd/bd/*_proxied_integration_test.go).
#
# - name: Set up Go
# uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # 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/
# Reuses the cmd/bd test binary compiled once by build-artifacts (bd-cmd-test):
# the proxied tests share the package and are gated at runtime by
# BEADS_TEST_PROXIED_SERVER=1. Shard assignment is committed in
# .github/scripts/proxied-cmd-test-shards.txt; newly-added TestProxiedServer*
# tests hash-distribute until listed there. Adopt the
# `TestProxiedServer<Subcommand>` naming convention for new entry points.
test-proxied-cmd:
name: Test (proxied-server cmd ${{ matrix.shard }}/8)
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
needs: build-artifacts
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5, 6, 7, 8]
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
- 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 bd-cmd-test
- name: Install Dolt CLI
# TestProxiedServerExternalCreate needs the dolt binary on PATH; the
# shared harness itself uses the dolt sql-server container image.
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
# The shared proxied harness requires the image cached locally
# (isDoltImageCached); without it every proxied test self-skips. Keep the
# tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
run: docker pull dolthub/dolt-sql-server:2.2.0
- name: Test proxied-server cmd shard
env:
BEADS_TEST_PROXIED_SERVER: "1"
BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure
BEADS_TEST_CMD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-cmd-test
run: bash .github/scripts/proxied-test-shard.sh ${{ matrix.shard }} 8
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
#
@ -829,9 +838,10 @@ jobs:
BEADS_TEST_EMBEDDED_DOLT: "1"
BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test
# Conformance runs in the dedicated test-embedded-conformance job
# below (mirrors pr-risk.yml); skip it here so this job stays inside
# its 20m envelope as the base embedded suite grows.
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=20m -test.skip '^TestConformance$'
# below (mirrors pr-risk.yml); skip it here. The budget must cover
# every store-open re-running the full migration chain, which grows
# with each migration (bd-lrgn1 pushed a slow runner past 20m).
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.skip '^TestConformance$'
test-embedded-conformance:
name: Test (Embedded Dolt Conformance)

View file

@ -32,60 +32,62 @@ jobs:
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
# End-to-end coverage for proxied-server CLI subcommands, sharded across the
# CI matrix. Each sub-test drives the bd CLI subprocess against a real dolt
# sql-server started via testcontainers by the shared proxied harness
# (cmd/bd/*_proxied_integration_test.go).
#
# - name: Set up Go
# uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # 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/
# Reuses the cmd/bd test binary compiled once by build-embedded: the proxied
# tests live in the same package and are gated at runtime by
# BEADS_TEST_PROXIED_SERVER=1, so no separate build is needed. Shard
# assignment is committed in .github/scripts/proxied-cmd-test-shards.txt;
# newly-added TestProxiedServer* tests hash-distribute until listed there.
test-proxied-cmd:
name: Test (Proxied 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
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5, 6, 7, 8]
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-proxied /tmp/bd-cmd-test
- name: Install Dolt CLI
# TestProxiedServerExternalCreate needs the dolt binary on PATH; the
# shared harness itself uses the dolt sql-server container image.
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
# The shared proxied harness requires the image cached locally
# (isDoltImageCached); without it every proxied test self-skips. Keep the
# tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
run: docker pull dolthub/dolt-sql-server:2.2.0
- name: Test proxied-server cmd shard
env:
BEADS_TEST_PROXIED_SERVER: "1"
BEADS_TEST_BD_BINARY: /tmp/bd-proxied
BEADS_TEST_CMD_BINARY: /tmp/bd-cmd-test
run: bash .github/scripts/proxied-test-shard.sh ${{ matrix.shard }} 8
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
#
@ -115,6 +117,12 @@ jobs:
- name: Build embedded cmd test binary
run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/
# Non-race bd used as the proxied-server test subprocess. The proxied
# tests spawn bd many times per sub-test; a -race subprocess would slow
# every invocation, so build a plain binary for BEADS_TEST_BD_BINARY.
- name: Build proxied bd subprocess binary
run: go build -tags gms_pure_go -o /tmp/bd-proxied ./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
@ -130,6 +138,7 @@ jobs:
/tmp/bd-embedded-test
/tmp/embeddeddolt-test
/tmp/bd-cmd-test
/tmp/bd-proxied
/tmp/dolt-conformance-test
retention-days: 1
@ -160,9 +169,10 @@ jobs:
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$'
# it here. The budget must cover every store-open re-running the full
# migration chain, which grows with each migration (bd-lrgn1 pushed a
# slow runner past the old 20m).
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.skip '^TestConformance$'
test-embedded-conformance:
name: Test (Embedded Dolt Conformance)
@ -193,9 +203,9 @@ jobs:
# 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.
# 30m matches the repo's integration timeout: the audit suite is large and
# embedded Dolt under -race is slow, so 15m no longer left headroom.
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$'
# 45m gives the audit-heavy embedded run enough headroom without making
# the workflow open-ended.
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=45m -test.run '^TestConformance$'
test-server-storage:
name: Test (Server Dolt Conformance)
@ -308,6 +318,7 @@ jobs:
- test-embedded-conformance
- test-server-storage
- test-embedded-cmd
- test-proxied-cmd
- test-nix
if: ${{ always() }}
steps:
@ -323,6 +334,7 @@ jobs:
TEST_EMBEDDED_CONFORMANCE
TEST_SERVER_STORAGE
TEST_EMBEDDED_CMD
TEST_PROXIED_CMD
TEST_NIX
FULL_EMBEDDED: ${{ needs.detect-ci-tier.outputs.full_embedded }}
DETECT_CI_TIER: ${{ needs.detect-ci-tier.result }}
@ -331,11 +343,12 @@ jobs:
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_PROXIED_CMD: ${{ needs.test-proxied-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"
skipped_ok="BUILD_EMBEDDED TEST_EMBEDDED_STORAGE TEST_EMBEDDED_CONFORMANCE TEST_SERVER_STORAGE TEST_EMBEDDED_CMD TEST_PROXIED_CMD"
fi
export CI_GATE_SKIPPED_OK="$skipped_ok"
bash .github/scripts/ci-gate.sh

View file

@ -158,6 +158,14 @@ linters:
linters:
- gosec
text: "G705"
# G705: XSS via taint in CLI progress/warning/error output — every flagged
# sink is fmt.Fprint* to the terminal (os.Stderr or cobra's stdout/stderr
# writers), never a browser context (surfaced by the gosec bundled with
# golangci-lint v2.10)
- path: 'cmd/bd/(ado|doctor|errors|github|gitlab|hooks|jira|linear|main|notion|sync_push_pull)\.go'
linters:
- gosec
text: "G705"
# errcheck: fmt.Fprintf errors are noise in CLI help text generation
- path: 'cmd/bd/help_all\.go'
linters:
@ -174,11 +182,6 @@ linters:
linters:
- unparam
text: 'reimportConflicts|resolveConflictsByTimestamp'
# unparam: readOnly param kept for API symmetry with fix/sqlite_open.go
- path: 'cmd/bd/doctor/sqlite_open\.go'
linters:
- unparam
text: 'readOnly'
# unparam: childrenMap return computed for future parent-child display
- path: 'cmd/bd/list\.go'
linters:

View file

@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- **Storage backend scope simplified** (bd-sadcd). The recently merged direct
PostgreSQL and MySQL adapters have been rolled back before entering a tagged
release. Supporting additional general-purpose server databases introduced
dialect, credential, schema-lifecycle, migration, CI, and operational
complexity at odds with our goal of keeping Beads as simple as possible and
consuming as few resources as possible. The storage interface, shared issue
core, SQLite implementation, and conformance harness remain; embedded Dolt,
Dolt server, and SQLite are the supported storage paths. Dolt server mode and
its use of the MySQL wire protocol are unchanged. Existing PostgreSQL or
MySQL workspaces stop before their configured databases are opened or
modified; see the [migration
guide](docs/architecture/storage-backends.md#existing-postgresql-or-mysql-workspaces).
- **Cross-type blocking dependencies are now allowed** (bd-wg7ve,
[#4034](https://github.com/gastownhall/beads/pull/4034)).
`bd dep add <task> <epic>` — gating a work item on an epic (program)
@ -23,8 +35,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
entirely. A task gated on an epic becomes ready when the epic itself is
closed, consistent with `bd ready`/`bd blocked`.
- **Claim/unclaim refusals now steer toward the holder instead of teaching
eviction** (bd-at6rc, wyvern wy-zs5s2). The `--claim` refusal for an issue
assigned to someone else suggested `bd unclaim <id>` — in a multi-agent
fleet that copy taught an unclaim-then-claim steamroller that evicted a
live, heartbeated claim mid-review. The refusal now says to coordinate
with the holder, and unclaim's ownership rejection frames `--force` as an
abandoned-claim escape hatch rather than a routine override. (The
ownership check itself — foreign unclaim requires `--force` — landed in
[#4675](https://github.com/gastownhall/beads/pull/4675).)
### Added
- **Pool-aware claiming via the `claim.pools` config key** (bd-bguz6).
Dispatcher fleets pre-assign issues to a pool pseudo-assignee (e.g.
`fable-crew`); `--claim` previously refused those ("already assigned"),
forcing a two-step `--assignee <me> -s in_progress` per issue. Aliases
listed in `bd config set claim.pools "fable-crew,night-crew"` are now
claimable by any actor through the same atomic compare-and-swap — the
claim stamps the normal lease, and issues assigned to a real actor (or
to an alias not in the config) keep their anti-steal protection.
Pool-aware claiming works in every dolt mode — the proxied-server claim
path applies the same predicate — and `claim.*` is a recognized config
namespace (documented in `bd config --help`). Note: if a pool take's
lease expires, `bd reclaim` returns the issue to the unassigned pool,
not to the pool alias it was dispatched to.
Off by default: with no `claim.pools` configured, behavior is unchanged.
- **Work leases: claim-TTL, heartbeat, and reclaim for dead-worker recovery**
(schema v54, migration `0054`)
([#4537](https://github.com/gastownhall/beads/pull/4537)). A claim was

View file

@ -1,6 +1,6 @@
# PROPOSAL: Pluggable Storage Backends
**Status:** Draft for review (survived one adversarial review round; defects folded in)
**Status:** Historical — partially implemented, then superseded on 2026-07-16
**Date:** 2026-07-02
**Informed by:** the bts-rs Rust spike (a from-scratch Rust reimplementation
of the gc-contract surface that validated a backend-agnostic storage seam at 299/299 byte-parity
@ -8,6 +8,21 @@ across two radically different backends), a five-dimension recon of this repo's
architecture, and a two-reviewer adversarial verification pass. All file:line citations verified
against `worktree-beads-new`.
> **Superseded scope:** This proposal is retained as the design record for the
> storage interface, shared issue core, SQLite adapter, and differential
> conformance work that grew from it. Those pieces remain. The direct
> PostgreSQL and MySQL adapters were rolled back before entering a tagged
> release because supporting additional general-purpose server databases adds
> substantial dialect, credential, schema-lifecycle, migration, CI, and
> operational complexity. Our goal is to keep Beads as simple as possible and
> consume as few resources as possible. The supported paths are now embedded
> Dolt, Dolt server, and SQLite; Dolt server's use of the MySQL wire protocol is
> unchanged. See [Storage Backends](docs/architecture/storage-backends.md) for
> the current design.
Everything below this notice is retained as historical design material, not as
current backend support or migration guidance.
---
## 1. End state

View file

@ -109,7 +109,7 @@ version: sync remote-backed databases with your current `bd`, back up with
`bd export --all`, upgrade the binary, then run `bd info --whats-new`,
`bd hooks install`, and `bd version`. If the upgrade crosses a schema
migration on a remote-backed database, exactly one designated clone runs
`bd migrate --force` and `bd dolt push`; other clones install the new binary
`bd migrate` and `bd dolt push`; other clones install the new binary
and run `bd bootstrap`. See the full
[upgrade guide](https://beads.gascity.com/getting-started/upgrading)
or [docs/getting-started/installation.md](docs/getting-started/installation.md#updating-bd).
@ -140,10 +140,7 @@ migrate between modes with `bd backup`; reclaim space with `bd prune` /
`bd purge`.
Full detail — connection flags, sockets, maintenance, backup, and migration —
in the [Dolt backend guide](docs/architecture/dolt.md). Prefer a different
database? [Storage Backends](docs/architecture/storage-backends.md) covers
Postgres, MySQL, and SQLite (Dolt stays the default and the only backend
with history).
in the [Dolt backend guide](docs/architecture/dolt.md).
## 🌐 Community Tools
@ -179,9 +176,6 @@ This is useful for:
- **CI/CD** — isolated task tracking without repo-level side effects
- **Evaluation/testing** — ephemeral databases in `/tmp`
For daemon mode without git, use `bd daemon start --local`
(see [PR #433](https://github.com/gastownhall/beads/pull/433)).
## 📝 Documentation
* [Documentation site](https://beads.gascity.com/) | [Installing](docs/getting-started/installation.md) | [Sync Concepts](docs/core-concepts/sync-concepts.md) | [Agent Workflow](AGENT_INSTRUCTIONS.md) | [Copilot CLI Setup](docs/integrations/copilot-cli.md) | [Copilot VS Code MCP](docs/integrations/github-copilot.md) | [Articles](ARTICLES.md) | [Sync Branch Mode](docs/reference/protected-branches.md) | [Troubleshooting](docs/reference/troubleshooting.md) | [FAQ](docs/reference/faq.md)

View file

@ -11,18 +11,53 @@ import (
"context"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// Storage is the interface for beads storage operations
type Storage = beads.Storage
func configuredBackendUnavailable(backend string) error {
switch backend {
case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite:
return configfile.RemovedBackendError(backend)
default:
return configfile.UnknownBackendError(backend)
}
}
// Transaction provides atomic multi-operation support within a database transaction.
// Use Storage.RunInTransaction() to obtain a Transaction instance.
type Transaction = beads.Transaction
// DependencyAddOptions controls transaction-scoped dependency insertion for
// Transaction.AddDependencyWithOptions. Exported so embedders' bulk graph
// writers can set SkipCycleCheck per edge and run one whole-graph
// Transaction.CycleThroughEdges pass before commit (bd-6dnrw.8) instead of
// paying the recursive per-edge cycle query — which cannot finish inside a
// per-command budget on molecule-sized graphs (observed: a 67-node/100-edge
// batch blowing a 120s deadline mid-transaction, gascity 2026-07-17).
//
// Callers that set SkipCycleCheck MUST run Transaction.CycleThroughEdges before
// commit and fail on new blocks/conditional-blocks/parent-child cycles
// (waits-for is excluded); skipping the per-edge check trades per-edge cost for
// one whole-graph check, never graph integrity.
type DependencyAddOptions = storage.DependencyAddOptions
// CloseIssueOptions carries the optional inputs to Storage.CloseIssueChecked —
// an atomic, guarded close that refuses a still-blocked issue with
// ErrCloseBlocked unless Force is set. Exported so consumers can name it without
// importing internal/storage.
type CloseIssueOptions = storage.CloseIssueOptions
// CloseIssueResult reports the outcome of Storage.CloseIssueChecked. Unchanged
// is true when the issue was already closed (idempotent no-op).
type CloseIssueResult = storage.CloseIssueResult
// RemoteStore provides dolt remote management and replication operations.
// Use type assertion on a Storage value to access these methods:
//
@ -64,9 +99,9 @@ func Open(ctx context.Context, dbPath string) (Storage, error) {
return dolt.New(ctx, &dolt.Config{Path: dbPath, CreateIfMissing: true})
}
// OpenFromConfig opens a beads database using configuration from metadata.json.
// Unlike Open, this respects Dolt server mode settings and database name
// configuration, connecting to the Dolt SQL server when dolt_mode is "server".
// OpenFromConfig opens the Dolt implementation using configuration from
// metadata.json. Unlike Open, this respects Dolt server mode settings and database
// name configuration.
// beadsDir is the path to the .beads directory.
func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) {
return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true})
@ -172,3 +207,15 @@ const (
EventLabelRemoved = types.EventLabelRemoved
EventCompacted = types.EventCompacted
)
// Re-exported error sentinels so consumers match on errors.Is rather than
// on message text. Each is an ALIAS of the internal sentinel, so the identity
// is preserved across the package boundary.
var (
ErrNotFound = storage.ErrNotFound
ErrAlreadyClaimed = storage.ErrAlreadyClaimed
ErrNotClaimable = storage.ErrNotClaimable
ErrCloseBlocked = storage.ErrCloseBlocked
ErrSelfDependency = domain.ErrSelfDependency
ErrDependencyCycle = domain.ErrDependencyCycle
)

View file

@ -4,6 +4,7 @@ package beads
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/dolt"
@ -14,15 +15,25 @@ import (
// for the given .beads directory. It reads metadata.json to determine the
// configured mode:
//
// - Embedded mode (default): Opens via the CGo embedded Dolt engine.
// - Server mode: Connects to an external dolt sql-server via OpenFromConfig.
// - Embedded Dolt (default): Opens via the CGo embedded Dolt engine.
// - Dolt server: Connects to a dolt sql-server via OpenFromConfig.
//
// The returned Storage must be closed when no longer needed.
//
// beadsDir is the path to the .beads directory.
func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) {
cfg, err := configfile.Load(beadsDir)
if err == nil && cfg != nil && cfg.IsDoltServerMode() {
if err != nil {
return nil, fmt.Errorf("loading storage metadata: %w", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if !configfile.IsSupportedBackend(cfg.Backend) {
return nil, configuredBackendUnavailable(cfg.Backend)
}
if cfg.IsDoltServerMode() {
store, err := dolt.NewFromConfig(ctx, beadsDir)
if err != nil {
return nil, err

View file

@ -11,13 +11,23 @@ import (
)
// OpenBestAvailable opens a beads database using the best available backend
// for the given .beads directory. In non-CGO builds, only server mode is
// supported; embedded mode returns an error directing the user to server mode.
// for the given .beads directory. In non-CGO builds, only Dolt server mode is
// supported; embedded Dolt returns an error directing the user to server mode.
//
// beadsDir is the path to the .beads directory.
func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) {
cfg, err := configfile.Load(beadsDir)
if err == nil && cfg != nil && cfg.IsDoltServerMode() {
if err != nil {
return nil, fmt.Errorf("loading storage metadata: %w", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if !configfile.IsSupportedBackend(cfg.Backend) {
return nil, configuredBackendUnavailable(cfg.Backend)
}
if cfg.IsDoltServerMode() {
store, err := dolt.NewFromConfig(ctx, beadsDir)
if err != nil {
return nil, err

45
cmd/bd/backend_support.go Normal file
View file

@ -0,0 +1,45 @@
package main
import (
"fmt"
"github.com/steveyegge/beads/internal/configfile"
)
func validateConfiguredBackend(cfg *configfile.Config) error {
if cfg == nil {
return nil
}
switch cfg.Backend {
case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite:
return configfile.RemovedBackendError(cfg.Backend)
case "", configfile.BackendDolt:
return nil
default:
return configfile.UnknownBackendError(cfg.Backend)
}
}
func requireDoltBackend(cfg *configfile.Config) error {
if err := validateConfiguredBackend(cfg); err != nil {
return err
}
if cfg != nil && cfg.GetBackend() != configfile.BackendDolt {
return fmt.Errorf("not using Dolt backend (configured backend %q)", cfg.GetBackend())
}
return nil
}
func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) {
cfg, err := configfile.Load(beadsDir)
if err != nil {
return nil, fmt.Errorf("loading config: %w", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if err := requireDoltBackend(cfg); err != nil {
return nil, err
}
return cfg, nil
}

View file

@ -43,11 +43,13 @@ func bdProxiedBlockedCapture(t *testing.T, bd string, p proxiedProject, args ...
}
func TestProxiedServerBlocked(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("json_and_text_with_blockers", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bk1")
t.Parallel()
p := newSharedProxiedProject(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)
@ -80,7 +82,8 @@ func TestProxiedServerBlocked(t *testing.T) {
})
t.Run("empty_case", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bk2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "bk2")
bdProxiedCreate(t, bd, p.dir, "Nothing blocked here")
out, err := bdProxiedRun(t, bd, p.dir, "blocked", "--json")
@ -102,7 +105,8 @@ func TestProxiedServerBlocked(t *testing.T) {
})
t.Run("parent_filter_restricts_to_descendants", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bk3")
t.Parallel()
p := newSharedProxiedProject(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)

View file

@ -191,12 +191,21 @@ Examples:
// name (e.g. dolt_database). Without this, server-mode rigs get the
// default name "beads" instead of their configured name. (GH#3029)
cfg, err := configfile.Load(beadsDir)
if err != nil || cfg == nil {
cfg = findParentConfig(beadsDir)
if err != nil {
return HandleError("failed to load %s: %v; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err)
}
if cfg == nil {
cfg, err = findParentConfig(beadsDir)
if err != nil {
return HandleError("failed to load ancestor storage metadata: %v; no storage database was opened or modified; fix or restore metadata.json and retry", err)
}
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if err := requireBootstrapDoltBackend(cfg); err != nil {
return HandleError("%v", err)
}
resolvedCfg, repairMsg, err := applyBootstrapMetadataRepair(beadsDir, cfg, !dryRun)
if err != nil {
@ -270,6 +279,13 @@ func noWorkspaceBootstrapPayload() map[string]interface{} {
}
}
func requireBootstrapDoltBackend(cfg *configfile.Config) error {
if err := validateConfiguredBackend(cfg); err != nil {
return err
}
return nil
}
func detectBootstrapAction(beadsDir string, cfg *configfile.Config) BootstrapPlan {
plan := BootstrapPlan{
BeadsDir: beadsDir,
@ -513,6 +529,9 @@ func confirmPrompt(message string, nonInteractive bool) bool {
}
func executeBootstrapPlan(plan BootstrapPlan, cfg *configfile.Config, nonInteractive bool) error {
if err := requireBootstrapDoltBackend(cfg); err != nil {
return err
}
if !confirmPrompt("Proceed?", nonInteractive) {
fmt.Fprintf(os.Stderr, "Aborted.\n")
return nil
@ -955,8 +974,10 @@ func isNonInteractiveBootstrap(flagValue bool) bool {
// findParentConfig walks up from beadsDir's parent looking for a
// .beads/metadata.json in ancestor directories. This handles the case where a
// rig subdirectory (its own git repo) doesn't have a local .beads but its
// parent workspace does. Returns nil if no parent config is found.
func findParentConfig(beadsDir string) *configfile.Config {
// parent workspace does. Returns nil if no parent config is found. A malformed
// or unreadable ancestor metadata file is authoritative and returned as an error;
// bootstrap must not skip it and select a more distant workspace or defaults.
func findParentConfig(beadsDir string) (*configfile.Config, error) {
// Start from the parent of beadsDir's enclosing directory.
// beadsDir is typically "<project>/.beads", so we start from <project>'s parent.
start := filepath.Dir(filepath.Dir(beadsDir))
@ -964,8 +985,12 @@ func findParentConfig(beadsDir string) *configfile.Config {
for dir := start; dir != "/" && dir != "."; {
candidate := filepath.Join(dir, ".beads")
if cfg, err := configfile.Load(candidate); err == nil && cfg != nil {
return cfg
cfg, err := configfile.Load(candidate)
if err != nil {
return nil, fmt.Errorf("%s: %w", configfile.ConfigPath(candidate), err)
}
if cfg != nil {
return cfg, nil
}
// Don't search above $HOME
@ -979,7 +1004,7 @@ func findParentConfig(beadsDir string) *configfile.Config {
}
dir = parent
}
return nil
return nil, nil
}
func init() {

View file

@ -0,0 +1,295 @@
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/configfile"
)
func TestBootstrapRejectsRemovedBackendsBeforeWorkspaceWrites(t *testing.T) {
bd := buildBDForInitTests(t)
for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} {
backend := backend
for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} {
args := args
mode := "execute"
if len(args) > 1 && args[1] == "--dry-run" {
mode = "dry-run"
}
t.Run(backend+"/"+mode, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadata := []byte(fmt.Sprintf("{\n \"database\": \"legacy.db\",\n \"backend\": %q,\n \"project_id\": \"legacy-project\"\n}\n", backend))
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write metadata.json: %v", err)
}
cmd := exec.Command(bd, args...)
cmd.Dir = root
cmd.Env = bootstrapBackendGuardEnv(root, beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Errorf("bd %s unexpectedly succeeded for removed backend %q:\n%s", strings.Join(args, " "), backend, out)
}
message := strings.ToLower(string(out))
for _, want := range removedBackendWantSubstrings(backend) {
if !strings.Contains(message, want) {
t.Errorf("bd %s error for %q missing %q:\n%s", strings.Join(args, " "), backend, want, message)
}
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read metadata.json after rejected bootstrap: %v", readErr)
}
if !bytes.Equal(after, metadata) {
t.Errorf("bd %s rewrote metadata.json for removed backend %q:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), backend, metadata, after)
}
assertNoBootstrapStorageArtifacts(t, beadsDir)
})
}
}
}
func TestBootstrapRejectsUnknownBackendBeforeWorkspaceWrites(t *testing.T) {
bd := buildBDForInitTests(t)
for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} {
mode := "execute"
if args[1] == "--dry-run" {
mode = "dry-run"
}
t.Run(mode, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadata := []byte("{\n \"backend\": \"mystery\",\n \"project_id\": \"legacy-project\"\n}\n")
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write metadata.json: %v", err)
}
cmd := exec.Command(bd, args...)
cmd.Dir = root
cmd.Env = bootstrapBackendGuardEnv(root, beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Errorf("bd %s unexpectedly accepted an unknown backend:\n%s", strings.Join(args, " "), out)
}
message := string(out)
for _, want := range []string{"not recognized", "no storage database was opened or modified", "dolt"} {
if !strings.Contains(message, want) {
t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, message)
}
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read metadata.json after rejected bootstrap: %v", readErr)
}
if !bytes.Equal(after, metadata) {
t.Errorf("bd %s rewrote unknown-backend metadata:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), metadata, after)
}
assertNoBootstrapStorageArtifacts(t, beadsDir)
})
}
}
func TestBootstrapRejectsCorruptMetadataBeforeWorkspaceWrites(t *testing.T) {
bd := buildBDForInitTests(t)
for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} {
mode := "execute"
if args[1] == "--dry-run" {
mode = "dry-run"
}
t.Run(mode, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadata := []byte("{\n")
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write corrupt metadata.json: %v", err)
}
cmd := exec.Command(bd, args...)
cmd.Dir = root
cmd.Env = bootstrapBackendGuardEnv(root, beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("bd %s unexpectedly ignored corrupt metadata:\n%s", strings.Join(args, " "), out)
}
message := strings.ToLower(string(out))
for _, want := range []string{"metadata.json", "no storage database was opened or modified"} {
if !strings.Contains(message, want) {
t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, out)
}
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read corrupt metadata after rejected bootstrap: %v", readErr)
}
if !bytes.Equal(after, metadata) {
t.Errorf("bd %s rewrote corrupt metadata:\nbefore: %q\nafter: %q", strings.Join(args, " "), metadata, after)
}
assertNoBootstrapStorageArtifacts(t, beadsDir)
})
}
}
func TestBootstrapDoesNotConvertExistingSQLiteWorkspace(t *testing.T) {
bd := buildBDForInitTests(t)
for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} {
args := args
mode := "execute"
if len(args) > 1 && args[1] == "--dry-run" {
mode = "dry-run"
}
t.Run(mode, func(t *testing.T) {
root := t.TempDir()
for _, gitArgs := range [][]string{
{"init", "-q"},
{"config", "user.email", "test@test.com"},
{"config", "user.name", "Test"},
{"config", "core.hooksPath", ".git/hooks"},
} {
runGitForBootstrapTest(t, root, gitArgs...)
}
// Hand-seed a workspace created by an earlier build's SQLite backend:
// metadata selecting the removed backend plus its database file. The
// guard must reject it without reading or rewriting either.
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
metadataBefore := []byte("{\n \"database\": \"beads.db\",\n \"backend\": \"sqlite\",\n \"sqlite_path\": \"beads.db\",\n \"project_id\": \"sqlite-guard\"\n}\n")
if err := os.WriteFile(metadataPath, metadataBefore, 0o600); err != nil {
t.Fatalf("write metadata.json: %v", err)
}
databasePath := filepath.Join(beadsDir, "beads.db")
databaseContent := []byte("sqlite-guard database placeholder")
if err := os.WriteFile(databasePath, databaseContent, 0o600); err != nil {
t.Fatalf("write beads.db: %v", err)
}
databaseBefore := sha256.Sum256(databaseContent)
localVersionBefore, hadLocalVersion := readOptionalBootstrapGuardFile(t, filepath.Join(beadsDir, ".local_version"))
cmd := exec.Command(bd, args...)
cmd.Dir = root
cmd.Env = bootstrapBackendGuardEnv(root, beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Errorf("bd %s unexpectedly accepted an existing SQLite workspace:\n%s", strings.Join(args, " "), out)
}
message := strings.ToLower(string(out))
if !strings.Contains(message, "sqlite") {
t.Errorf("bd %s should name the rejected backend:\n%s", strings.Join(args, " "), out)
}
for _, want := range removedBackendWantSubstrings(configfile.BackendSQLite) {
if !strings.Contains(message, want) {
t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, out)
}
}
metadataAfter := readBootstrapGuardFile(t, metadataPath)
if !bytes.Equal(metadataAfter, metadataBefore) {
t.Errorf("bd %s rewrote SQLite metadata.json:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), metadataBefore, metadataAfter)
}
databaseAfter := sha256.Sum256(readBootstrapGuardFile(t, databasePath))
if databaseAfter != databaseBefore {
t.Errorf("bd %s modified the existing SQLite database", strings.Join(args, " "))
}
localVersionAfter, hasLocalVersion := readOptionalBootstrapGuardFile(t, filepath.Join(beadsDir, ".local_version"))
if hasLocalVersion != hadLocalVersion || !bytes.Equal(localVersionAfter, localVersionBefore) {
t.Errorf("bd %s created or modified SQLite workspace version tracking", strings.Join(args, " "))
}
for _, name := range []string{"embeddeddolt", "dolt"} {
path := filepath.Join(beadsDir, name)
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Errorf("bd %s converted SQLite by creating Dolt state at %s (stat error: %v)", strings.Join(args, " "), path, statErr)
}
}
})
}
}
func bootstrapBackendGuardEnv(home, beadsDir string) []string {
env := make([]string, 0, len(os.Environ())+7)
for _, entry := range os.Environ() {
if strings.HasPrefix(entry, "BEADS_") || strings.HasPrefix(entry, "BD_") || strings.HasPrefix(entry, "HOME=") {
continue
}
env = append(env, entry)
}
return append(env,
"HOME="+home,
"BEADS_DIR="+beadsDir,
"BEADS_DOLT_AUTO_START=0",
"BEADS_NO_DAEMON=1",
"BEADS_TEST_IGNORE_REPO_CONFIG=1",
"BD_DISABLE_METRICS=1",
"BD_DISABLE_EVENT_FLUSH=1",
"BD_NON_INTERACTIVE=1",
)
}
func assertNoBootstrapStorageArtifacts(t *testing.T, beadsDir string) {
t.Helper()
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} {
path := filepath.Join(beadsDir, name)
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Errorf("rejected bootstrap created local state at %s (stat error: %v)", path, err)
}
}
}
func readBootstrapGuardFile(t *testing.T, path string) []byte {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return data
}
func readOptionalBootstrapGuardFile(t *testing.T, path string) ([]byte, bool) {
t.Helper()
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return nil, false
}
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return data, true
}

View file

@ -919,7 +919,10 @@ func TestBootstrapRigSubdirUsesParentDBName(t *testing.T) {
cfg, cfgErr := configfile.Load(synthesizedDir)
if cfgErr != nil || cfg == nil {
// This is the fix path: search parent directories for metadata.json
cfg = findParentConfig(synthesizedDir)
cfg, cfgErr = findParentConfig(synthesizedDir)
if cfgErr != nil {
t.Fatalf("findParentConfig: %v", cfgErr)
}
}
if cfg == nil {
cfg = configfile.DefaultConfig()
@ -939,6 +942,37 @@ func TestBootstrapRigSubdirUsesParentDBName(t *testing.T) {
}
}
func TestFindParentConfigDoesNotSkipCorruptNearestAncestor(t *testing.T) {
root := t.TempDir()
higherBeadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(higherBeadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(higherBeadsDir, "metadata.json"), []byte(`{"dolt_database":"wrong_higher_database"}`), 0o600); err != nil {
t.Fatal(err)
}
nearestBeadsDir := filepath.Join(root, "workspace", ".beads")
if err := os.MkdirAll(nearestBeadsDir, 0o750); err != nil {
t.Fatal(err)
}
corrupt := []byte("{\n")
metadataPath := filepath.Join(nearestBeadsDir, "metadata.json")
if err := os.WriteFile(metadataPath, corrupt, 0o600); err != nil {
t.Fatal(err)
}
synthesizedDir := filepath.Join(root, "workspace", "rig", ".beads")
if cfg, err := findParentConfig(synthesizedDir); err == nil {
t.Fatalf("findParentConfig skipped corrupt nearest metadata and selected higher database %q", cfg.GetDoltDatabase())
} else if !strings.Contains(err.Error(), filepath.Join("workspace", ".beads", "metadata.json")) {
t.Fatalf("findParentConfig error = %v, want nearest metadata path", err)
}
if after, err := os.ReadFile(metadataPath); err != nil || string(after) != string(corrupt) {
t.Fatalf("corrupt nearest metadata changed: got %q, err %v", after, err)
}
}
// TestDetectBootstrapAction_SharedServerEnvUsesSharedPath verifies that when
// BEADS_DOLT_SHARED_SERVER=1 is set but cfg.DoltMode is the default (embedded),
// detectBootstrapAction looks in the shared-server directory — not embeddeddolt/.
@ -1052,7 +1086,10 @@ func TestDetectBootstrapAction_WorktreeSynthesizedDirPrefersSyncOverDefaultShare
synthesizedDir := filepath.Join(localBare, ".beads")
cfg, cfgErr := configfile.Load(synthesizedDir)
if cfgErr != nil || cfg == nil {
cfg = findParentConfig(synthesizedDir)
cfg, cfgErr = findParentConfig(synthesizedDir)
if cfgErr != nil {
t.Fatalf("findParentConfig: %v", cfgErr)
}
}
if cfg == nil {
cfg = configfile.DefaultConfig()

View file

@ -0,0 +1,111 @@
//go:build cgo
package main
import (
"os"
"os/exec"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestEmbeddedClaimPools covers pool-aware claiming (bd-bguz6): issues
// pre-assigned to a pool alias listed in the claim.pools config are
// claimable by any actor through the normal --claim CAS, while issues
// assigned to a real actor (or to an unconfigured alias) keep their
// anti-steal protection. Mirrors the wyvern dispatcher pattern that
// pre-assigns review beads to "fable-crew".
func TestEmbeddedClaimPools(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", "tp")
cfgCmd := exec.Command(bd, "config", "set", "claim.pools", "fable-crew, night-crew")
cfgCmd.Dir = dir
cfgCmd.Env = bdEnv(dir)
if out, err := cfgCmd.CombinedOutput(); err != nil {
t.Fatalf("bd config set claim.pools failed: %v\n%s", err, out)
} else if strings.Contains(string(out), "not a recognized config key") {
// The exit code alone missed this once: claim.* must be a
// recognized namespace so the feature's setup command doesn't
// warn every adopter.
t.Fatalf("bd config set claim.pools warned about an unrecognized key:\n%s", out)
}
t.Run("claim_from_pool_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Pool-dispatched review", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "fable-crew")
bdUpdate(t, bd, dir, issue.ID, "--claim", "--actor", "tortoise")
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "tortoise" {
t.Errorf("assignee after pool claim = %q, want tortoise", got.Assignee)
}
if got.Status != types.StatusInProgress {
t.Errorf("status after pool claim = %s, want in_progress", got.Status)
}
// The full dispatcher flow: claim from pool, work, close — no
// reassign-then-close two-step (the friction reported in bd-bguz6).
bdClose(t, bd, dir, issue.ID, "--reason", "reviewed", "--actor", "tortoise")
gotClosed := bdShow(t, bd, dir, issue.ID)
if gotClosed.Status != types.StatusClosed {
t.Errorf("status after close = %s, want closed", gotClosed.Status)
}
})
t.Run("second_pool_alias_also_claimable", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Night shift item", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "night-crew")
bdUpdate(t, bd, dir, issue.ID, "--claim", "--actor", "owl")
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "owl" {
t.Errorf("assignee = %q, want owl", got.Assignee)
}
})
t.Run("real_actor_assignment_still_protected", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Alice's work", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice")
out := bdUpdateFail(t, bd, dir, issue.ID, "--claim", "--actor", "tortoise")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected anti-steal refusal, got: %s", out)
}
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "alice" {
t.Errorf("assignee after refused claim = %q, want alice (unchanged)", got.Assignee)
}
})
t.Run("unconfigured_alias_still_protected", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Other crew's work", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "other-crew")
out := bdUpdateFail(t, bd, dir, issue.ID, "--claim", "--actor", "tortoise")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected refusal for unconfigured alias, got: %s", out)
}
})
t.Run("pool_claim_stamps_lease", func(t *testing.T) {
// A pool take is a normal claim: it must carry a lease so the
// reclaim machinery can recover it if the taker dies.
issue := bdCreate(t, bd, dir, "Leased pool item", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "fable-crew")
bdUpdate(t, bd, dir, issue.ID, "--claim", "--actor", "tortoise")
raw := bdShowJSON(t, bd, dir, issue.ID)
if !strings.Contains(raw, "lease_expires_at") {
t.Errorf("pool claim should stamp a lease; show --json: %s", raw)
}
})
}

View file

@ -487,7 +487,7 @@ func checkGateSatisfaction(issue *types.Issue) error {
case issue.AwaitType == "timer":
resolved, escalated, reason, err = checkTimer(issue, time.Now())
case issue.AwaitType == "bead":
resolved, reason = checkBeadGate(rootCtx, issue.AwaitID)
resolved, reason = checkBeadGate(rootCtx, store, issue.AwaitID)
if resolved {
return nil
}

View file

@ -197,11 +197,13 @@ func readDoltLogCountSince(t *testing.T, db *sql.DB, sinceHash string) int {
}
func TestProxiedServerClose(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("basic_close", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cb")
t.Parallel()
p := newSharedProxiedProject(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)
@ -214,7 +216,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_default_reason", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cdr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cdr")
issue := bdProxiedCreate(t, bd, p.dir, "Default reason")
bdProxiedClose(t, bd, p.dir, issue.ID)
db := openProxiedDB(t, p)
@ -224,7 +227,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_reason", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cwr")
issue := bdProxiedCreate(t, bd, p.dir, "Reason test")
bdProxiedClose(t, bd, p.dir, issue.ID, "--reason", "done")
db := openProxiedDB(t, p)
@ -234,7 +238,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_reason_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwrs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cwrs")
issue := bdProxiedCreate(t, bd, p.dir, "Short reason")
bdProxiedClose(t, bd, p.dir, issue.ID, "-r", "fixed")
db := openProxiedDB(t, p)
@ -244,7 +249,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_message_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwma")
t.Parallel()
p := newSharedProxiedProject(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)
@ -254,7 +260,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_resolution_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwra")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cwra")
issue := bdProxiedCreate(t, bd, p.dir, "Resolution alias")
bdProxiedClose(t, bd, p.dir, issue.ID, "--resolution", "wontfix")
db := openProxiedDB(t, p)
@ -264,7 +271,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_comment_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwca")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cwca")
issue := bdProxiedCreate(t, bd, p.dir, "Comment alias")
bdProxiedClose(t, bd, p.dir, issue.ID, "--comment", "duplicate")
db := openProxiedDB(t, p)
@ -274,7 +282,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_multiple_ids", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cmi")
t.Parallel()
p := newSharedProxiedProject(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)
@ -288,7 +297,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_multiple_ids_with_per_id_reasons", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cmpr")
t.Parallel()
p := newSharedProxiedProject(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")
@ -302,7 +312,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_already_closed", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cac")
t.Parallel()
p := newSharedProxiedProject(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")
@ -316,7 +327,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_nonexistent_id", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cni")
t.Parallel()
p := newSharedProxiedProject(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)
@ -324,7 +336,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_blocked_refuses_without_force", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cbr")
t.Parallel()
p := newSharedProxiedProject(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)
@ -338,7 +351,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_blocked_with_force", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cbf")
t.Parallel()
p := newSharedProxiedProject(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")
@ -349,7 +363,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_pinned_refuses_without_force", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cpr")
t.Parallel()
p := newSharedProxiedProject(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)
@ -360,7 +375,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_pinned_with_force", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cpf")
t.Parallel()
p := newSharedProxiedProject(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")
@ -371,7 +387,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_epic_open_children_refuses", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ceor")
t.Parallel()
p := newSharedProxiedProject(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)
@ -381,7 +398,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_epic_open_children_force", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ceof")
t.Parallel()
p := newSharedProxiedProject(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")
@ -392,7 +410,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_last_child_keeps_regular_epic_open", func(t *testing.T) {
p := bdProxiedInit(t, bd, "clce")
t.Parallel()
p := newSharedProxiedProject(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)
@ -403,7 +422,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_unblocks_dependent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cud")
t.Parallel()
p := newSharedProxiedProject(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)
@ -417,7 +437,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_suggest_next", func(t *testing.T) {
p := bdProxiedInit(t, bd, "csn")
t.Parallel()
p := newSharedProxiedProject(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")
@ -427,7 +448,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_suggest_next_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "csnj")
t.Parallel()
p := newSharedProxiedProject(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")
@ -445,7 +467,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_claim_next", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ccn")
t.Parallel()
p := newSharedProxiedProject(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")
@ -459,7 +482,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_claim_next_no_ready", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ccnr")
t.Parallel()
p := newSharedProxiedProject(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") {
@ -468,7 +492,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_claim_next_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ccnj")
t.Parallel()
p := newSharedProxiedProject(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")
@ -481,7 +506,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_with_session", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cws")
t.Parallel()
p := newSharedProxiedProject(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)
@ -491,10 +517,12 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_session_from_env", func(t *testing.T) {
t.Setenv("CLAUDE_SESSION_ID", "sess-env")
p := bdProxiedInit(t, bd, "cse")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cse")
issue := bdProxiedCreate(t, bd, p.dir, "Session env")
bdProxiedClose(t, bd, p.dir, issue.ID)
if _, stderr, err := bdProxiedRunEnv(t, bd, p.dir, []string{"CLAUDE_SESSION_ID=sess-env"}, "close", issue.ID); err != nil {
t.Fatalf("close failed: %v\n%s", err, stderr)
}
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")
@ -502,7 +530,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cjo")
t.Parallel()
p := newSharedProxiedProject(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 {
@ -514,7 +543,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("done_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "da")
t.Parallel()
p := newSharedProxiedProject(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 {
@ -527,7 +557,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("done_positional_reason", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpr")
t.Parallel()
p := newSharedProxiedProject(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 {
@ -540,7 +571,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_continue_multiple_ids_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ccmi")
t.Parallel()
p := newSharedProxiedProject(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")
@ -550,7 +582,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_suggest_next_multiple_ids_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "csmi")
t.Parallel()
p := newSharedProxiedProject(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")
@ -560,7 +593,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("single_transaction_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "stdc")
t.Parallel()
p := newSharedProxiedProject(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")
@ -583,7 +617,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("no_ids_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "nie")
t.Parallel()
p := newSharedProxiedProject(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)
@ -591,7 +626,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("last_touched_not_supported", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ltns")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ltns")
_ = bdProxiedCreate(t, bd, p.dir, "Recent create")
out := bdProxiedCloseFail(t, bd, p.dir)
if !strings.Contains(out, "no issue ID provided") {
@ -600,7 +636,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_wisp_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cwi")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp close", "--ephemeral")
bdProxiedClose(t, bd, p.dir, wisp.ID)
db := openProxiedDB(t, p)
@ -615,7 +652,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_wisp_epic_open_children", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cweoc")
t.Parallel()
p := newSharedProxiedProject(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)
@ -625,7 +663,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("close_wisp_blocked_refuses", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cwbr")
t.Parallel()
p := newSharedProxiedProject(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)
@ -635,7 +674,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("continue_advances_to_next_ready_step", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cantrs")
t.Parallel()
p := newSharedProxiedProject(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)
@ -651,7 +691,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("continue_no_auto_does_not_claim", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cnac")
t.Parallel()
p := newSharedProxiedProject(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)
@ -666,7 +707,8 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("auto_close_completed_molecule", func(t *testing.T) {
p := bdProxiedInit(t, bd, "accm")
t.Parallel()
p := newSharedProxiedProject(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)
@ -681,12 +723,13 @@ func TestProxiedServerClose(t *testing.T) {
})
t.Run("hooks_fire_on_close", func(t *testing.T) {
t.Parallel()
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})
p := newSharedProxiedProjectWithHooks(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)
@ -704,10 +747,11 @@ func shellQuote(s string) string {
}
func TestProxiedServerCloseConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "cxc")
p := newSharedProxiedProject(t, bd, "cxc")
const (
numWorkers = 10

View file

@ -66,12 +66,14 @@ func bdProxiedCommentsJSON(t *testing.T, bd, dir string, args ...string) []*type
}
func TestProxiedServerComment(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("comment_shorthand_then_list", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cm")
issue := bdProxiedCreate(t, bd, p.dir, "Needs a comment")
out := bdProxiedComment(t, bd, p.dir, issue.ID, "first thoughts")
@ -86,7 +88,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comments_add_subcommand", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ca")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ca")
issue := bdProxiedCreate(t, bd, p.dir, "Add via subcommand")
if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "comments", "add", issue.ID, "via add"); err != nil {
@ -103,7 +106,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("multiple_comments_ordered", func(t *testing.T) {
p := bdProxiedInit(t, bd, "mo")
t.Parallel()
p := newSharedProxiedProject(t, bd, "mo")
issue := bdProxiedCreate(t, bd, p.dir, "Multi comment")
bdProxiedComment(t, bd, p.dir, issue.ID, "one")
@ -120,7 +124,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comment_json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cj")
issue := bdProxiedCreate(t, bd, p.dir, "JSON comment")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "comment", "--json", issue.ID, "json body")
@ -147,7 +152,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("no_comments_message", func(t *testing.T) {
p := bdProxiedInit(t, bd, "nc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "nc")
issue := bdProxiedCreate(t, bd, p.dir, "Uncommented")
out := bdProxiedComments(t, bd, p.dir, issue.ID)
@ -157,7 +163,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("empty_text_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "et")
t.Parallel()
p := newSharedProxiedProject(t, bd, "et")
issue := bdProxiedCreate(t, bd, p.dir, "Empty text")
out := bdProxiedCommentFail(t, bd, p.dir, issue.ID, "")
@ -167,7 +174,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("missing_issue_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "mi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "mi")
out := bdProxiedCommentFail(t, bd, p.dir, "mi-99999", "orphan comment")
if !strings.Contains(out, "not found") {
t.Errorf("expected not-found error, got:\n%s", out)
@ -175,7 +183,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comments_add_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "aj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "aj")
issue := bdProxiedCreate(t, bd, p.dir, "Add JSON")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "comments", "add", issue.ID, "add json body", "--json")
@ -199,7 +208,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comment_from_file", func(t *testing.T) {
p := bdProxiedInit(t, bd, "cf")
t.Parallel()
p := newSharedProxiedProject(t, bd, "cf")
issue := bdProxiedCreate(t, bd, p.dir, "Comment from file")
file := filepath.Join(t.TempDir(), "body.txt")
@ -219,7 +229,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comments_add_from_file", func(t *testing.T) {
p := bdProxiedInit(t, bd, "af")
t.Parallel()
p := newSharedProxiedProject(t, bd, "af")
issue := bdProxiedCreate(t, bd, p.dir, "Add from file")
file := filepath.Join(t.TempDir(), "note.txt")
@ -238,7 +249,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comments_list_local_time", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lt")
issue := bdProxiedCreate(t, bd, p.dir, "Local time")
bdProxiedComment(t, bd, p.dir, issue.ID, "timed comment")
@ -249,7 +261,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comment_on_wisp_routes_to_wisp_comments", func(t *testing.T) {
p := bdProxiedInit(t, bd, "wc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "wc")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp target", "--ephemeral")
out := bdProxiedComment(t, bd, p.dir, wisp.ID, "wisp comment")
@ -281,7 +294,8 @@ func TestProxiedServerComment(t *testing.T) {
})
t.Run("comments_add_on_wisp", func(t *testing.T) {
p := bdProxiedInit(t, bd, "wa")
t.Parallel()
p := newSharedProxiedProject(t, bd, "wa")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp add target", "--ephemeral")
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "comments", "add", wisp.ID, "wisp via add"); err != nil {

View file

@ -33,7 +33,9 @@ How it works:
2. Creates a squashed base commit from all old history
3. Cherry-picks recent commits on top
4. Swaps main branch to the compacted version
5. Runs Dolt GC to reclaim space
5. Prunes remote-tracking refs (they would keep the old history alive;
the next push or fetch re-creates them at the new tip)
6. Runs Dolt GC to reclaim space
Examples:
bd compact --dry-run # Preview: show commit breakdown
@ -175,29 +177,46 @@ Examples:
return HandleError("compact failed: %v", err)
}
// Prune remote-tracking refs before GC: they still anchor the
// pre-compact chain, and with them in place GC reclaims nothing on any
// workspace that has ever pushed or fetched (bd-agctw).
sizeBefore := storeSizeBytes()
pruned, tags := pruneRemoteRefsForGC(ctx)
if !jsonOutput {
printPruneReport(pruned, tags)
}
// Reclaim disk space from orphaned old history
if gc, ok := storage.UnwrapStore(store).(storage.GarbageCollector); ok {
if err := gc.DoltGC(ctx); err != nil {
WarnError("dolt gc after compact failed: %v", err)
}
}
sizeAfter := storeSizeBytes()
elapsed := time.Since(start)
resultCommits := len(recentHashes) + 1
if jsonOutput {
return outputJSON(map[string]interface{}{
"success": true,
"commits_before": totalCommits,
"commits_after": resultCommits,
"old_squashed": oldCommits,
"recent_kept": len(recentHashes),
"elapsed_ms": elapsed.Milliseconds(),
})
result := map[string]interface{}{
"success": true,
"commits_before": totalCommits,
"commits_after": resultCommits,
"old_squashed": oldCommits,
"recent_kept": len(recentHashes),
"remote_refs_pruned": pruned,
"tags_anchoring": tags,
"elapsed_ms": elapsed.Milliseconds(),
}
addGCSizeJSON(result, sizeBefore, sizeAfter)
return outputJSON(result)
}
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))
if line := gcSizeLine(sizeBefore, sizeAfter); line != "" {
fmt.Printf(" Store: %s\n", line)
}
fmt.Printf(" Time: %v\n", elapsed.Round(time.Millisecond))
return nil
},

View file

@ -39,6 +39,7 @@ Common namespaces:
- notion.* Notion integration settings
- custom.* Custom integration settings
- status.* Issue status configuration
- claim.* Claim arbitration settings (pool-aware claiming)
- doctor.suppress.* Suppress specific bd doctor warnings (GH#1095)
Auto-Export (config.yaml):
@ -72,6 +73,18 @@ Custom Status States:
This enables issues to use statuses like 'awaiting_review' in addition to
the built-in statuses (open, in_progress, blocked, deferred, closed).
Claim Pools:
A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g.
"fable-crew") and let any actor take them with --claim. List the pool
aliases in the claim.pools config key, comma-separated:
bd config set claim.pools "fable-crew,night-crew"
Issues assigned to a real actor (or to an alias not in the list) keep
their anti-steal protection. Pool takes carry the normal lease; note
that if a taker's lease expires, bd reclaim returns the issue to the
unassigned pool, not to the pool alias it was dispatched to.
Suppressing Doctor Warnings:
Suppress specific bd doctor warnings by check name slug:
bd config set doctor.suppress.pending-migrations true
@ -88,6 +101,7 @@ Examples:
bd config set jira.url "https://company.atlassian.net"
bd config set jira.project "PROJ"
bd config set status.custom "awaiting_review,awaiting_testing"
bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor
bd config set doctor.suppress.pending-migrations true
bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu)
bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init
@ -926,6 +940,7 @@ var recognizedConfigPrefixes = []string{
"status.", "types.", "doctor.suppress.", "routing.", "sync.", "git.",
"directory.", "repos.", "external_projects.", "validation.",
"hierarchy.", "ai.", "backup.", "federation.", "metrics.", "agent.",
"claim.",
}
// allRecognizedConfigPrefixes returns the static namespaces plus the prefix of

View file

@ -81,11 +81,13 @@ func proxiedDoltCommitCountSince(t *testing.T, db *sql.DB, sinceHash string) int
}
func TestProxiedServerConfig(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("config_set_and_get", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcs")
t.Parallel()
p := newSharedProxiedProject(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") {
@ -94,7 +96,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_set_overwrite", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pco")
t.Parallel()
p := newSharedProxiedProject(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")
@ -104,7 +107,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_set_namespaced", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcn")
t.Parallel()
p := newSharedProxiedProject(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") {
@ -113,7 +117,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_set_and_get_linear_state_map_dotted_key", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcd")
t.Parallel()
p := newSharedProxiedProject(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" {
@ -122,7 +127,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_list", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcl")
t.Parallel()
p := newSharedProxiedProject(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)
@ -130,7 +136,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_list_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcj")
bdProxiedConfig(t, bd, p.dir, "set", "test.key1", "hello")
m := bdProxiedConfigListJSON(t, bd, p.dir)
if _, ok := m["issue_prefix"]; !ok {
@ -142,7 +149,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_unset", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcu")
t.Parallel()
p := newSharedProxiedProject(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") {
@ -160,7 +168,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_get_missing_key", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcm")
t.Parallel()
p := newSharedProxiedProject(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)
@ -168,17 +177,20 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_set_no_args", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcsna")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcsna")
bdProxiedConfigFail(t, bd, p.dir, "set")
})
t.Run("config_unset_no_args", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcuna")
t.Parallel()
p := newSharedProxiedProject(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")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcsc")
db := openProxiedDB(t, p)
before := proxiedDoltHead(t, db)
@ -191,7 +203,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_unset_creates_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcuc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcuc")
bdProxiedConfig(t, bd, p.dir, "set", "test.commit", "v1")
db := openProxiedDB(t, p)
@ -206,7 +219,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_yaml_only_key_skips_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcy")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcy")
db := openProxiedDB(t, p)
before := proxiedDoltHead(t, db)
@ -240,7 +254,8 @@ func TestProxiedServerConfig(t *testing.T) {
})
t.Run("config_beads_role_skips_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcr")
db := openProxiedDB(t, p)
before := proxiedDoltHead(t, db)
@ -271,11 +286,13 @@ func TestProxiedServerConfig(t *testing.T) {
}
func TestProxiedServerConfigSetMany(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("set_many_single_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcsm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcsm")
db := openProxiedDB(t, p)
before := proxiedDoltHead(t, db)
@ -296,7 +313,8 @@ func TestProxiedServerConfigSetMany(t *testing.T) {
})
t.Run("set_many_cli_round_trip", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcsmr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcsmr")
bdProxiedConfig(t, bd, p.dir, "set-many",
"jira.url=https://example.atlassian.net",
"jira.project=PROJ",
@ -325,10 +343,11 @@ func TestProxiedServerConfigSetMany(t *testing.T) {
}
func TestProxiedServerConfigConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "pcc")
p := newSharedProxiedProject(t, bd, "pcc")
const numWorkers = 8

View file

@ -13,6 +13,7 @@ func TestIsRecognizedConfigKey(t *testing.T) {
"doctor.suppress.git-hooks", "no-git-ops", "beads.role",
"status.custom", "types.custom", "types.infra", "ai.model",
"backup.enabled", "import.path", "dolt.local-only", "agent.profile",
"claim.pools",
// Tracker namespaces are derived from the registry (GH#4427); cover
// ado (the original bug) plus the others removed from the static list.
"ado.org", "ado.project", "github.token", "linear.api-key",

View file

@ -13,11 +13,13 @@ import (
)
func TestProxiedServerContext(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "ctx")
p := newSharedProxiedProject(t, bd, "ctx")
t.Run("default_text", func(t *testing.T) {
t.Parallel()
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)
@ -31,6 +33,7 @@ func TestProxiedServerContext(t *testing.T) {
})
t.Run("json_fields", func(t *testing.T) {
t.Parallel()
info := proxiedContextJSON(t, bd, p)
if info.DoltMode != configfile.DoltModeProxiedServer {
@ -57,6 +60,7 @@ func TestProxiedServerContext(t *testing.T) {
})
t.Run("concurrent", func(t *testing.T) {
t.Parallel()
const numWorkers = 8
errs := make([]error, numWorkers)
modes := make([]string, numWorkers)

View file

@ -528,104 +528,45 @@ var createCmd = &cobra.Command{
ctx := createCtx
// Parse --deps BEFORE CreateIssue so multi-type same-target / invalid specs
// fail closed without leaving an orphan issue (GH#4626).
parsedDeps, err := parseDepSpecs(deps)
// Parse every requested dependency edge BEFORE creating anything so
// a malformed spec (incl. multi-type same-target, GH#4626) aborts
// with no orphan issue behind it.
depSpecs, err := parseDepSpecs(deps)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
// If any dependency is discovered-from, inherit source_repo from that parent.
for _, spec := range parsedDeps {
if spec.Type == types.DepDiscoveredFrom && spec.TargetID != "" {
parentIssue, gerr := store.GetIssue(ctx, spec.TargetID)
if gerr == nil && parentIssue.SourceRepo != "" {
issue.SourceRepo = parentIssue.SourceRepo
}
break
}
}
if err := store.CreateIssue(ctx, issue, actor); err != nil {
waitsForSpec, err := buildWaitsFor(waitsFor, waitsForGate)
if err != nil {
return HandleError("%v", err)
}
// Track whether any post-create writes occurred. CreateIssue commits
// the issue and its initial labels to Dolt internally, but subsequent
// AddDependency calls only write to the working set. A follow-up Dolt
// commit is needed to persist them (GH#2009).
postCreateWrites := false
// If parent was specified, add parent-child dependency
if parentID != "" {
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: parentID,
Type: types.DepParentChild,
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
WarnError("failed to add parent-child dependency %s -> %s: %v", issue.ID, parentID, err)
} else {
postCreateWrites = true
// If a discovered-from dependency is present, inherit source_repo
// from the referenced parent issue.
if dfParent := discoveredFromParent(deps); dfParent != "" {
parentIssue, err := store.GetIssue(ctx, dfParent)
if err == nil && parentIssue.SourceRepo != "" {
issue.SourceRepo = parentIssue.SourceRepo
}
// If error getting parent or parent has no source_repo, continue with default
}
// Apply pre-parsed deps (uniqueness already validated before create).
for _, spec := range parsedDeps {
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: spec.TargetID,
Type: spec.Type,
}
if spec.SwapDirection {
dep.IssueID = spec.TargetID
dep.DependsOnID = issue.ID
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
// Hard-fail: silent WarnError dropped edges and left issues un-gated (GH#4626).
return HandleErrorRespectJSON("failed to add dependency %s -> %s (%s): %v", dep.IssueID, dep.DependsOnID, dep.Type, err)
}
postCreateWrites = true
edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec}
if err := createIssueWithDeps(ctx, store, issue, actor, edges); err != nil {
return HandleErrorRespectJSON("%v", err)
}
if waitsFor != "" {
gate := waitsForGate
if gate == "" {
gate = types.WaitsForAllChildren
}
if gate != types.WaitsForAllChildren && gate != types.WaitsForAnyChildren {
return HandleError("invalid --waits-for-gate value '%s' (valid: all-children, any-children)", gate)
}
meta := types.WaitsForMeta{
Gate: gate,
}
metaJSON, err := json.Marshal(meta)
if edges.empty() {
// Bare create: preserve the embedded-mode follow-up Dolt commit.
// The deps path commits inside its transaction instead.
shouldCommit, err := shouldCommitCreatePostWrites(issue, false)
if err != nil {
return HandleError("failed to serialize waits-for metadata: %v", err)
return HandleError("dolt auto-commit failed: %v", err)
}
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: waitsFor,
Type: types.DepWaitsFor,
Metadata: string(metaJSON),
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
WarnError("failed to add waits-for dependency %s -> %s: %v", issue.ID, waitsFor, err)
} else {
postCreateWrites = true
}
}
shouldCommit, err := shouldCommitCreatePostWrites(issue, postCreateWrites)
if err != nil {
return HandleError("dolt auto-commit failed: %v", err)
}
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit: %v", err)
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit: %v", err)
}
}
}

126
cmd/bd/create_atomic.go Normal file
View file

@ -0,0 +1,126 @@
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// createDepEdges describes the dependency edges attached to a new issue at
// create time: --parent, --deps, and --waits-for.
type createDepEdges struct {
parentID string
specs []domain.DependencySpec
waitsFor *domain.WaitsForSpec
}
func (e createDepEdges) empty() bool {
return e.parentID == "" && len(e.specs) == 0 && e.waitsFor == nil
}
// createIssueWithDeps persists a new issue together with its create-time
// dependency edges in one transaction. The previous shape — commit the issue
// first, then add each edge in its own transaction with warn-only error
// handling — meant a failed dep-add still exited 0 and left a dep-less,
// permanently-ready bead behind for orchestrators to dispatch prematurely.
// Here any edge failure rolls back the create and is returned as a fatal
// error naming the failing edge.
//
// With no edges requested it delegates to store.CreateIssue so a bare create
// keeps its store-specific routing and commit behavior.
func createIssueWithDeps(ctx context.Context, st storage.DoltStorage, issue *types.Issue, actor string, edges createDepEdges) error {
if edges.empty() {
return st.CreateIssue(ctx, issue, actor)
}
// Store-level CreateIssue routes configured infra types to the wisps
// tables; transaction-level CreateIssue routes on the Ephemeral/NoHistory
// flags only, so resolve the routing up front (mirrors DoltStore and
// sqlkit CreateIssue).
if !issue.Ephemeral && !issue.NoHistory && st.IsInfraTypeCtx(ctx, issue.IssueType) {
issue.Ephemeral = true
}
// Auto-minted IDs are only known after tx.CreateIssue runs, so the Dolt
// commit message can name the issue only when the ID is already reserved
// (explicit --id or a parent-child child ID).
commitMsg := "bd: create"
if issue.ID != "" {
commitMsg = "bd: create " + issue.ID
}
return transactHonoringAutoCommit(ctx, st, commitMsg, func(tx storage.Transaction) error {
if err := tx.CreateIssue(ctx, issue, actor); err != nil {
return err
}
// issue.ID is only reserved after tx.CreateIssue for auto-minted IDs, so
// the edge helpers run after the create.
if err := addParentEdge(ctx, tx, issue.ID, edges.parentID, actor); err != nil {
return err
}
if err := addDepSpecEdges(ctx, tx, issue.ID, edges.specs, actor); err != nil {
return err
}
return addWaitsForEdge(ctx, tx, issue.ID, edges.waitsFor, actor)
})
}
// addParentEdge adds the --parent parent-child edge, if requested.
func addParentEdge(ctx context.Context, tx storage.Transaction, issueID, parentID, actor string) error {
if parentID == "" {
return nil
}
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: parentID,
Type: types.DepParentChild,
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding parent-child dependency %s -> %s: %w", issueID, parentID, err)
}
return nil
}
// addDepSpecEdges adds the --deps edges, honoring each spec's SwapDirection.
func addDepSpecEdges(ctx context.Context, tx storage.Transaction, issueID string, specs []domain.DependencySpec, actor string) error {
for _, spec := range specs {
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: spec.TargetID,
Type: spec.Type,
Metadata: spec.Metadata,
}
if spec.SwapDirection {
dep.IssueID, dep.DependsOnID = dep.DependsOnID, dep.IssueID
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
}
return nil
}
// addWaitsForEdge adds the --waits-for spawner-gate edge, if requested.
func addWaitsForEdge(ctx context.Context, tx storage.Transaction, issueID string, waitsFor *domain.WaitsForSpec, actor string) error {
if waitsFor == nil {
return nil
}
metaJSON, err := json.Marshal(types.WaitsForMeta{Gate: waitsFor.Gate})
if err != nil {
return fmt.Errorf("serializing waits-for metadata: %w", err)
}
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: waitsFor.SpawnerID,
Type: types.DepWaitsFor,
Metadata: string(metaJSON),
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding waits-for dependency %s -> %s: %w", issueID, waitsFor.SpawnerID, err)
}
return nil
}

View file

@ -0,0 +1,175 @@
package main
import (
"context"
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// createAtomicFakeTx records mutations made inside a fake transaction.
type createAtomicFakeTx struct {
storage.Transaction
created []*types.Issue
deps []*types.Dependency
failDep string // DependsOnID whose AddDependency fails
}
func (t *createAtomicFakeTx) CreateIssue(_ context.Context, issue *types.Issue, _ string) error {
if issue.ID == "" {
issue.ID = "fake-1"
}
cp := *issue
t.created = append(t.created, &cp)
return nil
}
func (t *createAtomicFakeTx) AddDependency(_ context.Context, dep *types.Dependency, _ string) error {
if t.failDep != "" && dep.DependsOnID == t.failDep {
return errors.New("issue " + dep.DependsOnID + " not found")
}
cp := *dep
t.deps = append(t.deps, &cp)
return nil
}
// createAtomicFakeStore counts store-level calls and applies transaction
// writes only when the callback commits (returns nil).
type createAtomicFakeStore struct {
storage.DoltStorage
txCount int
storeCreateCalls int
committedIssues []*types.Issue
committedDeps []*types.Dependency
failDep string
}
func (s *createAtomicFakeStore) IsInfraTypeCtx(context.Context, types.IssueType) bool { return false }
func (s *createAtomicFakeStore) CreateIssue(_ context.Context, issue *types.Issue, _ string) error {
s.storeCreateCalls++
if issue.ID == "" {
issue.ID = "fake-1"
}
cp := *issue
s.committedIssues = append(s.committedIssues, &cp)
return nil
}
func (s *createAtomicFakeStore) RunInTransaction(_ context.Context, _ string, fn func(tx storage.Transaction) error) error {
s.txCount++
tx := &createAtomicFakeTx{failDep: s.failDep}
if err := fn(tx); err != nil {
// Rollback: discard everything recorded inside the transaction.
return err
}
s.committedIssues = append(s.committedIssues, tx.created...)
s.committedDeps = append(s.committedDeps, tx.deps...)
return nil
}
// saveCreateAtomicGlobals snapshots the auto-commit globals that
// transactHonoringAutoCommit reads and writes.
func saveCreateAtomicGlobals(t *testing.T) {
t.Helper()
origAutoCommit := doltAutoCommit
origExplicit := commandDidExplicitDoltCommit
t.Cleanup(func() {
doltAutoCommit = origAutoCommit
commandDidExplicitDoltCommit = origExplicit
})
}
func TestCreateIssueWithDepsRunsOneTransaction(t *testing.T) {
saveCreateAtomicGlobals(t)
st := &createAtomicFakeStore{}
issue := &types.Issue{Title: "atomic create", Status: types.StatusOpen, IssueType: types.TypeTask}
edges := createDepEdges{
parentID: "fake-parent",
specs: []domain.DependencySpec{
{Type: types.DepBlocks, TargetID: "fake-dep1"},
{Type: types.DepBlocks, TargetID: "fake-dep2", SwapDirection: true},
},
waitsFor: &domain.WaitsForSpec{SpawnerID: "fake-spawner", Gate: types.WaitsForAllChildren},
}
if err := createIssueWithDeps(context.Background(), st, issue, "tester", edges); err != nil {
t.Fatalf("createIssueWithDeps: %v", err)
}
if st.txCount != 1 {
t.Errorf("RunInTransaction calls = %d, want 1", st.txCount)
}
if st.storeCreateCalls != 0 {
t.Errorf("store-level CreateIssue calls = %d, want 0 (create must run inside the transaction)", st.storeCreateCalls)
}
if len(st.committedIssues) != 1 || st.committedIssues[0].Title != "atomic create" {
t.Fatalf("committed issues = %+v, want the one created issue", st.committedIssues)
}
if len(st.committedDeps) != 4 {
t.Fatalf("committed deps = %d, want 4 (parent + 2 specs + waits-for)", len(st.committedDeps))
}
parent := st.committedDeps[0]
if parent.Type != types.DepParentChild || parent.IssueID != "fake-1" || parent.DependsOnID != "fake-parent" {
t.Errorf("parent edge = %+v, want fake-1 -> fake-parent (parent-child)", parent)
}
plain := st.committedDeps[1]
if plain.IssueID != "fake-1" || plain.DependsOnID != "fake-dep1" {
t.Errorf("plain edge = %+v, want fake-1 -> fake-dep1", plain)
}
swapped := st.committedDeps[2]
if swapped.IssueID != "fake-dep2" || swapped.DependsOnID != "fake-1" {
t.Errorf("swapped edge = %+v, want fake-dep2 -> fake-1", swapped)
}
wf := st.committedDeps[3]
if wf.Type != types.DepWaitsFor || wf.DependsOnID != "fake-spawner" || !strings.Contains(wf.Metadata, types.WaitsForAllChildren) {
t.Errorf("waits-for edge = %+v, want fake-1 -> fake-spawner with %q gate metadata", wf, types.WaitsForAllChildren)
}
}
func TestCreateIssueWithDepsRollsBackOnDepFailure(t *testing.T) {
saveCreateAtomicGlobals(t)
st := &createAtomicFakeStore{failDep: "fake-missing"}
issue := &types.Issue{Title: "doomed create", Status: types.StatusOpen, IssueType: types.TypeTask}
edges := createDepEdges{
specs: []domain.DependencySpec{
{Type: types.DepBlocks, TargetID: "fake-dep1"},
{Type: types.DepBlocks, TargetID: "fake-missing"},
},
}
err := createIssueWithDeps(context.Background(), st, issue, "tester", edges)
if err == nil {
t.Fatal("expected error when a dep-add fails")
}
if !strings.Contains(err.Error(), "fake-missing") {
t.Errorf("error should name the failing dependency, got: %v", err)
}
if len(st.committedIssues) != 0 {
t.Errorf("committed issues = %+v, want none (create must roll back with the failed dep)", st.committedIssues)
}
if len(st.committedDeps) != 0 {
t.Errorf("committed deps = %+v, want none", st.committedDeps)
}
}
func TestCreateIssueWithDepsEmptyEdgesUsesStoreCreate(t *testing.T) {
saveCreateAtomicGlobals(t)
st := &createAtomicFakeStore{}
issue := &types.Issue{Title: "bare create", Status: types.StatusOpen, IssueType: types.TypeTask}
if err := createIssueWithDeps(context.Background(), st, issue, "tester", createDepEdges{}); err != nil {
t.Fatalf("createIssueWithDeps: %v", err)
}
if st.storeCreateCalls != 1 {
t.Errorf("store-level CreateIssue calls = %d, want 1 (bare create keeps the store path)", st.storeCreateCalls)
}
if st.txCount != 0 {
t.Errorf("RunInTransaction calls = %d, want 0 for a bare create", st.txCount)
}
}

View file

@ -0,0 +1,208 @@
package main
// Regression tests for create-time dependency atomicity.
//
// `bd create --deps` used to commit the issue in one transaction and then add
// each dependency edge in its own transaction with warn-only error handling
// (WarnError + exit 0). A failed dep-add therefore exited 0 with valid JSON
// and left a dep-less bead behind — permanently READY, so an orchestrator
// polling `bd ready` would dispatch it before its prerequisites existed.
//
// The contract under test: the create and every requested dependency edge
// (--deps, --parent, --waits-for) commit in ONE transaction. Any dep failure
// fails the command with a nonzero exit and rolls back the create.
//
// These tests run the real bd binary against an isolated Dolt-backed
// workspace. The binary is built with the gms_pure_go embedded-Dolt engine
// (see buildBDForInitTests), so the tests need no external Dolt server and work
// in both cgo and pure-Go builds.
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// createDepsTestEnv returns a hermetic environment for the subprocess bd
// commands. It strips ambient BEADS_/BD_ configuration so a developer or CI
// shell pointing at a shared Dolt server (BEADS_DOLT_SERVER_*) or a real
// workspace (BEADS_DIR) cannot leak in, then pins BEADS_DIR at the isolated
// per-test workspace and keeps the child non-interactive.
func createDepsTestEnv(dir string) []string {
var env []string
for _, e := range os.Environ() {
if strings.HasPrefix(e, "BEADS_") || strings.HasPrefix(e, "BD_") {
continue
}
env = append(env, e)
}
return append(env,
"BEADS_DIR="+filepath.Join(dir, ".beads"),
"BD_NON_INTERACTIVE=1",
)
}
// runCreateDepsBD runs bd and returns stdout only. Warnings (e.g. the
// beads.role notice) go to stderr and must never leak into parsed output
// like --silent issue IDs.
func runCreateDepsBD(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = createDepsTestEnv(dir)
var stderr strings.Builder
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
t.Fatalf("bd %v failed: %v\nstdout:\n%s\nstderr:\n%s", args, err, out, stderr.String())
}
return string(out)
}
// runCreateDepsBDRaw runs bd and returns combined output plus the exit error,
// for asserting on failure output.
func runCreateDepsBDRaw(bd, dir string, args ...string) (string, error) {
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = createDepsTestEnv(dir)
out, err := cmd.CombinedOutput()
return string(out), err
}
// createDepsIssueTitles returns the set of issue titles visible in `bd list --json`.
func createDepsIssueTitles(t *testing.T, bd, dir string) map[string]bool {
t.Helper()
out := runCreateDepsBD(t, bd, dir, "list", "--json")
start := strings.Index(out, "[")
if start < 0 {
// An empty workspace may print a non-JSON "no issues" notice.
return map[string]bool{}
}
var issues []struct {
Title string `json:"title"`
}
if err := json.Unmarshal([]byte(out[start:]), &issues); err != nil {
t.Fatalf("parse bd list --json: %v\n%s", err, out)
}
titles := make(map[string]bool, len(issues))
for _, iss := range issues {
titles[iss.Title] = true
}
return titles
}
// createDepsExtractID pulls the created issue ID out of `bd create --json`
// output, which may carry warning lines before the JSON object.
func createDepsExtractID(t *testing.T, out string) string {
t.Helper()
start := strings.Index(out, "{")
if start < 0 {
t.Fatalf("no JSON object in create output:\n%s", out)
}
var issue struct {
ID string `json:"id"`
}
if err := json.Unmarshal([]byte(out[start:]), &issue); err != nil {
t.Fatalf("parse create --json output: %v\n%s", err, out)
}
if issue.ID == "" {
t.Fatalf("create --json output has empty id:\n%s", out)
}
return issue.ID
}
func TestCreateDepsAtomicity(t *testing.T) {
bd := buildBDForInitTests(t)
dir := t.TempDir()
runCreateDepsBD(t, bd, dir, "init", "--backend", "dolt", "--prefix", "test",
"--quiet", "--non-interactive", "--skip-hooks", "--skip-agents")
blocker := strings.TrimSpace(runCreateDepsBD(t, bd, dir, "create", "existing blocker", "--silent"))
if blocker == "" {
t.Fatal("blocker create returned empty ID")
}
t.Run("failed_dep_add_is_fatal_and_rolls_back_create", func(t *testing.T) {
out, err := runCreateDepsBDRaw(bd, dir, "create", "orphan candidate", "--json",
"--deps", "depends-on:test-missing1")
if err == nil {
t.Errorf("create with unresolvable dep exited 0; output:\n%s", out)
}
if !strings.Contains(out, "test-missing1") {
t.Errorf("error output should name the failing dependency target test-missing1, got:\n%s", out)
}
if createDepsIssueTitles(t, bd, dir)["orphan candidate"] {
t.Error("issue \"orphan candidate\" persisted despite failed dep-add (create not rolled back)")
}
})
t.Run("one_failing_dep_rolls_back_valid_deps_and_create", func(t *testing.T) {
out, err := runCreateDepsBDRaw(bd, dir, "create", "partial dep issue", "--json",
"--deps", "depends-on:"+blocker+",depends-on:test-missing2")
if err == nil {
t.Errorf("create with one unresolvable dep exited 0; output:\n%s", out)
}
if !strings.Contains(out, "test-missing2") {
t.Errorf("error output should name the failing dependency target test-missing2, got:\n%s", out)
}
if createDepsIssueTitles(t, bd, dir)["partial dep issue"] {
t.Error("issue \"partial dep issue\" persisted despite failed dep-add (create not rolled back)")
}
})
t.Run("waits_for_missing_spawner_is_fatal_and_rolls_back", func(t *testing.T) {
out, err := runCreateDepsBDRaw(bd, dir, "create", "waits-for orphan", "--json",
"--waits-for", "test-missing3")
if err == nil {
t.Errorf("create with unresolvable --waits-for exited 0; output:\n%s", out)
}
if !strings.Contains(out, "test-missing3") {
t.Errorf("error output should name the failing waits-for target test-missing3, got:\n%s", out)
}
if createDepsIssueTitles(t, bd, dir)["waits-for orphan"] {
t.Error("issue \"waits-for orphan\" persisted despite failed waits-for add (create not rolled back)")
}
})
t.Run("ready_never_offers_a_failed_create", func(t *testing.T) {
out := runCreateDepsBD(t, bd, dir, "ready", "--json")
for _, title := range []string{"orphan candidate", "partial dep issue", "waits-for orphan"} {
if strings.Contains(out, title) {
t.Errorf("bd ready offers %q, a bead whose create should have been rolled back:\n%s", title, out)
}
}
})
t.Run("happy_path_deps_created_atomically", func(t *testing.T) {
out := runCreateDepsBD(t, bd, dir, "create", "happy child", "--json",
"--deps", "depends-on:"+blocker)
child := createDepsExtractID(t, out)
depOut := runCreateDepsBD(t, bd, dir, "dep", "list", child, "--json")
if !strings.Contains(depOut, blocker) {
t.Errorf("dep list %s should include %s:\n%s", child, blocker, depOut)
}
readyOut := runCreateDepsBD(t, bd, dir, "ready", "--json")
if strings.Contains(readyOut, child) {
t.Errorf("child %s blocked by open %s must not be ready:\n%s", child, blocker, readyOut)
}
})
t.Run("invalid_dep_type_rejected_before_create", func(t *testing.T) {
out, err := runCreateDepsBDRaw(bd, dir, "create", "bad dep type issue", "--json",
"--deps", "bogus-type:"+blocker)
if err == nil {
t.Errorf("create with unknown dep type exited 0; output:\n%s", out)
}
if !strings.Contains(out, "unknown dependency type") {
t.Errorf("expected 'unknown dependency type' error, got:\n%s", out)
}
if createDepsIssueTitles(t, bd, dir)["bad dep type issue"] {
t.Error("issue \"bad dep type issue\" persisted despite invalid dep type")
}
})
}

View file

@ -12,6 +12,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
@ -145,61 +146,19 @@ func CreateIssueFromFormValues(ctx context.Context, s storage.DoltStorage, fv *c
issue.ID = explicitID
}
// Check if any dependencies are discovered-from type
// If so, inherit source_repo from the parent issue
var discoveredFromParentID string
for _, depSpec := range fv.Dependencies {
depSpec = strings.TrimSpace(depSpec)
if depSpec == "" {
continue
}
if strings.Contains(depSpec, ":") {
parts := strings.SplitN(depSpec, ":", 2)
if len(parts) == 2 {
depType := types.DependencyType(strings.TrimSpace(parts[0]))
dependsOnID := strings.TrimSpace(parts[1])
if depType == types.DepDiscoveredFrom && dependsOnID != "" {
discoveredFromParentID = dependsOnID
break
}
}
}
}
// If we found a discovered-from dependency, inherit source_repo from parent
if discoveredFromParentID != "" {
parentIssue, err := s.GetIssue(ctx, discoveredFromParentID)
// If a discovered-from dependency is present, inherit source_repo from
// the referenced parent issue.
if dfParent := discoveredFromParent(fv.Dependencies); dfParent != "" {
parentIssue, err := s.GetIssue(ctx, dfParent)
if err == nil && parentIssue != nil && parentIssue.SourceRepo != "" {
issue.SourceRepo = parentIssue.SourceRepo
}
}
if err := s.CreateIssue(ctx, issue, actor); err != nil {
return nil, fmt.Errorf("failed to create issue: %w", err)
}
// Track whether any post-create writes occurred. In embedded mode,
// CreateIssue writes the SQL working set and the caller must commit it.
// Subsequent AddDependency calls also need a follow-up Dolt commit.
postCreateWrites := false
// If parent was specified, add parent-child dependency (GH#1983)
if fv.ParentID != "" {
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: fv.ParentID,
Type: types.DepParentChild,
}
if err := s.AddDependency(ctx, dep, actor); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to add parent-child dependency %s -> %s: %v\n", issue.ID, fv.ParentID, err)
} else {
postCreateWrites = true
}
}
// Add dependencies if specified
// Parse dependency specs before creating anything. The form keeps its
// historical lenient parsing (warn and skip malformed entries), but the
// edges that do parse commit atomically with the create below.
var depSpecs []domain.DependencySpec
for _, depSpec := range fv.Dependencies {
depSpec = strings.TrimSpace(depSpec)
if depSpec == "" {
@ -211,10 +170,6 @@ func CreateIssueFromFormValues(ctx context.Context, s storage.DoltStorage, fv *c
if strings.Contains(depSpec, ":") {
parts := strings.SplitN(depSpec, ":", 2)
if len(parts) != 2 {
fmt.Fprintf(os.Stderr, "Warning: invalid dependency format '%s', expected 'type:id' or 'id'\n", depSpec)
continue
}
depType = types.DependencyType(strings.TrimSpace(parts[0]))
dependsOnID = strings.TrimSpace(parts[1])
} else {
@ -227,31 +182,29 @@ func CreateIssueFromFormValues(ctx context.Context, s storage.DoltStorage, fv *c
continue
}
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: dependsOnID,
Type: depType,
}
if err := s.AddDependency(ctx, dep, actor); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to add dependency %s -> %s: %v\n", issue.ID, dependsOnID, err)
} else {
postCreateWrites = true
}
depSpecs = append(depSpecs, domain.DependencySpec{Type: depType, TargetID: dependsOnID})
}
// Match bd create: server-mode writes version themselves, while embedded
// create commits pending writes only when auto-commit is on.
shouldCommit, err := shouldCommitCreatePostWrites(issue, postCreateWrites)
if err != nil {
return nil, fmt.Errorf("dolt auto-commit: %w", err)
// The issue and its edges (parent-child per GH#1983, plus form deps)
// commit in one transaction; a failed edge rolls back the create instead
// of leaving a dep-less issue behind (same contract as bd create).
edges := createDepEdges{parentID: fv.ParentID, specs: depSpecs}
if err := createIssueWithDeps(ctx, s, issue, actor, edges); err != nil {
return nil, fmt.Errorf("failed to create issue: %w", err)
}
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if postCreateWrites {
commitMsg = fmt.Sprintf("bd: create %s (metadata)", issue.ID)
if edges.empty() {
// Bare create: preserve the embedded-mode follow-up Dolt commit.
// The deps path commits inside its transaction instead.
shouldCommit, err := shouldCommitCreatePostWrites(issue, false)
if err != nil {
return nil, fmt.Errorf("dolt auto-commit: %w", err)
}
if err := s.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit post-create metadata: %v", err)
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if err := s.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit post-create metadata: %v", err)
}
}
}

View file

@ -16,12 +16,14 @@ import (
)
func TestProxiedServerCreate(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("basic", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "bc")
issue := bdProxiedCreate(t, bd, p.dir, "Basic issue")
if issue.ID == "" {
t.Fatal("expected issue ID")
@ -44,7 +46,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("title_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "tf")
t.Parallel()
p := newSharedProxiedProject(t, bd, "tf")
issue := bdProxiedCreate(t, bd, p.dir, "--title", "Title via flag")
if issue.Title != "Title via flag" {
t.Errorf("title: got %q, want %q", issue.Title, "Title via flag")
@ -52,7 +55,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("silent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sl")
id := bdProxiedCreateSilent(t, bd, p.dir, "Silent issue")
if id == "" {
t.Fatal("expected issue ID from --silent")
@ -63,7 +67,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("priority", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pr")
for _, tc := range []struct {
flag string
want int
@ -80,7 +85,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("issue_types", func(t *testing.T) {
p := bdProxiedInit(t, bd, "it")
t.Parallel()
p := newSharedProxiedProject(t, bd, "it")
for _, issueType := range []string{"bug", "feature", "task", "epic", "chore", "decision"} {
t.Run(issueType, func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("Type %s", issueType), "-t", issueType)
@ -93,7 +99,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("description", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ds")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ds")
issue := bdProxiedCreate(t, bd, p.dir, "Desc issue", "-d", "This is the description")
if issue.Description != "This is the description" {
t.Errorf("description: got %q, want %q", issue.Description, "This is the description")
@ -101,7 +108,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("design_and_acceptance", func(t *testing.T) {
p := bdProxiedInit(t, bd, "da")
t.Parallel()
p := newSharedProxiedProject(t, bd, "da")
issue := bdProxiedCreate(t, bd, p.dir, "Design issue",
"--design", "Use MVC pattern",
"--acceptance", "All tests pass")
@ -114,7 +122,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("assignee", func(t *testing.T) {
p := bdProxiedInit(t, bd, "as")
t.Parallel()
p := newSharedProxiedProject(t, bd, "as")
issue := bdProxiedCreate(t, bd, p.dir, "Assigned issue", "-a", "alice")
if issue.Assignee != "alice" {
t.Errorf("assignee: got %q, want %q", issue.Assignee, "alice")
@ -122,7 +131,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lb")
issue := bdProxiedCreate(t, bd, p.dir, "Labeled issue", "-l", "bug,critical")
db := openProxiedDB(t, p)
@ -137,7 +147,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("explicit_id", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ei")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ei")
issue := bdProxiedCreate(t, bd, p.dir, "Explicit ID", "--id", "ei-custom42")
if issue.ID != "ei-custom42" {
t.Errorf("ID: got %q, want %q", issue.ID, "ei-custom42")
@ -145,7 +156,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("dependencies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dp")
parent := bdProxiedCreate(t, bd, p.dir, "Parent issue")
child := bdProxiedCreate(t, bd, p.dir, "Child issue", "--deps", "blocks:"+parent.ID)
@ -154,7 +166,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("blocked_by_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "bb")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker issue")
blocked := bdProxiedCreate(t, bd, p.dir, "Blocked issue", "--deps", "blocked-by:"+blocker.ID)
@ -163,7 +176,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("depends_on_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "do")
t.Parallel()
p := newSharedProxiedProject(t, bd, "do")
prereq := bdProxiedCreate(t, bd, p.dir, "Prerequisite")
dependent := bdProxiedCreate(t, bd, p.dir, "Dependent issue", "--deps", "depends-on:"+prereq.ID)
@ -172,7 +186,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("unknown_dep_type_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ud")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ud")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker")
out := bdProxiedCreateFail(t, bd, p.dir, "Bad dep type", "--deps", "bogus-type:"+blocker.ID)
if !strings.Contains(out, "unknown dependency type") {
@ -184,7 +199,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("multiple_dependencies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "md")
t.Parallel()
p := newSharedProxiedProject(t, bd, "md")
dep1 := bdProxiedCreate(t, bd, p.dir, "Dep 1")
dep2 := bdProxiedCreate(t, bd, p.dir, "Dep 2")
child := bdProxiedCreate(t, bd, p.dir, "Multi dep issue",
@ -196,7 +212,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("parent_child", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pc")
parent := bdProxiedCreate(t, bd, p.dir, "Parent epic", "-t", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child task", "--parent", parent.ID)
@ -208,7 +225,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("parent_label_inheritance", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pi")
parent := bdProxiedCreate(t, bd, p.dir, "Parent with labels", "-t", "epic", "-l", "team-a,priority:high")
child := bdProxiedCreate(t, bd, p.dir, "Child inherits", "--parent", parent.ID)
@ -224,7 +242,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("parent_no_inherit_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ni")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ni")
parent := bdProxiedCreate(t, bd, p.dir, "Parent", "-t", "epic", "-l", "inherited-label")
child := bdProxiedCreate(t, bd, p.dir, "Child no inherit", "--parent", parent.ID, "--no-inherit-labels", "-l", "own-label")
@ -243,7 +262,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("due_date", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dd")
issue := bdProxiedCreate(t, bd, p.dir, "Due issue", "--due", "+24h")
if issue.DueAt == nil {
t.Fatal("expected DueAt to be set")
@ -256,7 +276,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("defer_until", func(t *testing.T) {
p := bdProxiedInit(t, bd, "df")
t.Parallel()
p := newSharedProxiedProject(t, bd, "df")
issue := bdProxiedCreate(t, bd, p.dir, "Deferred issue", "--defer", "+2h")
if issue.DeferUntil == nil {
t.Fatal("expected DeferUntil to be set")
@ -269,7 +290,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("ephemeral", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ep")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ep")
issue := bdProxiedCreate(t, bd, p.dir, "Ephemeral issue", "--ephemeral")
db := openProxiedDB(t, p)
@ -283,7 +305,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("no_history", func(t *testing.T) {
p := bdProxiedInit(t, bd, "nh")
t.Parallel()
p := newSharedProxiedProject(t, bd, "nh")
issue := bdProxiedCreate(t, bd, p.dir, "No history issue", "--no-history")
if issue.ID == "" {
t.Fatal("expected issue ID")
@ -291,7 +314,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("estimate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "es")
t.Parallel()
p := newSharedProxiedProject(t, bd, "es")
issue := bdProxiedCreate(t, bd, p.dir, "Estimated issue", "-e", "60")
if issue.EstimatedMinutes == nil || *issue.EstimatedMinutes != 60 {
t.Errorf("estimate: got %v, want 60", issue.EstimatedMinutes)
@ -299,7 +323,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("notes", func(t *testing.T) {
p := bdProxiedInit(t, bd, "nt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "nt")
issue := bdProxiedCreate(t, bd, p.dir, "Notes issue", "--notes", "Some notes here")
if issue.Notes != "Some notes here" {
t.Errorf("notes: got %q, want %q", issue.Notes, "Some notes here")
@ -307,7 +332,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("spec_id", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sp")
issue := bdProxiedCreate(t, bd, p.dir, "Spec issue", "--spec-id", "sp-spec1")
if issue.SpecID != "sp-spec1" {
t.Errorf("spec_id: got %q, want %q", issue.SpecID, "sp-spec1")
@ -315,7 +341,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("external_ref", func(t *testing.T) {
p := bdProxiedInit(t, bd, "er")
t.Parallel()
p := newSharedProxiedProject(t, bd, "er")
issue := bdProxiedCreate(t, bd, p.dir, "External ref issue", "--external-ref", "gh-123")
if issue.ExternalRef == nil || *issue.ExternalRef != "gh-123" {
t.Errorf("external_ref: got %v, want %q", issue.ExternalRef, "gh-123")
@ -323,7 +350,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("linear_external_ref", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ler")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ler")
ref := "https://linear.app/team/issue/TEAM-123/fix-login"
issue := bdProxiedCreate(t, bd, p.dir, "Pre-linked Linear issue", "--external-ref", ref)
if issue.ExternalRef == nil || *issue.ExternalRef != ref {
@ -332,7 +360,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("metadata", func(t *testing.T) {
p := bdProxiedInit(t, bd, "mt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "mt")
issue := bdProxiedCreate(t, bd, p.dir, "Metadata issue", "--metadata", `{"key":"value"}`)
if issue.Metadata == nil {
t.Fatal("expected metadata to be set")
@ -347,7 +376,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("dry_run", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dr")
out, err := bdProxiedRun(t, bd, p.dir, "create", "--dry-run", "Dry run issue", "--json")
if err != nil {
t.Fatalf("bd create --dry-run failed: %v\n%s", err, out)
@ -366,7 +396,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("skills_and_context", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sc")
issue := bdProxiedCreate(t, bd, p.dir, "Skills issue",
"--skills", "Go, SQL",
"--context", "Working on embedded storage")
@ -379,7 +410,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("discovered_from_dep", func(t *testing.T) {
p := bdProxiedInit(t, bd, "di")
t.Parallel()
p := newSharedProxiedProject(t, bd, "di")
parent := bdProxiedCreate(t, bd, p.dir, "Parent work")
child := bdProxiedCreate(t, bd, p.dir, "Discovered bug",
"--deps", "discovered-from:"+parent.ID)
@ -391,7 +423,8 @@ func TestProxiedServerCreate(t *testing.T) {
})
t.Run("markdown_bulk_create", func(t *testing.T) {
p := bdProxiedInit(t, bd, "mk")
t.Parallel()
p := newSharedProxiedProject(t, bd, "mk")
mdContent := `## First issue
### Priority
@ -436,7 +469,8 @@ A new feature
})
t.Run("both_due_and_defer", func(t *testing.T) {
p := bdProxiedInit(t, bd, "bd2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "bd2")
issue := bdProxiedCreate(t, bd, p.dir, "Both due and defer", "--due", "+48h", "--defer", "+24h")
if issue.DueAt == nil {
t.Fatal("expected DueAt to be set")
@ -447,7 +481,8 @@ A new feature
})
t.Run("parent_label_inheritance_merge", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pm")
parent := bdProxiedCreate(t, bd, p.dir, "Parent with a,b", "-t", "epic", "-l", "a,b")
child := bdProxiedCreate(t, bd, p.dir, "Child with c,a", "--parent", parent.ID, "-l", "c,a")
@ -468,7 +503,8 @@ A new feature
})
t.Run("parent_no_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pn")
parent := bdProxiedCreate(t, bd, p.dir, "Labelless parent", "-t", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child of labelless", "--parent", parent.ID)
@ -480,7 +516,8 @@ A new feature
})
t.Run("discovered_from_inherits_source_repo", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sr")
parent := bdProxiedCreate(t, bd, p.dir, "Parent with source repo")
db := openProxiedDB(t, p)
@ -505,7 +542,8 @@ A new feature
})
t.Run("no_title_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "nt2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "nt2")
out := bdProxiedCreateFail(t, bd, p.dir)
if !strings.Contains(out, "title") {
t.Errorf("expected title-related error, got: %s", out)
@ -513,7 +551,8 @@ A new feature
})
t.Run("graph_basic", func(t *testing.T) {
p := bdProxiedInit(t, bd, "gb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "gb")
plan := `{
"nodes": [
{"key": "a", "title": "Node A", "type": "task"},
@ -544,7 +583,8 @@ A new feature
})
t.Run("graph_parent_child_top_level_ids", func(t *testing.T) {
p := bdProxiedInit(t, bd, "gpc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "gpc")
plan := `{
"nodes": [
{"key": "child", "title": "Child", "type": "task", "parent_key": "parent"},
@ -575,7 +615,8 @@ A new feature
})
t.Run("graph_dry_run_db_aware", func(t *testing.T) {
p := bdProxiedInit(t, bd, "gdr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "gdr")
db := openProxiedDB(t, p)
_, err := db.ExecContext(context.Background(),
`REPLACE INTO config (`+"`key`"+`, value) VALUES (?, ?)`,
@ -607,7 +648,8 @@ A new feature
})
t.Run("graph_initial_labels_not_duplicated", func(t *testing.T) {
p := bdProxiedInit(t, bd, "gil")
t.Parallel()
p := newSharedProxiedProject(t, bd, "gil")
plan := `{
"nodes": [
{"key": "root", "title": "Graph root", "type": "task", "labels": ["team-a", "shared"]}

View file

@ -1,6 +1,7 @@
package main
import (
"context"
"errors"
"fmt"
"strings"
@ -14,21 +15,18 @@ import (
)
var (
dbProxyChildRoot string
dbProxyChildPort int
dbProxyChildIdleTimeout time.Duration
dbProxyChildBackend string
dbProxyChildConfig string
dbProxyChildLogPath string
dbProxyChildDoltBin string
dbProxyChildDatabase string
dbProxyChildExternalHost string
dbProxyChildExternalPort int
dbProxyChildExternalSocketPath string
dbProxyChildExternalTLS bool
dbProxyChildExternalTLSCertPath string
dbProxyChildExternalTLSKeyPath string
dbProxyChildExternalKeepAlive time.Duration
dbProxyChildRoot string
dbProxyChildPort int
dbProxyChildIdleTimeout time.Duration
dbProxyChildBackend string
dbProxyChildConfig string
dbProxyChildLogPath string
dbProxyChildDoltBin string
dbProxyChildDatabase string
dbProxyChildExternalHost string
dbProxyChildExternalPort int
dbProxyChildExternalSocketPath string
dbProxyChildExternalKeepAlive time.Duration
)
var dbProxyChildCmd = &cobra.Command{
@ -52,9 +50,6 @@ not intended to be invoked directly by users.`,
Host: dbProxyChildExternalHost,
Port: dbProxyChildExternalPort,
Socket: dbProxyChildExternalSocketPath,
TLSRequired: dbProxyChildExternalTLS,
TLSCert: dbProxyChildExternalTLSCertPath,
TLSKey: dbProxyChildExternalTLSKeyPath,
KeepAlivePeriod: dbProxyChildExternalKeepAlive,
}
@ -62,6 +57,7 @@ not intended to be invoked directly by users.`,
if err != nil {
return err
}
defer func() { _ = srv.Stop(context.Background()) }()
p := proxy.NewProxyServer(proxy.ProxyOpts{
RootDir: dbProxyChildRoot,
@ -104,9 +100,6 @@ func init() {
dbProxyChildCmd.Flags().StringVar(&dbProxyChildExternalHost, "external-host", "", "external backend: hostname or IP of the dolt sql-server")
dbProxyChildCmd.Flags().IntVar(&dbProxyChildExternalPort, "external-port", 0, "external backend: TCP port of the dolt sql-server")
dbProxyChildCmd.Flags().StringVar(&dbProxyChildExternalSocketPath, "external-socket-path", "", "external backend: absolute path to a unix domain socket (overrides host/port)")
dbProxyChildCmd.Flags().BoolVar(&dbProxyChildExternalTLS, "external-tls", false, "external backend: require TLS in the MySQL handshake")
dbProxyChildCmd.Flags().StringVar(&dbProxyChildExternalTLSCertPath, "external-tls-cert-path", "", "external backend: absolute path to client TLS certificate (mTLS)")
dbProxyChildCmd.Flags().StringVar(&dbProxyChildExternalTLSKeyPath, "external-tls-key-path", "", "external backend: absolute path to client TLS private key (mTLS)")
dbProxyChildCmd.Flags().DurationVar(&dbProxyChildExternalKeepAlive, "external-keep-alive", 0, "external backend: TCP keepalive period (default 30s)")
_ = dbProxyChildCmd.MarkFlagRequired("root")
_ = dbProxyChildCmd.MarkFlagRequired("port")

View file

@ -74,9 +74,6 @@ func TestDbProxyChildRegistersExternalFlags(t *testing.T) {
{"external-host", ""},
{"external-port", "0"},
{"external-socket-path", ""},
{"external-tls", "false"},
{"external-tls-cert-path", ""},
{"external-tls-key-path", ""},
{"external-keep-alive", "0s"},
}
for _, tc := range cases {

View file

@ -14,11 +14,13 @@ import (
)
func TestProxiedServerDelete(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("delete_single_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dsi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dsi")
issue := bdProxiedCreate(t, bd, p.dir, "Delete me", "-t", "task")
bdProxiedDelete(t, bd, p.dir, issue.ID, "--force")
db := openProxiedDB(t, p)
@ -26,7 +28,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_without_force_shows_preview", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwf")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwf")
issue := bdProxiedCreate(t, bd, p.dir, "Preview only", "-t", "task")
out := bdProxiedDelete(t, bd, p.dir, issue.ID)
@ -39,7 +42,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_clears_aux_tables", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dcat")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dcat")
neighbor := bdProxiedCreate(t, bd, p.dir, "Neighbor", "-t", "task")
issue := bdProxiedCreate(t, bd, p.dir, "Aux cleanup", "-t", "task",
"--label", "alpha",
@ -74,7 +78,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_json_returns_result_shape", func(t *testing.T) {
p := bdProxiedInit(t, bd, "djs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "djs")
issue := bdProxiedCreate(t, bd, p.dir, "JSON shape", "-t", "task")
got := bdProxiedDeleteJSON(t, bd, p.dir, "--json", issue.ID, "--force")
@ -97,7 +102,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_leaf_clears_outbound_dep_rows", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dlc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dlc")
a := bdProxiedCreate(t, bd, p.dir, "Survivor A", "-t", "task")
b := bdProxiedCreate(t, bd, p.dir, "Will be deleted", "-t", "task",
"--deps", "depends-on:"+a.ID)
@ -120,7 +126,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_creates_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ddc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ddc")
issue := bdProxiedCreate(t, bd, p.dir, "Dolt commit test", "-t", "task")
db := openProxiedDB(t, p)
@ -144,7 +151,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_bulk_no_resurrection", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dbr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dbr")
const total = 20
const toDelete = 10
@ -177,7 +185,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_nonexistent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dne")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dne")
out := bdProxiedDeleteFail(t, bd, p.dir, "dne-doesnotexist", "--force")
if !strings.Contains(strings.ToLower(out), "not found") &&
!strings.Contains(strings.ToLower(out), "error") {
@ -186,7 +195,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_batch", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dbt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dbt")
a := bdProxiedCreate(t, bd, p.dir, "Batch 1", "-t", "task")
b := bdProxiedCreate(t, bd, p.dir, "Batch 2", "-t", "task")
c := bdProxiedCreate(t, bd, p.dir, "Batch 3", "-t", "task")
@ -200,7 +210,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_force_cascades_dependents", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dfc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dfc")
parent := bdProxiedCreate(t, bd, p.dir, "Force parent", "-t", "task")
child := bdProxiedCreate(t, bd, p.dir, "Force child", "-t", "task",
"--deps", "depends-on:"+parent.ID)
@ -213,7 +224,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_cleans_up_dependencies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dcd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dcd")
parent := bdProxiedCreate(t, bd, p.dir, "Parent", "-t", "task")
child := bdProxiedCreate(t, bd, p.dir, "Child", "-t", "task",
"--deps", "depends-on:"+parent.ID)
@ -235,7 +247,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_always_cascades_dependents", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dac")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dac")
parent := bdProxiedCreate(t, bd, p.dir, "Parent", "-t", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child", "-t", "task",
"--parent", parent.ID)
@ -248,7 +261,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_cascade_spans_all_dep_types", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dcs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dcs")
a := bdProxiedCreate(t, bd, p.dir, "A", "-t", "task")
b := bdProxiedCreate(t, bd, p.dir, "B", "-t", "task",
"--deps", "depends-on:"+a.ID)
@ -264,7 +278,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_json_counts_match_cascade", func(t *testing.T) {
p := bdProxiedInit(t, bd, "djc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "djc")
a := bdProxiedCreate(t, bd, p.dir, "Chain A", "-t", "task")
b := bdProxiedCreate(t, bd, p.dir, "Chain B", "-t", "task",
"--deps", "depends-on:"+a.ID)
@ -288,7 +303,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_dry_run_does_not_mutate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ddr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ddr")
issue := bdProxiedCreate(t, bd, p.dir, "Dry run target", "-t", "task")
got := bdProxiedDeleteJSON(t, bd, p.dir, "--json", issue.ID, "--dry-run")
@ -301,7 +317,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_preview_lists_not_found", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpn")
issue := bdProxiedCreate(t, bd, p.dir, "Preview NotFound", "-t", "task")
out := bdProxiedDeleteFail(t, bd, p.dir, issue.ID, "dpn-bogus")
@ -317,7 +334,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_preview_lists_connected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpc")
neighbor := bdProxiedCreate(t, bd, p.dir, "Preview neighbor", "-t", "task")
target := bdProxiedCreate(t, bd, p.dir, "Preview target", "-t", "task",
"--deps", "depends-on:"+neighbor.ID)
@ -345,7 +363,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_rewrites_text_references", func(t *testing.T) {
p := bdProxiedInit(t, bd, "drt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "drt")
neighbor := bdProxiedCreate(t, bd, p.dir, "Rewrite neighbor", "-t", "task")
target := bdProxiedCreate(t, bd, p.dir, "Rewrite target", "-t", "task",
"--deps", "depends-on:"+neighbor.ID)
@ -369,7 +388,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_references_updated_count_reported", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dru")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dru")
neighbor := bdProxiedCreate(t, bd, p.dir, "Refs neighbor", "-t", "task")
target := bdProxiedCreate(t, bd, p.dir, "Refs target", "-t", "task",
"--deps", "depends-on:"+neighbor.ID)
@ -387,7 +407,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_zero_aux_rows_after", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dza")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dza")
outbound := bdProxiedCreate(t, bd, p.dir, "Outbound dependee", "-t", "task")
issue := bdProxiedCreate(t, bd, p.dir, "Zero aux target", "-t", "task",
"--label", "alpha",
@ -426,7 +447,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_from_file", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dff")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dff")
a := bdProxiedCreate(t, bd, p.dir, "From-file 1", "-t", "task")
b := bdProxiedCreate(t, bd, p.dir, "From-file 2", "-t", "task")
c := bdProxiedCreate(t, bd, p.dir, "From-file 3", "-t", "task")
@ -446,7 +468,8 @@ func TestProxiedServerDelete(t *testing.T) {
})
t.Run("delete_cascade_flag_is_error", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dcn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dcn")
issue := bdProxiedCreate(t, bd, p.dir, "Cascade flag", "-t", "task")
out := bdProxiedDeleteFail(t, bd, p.dir, issue.ID, "--force", "--cascade")
@ -460,11 +483,13 @@ func TestProxiedServerDelete(t *testing.T) {
}
func TestProxiedServerDeleteWisp(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("delete_mixed_wisp_and_issue_partition", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dmp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dmp")
issue := bdProxiedCreate(t, bd, p.dir, "Regular target", "-t", "task")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp target", "--ephemeral")
@ -479,7 +504,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_clears_wisp_aux_tables", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwc")
a := bdProxiedCreate(t, bd, p.dir, "Wisp aux A", "--ephemeral")
_ = bdProxiedCreate(t, bd, p.dir, "Wisp aux B", "--ephemeral",
"--deps", "depends-on:"+a.ID)
@ -514,7 +540,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_routes_to_wisps_table", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwr")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp delete routing", "--ephemeral")
db := openProxiedDB(t, p)
@ -535,7 +562,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_batch", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwb")
a := bdProxiedCreate(t, bd, p.dir, "Wisp batch 1", "--ephemeral")
b := bdProxiedCreate(t, bd, p.dir, "Wisp batch 2", "--ephemeral")
c := bdProxiedCreate(t, bd, p.dir, "Wisp batch 3", "--ephemeral")
@ -549,7 +577,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_cascades_dependents", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwc")
parent := bdProxiedCreate(t, bd, p.dir, "Wisp parent", "--ephemeral")
child := bdProxiedCreate(t, bd, p.dir, "Wisp child", "--ephemeral",
"--deps", "depends-on:"+parent.ID)
@ -562,7 +591,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_cascade_spans_all_dep_types", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dws")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dws")
a := bdProxiedCreate(t, bd, p.dir, "Wisp A", "--ephemeral")
b := bdProxiedCreate(t, bd, p.dir, "Wisp B", "--ephemeral",
"--deps", "depends-on:"+a.ID)
@ -578,7 +608,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_skips_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwdc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwdc")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp commit skip", "--ephemeral")
db := openProxiedDB(t, p)
@ -602,7 +633,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_dry_run_does_not_mutate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwdr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwdr")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp dry-run target", "--ephemeral")
got := bdProxiedDeleteJSON(t, bd, p.dir, "--json", wisp.ID, "--dry-run")
@ -615,7 +647,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_rewrites_text_references", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwrt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwrt")
neighbor := bdProxiedCreate(t, bd, p.dir, "Wisp neighbor", "--ephemeral")
target := bdProxiedCreate(t, bd, p.dir, "Wisp target", "--ephemeral",
"--deps", "depends-on:"+neighbor.ID)
@ -639,7 +672,8 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
})
t.Run("delete_wisp_nonexistent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dwn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dwn")
out := bdProxiedDeleteFail(t, bd, p.dir, "dwn-doesnotexist", "--force")
if !strings.Contains(strings.ToLower(out), "not found") {
t.Errorf("expected `not found` error for bogus wisp id, got: %s", out)
@ -648,10 +682,11 @@ func TestProxiedServerDeleteWisp(t *testing.T) {
}
func TestProxiedServerDeleteConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "ddc")
p := newSharedProxiedProject(t, bd, "ddc")
issue := bdProxiedCreate(t, bd, p.dir, "Concurrent delete contest", "-t", "task")
const n = 5

View file

@ -14,6 +14,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
@ -527,7 +528,11 @@ func addBulkDependenciesInTx(ctx context.Context, tx storage.Transaction, edges
return fmt.Errorf("final cycle check failed (no edges added): %w", cycleErr)
}
if cyclePath != "" {
return fmt.Errorf("dependency cycle would be created: %s (no edges added; run 'bd dep cycles' for analysis)", cyclePath)
// Type this rejection so callers can errors.Is(err, domain.ErrDependencyCycle),
// matching the proxied/domain bulk final gate. NewCycleError renders the
// message verbatim (no sentinel text appended), so the user-facing string
// is unchanged.
return domain.NewCycleError("dependency cycle would be created: %s (no edges added; run 'bd dep cycles' for analysis)", cyclePath)
}
return nil
}

View file

@ -121,12 +121,15 @@ func bdProxiedDepWithInputFail(t *testing.T, bd, dir, input string, args ...stri
}
func TestProxiedServerDep(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("Blocks", func(t *testing.T) {
t.Parallel()
t.Run("happy_path", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpb1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpb1")
a := bdProxiedCreate(t, bd, p.dir, "Block A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Block B", "--type", "task")
out := bdProxiedDep(t, bd, p.dir, a.ID, "--blocks", b.ID)
@ -137,8 +140,10 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("Add", func(t *testing.T) {
t.Parallel()
t.Run("positional_args", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa1")
a := bdProxiedCreate(t, bd, p.dir, "Pos A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Pos B", "--type", "task")
out := bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -148,7 +153,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("type_parent_child", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa2")
epic := bdProxiedCreate(t, bd, p.dir, "Epic", "--type", "epic")
c1 := bdProxiedCreate(t, bd, p.dir, "Child 1", "--type", "task")
c2 := bdProxiedCreate(t, bd, p.dir, "Child 2", "--type", "task")
@ -161,7 +167,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("type_tracks", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa3")
tracker := bdProxiedCreate(t, bd, p.dir, "Tracker", "--type", "task")
tracked := bdProxiedCreate(t, bd, p.dir, "Tracked", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", tracker.ID, tracked.ID, "--type", "tracks")
@ -172,7 +179,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("type_related", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa4")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa4")
r1 := bdProxiedCreate(t, bd, p.dir, "Related 1", "--type", "task")
r2 := bdProxiedCreate(t, bd, p.dir, "Related 2", "--type", "task")
out := bdProxiedDep(t, bd, p.dir, "add", r1.ID, r2.ID, "--type", "related")
@ -182,7 +190,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("blocked_by_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa5")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa5")
x := bdProxiedCreate(t, bd, p.dir, "Blocked", "--type", "task")
y := bdProxiedCreate(t, bd, p.dir, "Blocker", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", x.ID, "--blocked-by", y.ID)
@ -193,7 +202,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("depends_on_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa6")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa6")
x := bdProxiedCreate(t, bd, p.dir, "Dependent", "--type", "task")
y := bdProxiedCreate(t, bd, p.dir, "Dependency", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", x.ID, "--depends-on", y.ID)
@ -204,7 +214,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("cycle_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa7")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa7")
a := bdProxiedCreate(t, bd, p.dir, "Cyc A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Cyc B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -215,7 +226,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("child_parent_antipattern", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa8")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa8")
parent := bdProxiedCreate(t, bd, p.dir, "AP Parent", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "AP Child", "--type", "task", "--parent", parent.ID)
out := bdProxiedDepFail(t, bd, p.dir, "add", child.ID, parent.ID)
@ -225,7 +237,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa9")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa9")
j1 := bdProxiedCreate(t, bd, p.dir, "JSON A", "--type", "task")
j2 := bdProxiedCreate(t, bd, p.dir, "JSON B", "--type", "task")
m := bdProxiedDepJSON(t, bd, p.dir, "add", j1.ID, j2.ID)
@ -238,7 +251,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("bulk_file_jsonl", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa10")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa10")
b1 := bdProxiedCreate(t, bd, p.dir, "Bulk A", "--type", "task")
b2 := bdProxiedCreate(t, bd, p.dir, "Bulk B", "--type", "task")
b3 := bdProxiedCreate(t, bd, p.dir, "Bulk C", "--type", "task")
@ -263,7 +277,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("bulk_file_validation_atomic", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa11")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa11")
v1 := bdProxiedCreate(t, bd, p.dir, "Valid A", "--type", "task")
v2 := bdProxiedCreate(t, bd, p.dir, "Valid B", "--type", "task")
path := filepath.Join(t.TempDir(), "bad-deps.jsonl")
@ -283,7 +298,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("no_cycle_check_chain", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa12")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa12")
const n = 10
ids := make([]string, n)
for i := 0; i < n; i++ {
@ -305,7 +321,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("bulk_no_cycle_check_whole_graph_gate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa13")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa13")
a := bdProxiedCreate(t, bd, p.dir, "Gate A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Gate B", "--type", "task")
c := bdProxiedCreate(t, bd, p.dir, "Gate C", "--type", "task")
@ -330,7 +347,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("commit_visible_to_subsequent_invocation", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa14")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa14")
a := bdProxiedCreate(t, bd, p.dir, "Commit A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Commit B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -341,7 +359,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("bulk_external_ref_passthrough", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpa15")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpa15")
src := bdProxiedCreate(t, bd, p.dir, "Ext src", "--type", "task")
input := fmt.Sprintf("{\"from\":%q,\"to\":\"external:other:capability\"}\n", src.ID)
cmd := exec.Command(bd, "dep", "add", "--file", "-")
@ -362,8 +381,10 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("Remove", func(t *testing.T) {
t.Parallel()
t.Run("basic", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpr1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpr1")
a := bdProxiedCreate(t, bd, p.dir, "Rm A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Rm B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -374,7 +395,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("rm_alias", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpr2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpr2")
a := bdProxiedCreate(t, bd, p.dir, "Rm A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Rm B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -385,7 +407,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpr3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpr3")
a := bdProxiedCreate(t, bd, p.dir, "Rm JSON A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Rm JSON B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -397,8 +420,10 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("List", func(t *testing.T) {
t.Parallel()
t.Run("default_direction_down", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl1")
a := bdProxiedCreate(t, bd, p.dir, "L A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "L B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -409,7 +434,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("direction_up", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl2")
a := bdProxiedCreate(t, bd, p.dir, "Up A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "Up B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -420,7 +446,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("type_filter", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl3")
epic := bdProxiedCreate(t, bd, p.dir, "TF epic", "--type", "epic")
c1 := bdProxiedCreate(t, bd, p.dir, "TF c1", "--type", "task")
c2 := bdProxiedCreate(t, bd, p.dir, "TF c2", "--type", "task")
@ -433,7 +460,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl4")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl4")
a := bdProxiedCreate(t, bd, p.dir, "LJ A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "LJ B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -448,7 +476,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("batch_multi_arg", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl5")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl5")
a := bdProxiedCreate(t, bd, p.dir, "B A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "B B", "--type", "task")
c := bdProxiedCreate(t, bd, p.dir, "B C", "--type", "task")
@ -466,7 +495,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("batch_partitions_wisp_and_issue_ids", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpl6")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpl6")
issueSrc := bdProxiedCreate(t, bd, p.dir, "WP issue src", "--type", "task")
issueTgt := bdProxiedCreate(t, bd, p.dir, "WP issue tgt", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", issueSrc.ID, issueTgt.ID)
@ -497,8 +527,10 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("Tree", func(t *testing.T) {
t.Parallel()
t.Run("basic", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt1")
root := bdProxiedCreate(t, bd, p.dir, "Tree root", "--type", "task")
child := bdProxiedCreate(t, bd, p.dir, "Tree child", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, child.ID)
@ -509,7 +541,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("direction_up", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt2")
root := bdProxiedCreate(t, bd, p.dir, "Up tree root", "--type", "task")
dep := bdProxiedCreate(t, bd, p.dir, "Up tree dep", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, dep.ID)
@ -520,7 +553,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("direction_both", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt3")
root := bdProxiedCreate(t, bd, p.dir, "Both root", "--type", "task")
dep := bdProxiedCreate(t, bd, p.dir, "Both dep", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, dep.ID)
@ -531,7 +565,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("both_does_not_duplicate_root", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt4")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt4")
root := bdProxiedCreate(t, bd, p.dir, "Dedup root", "--type", "task")
depDown := bdProxiedCreate(t, bd, p.dir, "Dedup down", "--type", "task")
depUp := bdProxiedCreate(t, bd, p.dir, "Dedup up", "--type", "task")
@ -554,7 +589,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("max_depth", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt5")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt5")
a := bdProxiedCreate(t, bd, p.dir, "MD A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "MD B", "--type", "task")
c := bdProxiedCreate(t, bd, p.dir, "MD C", "--type", "task")
@ -567,7 +603,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("status_filter", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt6")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt6")
root := bdProxiedCreate(t, bd, p.dir, "SF root", "--type", "task")
dep := bdProxiedCreate(t, bd, p.dir, "SF dep", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, dep.ID)
@ -575,7 +612,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("format_mermaid", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt7")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt7")
root := bdProxiedCreate(t, bd, p.dir, "Mer root", "--type", "task")
dep := bdProxiedCreate(t, bd, p.dir, "Mer dep", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, dep.ID)
@ -586,7 +624,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt8")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt8")
root := bdProxiedCreate(t, bd, p.dir, "JT root", "--type", "task")
dep := bdProxiedCreate(t, bd, p.dir, "JT dep", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", root.ID, dep.ID)
@ -598,7 +637,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("ignores_relates_to", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpt9")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpt9")
root := bdProxiedCreate(t, bd, p.dir, "Rel root", "--type", "task")
blocker := bdProxiedCreate(t, bd, p.dir, "Real blocker", "--type", "task")
related := bdProxiedCreate(t, bd, p.dir, "Loose relation", "--type", "task")
@ -627,8 +667,10 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("Cycles", func(t *testing.T) {
t.Parallel()
t.Run("detect", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpc1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpc1")
a := bdProxiedCreate(t, bd, p.dir, "C A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "C B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -647,7 +689,8 @@ func TestProxiedServerDep(t *testing.T) {
})
t.Run("none", func(t *testing.T) {
p := bdProxiedInit(t, bd, "dpc2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "dpc2")
a := bdProxiedCreate(t, bd, p.dir, "NC A", "--type", "task")
b := bdProxiedCreate(t, bd, p.dir, "NC B", "--type", "task")
bdProxiedDep(t, bd, p.dir, "add", a.ID, b.ID)
@ -660,9 +703,10 @@ func TestProxiedServerDep(t *testing.T) {
}
func TestProxiedServerDepConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "dpcon")
p := newSharedProxiedProject(t, bd, "dpcon")
var ids []string
for i := 0; i < 16; i++ {

View file

@ -6,6 +6,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
@ -16,6 +17,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
@ -1722,6 +1724,16 @@ func TestAddBulkDependenciesInTxOrdersHierarchyAndAlwaysRunsFinalGate(t *testing
if err == nil || !strings.Contains(err.Error(), "dependency cycle would be created") {
t.Fatalf("normal-mode final gate error = %v, want rejection", err)
}
// The embedded bulk final gate must type its rejection identically to the
// proxied/domain bulk gate so callers can errors.Is it regardless of plumbing.
if !errors.Is(err, domain.ErrDependencyCycle) {
t.Fatalf("final gate error must errors.Is domain.ErrDependencyCycle, got %v", err)
}
// Typing must not alter the rendered text: no sentinel string appended.
const wantMsg = "dependency cycle would be created: child → grand → child (no edges added; run 'bd dep cycles' for analysis)"
if err.Error() != wantMsg {
t.Fatalf("final gate message = %q, want byte-identical %q", err.Error(), wantMsg)
}
if len(tx.added) != 3 {
t.Fatalf("added dependencies = %d, want 3", len(tx.added))
}

View file

@ -84,10 +84,17 @@ This command checks:
- .beads/.gitignore up to date
- Metadata.json version tracking (LastBdVersion field)
Storage Availability:
Full diagnostics, --perf, --deep, --server, --migration, and
--check=validate currently require Dolt server mode. Embedded Dolt
supports --check=artifacts, --check=conventions, and
--check=pollution. --check-health has a limited hook-health fallback.
Unsupported combinations return a notice without changing storage.
Performance Mode (--perf):
Run performance diagnostics on your database:
- Times key operations (bd ready, bd list, bd show, etc.)
- Collects system info (OS, arch, SQLite version, database stats)
- Collects system info (OS, arch, database stats)
- Generates CPU profile for analysis
- Outputs shareable report for bug reports
@ -123,18 +130,12 @@ Server Mode (--server):
- Schema compatible: Can query beads tables?
- Connection pool: Pool health metrics
Migration Validation Mode (--migration):
Run Dolt migration validation checks with machine-parseable output.
Use --migration=pre before migration to verify readiness:
- JSONL file exists and is valid (parseable, no corruption)
- All JSONL issues are present in SQLite (or explains discrepancies)
- No blocking issues prevent migration
Use --migration=post after migration to verify completion:
- Dolt database exists and is healthy
- All issues from JSONL are present in Dolt
- No data was lost during migration
- Dolt database has no locks or uncommitted changes
Combine with --json for machine-parseable output for automation.
Legacy Dolt Migration Validation Mode (--migration):
Retained for older SQLite-to-Dolt migration workflows and available only in
Dolt server mode. It is not the migration path for removed backends
(PostgreSQL, MySQL, SQLite); those fail closed with export/import guidance.
Combine
with --json for machine-parseable diagnostic output.
Agent Mode (--agent):
Output diagnostics designed for AI agent consumption. Instead of terse
@ -181,9 +182,9 @@ Examples:
bd doctor --check=validate --fix # Auto-fix data-integrity issues
bd doctor --deep # Full graph integrity validation
bd doctor --server # Dolt server mode health checks
bd doctor --migration=pre # Validate readiness for Dolt migration
bd doctor --migration=post # Validate Dolt migration completed
bd doctor --migration=pre --json # Machine-parseable migration validation`,
bd doctor --migration=pre # Legacy Dolt-server migration diagnostic
bd doctor --migration=post # Legacy Dolt-server completion diagnostic
bd doctor --migration=pre --json # Machine-parseable legacy diagnostic`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
@ -194,11 +195,6 @@ Examples:
}
}()
if usesProxiedServer() {
fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.")
return nil
}
var checkPath string
if len(args) > 0 {
checkPath = args[0]
@ -212,6 +208,14 @@ Examples:
if err != nil {
return HandleError("failed to resolve path: %v", err)
}
if err := validateDoctorWorkspaceBackend(absPath); err != nil {
return HandleError("%v", err)
}
if usesProxiedServer() {
fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.")
return nil
}
if doctorFix && isOrchestratorRoot(absPath) {
return HandleErrorWithHint(
@ -340,7 +344,7 @@ func init() {
doctorCmd.Flags().BoolVar(&doctorOrchestrator, "orchestrator", false, "Running in orchestrator multi-workspace mode (routes.jsonl is expected, higher duplicate tolerance)")
doctorCmd.Flags().IntVar(&orchestratorDuplicatesThreshold, "orchestrator-duplicates-threshold", 1000, "Duplicate tolerance threshold for orchestrator mode (wisps are ephemeral)")
doctorCmd.Flags().BoolVar(&doctorServer, "server", false, "Run Dolt server mode health checks (connectivity, version, schema)")
doctorCmd.Flags().StringVar(&doctorMigration, "migration", "", "Run Dolt migration validation: 'pre' (before migration) or 'post' (after migration)")
doctorCmd.Flags().StringVar(&doctorMigration, "migration", "", "Run legacy Dolt-server migration diagnostics: 'pre' or 'post'")
doctorCmd.Flags().BoolVar(&doctorAgent, "agent", false, "Agent-facing diagnostic mode: rich context for AI agents (ZFC-compliant)")
}
@ -348,6 +352,19 @@ func shouldSkipDoctorNetworkChecks() bool {
return jsonOutput || !ui.IsTerminal()
}
// validateDoctorWorkspaceBackend keeps doctor diagnostics read-only when metadata
// selects a removed or unknown implementation or cannot be parsed. Doctor contains
// direct diagnostic store paths and may run under shared-server mode, so corrupt
// metadata must be rejected before version tracking or any database check begins.
func validateDoctorWorkspaceBackend(path string) error {
beadsDir := doctor.ResolveBeadsDirForRepo(path)
cfg, err := configfile.Load(beadsDir)
if err != nil {
return fmt.Errorf("failed to load %s: %w; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err)
}
return validateConfiguredBackend(cfg)
}
// printEmbeddedUnsupported reports that a doctor variant is not yet wired up
// for embedded mode. Emits a structured payload to stderr when --json or
// --agent is set so downstream tooling can detect the gap without parsing

View file

@ -43,9 +43,8 @@ func RunDeepValidation(path string) DeepValidationResult {
check := DoctorCheck{
Name: "Deep Validation",
Status: StatusWarning,
Message: "SQLite backend detected",
Message: fmt.Sprintf("N/A (deep validation requires Dolt; configured backend is %q)", backend),
Category: CategoryMaintenance,
Fix: "Run 'bd init' to set up Dolt backend",
}
result.AllChecks = append(result.AllChecks, check)
return result

View file

@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/types"
)
@ -45,6 +46,26 @@ func TestRunDeepValidation_EmptyBeadsDir(t *testing.T) {
}
}
func TestRunDeepValidationSQLiteIsNotAMigrationWarning(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := (&configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"}).Save(beadsDir); err != nil {
t.Fatalf("save SQLite config: %v", err)
}
result := RunDeepValidation(tmpDir)
if len(result.AllChecks) != 1 {
t.Fatalf("SQLite deep-validation result = %#v, want one N/A check", result)
}
check := result.AllChecks[0]
if check.Status != StatusWarning || !strings.Contains(check.Message, "sqlite") || check.Fix != "" {
t.Fatalf("SQLite deep-validation check = %#v, want non-Dolt N/A without migration fix", check)
}
}
// TestCheckParentConsistency_OrphanedDeps verifies detection of orphaned parent-child deps
func TestCheckParentConsistency_OrphanedDeps(t *testing.T) {
store := newTestDoltStore(t, "bd")

View file

@ -101,9 +101,10 @@ func openDoltConn(beadsDir string) (*doltConn, error) {
return &doltConn{db: db, cfg: cfg, port: port}, nil
}
// GetBackend returns the configured backend type from configuration.
// It checks config.yaml first (storage-backend key), then falls back to metadata.json.
// Returns "dolt" (default) or "sqlite" (legacy).
// GetBackend returns the configured backend type from metadata.json. An absent
// or empty backend field reads as "dolt" (the default); removed-backend
// tombstones ("postgres", "mysql", "sqlite") are returned verbatim so callers
// can label them without opening anything.
// hq-3446fc.17: Use dolt.GetBackendFromConfig for consistent backend detection.
func GetBackend(beadsDir string) string {
return dolt.GetBackendFromConfig(beadsDir)
@ -126,13 +127,13 @@ func runDoltHealthChecksInternal(path string) []DoctorCheck {
if !IsDoltBackend(beadsDir) {
return []DoctorCheck{
{Name: "Dolt Connection", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryCore},
{Name: "Dolt Schema", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryCore},
{Name: "Dolt Issue Count", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData},
{Name: "Dolt Status", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData},
{Name: "Dolt Lock Health", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryRuntime},
{Name: "Phantom Databases", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData},
{Name: "Shared Server", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryRuntime},
{Name: "Dolt Connection", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryCore},
{Name: "Dolt Schema", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryCore},
{Name: "Dolt Issue Count", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData},
{Name: "Dolt Status", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData},
{Name: "Dolt Lock Health", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryRuntime},
{Name: "Phantom Databases", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData},
{Name: "Shared Server", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryRuntime},
}
}
@ -288,7 +289,7 @@ func checkSchemaWithDB(conn *doltConn) DoctorCheck {
// Check dolt_ignore'd tables — these only exist in the working set and
// must be recreated each server session. (GH#2271)
ignoredTables := []string{
"local_metadata", "repo_mtimes",
"leases", "local_metadata", "repo_mtimes",
"wisps", "wisp_labels", "wisp_dependencies", "wisp_events", "wisp_comments",
}
var missingIgnoredTables []string
@ -411,7 +412,7 @@ func CheckDoltIssueCount(path string) DoctorCheck {
// produces self-fulfilling warnings that can never be cleared.
func isIgnoredTable(tableName string) bool {
switch tableName {
case "wisps", "local_metadata", "repo_mtimes":
case "wisps", "leases", "local_metadata", "repo_mtimes":
return true
}
return strings.HasPrefix(tableName, "wisp_")

View file

@ -274,7 +274,7 @@ func runBDDoctor(t *testing.T, bdPath, path string) (e2eDoctorResult, string, er
return result, string(out), execErr
}
// TestE2E_DoctorSQLiteBackend was removed: SQLite backend no longer exists.
// TestE2E_DoctorSQLiteBackend is covered by the backend-neutral doctor tests.
// GetBackend() always returns "dolt" after the dolt-native cleanup (bd-yqpwy).
// TestE2E_DoctorDoltBackendNoDB was removed: the embedded Dolt driver

View file

@ -508,7 +508,7 @@ func CheckFreshClone(repoPath string) DoctorCheck {
return freshCloneServerUnreachableResult(dbName, host, port, result.Err)
}
default:
// SQLite (default): check configured .db file path.
// Non-Dolt (legacy sqlite-era metadata): check configured .db file path.
var dbPath string
if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil && cfg.Database != "" {
dbPath = cfg.DatabasePath(beadsDir)

View file

@ -148,7 +148,7 @@ func CheckMigrationReadiness(path string) (DoctorCheck, MigrationValidationResul
Status: status,
Message: message,
Detail: strings.Join(result.Warnings, "\n"),
Fix: "Run 'bd migrate dolt' to start migration",
Fix: "Follow 'bd help init-safety' to reinitialize with Dolt, then import and verify this JSONL export",
Category: CategoryMaintenance,
}, result
}
@ -195,7 +195,7 @@ func CheckMigrationCompletion(path string) (DoctorCheck, MigrationValidationResu
Status: StatusError,
Message: "Not using Dolt backend",
Detail: fmt.Sprintf("Current backend: %s", result.Backend),
Fix: "Run 'bd migrate dolt' to migrate to Dolt",
Fix: "Follow 'bd help init-safety' to reinitialize with Dolt, then import and verify the issue export",
Category: CategoryMaintenance,
}, result
}
@ -302,7 +302,7 @@ func CheckMigrationCompletion(path string) (DoctorCheck, MigrationValidationResu
Status: StatusError,
Message: fmt.Sprintf("Migration incomplete: %d error(s)", len(result.Errors)),
Detail: strings.Join(result.Errors, "\n"),
Fix: "Re-run 'bd migrate dolt' or check for data issues",
Fix: "Check the export/import results; follow 'bd help init-safety' before reinitializing again",
Category: CategoryMaintenance,
}, result
}

View file

@ -6,6 +6,7 @@ import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
@ -135,13 +136,14 @@ func TestCheckMigrationReadinessResult_NoJSONL(t *testing.T) {
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil {
t.Fatalf("failed to create SQLite metadata: %v", err)
}
check, _ := CheckMigrationReadiness(tmpDir)
// With Dolt-only backend, GetBackend defaults to BackendDolt,
// so migration readiness returns OK ("Already using Dolt backend")
if check.Status != StatusOK {
t.Errorf("status = %q, want %q (Dolt-only backend returns OK)", check.Status, StatusOK)
if check.Status != StatusError {
t.Errorf("status = %q, want %q", check.Status, StatusError)
}
}
@ -156,6 +158,9 @@ func TestCheckMigrationReadinessResult_ValidJSONL(t *testing.T) {
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil {
t.Fatalf("failed to create SQLite metadata: %v", err)
}
// Create valid JSONL
jsonl := `{"id":"bd-001","title":"Test 1"}` + "\n" + `{"id":"bd-002","title":"Test 2"}`
@ -165,12 +170,15 @@ func TestCheckMigrationReadinessResult_ValidJSONL(t *testing.T) {
check, _ := CheckMigrationReadiness(tmpDir)
// With Dolt-only backend, GetBackend defaults to BackendDolt,
// so migration readiness returns OK ("Already using Dolt backend")
// without validating JSONL (no migration needed)
if check.Status == StatusError {
t.Errorf("status = %q, did not want error", check.Status)
}
if !strings.Contains(check.Fix, "bd help init-safety") {
t.Errorf("fix must point to safe reinitialization guidance, got %q", check.Fix)
}
if strings.Contains(check.Fix, "bd migrate dolt") {
t.Errorf("fix must not recommend removed backend-conversion command, got %q", check.Fix)
}
}
func TestCheckMigrationCompletionResult_NoBeadsDir(t *testing.T) {
@ -206,6 +214,9 @@ func TestCheckMigrationCompletionResult_NotDoltBackend(t *testing.T) {
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil {
t.Fatalf("failed to create SQLite metadata: %v", err)
}
// Create JSONL (no Dolt backend present)
jsonl := `{"id":"bd-001","title":"Test 1"}`
@ -226,6 +237,12 @@ func TestCheckMigrationCompletionResult_NotDoltBackend(t *testing.T) {
if len(result.Errors) == 0 {
t.Error("expected errors in result")
}
if !strings.Contains(check.Fix, "bd help init-safety") {
t.Errorf("fix must point to safe reinitialization guidance, got %q", check.Fix)
}
if strings.Contains(check.Fix, "bd migrate dolt") {
t.Errorf("fix must not recommend removed backend-conversion command, got %q", check.Fix)
}
}
func TestMigrationValidationResult_JSONSerialization(t *testing.T) {

View file

@ -49,7 +49,8 @@ func RunDoltPerformanceDiagnostics(path string, enableProfiling bool) (*DoltPerf
// Verify this is a Dolt backend
if !IsDoltBackend(beadsDir) {
return nil, fmt.Errorf("SQLite backend is no longer supported. Migrate to Dolt with 'bd migrate'")
backend, _ := getBackendAndBeadsDir(path)
return nil, fmt.Errorf("Dolt server performance diagnostics do not apply to the configured backend %q", backend)
}
metrics := &DoltPerfMetrics{

View file

@ -40,3 +40,24 @@ func TestRunDoltPerformanceDiagnostics_RequiresServer(t *testing.T) {
t.Errorf("expected server/database error, got: %v", err)
}
}
func TestRunDoltPerformanceDiagnosticsDeclineNonDoltBackend(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
cfg := &configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"}
if err := cfg.Save(beadsDir); err != nil {
t.Fatalf("save SQLite config: %v", err)
}
_, err := RunDoltPerformanceDiagnostics(tmpDir, false)
if err == nil {
t.Fatal("expected Dolt-only diagnostics to decline a non-Dolt workspace")
}
message := err.Error()
if !strings.Contains(message, "Dolt") || !strings.Contains(message, `"sqlite"`) {
t.Fatalf("diagnostic error should explain the backend mismatch: %v", err)
}
}

View file

@ -61,9 +61,8 @@ func RunServerHealthChecks(path string) ServerHealthResult {
result.Checks = append(result.Checks, DoctorCheck{
Name: "Server Config",
Status: StatusWarning,
Message: fmt.Sprintf("Backend is '%s', not Dolt", cfg.GetBackend()),
Detail: "Server mode health checks are only relevant for Dolt backend",
Fix: "Set backend: dolt in metadata.json to use Dolt server mode",
Message: fmt.Sprintf("Server checks require Dolt; configured backend is %q", cfg.GetBackend()),
Detail: "Dolt server health checks do not apply to this backend",
Category: CategoryFederation,
})
result.OverallOK = false

View file

@ -0,0 +1,33 @@
package doctor
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/configfile"
)
func TestRunServerHealthChecksSQLiteIsNotAMigrationWarning(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := (&configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"}).Save(beadsDir); err != nil {
t.Fatalf("save SQLite config: %v", err)
}
// The sqlite backend is a removed-backend tombstone: server checks report a
// clearly-attributed non-Dolt warning with no migration fix, and never edit
// the workspace.
result := RunServerHealthChecks(tmpDir)
if result.OverallOK || len(result.Checks) != 1 {
t.Fatalf("SQLite server-health result = %#v, want one non-Dolt warning", result)
}
check := result.Checks[0]
if check.Status != StatusWarning || !strings.Contains(check.Message, "sqlite") || check.Fix != "" {
t.Fatalf("SQLite server-health check = %#v, want non-Dolt warning without migration fix", check)
}
}

View file

@ -0,0 +1,61 @@
//go:build cgo
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestDoctorRejectsCorruptMetadataBeforeSharedServerChecks(t *testing.T) {
bd := buildBDUnderTest(t)
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadata := []byte("{\n")
metadataPath := filepath.Join(beadsDir, "metadata.json")
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write corrupt metadata.json: %v", err)
}
cmd := exec.Command(bd, "doctor", "--json")
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir),
"BEADS_DOLT_SHARED_SERVER=1",
"BEADS_DOLT_SERVER_PORT=1",
"BEADS_DOLT_AUTO_START=0",
"BEADS_NO_DAEMON=1",
"BD_DISABLE_METRICS=1",
)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("doctor unexpectedly ran shared-server checks with corrupt metadata:\n%s", out)
}
message := strings.ToLower(string(out))
for _, want := range []string{"metadata.json", "parsing config", "no storage database was opened or modified"} {
if !strings.Contains(message, want) {
t.Errorf("doctor corrupt-metadata error missing %q:\n%s", want, out)
}
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read metadata after refusal: %v", readErr)
}
if !bytes.Equal(after, metadata) {
t.Fatalf("doctor rewrote corrupt metadata:\nbefore: %q\nafter: %q", metadata, after)
}
for _, name := range []string{".local_version", "embeddeddolt", "dolt", "beads.db", "dolt-server.pid", "dolt-server.port"} {
if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) {
t.Fatalf("doctor created %s before rejecting corrupt metadata (stat error: %v)", name, statErr)
}
}
}

View file

@ -144,7 +144,7 @@ func TestValidateCheck_DetectsOrphanedDeps(t *testing.T) {
}
func TestValidateCheck_GitConflicts_DoltClean(t *testing.T) {
// Since GetBackend() always returns "dolt" (SQLite removed in 87493ce9),
// When metadata is absent, GetBackend() defaults to "dolt",
// the Git Conflicts check now queries dolt_conflicts (GH-2249).
// Verify it reports OK for a clean Dolt database.
tmpDir, store := setupValidateTestDB(t, "val")

View file

@ -106,6 +106,13 @@ Examples:
bd dolt set data-dir /home/user/.beads-dolt/myproject`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt set' is not supported in embedded mode (no Dolt server)")
}
@ -129,6 +136,13 @@ This verifies that:
Use this before switching to server mode to ensure the server is running.`,
RunE: func(cmd *cobra.Command, args []string) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt test' is not supported in embedded mode (no Dolt server)")
}
@ -488,30 +502,6 @@ The remote must already exist (see 'bd dolt remote add').`,
},
}
// errExplicitCommitUnsupported returns a typed *storage.ErrUnsupported when the
// open store has no Dolt commit graph (Postgres/MySQL/SQLite), and nil for Dolt.
// The SQL backends deliberately expose a no-op Commit so internal write paths can
// call store.Commit() opportunistically without erroring; an EXPLICIT `bd dolt
// commit` / `bd vc commit` must not ride that no-op and print a fake "Committed."
// with no commit graph behind it. Internal opportunistic auto-commit is skipped
// separately in PostRun for these backends, so gating only the explicit commands
// keeps that path untouched.
func errExplicitCommitUnsupported(st storage.DoltStorage, op string) error {
ncg, ok := storage.UnwrapStore(st).(storage.NonCommitGraphBackend)
if !ok || !ncg.CommitGraphUnsupported() {
return nil
}
backend := "non-dolt"
if beadsDir := selectedDoltBeadsDir(); beadsDir != "" {
if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil {
if b := cfg.GetBackend(); b != "" && b != configfile.BackendDolt {
backend = b
}
}
}
return &storage.ErrUnsupported{Op: op, Backend: backend}
}
var doltCommitCmd = &cobra.Command{
Use: "commit",
Short: "Create a Dolt commit from pending changes",
@ -533,9 +523,6 @@ For more options (--stdin, custom messages), see: bd vc commit`,
if st == nil {
return HandleError("no store available")
}
if err := errExplicitCommitUnsupported(st, "dolt commit"); err != nil {
return HandleError("%v", err)
}
msg, _ := cmd.Flags().GetString("message")
if msg == "" {
msg = fmt.Sprintf("bd: dolt commit (auto-commit) by %s", getActor())
@ -566,13 +553,16 @@ project path. PID and logs are stored in .beads/.
The server auto-starts transparently when needed, so manual start is rarely
required. Use this command for explicit control or diagnostics.`,
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)")
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)")
}
serverDir := doltserver.ResolveServerDir(beadsDir)
state, err := doltserver.Start(serverDir)
@ -609,13 +599,16 @@ var doltStopCmd = &cobra.Command{
This sends a graceful shutdown signal. The server will restart automatically
on the next bd command unless auto-start is disabled.`,
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)")
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)")
}
if usesProxiedServer() {
rootDir, err := resolveProxiedServerRootPath(beadsDir)
@ -659,10 +652,20 @@ endpoint via SQL and reports reachability, server version, and database.`,
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// A non-Dolt backend (postgres/mysql/sqlite) has no Dolt engine at all;
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
return HandleError("loading config: %v", cfgErr)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if err := validateConfiguredBackend(cfg); err != nil {
return HandleError("%v", err)
}
// A non-Dolt backend (SQLite or a removed-backend tombstone) has no Dolt engine;
// report the backend rather than misdescribing an embedded Dolt server
// (parity with `bd dolt show`, which already special-cases this).
if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil && cfg.GetBackend() != configfile.BackendDolt {
if cfg.GetBackend() != configfile.BackendDolt {
fmt.Printf("Backend: %s (no Dolt engine)\n", cfg.GetBackend())
return nil
}
@ -679,19 +682,10 @@ endpoint via SQL and reports reachability, server version, and database.`,
// systemd manages the server lifecycle, be-0eyj)
//
// IsAutoStartDisabled reads the active (globally-bound) config and
// BEADS_DOLT_AUTO_START env, not the per-beadsDir cfg loaded just
// below. That coupling is intentional and consistent with every
// BEADS_DOLT_AUTO_START env, not the per-beadsDir cfg loaded above.
// That coupling is intentional and consistent with every
// other call site of IsAutoStartDisabled in this package — both
// resolve against the same active workspace at command time.
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
// Don't silently swallow. A corrupted or missing metadata.json
// would otherwise mask the externally-managed routing for both
// the remote-host and auto-start-disabled-local cases, falling
// through to the PID-file path with a misleading "not running"
// — which is the exact failure mode this PR addresses.
fmt.Fprintf(os.Stderr, "Warning: cannot load .beads config (%v); falling back to PID-file status path\n", cfgErr)
}
if cfg != nil && shouldUseExternalDoltStatus(cfg, doltserver.IsAutoStartDisabled(), doltserver.IsSharedServerMode()) {
runExternalDoltStatus(beadsDir, cfg)
return nil
@ -942,10 +936,15 @@ servers are preserved.`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir != "" {
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
}
if !usesSQLServer() {
return HandleError("'bd dolt killall' is not supported in embedded mode (no Dolt server)")
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
beadsDir = "." // best effort
}
@ -1007,6 +1006,13 @@ Stale database prefixes: testdb_*, beads_test*, beads_pt*, beads_vr*, doctest_*,
These waste server memory and can degrade performance under concurrent load.
Use --dry-run to see what would be dropped without actually dropping.`,
RunE: func(cmd *cobra.Command, args []string) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt clean-databases' is not supported in embedded mode (no Dolt server)")
}
@ -1450,6 +1456,9 @@ func showDoltConfig(testConnection bool) error {
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if err := validateConfiguredBackend(cfg); err != nil {
return HandleError("%v", err)
}
backend := cfg.GetBackend()
embedded := !usesSQLServer()
@ -1548,16 +1557,9 @@ func setDoltConfig(key, value string, updateConfig bool) error {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
cfg, err := loadDoltBackendConfig(beadsDir)
if err != nil {
return HandleError("loading config: %v", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if cfg.GetBackend() != configfile.BackendDolt {
return HandleError("not using Dolt backend")
return HandleError("%v", err)
}
var yamlKey string
@ -1709,16 +1711,9 @@ func testDoltConnection() error {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
cfg, err := loadDoltBackendConfig(beadsDir)
if err != nil {
return HandleError("loading config: %v", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
if cfg.GetBackend() != configfile.BackendDolt {
return HandleError("not using Dolt backend")
return HandleError("%v", err)
}
host := cfg.GetDoltServerHost()
@ -1878,12 +1873,9 @@ func openDoltServerConnection() (*sql.DB, func(), error) {
return nil, nil, HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
cfg, err := loadDoltBackendConfig(beadsDir)
if err != nil {
return nil, nil, HandleError("loading config: %v", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
return nil, nil, HandleError("%v", err)
}
host := cfg.GetDoltServerHost()

View file

@ -10,7 +10,8 @@ import (
)
func TestProxiedServerDoltRemoteRemove(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
seedRemote := func(t *testing.T, p proxiedProject, name, url string) {
@ -34,7 +35,8 @@ func TestProxiedServerDoltRemoteRemove(t *testing.T) {
}
t.Run("removes_existing_remote", func(t *testing.T) {
p := bdProxiedInit(t, bd, "prr1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "prr1")
seedRemote(t, p, "backup", "https://doltremoteapi.dolthub.com/org/backup")
out, err := bdProxiedRun(t, bd, p.dir, "dolt", "remote", "remove", "backup")
@ -50,7 +52,8 @@ func TestProxiedServerDoltRemoteRemove(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "prr2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "prr2")
seedRemote(t, p, "backup", "https://doltremoteapi.dolthub.com/org/backup")
out, err := bdProxiedRun(t, bd, p.dir, "dolt", "remote", "remove", "--json", "backup")
@ -78,7 +81,8 @@ func TestProxiedServerDoltRemoteRemove(t *testing.T) {
})
t.Run("nonexistent_remote_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "prr3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "prr3")
out, err := bdProxiedRun(t, bd, p.dir, "dolt", "remote", "remove", "ghost")
if err == nil {
t.Fatalf("expected error removing nonexistent remote, got:\n%s", out)

View file

@ -24,11 +24,13 @@ func bdProxiedRunEnv(t *testing.T, bd, dir string, extraEnv []string, args ...st
}
func TestProxiedServerAssign(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("assign_then_unassign", func(t *testing.T) {
p := bdProxiedInit(t, bd, "as")
t.Parallel()
p := newSharedProxiedProject(t, bd, "as")
issue := bdProxiedCreate(t, bd, p.dir, "Assign target")
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "assign", issue.ID, "alice")
@ -55,7 +57,8 @@ func TestProxiedServerAssign(t *testing.T) {
})
t.Run("assign_missing_issue_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "am")
t.Parallel()
p := newSharedProxiedProject(t, bd, "am")
_, _, err := bdProxiedRunBuffers(t, bd, p.dir, "assign", "as-nope99", "alice")
if err == nil {
t.Error("expected assign of missing issue to fail")
@ -64,10 +67,11 @@ func TestProxiedServerAssign(t *testing.T) {
}
func TestProxiedServerPriority(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "pr")
p := newSharedProxiedProject(t, bd, "pr")
issue := bdProxiedCreate(t, bd, p.dir, "Priority target", "--priority", "3")
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "priority", issue.ID, "0")
@ -83,10 +87,11 @@ func TestProxiedServerPriority(t *testing.T) {
}
func TestProxiedServerNote(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "nt")
p := newSharedProxiedProject(t, bd, "nt")
issue := bdProxiedCreate(t, bd, p.dir, "Note target")
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "note", issue.ID, "first note"); err != nil {
@ -106,11 +111,13 @@ func TestProxiedServerNote(t *testing.T) {
}
func TestProxiedServerTag(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("tag_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "tg")
t.Parallel()
p := newSharedProxiedProject(t, bd, "tg")
issue := bdProxiedCreate(t, bd, p.dir, "Tag target")
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "tag", issue.ID, "needs-review")
@ -129,7 +136,8 @@ func TestProxiedServerTag(t *testing.T) {
})
t.Run("tag_wisp_routes_to_wisp_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "tw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "tw")
wisp := bdProxiedCreate(t, bd, p.dir, "Tag wisp", "--ephemeral")
if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "tag", wisp.ID, "wtag"); err != nil {
@ -151,10 +159,11 @@ func TestProxiedServerTag(t *testing.T) {
}
func TestProxiedServerEdit(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "ed")
p := newSharedProxiedProject(t, bd, "ed")
issue := bdProxiedCreate(t, bd, p.dir, "Edit target", "--description", "original body")
editorScript := filepath.Join(p.dir, "editor.sh")

View file

@ -25,7 +25,9 @@ This uses the Tim Sehn recipe:
2. Soft-reset to the initial commit (preserving all data)
3. Commit everything as a single snapshot
4. Swap main branch to the new flattened branch
5. Run Dolt GC to reclaim space from old history
5. Prune remote-tracking refs (they would keep the old history alive;
the next push or fetch re-creates them at the new tip)
6. Run Dolt GC to reclaim space from old history
This is irreversible — all commit history is lost. The resulting database
has exactly one commit containing all current data.
@ -75,17 +77,27 @@ Examples:
}
if flattenDryRun {
remoteRefs, tags := listRemoteRefsAndTags(ctx)
if jsonOutput {
return outputJSON(map[string]interface{}{
"dry_run": true,
"commit_count": commitCount,
"initial_hash": initialHash,
"would_flatten": commitCount > 1,
"dry_run": true,
"commit_count": commitCount,
"initial_hash": initialHash,
"would_flatten": commitCount > 1,
"remote_refs": remoteRefs,
"tags": tags,
"size_before_bytes": storeSizeBytes(),
})
}
fmt.Printf("DRY RUN — Flatten preview\n\n")
fmt.Printf(" Commits: %d\n", commitCount)
fmt.Printf(" Initial commit: %s\n", initialHash)
if len(remoteRefs) > 0 {
fmt.Printf(" Remote refs: %d (pruned before GC so old history is reclaimable)\n", len(remoteRefs))
}
if len(tags) > 0 {
fmt.Printf(" Tags: %d (anchor old history; GC cannot reclaim past them)\n", len(tags))
}
if commitCount <= 1 {
fmt.Printf("\n Already flat (1 commit). Nothing to do.\n")
} else {
@ -121,23 +133,40 @@ Examples:
return HandleErrorRespectJSON("flatten failed: %v", err)
}
// Prune remote-tracking refs before GC: they still anchor the entire
// pre-flatten chain, and with them in place GC reclaims nothing on any
// workspace that has ever pushed or fetched (bd-agctw).
sizeBefore := storeSizeBytes()
pruned, tags := pruneRemoteRefsForGC(ctx)
if !jsonOutput {
printPruneReport(pruned, tags)
}
if gc, ok := storage.UnwrapStore(store).(storage.GarbageCollector); ok {
if err := gc.DoltGC(ctx); err != nil {
WarnError("dolt gc after flatten failed: %v", err)
}
}
sizeAfter := storeSizeBytes()
elapsed := time.Since(start)
if jsonOutput {
return outputJSON(map[string]interface{}{
"success": true,
"commits_before": commitCount,
"commits_after": 1,
"elapsed_ms": elapsed.Milliseconds(),
})
result := map[string]interface{}{
"success": true,
"commits_before": commitCount,
"commits_after": 1,
"remote_refs_pruned": pruned,
"tags_anchoring": tags,
"elapsed_ms": elapsed.Milliseconds(),
}
addGCSizeJSON(result, sizeBefore, sizeAfter)
return outputJSON(result)
}
fmt.Printf("✓ Flattened %d commits → 1\n", commitCount)
if line := gcSizeLine(sizeBefore, sizeAfter); line != "" {
fmt.Printf(" Store: %s\n", line)
}
fmt.Printf(" Time: %v\n", elapsed.Round(time.Millisecond))
return nil
},

View file

@ -31,9 +31,11 @@ Gate types:
timer - Expires after timeout (Phase 2)
gh:run - Waits for GitHub workflow (Phase 3)
gh:pr - Waits for PR merge (Phase 3)
bead - Waits for cross-rig bead to close (Phase 4)
bead - Waits for another bead to close (Phase 4)
For bead gates, await_id format is <rig>:<bead-id> (e.g., "other-project:op-abc123").
For bead gates, await_id is a bead ID in this rig's database (e.g., "bd-abc123").
The historical cross-rig form <rig>:<bead-id> can no longer be evaluated
(multi-rig routing removed) and stays pending until resolved manually.
Examples:
bd gate list # Show all open gates
@ -630,7 +632,7 @@ Examples:
case gate.AwaitType == "timer":
result.resolved, result.escalated, result.reason, result.err = checkTimer(gate, now)
case gate.AwaitType == "bead":
result.resolved, result.reason = checkBeadGate(ctx, gate.AwaitID)
result.resolved, result.reason = checkBeadGate(ctx, store, gate.AwaitID)
default:
// Skip unsupported gate types (human gates need manual resolution)
continue
@ -935,14 +937,43 @@ func checkTimer(gate *types.Issue, now time.Time) (resolved, escalated bool, rea
return false, false, fmt.Sprintf("expires in %s", remaining), nil
}
// checkBeadGate checks if a cross-rig bead gate is satisfied.
// await_id format: <rig>:<bead-id> (e.g., "other-project:op-abc123")
// issueGetter is the one storage method checkBeadGate needs, split out so
// tests can fake the lookup without standing up a Dolt store.
type issueGetter interface {
GetIssue(ctx context.Context, id string) (*types.Issue, error)
}
// checkBeadGate checks if a bead gate is satisfied.
// Returns (satisfied, reason).
//
// Multi-rig routing has been removed, so cross-rig bead gates cannot be resolved.
// This always returns false with a descriptive message.
func checkBeadGate(_ context.Context, awaitID string) (bool, string) {
return false, fmt.Sprintf("cross-rig bead gate %q cannot be checked (multi-rig routing removed)", awaitID)
// A plain await_id (no colon) names a bead in THIS rig's database: the gate
// resolves once that bead closes — the common case, an agent idle-waiting on
// local work (wy-hgms2; the old unconditional cross-rig refusal left every
// local bead gate permanently pending and its waiters asleep).
//
// The historical cross-rig form <rig>:<bead-id> cannot be evaluated since
// multi-rig routing was removed; it stays pending with a descriptive message.
func checkBeadGate(ctx context.Context, st issueGetter, awaitID string) (bool, string) {
if awaitID == "" {
return false, "bead gate has no await_id"
}
if strings.Contains(awaitID, ":") {
return false, fmt.Sprintf("cross-rig bead gate %q cannot be checked (multi-rig routing removed)", awaitID)
}
if st == nil {
return false, fmt.Sprintf("bead gate %q: no local store available", awaitID)
}
issue, err := st.GetIssue(ctx, awaitID)
if err != nil {
return false, fmt.Sprintf("bead gate %q: %v", awaitID, err)
}
if issue == nil {
return false, fmt.Sprintf("bead gate %q: bead not found", awaitID)
}
if issue.Status == types.StatusClosed {
return true, fmt.Sprintf("bead %s closed", awaitID)
}
return false, fmt.Sprintf("bead %s is %s", awaitID, issue.Status)
}
// closeGate closes a gate issue with the given reason

View file

@ -150,28 +150,40 @@ func TestShouldCheckGate(t *testing.T) {
}
}
func TestCheckBeadGate_InvalidFormat(t *testing.T) {
// fakeBeadGateGetter fakes the one lookup checkBeadGate performs.
type fakeBeadGateGetter struct {
issues map[string]*types.Issue
err error
}
func (f *fakeBeadGateGetter) GetIssue(_ context.Context, id string) (*types.Issue, error) {
if f.err != nil {
return nil, f.err
}
return f.issues[id], nil
}
func TestCheckBeadGate_CrossRigStaysPending(t *testing.T) {
ctx := context.Background()
// The cross-rig <rig>:<bead-id> form cannot be evaluated since multi-rig
// routing was removed; it must stay pending with the explanatory message,
// never consult the store, and never resolve.
tests := []struct {
name string
awaitID string
}{
{name: "empty", awaitID: ""},
{name: "no colon", awaitID: "my-project-mp-abc"},
{name: "missing rig", awaitID: ":gt-abc"},
{name: "missing bead", awaitID: "my-project:"},
{name: "well-formed cross-rig", awaitID: "nonexistent:some-id"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
satisfied, reason := checkBeadGate(ctx, tt.awaitID)
satisfied, reason := checkBeadGate(ctx, nil, tt.awaitID)
if satisfied {
t.Errorf("expected not satisfied for %q", tt.awaitID)
}
if reason == "" {
t.Error("expected reason to be set")
}
if !gateTestContainsIgnoreCase(reason, "multi-rig routing removed") {
t.Errorf("reason %q does not contain %q", reason, "multi-rig routing removed")
}
@ -179,24 +191,75 @@ func TestCheckBeadGate_InvalidFormat(t *testing.T) {
}
}
func TestCheckBeadGate_RigNotFound(t *testing.T) {
ctx := context.Background()
// With multi-rig routing removed, all bead gates return the same message
satisfied, reason := checkBeadGate(ctx, "nonexistent:some-id")
func TestCheckBeadGate_EmptyAwaitID(t *testing.T) {
satisfied, reason := checkBeadGate(context.Background(), nil, "")
if satisfied {
t.Error("expected not satisfied for non-existent rig")
t.Error("expected not satisfied for empty await_id")
}
if reason == "" {
t.Error("expected reason to be set")
}
if !gateTestContainsIgnoreCase(reason, "multi-rig routing removed") {
t.Errorf("reason %q does not contain %q", reason, "multi-rig routing removed")
}
func TestCheckBeadGate_LocalBead(t *testing.T) {
// A plain (no-colon) await_id is a bead in this rig's own database
// (wy-hgms2): closed resolves the gate, anything else stays pending with
// a status-bearing reason.
ctx := context.Background()
st := &fakeBeadGateGetter{
issues: map[string]*types.Issue{
"bd-closed": {ID: "bd-closed", Status: types.StatusClosed},
"bd-open": {ID: "bd-open", Status: types.StatusOpen},
},
}
satisfied, reason := checkBeadGate(ctx, st, "bd-closed")
if !satisfied {
t.Errorf("expected satisfied for closed local bead, got reason %q", reason)
}
if !gateTestContainsIgnoreCase(reason, "closed") {
t.Errorf("reason %q does not mention closed", reason)
}
satisfied, reason = checkBeadGate(ctx, st, "bd-open")
if satisfied {
t.Error("expected not satisfied for open local bead")
}
if !gateTestContainsIgnoreCase(reason, "open") {
t.Errorf("reason %q does not mention the bead status", reason)
}
}
func TestCheckBeadGate_TargetClosed(t *testing.T) {
t.Skip("SQLite-specific: created SQLite DB directly; full integration testing requires routes.jsonl + Dolt rig infrastructure")
func TestCheckBeadGate_LocalBeadNotFound(t *testing.T) {
st := &fakeBeadGateGetter{issues: map[string]*types.Issue{}}
satisfied, reason := checkBeadGate(context.Background(), st, "bd-missing")
if satisfied {
t.Error("expected not satisfied for missing local bead")
}
if !gateTestContainsIgnoreCase(reason, "not found") {
t.Errorf("reason %q does not mention not found", reason)
}
}
func TestCheckBeadGate_LocalBeadLookupError(t *testing.T) {
st := &fakeBeadGateGetter{err: errors.New("dolt exploded")}
satisfied, reason := checkBeadGate(context.Background(), st, "bd-abc")
if satisfied {
t.Error("expected not satisfied on lookup error")
}
if !gateTestContainsIgnoreCase(reason, "dolt exploded") {
t.Errorf("reason %q does not carry the lookup error", reason)
}
}
func TestCheckBeadGate_NilStoreStaysPending(t *testing.T) {
satisfied, reason := checkBeadGate(context.Background(), nil, "bd-abc")
if satisfied {
t.Error("expected not satisfied with no store")
}
if reason == "" {
t.Error("expected reason to be set")
}
}
func TestCheckGHPRUsesStateWithoutMergedField(t *testing.T) {

View file

@ -170,6 +170,7 @@ Examples:
}
}
var gcSizeInfo map[string]interface{}
if gcSkipDolt {
results = append(results, phaseResult{name: "Dolt GC", skipped: true})
} else {
@ -189,14 +190,34 @@ Examples:
}
results = append(results, phaseResult{name: "Dolt GC", detail: "dry-run"})
} else {
// bd gc runs without a preceding squash, so remote-tracking
// refs are left alone here (they cache the remote tip for the
// migrate gate); flatten/compact prune them before their GC
// (bd-agctw). Sizes are reported so a no-op reclaim is visible.
sizeBefore := storeSizeBytes()
remoteRefs, tags := listRemoteRefsAndTags(ctx)
if err := gc.DoltGC(ctx); err != nil {
WarnError("dolt gc failed: %v", err)
results = append(results, phaseResult{name: "Dolt GC", detail: "failed"})
} else {
if !jsonOutput {
fmt.Println(" Done")
sizeAfter := storeSizeBytes()
detail := "complete"
if line := gcSizeLine(sizeBefore, sizeAfter); line != "" {
detail = "complete: " + line
}
results = append(results, phaseResult{name: "Dolt GC", detail: "complete"})
if !jsonOutput {
fmt.Printf(" Done (%s)\n", detail)
if len(remoteRefs)+len(tags) > 0 {
fmt.Printf(" Note: %d remote-tracking ref(s) and %d tag(s) anchor history;\n", len(remoteRefs), len(tags))
fmt.Printf(" after a history squash, use bd flatten / bd compact so they are pruned first.\n")
}
}
results = append(results, phaseResult{name: "Dolt GC", detail: detail})
gcSizeInfo = map[string]interface{}{
"remote_refs": len(remoteRefs),
"tags": len(tags),
}
addGCSizeJSON(gcSizeInfo, sizeBefore, sizeAfter)
}
}
if !jsonOutput {
@ -222,6 +243,9 @@ Examples:
phases = append(phases, p)
}
summaryMap["phases"] = phases
if gcSizeInfo != nil {
summaryMap["dolt_gc"] = gcSizeInfo
}
return outputJSON(summaryMap)
}

101
cmd/bd/gc_prune.go Normal file
View file

@ -0,0 +1,101 @@
package main
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/storage"
)
// storeSizeBytes returns the on-disk size of the store's data directory, or
// -1 when it cannot be determined (no local path, walk error). Measured
// around DOLT_GC so a no-op reclaim is visible to the operator (bd-agctw).
func storeSizeBytes() int64 {
loc, ok := storage.UnwrapStore(store).(storage.StoreLocator)
if !ok || loc.Path() == "" {
return -1
}
size, err := getDirSize(loc.Path())
if err != nil {
return -1
}
return size
}
// pruneRemoteRefsForGC deletes cached remote-tracking refs ahead of a
// post-squash GC — they anchor the pre-squash chain, and with them in place
// DOLT_GC reclaims nothing on any workspace that has ever pushed or fetched
// (bd-agctw). Also returns tags, which anchor history the same way but are
// user-created and therefore only warned about. Failures are warnings: GC
// still runs, it just reclaims less.
func pruneRemoteRefsForGC(ctx context.Context) (pruned, tags []string) {
pruner, ok := storage.UnwrapStore(store).(storage.RemoteRefPruner)
if !ok {
return nil, nil
}
var err error
pruned, err = pruner.PruneRemoteRefs(ctx)
if err != nil {
WarnError("pruning remote-tracking refs before GC: %v (GC may reclaim little)", err)
}
tags, err = pruner.ListTags(ctx)
if err != nil {
WarnError("listing tags before GC: %v", err)
}
return pruned, tags
}
// listRemoteRefsAndTags is the read-only companion for dry runs and bd gc.
func listRemoteRefsAndTags(ctx context.Context) (refs, tags []string) {
pruner, ok := storage.UnwrapStore(store).(storage.RemoteRefPruner)
if !ok {
return nil, nil
}
refs, _ = pruner.ListRemoteRefs(ctx)
tags, _ = pruner.ListTags(ctx)
return refs, tags
}
// printPruneReport prints the outcome of pruneRemoteRefsForGC (text mode only).
func printPruneReport(pruned, tags []string) {
if len(pruned) > 0 {
fmt.Printf(" Pruned %d remote-tracking ref(s): %s\n", len(pruned), strings.Join(pruned, ", "))
fmt.Printf(" (local cache only — the next push/fetch re-creates them at the new tip)\n")
}
if len(tags) > 0 {
fmt.Printf(" Warning: %d tag(s) still anchor old history: %s\n", len(tags), strings.Join(tags, ", "))
fmt.Printf(" GC cannot reclaim commits reachable from tags; delete unwanted tags and re-run GC.\n")
}
}
// gcSizeLine formats a before/after size pair as "X → Y (freed Z)", or ""
// when either measurement failed.
func gcSizeLine(before, after int64) string {
if before < 0 || after < 0 {
return ""
}
freed := before - after
if freed < 0 {
freed = 0
}
return fmt.Sprintf("%s → %s (freed %s)", formatBytes(before), formatBytes(after), formatBytes(freed))
}
// addGCSizeJSON adds size measurements to a JSON output map (fields omitted
// when a measurement failed).
func addGCSizeJSON(m map[string]interface{}, before, after int64) {
if before >= 0 {
m["size_before_bytes"] = before
}
if after >= 0 {
m["size_after_bytes"] = after
}
if before >= 0 && after >= 0 {
freed := before - after
if freed < 0 {
freed = 0
}
m["freed_bytes"] = freed
}
}

View file

@ -24,8 +24,10 @@ it up. Heartbeat pushes lease_expires_at forward and stamps heartbeat_at = now.
Only the current owner may heartbeat. If the lease has already been reclaimed or
the issue closed, heartbeat fails so the worker learns to stop.
Heartbeat writes a Dolt commit, so heartbeat well below the TTL but not so fast
it bloats history — cadence should be a small fraction of the TTL, not per-op.
Leases live in an ephemeral, node-local table: heartbeats write no Dolt commit
and no history, so any cadence comfortably below the TTL is fine. Leases are
only enforceable on the node that granted them; cross-machine claim visibility
rides the issue's status and assignee, which do commit.
Examples:
bd heartbeat bd-123

View file

@ -72,6 +72,16 @@ an import is visible. To deliberately restore an older snapshot, pass
--allow-stale, which imports every row even when it overwrites newer
local state.
Large imports are written in bounded transactions (a few hundred issues
each, with a short pause between commits) with progress on stderr, so
concurrent bd commands keep working while the import runs instead of
stalling on one batch-wide write lock. Rows land in dependency order
with their blocking edges in the same transaction, so a half-finished
import never shows a blocked issue as ready. If an import fails partway,
the already-committed chunks are durable and the command exits nonzero;
re-running the same import is safe and converges (rows upsert,
labels/comments/dependencies deduplicate).
EXAMPLES:
bd import # Import from configured import.path
bd import backup.jsonl # Import from a specific file

View file

@ -0,0 +1,676 @@
//go:build cgo
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// These tests exercise the chunked-import logic against a real, persisting
// engine (embedded Dolt, the in-process store the repo ships) rather than the
// call-recording mock in import_chunking_test.go: they assert that bounded
// transactions leave a durable committed prefix after a crash, that readiness
// edges are visible at every freeze point, and that concurrent row updates do
// not drop the import's deferred edges — invariants the mock cannot answer
// because it never actually stores rows or computes readiness.
//
// They require cgo and are skipped unless BEADS_TEST_EMBEDDED_DOLT=1, following
// the cmd/bd embedded-test convention (see import_embedded_test.go,
// create_embedded_test.go). The shared helpers (setImportChunkSize,
// recordImportPauses, setImportProgressBuffer, chunkTestIssues) live in
// import_chunking_test.go and are reused here.
//
// A prior revision of this suite included TestImportChunkedConcurrentAvailability,
// which opened two connection pools on one database file to probe SQLite's
// two-connection file-lock fairness. That test targeted an
// internal/storage/sqlite backend that is not present on main; embedded Dolt
// serializes writes in-process and refcount-aliases handles per data directory,
// so the two-pool premise does not hold and the probe cannot be ported
// faithfully. The inter-chunk pause it validated end-to-end remains covered by
// TestImportChunkedPausesBetweenChunkTransactions, which asserts a pause is
// issued between every adjacent import transaction. Re-add an availability probe
// when a backend with the relevant concurrency semantics lands.
func requireEmbeddedDolt(t *testing.T) {
t.Helper()
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt chunked-import tests")
}
}
// failNthCreateStore wraps a real store and fails the Nth batch-create call,
// simulating a crash mid-import against a real engine.
type failNthCreateStore struct {
storage.DoltStorage
calls int
failOnCall int
}
func (f *failNthCreateStore) CreateIssuesWithFullOptions(ctx context.Context, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
f.calls++
if f.calls == f.failOnCall {
return errors.New("simulated crash")
}
return f.DoltStorage.CreateIssuesWithFullOptions(ctx, issues, actor, opts)
}
// provisionChunkStore opens a fresh embedded Dolt store in a temp data dir. The
// store auto-provisions its schema, so no subprocess `bd init` is needed; each
// call uses a distinct t.TempDir() so the per-dir refcount cache never aliases
// two stores together.
func provisionChunkStore(t *testing.T) storage.DoltStorage {
t.Helper()
ctx := context.Background()
store, err := embeddeddolt.Open(ctx, t.TempDir(), "beads", "main")
if err != nil {
t.Fatalf("provision embedded dolt store: %v", err)
}
t.Cleanup(func() { _ = store.Close() })
if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
t.Fatalf("seed issue_prefix: %v", err)
}
return store
}
// End-to-end against the real engine: a mid-import failure leaves a committed,
// queryable prefix, and re-running the same import converges — every row
// present, cross-chunk dependencies wired, no duplicated events.
func TestImportChunkedRealStoreResumeConverges(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
store := provisionChunkStore(t)
makeIssues := func() []*types.Issue {
issues := chunkTestIssues(12)
// Blocking forward reference in file order: 1 -> 11.
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepBlocks}}
return issues
}
failing := &failNthCreateStore{DoltStorage: store, failOnCall: 2}
_, err := importIssuesCore(ctx, "", failing, makeIssues(), ImportOptions{SkipPrefixValidation: true})
if err == nil {
t.Fatalf("importIssuesCore succeeded, want simulated crash at chunk 2")
}
// Some rows are committed and queryable, others absent: the transactions
// really are bounded.
committed, absent := 0, 0
for i := 1; i <= 12; i++ {
if _, err := store.GetIssue(ctx, fmt.Sprintf("bd-chunk%02d", i)); err == nil {
committed++
} else {
absent++
}
}
if committed != 5 || absent != 7 {
t.Fatalf("after crash at chunk 2: committed=%d absent=%d, want exactly the first chunk (5) durable", committed, absent)
}
// Re-run the identical import: it must converge.
result, err := importIssuesCore(ctx, "", store, makeIssues(), ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("re-run importIssuesCore: %v", err)
}
if result.Created != 12 {
t.Fatalf("re-run Created = %d, want all 12 rows accounted for", result.Created)
}
for i := 1; i <= 12; i++ {
id := fmt.Sprintf("bd-chunk%02d", i)
if _, err := store.GetIssue(ctx, id); err != nil {
t.Fatalf("issue %s missing after re-run: %v", id, err)
}
}
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies: %v", err)
}
if len(deps) != 1 || deps[0].ID != "bd-chunk11" {
t.Fatalf("cross-chunk dependency not wired, got %#v", deps)
}
// Rows upserted twice must not accrue duplicate created events.
for _, id := range []string{"bd-chunk01", "bd-chunk02"} {
events, err := store.GetEvents(ctx, id, 50)
if err != nil {
t.Fatalf("GetEvents(%s): %v", id, err)
}
created := 0
for _, e := range events {
if e.EventType == types.EventCreated {
created++
}
}
if created != 1 {
t.Fatalf("%s has %d created events after resume, want 1", id, created)
}
}
}
// No freeze point of a chunked import may expose a blocked bead as ready:
// whenever an imported row is visible to a concurrent reader, the blocking
// edges its import file declares must be visible too. This is the red-team
// ready-window finding: the previous two-phase layout committed every row
// dep-less first, so `bd ready` mid-import offered blocked work for dispatch.
func TestImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
makeIssues := func() []*types.Issue {
issues := chunkTestIssues(12)
// bd-chunk01 is BLOCKED by bd-chunk11 (forward ref in file order).
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepBlocks}}
return issues
}
// Learn how many transactions a full import issues.
full := provisionChunkStore(t)
counting := &failNthCreateStore{DoltStorage: full}
if _, err := importIssuesCore(ctx, "", counting, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("full import: %v", err)
}
totalCalls := counting.calls
if totalCalls < 2 {
t.Fatalf("totalCalls = %d, want a chunked import", totalCalls)
}
ready, err := full.GetReadyWork(ctx, types.WorkFilter{Limit: 50})
if err != nil {
t.Fatalf("GetReadyWork: %v", err)
}
for _, issue := range ready {
if issue.ID == "bd-chunk01" {
t.Fatalf("bd-chunk01 ready after a full import; it is blocked by open bd-chunk11")
}
}
// Freeze the store at every possible transaction boundary and check the
// invariant: row visible => blocking edge visible => not ready.
for failAt := 1; failAt <= totalCalls; failAt++ {
store := provisionChunkStore(t)
failing := &failNthCreateStore{DoltStorage: store, failOnCall: failAt}
if _, err := importIssuesCore(ctx, "", failing, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err == nil {
t.Fatalf("freeze point %d: import unexpectedly succeeded", failAt)
}
if _, err := store.GetIssue(ctx, "bd-chunk01"); err != nil {
continue // row not committed yet: nothing to observe
}
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("freeze point %d: GetDependencies: %v", failAt, err)
}
if len(deps) == 0 {
t.Fatalf("freeze point %d: bd-chunk01 committed without its blocking edge — ready window", failAt)
}
ready, err := store.GetReadyWork(ctx, types.WorkFilter{Limit: 50})
if err != nil {
t.Fatalf("freeze point %d: GetReadyWork: %v", failAt, err)
}
for _, issue := range ready {
if issue.ID == "bd-chunk01" {
t.Fatalf("freeze point %d: blocked bead bd-chunk01 offered as ready work mid-import", failAt)
}
}
}
}
// A readiness edge that points INTO a tolerated readiness cycle must still ride
// inline with its row across every import freeze point: the cycle-fallback
// ordering must not place a valid dependent of a cycle in an earlier chunk than
// the cycle member it blocks on. The import only meets a blocking cycle in
// corrupted or legacy JSONL, which it tolerates (SkipDependencyValidationErrors),
// but the no-ready-window invariant must hold there too — otherwise the
// dependent commits ready-without-blocker for the rest of the import. Regression
// for the attempt-1 review finding.
func TestImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
makeIssues := func() []*types.Issue {
issues := chunkTestIssues(12)
// bd-chunk11 <-> bd-chunk12 form a tolerated blocking cycle. bd-chunk01
// validly blocks on bd-chunk11; in file order it precedes the cycle, so
// a plain file-order fallback would chunk it ahead of bd-chunk11 and
// defer the live edge.
issues[10].Dependencies = []*types.Dependency{{IssueID: issues[10].ID, DependsOnID: issues[11].ID, Type: types.DepBlocks}}
issues[11].Dependencies = []*types.Dependency{{IssueID: issues[11].ID, DependsOnID: issues[10].ID, Type: types.DepBlocks}}
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepBlocks}}
return issues
}
// A full import must tolerate the cycle, leave bd-chunk01 blocked by open
// bd-chunk11, and report how many transactions the import issues.
full := provisionChunkStore(t)
counting := &failNthCreateStore{DoltStorage: full}
if _, err := importIssuesCore(ctx, "", counting, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("full import (tolerated cycle): %v", err)
}
totalCalls := counting.calls
if totalCalls < 2 {
t.Fatalf("totalCalls = %d, want a chunked import", totalCalls)
}
deps, err := full.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies(bd-chunk01): %v", err)
}
if len(deps) != 1 || deps[0].ID != "bd-chunk11" {
t.Fatalf("bd-chunk01 must be blocked by bd-chunk11 after import, got %#v", deps)
}
ready, err := full.GetReadyWork(ctx, types.WorkFilter{Limit: 50})
if err != nil {
t.Fatalf("GetReadyWork: %v", err)
}
for _, issue := range ready {
if issue.ID == "bd-chunk01" {
t.Fatalf("bd-chunk01 ready after a full import; it is blocked by open bd-chunk11 (cycle member)")
}
}
// Freeze at every transaction boundary: whenever bd-chunk01 is visible, its
// blocking edge into the cycle must be visible too, so it is never offered
// as ready mid-import.
for failAt := 1; failAt <= totalCalls; failAt++ {
store := provisionChunkStore(t)
failing := &failNthCreateStore{DoltStorage: store, failOnCall: failAt}
if _, err := importIssuesCore(ctx, "", failing, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err == nil {
t.Fatalf("freeze point %d: import unexpectedly succeeded", failAt)
}
if _, err := store.GetIssue(ctx, "bd-chunk01"); err != nil {
continue // row not committed yet: nothing to observe
}
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("freeze point %d: GetDependencies: %v", failAt, err)
}
if len(deps) == 0 {
t.Fatalf("freeze point %d: bd-chunk01 committed without its blocking edge into the cycle — ready window", failAt)
}
ready, err := store.GetReadyWork(ctx, types.WorkFilter{Limit: 50})
if err != nil {
t.Fatalf("freeze point %d: GetReadyWork: %v", failAt, err)
}
for _, issue := range ready {
if issue.ID == "bd-chunk01" {
t.Fatalf("freeze point %d: blocked bead bd-chunk01 offered as ready work mid-import", failAt)
}
}
}
}
// A waits-for waiter's is_blocked state is gated on its spawner having an active
// parent-child child, and the per-chunk is_blocked recompute only re-evaluates
// the rows in its own transaction. So when the waiter and its spawner's active
// child straddle a chunk boundary in file order (waiter first, child later), a
// naive ordering leaves the waiter's chunk computing is_blocked=0 against a
// still-childless spawner, and the later chunk that imports the child never
// re-blocks the waiter — it sits ready for the rest of the import and after it.
// Ordering the spawner inline with the waiter is not enough; every in-batch
// child of a waited spawner must be emitted no later than the waiter. Regression
// for the attempt-2 review blocker.
func TestImportChunkedWaitsForChildImportedLaterStaysBlocked(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
makeIssues := func() []*types.Issue {
// File order: waiter, spawner, three fillers, active child. At chunk
// size 5 the waiter (chunk 0) and the child (chunk 1) straddle the
// boundary unless the import reorders the child ahead of the waiter.
// bd-chunk01 waits for bd-chunk02; bd-chunk06 is an open parent-child
// child of bd-chunk02.
issues := chunkTestIssues(6)
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[1].ID, Type: types.DepWaitsFor}}
issues[5].Dependencies = []*types.Dependency{{IssueID: issues[5].ID, DependsOnID: issues[1].ID, Type: types.DepParentChild}}
return issues
}
full := provisionChunkStore(t)
counting := &failNthCreateStore{DoltStorage: full}
if _, err := importIssuesCore(ctx, "", counting, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("full import (waits-for child across chunks): %v", err)
}
if counting.calls < 2 {
t.Fatalf("calls = %d, want a chunked (>=2 transaction) import so the waiter and child can straddle a boundary", counting.calls)
}
// The waits-for edge must be wired inline so the gate can see it.
waiterDeps, err := full.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies(bd-chunk01): %v", err)
}
if len(waiterDeps) != 1 || waiterDeps[0].ID != "bd-chunk02" {
t.Fatalf("bd-chunk01 must wait for bd-chunk02 after import, got %#v", waiterDeps)
}
// The waiter must NOT be ready: its spawner bd-chunk02 has an open child
// bd-chunk06, so the waits-for gate keeps bd-chunk01 blocked.
ready, err := full.GetReadyWork(ctx, types.WorkFilter{Limit: 50})
if err != nil {
t.Fatalf("GetReadyWork: %v", err)
}
for _, issue := range ready {
if issue.ID == "bd-chunk01" {
t.Fatalf("bd-chunk01 ready after a full import; it waits for bd-chunk02 whose active child bd-chunk06 was imported in a later chunk")
}
}
}
// raceInjectingStore simulates a concurrent writer landing between import
// transactions: before the Nth CreateIssuesWithFullOptions call it updates an
// issue directly, bumping its updated_at — exactly what a concurrent
// `bd update` or a gc claim does in the windows the chunking opens up.
type raceInjectingStore struct {
storage.DoltStorage
calls int
injectBefore int
injectID string
injected bool
t *testing.T
}
func (r *raceInjectingStore) CreateIssuesWithFullOptions(ctx context.Context, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
r.calls++
if r.calls == r.injectBefore && !r.injected {
r.injected = true
if err := r.DoltStorage.UpdateIssue(ctx, r.injectID, map[string]interface{}{"assignee": "concurrent-racer"}, "racer"); err != nil {
r.t.Fatalf("inject concurrent update: %v", err)
}
}
return r.DoltStorage.CreateIssuesWithFullOptions(ctx, issues, actor, opts)
}
// A concurrent update to a row between its commit and the deferred-dependency
// pass must not drop the import's edges for it. This is the red-team #1
// finding: the old dependency pass resubmitted the full row with
// RejectStaleUpserts, so the now-newer stored row stale-rejected the resubmit
// and the engine dropped its deps — silently, permanently (re-runs pre-filter
// the row away). The dependency pass must wire edges for every row phase 1
// accepted, regardless of later row-level updates, and must not clobber the
// concurrent write.
func TestImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
store := provisionChunkStore(t)
makeIssues := func() []*types.Issue {
issues := chunkTestIssues(12)
// A non-blocking forward edge stays deferred (related edges do not
// affect readiness, so the ordering pass leaves file order alone):
// this is the shape that still crosses the inter-transaction window.
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepRelated}}
return issues
}
// 12 issues at chunk size 5 = 3 row chunks (calls 1-3); the deferred
// dependency pass is call 4. Inject the concurrent update just before it.
racing := &raceInjectingStore{DoltStorage: store, injectBefore: 4, injectID: "bd-chunk01", t: t}
result, err := importIssuesCore(ctx, "", racing, makeIssues(), ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if !racing.injected {
t.Fatalf("race was never injected (calls=%d); test harness broken", racing.calls)
}
// The concurrent write survives: the dependency pass must not rewrite rows.
got, err := store.GetIssue(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("bd-chunk01 not committed: %v", err)
}
if got.Assignee != "concurrent-racer" {
t.Fatalf("assignee = %q, want the concurrent update preserved", got.Assignee)
}
// The import's edge survives: phase 1 accepted the row, so its deferred
// deps must be wired even though the stored row is now newer.
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies: %v", err)
}
if len(deps) != 1 || deps[0].ID != "bd-chunk11" {
t.Fatalf("deferred edge dropped after concurrent update: deps = %#v", deps)
}
// And the reporting must not misclassify the row: its row IS committed.
for _, id := range result.StaleSkippedIDs {
if id == "bd-chunk01" {
t.Fatalf("bd-chunk01 reported stale-skipped, but its row was imported in phase 1")
}
}
if result.Created != 12 {
t.Fatalf("Created = %d, want 12", result.Created)
}
}
// The red-team #1 repro shape verbatim, for blocking edges: a claim-like
// update racing the import must leave the blocking edge intact. With ordered
// inline wiring the row and its edge commit atomically, so no interleaving of
// row-level updates can separate them.
func TestImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
store := provisionChunkStore(t)
makeIssues := func() []*types.Issue {
issues := chunkTestIssues(12)
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepBlocks}}
return issues
}
// The blocker's row (bd-chunk11) lands before bd-chunk01's chunk. Update
// it between chunks — the interleaving that used to poison the dep pass.
racing := &raceInjectingStore{DoltStorage: store, injectBefore: 3, injectID: "bd-chunk11", t: t}
if _, err := importIssuesCore(ctx, "", racing, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if !racing.injected {
t.Fatalf("race was never injected (calls=%d); test harness broken", racing.calls)
}
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies: %v", err)
}
if len(deps) != 1 || deps[0].ID != "bd-chunk11" {
t.Fatalf("blocking edge missing after concurrent update: deps = %#v", deps)
}
// Re-running the identical import stays convergent and keeps the edge.
if _, err := importIssuesCore(ctx, "", store, makeIssues(), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("re-run importIssuesCore: %v", err)
}
deps, err = store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies after re-run: %v", err)
}
if len(deps) != 1 {
t.Fatalf("blocking edge lost on re-run: deps = %#v", deps)
}
}
// The other half of the stale-snapshot invariant (bd-578h9.8): when the row
// write itself was stale-rejected in phase 1 (a local update landed between
// the pre-filter read and the row's chunk), the snapshot's deferred deps must
// stay out too. This is why the dependency pass cannot simply run everything
// with ConflictSkip: it must be restricted to rows phase 1 accepted.
func TestImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
store := provisionChunkStore(t)
base := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
// Seed bd-chunk01 with an OLDER snapshot so the incoming row passes the
// pre-filter (incoming strictly newer than local at read time).
seed := &types.Issue{ID: "bd-chunk01", Title: "seeded", UpdatedAt: base.Add(-time.Hour)}
seed.SetDefaults()
if _, err := importIssuesCore(ctx, "", store, []*types.Issue{seed}, ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("seed import: %v", err)
}
issues := chunkTestIssues(12)
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[10].ID, Type: types.DepRelated}}
// Bump bd-chunk01 to "now" after the pre-filter read but before its row
// chunk: the in-transaction stale guard rejects the row write, so the
// whole snapshot — deferred deps included — must stay out.
racing := &raceInjectingStore{DoltStorage: store, injectBefore: 1, injectID: "bd-chunk01", t: t}
result, err := importIssuesCore(ctx, "", racing, issues, ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if !racing.injected {
t.Fatalf("race was never injected; test harness broken")
}
deps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies: %v", err)
}
if len(deps) != 0 {
t.Fatalf("stale-rejected row's deferred deps were wired anyway: %#v (violates bd-578h9.8)", deps)
}
found := false
for _, id := range result.StaleSkippedIDs {
if id == "bd-chunk01" {
found = true
}
}
if !found {
t.Fatalf("bd-chunk01 not reported stale-skipped; StaleSkippedIDs = %v", result.StaleSkippedIDs)
}
}
// A chunked import mixing regular issues and wisps must apply the cross-bucket
// dependency policy over the FULL logical set, not per chunk. Dependencies are
// stored in per-bucket tables (dependencies vs wisp_dependencies), so a batch
// cannot create a regular<->wisp edge atomically; the engine's per-chunk filter
// only sees one chunk and short-circuits on an all-one-bucket chunk, so it can
// no longer catch a cross-bucket edge whose endpoints land in different chunks.
// The up-front FilterCreateIssuesMixedBucketDependencies pass exists for exactly
// that case. This exercises it end to end against the real engine: a regular ->
// wisp edge straddling a chunk boundary must be skip-reported while both rows
// still import, and a same-bucket wisp -> wisp edge straddling the same boundary
// must survive the double filtering and be wired. Regression for the attempt-1
// test-evidence finding (the prior chunked tests seeded only regular issues).
func TestImportChunkedMixedRegularWispCrossBucketFiltering(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
setImportProgressBuffer(t)
ctx := context.Background()
store := provisionChunkStore(t)
base := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
mk := func(id string, wisp bool) *types.Issue {
iss := &types.Issue{ID: id, Title: id, UpdatedAt: base, Ephemeral: wisp}
iss.SetDefaults()
return iss
}
// 12 rows across three chunks (5/5/2) at chunk size 5. Every edge below is
// `related` (non-readiness), so orderImportIssuesForChunking preserves file
// order and the two forward edges genuinely straddle the chunk-0/chunk-1
// boundary. Chunks 0 and 1 are each mixed (regular + wisp), so the engine's
// per-chunk mixed-bucket filter actually runs instead of short-circuiting on
// an all-one-bucket chunk.
makeIssues := func() []*types.Issue {
issues := []*types.Issue{
mk("bd-chunk01", false), // chunk 0: regular source of the cross-bucket edge
mk("bd-wisp02", true), // chunk 0: wisp source of the same-bucket edge
mk("bd-chunk03", false), // chunk 0
mk("bd-chunk04", false), // chunk 0
mk("bd-chunk05", false), // chunk 0
mk("bd-chunk06", false), // chunk 1
mk("bd-wisp07", true), // chunk 1: shared target wisp
mk("bd-chunk08", false), // chunk 1
mk("bd-chunk09", false), // chunk 1
mk("bd-chunk10", false), // chunk 1
mk("bd-chunk11", false), // chunk 2
mk("bd-chunk12", false), // chunk 2
}
// Cross-bucket regular -> wisp, endpoints in different chunks: only the
// up-front full-set filter can see both ends, so it must be skip-reported.
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: "bd-wisp07", Type: types.DepRelated}}
// Same-bucket wisp -> wisp, endpoints in different chunks: must survive the
// double filtering and be wired into wisp_dependencies.
issues[1].Dependencies = []*types.Dependency{{IssueID: issues[1].ID, DependsOnID: "bd-wisp07", Type: types.DepRelated}}
return issues
}
counting := &failNthCreateStore{DoltStorage: store}
result, err := importIssuesCore(ctx, "", counting, makeIssues(), ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
// 3 row chunks (5/5/2) plus one deferred-dependency pass for the surviving
// same-bucket cross-chunk edge — so the endpoints really did straddle a
// boundary and the deferred pass really ran.
if counting.calls != 4 {
t.Fatalf("calls = %d, want 3 row chunks + 1 deferred-dependency pass", counting.calls)
}
if result.Created != 12 {
t.Fatalf("Created = %d, want 12 (every row imports even when a cross-bucket edge is dropped)", result.Created)
}
// The cross-bucket edge is dropped and reported exactly once; the same-bucket
// edge is never reported.
if len(result.SkippedDependencies) != 1 ||
!strings.Contains(result.SkippedDependencies[0], "bd-chunk01 -> bd-wisp07") ||
!strings.Contains(result.SkippedDependencies[0], "cross-bucket") {
t.Fatalf("SkippedDependencies = %#v, want exactly the cross-bucket bd-chunk01 -> bd-wisp07 edge", result.SkippedDependencies)
}
// Both endpoints of the dropped cross-bucket edge still imported (GetIssue
// finds the wisp in the wisps table too).
if _, err := store.GetIssue(ctx, "bd-chunk01"); err != nil {
t.Fatalf("regular source bd-chunk01 not imported: %v", err)
}
if _, err := store.GetIssue(ctx, "bd-wisp07"); err != nil {
t.Fatalf("wisp target bd-wisp07 not imported: %v", err)
}
// The cross-bucket edge left no dependency on the regular source.
regularDeps, err := store.GetDependencies(ctx, "bd-chunk01")
if err != nil {
t.Fatalf("GetDependencies(bd-chunk01): %v", err)
}
if len(regularDeps) != 0 {
t.Fatalf("bd-chunk01 deps = %#v, want none (cross-bucket edge dropped)", regularDeps)
}
// The same-bucket wisp -> wisp edge survived the chunk boundary and is wired
// into wisp_dependencies (GetDependencies routes a wisp source there).
wispDeps, err := store.GetDependencies(ctx, "bd-wisp02")
if err != nil {
t.Fatalf("GetDependencies(bd-wisp02): %v", err)
}
if len(wispDeps) != 1 || wispDeps[0].ID != "bd-wisp07" {
t.Fatalf("bd-wisp02 deps = %#v, want the same-bucket wisp->wisp edge to bd-wisp07 preserved", wispDeps)
}
}

View file

@ -0,0 +1,338 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// chunkRecordingStore records every CreateIssuesWithFullOptions call as a
// snapshot (issue rows plus the dependencies attached at call time), so tests
// can assert on transaction boundaries. failOnCall simulates a mid-import
// failure at the Nth call (1-based; 0 = never fail).
//
// Tests that need a real, persisting engine (durable committed prefixes,
// readiness recomputation, event dedup) live in import_chunking_embedded_test.go
// and run against embedded Dolt behind BEADS_TEST_EMBEDDED_DOLT; the shared
// helpers below are reused by both files.
type chunkRecordingStore struct {
storage.DoltStorage
batches [][]*types.Issue
calls int
failOnCall int
}
func (f *chunkRecordingStore) GetIssuesByIDs(_ context.Context, _ []string) ([]*types.Issue, error) {
return nil, nil
}
func (f *chunkRecordingStore) CreateIssuesWithFullOptions(_ context.Context, issues []*types.Issue, _ string, _ storage.BatchCreateOptions) error {
f.calls++
if f.failOnCall != 0 && f.calls == f.failOnCall {
return errors.New("simulated chunk failure")
}
snapshot := make([]*types.Issue, len(issues))
for i, issue := range issues {
cp := *issue
cp.Dependencies = append([]*types.Dependency(nil), issue.Dependencies...)
snapshot[i] = &cp
}
f.batches = append(f.batches, snapshot)
return nil
}
func setImportChunkSize(t *testing.T, n int) {
t.Helper()
old := importChunkSize
importChunkSize = n
t.Cleanup(func() { importChunkSize = old })
}
func setImportProgressBuffer(t *testing.T) *bytes.Buffer {
t.Helper()
old := importProgress
buf := &bytes.Buffer{}
importProgress = buf
t.Cleanup(func() { importProgress = old })
return buf
}
// recordImportPauses replaces the inter-chunk sleep with a counter so tests
// run at full speed while still asserting the pause is issued.
func recordImportPauses(t *testing.T) *int {
t.Helper()
old := importPause
count := 0
importPause = func(time.Duration) { count++ }
t.Cleanup(func() { importPause = old })
return &count
}
func chunkTestIssues(n int) []*types.Issue {
base := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
issues := make([]*types.Issue, n)
for i := range issues {
issues[i] = &types.Issue{
ID: fmt.Sprintf("bd-chunk%02d", i+1),
Title: fmt.Sprintf("chunk issue %d", i+1),
UpdatedAt: base,
}
issues[i].SetDefaults()
}
return issues
}
// An import at or below the chunk size must keep today's semantics exactly:
// one CreateIssuesWithFullOptions call, dependencies inline, one transaction.
func TestImportIssuesCoreSingleBatchAtOrBelowChunkSize(t *testing.T) {
setImportChunkSize(t, 4)
recordImportPauses(t)
issues := chunkTestIssues(4)
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[3].ID, Type: types.DepBlocks}}
store := &chunkRecordingStore{}
result, err := importIssuesCore(context.Background(), "", store, issues, ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 1 {
t.Fatalf("calls = %d, want exactly 1 transaction for a small import", store.calls)
}
if len(store.batches[0]) != 4 {
t.Fatalf("batch size = %d, want 4", len(store.batches[0]))
}
foundDep := false
for _, issue := range store.batches[0] {
if issue.ID == issues[0].ID && len(issue.Dependencies) == 1 {
foundDep = true
}
}
if !foundDep {
t.Fatalf("small import must keep dependencies inline in the single batch")
}
if result.Created != 4 {
t.Fatalf("Created = %d, want 4", result.Created)
}
}
// A large import must be split into bounded transactions so the write lock is
// released between chunks instead of being held for the whole batch.
func TestImportIssuesCoreChunksLargeImports(t *testing.T) {
setImportChunkSize(t, 3)
recordImportPauses(t)
progress := setImportProgressBuffer(t)
issues := chunkTestIssues(8)
store := &chunkRecordingStore{}
result, err := importIssuesCore(context.Background(), "", store, issues, ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 3 {
t.Fatalf("calls = %d, want 3 bounded transactions (3+3+2)", store.calls)
}
wantSizes := []int{3, 3, 2}
seen := map[string]int{}
for i, batch := range store.batches {
if len(batch) != wantSizes[i] {
t.Fatalf("batch %d size = %d, want %d", i, len(batch), wantSizes[i])
}
for _, issue := range batch {
seen[issue.ID]++
}
}
for _, issue := range issues {
if seen[issue.ID] != 1 {
t.Fatalf("issue %s written %d times, want exactly once", issue.ID, seen[issue.ID])
}
}
if result.Created != 8 {
t.Fatalf("Created = %d, want 8", result.Created)
}
if got := progress.String(); !strings.Contains(got, "8/8") {
t.Fatalf("progress output missing final count, got %q", got)
}
}
// Exactly chunk-size and chunk-size+1 imports: no empty trailing chunk, and
// the boundary issue lands in a second transaction.
func TestImportIssuesCoreChunkBoundaries(t *testing.T) {
setImportChunkSize(t, 3)
recordImportPauses(t)
store := &chunkRecordingStore{}
if _, err := importIssuesCore(context.Background(), "", store, chunkTestIssues(3), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 1 {
t.Fatalf("calls = %d, want 1 for an exactly-chunk-size import", store.calls)
}
store = &chunkRecordingStore{}
if _, err := importIssuesCore(context.Background(), "", store, chunkTestIssues(4), ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 2 {
t.Fatalf("calls = %d, want 2 for a chunk-size+1 import", store.calls)
}
if got := []int{len(store.batches[0]), len(store.batches[1])}; got[0] != 3 || got[1] != 1 {
t.Fatalf("batch sizes = %v, want [3 1]", got)
}
}
// Readiness-affecting dependencies must land in the same transaction as the
// dependent's row, whatever order the JSONL puts the rows in: the import
// reorders rows so every (acyclic) blocking target lands in the same or an
// earlier chunk, and the edge rides inline with the row. No separate
// dependency pass may exist for them — a dependency pass is a window in which
// a concurrent reader sees the row without its edges.
func TestImportChunkedBlockingDepsLandInSameTransactionAsRow(t *testing.T) {
setImportChunkSize(t, 3)
recordImportPauses(t)
setImportProgressBuffer(t)
issues := chunkTestIssues(7)
// Forward reference across the chunk boundary in file order: 1 -> 7.
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[6].ID, Type: types.DepBlocks}}
// Backward reference: 5 -> 1.
issues[4].Dependencies = []*types.Dependency{{IssueID: issues[4].ID, DependsOnID: issues[0].ID, Type: types.DepBlocks}}
store := &chunkRecordingStore{}
if _, err := importIssuesCore(context.Background(), "", store, issues, ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 3 {
t.Fatalf("calls = %d, want 3 row chunks and NO separate dependency pass", store.calls)
}
// Every dependency must ride in its owner's row batch, and its target must
// already exist by the end of that batch (same or earlier batch).
batchOf := map[string]int{}
for b, batch := range store.batches {
for _, issue := range batch {
batchOf[issue.ID] = b
}
}
wantDeps := map[string]string{
issues[0].ID: issues[6].ID,
issues[4].ID: issues[0].ID,
}
got := map[string]string{}
for _, batch := range store.batches {
for _, issue := range batch {
for _, dep := range issue.Dependencies {
got[issue.ID] = dep.DependsOnID
tb, ok := batchOf[dep.DependsOnID]
if !ok {
t.Fatalf("dependency target %s never written", dep.DependsOnID)
}
if tb > batchOf[issue.ID] {
t.Fatalf("issue %s (batch %d) carries an edge to %s (batch %d): target does not exist when the edge commits",
issue.ID, batchOf[issue.ID], dep.DependsOnID, tb)
}
}
}
}
for id, target := range wantDeps {
if got[id] != target {
t.Fatalf("edge %s -> %s not written inline (got %q)", id, target, got[id])
}
}
// The caller's issues must come back with dependencies intact so a retry
// of the same slice still carries them.
if len(issues[0].Dependencies) != 1 || len(issues[4].Dependencies) != 1 {
t.Fatalf("original issues lost their dependencies after import")
}
}
// A failure mid-import must surface as an error naming the committed prefix,
// stop issuing further transactions, and leave the input re-runnable.
func TestImportIssuesCoreChunkedMidFailureLeavesCommittedPrefix(t *testing.T) {
setImportChunkSize(t, 3)
recordImportPauses(t)
setImportProgressBuffer(t)
issues := chunkTestIssues(8)
issues[7].Dependencies = []*types.Dependency{{IssueID: issues[7].ID, DependsOnID: issues[0].ID, Type: types.DepBlocks}}
store := &chunkRecordingStore{failOnCall: 2}
_, err := importIssuesCore(context.Background(), "", store, issues, ImportOptions{SkipPrefixValidation: true})
if err == nil {
t.Fatalf("importIssuesCore succeeded, want mid-chunk failure to surface")
}
if !strings.Contains(err.Error(), "3 issues already committed") {
t.Fatalf("error %q does not name the committed prefix", err)
}
if !strings.Contains(err.Error(), "re-run") {
t.Fatalf("error %q does not tell the user the import is re-runnable", err)
}
if store.calls != 2 {
t.Fatalf("calls = %d, want to stop after the failing chunk", store.calls)
}
if len(store.batches) != 1 || len(store.batches[0]) != 3 {
t.Fatalf("committed prefix = %d batches, want exactly the first chunk", len(store.batches))
}
if len(issues[7].Dependencies) != 1 {
t.Fatalf("failure path lost the caller's dependencies; retry would drop edges")
}
}
// The bounded transactions must not run back-to-back: a chunked import that
// re-takes the write lock microseconds after each commit starves every
// concurrent bd operation for the whole import (SQLite busy-polling has no
// fairness queue). A pause must separate every adjacent pair of import
// transactions, including the boundary into the deferred-dependency pass.
func TestImportChunkedPausesBetweenChunkTransactions(t *testing.T) {
setImportChunkSize(t, 3)
setImportProgressBuffer(t)
pauses := recordImportPauses(t)
issues := chunkTestIssues(8)
// A non-blocking forward reference forces a deferred-dependency pass, so
// the count also covers the phase boundary. 3 row chunks + 1 dep pass.
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[7].ID, Type: types.DepRelated}}
store := &chunkRecordingStore{}
if _, err := importIssuesCore(context.Background(), "", store, issues, ImportOptions{SkipPrefixValidation: true}); err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if store.calls != 4 {
t.Fatalf("calls = %d, want 3 row chunks + 1 deferred-dependency pass", store.calls)
}
if *pauses != store.calls-1 {
t.Fatalf("pauses = %d, want one between every adjacent pair of transactions (%d)", *pauses, store.calls-1)
}
if importInterChunkPause <= 0 {
t.Fatalf("importInterChunkPause = %v, want a positive gap for lock fairness", importInterChunkPause)
}
}
// orderImportIssuesForChunking must emit a cycle member before a valid row that
// blocks on it, even when that row precedes the cycle in file order. A plain
// file-order cycle fallback would chunk the dependent ahead of its blocker and
// defer the live readiness edge. Regression for the attempt-1 review finding.
func TestOrderImportIssuesForChunkingPlacesCycleBeforeDependent(t *testing.T) {
issues := chunkTestIssues(4)
// bd-chunk03 <-> bd-chunk04 is a tolerated blocking cycle; bd-chunk01
// validly blocks on bd-chunk03 — an acyclic edge pointing into the cycle.
issues[2].Dependencies = []*types.Dependency{{IssueID: issues[2].ID, DependsOnID: issues[3].ID, Type: types.DepBlocks}}
issues[3].Dependencies = []*types.Dependency{{IssueID: issues[3].ID, DependsOnID: issues[2].ID, Type: types.DepBlocks}}
issues[0].Dependencies = []*types.Dependency{{IssueID: issues[0].ID, DependsOnID: issues[2].ID, Type: types.DepBlocks}}
ordered := orderImportIssuesForChunking(issues)
if len(ordered) != len(issues) {
t.Fatalf("ordered length = %d, want %d", len(ordered), len(issues))
}
pos := map[string]int{}
for i, issue := range ordered {
pos[issue.ID] = i
}
if pos["bd-chunk03"] > pos["bd-chunk01"] {
t.Fatalf("bd-chunk03 (blocker on a cycle) at %d must precede its dependent bd-chunk01 at %d so the edge rides inline",
pos["bd-chunk03"], pos["bd-chunk01"])
}
}

View file

@ -5,15 +5,48 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// importChunkSize bounds the number of issues written per transaction during
// import. One giant transaction holds the store's write lock for the whole
// batch (a 26k-issue import measured ~2 minutes of full-store outage on
// SQLite); bounded chunks release the lock between commits so concurrent
// readers and writers interleave.
//
// 250 was picked by measurement (8k-issue import, SQLite backend): 250- and
// 500-issue chunks both cost ~13% total time over one big transaction, but
// 250 holds the write lock ~1.4s per transaction versus ~2.8s at 500 and ~6s
// at 1000 — and the SQLite connection's busy_timeout is 5s, so per-chunk lock
// holds must stay comfortably below that for concurrent bd operations to wait
// out an import instead of failing. A var, not a const, so tests can shrink it.
var importChunkSize = 250
// importInterChunkPause is slept between import transactions. Bounding the
// transactions is not enough on its own: SQLite busy-polling has no fairness
// queue, so a loop that re-issues BEGIN IMMEDIATE microseconds after each
// COMMIT re-takes the lock before any waiter's poll fires and starves every
// concurrent bd operation for the whole import — measured as an unchanged
// 100% failure pattern with zero lock acquisitions across 20 chunk commits.
// The pause is the acquisition window that lets waiters in. 150ms costs
// ~15s on a 26k-issue import (104 chunks) against the ~2-minute write time.
var importInterChunkPause = 150 * time.Millisecond
// importPause is the sleep seam for the inter-chunk pause, swappable in tests.
var importPause = time.Sleep
// importProgress is where chunked imports report per-chunk progress.
// Swappable in tests.
var importProgress io.Writer = os.Stderr
// ImportOptions configures import behavior.
type ImportOptions struct {
DryRun bool
@ -106,7 +139,8 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
// (local update committed between the pre-filter read and the batch
// write). The transaction may retry, so dedup by ID.
staleRejectedSet := make(map[string]struct{})
err := store.CreateIssuesWithFullOptions(ctx, issues, getActorWithGit(), storage.BatchCreateOptions{
actor := getActorWithGit()
batchOpts := storage.BatchCreateOptions{
OrphanHandling: storage.OrphanAllow,
SkipPrefixValidation: opts.SkipPrefixValidation,
ConflictSkip: opts.ConflictSkip,
@ -123,7 +157,15 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
OnStaleRejected: func(issueID string) {
staleRejectedSet[issueID] = struct{}{}
},
})
}
var err error
if len(issues) <= importChunkSize {
// Small import: one transaction, dependencies inline — exactly the
// pre-chunking behavior.
err = store.CreateIssuesWithFullOptions(ctx, issues, actor, batchOpts)
} else {
err = importIssuesChunked(ctx, store, issues, actor, batchOpts)
}
if err != nil {
return nil, err
}
@ -159,6 +201,437 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
}, nil
}
// importIssuesChunked writes a large import in bounded transactions of
// importChunkSize rows instead of one batch-wide transaction, sleeping
// importInterChunkPause between commits. One giant transaction holds the
// store's write lock for the whole import, taking every concurrent bd
// operation down with it; bounded chunks cap the per-transaction lock hold,
// and the pause between commits is the fairness window that actually lets
// waiters acquire (see importInterChunkPause).
//
// Rows are written in dependency order (orderImportIssuesForChunking): every
// readiness-affecting edge owned by a non-cycle row points at a row in the same
// or an earlier chunk — Kahn's order for the acyclic majority, plus a
// cycle-breaking fallback that still emits each cycle member before the rows it
// blocks — so that edge rides inline with its row and both commit in one
// transaction. Only a force-emitted cycle member can carry a readiness edge into
// the deferred pass, and that is the already-tolerated corrupt/legacy-cycle
// window. A concurrent reader therefore never observes a non-cycle imported bead
// without the blocking edges its import file declares —
// `bd ready` mid-import cannot offer blocked work for dispatch, and a crash
// mid-import cannot freeze a bead in a spuriously-ready state.
//
// Only edges that cannot be satisfied when their row commits are deferred to
// a final dependency pass: edges into an intra-batch dependency cycle
// (invalid for blocking types; still broken and skip-reported at wire time,
// though for a cycle of length >=3 the specific edge dropped — and thus which
// member is left spuriously ready — can differ from the single-transaction
// import, which checks the whole cycle in file order) and non-readiness edges
// (related, discovered-from) that point at a later chunk. The dependency pass submits
// row copies stripped to those deferred edges with ConflictSkip set, so an
// existing row is never rewritten: a concurrent update landing between a
// row's chunk and the dependency pass cannot stale-reject the pass and drop
// the edges (the resubmit-the-full-row alternative did exactly that,
// silently and unrecoverably). Rows whose phase-1 write was itself
// stale-rejected are excluded from the pass: a stale snapshot keeps its
// labels, comments, AND dependencies out (bd-578h9.8).
//
// Every per-row application is an idempotent upsert (conditional-update row
// write, INSERT IGNORE labels, existence-checked comments, deterministic-id
// dependency edges, created-events only for genuinely new rows), so a failure
// mid-import leaves a committed, durable prefix and re-running the same import
// converges on the full set — subject to the import's standing stale policy:
// a row a rival updated since its chunk committed is locally newer on the
// re-run, so the pre-filter stale-skips that snapshot wholesale (row and any
// still-unwired deferred edges), reported in StaleSkippedIDs. That is the
// same local-wins outcome the single-transaction import gave a rival update
// racing a crashed import, and it can only affect deferred edges (non-readiness
// edges, plus the readiness edges of force-emitted cycle members); every
// non-cycle row's readiness edges commit with their row.
func importIssuesChunked(ctx context.Context, store storage.DoltStorage, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
// Apply the cross-bucket dependency policy over the full set up front:
// the engine's per-batch filter only sees one chunk, so it could no
// longer detect an edge whose endpoints land in different chunks.
issues, err := issueops.FilterCreateIssuesMixedBucketDependencies(issues, opts)
if err != nil {
return err
}
ordered := orderImportIssuesForChunking(issues)
// Partitioning narrows each issue's dependency slice to its inline subset in
// place; always restore the full slices so the caller's issues stay intact
// for retries and reporting.
fullDeps := make([][]*types.Dependency, len(ordered))
for i, issue := range ordered {
fullDeps[i] = issue.Dependencies
}
defer func() {
for i, issue := range ordered {
issue.Dependencies = fullDeps[i]
}
}()
deferred := partitionChunkedImportDeps(ordered)
// Record phase-1 stale rejections locally (as well as forwarding them to
// the caller): the dependency pass must skip those rows.
phase1Stale := make(map[string]struct{})
rowOpts := opts
rowOpts.OnStaleRejected = func(issueID string) {
phase1Stale[issueID] = struct{}{}
if opts.OnStaleRejected != nil {
opts.OnStaleRejected(issueID)
}
}
pacer := &importChunkPacer{}
if err := writeImportRowChunks(ctx, store, ordered, actor, rowOpts, pacer); err != nil {
return err
}
return wireDeferredImportDeps(ctx, store, deferred, phase1Stale, len(ordered), actor, opts, pacer)
}
// importChunkPacer sleeps importInterChunkPause between import transactions. One
// shared pacer spans phase 1 and the dependency pass, so the fairness pause is
// issued before every transaction except the very first: SQLite busy-polling has
// no fairness queue, and a back-to-back BEGIN IMMEDIATE re-takes the lock before
// a waiter's poll fires (see importInterChunkPause).
type importChunkPacer struct{ transactions int }
func (p *importChunkPacer) beforeTx() {
if p.transactions > 0 {
importPause(importInterChunkPause)
}
p.transactions++
}
// deferredImportEdges carries the dependencies of one row that could not be
// wired inline with its phase-1 write and must be applied in the dependency
// pass.
type deferredImportEdges struct {
issue *types.Issue
deps []*types.Dependency
}
// partitionChunkedImportDeps splits each ordered row's dependencies into edges
// wired inline with the row (target outside the batch, or first written in the
// same or an earlier chunk) and edges deferred to the dependency pass. It
// narrows each issue's dependency slice to the inline subset in place and
// returns the deferred edges. orderImportIssuesForChunking guarantees every
// readiness edge owned by a non-cycle row points at the same or an earlier
// chunk, so only non-readiness edges (related, discovered-from) into a later
// chunk and the readiness edges of force-emitted cycle members (their own cyclic
// edges, plus any acyclic blocker they were emitted ahead of) are ever deferred
// here.
func partitionChunkedImportDeps(ordered []*types.Issue) []deferredImportEdges {
firstChunkOf := make(map[string]int, len(ordered))
for pos, issue := range ordered {
if issue.ID == "" {
continue // ID assigned by the engine at insert; nothing can reference it yet
}
if _, ok := firstChunkOf[issue.ID]; !ok {
firstChunkOf[issue.ID] = pos / importChunkSize
}
}
var deferred []deferredImportEdges
for pos, issue := range ordered {
if len(issue.Dependencies) == 0 {
continue
}
inline, later := splitDepsByChunk(issue.Dependencies, pos/importChunkSize, firstChunkOf)
if len(later) == 0 {
continue
}
issue.Dependencies = inline
deferred = append(deferred, deferredImportEdges{issue: issue, deps: later})
}
return deferred
}
// splitDepsByChunk partitions one row's dependencies (the row lands in rowChunk)
// into edges that can be wired inline and edges whose target is first written in
// a later chunk and so must be deferred.
func splitDepsByChunk(deps []*types.Dependency, rowChunk int, firstChunkOf map[string]int) (inline, later []*types.Dependency) {
for _, dep := range deps {
if targetChunk, inBatch := firstChunkOf[dep.DependsOnID]; inBatch && targetChunk > rowChunk {
later = append(later, dep)
continue
}
inline = append(inline, dep)
}
return inline, later
}
// writeImportRowChunks writes the ordered rows (dependencies already narrowed to
// their inline subset) in bounded transactions, pausing between commits.
func writeImportRowChunks(ctx context.Context, store storage.DoltStorage, ordered []*types.Issue, actor string, rowOpts storage.BatchCreateOptions, pacer *importChunkPacer) error {
total := len(ordered)
chunks := (total + importChunkSize - 1) / importChunkSize
for start, chunk := 0, 1; start < total; start, chunk = start+importChunkSize, chunk+1 {
end := min(start+importChunkSize, total)
pacer.beforeTx()
if err := store.CreateIssuesWithFullOptions(ctx, ordered[start:end], actor, rowOpts); err != nil {
return fmt.Errorf("import chunk %d/%d failed, %d issues already committed (committed rows are durable; re-run the import to resume — it converges): %w", chunk, chunks, start, err)
}
fmt.Fprintf(importProgress, "bd import: %d/%d issues committed\n", end, total)
}
return nil
}
// wireDeferredImportDeps applies the deferred edges once every target row exists,
// without rewriting the rows themselves. rowTotal is the count of phase-1 rows
// already committed, used only for the resume message.
func wireDeferredImportDeps(ctx context.Context, store storage.DoltStorage, deferred []deferredImportEdges, phase1Stale map[string]struct{}, rowTotal int, actor string, opts storage.BatchCreateOptions, pacer *importChunkPacer) error {
depRows := make([]*types.Issue, 0, len(deferred))
for _, d := range deferred {
if _, stale := phase1Stale[d.issue.ID]; stale {
continue // stale snapshot: its deps stay out too (bd-578h9.8)
}
cp := *d.issue
cp.Dependencies = d.deps
// The row landed in phase 1 and its labels/comments merged there;
// this pass carries edges only.
cp.Labels = nil
cp.Comments = nil
depRows = append(depRows, &cp)
}
if len(depRows) == 0 {
return nil
}
depOpts := opts
// Never rewrite an existing row here: the import's row write already
// happened in phase 1, and a concurrent update since then must win. With
// ConflictSkip the engine leaves the stored row untouched and still wires
// the batch's dependencies.
depOpts.ConflictSkip = true
// No row write can be stale-rejected under ConflictSkip; leaving the
// callback unset keeps a phase-2 signal from ever misreporting a row
// whose phase-1 write committed.
depOpts.OnStaleRejected = nil
depTotal := len(depRows)
depChunks := (depTotal + importChunkSize - 1) / importChunkSize
for start, chunk := 0, 1; start < depTotal; start, chunk = start+importChunkSize, chunk+1 {
end := min(start+importChunkSize, depTotal)
pacer.beforeTx()
if err := store.CreateIssuesWithFullOptions(ctx, depRows[start:end], actor, depOpts); err != nil {
return fmt.Errorf("import dependency pass chunk %d/%d failed (all %d issue rows are committed; re-run the import to resume — it converges): %w", chunk, depChunks, rowTotal, err)
}
fmt.Fprintf(importProgress, "bd import: deferred dependencies wired for %d/%d issues\n", end, depTotal)
}
return nil
}
// orderImportIssuesForChunking returns the issues reordered so that every valid
// readiness-affecting edge (blocks, parent-child, conditional-blocks, waits-for;
// the types GetReadyWork consults) points at a row in the same or an earlier
// chunk, which lets the import wire that edge in the same transaction as the
// row. It runs Kahn's algorithm over the intra-batch readiness edges, seeded in
// file order so unconstrained rows keep their relative order; duplicate IDs are
// chained in file order to preserve last-row-wins upsert semantics.
//
// A readiness cycle (invalid for blocking types; only ever present in the
// corrupted or legacy JSONL the import tolerates) cannot be fully ordered.
// Appending the stalled rows in plain file order — as an earlier version did —
// can place a valid dependent of a cycle before the cycle member it blocks on,
// deferring that live readiness edge and briefly exposing the dependent as ready
// without its blocker. Instead each stall is broken by emitting a row that
// genuinely lies on a cycle, so every readiness edge owned by a non-cycle row
// still rides inline; only a force-emitted cycle member may defer a readiness
// edge — its own unsatisfiable cycle edge, or a valid acyclic edge whose blocker
// it was emitted ahead of — and the engine skip-reports the unsatisfiable ones,
// still breaking the cycle. For a cycle of length
// >=3 the edge left to defer (and hence which member is left spuriously ready)
// can differ from the one the single-transaction import drops, which checks all
// cycle edges in file order against the already-persisted set; both break it.
func orderImportIssuesForChunking(issues []*types.Issue) []*types.Issue {
if len(issues) < 2 {
return issues
}
return buildImportOrderGraph(issues).topologicalFileOrder(issues)
}
// importOrderGraph is the intra-batch readiness-edge graph over import rows,
// indexed by position in the input slice. An edge target->dependent means the
// target (a readiness blocker, or an earlier duplicate of the same ID) must be
// emitted no later than the dependent.
type importOrderGraph struct {
dependents [][]int // dependents[t]: rows released when row t is emitted
blockers [][]int // blockers[u]: rows that must be emitted before row u
indegree []int
}
func buildImportOrderGraph(issues []*types.Issue) importOrderGraph {
n := len(issues)
indicesByID := indexImportIssuesByID(issues)
// A waits-for waiter's is_blocked state is gated on whether its spawner has
// an active parent-child child, not on the spawner row itself, so those
// child rows are readiness inputs to the waiter (see addRowReadinessEdges).
// Index them by spawner up front so the edge pass can order them.
childrenBySpawnerID := parentChildChildrenBySpawner(issues)
g := importOrderGraph{
dependents: make([][]int, n),
blockers: make([][]int, n),
indegree: make([]int, n),
}
for i, issue := range issues {
g.addRowReadinessEdges(i, issue, indicesByID, childrenBySpawnerID)
}
// Chain duplicate IDs in file order so the last row wins the upsert.
for _, indices := range indicesByID {
for k := 1; k < len(indices); k++ {
g.addEdge(indices[k-1], indices[k])
}
}
return g
}
// indexImportIssuesByID maps each import row's ID to its positions in the input
// slice. ID-less rows are skipped: their ID is assigned by the engine at insert,
// so nothing in the batch can reference them yet.
func indexImportIssuesByID(issues []*types.Issue) map[string][]int {
indicesByID := make(map[string][]int, len(issues))
for i, issue := range issues {
if issue.ID == "" {
continue
}
indicesByID[issue.ID] = append(indicesByID[issue.ID], i)
}
return indicesByID
}
// parentChildChildrenBySpawner maps each spawner ID to the positions of the
// in-batch rows that declare it as their parent-child parent. A parent-child
// dependency row is stored on the child (issue_id = child, depends_on = parent),
// so the child is the row carrying the edge.
func parentChildChildrenBySpawner(issues []*types.Issue) map[string][]int {
children := make(map[string][]int)
for i, issue := range issues {
for _, dep := range issue.Dependencies {
if dep != nil && dep.Type == types.DepParentChild && dep.DependsOnID != "" {
children[dep.DependsOnID] = append(children[dep.DependsOnID], i)
}
}
}
return children
}
// addEdge records that row target must be emitted no later than row dependent.
func (g importOrderGraph) addEdge(target, dependent int) {
g.dependents[target] = append(g.dependents[target], dependent)
g.blockers[dependent] = append(g.blockers[dependent], target)
g.indegree[dependent]++
}
// addEdgesBefore orders every target row no later than dependent, skipping any
// self-reference.
func (g importOrderGraph) addEdgesBefore(dependent int, targets []int) {
for _, target := range targets {
if target != dependent {
g.addEdge(target, dependent)
}
}
}
// addRowReadinessEdges records the intra-batch ordering edges that row i imposes:
// every readiness blocker it names must be emitted no later than i, and for a
// waits-for edge the spawner's in-batch parent-child children must be too.
//
// The waiter's is_blocked state keys on whether its spawner has an active child,
// not on the spawner row itself, and the per-chunk is_blocked recompute only
// re-evaluates the rows in its own transaction. So a waiter whose spawner's child
// lands in a later chunk would compute is_blocked=0 against a still-childless
// spawner and never be re-blocked — spuriously ready for the rest of the import
// and after it. Ordering the spawner inline is not enough; the child must be
// committed by the time the waiter's chunk recomputes.
func (g importOrderGraph) addRowReadinessEdges(i int, issue *types.Issue, indicesByID, childrenBySpawnerID map[string][]int) {
for _, dep := range issue.Dependencies {
if dep == nil || dep.DependsOnID == "" || !dep.Type.AffectsReadyWork() {
continue
}
g.addEdgesBefore(i, indicesByID[dep.DependsOnID])
if dep.Type == types.DepWaitsFor {
g.addEdgesBefore(i, childrenBySpawnerID[dep.DependsOnID])
}
}
}
// topologicalFileOrder emits rows in dependency order (Kahn's, file-order
// seeded), breaking each stall by force-emitting a row that lies on a readiness
// cycle, so every non-cycle row's readiness edges ride inline; only a
// force-emitted cycle member can leave a readiness edge (its unsatisfiable cycle
// edge, or a valid acyclic edge it was emitted ahead of) for the deferred
// dependency pass.
func (g importOrderGraph) topologicalFileOrder(issues []*types.Issue) []*types.Issue {
n := len(issues)
indegree := append([]int(nil), g.indegree...)
emitted := make([]bool, n)
queue := make([]int, 0, n)
for i := range n {
if indegree[i] == 0 {
queue = append(queue, i)
}
}
ordered := make([]*types.Issue, 0, n)
for len(ordered) < n {
if len(queue) == 0 {
queue = append(queue, g.nextCycleParticipant(emitted))
}
i := queue[0]
queue = queue[1:]
if emitted[i] {
continue
}
emitted[i] = true
ordered = append(ordered, issues[i])
queue = g.release(i, indegree, emitted, queue)
}
return ordered
}
// release decrements the indegree of every row that row i blocks and enqueues
// any that becomes free and has not already been emitted.
func (g importOrderGraph) release(i int, indegree []int, emitted []bool, queue []int) []int {
for _, j := range g.dependents[i] {
indegree[j]--
if indegree[j] == 0 && !emitted[j] {
queue = append(queue, j)
}
}
return queue
}
// nextCycleParticipant returns an un-emitted row that lies on a readiness cycle,
// used to break a Kahn stall.
func (g importOrderGraph) nextCycleParticipant(emitted []bool) int {
start := 0
for start < len(emitted) && emitted[start] {
start++
}
return g.cycleParticipant(start, emitted)
}
// cycleParticipant walks blocker edges from an un-emitted row until it revisits
// a row, which therefore lies on a cycle. At a stall every un-emitted row still
// has an un-emitted blocker, so the walk always closes a cycle.
func (g importOrderGraph) cycleParticipant(start int, emitted []bool) int {
seen := make(map[int]bool)
v := start
for !seen[v] {
seen[v] = true
next := -1
for _, b := range g.blockers[v] {
if !emitted[b] {
next = b
break
}
}
if next == -1 {
return v // defensive: no un-emitted blocker (unexpected at a stall)
}
v = next
}
return v
}
// importChangePlan reports how the import batch relates to existing local
// issues, so the import can surface what it changed instead of doing it
// silently (bd-hj85c).

File diff suppressed because it is too large Load diff

View file

@ -1377,24 +1377,18 @@ func TestEmbeddedInit(t *testing.T) {
})
t.Run("sql_backend_flags", func(t *testing.T) {
// SQLite is a supported pluggable backend now: init succeeds and records it.
_, beadsDir, _ := bdInit(t, bd, "--prefix", "sqlt", "--backend", "sqlite")
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("failed to load metadata.json: %v", err)
}
if cfg.Backend != configfile.BackendSQLite {
t.Errorf("backend: got %q, want %q", cfg.Backend, configfile.BackendSQLite)
// The SQLite backend was rolled back with the other alternative
// backends: init fails closed with its own rationale.
sqliteOut := bdInitFail(t, bd, "--backend", "sqlite")
if !strings.Contains(sqliteOut, "no longer supported") || !strings.Contains(sqliteOut, "single engine") {
t.Errorf("sqlite should report the backend rollback: %s", sqliteOut)
}
// Postgres is recognized, not an unknown backend: it fails only because the
// required connection config is absent (bdEnv strips any ambient DSN).
pgOut := bdInitFail(t, bd, "--backend", "postgres")
if strings.Contains(pgOut, "unknown backend") {
t.Errorf("postgres should be recognized, got unknown-backend error: %s", pgOut)
}
if !strings.Contains(pgOut, "--pg-url") {
t.Errorf("postgres init should request --pg-url, got: %s", pgOut)
for _, backend := range []string{"postgres", "mysql"} {
out := bdInitFail(t, bd, "--backend", backend)
if !strings.Contains(out, "no longer supported") {
t.Errorf("%s should report the backend rollback: %s", backend, out)
}
}
// A genuinely unsupported backend is still rejected.

430
cmd/bd/init_gateway_test.go Normal file
View file

@ -0,0 +1,430 @@
package main
import (
"context"
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// Gateway mode: a configured credential command resolves its token into the
// connection username, marks the config as targeting a gateway server, and
// disables local auto-start (the gateway is externally managed). This is what
// makes bd init connect as the token — never as "root" — and what makes the
// store skip the SHOW/CREATE DATABASE probe (openServerConnection keys that on
// cfg.Gateway). ServerMode is set because gateway init always targets a server.
func TestApplyInitGatewayCredentialAdoptsToken(t *testing.T) {
t.Setenv("BEADS_DOLT_CREDENTIAL_COMMAND", "printf tok-init")
doltCfg := &dolt.Config{ServerMode: true, AutoStart: true}
if err := applyInitGatewayCredential(context.Background(), t.TempDir(), doltCfg); err != nil {
t.Fatalf("applyInitGatewayCredential: %v", err)
}
if doltCfg.ServerUser != "tok-init" {
t.Fatalf("ServerUser = %q, want tok-init (never root)", doltCfg.ServerUser)
}
if !doltCfg.Gateway {
t.Fatal("Gateway must be true so the store skips SHOW/CREATE DATABASE")
}
if doltCfg.AutoStart {
t.Fatal("AutoStart must be disabled in gateway mode (server is externally managed)")
}
}
// Embedded init (no ServerMode) must never run the credential command, even when
// BEADS_DOLT_CREDENTIAL_COMMAND is ambient on the host. This is the FIX-1
// regression guard: the canonical open path gates the command on server mode
// ("a command exported in the environment must not run (or fail) an embedded
// open"), so init must too. The command here (`false`) would error if it ran;
// the helper returning nil with the config untouched proves it did not.
func TestApplyInitGatewayCredentialSkipsEmbeddedMode(t *testing.T) {
t.Setenv("BEADS_DOLT_CREDENTIAL_COMMAND", "false")
doltCfg := &dolt.Config{AutoStart: true} // ServerMode defaults to false
if err := applyInitGatewayCredential(context.Background(), t.TempDir(), doltCfg); err != nil {
t.Fatalf("embedded init must not run the credential command: %v", err)
}
if doltCfg.Gateway || doltCfg.ServerUser != "" || !doltCfg.AutoStart {
t.Fatalf("embedded config must be left untouched: %+v", doltCfg)
}
}
// Server mode, but no command configured: a strict no-op. The hand-built config is
// left exactly as the caller built it.
func TestApplyInitGatewayCredentialNoopWithoutCommand(t *testing.T) {
t.Setenv("BEADS_DOLT_CREDENTIAL_COMMAND", "")
doltCfg := &dolt.Config{ServerMode: true, AutoStart: true}
if err := applyInitGatewayCredential(context.Background(), t.TempDir(), doltCfg); err != nil {
t.Fatalf("applyInitGatewayCredential: %v", err)
}
if doltCfg.ServerUser != "" || doltCfg.Gateway || !doltCfg.AutoStart {
t.Fatalf("config must be untouched without a command: %+v", doltCfg)
}
}
// Fail-closed: in server mode a configured-but-failing command aborts init and
// never leaves a fallback (root) user behind.
func TestApplyInitGatewayCredentialFailsClosed(t *testing.T) {
t.Setenv("BEADS_DOLT_CREDENTIAL_COMMAND", "false")
doltCfg := &dolt.Config{ServerMode: true, AutoStart: true}
err := applyInitGatewayCredential(context.Background(), t.TempDir(), doltCfg)
if err == nil {
t.Fatal("expected an error when the credential command fails")
}
if doltCfg.ServerUser != "" || doltCfg.Gateway {
t.Fatalf("config must be untouched on failure: %+v", doltCfg)
}
}
// A caller/flag-preset --server-user wins over the credential command (the
// command is not run). Mirrors ApplyGatewayCredential's preset short-circuit.
func TestApplyInitGatewayCredentialPresetWins(t *testing.T) {
t.Setenv("BEADS_DOLT_CREDENTIAL_COMMAND", "false")
doltCfg := &dolt.Config{ServerMode: true, ServerUser: "preset", AutoStart: true}
if err := applyInitGatewayCredential(context.Background(), t.TempDir(), doltCfg); err != nil {
t.Fatalf("preset should short-circuit before running the command: %v", err)
}
if doltCfg.ServerUser != "preset" || doltCfg.Gateway || !doltCfg.AutoStart {
t.Fatalf("preset user must be preserved untouched: %+v", doltCfg)
}
}
// issue_prefix resolution.
// Gateway with no server-provisioned issue_prefix is a provisioning-contract
// violation: bd refuses to choose one for a hosted database.
func TestResolveInitIssuePrefixGatewayMissing(t *testing.T) {
value, write, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", nil)
if err == nil {
t.Fatal("expected a provisioning-contract error for a hosted db with no issue_prefix")
}
if !strings.Contains(err.Error(), "provisioning-contract violation") ||
!strings.Contains(err.Error(), "myhosteddb") {
t.Fatalf("error should name the db and the contract violation, got: %v", err)
}
if write || value != "" {
t.Fatalf("nothing must be written on violation: value=%q write=%v", value, write)
}
}
// FIX 3: a transient read error in gateway mode is surfaced as that error, NOT as
// a false provisioning-contract violation — the prefix may well be provisioned; we
// simply failed to read it.
func TestResolveInitIssuePrefixGatewayReadError(t *testing.T) {
readErr := errors.New("dial tcp: connection refused")
value, write, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", readErr)
if err == nil {
t.Fatal("expected the read error to be surfaced")
}
if !errors.Is(err, readErr) {
t.Fatalf("returned error must wrap the read error, got: %v", err)
}
if strings.Contains(err.Error(), "provisioning-contract violation") {
t.Fatalf("a transient read error must not be reported as a contract violation, got: %v", err)
}
if write || value != "" {
t.Fatalf("nothing must be written on a read error: value=%q write=%v", value, write)
}
}
// Gateway with an already-provisioned issue_prefix: adopt it (no write).
func TestResolveInitIssuePrefixGatewayAdopts(t *testing.T) {
value, write, err := resolveInitIssuePrefix(true, "hq", "myhosteddb", "fallback", nil)
if err != nil {
t.Fatalf("adoption must not error: %v", err)
}
if write || value != "" {
t.Fatalf("adoption must not write: value=%q write=%v", value, write)
}
}
// Non-gateway with no existing prefix: set the sanitized prefix (dots -> underscores).
// This is the byte-identical legacy behavior — and a read error is ignored here,
// exactly as legacy init ignored it (the guard is gateway-only).
func TestResolveInitIssuePrefixNonGatewaySets(t *testing.T) {
value, write, err := resolveInitIssuePrefix(false, "", "mydb", "GPUPolynomials.jl", errors.New("ignored"))
if err != nil {
t.Fatalf("non-gateway set must not error even with a read error: %v", err)
}
if !write || value != "GPUPolynomials_jl" {
t.Fatalf("value=%q write=%v, want (GPUPolynomials_jl, true)", value, write)
}
}
// Non-gateway with an existing prefix: no-op (do not clobber a shared db).
func TestResolveInitIssuePrefixNonGatewayExisting(t *testing.T) {
value, write, err := resolveInitIssuePrefix(false, "existing", "mydb", "prefix", nil)
if err != nil {
t.Fatalf("non-gateway existing must not error: %v", err)
}
if write || value != "" {
t.Fatalf("existing prefix must be preserved: value=%q write=%v", value, write)
}
}
// project identity resolution.
// Gateway with no server-provisioned _project_id is a provisioning-contract
// violation: bd will not mint an identity for a hosted database.
func TestResolveInitProjectIDGatewayMissing(t *testing.T) {
value, _, err := resolveInitProjectID(true, "", "", "myhosteddb", nil)
if err == nil {
t.Fatal("expected a provisioning-contract error for a hosted db with no _project_id")
}
if !strings.Contains(err.Error(), "provisioning-contract violation") ||
!strings.Contains(err.Error(), "_project_id") ||
!strings.Contains(err.Error(), "myhosteddb") {
t.Fatalf("error should name the db, _project_id, and the contract, got: %v", err)
}
if value != "" {
t.Fatalf("no identity must be produced: %q", value)
}
}
// FIX 3: a transient read error in gateway mode is surfaced as that error, NOT as
// a false provisioning-contract violation.
func TestResolveInitProjectIDGatewayReadError(t *testing.T) {
readErr := errors.New("i/o timeout")
value, _, err := resolveInitProjectID(true, "", "", "myhosteddb", readErr)
if err == nil {
t.Fatal("expected the read error to be surfaced")
}
if !errors.Is(err, readErr) {
t.Fatalf("returned error must wrap the read error, got: %v", err)
}
if strings.Contains(err.Error(), "provisioning-contract violation") {
t.Fatalf("a transient read error must not be reported as a contract violation, got: %v", err)
}
if value != "" {
t.Fatalf("no identity must be produced on a read error: %q", value)
}
}
// Gateway with a server-provisioned _project_id and no local id yet: adopt it
// verbatim and report the change (fresh adoption).
func TestResolveInitProjectIDGatewayAdopts(t *testing.T) {
value, changed, err := resolveInitProjectID(true, "", "proj-xyz", "myhosteddb", nil)
if err != nil {
t.Fatalf("adoption must not error: %v", err)
}
if value != "proj-xyz" {
t.Fatalf("value = %q, want adopted proj-xyz", value)
}
if !changed {
t.Fatal("adopting a server id over an empty local id must report changed")
}
}
// The regression this PR revision fixes: gateway re-init with a local
// metadata.json that already carries a project_id. The hosted server is
// authoritative, so a server _project_id that differs from the stale local id is
// adopted (and reported changed), not silently kept — otherwise init opens with
// CreateIfMissing (skipping the identity verifier), saves the stale id as
// success, and every later normal open hard-fails PROJECT IDENTITY MISMATCH.
func TestResolveInitProjectIDGatewayReconcilesStaleLocal(t *testing.T) {
value, changed, err := resolveInitProjectID(true, "stale-local", "server-authoritative", "myhosteddb", nil)
if err != nil {
t.Fatalf("reconciliation must not error: %v", err)
}
if value != "server-authoritative" {
t.Fatalf("value = %q, want the server-authoritative id adopted over the stale local one", value)
}
if !changed {
t.Fatal("a differing server id must report changed so the caller surfaces the reconcile")
}
}
// Gateway re-init where the local id already matches the server: adopt it but
// report no change, so no false "reconciled" message is printed.
func TestResolveInitProjectIDGatewayLocalMatchesServer(t *testing.T) {
value, changed, err := resolveInitProjectID(true, "proj-x", "proj-x", "myhosteddb", nil)
if err != nil {
t.Fatalf("matching identity must not error: %v", err)
}
if value != "proj-x" || changed {
t.Fatalf("value=%q changed=%v, want (proj-x, false)", value, changed)
}
}
// A stale local id must not mask a missing server identity in gateway mode: the
// provisioning-contract violation still fires even when localID is set, so init
// fails loudly instead of persisting an id the hosted database does not have.
func TestResolveInitProjectIDGatewayMissingWithLocalSet(t *testing.T) {
value, changed, err := resolveInitProjectID(true, "stale-local", "", "myhosteddb", nil)
if err == nil {
t.Fatal("expected a provisioning-contract error even with a local id set")
}
if !strings.Contains(err.Error(), "provisioning-contract violation") {
t.Fatalf("error should name the contract violation, got: %v", err)
}
if value != "" || changed {
t.Fatalf("no identity must be produced on violation: value=%q changed=%v", value, changed)
}
}
// Non-gateway with no adopted id: generate a fresh identity (legacy behavior).
// A read error is ignored here, exactly as legacy init ignored it.
func TestResolveInitProjectIDNonGatewayGenerates(t *testing.T) {
value, _, err := resolveInitProjectID(false, "", "", "mydb", errors.New("ignored"))
if err != nil {
t.Fatalf("non-gateway generation must not error even with a read error: %v", err)
}
if value == "" {
t.Fatal("non-gateway must generate a non-empty project id")
}
}
// Non-gateway with no local id and an adopted id (existing shared/bootstrapped
// db): use it and report the change.
func TestResolveInitProjectIDNonGatewayAdopts(t *testing.T) {
value, changed, err := resolveInitProjectID(false, "", "adopted-id", "mydb", nil)
if err != nil {
t.Fatalf("non-gateway adoption must not error: %v", err)
}
if value != "adopted-id" {
t.Fatalf("value = %q, want adopted-id", value)
}
if !changed {
t.Fatal("adopting over an empty local id must report changed")
}
}
// Non-gateway keeps the legacy guard: an existing local id is never clobbered,
// even if a database id was somehow read — local wins and reports no change.
func TestResolveInitProjectIDNonGatewayKeepsLocal(t *testing.T) {
value, changed, err := resolveInitProjectID(false, "local-id", "db-id", "mydb", nil)
if err != nil {
t.Fatalf("non-gateway keep must not error: %v", err)
}
if value != "local-id" || changed {
t.Fatalf("value=%q changed=%v, want (local-id, false)", value, changed)
}
}
// shouldConsultInitProjectID decides when init reads _project_id from the db.
// Gateway always consults (the fix: it must reconcile even when a local id is
// already set — a re-init or preseeded workspace). Non-gateway only consults to
// adopt from a pre-existing shared/bootstrapped database when no local id exists.
func TestShouldConsultInitProjectID(t *testing.T) {
tests := []struct {
name string
gateway bool
localID string
database string
bootstrappedFromRemote bool
want bool
}{
{"gateway fresh, no local id", true, "", "", false, true},
{"gateway re-init with local id", true, "local", "", false, true},
{"gateway preseeded + database", true, "local", "hosteddb", false, true},
{"non-gateway fresh local-only", false, "", "", false, false},
{"non-gateway --database, no local id", false, "", "mydb", false, true},
{"non-gateway bootstrapped, no local id", false, "", "", true, true},
{"non-gateway --database but local id set", false, "local", "mydb", false, false},
{"non-gateway bootstrapped but local id set", false, "local", "", true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldConsultInitProjectID(tt.gateway, tt.localID, tt.database, tt.bootstrappedFromRemote)
if got != tt.want {
t.Fatalf("shouldConsultInitProjectID(%v, %q, %q, %v) = %v, want %v",
tt.gateway, tt.localID, tt.database, tt.bootstrappedFromRemote, got, tt.want)
}
})
}
}
// The project identity is server-authoritative in gateway mode: bd must not
// write _project_id back to the (possibly read-only) hosted database. Non-gateway
// keeps writing it for cross-project verification.
func TestShouldWriteProjectIDLocally(t *testing.T) {
if shouldWriteProjectIDLocally(true, "proj-xyz") {
t.Fatal("gateway mode must not write _project_id back (server-authoritative)")
}
if !shouldWriteProjectIDLocally(false, "proj-xyz") {
t.Fatal("non-gateway must write _project_id for cross-project verification")
}
if shouldWriteProjectIDLocally(false, "") {
t.Fatal("no id means nothing to write")
}
}
// FIX 2: gateway init must not write clone-local tracking state (bd_version,
// repo_id, clone_id, last_import_time) or issue the initial-state DOLT_COMMIT into
// the shared, server-owned database. Non-gateway keeps doing all of it —
// byte-identical legacy behavior.
func TestShouldWriteInitStateToDB(t *testing.T) {
if shouldWriteInitStateToDB(true) {
t.Fatal("gateway mode must not write tracking metadata or commit initial state to the shared db")
}
if !shouldWriteInitStateToDB(false) {
t.Fatal("non-gateway init must write tracking metadata and commit initial state (byte-identical)")
}
}
// Gateway init must not manage the local shared server or provision beads_global.
// Shared-server mode forces server mode on, which is exactly what makes the gateway
// credential path run, so BEADS_DOLT_SHARED_SERVER and BEADS_DOLT_CREDENTIAL_COMMAND
// can be active together. When they are, the gateway wins: init skips starting a
// local shared server, EnsureGlobalDatabase, and initGlobalDatabaseConfig — which
// otherwise rebuilds its dolt.Config without the Gateway flag and would drive
// create/schema/write operations against the authenticating gateway. Non-gateway
// shared-server behavior (flag or env) is unchanged.
func TestShouldInitSharedGlobalDB(t *testing.T) {
tests := []struct {
name string
sharedServer bool
sharedServerMode bool
gateway bool
want bool
}{
{"shared flag, no gateway", true, false, false, true},
{"shared env mode, no gateway", false, true, false, true},
{"shared flag + gateway skips (credential+shared-server)", true, false, true, false},
{"shared env mode + gateway skips", false, true, true, false},
{"neither shared nor gateway", false, false, false, false},
{"gateway only, not shared", false, false, true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := shouldInitSharedGlobalDB(tt.sharedServer, tt.sharedServerMode, tt.gateway); got != tt.want {
t.Fatalf("shouldInitSharedGlobalDB(%v, %v, %v) = %v, want %v",
tt.sharedServer, tt.sharedServerMode, tt.gateway, got, tt.want)
}
})
}
}
// Gateway init must not write the Dolt "origin" remote (AddRemote =
// DOLT_REMOTE('add', ...)) against the server-owned database, even when a git
// origin would normally wire one. Non-gateway remote-wiring is unchanged and
// still honored (byte-identical to shouldConfigureInitDoltRemote).
func TestShouldWriteInitDoltRemote(t *testing.T) {
const gitOrigin = "https://example.com/repo.git"
tests := []struct {
name string
gateway bool
syncURL string
syncFromRemote bool
syncURLFromConfig bool
syncURLFromGitOrigin bool
localOnly bool
want bool
}{
{"gateway + git origin suppresses the write", true, gitOrigin, false, false, true, false, false},
{"gateway + explicit sync remote suppresses the write", true, gitOrigin, true, false, false, false, false},
{"non-gateway + git origin writes", false, gitOrigin, false, false, true, false, true},
{"non-gateway + explicit sync remote writes", false, gitOrigin, true, false, false, false, true},
{"non-gateway local-only does not write", false, gitOrigin, false, false, true, true, false},
{"non-gateway no remote does not write", false, "", false, false, false, false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldWriteInitDoltRemote(tt.gateway, tt.syncURL, tt.syncFromRemote, tt.syncURLFromConfig, tt.syncURLFromGitOrigin, tt.localOnly)
if got != tt.want {
t.Fatalf("shouldWriteInitDoltRemote(%v, %q, %v, %v, %v, %v) = %v, want %v",
tt.gateway, tt.syncURL, tt.syncFromRemote, tt.syncURLFromConfig, tt.syncURLFromGitOrigin, tt.localOnly, got, tt.want)
}
})
}
}

View file

@ -583,37 +583,6 @@ func TestMetricsRootVersionFlagSuppressesFirstRunNotice(t *testing.T) {
}
}
// TestInitProxiedServerRejectedNotYetImplemented asserts `bd init
// --proxied-server` is rejected as "not yet implemented", keeping
// proxied-server mode gated off so usesProxiedServer() is never true.
func TestInitProxiedServerRejectedNotYetImplemented(t *testing.T) {
bd := buildEmbeddedBD(t)
home, err := testTempDir("bd-proxied-gate-home-*")
if err != nil {
t.Fatalf("temp home: %v", err)
}
repo, err := testTempDir("bd-proxied-gate-repo-*")
if err != nil {
t.Fatalf("temp repo: %v", err)
}
initGitRepoAt(t, repo)
cmd := exec.Command(bd, "init", "--non-interactive", "--quiet", "--proxied-server")
cmd.Dir = repo
cmd.Env = metricsTestEnv(home)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
runErr := cmd.Run()
if runErr == nil {
t.Fatalf("bd init --proxied-server unexpectedly succeeded; proxied-server mode must stay gated off\nstdout:\n%s", stdout.String())
}
if !strings.Contains(stderr.String(), "not yet implemented") {
t.Errorf("bd init --proxied-server stderr = %q, want it to contain %q", stderr.String(), "not yet implemented")
}
}
// metrics off must not queue a usage event, honoring the "No usage data will be
// collected or sent" promise even though metrics are still enabled for the
// off invocation itself.

View file

@ -152,6 +152,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
if err != nil {
return fmt.Errorf("failed to open uow provider: %v", err)
}
defer func() { _ = initUOWProvider.Close(ctx) }()
remoteURL := resolveProxiedInitRemoteURL(ctx, gitUC, in)

View file

@ -2369,10 +2369,9 @@ func initBackendTestEnv(beadsDir string) []string {
func TestInitBackendFlag(t *testing.T) {
bd := buildBDForInitTests(t)
// SQLite is a supported pluggable backend now (it was removed under the
// one-backend assumption in #3151 and re-added as a leaf backend): init
// succeeds and metadata.json records backend=sqlite.
t.Run("sqlite_initializes_and_persists_backend", func(t *testing.T) {
// The SQLite backend was rolled back with the other alternative backends:
// init fails closed with migration guidance and writes no workspace state.
t.Run("sqlite_is_no_longer_supported", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
@ -2380,45 +2379,41 @@ func TestInitBackendFlag(t *testing.T) {
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --backend=sqlite should succeed: %v\n%s", err, out)
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found after --backend=sqlite init")
}
if cfg.Backend != configfile.BackendSQLite {
t.Errorf("Expected backend %q, got %q", configfile.BackendSQLite, cfg.Backend)
}
})
// Postgres is a recognized backend now: it must not be rejected as unknown,
// and it fails only because the required connection config is absent.
t.Run("postgres_is_recognized_and_requires_config", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", "postgres", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected non-zero exit for --backend=postgres without connection config")
t.Fatalf("Expected non-zero exit for --backend=sqlite:\n%s", out)
}
outStr := string(out)
if strings.Contains(outStr, "unknown backend") {
t.Errorf("postgres must be a recognized backend, not reported unknown: %s", outStr)
if !strings.Contains(outStr, "no longer supported") || !strings.Contains(outStr, "single engine") {
t.Errorf("Expected rollback guidance for sqlite, got: %s", outStr)
}
if !strings.Contains(outStr, "--pg-url") {
t.Errorf("Expected missing --pg-url guidance for postgres, got: %s", outStr)
if _, statErr := os.Stat(beadsDir); !os.IsNotExist(statErr) {
t.Fatalf("rejected sqlite init created workspace state (stat error: %v)", statErr)
}
})
for _, backend := range []string{"postgres", "mysql"} {
t.Run(backend+"_is_no_longer_supported", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", backend, "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("Expected non-zero exit for --backend=%s", backend)
}
outStr := string(out)
if !strings.Contains(outStr, "no longer supported") {
t.Errorf("Expected rollback guidance for %s, got: %s", backend, outStr)
}
if !strings.Contains(outStr, `"dolt"`) {
t.Errorf("Expected supported backend guidance for %s, got: %s", backend, outStr)
}
})
}
// A genuinely unsupported backend value is still rejected up front.
t.Run("unknown_backend_errors", func(t *testing.T) {
tmpDir := t.TempDir()

View file

@ -51,12 +51,14 @@ func bdProxiedLabelListJSON(t *testing.T, bd, dir, issueID string) []string {
}
func TestProxiedServerLabel(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("add_list_remove", func(t *testing.T) {
p := bdProxiedInit(t, bd, "la")
t.Parallel()
p := newSharedProxiedProject(t, bd, "la")
issue := bdProxiedCreate(t, bd, p.dir, "Label target")
out := bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "alpha,beta")
@ -82,7 +84,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("add_multiple_issues", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lm")
a := bdProxiedCreate(t, bd, p.dir, "Issue A")
b := bdProxiedCreate(t, bd, p.dir, "Issue B")
@ -97,7 +100,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("list_empty", func(t *testing.T) {
p := bdProxiedInit(t, bd, "le")
t.Parallel()
p := newSharedProxiedProject(t, bd, "le")
issue := bdProxiedCreate(t, bd, p.dir, "No labels")
out := bdProxiedLabel(t, bd, p.dir, "list", issue.ID)
if !strings.Contains(out, "no labels") {
@ -106,7 +110,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("list_all", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ll")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ll")
a := bdProxiedCreate(t, bd, p.dir, "A")
b := bdProxiedCreate(t, bd, p.dir, "B")
bdProxiedLabel(t, bd, p.dir, "add", a.ID, "common")
@ -141,7 +146,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("propagate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lp")
parent := bdProxiedCreate(t, bd, p.dir, "Parent epic", "--type", "epic")
c1 := bdProxiedCreate(t, bd, p.dir, "Child 1", "--parent", parent.ID)
c2 := bdProxiedCreate(t, bd, p.dir, "Child 2", "--parent", parent.ID)
@ -159,7 +165,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("propagate_no_children", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pn")
lonely := bdProxiedCreate(t, bd, p.dir, "Lonely")
out := bdProxiedLabel(t, bd, p.dir, "propagate", lonely.ID, "nope")
if !strings.Contains(out, "No children found") {
@ -168,7 +175,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("add_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "aj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "aj")
issue := bdProxiedCreate(t, bd, p.dir, "Add JSON")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "label", "add", issue.ID, "j1,j2", "--json")
@ -198,7 +206,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("remove_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rj")
issue := bdProxiedCreate(t, bd, p.dir, "Remove JSON")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "rmj")
@ -223,7 +232,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("add_duplicate_idempotent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "di")
t.Parallel()
p := newSharedProxiedProject(t, bd, "di")
issue := bdProxiedCreate(t, bd, p.dir, "Dup label")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "dup")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "dup")
@ -234,7 +244,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("remove_comma_separated_multi", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rm")
issue := bdProxiedCreate(t, bd, p.dir, "Multi remove")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "rm-a,rm-b,rm-keep")
@ -245,7 +256,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("remove_batch", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rb")
a := bdProxiedCreate(t, bd, p.dir, "Batch rm A")
b := bdProxiedCreate(t, bd, p.dir, "Batch rm B")
bdProxiedLabel(t, bd, p.dir, "add", a.ID, b.ID, "batch-rm")
@ -259,7 +271,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("list_text", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lx")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lx")
issue := bdProxiedCreate(t, bd, p.dir, "Text list")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "alpha,beta")
@ -270,7 +283,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("propagate_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pj")
parent := bdProxiedCreate(t, bd, p.dir, "JSON propagate", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "JSON prop child", "--parent", parent.ID)
@ -296,7 +310,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("add_empty_label_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "el")
t.Parallel()
p := newSharedProxiedProject(t, bd, "el")
issue := bdProxiedCreate(t, bd, p.dir, "Empty label")
out := bdProxiedLabelFail(t, bd, p.dir, "add", issue.ID, "")
if !strings.Contains(out, "empty") {
@ -305,7 +320,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("provides_label_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pv")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pv")
issue := bdProxiedCreate(t, bd, p.dir, "Provides guard")
out := bdProxiedLabelFail(t, bd, p.dir, "add", issue.ID, "provides:foo")
if !strings.Contains(out, "provides:") {
@ -314,7 +330,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("provides_in_comma_list_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pc")
issue := bdProxiedCreate(t, bd, p.dir, "Provides in list")
out := bdProxiedLabelFail(t, bd, p.dir, "add", issue.ID, "ok-label,provides:auth")
if !strings.Contains(out, "provides:") {
@ -326,7 +343,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("wisp_label_routes_to_wisp_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lw")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp target", "--ephemeral")
bdProxiedLabel(t, bd, p.dir, "add", wisp.ID, "wlabel")
@ -354,7 +372,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("wisp_label_remove_routes_to_wisp_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "wr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "wr")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp remove target", "--ephemeral")
bdProxiedLabel(t, bd, p.dir, "add", wisp.ID, "keep,drop")
@ -376,7 +395,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("list_all_includes_wisp_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "law")
t.Parallel()
p := newSharedProxiedProject(t, bd, "law")
perm := bdProxiedCreate(t, bd, p.dir, "Perm issue")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp issue", "--ephemeral")
bdProxiedLabel(t, bd, p.dir, "add", perm.ID, "shared")
@ -411,7 +431,8 @@ func TestProxiedServerLabel(t *testing.T) {
})
t.Run("propagate_to_wisp_children", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pw")
parent := bdProxiedCreate(t, bd, p.dir, "Wisp parent", "--ephemeral", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Wisp child", "--ephemeral", "--parent", parent.ID)

View file

@ -14,9 +14,10 @@ import (
)
func TestProxiedServerList(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "lst")
p := newSharedProxiedProject(t, bd, "lst")
seed := seedProxiedListData(t, bd, p)
// --- A. Basic filtering ---
@ -499,7 +500,7 @@ func TestProxiedServerList(t *testing.T) {
t.Run("empty_database", func(t *testing.T) {
// Fresh proxied project with no seeded issues.
empty := bdProxiedInit(t, bd, "lst-empty")
empty := newSharedProxiedProject(t, bd, "lst-empty")
issues := bdProxiedListJSON(t, bd, empty)
if len(issues) != 0 {
t.Errorf("expected 0 issues in empty proxied database, got %d", len(issues))
@ -732,7 +733,7 @@ func TestProxiedServerList(t *testing.T) {
t.Run("concurrent_create_and_list", func(t *testing.T) {
// Isolated project: race test creates 20 issues; keep them out of
// the shared fixture so subsequent runs aren't polluted.
race := bdProxiedInit(t, bd, "lst-race")
race := newSharedProxiedProject(t, bd, "lst-race")
const (
workers = 4

View file

@ -33,11 +33,7 @@ import (
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
mysqlstore "github.com/steveyegge/beads/internal/storage/mysql"
"github.com/steveyegge/beads/internal/storage/pgdialect"
pgstore "github.com/steveyegge/beads/internal/storage/postgres"
"github.com/steveyegge/beads/internal/storage/schema"
sqlitestore "github.com/steveyegge/beads/internal/storage/sqlite"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/telemetry"
"github.com/steveyegge/beads/internal/ui"
@ -992,9 +988,13 @@ var rootCmd = &cobra.Command{
if dbPath == "" {
if bd := beads.FindBeadsDir(); bd != "" {
if cfg, _ := configfile.Load(bd); cfg != nil && (cfg.IsDoltProxiedServerMode() || cfg.GetBackend() == configfile.BackendPostgres || cfg.GetBackend() == configfile.BackendMySQL || cfg.GetBackend() == configfile.BackendSQLite) {
// A non-Dolt SQL (or proxied-server) workspace has no local Dolt
// database file; the .beads dir with metadata.json IS the workspace.
cfg, cfgErr := configfile.Load(bd)
if cfgErr != nil || cfg != nil && (cfg.IsDoltProxiedServerMode() || !configfile.IsSupportedBackend(cfg.Backend)) {
// Proxied-server and removed-backend workspaces may have no
// local Dolt database file. Invalid or unknown metadata likewise must
// reach config validation instead of becoming a generic "no database"
// result. metadata.json identifies the workspace so store selection can
// route or reject it explicitly.
dbPath = bd
}
}
@ -1076,6 +1076,18 @@ var rootCmd = &cobra.Command{
return HandleError("%v", err)
}
// Resolve the backend before version tracking, migration, server startup, or
// any store construction. PostgreSQL/MySQL values are retained as metadata
// tombstones so an existing workspace fails closed instead of falling through
// to a new, empty Dolt database.
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr)
}
if backendErr := validateConfiguredBackend(cfg); backendErr != nil {
return HandleError("%v", backendErr)
}
// Set actor for audit trail
actor = getActorWithGit()
// Attach actor to the command span now that we have it.
@ -1134,10 +1146,6 @@ var rootCmd = &cobra.Command{
// result set and exit 0 (false-empty), which readers misinterpret as
// "no work". Absent metadata.json (cfg == nil, cfgErr == nil) keeps
// the fresh-repo embedded default below.
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr)
}
if cfg != nil {
warnSharedServerEmbeddedMismatch(cfg)
doltCfg.ProxiedServer = cfg.IsDoltProxiedServerMode()
@ -1179,9 +1187,7 @@ var rootCmd = &cobra.Command{
// command must not run (or fail) embedded opens even when the env var is set.
// Dolt-only: the gateway credential command mints a Dolt server
// username. IsSharedServerMode() forces ServerMode true with no backend
// guard, so without this check a shared-server config in config.yaml
// would run (and fail closed) the command for postgres/mysql/sqlite
// workspaces, which never present a server username.
// guard, so non-Dolt metadata must not try to resolve a server username.
if doltCfg.ServerMode && cfg.GetBackend() == configfile.BackendDolt {
if _, credErr := dolt.ApplyGatewayCredential(rootCtx, cfg, doltCfg); credErr != nil {
return HandleError("resolving dolt credential command: %v", credErr)
@ -1275,19 +1281,7 @@ var rootCmd = &cobra.Command{
// Removing them WILL cause unrecoverable data corruption and data loss.
// Dolt manages these files itself; external interference is never safe.
if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres {
// Postgres backend: open via the SQL-family bundle, bypassing the
// Dolt open path (the doltCfg above is built but unused here).
store, err = pgstore.NewFromConfig(rootCtx, beadsDir)
} else if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL {
// MySQL backend: same SQL-family bundle, isolation by database.
store, err = mysqlstore.NewFromConfig(rootCtx, beadsDir)
} else if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite {
// SQLite backend: pure-Go file-based SQL-family bundle.
store, err = sqlitestore.NewFromConfig(rootCtx, beadsDir)
} else {
store, err = newDoltStore(rootCtx, doltCfg)
}
store, err = newDoltStore(rootCtx, doltCfg)
// Track final read-only state for staleness checks (GH#1089)
storeIsReadOnly = doltCfg.ReadOnly
@ -1394,72 +1388,60 @@ var rootCmd = &cobra.Command{
uowProvider = nil
}
} else {
// Slice 5c: a NonCommitGraphBackend (Postgres, SQLite, ...) has no Dolt
// commit graph, so skip the Dolt-only maintenance tail. UnwrapStore reaches
// the concrete store past the HookFiringStore decorator; a store WITHOUT the
// marker (every Dolt variant) leaves skipMaintenance false and runs the tail
// unchanged. store.Close below stays unconditional.
skipMaintenance := false
if ncg, ok := storage.UnwrapStore(store).(storage.NonCommitGraphBackend); ok && ncg.CommitGraphUnsupported() {
skipMaintenance = true
// Dolt auto-commit: after a successful write command (and after final flush),
// create a Dolt commit so changes don't remain only in the working set.
if commandDidWrite.Load() && !commandDidExplicitDoltCommit {
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil {
return HandleError("dolt auto-commit failed: %v", err)
}
}
if !skipMaintenance {
// Dolt auto-commit: after a successful write command (and after final flush),
// create a Dolt commit so changes don't remain only in the working set.
if commandDidWrite.Load() && !commandDidExplicitDoltCommit {
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil {
return HandleError("dolt auto-commit failed: %v", err)
}
}
// Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the
// tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands.
if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 {
// Only applies when dolt auto-commit is enabled and backend is versioned (Dolt).
if mode, err := getDoltAutoCommitMode(); err != nil {
return HandleError("dolt tip auto-commit failed: %v", err)
} else if mode == doltAutoCommitOn {
// Apply tip metadata writes now (deferred in recordTipShown for Dolt).
for tipID := range commandTipIDsShown {
key := fmt.Sprintf("tip_%s_last_shown", tipID)
value := time.Now().Format(time.RFC3339)
if err := store.SetLocalMetadata(rootCtx, key, value); err != nil {
return HandleError("dolt tip auto-commit failed: %v", err)
}
}
ids := make([]string, 0, len(commandTipIDsShown))
for tipID := range commandTipIDsShown {
ids = append(ids, tipID)
}
msg := formatDoltAutoCommitMessage("tip", getActor(), ids)
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil {
// Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the
// tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands.
if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 {
// Only applies when dolt auto-commit is enabled and backend is versioned (Dolt).
if mode, err := getDoltAutoCommitMode(); err != nil {
return HandleError("dolt tip auto-commit failed: %v", err)
} else if mode == doltAutoCommitOn {
// Apply tip metadata writes now (deferred in recordTipShown for Dolt).
for tipID := range commandTipIDsShown {
key := fmt.Sprintf("tip_%s_last_shown", tipID)
value := time.Now().Format(time.RFC3339)
if err := store.SetLocalMetadata(rootCtx, key, value); err != nil {
return HandleError("dolt tip auto-commit failed: %v", err)
}
}
}
// Auto-backup: sync a Dolt-native backup if enabled and due
maybeAutoBackup(rootCtx)
// Auto-export: write git-tracked JSONL for portability if enabled and due.
// Read-only commands must not perform post-run maintenance writes or emit
// sync guidance after machine-readable output.
if shouldRunPostCommandAutoExport(cmd) {
if err := maybeAutoExport(rootCtx, commandAllowsEmptyAutoExport(cmd)); err != nil {
return HandleError("%v", err)
ids := make([]string, 0, len(commandTipIDsShown))
for tipID := range commandTipIDsShown {
ids = append(ids, tipID)
}
msg := formatDoltAutoCommitMessage("tip", getActor(), ids)
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil {
return HandleError("dolt tip auto-commit failed: %v", err)
}
}
}
// Auto-push: push to Dolt remote if enabled and due.
// Skip for read-only commands to avoid unnecessary network operations
// and metadata writes on commands like bd list/show/ready (GH#2191).
if !isReadOnlyCommand(cmd.Name()) {
maybeAutoPush(rootCtx)
// Auto-backup: sync a Dolt-native backup if enabled and due
maybeAutoBackup(rootCtx)
// Auto-export: write git-tracked JSONL for portability if enabled and due.
// Read-only commands must not perform post-run maintenance writes or emit
// sync guidance after machine-readable output.
if shouldRunPostCommandAutoExport(cmd) {
if err := maybeAutoExport(rootCtx, commandAllowsEmptyAutoExport(cmd)); err != nil {
return HandleError("%v", err)
}
}
// Auto-push: push to Dolt remote if enabled and due.
// Skip for read-only commands to avoid unnecessary network operations
// and metadata writes on commands like bd list/show/ready (GH#2191).
if !isReadOnlyCommand(cmd.Name()) {
maybeAutoPush(rootCtx)
}
// Signal that store is closing (prevents background flush from accessing closed store)
storeMutex.Lock()
storeActive = false
@ -1572,7 +1554,7 @@ func checkBlockedEnvVars() error {
for _, name := range blockedEnvVars {
if os.Getenv(name) != "" {
return fmt.Errorf("%s env var is not supported and has been removed to prevent data fragmentation.\n"+
"The storage backend is set in .beads/metadata.json. To change it, use: bd migrate dolt", name)
"Unset %s; storage selection comes from .beads/metadata.json. To choose a different supported backend, follow 'bd help init-safety'; do not edit metadata.json by hand", name, name)
}
}
return nil
@ -1747,15 +1729,9 @@ func envTruthyValue(v string) bool {
return true
}
// dsnFlags are the flags whose value is a connection string that may embed a
// password (bd init --backend=postgres/mysql). Their values get the full
// parser-backed DSN scrub; other args only get the unambiguous userinfo scrub.
var dsnFlags = map[string]bool{"--pg-url": true, "--mysql-url": true}
// secretFlagNames are long flag names whose entire value is an opaque credential
// that must never reach the bd.args telemetry span. Unlike dsnFlags (a DSN that is
// parsed so its structure survives), a secret flag's value is redacted wholesale.
// Only federation add-peer's --password currently qualifies. Its shorthand (-p) is
// that must never reach the bd.args telemetry span. The flag's value is redacted
// wholesale. Only federation add-peer's --password currently qualifies. Its shorthand (-p) is
// resolved per command via secretFlagTokens so the same letter bound to
// --priority/--prefix/--parallel on other commands is never redacted.
var secretFlagNames = map[string]bool{"password": true}
@ -1784,40 +1760,38 @@ func secretFlagTokens(cmd *cobra.Command) map[string]bool {
}
// scrubArgsForTelemetry joins argv for the bd.args span attribute with any
// credential-bearing values redacted. --pg-url/--mysql-url may carry a password
// for init, and federation add-peer --password/-p carries a SQL password;
// RedactPassword protects metadata.json, but the raw argv would otherwise leak the
// secret into the telemetry root span and trace logs.
//
// A DSN flag's value is scrubbed through the parser-backed pgdialect logic so every
// password form pgx accepts is caught — URL userinfo, URL `?password=`/`?sslpassword=`
// query params, and libpq `password=`/`sslpassword=` keyword/value tokens — in both
// the `--pg-url=<dsn>` and `--pg-url <dsn>` spellings. A secretFlags token's value is
// an opaque credential and is redacted wholesale across the `--password <v>`,
// credential-bearing values redacted. A secretFlags token's value is redacted
// wholesale across the `--password <v>`,
// `--password=<v>`, `-p <v>`, `-p=<v>`, and `-p<v>` spellings pflag accepts. Every
// other arg still gets the narrow user:PASS@host userinfo scrub as defense in depth,
// without the broad keyword scan that would over-redact ordinary text.
// other arg gets a conservative DSN/userinfo scrub as defense in depth so a
// positional connection string cannot leak a password.
func scrubArgsForTelemetry(argv []string, secretFlags map[string]bool) string {
parts := make([]string, len(argv))
redactNext := false
for i, a := range argv {
if name, val, ok := strings.Cut(a, "="); ok {
if dsnFlags[name] {
// --pg-url=<dsn> — scrub only the value, keep the flag name.
parts[i] = name + "=" + scrubDSNValue(val)
continue
}
if redactNext {
parts[i] = "xxxxx"
redactNext = false
continue
}
if name, value, ok := strings.Cut(a, "="); ok {
if secretFlags[name] {
// --password=<secret> / -p=<secret> — redact the whole value.
parts[i] = name + "=xxxxx"
continue
}
if strings.HasPrefix(name, "-") {
scrubbed := scrubUserinfoPassword(scrubPotentialDSNPasswords(value))
if scrubbed != value {
// Preserve an arbitrary flag name while parsing its equals-value as
// a possible DSN. Passing the whole token to url.Parse would treat
// the flag prefix as the URL scheme and miss query credentials.
parts[i] = name + "=" + scrubbed
continue
}
}
}
if i > 0 {
if dsnFlags[argv[i-1]] {
// <dsn> following a bare --pg-url token.
parts[i] = scrubDSNValue(a)
continue
}
if secretFlags[argv[i-1]] {
// <secret> following a bare --password / -p token.
parts[i] = "xxxxx"
@ -1829,7 +1803,14 @@ func scrubArgsForTelemetry(argv []string, secretFlags map[string]bool) string {
parts[i] = short + "xxxxx"
continue
}
parts[i] = scrubUserinfoPassword(a)
if secretShorthandTakesSeparateValue(a, secretFlags) {
// -qp <secret> — a boolean shorthand cluster ending in the
// value-taking secret shorthand, with its value in the next token.
parts[i] = a
redactNext = true
continue
}
parts[i] = scrubUserinfoPassword(scrubPotentialDSNPasswords(a))
}
return strings.Join(parts, " ")
}
@ -1868,12 +1849,23 @@ func secretShorthandPrefix(a string, secretFlags map[string]bool) (string, bool)
return "", false
}
// scrubDSNValue redacts every password form from a connection-string value. The
// pgdialect pass covers pgx's URL (userinfo + query) and libpq keyword/value shapes;
// the trailing userinfo pass covers the MySQL user:PASS@tcp(...) DSN, which is not a
// scheme URL and so is invisible to the pgdialect extractor.
func scrubDSNValue(val string) string {
return scrubUserinfoPassword(pgdialect.ScrubDSNString(val, val))
// secretShorthandTakesSeparateValue recognizes a boolean-shorthand cluster that
// ends in a registered secret shorthand with no attached value. For example,
// pflag parses "-qp secret" as -q followed by -p=secret.
func secretShorthandTakesSeparateValue(a string, secretFlags map[string]bool) bool {
if len(a) < 3 || a[0] != '-' || a[1] == '-' {
return false
}
for i := 1; i < len(a); i++ {
c := a[i]
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return false
}
if secretFlags["-"+string(c)] {
return i == len(a)-1
}
}
return false
}
// scrubUserinfoPassword redacts the password in a URL/DSN userinfo section

View file

@ -142,6 +142,12 @@ func TestBlockedEnvVars(t *testing.T) {
if err != nil && !strings.Contains(err.Error(), tt.envVar) {
t.Errorf("expected error to mention %s, got: %v", tt.envVar, err)
}
if err != nil && !strings.Contains(err.Error(), "bd help init-safety") {
t.Errorf("expected error to point to safe reinitialization guidance, got: %v", err)
}
if err != nil && strings.Contains(err.Error(), "bd migrate dolt") {
t.Errorf("error must not recommend the removed backend-conversion command: %v", err)
}
})
}

View file

@ -22,16 +22,8 @@ import (
const migrateLockFileName = "migrate.lock"
func migrateModeGate(cmd *cobra.Command) error {
return fmt.Errorf("%s is not yet implemented", cmd.CommandPath())
}
func migrateToProxiedRunE(metricName, checkName string, shared bool) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, _ []string) error {
if err := migrateModeGate(cmd); err != nil {
return err
}
evt := metrics.NewCommandEvent(metricName)
defer func() {
if c := metrics.Global(); c != nil {
@ -54,10 +46,6 @@ func migrateToProxiedRunE(metricName, checkName string, shared bool) func(*cobra
func migrateFromProxiedRunE(metricName, checkName string, shared bool) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, _ []string) error {
if err := migrateModeGate(cmd); err != nil {
return err
}
evt := metrics.NewCommandEvent(metricName)
defer func() {
if c := metrics.Global(); c != nil {

View file

@ -5,7 +5,6 @@ import (
"path/filepath"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -42,14 +41,6 @@ func proxiedAssetNames() []string {
return []string{"proxy.pid", "proxy.lock", "proxy.log", "proxy-child.pid", "proxy-child.lock", "server.log"}
}
func TestMigrateModeCommands_Gated(t *testing.T) {
for _, cmd := range []*cobra.Command{migrateToProxiedServerCmd, migrateToServerCmd, migrateSharedToProxiedServerCmd, migrateToSharedServerCmd} {
err := cmd.RunE(cmd, nil)
require.Error(t, err, "%s must be gated", cmd.Name())
assert.Contains(t, err.Error(), "is not yet implemented")
}
}
func TestMigrateToProxiedServer_FlipsMode(t *testing.T) {
beadsDir := migrateModeWorkspace(t, configfile.DoltModeServer)

View file

@ -8,6 +8,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/ui"
)
@ -95,14 +96,13 @@ Examples:
return HandleErrorRespectJSON("%s", err)
}
combined := issue.Notes
if combined != "" {
combined += "\n"
}
combined += noteText
// Passed as an append OPERATION, not a pre-merged value: the storage
// layer re-reads the row inside the mutation transaction and appends
// there. Concatenating onto the `issue` snapshot here (read in an
// earlier transaction) silently erased notes committed by a concurrent
// `bd note` / `bd update --append-notes` — both processes exited 0.
updates := map[string]interface{}{
"notes": combined,
issueops.OpAppendNotes: noteText,
}
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil {
return HandleErrorRespectJSON("updating %s: %v", id, err)

View file

@ -0,0 +1,339 @@
// lease_claim_test.go — CLI-level conformance for the claim/lease clauses of
// protocol v0 §L that the §11 manifest listed as unpinned: the unassigned-only
// claim rule (L3.1), the empty-front success contract (L3.4/E1), filter
// composition (L3.5), and the JSONL round-trip of the lease fields (L1.2).
//
// These live at the CLI surface rather than the store because they are what a
// worker fleet actually drives: `bd ready --claim` is the whole coordination
// protocol between N workers and one queue.
package protocol
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// claimReady runs `bd ready --claim --json` as actor and returns the claimed
// issues (empty when the front holds nothing claimable). It fails the test if
// the command exits nonzero — an empty front is success (L3.4), not an error.
func claimReady(t *testing.T, w *workspace, actor string, args ...string) []map[string]any {
t.Helper()
full := append([]string{"ready", "--claim", "--json"}, args...)
out, err := w.tryRunEnv([]string{"BEADS_ACTOR=" + actor}, full...)
if err != nil {
t.Fatalf("bd %s as %s: %v\n%s", strings.Join(full, " "), actor, err, out)
}
return parseJSONOutput(t, out)
}
// TestProtocol_ClaimIsUnassignedOnly pins clause L3.1, the single most
// bitten-in-production rule of the claim protocol: `--claim` considers only
// issues that are open AND unassigned. An open issue that carries an assignee —
// even with no lease on it, even though `bd ready` happily LISTS it — is never a
// claim candidate. This is the gotcha behind a backlog generated with
// self-assigned creates: it looks ready and claims nothing, and a worker fleet
// pointed at it spins on an empty front while the queue sits full.
func TestProtocol_ClaimIsUnassignedOnly(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
// Same priority and creation order, so the only thing separating them is the
// assignee: if --claim ignored L3.1, the assigned issue is a live candidate.
assigned := w.create("--title", "Open but assigned", "--type", "task", "-p", "1", "-a", "someone-else")
free := w.create("--title", "Open and unassigned", "--type", "task", "-p", "1")
// The listing is NOT filtered by assignee (§R): both are on the ready front.
ready := parseReadyIDs(t, w)
if !ready[assigned] || !ready[free] {
t.Fatalf("precondition: bd ready should list both %s (assigned) and %s (unassigned), got %v", assigned, free, ready)
}
claimed := claimReady(t, w, "alice")
if len(claimed) != 1 {
t.Fatalf("bd ready --claim returned %d issues, want 1", len(claimed))
}
if got := claimed[0]["id"]; got != free {
t.Fatalf("L3.1: --claim returned %v, want the unassigned issue %s (the assigned one %s must never be a candidate)", got, free, assigned)
}
// With only the assigned issue left, the front is empty for claiming — even
// though bd ready still lists it.
if again := claimReady(t, w, "alice"); len(again) != 0 {
t.Errorf("L3.1: --claim returned %v with only an assigned-but-open issue left; want nothing claimable", again)
}
if still := parseReadyIDs(t, w); !still[assigned] {
t.Errorf("bd ready stopped listing the assigned issue %s; only --claim filters to unassigned (§R)", assigned)
}
// The rejected candidate was not touched: still open, still someone else's.
got := w.showJSON(assigned)
if got["status"] != "open" {
t.Errorf("assigned issue status = %v, want open (--claim must not mutate a non-candidate)", got["status"])
}
if got["assignee"] != "someone-else" {
t.Errorf("assigned issue assignee = %v, want someone-else", got["assignee"])
}
}
// TestProtocol_ReadyClaimEmptyFrontIsSuccess pins clause L3.4 (and §E1): when
// nothing is claimable, `bd ready --claim --json` MUST exit 0 with an explicit
// empty JSON array. Queue-drained is the steady state of a worker fleet, not an
// error — a nonzero exit here would make every idle worker look like a failure.
func TestProtocol_ReadyClaimEmptyFrontIsSuccess(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
// (a) Never had any work.
out, err := w.tryRunEnv([]string{"BEADS_ACTOR=alice"}, "ready", "--claim", "--json")
if err != nil {
t.Fatalf("L3.4: bd ready --claim --json on an empty tracker exited nonzero: %v\n%s", err, out)
}
if trimmed := strings.TrimSpace(out); trimmed != "[]" {
t.Errorf("L3.4: empty front printed %q, want the explicit empty array []", trimmed)
}
// (b) Drained: the one issue is claimed, so the next claim comes up empty.
only := w.create("--title", "The only work", "--type", "task")
if claimed := claimReady(t, w, "alice"); len(claimed) != 1 || claimed[0]["id"] != only {
t.Fatalf("setup: first claim = %v, want [%s]", claimed, only)
}
out, err = w.tryRunEnv([]string{"BEADS_ACTOR=bob"}, "ready", "--claim", "--json")
if err != nil {
t.Fatalf("L3.4: bd ready --claim --json on a drained queue exited nonzero: %v\n%s", err, out)
}
if trimmed := strings.TrimSpace(out); trimmed != "[]" {
t.Errorf("L3.4: drained queue printed %q, want []", trimmed)
}
}
// TestProtocol_ReadyClaimComposesWithFilters pins clause L3.5: `--claim` composes
// with the ready-front filters, and the issue it claims satisfies the same filter
// the plain `bd ready` listing would. This is what lets several fleets drain one
// shared queue without colliding — each claims only its own lane (--label) or its
// own epic (--parent, transitive per R3).
func TestProtocol_ReadyClaimComposesWithFilters(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
epic := w.create("--title", "Epic under drain", "--type", "epic")
child := w.create("--title", "Child", "--type", "task", "--parent", epic)
grandchild := w.create("--title", "Grandchild", "--type", "task", "--parent", child)
outsider := w.create("--title", "Not under the epic", "--type", "task")
lane := w.create("--title", "Lane work", "--type", "task", "-l", "lane:x")
// --parent claims only transitive descendants of the epic, never the
// outsider and never the lane issue.
underEpic := map[string]bool{child: true, grandchild: true}
for i := 0; i < 2; i++ {
claimed := claimReady(t, w, "alice", "--parent", epic)
if len(claimed) != 1 {
t.Fatalf("L3.5: --claim --parent %s returned %d issues on pass %d, want 1", epic, len(claimed), i+1)
}
id, _ := claimed[0]["id"].(string)
if !underEpic[id] {
t.Fatalf("L3.5: --claim --parent %s claimed %s, which is not a descendant of the epic", epic, id)
}
delete(underEpic, id) // never the same issue twice
}
if len(underEpic) != 0 {
t.Errorf("L3.5: --claim --parent left %v unclaimed; --parent must be transitive (R3)", underEpic)
}
if drained := claimReady(t, w, "alice", "--parent", epic); len(drained) != 0 {
t.Errorf("L3.5: --claim --parent %s claimed %v after its subtree drained; the filter leaked", epic, drained)
}
// --label claims only the matching lane, and the claimed issue really carries
// the label the filter named.
claimed := claimReady(t, w, "bob", "--label", "lane:x")
if len(claimed) != 1 || claimed[0]["id"] != lane {
t.Fatalf("L3.5: --claim --label lane:x returned %v, want [%s]", claimed, lane)
}
labels, _ := w.showJSON(lane)["labels"].([]any)
found := false
for _, l := range labels {
if l == "lane:x" {
found = true
}
}
if !found {
t.Errorf("L3.5: claimed issue %s does not carry the filtered label lane:x (labels=%v)", lane, labels)
}
// The outsider was never a candidate under either filter and is still ready.
// (An unassigned issue reports assignee as JSON null or "", never an owner.)
out := w.showJSON(outsider)
if assignee, _ := out["assignee"].(string); out["status"] != "open" || assignee != "" {
t.Errorf("L3.5: filtered claims touched the out-of-filter issue %s: status=%v assignee=%v",
outsider, out["status"], out["assignee"])
}
}
// exportLeaseFixture claims one issue, leaves another unclaimed, exports the
// tracker to JSONL, and returns the export path plus the parsed lines by id.
func exportLeaseFixture(t *testing.T, w *workspace, leased, idle string) (string, map[string]map[string]any) {
t.Helper()
w.runEnv([]string{"BEADS_ACTOR=alice"}, "update", leased, "--claim")
path := filepath.Join(w.dir, "export.jsonl")
w.run("export", "-o", path)
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read export: %v", err)
}
exported := map[string]map[string]any{}
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
if strings.TrimSpace(line) == "" {
continue
}
var obj map[string]any
if err := json.Unmarshal([]byte(line), &obj); err != nil {
t.Fatalf("export line is not JSON: %v\n%s", err, line)
}
if id, ok := obj["id"].(string); ok {
exported[id] = obj
}
}
if _, ok := exported[leased]; !ok {
t.Fatalf("export omitted the claimed issue %s", leased)
}
if _, ok := exported[idle]; !ok {
t.Fatalf("export omitted the unclaimed issue %s", idle)
}
return path, exported
}
// TestProtocol_LeaseFieldsExportToJSONL pins the export half of clause L1.2: a
// claimed issue carries both lease fields into the JSONL interchange as RFC 3339
// timestamps (§J2.4), and an issue holding no lease carries NEITHER — the fields
// are omitted, not emitted as null.
func TestProtocol_LeaseFieldsExportToJSONL(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
leased := w.create("--title", "Claimed and leased", "--type", "task")
idle := w.create("--title", "Never claimed", "--type", "task")
_, exported := exportLeaseFixture(t, w, leased, idle)
expires := requireRFC3339(t, exported[leased], "lease_expires_at", leased)
heartbeat := requireRFC3339(t, exported[leased], "heartbeat_at", leased)
if !expires.After(heartbeat) {
t.Errorf("L1.2: lease_expires_at (%v) is not after heartbeat_at (%v)", expires, heartbeat)
}
for _, field := range []string{"lease_expires_at", "heartbeat_at"} {
if v, present := exported[idle][field]; present {
t.Errorf("L1.2: unclaimed issue %s exported %s = %v, want the field omitted", idle, field, v)
}
}
}
// TestProtocol_LeaseFieldsRoundTripJSONL pins the other half of clause L1.2: the
// lease fields must survive the round trip, not just the export. bd import once
// dropped them (wy-urlct: the sole issue INSERT path, issueops.InsertIssueIntoTable,
// listed no lease columns), so an issue exported while claimed was imported as
// in_progress with a NULL lease. Reclaim only recovers leased claims (L5.1),
// which made such an issue unreclaimable by any
// reaper: stranded forever under a worker that may be long dead — exactly the
// recoverability the lease exists to provide. Leases now live in the ephemeral
// leases table (bd-lrgn1) and import restores them via
// issueops.RestoreLeaseOnImportInTx, so an import can restore a lease but
// snapshot data can never clobber a live (unexpired) local lease — pinned by
// TestProtocol_ImportNeverClobbersLiveLocalLease.
func TestProtocol_LeaseFieldsRoundTripJSONL(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
leased := w.create("--title", "Claimed and leased", "--type", "task")
idle := w.create("--title", "Never claimed", "--type", "task")
path, exported := exportLeaseFixture(t, w, leased, idle)
expires := requireRFC3339(t, exported[leased], "lease_expires_at", leased)
heartbeat := requireRFC3339(t, exported[leased], "heartbeat_at", leased)
fresh := newWorkspace(t)
fresh.run("import", path)
restored := fresh.showJSON(leased)
if back := requireRFC3339(t, restored, "lease_expires_at", leased); !back.Equal(expires) {
t.Errorf("L1.2: lease_expires_at did not round-trip: exported %v, imported %v", expires, back)
}
if back := requireRFC3339(t, restored, "heartbeat_at", leased); !back.Equal(heartbeat) {
t.Errorf("L1.2: heartbeat_at did not round-trip: exported %v, imported %v", heartbeat, back)
}
if restored["assignee"] != "alice" || restored["status"] != "in_progress" {
t.Errorf("L1.2: lease owner did not round-trip: assignee=%v status=%v, want alice/in_progress",
restored["assignee"], restored["status"])
}
}
// TestProtocol_ImportNeverClobbersLiveLocalLease pins the lease-restore guard
// of clause L1.2 under the ephemeral leases table (bd-lrgn1): leases are
// node-local — only enforceable on the node that granted them — so a snapshot
// imported over a LIVE (unexpired) local lease must leave the local lease
// untouched, even when the snapshot's issue row is strictly newer and its
// other fields win the stale-guard merge. Only an expired (or absent) local
// lease may be replaced by snapshot lease data.
func TestProtocol_ImportNeverClobbersLiveLocalLease(t *testing.T) {
t.Parallel()
w := newWorkspace(t)
leased := w.create("--title", "Locally claimed", "--type", "task")
w.runEnv([]string{"BEADS_ACTOR=alice"}, "update", leased, "--claim")
local := w.showJSON(leased)
localExpiry := requireRFC3339(t, local, "lease_expires_at", leased)
if !localExpiry.After(time.Now()) {
t.Fatalf("precondition: local lease already expired (%v)", localExpiry)
}
// Craft a snapshot of the same issue that is strictly NEWER by updated_at
// and carries different (also-live) lease timestamps — as if exported from
// another node that also believes it holds the claim.
snapshot := map[string]any{}
for k, v := range local {
snapshot[k] = v
}
delete(snapshot, "labels")
snapshot["updated_at"] = time.Now().UTC().Add(2 * time.Hour).Format(time.RFC3339)
snapshot["lease_expires_at"] = time.Now().UTC().Add(30 * time.Hour).Format(time.RFC3339)
snapshot["heartbeat_at"] = time.Now().UTC().Add(29 * time.Hour).Format(time.RFC3339)
snapshot["notes"] = "remote edit that must land"
line, err := json.Marshal(snapshot)
if err != nil {
t.Fatalf("marshal snapshot: %v", err)
}
path := filepath.Join(w.dir, "remote.jsonl")
if err := os.WriteFile(path, append(line, '\n'), 0o644); err != nil {
t.Fatalf("write snapshot: %v", err)
}
w.run("import", path)
restored := w.showJSON(leased)
// The newer snapshot's row fields won the merge...
if restored["notes"] != "remote edit that must land" {
t.Errorf("newer snapshot's field edit did not land: notes=%v", restored["notes"])
}
// ...but the live local lease was NOT clobbered by the snapshot's lease.
if back := requireRFC3339(t, restored, "lease_expires_at", leased); !back.Equal(localExpiry) {
t.Errorf("import clobbered a live local lease: expiry was %v, now %v (snapshot's was ~30h out)",
localExpiry, back)
}
}
// requireRFC3339 asserts obj[field] is a non-empty RFC 3339 timestamp (§J2.4)
// and returns it.
func requireRFC3339(t *testing.T, obj map[string]any, field, id string) time.Time {
t.Helper()
raw, ok := obj[field].(string)
if !ok || raw == "" {
t.Fatalf("L1.2: issue %s carries no %s (got %v)", id, field, obj[field])
}
ts, err := time.Parse(time.RFC3339, raw)
if err != nil {
t.Fatalf("L1.2: %s of %s is not RFC 3339: %q (%v)", field, id, raw, err)
}
return ts
}

View file

@ -508,8 +508,11 @@ func TestInitCommandRegistersProxiedServerExternalFlags(t *testing.T) {
{"proxied-server-external-socket-path", ""},
{"proxied-server-external-user", ""},
{"proxied-server-external-tls", "false"},
{"proxied-server-external-tls-ca-cert-path", ""},
{"proxied-server-external-tls-cert-path", ""},
{"proxied-server-external-tls-key-path", ""},
{"proxied-server-external-tls-server-name", ""},
{"proxied-server-external-tls-skip-verify", "false"},
{"proxied-server-external-keep-alive", "0s"},
}
for _, tc := range cases {

View file

@ -0,0 +1,82 @@
//go:build cgo
package main
import (
"fmt"
"os"
"strconv"
"sync"
"sync/atomic"
"testing"
"github.com/steveyegge/beads/internal/testutil"
)
var (
sharedProxiedOnce sync.Once
sharedProxiedPort int
sharedProxiedErr error
sharedProxiedDBSeq atomic.Int64
)
func sharedProxiedServerPort(t *testing.T) int {
t.Helper()
sharedProxiedOnce.Do(func() {
if err := testutil.EnsureDoltContainerForTestMain(); err != nil {
sharedProxiedErr = err
return
}
port := testutil.DoltContainerPortInt()
if port == 0 {
sharedProxiedErr = fmt.Errorf("shared dolt container reported no port")
return
}
sharedProxiedPort = port
})
if sharedProxiedErr != nil {
t.Skipf("shared proxied-server unavailable: %v", sharedProxiedErr)
}
return sharedProxiedPort
}
func requireSharedProxiedServer(t *testing.T) int {
t.Helper()
if os.Getenv("BEADS_TEST_PROXIED_SERVER") != "1" {
t.Skip("set BEADS_TEST_PROXIED_SERVER=1 to run proxied-server integration tests")
}
return sharedProxiedServerPort(t)
}
func uniqueProxiedDatabase() string {
return fmt.Sprintf("bdtest_%d", sharedProxiedDBSeq.Add(1))
}
func sharedProxiedInitArgs(t *testing.T, extraInitArgs ...string) (string, []string) {
t.Helper()
port := requireSharedProxiedServer(t)
database := uniqueProxiedDatabase()
args := append([]string{
"--database", database,
"--proxied-server-external-host", "127.0.0.1",
"--proxied-server-external-port", strconv.Itoa(port),
}, extraInitArgs...)
return database, args
}
func newSharedProxiedProject(t *testing.T, bd, prefix string, extraInitArgs ...string) proxiedProject {
t.Helper()
database, args := sharedProxiedInitArgs(t, extraInitArgs...)
p := bdProxiedInit(t, bd, prefix, args...)
p.database = database
return p
}
func newSharedProxiedProjectWithHooks(t *testing.T, bd, prefix string, hooks map[string]string, extraInitArgs ...string) proxiedProject {
t.Helper()
database, args := sharedProxiedInitArgs(t, extraInitArgs...)
p := bdProxiedInitWithHooks(t, bd, prefix, hooks, args...)
p.database = database
return p
}

View file

@ -43,11 +43,13 @@ func bdProxiedPruneFail(t *testing.T, bd, dir string, args ...string) string {
}
func TestProxiedServerPrune(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("requires_filter", func(t *testing.T) {
p := bdProxiedInit(t, bd, "prf")
t.Parallel()
p := newSharedProxiedProject(t, bd, "prf")
out := bdProxiedPruneFail(t, bd, p.dir)
if !strings.Contains(out, "requires --older-than or --pattern") {
t.Errorf("expected requires-filter error, got: %s", out)
@ -55,7 +57,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("dry_run_deletes_nothing", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pdr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pdr")
issue := bdProxiedCreate(t, bd, p.dir, "Prune me")
bdProxiedClose(t, bd, p.dir, issue.ID)
out := bdProxiedPrune(t, bd, p.dir, "--pattern", "*", "--dry-run")
@ -69,7 +72,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("force_deletes_closed", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pfd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pfd")
issue := bdProxiedCreate(t, bd, p.dir, "Delete me")
bdProxiedClose(t, bd, p.dir, issue.ID)
bdProxiedPrune(t, bd, p.dir, "--pattern", "*", "--force")
@ -80,7 +84,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("skips_open", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pso")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pso")
open := bdProxiedCreate(t, bd, p.dir, "Still open")
closed := bdProxiedCreate(t, bd, p.dir, "Now closed")
bdProxiedClose(t, bd, p.dir, closed.ID)
@ -95,7 +100,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("reference_aware_skip", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pras")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pras")
referenced := bdProxiedCreate(t, bd, p.dir, "Cited decision")
_ = bdProxiedCreate(t, bd, p.dir, "Open citer",
"--description", "per "+referenced.ID+" we decided X")
@ -112,7 +118,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("ignore_references_deletes_referenced", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pir")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pir")
referenced := bdProxiedCreate(t, bd, p.dir, "Cited decision")
_ = bdProxiedCreate(t, bd, p.dir, "Open citer",
"--description", "per "+referenced.ID+" we decided X")
@ -126,7 +133,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pjo")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pjo")
a := bdProxiedCreate(t, bd, p.dir, "JSON prune A")
b := bdProxiedCreate(t, bd, p.dir, "JSON prune B")
bdProxiedClose(t, bd, p.dir, a.ID, b.ID)
@ -159,7 +167,8 @@ func TestProxiedServerPrune(t *testing.T) {
})
t.Run("commits_deletion", func(t *testing.T) {
p := bdProxiedInit(t, bd, "pcd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "pcd")
issue := bdProxiedCreate(t, bd, p.dir, "Commit prune")
bdProxiedClose(t, bd, p.dir, issue.ID)
db := openProxiedDB(t, p)

View file

@ -57,9 +57,10 @@ func bdProxiedQueryFail(t *testing.T, bd string, p proxiedProject, args ...strin
}
func TestProxiedServerQuery(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "qry")
p := newSharedProxiedProject(t, bd, "qry")
seed := seedProxiedListData(t, bd, p)
t.Run("filter_only_and_chain", func(t *testing.T) {

View file

@ -88,37 +88,15 @@ Example:
ctx = storage.WithReservedChildCounter(ctx, parentID, childID)
}
if err := store.CreateIssue(ctx, issue, actor); err != nil {
// The issue and its parent-child edge commit in one transaction; a
// failed edge rolls back the create instead of leaving a dep-less
// child behind (same contract as bd create).
if err := createIssueWithDeps(ctx, store, issue, actor, createDepEdges{parentID: parentID}); err != nil {
return HandleError("%v", err)
}
commandDidWrite.Store(true)
if parentID != "" {
dep := &types.Dependency{
IssueID: issue.ID,
DependsOnID: parentID,
Type: types.DepParentChild,
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
WarnError("failed to add parent-child dependency %s -> %s: %v", issue.ID, parentID, err)
} else {
// CreateIssue commits internally, but the dependency write
// only lands in the working set (GH#2009) — same follow-up
// commit bd create performs.
shouldCommit, err := shouldCommitCreatePostWrites(issue, true)
if err != nil {
return HandleError("dolt auto-commit failed: %v", err)
}
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit: %v", err)
}
}
}
}
fmt.Println(issue.ID)
return nil
},

View file

@ -8,11 +8,13 @@ import (
)
func TestProxiedServerQuick(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("q_creates_and_outputs_id", func(t *testing.T) {
p := bdProxiedInit(t, bd, "qk")
t.Parallel()
p := newSharedProxiedProject(t, bd, "qk")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "q", "Quick captured task")
if err != nil {
t.Fatalf("q failed: %v\nstderr:\n%s", err, stderr)
@ -28,7 +30,8 @@ func TestProxiedServerQuick(t *testing.T) {
})
t.Run("q_with_parent_creates_child", func(t *testing.T) {
p := bdProxiedInit(t, bd, "qp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "qp")
parent := bdProxiedCreate(t, bd, p.dir, "Quick parent", "--type", "epic")
bdProxiedLabel(t, bd, p.dir, "add", parent.ID, "inherited")
@ -58,11 +61,13 @@ func TestProxiedServerQuick(t *testing.T) {
}
func TestProxiedServerTodo(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("add_list_done", func(t *testing.T) {
p := bdProxiedInit(t, bd, "td")
t.Parallel()
p := newSharedProxiedProject(t, bd, "td")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "add", "Write the tests")
if err != nil {
@ -82,7 +87,8 @@ func TestProxiedServerTodo(t *testing.T) {
})
t.Run("add_json_and_done", func(t *testing.T) {
p := bdProxiedInit(t, bd, "tj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "tj")
created := bdProxiedCreate(t, bd, p.dir, "Task to finish", "--type", "task")
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "done", created.ID)
@ -98,7 +104,8 @@ func TestProxiedServerTodo(t *testing.T) {
})
t.Run("bare_todo_lists_open_tasks", func(t *testing.T) {
p := bdProxiedInit(t, bd, "tb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "tb")
open := bdProxiedCreate(t, bd, p.dir, "Open todo", "--type", "task")
done := bdProxiedCreate(t, bd, p.dir, "Done todo", "--type", "task")
if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "done", done.ID); err != nil {

View file

@ -68,11 +68,13 @@ func bdProxiedReadyFail(t *testing.T, bd string, p proxiedProject, args ...strin
}
func TestProxiedServerReady(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("json_round_trips_issue_with_counts", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdj1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdj1")
issue := bdProxiedCreate(t, bd, p.dir, "Zero deps", "--label", "rdj1-only")
ready := bdProxiedReadyJSON(t, bd, p, "--label", "rdj1-only")
if len(ready) != 1 {
@ -87,7 +89,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("default_text_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdt")
bdProxiedCreate(t, bd, p.dir, "Ready title here")
stdout, _ := bdProxiedReadyCapture(t, bd, p)
if !strings.Contains(stdout, "Ready title here") {
@ -96,7 +99,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("json_validity", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdv")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdv")
bdProxiedCreate(t, bd, p.dir, "JSON test")
stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--json")
if err != nil {
@ -113,7 +117,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("limit_zero_returns_full_set_and_suppresses_hint", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdl0")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdl0")
const n = 4
want := make(map[string]bool, n)
for i := 0; i < n; i++ {
@ -152,7 +157,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("limit_truncation_hint_on_stderr", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdl")
for i := 0; i < 4; i++ {
bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("Ready item %d", i))
}
@ -174,7 +180,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("offset_with_large_finite_limit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdofflz")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdofflz")
for i := 0; i < 4; i++ {
bdProxiedCreate(t, bd, p.dir,
fmt.Sprintf("Lz item %d", i), "--label", "rdofflz")
@ -187,7 +194,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("offset_zero_equals_no_offset", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdoff0")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdoff0")
for i := 0; i < 3; i++ {
bdProxiedCreate(t, bd, p.dir,
fmt.Sprintf("Eq item %d", i), "--label", "rdoff0")
@ -207,7 +215,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("offset_combo_guards", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdoffg")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdoffg")
bdProxiedCreate(t, bd, p.dir, "Seed")
cases := []struct {
name string
@ -229,7 +238,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("offset_skips_leading_results", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdoff")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdoff")
ids := make([]string, 4)
for i := 0; i < 4; i++ {
issue := bdProxiedCreate(t, bd, p.dir,
@ -254,7 +264,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("claim_json_no_match_returns_empty_array", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rcn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rcn")
bdProxiedCreate(t, bd, p.dir, "Has wrong label", "--label", "real")
out, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json", "--label", "missing-label")
if err != nil {
@ -270,7 +281,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("claim_json_marks_in_progress_and_assignee", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rcm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rcm")
issue := bdProxiedCreate(t, bd, p.dir, "Claim me", "--label", "claim-me")
out, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json", "--label", "claim-me")
if err != nil {
@ -302,7 +314,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("blocked_issues_excluded_from_default_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdb")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker issue")
bdProxiedCreate(t, bd, p.dir, "Should be hidden because blocked", "--deps", "depends-on:"+blocker.ID)
stdout, _ := bdProxiedReadyCapture(t, bd, p)
@ -312,7 +325,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("exclude_label_filter", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdex")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdex")
bdProxiedCreate(t, bd, p.dir, "Triage pending item", "--label", "triage:pending")
bdProxiedCreate(t, bd, p.dir, "Normal ready item")
stdout, _ := bdProxiedReadyCapture(t, bd, p, "--exclude-label", "triage:pending")
@ -325,7 +339,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("explain_json_round_trip", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rde")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rde")
bdProxiedCreate(t, bd, p.dir, "Plain ready")
blocker := bdProxiedCreate(t, bd, p.dir, "Live blocker")
bdProxiedCreate(t, bd, p.dir, "Blocked dependent", "--deps", "depends-on:"+blocker.ID)
@ -351,7 +366,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("explain_text_header", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdet")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdet")
bdProxiedCreate(t, bd, p.dir, "Smoke")
stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain")
if err != nil {
@ -363,7 +379,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("explain_detects_cycles", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdc")
a := bdProxiedCreate(t, bd, p.dir, "Cycle node A")
b := bdProxiedCreate(t, bd, p.dir, "Cycle node B")
db := openProxiedDB(t, p)
@ -397,7 +414,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("gated_empty_case", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdge")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdge")
bdProxiedCreate(t, bd, p.dir, "No gates anywhere")
stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--gated", "--json")
if err != nil {
@ -423,7 +441,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("gated_json_shape_with_open_gate", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdgw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdgw")
bdProxiedCreate(t, bd, p.dir, "Open gate", "--type", "gate")
stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--gated", "--json")
if err != nil {
@ -444,7 +463,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("mol_text_and_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdm")
mol := bdProxiedCreate(t, bd, p.dir, "Mol parent", "--type", "molecule")
s1 := bdProxiedCreate(t, bd, p.dir, "Step one", "--parent", mol.ID)
bdProxiedCreate(t, bd, p.dir, "Step two", "--parent", mol.ID, "--deps", "depends-on:"+s1.ID)
@ -475,7 +495,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("empty_state_no_open_issues", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdei")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdei")
stdout, _ := bdProxiedReadyCapture(t, bd, p)
if !strings.Contains(stdout, "No open issues") {
t.Errorf("expected 'No open issues', got: %s", stdout)
@ -483,7 +504,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("empty_state_no_ready_with_blockers", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdeb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdeb")
blocker := bdProxiedCreate(t, bd, p.dir, "Self-blocker")
bdProxiedCreate(t, bd, p.dir, "Only issue, blocked", "--deps", "blocks:"+blocker.ID)
if _, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json"); err == nil {
@ -498,7 +520,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("filter_priority_pass_through", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rfp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rfp")
hi := bdProxiedCreate(t, bd, p.dir, "Hi pri", "-p", "0")
lo := bdProxiedCreate(t, bd, p.dir, "Lo pri", "-p", "3")
ready := bdProxiedReadyJSON(t, bd, p, "-p", "0")
@ -515,7 +538,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("filter_assignee_pass_through", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rfa")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rfa")
mine := bdProxiedCreate(t, bd, p.dir, "Alice work", "--assignee", "alice")
bdProxiedCreate(t, bd, p.dir, "Bob work", "--assignee", "bob")
ready := bdProxiedReadyJSON(t, bd, p, "--assignee", "alice")
@ -534,7 +558,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("filter_unassigned_pass_through", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rfu")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rfu")
un := bdProxiedCreate(t, bd, p.dir, "Free agent")
bdProxiedCreate(t, bd, p.dir, "Taken", "--assignee", "alice")
ready := bdProxiedReadyJSON(t, bd, p, "--unassigned")
@ -553,7 +578,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("filter_type_pass_through", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rft")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rft")
bug := bdProxiedCreate(t, bd, p.dir, "A bug", "--type", "bug")
bdProxiedCreate(t, bd, p.dir, "A task", "--type", "task")
ready := bdProxiedReadyJSON(t, bd, p, "--type", "bug")
@ -572,7 +598,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("filter_parent_pass_through", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rfpar")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rfpar")
epic := bdProxiedCreate(t, bd, p.dir, "Epic", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Inside", "--parent", epic.ID)
outside := bdProxiedCreate(t, bd, p.dir, "Outside")
@ -590,7 +617,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("metadata_field_match", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rmd1")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rmd1")
match := bdProxiedCreate(t, bd, p.dir, "Has team", "--metadata", `{"team":"platform"}`)
bdProxiedCreate(t, bd, p.dir, "Other team", "--metadata", `{"team":"frontend"}`)
ready := bdProxiedReadyJSON(t, bd, p, "--metadata-field", "team=platform")
@ -604,7 +632,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("metadata_has_key", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rmd2")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rmd2")
withMeta := bdProxiedCreate(t, bd, p.dir, "With meta", "--metadata", `{"team":"x"}`)
bdProxiedCreate(t, bd, p.dir, "No meta")
ready := bdProxiedReadyJSON(t, bd, p, "--has-metadata-key", "team")
@ -618,7 +647,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("metadata_field_invalid_key_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rmd3")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rmd3")
out := bdProxiedReadyFail(t, bd, p, "--metadata-field", "bad$key=x")
if !strings.Contains(out, "metadata-field") {
t.Errorf("expected validation error about metadata-field, got: %s", out)
@ -626,7 +656,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("include_deferred_toggle", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdd")
issue := bdProxiedCreate(t, bd, p.dir, "Will defer")
db := openProxiedDB(t, p)
if _, err := db.ExecContext(context.Background(),
@ -653,7 +684,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("include_ephemeral_surfaces_wisps", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rdie")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rdie")
reg := bdProxiedCreate(t, bd, p.dir, "Regular")
wisp := bdProxiedCreate(t, bd, p.dir, "Wispy", "--ephemeral")
def := bdProxiedReadyJSON(t, bd, p)
@ -678,7 +710,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("mol_type_validation_rejects_invalid", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rmtv")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rmtv")
out := bdProxiedReadyFail(t, bd, p, "--mol-type", "garbage")
if !strings.Contains(out, "invalid mol-type") {
t.Errorf("expected 'invalid mol-type' error, got: %s", out)
@ -686,7 +719,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("claim_combo_guards", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rcc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rcc")
bdProxiedCreate(t, bd, p.dir, "Seed")
cases := []struct {
name string
@ -708,7 +742,8 @@ func TestProxiedServerReady(t *testing.T) {
})
t.Run("exclude_type_csv_and_repeated", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rxt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rxt")
task := bdProxiedCreate(t, bd, p.dir, "Task work", "--type", "task")
bdProxiedCreate(t, bd, p.dir, "Bug work", "--type", "bug")
bdProxiedCreate(t, bd, p.dir, "Epic work", "--type", "epic")
@ -744,9 +779,10 @@ func TestProxiedServerReady(t *testing.T) {
}
func TestProxiedServerReadyConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "rxc")
p := newSharedProxiedProject(t, bd, "rxc")
bdProxiedCreate(t, bd, p.dir, "Concurrent read target")
const numWorkers = 8
@ -769,9 +805,10 @@ func TestProxiedServerReadyConcurrent(t *testing.T) {
}
func TestProxiedServerReadyClaimConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "rcx")
p := newSharedProxiedProject(t, bd, "rcx")
issue := bdProxiedCreate(t, bd, p.dir, "Atomic claim target", "--label", "atomic")
const numWorkers = 8

View file

@ -14,11 +14,13 @@ import (
)
func TestProxiedServerReadyWisp(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("claim_include_ephemeral_claims_wisp", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwc")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp to claim", "--ephemeral", "--label", "wclaim")
out, err := bdProxiedRun(t, bd, p.dir,
@ -58,7 +60,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("mol_on_wisp_molecule_currently_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwm")
mol := bdProxiedCreate(t, bd, p.dir, "Wisp mol", "--ephemeral", "--type", "molecule")
bdProxiedCreate(t, bd, p.dir, "Wisp step", "--ephemeral", "--parent", mol.ID)
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--mol", mol.ID, "--json")
@ -72,7 +75,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("wisp_blocked_by_wisp_hidden_and_listed_in_blocked", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwwb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwwb")
blocker := bdProxiedCreate(t, bd, p.dir, "Wisp blocker", "--ephemeral")
dependent := bdProxiedCreate(t, bd, p.dir, "Wisp dependent", "--ephemeral")
@ -111,7 +115,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("cross_table_issue_blocked_by_wisp", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwci")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwci")
wispBlocker := bdProxiedCreate(t, bd, p.dir, "Wisp blocker for issue", "--ephemeral")
issue := bdProxiedCreate(t, bd, p.dir, "Issue blocked by wisp")
@ -158,7 +163,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("cross_table_wisp_blocked_by_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwcw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwcw")
issueBlocker := bdProxiedCreate(t, bd, p.dir, "Issue blocker for wisp")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp blocked by issue", "--ephemeral")
@ -205,7 +211,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("blocked_lists_blocked_wisp", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwbl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwbl")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker wisp", "--ephemeral")
dependent := bdProxiedCreate(t, bd, p.dir, "Dependent wisp", "--ephemeral")
@ -238,7 +245,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("explain_enriches_wisp_blocker_details", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwexb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwexb")
wispBlocker := bdProxiedCreate(t, bd, p.dir,
"Wisp blocker title", "--ephemeral", "-p", "1")
issue := bdProxiedCreate(t, bd, p.dir, "Blocked issue")
@ -303,7 +311,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("explain_detects_cycle_in_wisp_dependencies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwcy")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwcy")
a := bdProxiedCreate(t, bd, p.dir, "Wisp cycle A", "--ephemeral")
b := bdProxiedCreate(t, bd, p.dir, "Wisp cycle B", "--ephemeral")
@ -353,7 +362,8 @@ func TestProxiedServerReadyWisp(t *testing.T) {
})
t.Run("empty_state_hint_when_only_wisps_exist", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rwes")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rwes")
bdProxiedCreate(t, bd, p.dir, "Lonely wisp", "--ephemeral")
stdout, _ := bdProxiedReadyCapture(t, bd, p)
if !strings.Contains(stdout, "No open issues") {

View file

@ -8,11 +8,13 @@ import (
)
func TestProxiedServerLink(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("link_default_blocks", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lk")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lk")
a := bdProxiedCreate(t, bd, p.dir, "Link from")
b := bdProxiedCreate(t, bd, p.dir, "Link to")
@ -29,7 +31,8 @@ func TestProxiedServerLink(t *testing.T) {
})
t.Run("link_with_type", func(t *testing.T) {
p := bdProxiedInit(t, bd, "lt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "lt")
a := bdProxiedCreate(t, bd, p.dir, "Rel from")
b := bdProxiedCreate(t, bd, p.dir, "Rel to")
@ -42,7 +45,8 @@ func TestProxiedServerLink(t *testing.T) {
})
t.Run("link_invalid_type_rejected", func(t *testing.T) {
p := bdProxiedInit(t, bd, "li")
t.Parallel()
p := newSharedProxiedProject(t, bd, "li")
a := bdProxiedCreate(t, bd, p.dir, "Bad from")
b := bdProxiedCreate(t, bd, p.dir, "Bad to")
_, out, err := bdProxiedRunBuffers(t, bd, p.dir, "link", a.ID, b.ID, "--type", "")
@ -53,10 +57,11 @@ func TestProxiedServerLink(t *testing.T) {
}
func TestProxiedServerChildren(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "ch")
p := newSharedProxiedProject(t, bd, "ch")
parent := bdProxiedCreate(t, bd, p.dir, "Parent", "--type", "epic")
c1 := bdProxiedCreate(t, bd, p.dir, "Child 1", "--parent", parent.ID)
c2 := bdProxiedCreate(t, bd, p.dir, "Child 2", "--parent", parent.ID)
@ -71,11 +76,13 @@ func TestProxiedServerChildren(t *testing.T) {
}
func TestProxiedServerGateList(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("db_wide_lists_gates", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ga")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ga")
gate := bdProxiedCreate(t, bd, p.dir, "A gate", "--type", "gate")
bdProxiedCreate(t, bd, p.dir, "Not a gate", "--type", "task")
@ -89,7 +96,8 @@ func TestProxiedServerGateList(t *testing.T) {
})
t.Run("bead_scoped_lists_blocking_gates", func(t *testing.T) {
p := bdProxiedInit(t, bd, "gb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "gb")
work := bdProxiedCreate(t, bd, p.dir, "Blocked work")
gate := bdProxiedCreate(t, bd, p.dir, "Blocking gate", "--type", "gate")
unrelated := bdProxiedCreate(t, bd, p.dir, "Unrelated gate", "--type", "gate")

View file

@ -85,11 +85,13 @@ func readReopenComment(t *testing.T, db *sql.DB, id string) string {
}
func TestProxiedServerReopen(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("no_ids_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ron")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ron")
out := bdProxiedReopenFail(t, bd, p.dir)
if !strings.Contains(out, "requires at least 1 arg") {
t.Errorf("expected cobra arg-count error, got: %s", out)
@ -97,7 +99,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reopens_closed_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rorc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rorc")
issue := bdProxiedCreate(t, bd, p.dir, "Reopen target")
bdProxiedClose(t, bd, p.dir, issue.ID)
out := bdProxiedReopen(t, bd, p.dir, issue.ID)
@ -122,7 +125,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reason_recorded_as_comment", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rorr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rorr")
issue := bdProxiedCreate(t, bd, p.dir, "Reason target")
bdProxiedClose(t, bd, p.dir, issue.ID)
bdProxiedReopen(t, bd, p.dir, issue.ID, "--reason", "regression in QA")
@ -133,7 +137,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("already_open_prints_warning", func(t *testing.T) {
p := bdProxiedInit(t, bd, "roao")
t.Parallel()
p := newSharedProxiedProject(t, bd, "roao")
issue := bdProxiedCreate(t, bd, p.dir, "Already open")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "reopen", issue.ID)
if err != nil {
@ -145,7 +150,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("missing_id_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rom")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rom")
out := bdProxiedReopenFail(t, bd, p.dir, "rom-does-not-exist")
if !strings.Contains(out, "not found") {
t.Errorf("expected 'not found' error, got: %s", out)
@ -153,7 +159,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reopens_wisp", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rorw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rorw")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp reopen", "--ephemeral")
bdProxiedClose(t, bd, p.dir, wisp.ID)
bdProxiedReopen(t, bd, p.dir, wisp.ID)
@ -186,7 +193,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("json_output", func(t *testing.T) {
p := bdProxiedInit(t, bd, "roj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "roj")
issue := bdProxiedCreate(t, bd, p.dir, "JSON reopen")
bdProxiedClose(t, bd, p.dir, issue.ID)
issues := bdProxiedReopenJSON(t, bd, p.dir, issue.ID)
@ -199,7 +207,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("batch_single_dolt_commit", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rosd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rosd")
a := bdProxiedCreate(t, bd, p.dir, "Batch A")
b := bdProxiedCreate(t, bd, p.dir, "Batch B")
bdProxiedClose(t, bd, p.dir, a.ID, b.ID)
@ -222,7 +231,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reblocks_dependent", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rorb")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rorb")
blocker := bdProxiedCreate(t, bd, p.dir, "Reblock blocker")
blocked := bdProxiedCreate(t, bd, p.dir, "Reblock blocked", "--deps", "depends-on:"+blocker.ID)
bdProxiedClose(t, bd, p.dir, blocker.ID)
@ -237,7 +247,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reopen_with_reason_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rorrs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rorrs")
issue := bdProxiedCreate(t, bd, p.dir, "Short reason target")
bdProxiedClose(t, bd, p.dir, issue.ID)
bdProxiedReopen(t, bd, p.dir, issue.ID, "-r", "needs more work")
@ -251,7 +262,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("reopen_clears_defer_until", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rocd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rocd")
issue := bdProxiedCreate(t, bd, p.dir, "Deferred reopen", "--defer", "+8760h")
bdProxiedClose(t, bd, p.dir, issue.ID)
bdProxiedReopen(t, bd, p.dir, issue.ID)
@ -270,7 +282,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("last_touched_not_supported", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rolt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rolt")
_ = bdProxiedCreate(t, bd, p.dir, "Recent create")
out := bdProxiedReopenFail(t, bd, p.dir)
if !strings.Contains(out, "requires at least 1 arg") {
@ -279,12 +292,13 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("hooks_fire_on_update", func(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("hook script form is POSIX shell")
}
marker := filepath.Join(t.TempDir(), "on_update_marker")
script := "#!/bin/sh\nprintf '%s\\n' \"$1\" > " + shellQuote(marker) + "\n"
p := bdProxiedInitWithHooks(t, bd, "rofh", map[string]string{"on_update": script})
p := newSharedProxiedProjectWithHooks(t, bd, "rofh", map[string]string{"on_update": script})
issue := bdProxiedCreate(t, bd, p.dir, "Hook reopen")
bdProxiedClose(t, bd, p.dir, issue.ID)
_ = os.Remove(marker)
@ -299,7 +313,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("wisp_reopen_clears_defer_until", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rowd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rowd")
wisp := bdProxiedCreate(t, bd, p.dir, "Deferred wisp", "--ephemeral", "--defer", "+8760h")
bdProxiedClose(t, bd, p.dir, wisp.ID)
bdProxiedReopen(t, bd, p.dir, wisp.ID)
@ -315,7 +330,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("wisp_reason_recorded_as_comment", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rowr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rowr")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp reason", "--ephemeral")
bdProxiedClose(t, bd, p.dir, wisp.ID)
bdProxiedReopen(t, bd, p.dir, wisp.ID, "--reason", "wisp regression")
@ -326,7 +342,8 @@ func TestProxiedServerReopen(t *testing.T) {
})
t.Run("wisp_reopen_with_reason_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "rowrs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "rowrs")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp short reason", "--ephemeral")
bdProxiedClose(t, bd, p.dir, wisp.ID)
bdProxiedReopen(t, bd, p.dir, wisp.ID, "-r", "still flaky")
@ -346,10 +363,11 @@ func TestProxiedServerReopen(t *testing.T) {
}
func TestProxiedServerReopenConcurrent(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "rxc")
p := newSharedProxiedProject(t, bd, "rxc")
const (
numWorkers = 10

View file

@ -61,11 +61,12 @@ func searchResultIDs(results []map[string]interface{}) map[string]bool {
}
func TestProxiedServerSearch(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "sp")
p := newSharedProxiedProject(t, bd, "sp")
taskA := bdProxiedCreate(t, bd, p.dir, "Alpha task", "--type", "task", "--priority", "1", "--assignee", "alice", "--description", "Important alpha work", "--label", "urgent")
taskB := bdProxiedCreate(t, bd, p.dir, "Beta bug", "--type", "bug", "--priority", "3", "--assignee", "bob", "--description", "Beta bug description", "--label", "backend")
taskC := bdProxiedCreate(t, bd, p.dir, "Gamma feature", "--type", "feature", "--priority", "2", "--label", "urgent", "--label", "frontend")
@ -330,7 +331,7 @@ func TestProxiedServerSearch(t *testing.T) {
})
t.Run("wisp_appears_in_search", func(t *testing.T) {
wp := bdProxiedInit(t, bd, "sw")
wp := newSharedProxiedProject(t, bd, "sw")
wisp := bdProxiedCreate(t, bd, wp.dir, "Wispy alpha search target", "--ephemeral")
if !searchResultIDs(bdProxiedSearchJSON(t, bd, wp.dir, "Wispy"))[wisp.ID] {
t.Errorf("expected ephemeral wisp %s to appear in search results", wisp.ID)
@ -338,7 +339,7 @@ func TestProxiedServerSearch(t *testing.T) {
})
t.Run("wisp_labels_hydrated_from_wisp_labels", func(t *testing.T) {
wp := bdProxiedInit(t, bd, "swl")
wp := newSharedProxiedProject(t, bd, "swl")
wisp := bdProxiedCreate(t, bd, wp.dir, "Wisp label search", "--ephemeral")
bdProxiedLabel(t, bd, wp.dir, "add", wisp.ID, "wlabel")

View file

@ -13,11 +13,13 @@ import (
)
func TestProxiedServerShow(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("show_single_issue", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ssi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ssi")
issue := bdProxiedCreate(t, bd, p.dir, "Show me", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID)
@ -30,7 +32,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_multiple_issues", func(t *testing.T) {
p := bdProxiedInit(t, bd, "smi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "smi")
issue1 := bdProxiedCreate(t, bd, p.dir, "Multi 1", "--type", "task")
issue2 := bdProxiedCreate(t, bd, p.dir, "Multi 2", "--type", "task")
@ -44,14 +47,16 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_nonexistent_id_exits_nonzero", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sne")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sne")
stdout, stderr := bdProxiedShowFail(t, bd, p.dir, "sne-nonexistent999")
_ = stdout
_ = stderr
})
t.Run("show_no_args_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sna")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sna")
stdout, stderr := bdProxiedShowFail(t, bd, p.dir)
combined := stdout + stderr
if !strings.Contains(combined, "at least one issue ID") {
@ -60,7 +65,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_fields_round_trip", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjf")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjf")
issue := bdProxiedCreate(t, bd, p.dir, "JSON show", "--type", "task",
"--description", "A description", "-p", "1")
@ -86,7 +92,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_includes_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjl")
issue := bdProxiedCreate(t, bd, p.dir, "Labeled show", "--type", "task", "-l", "bug")
m := bdProxiedShowDetailsFirst(t, bd, p.dir, issue.ID)
@ -106,7 +113,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_includes_dependencies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjd")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjd")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker", "--type", "task")
blocked := bdProxiedCreate(t, bd, p.dir, "Blocked",
"--type", "task", "--deps", "blocked-by:"+blocker.ID)
@ -126,7 +134,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_count_fields_default", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjc")
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker", "--type", "task")
blocked := bdProxiedCreate(t, bd, p.dir, "Blocked",
"--type", "task", "--deps", "blocked-by:"+blocker.ID)
@ -153,7 +162,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_includes_comments_under_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjic")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjic")
issue := bdProxiedCreate(t, bd, p.dir, "Commented", "--type", "task")
db := openProxiedDB(t, p)
@ -173,7 +183,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_includes_dependents_under_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjidep")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjidep")
hub := bdProxiedCreate(t, bd, p.dir, "Hub", "--type", "task")
bdProxiedCreate(t, bd, p.dir, "Spoke 1", "--type", "task", "--deps", "blocked-by:"+hub.ID)
bdProxiedCreate(t, bd, p.dir, "Spoke 2", "--type", "task", "--deps", "blocked-by:"+hub.ID)
@ -191,7 +202,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_epic_progress", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjep")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjep")
epic := bdProxiedCreate(t, bd, p.dir, "Epic progress", "--type", "epic")
child1 := bdProxiedCreate(t, bd, p.dir, "Epic child 1", "--type", "task", "--parent", epic.ID)
bdProxiedCreate(t, bd, p.dir, "Epic child 2", "--type", "task", "--parent", epic.ID)
@ -215,7 +227,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_json_parent_derived", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sjp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sjp")
parent := bdProxiedCreate(t, bd, p.dir, "Parent", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child", "--type", "task", "--parent", parent.ID)
@ -226,7 +239,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "ssh")
t.Parallel()
p := newSharedProxiedProject(t, bd, "ssh")
issue := bdProxiedCreate(t, bd, p.dir, "Short show", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID, "--short")
lines := strings.Split(strings.TrimSpace(out), "\n")
@ -239,7 +253,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_long", func(t *testing.T) {
p := bdProxiedInit(t, bd, "slong")
t.Parallel()
p := newSharedProxiedProject(t, bd, "slong")
issue := bdProxiedCreate(t, bd, p.dir, "Long show", "--type", "task",
"--description", "Desc", "--assignee", "alice")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID, "--long")
@ -249,7 +264,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_id_flag", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sid")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sid")
issue := bdProxiedCreate(t, bd, p.dir, "ID flag test", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, "--id", issue.ID, "--short")
@ -269,7 +285,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_local_time_no_error", func(t *testing.T) {
p := bdProxiedInit(t, bd, "slt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "slt")
issue := bdProxiedCreate(t, bd, p.dir, "Local time", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID, "--local-time")
if !strings.Contains(out, "Local time") {
@ -278,7 +295,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_external_ref_rendered", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sxr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sxr")
issue := bdProxiedCreate(t, bd, p.dir, "External ref test",
"--type", "task", "--external-ref", "https://example.com/spec.md")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID)
@ -291,7 +309,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_no_external_ref_omits_line", func(t *testing.T) {
p := bdProxiedInit(t, bd, "snx")
t.Parallel()
p := newSharedProxiedProject(t, bd, "snx")
issue := bdProxiedCreate(t, bd, p.dir, "No ref test", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID)
if strings.Contains(out, "External:") {
@ -300,7 +319,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_not_found_json_envelope", func(t *testing.T) {
p := bdProxiedInit(t, bd, "snj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "snj")
stdout, _ := bdProxiedShowFail(t, bd, p.dir, "snj-bogus", "--json")
if stdout == "" {
t.Fatal("expected JSON error on stdout, got empty")
@ -315,7 +335,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("view_alias_dispatches_to_proxied", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sva")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sva")
issue := bdProxiedCreate(t, bd, p.dir, "View alias", "--type", "task")
out, err := bdProxiedRun(t, bd, p.dir, "view", issue.ID, "--short")
if err != nil {
@ -327,7 +348,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_concurrent_json_and_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scn")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scn")
const (
numWorkers = 8
issuesPerWorker = 3
@ -375,7 +397,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_wisp_id_routes_to_wisp_uc", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swr")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp default", "--type", "task", "--ephemeral")
out := bdProxiedShowRaw(t, bd, p.dir, wisp.ID)
@ -393,7 +416,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_refs_lists_referrers", func(t *testing.T) {
p := bdProxiedInit(t, bd, "srl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "srl")
parent := bdProxiedCreate(t, bd, p.dir, "Refs parent", "--type", "task")
child := bdProxiedCreate(t, bd, p.dir, "Refs child",
"--type", "task", "--deps", "blocked-by:"+parent.ID)
@ -405,7 +429,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_refs_groups_by_type", func(t *testing.T) {
p := bdProxiedInit(t, bd, "srg")
t.Parallel()
p := newSharedProxiedProject(t, bd, "srg")
hub := bdProxiedCreate(t, bd, p.dir, "Refs hub", "--type", "task")
bdProxiedCreate(t, bd, p.dir, "Blocker A",
"--type", "task", "--deps", "blocked-by:"+hub.ID)
@ -422,7 +447,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_refs_empty", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sre")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sre")
issue := bdProxiedCreate(t, bd, p.dir, "No refs", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID, "--refs")
if !strings.Contains(out, "No references found") {
@ -431,7 +457,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_refs_json_map_shape", func(t *testing.T) {
p := bdProxiedInit(t, bd, "srj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "srj")
parent := bdProxiedCreate(t, bd, p.dir, "Refs parent J", "--type", "task")
child := bdProxiedCreate(t, bd, p.dir, "Refs child J",
"--type", "task", "--deps", "blocked-by:"+parent.ID)
@ -464,7 +491,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_wisp_refs", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swrefs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swrefs")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp ref target", "--type", "task", "--ephemeral")
referrer := bdProxiedCreate(t, bd, p.dir, "Wisp referrer",
"--type", "task", "--ephemeral", "--deps", "blocked-by:"+wisp.ID)
@ -476,7 +504,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_children", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sc")
parent := bdProxiedCreate(t, bd, p.dir, "Children parent", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Children child",
"--type", "task", "--parent", parent.ID)
@ -488,7 +517,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_children_empty", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sce")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sce")
issue := bdProxiedCreate(t, bd, p.dir, "No children", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, issue.ID, "--children")
if !strings.Contains(out, "No children found") {
@ -497,7 +527,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_children_short", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scs")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scs")
parent := bdProxiedCreate(t, bd, p.dir, "Parent S", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child S",
"--type", "task", "--parent", parent.ID)
@ -509,7 +540,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_children_json_map_shape", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scj")
parent := bdProxiedCreate(t, bd, p.dir, "Parent J", "--type", "epic")
child := bdProxiedCreate(t, bd, p.dir, "Child J",
"--type", "task", "--parent", parent.ID)
@ -545,7 +577,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_wisp_children", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swc")
epicW := bdProxiedCreate(t, bd, p.dir, "Wisp epic", "--type", "epic", "--ephemeral")
childW := bdProxiedCreate(t, bd, p.dir, "Wisp child",
"--type", "task", "--ephemeral", "--parent", epicW.ID)
@ -557,7 +590,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_as_of_historical_title", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sao")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sao")
issue := bdProxiedCreate(t, bd, p.dir, "AsOf original", "--type", "task")
hash := proxiedCurrentCommit(t, p)
@ -574,7 +608,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_as_of_invalid_ref_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "saoi")
t.Parallel()
p := newSharedProxiedProject(t, bd, "saoi")
issue := bdProxiedCreate(t, bd, p.dir, "AsOf invalid", "--type", "task")
_, stderr, _ := bdProxiedRunBuffers(t, bd, p.dir, "show", issue.ID, "--as-of", "'; DROP TABLE issues; --")
@ -584,7 +619,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_as_of_short_mode", func(t *testing.T) {
p := bdProxiedInit(t, bd, "saos")
t.Parallel()
p := newSharedProxiedProject(t, bd, "saos")
issue := bdProxiedCreate(t, bd, p.dir, "AsOf short", "--type", "task")
hash := proxiedCurrentCommit(t, p)
bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--title", "AsOf short updated")
@ -599,7 +635,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_as_of_json_array", func(t *testing.T) {
p := bdProxiedInit(t, bd, "saoj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "saoj")
issue := bdProxiedCreate(t, bd, p.dir, "AsOf JSON", "--type", "task")
hash := proxiedCurrentCommit(t, p)
bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--title", "AsOf JSON updated")
@ -614,7 +651,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_thread_walks_to_root", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sthr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sthr")
root := bdProxiedCreate(t, bd, p.dir, "Root msg", "--type", "task")
mid := bdProxiedCreate(t, bd, p.dir, "Mid reply",
"--type", "task", "--deps", "replies-to:"+root.ID)
@ -630,7 +668,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_thread_collects_replies", func(t *testing.T) {
p := bdProxiedInit(t, bd, "stbr")
t.Parallel()
p := newSharedProxiedProject(t, bd, "stbr")
root := bdProxiedCreate(t, bd, p.dir, "Branch root", "--type", "task")
a := bdProxiedCreate(t, bd, p.dir, "Reply A",
"--type", "task", "--deps", "replies-to:"+root.ID)
@ -648,7 +687,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_thread_json_emits_array", func(t *testing.T) {
p := bdProxiedInit(t, bd, "stj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "stj")
root := bdProxiedCreate(t, bd, p.dir, "Thread JSON root", "--type", "task")
reply := bdProxiedCreate(t, bd, p.dir, "Thread JSON reply",
"--type", "task", "--deps", "replies-to:"+root.ID)
@ -676,7 +716,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_thread_orphan_message_renders_alone", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sto")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sto")
orphan := bdProxiedCreate(t, bd, p.dir, "Orphan msg", "--type", "task")
out := bdProxiedShowRaw(t, bd, p.dir, orphan.ID, "--thread")
if !strings.Contains(out, orphan.ID) {
@ -688,7 +729,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_current_with_in_progress", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scur")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scur")
issue := bdProxiedCreate(t, bd, p.dir, "In progress", "--type", "task")
bdProxiedUpdateOne(t, bd, p.dir, issue.ID,
"--status", "in_progress", "--assignee", "alice", "--actor", "alice")
@ -703,7 +745,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_current_prefers_in_progress_over_hooked", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scp")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scp")
hooked := bdProxiedCreate(t, bd, p.dir, "Hooked one", "--type", "task")
inProg := bdProxiedCreate(t, bd, p.dir, "InProg one", "--type", "task")
bdProxiedUpdateOne(t, bd, p.dir, hooked.ID,
@ -724,7 +767,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_current_with_id_fails", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scid")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scid")
issue := bdProxiedCreate(t, bd, p.dir, "Conflict", "--type", "task")
stdout, stderr := bdProxiedShowFail(t, bd, p.dir, "--current", issue.ID)
combined := stdout + stderr
@ -734,7 +778,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_current_no_match_errors", func(t *testing.T) {
p := bdProxiedInit(t, bd, "scnm")
t.Parallel()
p := newSharedProxiedProject(t, bd, "scnm")
stdout, stderr := bdProxiedShowFail(t, bd, p.dir, "--current")
combined := stdout + stderr
if !strings.Contains(combined, "no current issue found") {
@ -743,7 +788,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_watch_rejected_in_proxied_mode", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swt")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swt")
issue := bdProxiedCreate(t, bd, p.dir, "Watch test", "--type", "task")
stdout, stderr := bdProxiedShowFail(t, bd, p.dir, issue.ID, "--watch")
combined := stdout + stderr
@ -753,7 +799,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_wisp_comments_default_count_only", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swcc")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swcc")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp w/comments", "--type", "task", "--ephemeral")
db := openProxiedDB(t, p)
@ -778,7 +825,8 @@ func TestProxiedServerShow(t *testing.T) {
})
t.Run("show_wisp_comments_include_streams", func(t *testing.T) {
p := bdProxiedInit(t, bd, "swci")
t.Parallel()
p := newSharedProxiedProject(t, bd, "swci")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp stream", "--type", "task", "--ephemeral")
db := openProxiedDB(t, p)

View file

@ -15,7 +15,7 @@ var sqlCmd = &cobra.Command{
Use: "sql <query>",
GroupID: "maint",
Short: "Execute raw SQL against the beads database",
Long: `Execute a raw SQL query against the underlying database (SQLite or Dolt).
Long: `Execute a raw SQL query against the underlying database (Dolt).
Useful for debugging, maintenance, and working around bugs in higher-level commands.

View file

@ -46,9 +46,10 @@ func bdProxiedSQLFail(t *testing.T, bd, dir string, args ...string) string {
}
func TestProxiedServerSQL(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := bdProxiedInit(t, bd, "sql")
p := newSharedProxiedProject(t, bd, "sql")
one := bdProxiedCreate(t, bd, p.dir, "Test issue one", "--type", "task", "--priority", "1")
two := bdProxiedCreate(t, bd, p.dir, "Test issue two", "--type", "bug", "--priority", "2")

View file

@ -9,11 +9,13 @@ import (
)
func TestProxiedServerState(t *testing.T) {
requireProxiedServerEnv(t)
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("state_query", func(t *testing.T) {
p := bdProxiedInit(t, bd, "st")
t.Parallel()
p := newSharedProxiedProject(t, bd, "st")
issue := bdProxiedCreate(t, bd, p.dir, "State target")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "patrol:active")
@ -27,7 +29,8 @@ func TestProxiedServerState(t *testing.T) {
})
t.Run("state_query_unset", func(t *testing.T) {
p := bdProxiedInit(t, bd, "su")
t.Parallel()
p := newSharedProxiedProject(t, bd, "su")
issue := bdProxiedCreate(t, bd, p.dir, "No state")
out, _, err := bdProxiedRunBuffers(t, bd, p.dir, "state", issue.ID, "mode")
if err != nil {
@ -39,7 +42,8 @@ func TestProxiedServerState(t *testing.T) {
})
t.Run("state_query_json", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sj")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sj")
issue := bdProxiedCreate(t, bd, p.dir, "State json")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "mode:degraded")
@ -61,7 +65,8 @@ func TestProxiedServerState(t *testing.T) {
})
t.Run("state_list", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sl")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sl")
issue := bdProxiedCreate(t, bd, p.dir, "State list target")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "patrol:active,mode:normal")
@ -75,7 +80,8 @@ func TestProxiedServerState(t *testing.T) {
})
t.Run("state_list_empty", func(t *testing.T) {
p := bdProxiedInit(t, bd, "se")
t.Parallel()
p := newSharedProxiedProject(t, bd, "se")
issue := bdProxiedCreate(t, bd, p.dir, "No labels")
out, _, err := bdProxiedRunBuffers(t, bd, p.dir, "state", "list", issue.ID)
if err != nil {
@ -87,7 +93,8 @@ func TestProxiedServerState(t *testing.T) {
})
t.Run("state_reads_wisp_labels", func(t *testing.T) {
p := bdProxiedInit(t, bd, "sw")
t.Parallel()
p := newSharedProxiedProject(t, bd, "sw")
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp state", "--ephemeral")
bdProxiedLabel(t, bd, p.dir, "add", wisp.ID, "patrol:muted")

View file

@ -15,9 +15,6 @@ import (
"github.com/steveyegge/beads/internal/storage/dbproxy/util"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
beadsmysql "github.com/steveyegge/beads/internal/storage/mysql"
"github.com/steveyegge/beads/internal/storage/postgres"
beadssqlite "github.com/steveyegge/beads/internal/storage/sqlite"
)
func usesSQLServer() bool {
@ -110,14 +107,8 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS
// metadata.json (cfg == nil, err == nil) keeps the embedded default.
return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres {
return postgres.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL {
return beadsmysql.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite {
return beadssqlite.NewFromConfig(ctx, beadsDir)
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
if cfg != nil && cfg.IsDoltProxiedServerMode() {
// TODO: this needs to be uow provider
@ -199,17 +190,8 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D
// "database not found" the embedded open would produce.
return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres {
// Postgres has no read-only open mode in the wedge; a normal open is fine
// (reads don't mutate, and search_path is per-workspace).
return postgres.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL {
// MySQL likewise has no separate read-only open in the wedge; reads don't mutate.
return beadsmysql.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite {
return beadssqlite.NewFromConfig(ctx, beadsDir)
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
if cfg != nil && cfg.IsDoltProxiedServerMode() {
// TODO: this needs to be uow provider

View file

@ -10,9 +10,6 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dbproxy/util"
"github.com/steveyegge/beads/internal/storage/dolt"
beadsmysql "github.com/steveyegge/beads/internal/storage/mysql"
"github.com/steveyegge/beads/internal/storage/postgres"
beadssqlite "github.com/steveyegge/beads/internal/storage/sqlite"
)
func usesSQLServer() bool {
@ -57,17 +54,8 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS
// message below.
return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres {
// Postgres needs no CGO (pure-Go pgx), so it works in the nocgo build too.
return postgres.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL {
// MySQL (go-sql-driver) needs no CGO either.
return beadsmysql.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite {
// SQLite (modernc.org/sqlite) is pure-Go; no CGO.
return beadssqlite.NewFromConfig(ctx, beadsDir)
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
if cfg != nil && cfg.IsDoltProxiedServerMode() {
// TODO: this needs to be uow provider
@ -90,14 +78,8 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D
if err != nil {
return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres {
return postgres.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL {
return beadsmysql.NewFromConfig(ctx, beadsDir)
}
if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite {
return beadssqlite.NewFromConfig(ctx, beadsDir)
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
if cfg != nil && cfg.IsDoltProxiedServerMode() {
// TODO: this needs to be uow provider

View file

@ -0,0 +1,420 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/configfile"
)
func TestCommandStartupRejectsRemovedBackendsBeforeLocalWrites(t *testing.T) {
bd := buildBDForInitTests(t)
for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} {
t.Run(backend, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("create beads dir: %v", err)
}
if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil {
t.Fatalf("save config: %v", err)
}
cmd := exec.Command(bd, "list", "--json")
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("removed backend %s unexpectedly opened", backend)
}
message := strings.ToLower(string(out))
for _, want := range removedBackendWantSubstrings(backend) {
if !strings.Contains(message, want) {
t.Errorf("startup error for %s missing %q: %s", backend, want, message)
}
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} {
path := filepath.Join(beadsDir, name)
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("removed backend %s created local state at %s (stat error: %v)", backend, path, statErr)
}
}
})
}
}
func TestCommandStartupRejectsUnknownBackendBeforeLocalWrites(t *testing.T) {
bd := buildBDForInitTests(t)
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
if err := (&configfile.Config{Backend: "mystery"}).Save(beadsDir); err != nil {
t.Fatalf("save unknown-backend metadata: %v", err)
}
cmd := exec.Command(bd, "list", "--json")
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("unknown backend unexpectedly opened:\n%s", out)
}
message := string(out)
if strings.Contains(message, "no beads database found") {
t.Fatalf("unknown backend stopped at generic discovery instead of metadata guidance:\n%s", out)
}
for _, want := range []string{"not recognized", "opened or modified", "dolt"} {
if !strings.Contains(message, want) {
t.Errorf("unknown-backend error missing %q:\n%s", want, out)
}
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} {
if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) {
t.Fatalf("unknown backend created %s (stat error: %v)", name, statErr)
}
}
}
func TestInitGuardRejectsCorruptMetadataBeforeWorkspaceWrites(t *testing.T) {
beadsDir := filepath.Join(t.TempDir(), ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
metadata := []byte("{\n")
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write corrupt metadata.json: %v", err)
}
err := checkExistingBeadsDataAt(beadsDir, "guard")
if err == nil || !strings.Contains(err.Error(), "metadata.json") {
t.Fatalf("init guard error = %v, want corrupt metadata refusal", err)
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read metadata after refusal: %v", readErr)
}
if string(after) != string(metadata) {
t.Fatalf("init guard rewrote corrupt metadata: before %q, after %q", metadata, after)
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} {
if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) {
t.Fatalf("init guard created %s (stat error: %v)", name, statErr)
}
}
}
func TestDoctorRejectsUnknownBackendBeforeDoltChecks(t *testing.T) {
bd := buildBDForInitTests(t)
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
cfg := &configfile.Config{
Backend: "mystery",
DoltMode: configfile.DoltModeServer,
DoltServerHost: "127.0.0.1",
DoltServerPort: 1,
}
if err := cfg.Save(beadsDir); err != nil {
t.Fatalf("save unknown-backend metadata: %v", err)
}
cmd := exec.Command(bd, "doctor", "--server", "--json")
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BEADS_DOLT_AUTO_START=0", "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("doctor unexpectedly ran Dolt checks for unknown backend:\n%s", out)
}
for _, want := range []string{"not recognized", "no storage database was opened or modified", "dolt"} {
if !strings.Contains(string(out), want) {
t.Errorf("doctor unknown-backend error missing %q:\n%s", want, out)
}
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", "dolt-server.pid", "dolt-server.port"} {
if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) {
t.Fatalf("doctor created %s for unknown backend (stat error: %v)", name, statErr)
}
}
}
func TestLegacyInitFlagsReachRemovedBackendGuidance(t *testing.T) {
bd := buildBDForInitTests(t)
tests := []struct {
backend string
args []string
wants []string
}{
{
backend: configfile.BackendPostgres,
args: []string{
"init", "--backend=postgres",
"--pg-url=postgres://beads@127.0.0.1:5432/beads",
"--pg-schema=legacy_workspace",
},
wants: []string{"no longer supported", "general-purpose server databases", "simple and resource-light", "dolt"},
},
{
backend: configfile.BackendMySQL,
args: []string{
"init", "--backend=mysql",
"--mysql-url=beads@tcp(127.0.0.1:3306)/",
"--mysql-database=legacy_workspace",
},
wants: []string{"no longer supported", "general-purpose server databases", "simple and resource-light", "dolt"},
},
{
backend: configfile.BackendSQLite,
args: []string{
"init", "--backend=sqlite",
"--sqlite-path=beads.db",
},
wants: []string{"no longer supported", "single engine", "dolt"},
},
}
for _, tt := range tests {
t.Run(tt.backend, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
cmd := exec.Command(bd, tt.args...)
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("legacy %s init unexpectedly succeeded: %s", tt.backend, out)
}
message := string(out)
if strings.Contains(message, "unknown flag") {
t.Errorf("legacy %s init stopped at argument parsing instead of rollback guidance: %s", tt.backend, message)
}
for _, want := range tt.wants {
if !strings.Contains(message, want) {
t.Errorf("legacy %s init error missing %q: %s", tt.backend, want, message)
}
}
if _, statErr := os.Stat(beadsDir); !os.IsNotExist(statErr) {
t.Fatalf("rejected legacy %s init created workspace state (stat error: %v)", tt.backend, statErr)
}
})
}
}
func TestDoltAdministrativeCommandsRejectRemovedBackends(t *testing.T) {
bd := buildBDForInitTests(t)
commands := []struct {
name string
args []string
}{
{name: "show", args: []string{"dolt", "show"}},
{name: "status", args: []string{"dolt", "status"}},
{name: "set", args: []string{"dolt", "set", "host", "127.0.0.1"}},
{name: "test", args: []string{"dolt", "test"}},
{name: "start", args: []string{"dolt", "start"}},
{name: "stop", args: []string{"dolt", "stop"}},
{name: "killall", args: []string{"dolt", "killall"}},
{name: "clean-databases", args: []string{"dolt", "clean-databases", "--dry-run"}},
}
for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} {
t.Run(backend, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("create beads dir: %v", err)
}
if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil {
t.Fatalf("save config: %v", err)
}
for _, command := range commands {
t.Run(command.name, func(t *testing.T) {
cmd := exec.Command(bd, command.args...)
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("%q unexpectedly succeeded for removed backend %s: %s", strings.Join(command.args, " "), backend, out)
}
message := strings.ToLower(string(out))
for _, want := range removedBackendWantSubstrings(backend) {
if !strings.Contains(message, want) {
t.Errorf("%q error for %s missing %q: %s", strings.Join(command.args, " "), backend, want, message)
}
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} {
path := filepath.Join(beadsDir, name)
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("%q created local state for removed backend %s at %s (stat error: %v)", strings.Join(command.args, " "), backend, path, statErr)
}
}
})
}
})
}
}
func TestDoltReadOnlyCommandsRejectUnknownBackend(t *testing.T) {
bd := buildBDForInitTests(t)
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
if err := (&configfile.Config{Backend: "mystery", DoltMode: configfile.DoltModeServer, DoltServerPort: 1}).Save(beadsDir); err != nil {
t.Fatalf("save unknown-backend metadata: %v", err)
}
for _, args := range [][]string{{"dolt", "show"}, {"dolt", "status"}, {"dolt", "killall"}} {
cmd := exec.Command(bd, args...)
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir), "BEADS_DOLT_AUTO_START=0", "BD_DISABLE_METRICS=1")
out, err := cmd.CombinedOutput()
if err == nil {
t.Errorf("bd %s unexpectedly treated unknown metadata as Dolt:\n%s", strings.Join(args, " "), out)
continue
}
if !strings.Contains(string(out), "not recognized") || !strings.Contains(string(out), "opened or modified") {
t.Errorf("bd %s error lacks fail-closed guidance:\n%s", strings.Join(args, " "), out)
}
}
}
func TestDoltKillallRejectsCorruptMetadataBeforeServerCleanup(t *testing.T) {
bd := buildBDForInitTests(t)
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("create .beads: %v", err)
}
metadata := []byte("{\n")
metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName)
if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil {
t.Fatalf("write corrupt metadata: %v", err)
}
cmd := exec.Command(bd, "dolt", "killall")
cmd.Dir = root
cmd.Env = append(removedBackendTestEnv(beadsDir),
"BEADS_DOLT_SHARED_SERVER=1",
"BEADS_DOLT_AUTO_START=0",
"BEADS_SHARED_SERVER_DIR="+filepath.Join(root, "shared-server"),
"BD_DISABLE_METRICS=1",
)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("bd dolt killall unexpectedly ignored corrupt metadata:\n%s", out)
}
message := strings.ToLower(string(out))
for _, want := range []string{"loading config", "parsing config"} {
if !strings.Contains(message, want) {
t.Errorf("bd dolt killall corrupt-metadata error missing %q:\n%s", want, out)
}
}
after, readErr := os.ReadFile(metadataPath)
if readErr != nil {
t.Fatalf("read metadata after refusal: %v", readErr)
}
if string(after) != string(metadata) {
t.Fatalf("bd dolt killall rewrote corrupt metadata: before %q, after %q", metadata, after)
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version", "dolt-server.pid", "dolt-server.port"} {
if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) {
t.Fatalf("bd dolt killall created %s before rejecting corrupt metadata (stat error: %v)", name, statErr)
}
}
}
func removedBackendTestEnv(beadsDir string) []string {
var env []string
for _, entry := range os.Environ() {
if strings.HasPrefix(entry, "BEADS_") || strings.HasPrefix(entry, "BD_") {
continue
}
env = append(env, entry)
}
return append(env, "BEADS_DIR="+beadsDir)
}
func TestStoreFactoriesRemovedBackendsFailLoud(t *testing.T) {
for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} {
t.Run(backend, func(t *testing.T) {
beadsDir := t.TempDir()
cfg := &configfile.Config{Backend: backend}
if err := cfg.Save(beadsDir); err != nil {
t.Fatalf("save config: %v", err)
}
factories := map[string]func(context.Context, string) (interface{ Close() error }, error){
"read-write": func(ctx context.Context, dir string) (interface{ Close() error }, error) {
return newDoltStoreFromConfig(ctx, dir)
},
"read-only": func(ctx context.Context, dir string) (interface{ Close() error }, error) {
return newReadOnlyStoreFromConfig(ctx, dir)
},
}
for name, open := range factories {
t.Run(name, func(t *testing.T) {
store, err := open(t.Context(), beadsDir)
if err == nil {
if store != nil {
_ = store.Close()
}
t.Fatalf("expected removed-backend error for %s", backend)
}
if !strings.Contains(err.Error(), "no longer supported") {
t.Fatalf("error should explain that %s is no longer supported: %v", backend, err)
}
guidance := strings.ToLower(err.Error())
if !strings.Contains(guidance, "export") || !strings.Contains(guidance, "dolt") {
t.Fatalf("error should provide safe migration guidance: %v", err)
}
for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} {
path := filepath.Join(beadsDir, name)
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("removed backend %s created local storage at %s (stat error: %v)", backend, path, statErr)
}
}
})
}
})
}
}
func TestRequireDoltBackend(t *testing.T) {
for _, cfg := range []*configfile.Config{nil, {}, {Backend: configfile.BackendDolt}} {
if err := requireDoltBackend(cfg); err != nil {
t.Fatalf("Dolt config %#v rejected: %v", cfg, err)
}
}
for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} {
err := requireDoltBackend(&configfile.Config{Backend: backend})
if err == nil || !strings.Contains(err.Error(), "no longer supported") || !strings.Contains(err.Error(), "export") {
t.Fatalf("removed backend %q guard error = %v, want rollback and migration guidance", backend, err)
}
}
}
// removedBackendWantSubstrings returns the guidance substrings every removed-backend
// rejection must carry, including the backend-specific rationale marker.
func removedBackendWantSubstrings(backend string) []string {
wants := []string{"no longer supported", "was not opened", "export", "dolt"}
if backend == configfile.BackendSQLite {
return append(wants, "single engine")
}
return append(wants, "general-purpose server databases", "simple and resource-light")
}

129
cmd/bd/telemetry_redact.go Normal file
View file

@ -0,0 +1,129 @@
package main
import (
"net/url"
"regexp"
"sort"
"strings"
)
// These expressions recognize password-bearing libpq keyword/value tokens. The
// scrubber is intentionally backend-neutral: command-line telemetry may receive a
// connection string even when bd does not implement that connection's backend.
const dsnWhitespace = `\t\n\f\r \v`
var dsnPasswordValue = regexp.MustCompile(`(?i)(?:^|[` + dsnWhitespace + `])(?:password|sslpassword)[` + dsnWhitespace + `]*=[` + dsnWhitespace + `]*(?:'((?:[^'\\]|\\.)*)'|((?:[^` + dsnWhitespace + `\\]|\\.)+))`)
// A libpq keyword/value connection string begins with a recognized connection
// parameter. Requiring the first key to be recognized avoids treating ordinary
// prose such as "transport=rail password=..." as a DSN while still covering valid
// minimal forms such as "password=..." and service-file forms.
var dsnLeadingKeyword = regexp.MustCompile(`(?i)^[` + dsnWhitespace + `]*(?:application_name|channel_binding|client_encoding|connect_timeout|dbname|fallback_application_name|gssencmode|gsslib|host|hostaddr|keepalives|keepalives_count|keepalives_idle|keepalives_interval|krbsrvname|load_balance_hosts|options|passfile|password|port|replication|requirepeer|service|servicefile|sslcert|sslcrl|sslcrldir|sslkey|sslmode|sslpassword|sslrootcert|sslsni|ssl_max_protocol_version|ssl_min_protocol_version|target_session_attrs|tcp_user_timeout|user)[` + dsnWhitespace + `]*=`)
func scrubStructuredDSNPasswords(dsn, text string) string {
secrets := structuredDSNPasswords(dsn)
sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) })
for _, secret := range secrets {
text = strings.ReplaceAll(text, secret, "xxxxx")
}
return text
}
func scrubPotentialDSNPasswords(value string) string {
if strings.Contains(value, "://") {
return scrubStructuredDSNPasswords(value, value)
}
if dsnLeadingKeyword.MatchString(value) {
return scrubStructuredDSNPasswords(value, value)
}
return value
}
func structuredDSNPasswords(dsn string) []string {
seen := make(map[string]bool)
var values []string
add := func(value string) {
if value == "" || seen[value] {
return
}
seen[value] = true
values = append(values, value)
}
if parsed, err := url.Parse(dsn); err == nil && parsed.Scheme != "" {
if parsed.User != nil {
if password, ok := parsed.User.Password(); ok {
add(password)
add(rawURLUserinfoPassword(dsn))
}
}
}
// Extract query credentials independently of url.Parse. A malformed escape in
// the path, userinfo, or fragment makes url.Parse reject the entire URL even
// when the password query pair itself is valid. Telemetry redaction must fail
// closed in that case.
addRawURLQueryPasswords(dsn, add)
for _, match := range dsnPasswordValue.FindAllStringSubmatch(dsn, -1) {
add(match[1])
add(match[2])
}
return values
}
func addRawURLQueryPasswords(dsn string, add func(string)) {
queryStart := strings.IndexByte(dsn, '?')
if queryStart < 0 {
return
}
query := dsn[queryStart+1:]
if fragment := strings.IndexByte(query, '#'); fragment >= 0 {
query = query[:fragment]
}
for _, pair := range strings.Split(query, "&") {
key, value, ok := strings.Cut(pair, "=")
if !ok {
continue
}
decodedKey, err := url.QueryUnescape(key)
if err != nil {
decodedKey = key
}
if !isDSNPasswordKey(key) && !isDSNPasswordKey(decodedKey) {
continue
}
add(value)
if decoded, err := url.QueryUnescape(value); err == nil {
add(decoded)
}
}
}
func isDSNPasswordKey(key string) bool {
switch strings.ToLower(key) {
case "password", "sslpassword":
return true
default:
return false
}
}
func rawURLUserinfoPassword(dsn string) string {
scheme := strings.Index(dsn, "://")
if scheme < 0 {
return ""
}
authority := dsn[scheme+len("://"):]
if end := strings.IndexAny(authority, "/?#"); end >= 0 {
authority = authority[:end]
}
at := strings.LastIndex(authority, "@")
if at < 0 {
return ""
}
_, password, ok := strings.Cut(authority[:at], ":")
if !ok {
return ""
}
return password
}

Some files were not shown because too many files have changed in this diff Show more