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

191 lines
5.7 KiB
Go

package dolt
import (
"context"
"database/sql"
"fmt"
"regexp"
"time"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/storage/versioncontrolops"
"github.com/steveyegge/beads/internal/types"
)
// validTablePattern matches valid table names
var validTablePattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
// validDatabasePattern matches valid MySQL database names (alphanumeric, underscore, hyphen)
var validDatabasePattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_\-]*$`)
// validateRef checks if a ref is safe to use in queries.
// Delegates to issueops.ValidateRef.
func validateRef(ref string) error {
return issueops.ValidateRef(ref)
}
// ValidateDatabaseName checks if a database name is safe to use in queries.
// Prevents SQL injection via backtick escaping in CREATE DATABASE statements.
func ValidateDatabaseName(name string) error {
if name == "" {
return fmt.Errorf("database name cannot be empty")
}
if len(name) > 64 {
return fmt.Errorf("database name too long")
}
if !validDatabasePattern.MatchString(name) {
return fmt.Errorf("invalid database name: %s", name)
}
return nil
}
// validateTableName checks if a table name is safe to use in queries
func validateTableName(table string) error {
if table == "" {
return fmt.Errorf("table name cannot be empty")
}
if len(table) > 64 {
return fmt.Errorf("table name too long")
}
if !validTablePattern.MatchString(table) {
return fmt.Errorf("invalid table name: %s", table)
}
return nil
}
// issueHistory represents an issue at a specific point in history
type issueHistory struct {
Issue *types.Issue
CommitHash string
Committer string
CommitDate time.Time
}
// getIssueHistory returns the complete history of an issue
func (s *DoltStore) getIssueHistory(ctx context.Context, issueID string) ([]*issueHistory, error) {
// Wrap in a subquery to avoid Dolt's max1Row optimization on PK lookup.
// dolt_history_* tables return multiple rows per PK (one per commit),
// but the query planner incorrectly assumes WHERE id=? returns one row.
rows, err := s.queryContext(ctx, `
SELECT
id, title, description, design, acceptance_criteria, notes,
status, priority, issue_type, assignee, owner, created_by,
estimated_minutes, created_at, updated_at, closed_at, close_reason,
pinned, mol_type,
commit_hash, committer, commit_date
FROM (
SELECT * FROM dolt_history_issues
) h
WHERE h.id = ?
ORDER BY h.commit_date DESC
`, issueID)
if err != nil {
return nil, fmt.Errorf("failed to get issue history: %w", err)
}
defer rows.Close()
var history []*issueHistory
for rows.Next() {
var h issueHistory
var issue types.Issue
var createdAtStr, updatedAtStr sql.NullString // TEXT columns - must parse manually
var closedAt sql.NullTime
var assignee, owner, createdBy, closeReason, molType sql.NullString
var estimatedMinutes sql.NullInt64
var pinned sql.NullInt64
if err := rows.Scan(
&issue.ID, &issue.Title, &issue.Description, &issue.Design, &issue.AcceptanceCriteria, &issue.Notes,
&issue.Status, &issue.Priority, &issue.IssueType, &assignee, &owner, &createdBy,
&estimatedMinutes, &createdAtStr, &updatedAtStr, &closedAt, &closeReason,
&pinned, &molType,
&h.CommitHash, &h.Committer, &h.CommitDate,
); err != nil {
return nil, fmt.Errorf("failed to scan history: %w", err)
}
// Parse timestamp strings (TEXT columns require manual parsing)
if createdAtStr.Valid {
issue.CreatedAt = parseTimeString(createdAtStr.String)
}
if updatedAtStr.Valid {
issue.UpdatedAt = parseTimeString(updatedAtStr.String)
}
if closedAt.Valid {
issue.ClosedAt = &closedAt.Time
}
if assignee.Valid {
issue.Assignee = assignee.String
}
if owner.Valid {
issue.Owner = owner.String
}
if createdBy.Valid {
issue.CreatedBy = createdBy.String
}
if estimatedMinutes.Valid {
mins := int(estimatedMinutes.Int64)
issue.EstimatedMinutes = &mins
}
if closeReason.Valid {
issue.CloseReason = closeReason.String
}
if pinned.Valid && pinned.Int64 != 0 {
issue.Pinned = true
}
if molType.Valid {
issue.MolType = types.MolType(molType.String)
}
h.Issue = &issue
history = append(history, &h)
}
return history, rows.Err()
}
// getIssueAsOf returns an issue as it existed at a specific commit or time
func (s *DoltStore) getIssueAsOf(ctx context.Context, issueID string, ref string) (*types.Issue, error) {
var result *types.Issue
err := s.withReadTx(ctx, func(tx *sql.Tx) error {
var err error
result, err = issueops.AsOfInTx(ctx, tx, issueID, ref)
return err
})
return result, err
}
// getInternalConflicts returns any merge conflicts in the current state (internal format).
// For the public interface, use GetConflicts which returns storage.Conflict.
func (s *DoltStore) getInternalConflicts(ctx context.Context) ([]*tableConflict, error) {
rows, err := s.queryContext(ctx,
"SELECT `table`, num_conflicts FROM dolt_conflicts")
if err != nil {
return nil, fmt.Errorf("failed to get conflicts: %w", err)
}
defer rows.Close()
var conflicts []*tableConflict
for rows.Next() {
var c tableConflict
if err := rows.Scan(&c.TableName, &c.NumConflicts); err != nil {
return nil, fmt.Errorf("failed to scan conflict: %w", err)
}
conflicts = append(conflicts, &c)
}
return conflicts, rows.Err()
}
// tableConflict represents a Dolt table-level merge conflict (internal representation).
type tableConflict struct {
TableName string
NumConflicts int
}
// ResolveConflicts resolves conflicts using the specified strategy
func (s *DoltStore) ResolveConflicts(ctx context.Context, table string, strategy string) error {
return versioncontrolops.ResolveConflicts(ctx, s.db, table, strategy)
}