* test: prevent Cobra command flag cache races
* chore: release gate PASS for be-psutr9 (cobra/pflag race-fix)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs(gate): update be-psutr9 gate — re-review PASS (be-mouz), fix stale file list
Re-review be-mouz confirmed PASS on current HEAD 1b5536624. Correct files
changed: stdio_race_guard_test.go + test_helpers_pure_test.go only (earlier
version listed notion_test.go/stale_test.go which are no longer in the diff).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: address PR review findings (bd-wrntbm)
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(dolt): adopt git origin on first push
bd dolt push now wires an existing git origin when no Dolt remote is configured, while init without origin stays local and doctor shows the concrete adoption command. This keeps refs/dolt/data sync discoverable without treating plain remotes as existing Dolt history.\n\n_kilocode-openai/gpt-5.5- on behalf of maphew_
* fix(dolt): address origin adoption review nits
Share Dolt remote URL normalization between the push adoption path and doctor guidance, fail before mutating Dolt state when no beads workspace is selected, and cover CheckRemoteConsistency's adoption detail.
_codex-gpt-5-medium on behalf of maphew_
Add a shared runCommandBuffers helper for embedded subprocess tests so the PR keeps stdout/stderr separation without repeating buffer setup in every JSON-output test.
_codex-gpt-5- on behalf of matt wilkie_
The stdout/stderr split in 88e13542e applied uniformly to every helper
and inline call site, but bd commands write user-facing status messages
to stderr, not stdout:
- cmd/bd/bootstrap.go:543: "Created fresh database" -> stderr
- cmd/bd/bootstrap.go:610: "Imported %d issues" -> stderr
- cmd/bd/import.go:270: "Imported %d issues" -> stderr
After the split, bdImport and the bootstrap inline tests returned only
stdout, so `strings.Contains(out, "Imported 2 issues")` and friends saw
empty (or plan-only) output. CI shard 5 (TestEmbeddedBootstrap) and
shard 11 (TestEmbeddedImport) failed for this reason.
Fix: have bdImport return stdout+stderr concatenated (matches its
"Returns combined output" docstring) and have the two inline subtests
in TestEmbeddedBootstrap grep a combined buffer. JSON-parsing helpers
keep returning stdout-only as the original PR intended; this only
restores the prior CombinedOutput contract for non-JSON text greps.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PR #3909 introduced an auto-export warning written to stderr. Tests that
called CombinedOutput() and then parsed the result as JSON would choke
on the warning text mixed into stdout.
Apply the pattern already established in list_embedded_test.go: for every
helper or inline call site that parses JSON or an ID from stdout, capture
stdout and stderr in separate bytes.Buffers and parse only stdout.
Covers 66 test files including duplicates, update, lint, todo, label,
count, swarm, close, list, status, types, find-duplicates, and more.
Closes TestEmbeddedDuplicates/dry_run and TestEmbeddedUpdate/update_json_output
failures from CI run 25967558419 and 25962887732.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Capture stdout and stderr separately in the embedded update JSON-output test.
Validate only stdout as JSON so post-run stderr advisories do not contaminate the parsed output.
`bd update <id> --external-ref ""` was writing an empty string into the
`external_ref` column instead of SQL NULL. The CLI builds an `updates`
map with `updates["external_ref"] = ""` and passes it straight through
to the storage layer, where `args = append(args, value)` sends the
empty string to the SQL driver verbatim.
`bd create` already handles this correctly: `buildCreateIssue` converts
an empty `ExternalRef` string to a nil `*string`, so newly created
issues round-trip as NULL when no ref is given. The update path didn't
mirror that conversion, leaving the database with two semantically
different "no external ref" states.
Downstream consequences:
- `internal/tracker/engine.go` treats `localIssue.ExternalRef == nil`
as "not linked" but compares the empty string as a real value, so a
cleared ref looked like a link to a non-existent record.
- `types.Issue.ExternalRef` is `*string` with `json:",omitempty"`, so
cleared issues emitted `"external_ref":""` while never-set issues
omitted the field entirely.
- The historical UNIQUE-constraint repro in #3902 only didn't fire
today because the SQLite backend that had the constraint was
removed; the empty-string semantic mismatch was the durable bug.
Fix in `cmd/bd/update.go`: when `--external-ref` is set to "", store
nil in the updates map, which the SQL driver translates to NULL.
Defensive fix in `internal/storage/dolt/ephemeral_routing.go`:
`applyUpdatesToIssueStruct` (used on wisp/no_history flips) previously
ignored a nil value because the `value.(string)` type assertion failed
silently, leaving the in-memory `ExternalRef` at its prior value.
Handle nil explicitly so the wisp-flip path agrees with the regular
update path.
Test: new `update_external_ref_clear` subtest in
`cmd/bd/update_embedded_test.go` verifies that clearing two refs in a
row succeeds (the historical UNIQUE repro), that `ExternalRef` reads
back as nil, and that the JSON output omits the field rather than
emitting `"external_ref":""`.
Refs #3902
Co-authored-by: Cursor <cursoragent@cursor.com>
Before this fix, `runWispCreate` unconditionally forced `rootOnly = true`
whenever the formula didn't set `pour=true`:
if !rootOnly && subgraph != nil && !subgraph.Pour {
rootOnly = true
}
Since vapor-phase formulas (the natural fit for wisps) don't set
`pour=true`, every reasonable `bd mol wisp <formula>` call collapsed to
root-only — making the advertised `--root-only` opt-out flag a no-op and
breaking ephemeral lifecycle testing of multi-step formulas, as reported
in #3872.
The plumbing for ephemeral children was already in place:
`spawnMoleculeWithOptions` propagates `opts.Ephemeral` to every child
issue (template.go:596). The fix is just deleting the override so the
CLI flag flows through unchanged.
Behavior delta:
- `bd mol wisp <vapor-formula>` now materializes the full DAG
ephemerally (the bug fix)
- `bd mol wisp <vapor-formula> --root-only` unchanged (still root only)
- `bd mol wisp <pour=true formula>` unchanged (still full DAG)
Also adjusts the dry-run printout: when `--root-only` is set, the skip
hint now points at the flag instead of the obsolete `set pour=true in
formula` suggestion.
Adds wisp_test.go with three regression tests covering the default
fanout, `--root-only` opt-out, and dry-run messaging on both branches.
Follow-up: `subgraph.Pour` is now write-only dead code (set in
cook.go:800, no longer read anywhere). Will be cleaned up in a separate
chore PR to keep this fix minimal.
Co-authored-by: Cursor <cursoragent@cursor.com>
`bd create --graph <plan>` had two related bugs reported in GH#3367:
1. Unknown node/edge/plan fields were silently dropped by encoding/json.
The reporter's plan placed `parent` (a string) and `blocks` (an array)
directly on nodes, expecting them to wire hierarchy and dependencies.
The accepted schema is `parent_key` / `parent_id` and a top-level
`edges` array, so the input parsed cleanly but produced a flat set of
orphaned issues with no warning. There was no signal to the operator
that the plan's intent did not survive import.
2. `--dry-run` was wired up on `bd create` but ignored by the --graph
path: `createIssuesFromGraph` did not consult the flag and went
straight to `executeGraphApply`. The --file path already fails fast
when --dry-run is passed; --graph silently created issues regardless.
Changes:
- cmd/bd/graph_apply.go:
- Add `detectUnknownGraphFields` and `warnUnknownGraphFields` helpers
that scan the raw plan JSON before unmarshalling and emit warnings
to stderr listing unknown fields by location (plan, node[<key>],
edge[<i>]). Both are pure, easy to unit test, and have no effect
on the parse result — the legacy lenient behavior is preserved.
- Per-field hints for the two highest-friction reporter fields:
`parent` -> use `parent_key` / `parent_id`; `blocks` -> use the
top-level `edges` array. Plus `depends` and `children` for the
next-most-likely typos.
- Keep `knownGraphPlanFields` / `knownGraphNodeFields` /
`knownGraphEdgeFields` in sync with json tags via a reflection
test that fails on schema drift.
- `createIssuesFromGraph` now takes a `dryRun bool` and emits a
`GraphApplyDryRun` preview (JSON when --json, otherwise human-
readable) instead of calling `executeGraphApply`. The plan is
still parsed and validated so the operator sees the same errors
they would see on a real run, just without writes.
- cmd/bd/create.go: pass --dry-run through to createIssuesFromGraph,
matching the existing wiring on the --file path.
- cmd/bd/graph_apply_test.go: 8 new tests covering the reporter's
exact JSON, the canonical-schema clean path, plan/edge level
unknowns, malformed JSON, hint emission, schema-drift guardrail,
and dry-run preview counts/contents.
Smoke-tested with the reporter's plan against a fresh `bd init`:
- `--dry-run`: warns + previews, leaves the database empty.
- live: warns + creates issues exactly as before (no behavior change
for any plan that doesn't use unknown fields).
Tests: full `make test` clean; focused tests pass.
Fixes#3367
Made-with: Cursor
When dolt_mode=server is configured but the Dolt server is unreachable
(TCP refused, TLS mismatch, auth failure), CheckFreshClone previously
fell through to the legacy "Fresh clone detected (N issues in
issues.jsonl, no database)" warning and recommended bd bootstrap.
In server mode the absence of a local Dolt directory is expected, so
the warning is a false positive and the recommended fix is wrong:
bd bootstrap won't help when the actual problem is connectivity or
credentials. The "fall through (FR-030)" comment misread FR-030, which
only requires that an unreachable server not panic the caller — not
that we silently degrade to a misleading message.
This change adds freshCloneServerUnreachableResult, which:
- identifies that we're in server mode and points at host:port,
- surfaces the underlying connection error in Detail for diagnostics,
- and recommends verifying server health, host/port, TLS, and
credentials rather than bd bootstrap.
CheckFreshClone now routes the unreachable branch through this helper
instead of falling through. The existing
TestCheckFreshClone_ServerModeUnreachable is updated to assert the new
behavior, and a new TestFreshCloneServerUnreachableResult adds direct
unit coverage for the helper, including a nil-error path.
Embedded count and swarm tests parsed JSON / IDs from CombinedOutput,
which mixes the new auto-export warnings (emitted on stderr) into the
buffer callers parse. The failing CI shards on upstream/main were
TestEmbeddedCount/filter_by_id (shard 5/20) and
TestEmbeddedSwarm/create_coordinator (shard 11/20).
This applies the same stdout/stderr separation pattern already used by
the close/create/gate/init/list/quick/update embedded test helpers
(landed via PR #3909) to:
- bdCount, bdCountJSON
- TestEmbeddedCountConcurrent worker
- bdSwarm, bdSwarmJSON
- TestEmbeddedSwarm/list_json subtest
bdCountFail and bdSwarmFail keep CombinedOutput because they are only
used to assert non-zero exit and surface diagnostics; no parsing.
TestEmbeddedSwarmConcurrent worker keeps CombinedOutput because it only
matches against expected error strings.
Verified locally with BEADS_TEST_EMBEDDED_DOLT=1 CGO_ENABLED=1
go test -tags gms_pure_go -run
'^TestEmbeddedCount$|^TestEmbeddedCountConcurrent$|^TestEmbeddedSwarm$|^TestEmbeddedSwarmConcurrent$'
_amp-claude-sonnet-4.5 on behalf of CI Bot_
Amp-Thread-ID: https://ampcode.com/threads/T-019e22c8-5e13-70b2-a240-564b70597651
Co-authored-by: CI Bot <ci@beads.test>
Co-authored-by: Amp <amp@ampcode.com>
* fix(init): wire git origin as Dolt remote
Default bd init now treats a git origin as the Dolt remote, persists sync.remote, and still skips synthesis in --stealth. JSONL auto-export/import paths now warn or skip based on sync.remote so exports do not masquerade as cross-machine sync.
Docs and generated agent/CLI references now state that Dolt is canonical, refs/dolt/data is the sync channel, and .beads/issues.jsonl is export/interchange/backup only.
_codex-gpt-5-xhigh on behalf of maphew_
* test: keep embedded command stderr out of parsed stdout
Embedded command tests parse IDs and JSON from command output. The new auto-export warnings correctly go to stderr, but several tests used CombinedOutput and treated warnings as stdout, which broke CI shards that parse issue IDs or JSON lists. Capture stdout separately on success while preserving combined output for error diagnostics.\n\n_codex-gpt-5-medium on behalf of CI Bot_
---------
Co-authored-by: CI Bot <ci@beads.test>
Remove gastown-specific language. Replace the formula command's Rig/Cook/Run lifecycle wording with existing beads verbs: define formulas, cook them into protos, then pour or wisp them into work. Describe GT_ROOT formulas as a shared workspace root instead of an orchestrator path. Update generated CLI references and add a regression check for the help text.
_codex-gpt-5-medium on behalf of matt wilkie_
Reverts PR #3498 / commit 0fffa44a2302a496dfa4ffa838843b3bbf0ee122.\n\nPR #3498 added BEADS_DOLT_CLI_DIR routing without a confirmed reproduction and introduced an external-server push/pull regression. Remove that override and its docs/tests so main no longer requires a local CLI database directory in external-server mode.\n\n_codex-gpt-5- on behalf of CI Bot_
* test(cmd/bd): use t.Chdir in drift tests to fix chdir race (GH#3729-followup)
The TestCheckHooksDrift/Server/Remote tests in config_drift_test.go were
using the manual os.Chdir + defer os.Chdir(origDir) pattern, which is
not race-safe when other tests in the same package call t.Parallel and
share the process cwd.
t.Chdir (Go 1.24+) restores cwd via t.Cleanup and refuses to run if the
test (or any ancestor) is parallel — both eliminating the race window
and surfacing future misuse loudly.
Fixes flaky TestCheckHooksDriftNotGitRepo identified as a pre-existing
chdir race during PR #3716 review (mybd-j2s).
Verified: go test -count=20 -run '^TestCheckHooksDriftNotGitRepo$' passes.
Amp-Thread-ID: https://ampcode.com/threads/T-019dfe19-17ae-713e-bc3a-d7c9da6a117d
Co-authored-by: Amp <amp@ampcode.com>
* test(cmd/bd): accept embedded Dolt lock output
---------
Co-authored-by: CI Bot <ci@beads.test>
Co-authored-by: Amp <amp@ampcode.com>
Co-authored-by: upgrade-test <test@beads.test>
* fix(auto-import): restore top-level emptiness guard in maybeAutoImportJSONL (#2)
* fix(auto-import): restore top-level emptiness guard in maybeAutoImportJSONL
PR #3630 introduced jsonlImporter as a single-transaction fast-path for embedded mode and moved the TotalIssues>0 emptiness check inside that path. Stores that don't implement jsonlImporter (server-mode dolt store) fall through to the fallback multi-call path — which has no emptiness guard, so every bd command unconditionally runs importFromLocalJSONLFull on a non-empty Dolt.
importFromLocalJSONLFull's underlying ON DUPLICATE KEY UPDATE semantics in InsertIssueIntoTable then re-impose the (often stale) JSONL field values on top of live Dolt rows. Combined with the auto-export's debounce/commit-watermark gating in export_auto.go, partial-field bd updates (e.g. --append-notes alone, --priority=N alone) get clobbered: the next command's auto-import overwrites the just-written field with whatever the JSONL last had.
Restore the top-level GetStatistics+TotalIssues>0 guard that v1.0.3 had, before the path-fork. The embedded jsonlImporter retains its own atomic in-tx check (defense in depth against concurrent-writer races, which was the legitimate intent of #3630). The fallback path is now once again a true upgrade-recovery path: it only fires when the database is actually empty.
Reproducer (server mode):
1. bd update X --priority=2 --notes="X"
2. bd update X --append-notes "; appended"
3. bd update X --priority=3
Pre-fix: step 3 leaves notes='X' (the '; appended' is silently lost) and step 2 may revert priority to JSONL's stale value.
Post-fix: each single-field update preserves the unspecified fields from Dolt.
Test coverage gap: existing auto_import_upgrade_test.go is //go:build cgo and only exercises the embedded path. A non-CGO server-mode integration test would prevent reintroduction; left as a follow-up.
* test(auto-import): add server-mode fallback regression test for empty-DB guard
Adds two unit tests covering the server-mode fallback path of maybeAutoImportJSONL. Existing tests in auto_import_upgrade_test.go are //go:build cgo and exercise only the embedded jsonlImporter branch — leaving the fallback path (the actual location of the data-clobber regression) uncovered by CI.
Test design: a small testability seam exposes importFromLocalJSONLFull as a package-level 'fallbackImporter' var that tests can substitute. A minimal stub storage.DoltStorage embeds the interface (nil) and overrides only GetStatistics; any other method call panics, which is correct since the function under test should not invoke them after the emptiness guard short-circuits.
TestMaybeAutoImportJSONL_ServerModeFallback_SkipsWhenNonEmpty fails on the buggy code (substituted importer is invoked when it shouldn't be) and passes after the guard is restored. TestMaybeAutoImportJSONL_ServerModeFallback_RunsWhenEmpty is the negative control — guards against a future change that always short-circuits and would let the regression test pass vacuously.
* fix(test): TestEmbeddedAutoImportJSONLNoExplicitCommit — use write command to trigger auto-import (#3)
* fix(test): use a write command to trigger auto-import in TestEmbeddedAutoImportJSONLNoExplicitCommit
The test was added in PR #3630 with a comment claiming bd list 'triggers maybeAutoImportJSONL in pre-run'. This is incorrect: bd list is registered in cmd/bd/main.go's readOnlyCommands map, and the dispatcher at main.go:1023 explicitly skips maybeAutoImportJSONL for read-only commands (a guard added 2026-04-14 in fa87dd2bd to avoid opening a writable handle for read commands per GH#804).
The test consequently asserted on a 0-issue empty store, failed with 'expected 3 imported issues, got 0', and shipped broken. CI did not catch this because the test is gated behind BEADS_TEST_EMBEDDED_DOLT=1 and t.Skips otherwise; the embedded suite must not have been enabled in the PR's pipeline.
Fix: use bd create (a write command) to trigger auto-import in pre-run. bd create's own write coalesces with the auto-import via PersistentPostRun's maybeAutoCommit — exactly the deferred-commit flow the test was designed to verify. The post-import marker also brings the asserted total to 4.
The original commitCount > 2 assertion was a brittle proxy for 'auto-import didn't issue its own DOLT_COMMIT'. Replace it with a direct check: forbid the 'auto-import: ... (upgrade recovery, GH#2994)' commit message that the function only emits when it calls s.Commit explicitly (the fallback path). Its absence is the actual property under test.
Verified: passes locally with BEADS_TEST_EMBEDDED_DOLT=1; the four sibling auto-import tests in the same file continue to pass.
* docs(test): correct commit path attribution per PR #3 review
Copilot reviewer noted the previous comment incorrectly attributed the coalesced Dolt commit to PersistentPostRun's maybeAutoCommit. The actual commit path: bd create itself calls store.Commit at cmd/bd/create.go:676 (gated on isEmbeddedMode || postCreateWrites). The auto-import stages writes into the Dolt working set and bd create's own commit picks them up alongside its create write; PersistentPostRun's maybeAutoCommit is then a no-op.
* fix(auto-import): handle nil statistics guard
Incorporates the defensive nil-statistics behavior from #3690 by realies, while keeping #3691 as the broader tested fix.
Co-authored-by: realies <5107843+realies@users.noreply.github.com>
---------
Co-authored-by: maphew <486200+maphew@users.noreply.github.com>
Co-authored-by: realies <5107843+realies@users.noreply.github.com>