gitgram/aitimemachine/beads/cmd/bd/auto_import_upgrade_test.go
caelum0x 49b183818c Unify gitgram + aitimemachine into the monorepo (de-submodule) and merge vendored engines
Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as
opaque submodule gitlinks on GitHub) into fully-tracked first-party content.

AITM now merges its 7 vendored repos as first-party engines:
- memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts
- git: vendored C git (bundled binary) + gitnexus (in-process code intelligence)
- agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess)

Includes the full session's product build: Gitgram web/mobile/backend features,
AITM website/CLI/MCP, the unified memory layer, engine build tooling
(scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md),
and extensive test suites.

Build artifacts, node_modules, external/, and gemini-cli are gitignored.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 14:14:09 +03:00

388 lines
14 KiB
Go

//go:build cgo
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
)
// TestEmbeddedAutoImportJSONLNoExplicitCommit verifies that auto-import
// uses a single transaction and defers the Dolt commit to PersistentPostRun
// (no separate DOLT_COMMIT during pre-run).
func TestEmbeddedAutoImportJSONLNoExplicitCommit(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)
// Create a source store with 3 issues, then export to JSONL.
srcDir, _, _ := bdInit(t, bd, "--prefix", "src")
for i := 0; i < 3; i++ {
bdCreate(t, bd, srcDir, fmt.Sprintf("auto-import-test-%d", i), "--type", "task")
}
srcJSONL := filepath.Join(srcDir, "export.jsonl")
cmd := exec.Command(bd, "export", "-o", srcJSONL)
cmd.Dir = srcDir
cmd.Env = bdEnv(srcDir)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("bd export failed: %v\n%s", err, out)
}
// Create a fresh empty store in a new directory.
dstDir, dstBeadsDir, _ := bdInit(t, bd, "--prefix", "dst")
// Place the JSONL file where auto-import looks for it.
srcData, err := os.ReadFile(srcJSONL)
if err != nil {
t.Fatalf("reading exported JSONL: %v", err)
}
if err := os.WriteFile(filepath.Join(dstBeadsDir, "issues.jsonl"), srcData, 0644); err != nil {
t.Fatalf("writing issues.jsonl: %v", err)
}
// Trigger auto-import via a write command. bd list is registered as
// read-only in cmd/bd/main.go's dispatcher and skips
// maybeAutoImportJSONL entirely — using it here would leave the
// destination empty and the test would assert against zero issues.
// bd create runs maybeAutoImportJSONL in PersistentPreRun (which
// stages the imported issues in the Dolt working set without an
// explicit DOLT_COMMIT), performs its own create write into the same
// working set, and then explicitly calls store.Commit at the end of
// cmd/bd/create.go — that single commit picks up both the auto-import
// and the new issue. PersistentPostRun's maybeAutoCommit is then a
// no-op (nothing left to commit).
bdCreate(t, bd, dstDir, "post-import marker", "--type", "task")
issues := bdListJSON(t, bd, dstDir)
if len(issues) != 4 {
t.Fatalf("expected 4 issues (3 imported + 1 created post-import), got %d", len(issues))
}
// Verify auto-import did NOT issue its own DOLT_COMMIT. The
// single-transaction import sets commandDidWrite and defers the commit
// to PersistentPostRun, so the auto-import and the post-run write
// (the bd create above) coalesce into one Dolt commit. The exact total
// depends on init detail (2-3 init commits + 1 coalesced post-run);
// what we want to forbid is a separate auto-import commit appearing
// alongside the post-run commit. The "auto-import: ... (upgrade
// recovery, GH#2994)" message is only used when the function calls
// s.Commit explicitly (the fallback path) — its absence proves the
// embedded path used the deferred-commit flow.
logOut := bdDolt(t, bd, dstDir, "log")
if strings.Contains(logOut, "auto-import:") && strings.Contains(logOut, "upgrade recovery, GH#2994") {
t.Errorf("embedded auto-import path issued an explicit DOLT_COMMIT; expected the commit to be deferred to PersistentPostRun;\nlog:\n%s", logOut)
}
}
// TestEmbeddedAutoImportJSONLConcurrentWriter verifies no data loss when
// auto-import runs concurrently with other writers (the race that prompted
// the single-transaction fix).
func TestEmbeddedAutoImportJSONLConcurrentWriter(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)
// Create a fresh store and place a hand-crafted issues.jsonl.
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cr")
jsonlIssues := []types.Issue{
{ID: "cr-import-1", Title: "Imported One", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: time.Now(), UpdatedAt: time.Now()},
{ID: "cr-import-2", Title: "Imported Two", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug, CreatedAt: time.Now(), UpdatedAt: time.Now()},
{ID: "cr-import-3", Title: "Imported Three", Status: types.StatusOpen, Priority: 3, IssueType: types.TypeTask, CreatedAt: time.Now(), UpdatedAt: time.Now()},
}
var lines []string
for _, issue := range jsonlIssues {
b, _ := json.Marshal(issue)
lines = append(lines, string(b))
}
if err := os.WriteFile(filepath.Join(beadsDir, "issues.jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0644); err != nil {
t.Fatal(err)
}
// Launch concurrent writers + one "bd list" that triggers auto-import.
const numWriters = 4
type result struct {
id string
err error
}
var wg sync.WaitGroup
writerResults := make([]result, numWriters)
// Concurrent create workers
for i := 0; i < numWriters; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
issue := bdCreateAllowError(t, bd, dir, fmt.Sprintf("concurrent-%d", idx), "--type", "task")
if issue != nil {
writerResults[idx] = result{id: issue.ID}
} else {
writerResults[idx] = result{err: fmt.Errorf("create failed for worker %d", idx)}
}
}(i)
}
// Trigger auto-import via bd list (runs concurrently with creates)
wg.Add(1)
var listIssues []*types.IssueWithCounts
go func() {
defer wg.Done()
listIssues = bdListJSONAllowError(t, bd, dir)
}()
wg.Wait()
// Count successful creates
var successfulCreates []string
for _, r := range writerResults {
if r.err == nil && r.id != "" {
successfulCreates = append(successfulCreates, r.id)
}
}
// Final authoritative list — after all concurrency is done
finalIssues := bdListJSON(t, bd, dir)
finalIDs := make(map[string]bool)
for _, issue := range finalIssues {
finalIDs[issue.ID] = true
}
// Every successfully created issue must be present (no lost writes)
for _, id := range successfulCreates {
if !finalIDs[id] {
t.Errorf("concurrent create %s succeeded but is missing from final list", id)
}
}
// If the list ran before any creates, the imported issues should be present
// (they may or may not be, depending on whether auto-import won the flock race)
t.Logf("final issue count: %d (imports: up to 3, concurrent creates: %d, list saw: %d)",
len(finalIssues), len(successfulCreates), len(listIssues))
}
// TestEmbeddedAutoImportJSONLSkipsNonEmpty verifies that auto-import is
// a no-op when the database already has issues (atomicity of the
// emptiness check + import within a single transaction).
func TestEmbeddedAutoImportJSONLSkipsNonEmpty(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)
// Create a store with one existing issue.
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "ne")
existing := bdCreate(t, bd, dir, "pre-existing issue", "--type", "task")
// Place a JSONL file with different issues.
jsonlIssues := []types.Issue{
{ID: "ne-should-not-import-1", Title: "Should Not Import", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: time.Now(), UpdatedAt: time.Now()},
{ID: "ne-should-not-import-2", Title: "Also Should Not Import", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug, CreatedAt: time.Now(), UpdatedAt: time.Now()},
}
var lines []string
for _, issue := range jsonlIssues {
b, _ := json.Marshal(issue)
lines = append(lines, string(b))
}
if err := os.WriteFile(filepath.Join(beadsDir, "issues.jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0644); err != nil {
t.Fatal(err)
}
// Run bd list — auto-import should skip because DB is non-empty.
issues := bdListJSON(t, bd, dir)
// Only the pre-existing issue should be present.
if len(issues) != 1 {
t.Fatalf("expected 1 issue (pre-existing only), got %d", len(issues))
}
if issues[0].ID != existing.ID {
t.Errorf("expected issue %s, got %s", existing.ID, issues[0].ID)
}
}
// bdCreateAllowError runs "bd create --json" and returns the issue on success,
// or nil on failure (without failing the test).
func bdCreateAllowError(t *testing.T, bd, dir string, args ...string) *types.Issue {
t.Helper()
fullArgs := append([]string{"create", "--json"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err != nil {
return nil
}
s := string(out)
start := strings.Index(s, "{")
if start < 0 {
return nil
}
var issue types.Issue
if err := json.Unmarshal([]byte(s[start:]), &issue); err != nil {
return nil
}
return &issue
}
// bdListJSONAllowError runs "bd list --json" and returns issues on success,
// or nil on failure (without failing the test).
func bdListJSONAllowError(t *testing.T, bd, dir string, args ...string) []*types.IssueWithCounts {
t.Helper()
fullArgs := append([]string{"list", "--json"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err != nil {
return nil
}
s := string(out)
start := strings.Index(s, "[")
if start < 0 {
return nil
}
var issues []*types.IssueWithCounts
if err := json.Unmarshal([]byte(s[start:]), &issues); err != nil {
return nil
}
return issues
}
// TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber asserts the
// GH#3955 Layer 2 guarantee against a real embedded store: the auto-import
// server-mode fallback importer (importFromLocalJSONLConflictSkip, the
// production fallbackImporter) never overwrites an existing issue row.
//
// We invoke it directly against a NON-empty store — deliberately modelling
// a regressed emptiness guard — and verify the live row is untouched while
// a brand-new id from the JSONL is still inserted.
func TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cs")
live := bdCreate(t, bd, dir, "live issue title", "--type", "task")
if live.ID == "" {
t.Fatal("expected a created issue ID")
}
const newID = "cs-new-9999"
now := time.Now().UTC()
jsonlIssues := []types.Issue{
// Mutated copy of the live issue: UPSERT would clobber it.
{ID: live.ID, Title: "CLOBBERED", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeBug, CreatedAt: now, UpdatedAt: now},
// Brand-new issue: must still be inserted.
{ID: newID, Title: "freshly imported", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: now, UpdatedAt: now},
}
var lines []string
for _, issue := range jsonlIssues {
b, err := json.Marshal(issue)
if err != nil {
t.Fatalf("marshal fixture: %v", err)
}
lines = append(lines, string(b))
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
store := openStore(t, beadsDir, "cs")
ctx := context.Background()
// Exactly the code path fallbackImporter points at; running it on a
// non-empty store models a guard regression (GH#3955 / PR #3630).
if _, err := importFromLocalJSONLConflictSkip(ctx, store, jsonlPath); err != nil {
t.Fatalf("importFromLocalJSONLConflictSkip: %v", err)
}
got, err := store.GetIssue(ctx, live.ID)
if err != nil {
t.Fatalf("GetIssue(%s): %v", live.ID, err)
}
if got.Title != "live issue title" {
t.Errorf("live issue title was clobbered: got %q, want %q", got.Title, "live issue title")
}
if got.Status != types.StatusOpen {
t.Errorf("live issue status was clobbered: got %q, want %q", got.Status, types.StatusOpen)
}
inserted, err := store.GetIssue(ctx, newID)
if err != nil {
t.Fatalf("brand-new issue %s was not inserted by conflict-skip import: %v", newID, err)
}
if inserted.Title != "freshly imported" {
t.Errorf("new issue title: got %q, want %q", inserted.Title, "freshly imported")
}
}
// TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll is the
// negative control for GH#3955: conflict-skip must NOT regress the
// legitimate upgrade-recovery path. Against an empty store the fallback
// still imports every issue from the JSONL.
func TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
_, beadsDir, _ := bdInit(t, bd, "--prefix", "ce")
now := time.Now().UTC()
jsonlIssues := []types.Issue{
{ID: "ce-1", Title: "recovered one", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedAt: now, UpdatedAt: now},
{ID: "ce-2", Title: "recovered two", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug, CreatedAt: now, UpdatedAt: now},
}
var lines []string
for _, issue := range jsonlIssues {
b, err := json.Marshal(issue)
if err != nil {
t.Fatalf("marshal fixture: %v", err)
}
lines = append(lines, string(b))
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
store := openStore(t, beadsDir, "ce")
ctx := context.Background()
res, err := importFromLocalJSONLConflictSkip(ctx, store, jsonlPath)
if err != nil {
t.Fatalf("importFromLocalJSONLConflictSkip: %v", err)
}
if res.Issues != 2 {
t.Errorf("expected 2 issues imported, got %d", res.Issues)
}
for _, id := range []string{"ce-1", "ce-2"} {
if _, err := store.GetIssue(ctx, id); err != nil {
t.Errorf("empty-DB recovery dropped issue %s: %v", id, err)
}
}
}