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

300 lines
8.3 KiB
Go

//go:build cgo
package fix
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/doltutil"
"github.com/steveyegge/beads/internal/testutil"
"github.com/steveyegge/beads/internal/types"
)
// fixTestServerPort returns the Dolt server port for fix tests.
// Uses DoltContainerPortInt so the port is only non-zero when TestMain
// actually started a container, ignoring any external BEADS_DOLT_PORT.
func fixTestServerPort() int {
return testutil.DoltContainerPortInt()
}
// newFixTestStore creates a DoltStore for fix package tests with proper
// .beads directory structure so openAnyDB can connect for end-to-end testing.
func newFixTestStore(t *testing.T, dir string, prefix string) *dolt.DoltStore {
t.Helper()
ctx := context.Background()
// Determine server port
port := fixTestServerPort()
// Generate unique database name for test isolation
h := sha256.Sum256([]byte(t.Name() + fmt.Sprintf("%d", time.Now().UnixNano())))
dbName := "fixtest_" + hex.EncodeToString(h[:6])
// Create .beads directory
beadsDir := filepath.Join(dir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("Failed to create .beads: %v", err)
}
// Write metadata.json so openAnyDB can connect to the same database
cfg := &configfile.Config{
Database: "dolt",
DoltMode: configfile.DoltModeServer,
DoltServerHost: "127.0.0.1",
DoltServerPort: port,
DoltDatabase: dbName,
}
if err := cfg.Save(beadsDir); err != nil {
t.Fatalf("Failed to write metadata.json: %v", err)
}
// Create store connected to the same database
dbPath := filepath.Join(beadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{
Path: dbPath,
ServerHost: "127.0.0.1",
ServerPort: port,
Database: dbName,
})
if err != nil {
t.Skipf("skipping: Dolt not available: %v", err)
}
if err := store.SetConfig(ctx, "issue_prefix", prefix); err != nil {
store.Close()
t.Fatalf("Failed to set issue_prefix: %v", err)
}
t.Cleanup(func() {
store.Close()
dropFixTestDatabase(dbName, port)
})
return store
}
// dropFixTestDatabase drops a test database (best-effort cleanup).
func dropFixTestDatabase(dbName string, port int) {
dsn := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String()
db, err := sql.Open("mysql", dsn)
if err != nil {
return
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
//nolint:gosec // G201: dbName is generated by test (fixtest_ + random hex)
_, _ = db.ExecContext(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName))
}
// TestFixFunctions_RequireBeadsDir verifies all fix functions properly validate
// that a .beads directory exists before attempting fixes.
func TestFixFunctions_RequireBeadsDir(t *testing.T) {
funcs := []struct {
name string
fn func(string) error
}{
{"GitHooks", GitHooks},
{"DatabaseVersion", DatabaseVersion},
{"SchemaCompatibility", SchemaCompatibility},
{"ChildParentDependencies", func(dir string) error { return ChildParentDependencies(dir, false) }},
{"OrphanedDependencies", func(dir string) error { return OrphanedDependencies(dir, false) }},
}
for _, tc := range funcs {
t.Run(tc.name, func(t *testing.T) {
// Use a temp directory without .beads
dir := t.TempDir()
err := tc.fn(dir)
if err == nil {
t.Errorf("%s should return error for missing .beads directory", tc.name)
}
})
}
}
func TestChildParentDependencies_NoBadDeps(t *testing.T) {
dir := t.TempDir()
store := newFixTestStore(t, dir, "bd")
ctx := context.Background()
// Create issues
for _, id := range []string{"bd-abc", "bd-abc.1", "bd-xyz"} {
issue := &types.Issue{
ID: id,
Title: "Issue " + id,
Status: types.StatusOpen,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Add a non-child→parent dependency (bd-abc.1 blocks bd-xyz)
dep := &types.Dependency{
IssueID: "bd-abc.1",
DependsOnID: "bd-xyz",
Type: types.DepBlocks,
CreatedAt: time.Now(),
CreatedBy: "test",
}
if err := store.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
// Run fix - should find no bad deps
err := ChildParentDependencies(dir, false)
if err != nil {
t.Errorf("ChildParentDependencies failed: %v", err)
}
// Verify the good dependency still exists
db := store.UnderlyingDB()
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM dependencies").Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Errorf("Expected 1 dependency, got %d", count)
}
}
func TestChildParentDependencies_FixesBadDeps(t *testing.T) {
dir := t.TempDir()
store := newFixTestStore(t, dir, "bd")
ctx := context.Background()
// Create issues
for _, id := range []string{"bd-abc", "bd-abc.1", "bd-abc.1.2"} {
issue := &types.Issue{
ID: id,
Title: "Issue " + id,
Status: types.StatusOpen,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Add child→parent blocking dependencies (anti-pattern)
for _, d := range []struct{ from, to string }{
{"bd-abc.1", "bd-abc"},
{"bd-abc.1.2", "bd-abc"},
{"bd-abc.1.2", "bd-abc.1"},
} {
dep := &types.Dependency{
IssueID: d.from,
DependsOnID: d.to,
Type: types.DepBlocks,
CreatedAt: time.Now(),
CreatedBy: "test",
}
if err := store.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
}
// Run fix
err := ChildParentDependencies(dir, false)
if err != nil {
t.Errorf("ChildParentDependencies failed: %v", err)
}
// Verify all bad dependencies were removed
db := store.UnderlyingDB()
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM dependencies").Scan(&count); err != nil {
t.Fatal(err)
}
if count != 0 {
t.Errorf("Expected 0 dependencies after fix, got %d", count)
}
}
// TestChildParentDependencies_PreservesParentChildType verifies that legitimate
// parent-child type dependencies are NOT removed (only blocking types are removed).
func TestChildParentDependencies_PreservesParentChildType(t *testing.T) {
dir := t.TempDir()
store := newFixTestStore(t, dir, "bd")
ctx := context.Background()
// Create issues
for _, id := range []string{"bd-abc", "bd-abc.1", "bd-abc.2"} {
issue := &types.Issue{
ID: id,
Title: "Issue " + id,
Status: types.StatusOpen,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Add a legitimate parent-child dep (should be preserved by the fix)
pcDep := &types.Dependency{
IssueID: "bd-abc.2",
DependsOnID: "bd-abc",
Type: types.DepParentChild,
CreatedAt: time.Now(),
CreatedBy: "test",
}
if err := store.AddDependency(ctx, pcDep, "test"); err != nil {
t.Fatal(err)
}
// Add a child→parent blocking dep (anti-pattern to be removed by the fix).
// AddDependency rejects type changes on the same key pair, so we use a
// different child (bd-abc.1) that has no prior parent-child dep.
blockDep := &types.Dependency{
IssueID: "bd-abc.1",
DependsOnID: "bd-abc",
Type: types.DepBlocks,
CreatedAt: time.Now(),
CreatedBy: "test",
}
if err := store.AddDependency(ctx, blockDep, "test"); err != nil {
t.Fatal(err)
}
// Run fix
err := ChildParentDependencies(dir, false)
if err != nil {
t.Fatalf("ChildParentDependencies failed: %v", err)
}
// Verify only 'blocks' type was removed, 'parent-child' preserved.
// bd-abc.2→bd-abc (parent-child) survives; bd-abc.1→bd-abc (blocks) is removed.
db := store.UnderlyingDB()
var blocksCount int
if err := db.QueryRow("SELECT COUNT(*) FROM dependencies WHERE type = 'blocks'").Scan(&blocksCount); err != nil {
t.Fatal(err)
}
if blocksCount != 0 {
t.Errorf("Expected 0 'blocks' dependencies after fix, got %d", blocksCount)
}
var parentChildCount int
if err := db.QueryRow("SELECT COUNT(*) FROM dependencies WHERE type = 'parent-child'").Scan(&parentChildCount); err != nil {
t.Fatal(err)
}
if parentChildCount != 1 {
t.Errorf("Expected 1 'parent-child' dependency preserved, got %d", parentChildCount)
}
}