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>
437 lines
14 KiB
Go
437 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
)
|
|
|
|
var renamePrefixCmd = &cobra.Command{
|
|
Use: "rename-prefix <new-prefix>",
|
|
GroupID: "maint",
|
|
Short: "Rename the issue prefix for all issues in the database",
|
|
Long: `Rename the issue prefix for all issues in the database.
|
|
This will update all issue IDs and all text references across all fields.
|
|
|
|
USE CASES:
|
|
- Shortening long prefixes (e.g., 'knowledge-work-' → 'kw-')
|
|
- Rebranding project naming conventions
|
|
- Consolidating multiple prefixes after database corruption
|
|
- Migrating to team naming standards
|
|
|
|
Prefix validation rules:
|
|
- Max length: 8 characters
|
|
- Allowed characters: lowercase letters, numbers, hyphens
|
|
- Must start with a letter
|
|
- Must end with a hyphen (e.g., 'kw-', 'work-')
|
|
- Cannot be empty or just a hyphen
|
|
|
|
Multiple prefix detection and repair:
|
|
If issues have multiple prefixes (corrupted database), use --repair to consolidate them.
|
|
The --repair flag will rename all issues with incorrect prefixes to the new prefix,
|
|
preserving issues that already have the correct prefix.
|
|
|
|
EXAMPLES:
|
|
bd rename-prefix kw- # Rename from 'knowledge-work-' to 'kw-'
|
|
bd rename-prefix mtg- --repair # Consolidate multiple prefixes into 'mtg-'
|
|
bd rename-prefix team- --dry-run # Preview changes without applying
|
|
|
|
NOTE: This is a rare operation. Most users never need this command.`,
|
|
Args: cobra.ExactArgs(1),
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
newPrefix := args[0]
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
repair, _ := cmd.Flags().GetBool("repair")
|
|
|
|
// Block writes in readonly mode
|
|
if !dryRun {
|
|
CheckReadonly("rename-prefix")
|
|
}
|
|
|
|
ctx := rootCtx
|
|
|
|
// rename-prefix requires direct database access
|
|
if store == nil {
|
|
if err := ensureStoreActive(); err != nil {
|
|
FatalError("%v", err)
|
|
}
|
|
}
|
|
|
|
if err := validatePrefix(newPrefix); err != nil {
|
|
FatalError("%v", err)
|
|
}
|
|
|
|
oldPrefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil || oldPrefix == "" {
|
|
FatalError("failed to get current prefix: %v", err)
|
|
}
|
|
|
|
newPrefix = strings.TrimRight(newPrefix, "-")
|
|
|
|
// Check for multiple prefixes first
|
|
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
FatalError("failed to list issues: %v", err)
|
|
}
|
|
|
|
prefixes := detectPrefixes(issues)
|
|
|
|
if len(prefixes) > 1 {
|
|
// Multiple prefixes detected - requires repair mode
|
|
|
|
fmt.Fprintf(os.Stderr, "%s Multiple prefixes detected in database:\n", ui.RenderFail("✗"))
|
|
for prefix, count := range prefixes {
|
|
fmt.Fprintf(os.Stderr, " - %s: %d issues\n", ui.RenderWarn(prefix), count)
|
|
}
|
|
fmt.Fprintf(os.Stderr, "\n")
|
|
|
|
if !repair {
|
|
FatalErrorWithHint(
|
|
"cannot rename with multiple prefixes. Use --repair to consolidate.",
|
|
fmt.Sprintf("Example: bd rename-prefix %s --repair", newPrefix),
|
|
)
|
|
}
|
|
|
|
// Repair mode: consolidate all prefixes to newPrefix
|
|
if err := repairPrefixes(ctx, store, actor, newPrefix, issues, prefixes, dryRun); err != nil {
|
|
FatalError("failed to repair prefixes: %v", err)
|
|
}
|
|
if !dryRun {
|
|
commandDidWrite.Store(true)
|
|
}
|
|
return
|
|
}
|
|
|
|
// Single prefix case - check if trying to rename to same prefix
|
|
if len(prefixes) == 1 && oldPrefix == newPrefix {
|
|
FatalError("new prefix is the same as current prefix: %s", oldPrefix)
|
|
}
|
|
|
|
// issues already fetched above
|
|
if len(issues) == 0 {
|
|
fmt.Printf("No issues to rename. Updating prefix to %s\n", newPrefix)
|
|
if !dryRun {
|
|
if err := store.SetConfig(ctx, "issue_prefix", newPrefix); err != nil {
|
|
FatalError("failed to update prefix: %v", err)
|
|
}
|
|
commandDidWrite.Store(true)
|
|
}
|
|
return
|
|
}
|
|
|
|
if dryRun {
|
|
fmt.Printf("DRY RUN: Would rename %d issues from prefix '%s' to '%s'\n\n", len(issues), oldPrefix, newPrefix)
|
|
fmt.Printf("Sample changes:\n")
|
|
for i, issue := range issues {
|
|
if i >= 5 {
|
|
fmt.Printf("... and %d more issues\n", len(issues)-5)
|
|
break
|
|
}
|
|
oldID := fmt.Sprintf("%s-%s", oldPrefix, strings.TrimPrefix(issue.ID, oldPrefix+"-"))
|
|
newID := fmt.Sprintf("%s-%s", newPrefix, strings.TrimPrefix(issue.ID, oldPrefix+"-"))
|
|
fmt.Printf(" %s -> %s\n", ui.RenderAccent(oldID), ui.RenderAccent(newID))
|
|
}
|
|
return
|
|
}
|
|
|
|
fmt.Printf("Renaming %d issues from prefix '%s' to '%s'...\n", len(issues), oldPrefix, newPrefix)
|
|
|
|
if err := renamePrefixInDB(ctx, oldPrefix, newPrefix, issues); err != nil {
|
|
FatalError("failed to rename prefix: %v", err)
|
|
}
|
|
|
|
fmt.Printf("%s Successfully renamed prefix from %s to %s\n", ui.RenderPass("✓"), ui.RenderAccent(oldPrefix), ui.RenderAccent(newPrefix))
|
|
|
|
if jsonOutput {
|
|
result := map[string]interface{}{
|
|
"old_prefix": oldPrefix,
|
|
"new_prefix": newPrefix,
|
|
"issues_count": len(issues),
|
|
}
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
_ = enc.Encode(result) // Best effort: JSON encoding of simple struct does not fail in practice
|
|
}
|
|
|
|
commandDidWrite.Store(true)
|
|
},
|
|
}
|
|
|
|
func validatePrefix(prefix string) error {
|
|
prefix = strings.TrimRight(prefix, "-")
|
|
|
|
if prefix == "" {
|
|
return fmt.Errorf("prefix cannot be empty")
|
|
}
|
|
|
|
matched, _ := regexp.MatchString(`^[a-z][a-z0-9-]*$`, prefix)
|
|
if !matched {
|
|
return fmt.Errorf("prefix must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens: %s", prefix)
|
|
}
|
|
|
|
if strings.HasPrefix(prefix, "-") || strings.HasSuffix(prefix, "--") {
|
|
return fmt.Errorf("prefix has invalid hyphen placement: %s", prefix)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// detectPrefixes analyzes all issues and returns a map of prefix -> count
|
|
func detectPrefixes(issues []*types.Issue) map[string]int {
|
|
prefixes := make(map[string]int)
|
|
for _, issue := range issues {
|
|
prefix := utils.ExtractIssuePrefix(issue.ID)
|
|
if prefix != "" {
|
|
prefixes[prefix]++
|
|
}
|
|
}
|
|
return prefixes
|
|
}
|
|
|
|
// issueSort is used for sorting issues by prefix and number
|
|
type issueSort struct {
|
|
issue *types.Issue
|
|
prefix string
|
|
number int
|
|
}
|
|
|
|
// repairPrefixes consolidates multiple prefixes into a single target prefix
|
|
// Issues with the correct prefix are left unchanged.
|
|
// Issues with incorrect prefixes get new hash-based IDs.
|
|
func repairPrefixes(ctx context.Context, st storage.DoltStorage, actorName string, targetPrefix string, issues []*types.Issue, prefixes map[string]int, dryRun bool) error {
|
|
|
|
// Separate issues into correct and incorrect prefix groups
|
|
var correctIssues []*types.Issue
|
|
var incorrectIssues []issueSort
|
|
|
|
for _, issue := range issues {
|
|
prefix := utils.ExtractIssuePrefix(issue.ID)
|
|
number := utils.ExtractIssueNumber(issue.ID)
|
|
|
|
if prefix == targetPrefix {
|
|
correctIssues = append(correctIssues, issue)
|
|
} else {
|
|
incorrectIssues = append(incorrectIssues, issueSort{
|
|
issue: issue,
|
|
prefix: prefix,
|
|
number: number,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Sort incorrect issues: first by prefix lexicographically, then by number
|
|
slices.SortFunc(incorrectIssues, func(a, b issueSort) int {
|
|
return cmp.Or(
|
|
cmp.Compare(a.prefix, b.prefix),
|
|
cmp.Compare(a.number, b.number),
|
|
)
|
|
})
|
|
|
|
// Build a map of all renames for text replacement using hash IDs
|
|
// Track used IDs to avoid collisions within the batch
|
|
renameMap := make(map[string]string)
|
|
usedIDs := make(map[string]bool)
|
|
|
|
// Mark existing correct IDs as used
|
|
for _, issue := range correctIssues {
|
|
usedIDs[issue.ID] = true
|
|
}
|
|
|
|
// Generate hash IDs for all incorrect issues
|
|
for _, is := range incorrectIssues {
|
|
newID, err := generateRepairHashID(targetPrefix, is.issue, actorName, usedIDs)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to generate hash ID for %s: %w", is.issue.ID, err)
|
|
}
|
|
renameMap[is.issue.ID] = newID
|
|
usedIDs[newID] = true
|
|
}
|
|
|
|
if dryRun {
|
|
fmt.Printf("DRY RUN: Would repair %d issues with incorrect prefixes\n\n", len(incorrectIssues))
|
|
fmt.Printf("Issues with correct prefix (%s): %d\n", ui.RenderAccent(targetPrefix), len(correctIssues))
|
|
fmt.Printf("Issues to repair: %d\n\n", len(incorrectIssues))
|
|
|
|
fmt.Printf("Planned renames (showing first 10):\n")
|
|
for i, is := range incorrectIssues {
|
|
if i >= 10 {
|
|
fmt.Printf("... and %d more\n", len(incorrectIssues)-10)
|
|
break
|
|
}
|
|
oldID := is.issue.ID
|
|
newID := renameMap[oldID]
|
|
fmt.Printf(" %s -> %s\n", ui.RenderWarn(oldID), ui.RenderAccent(newID))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Perform the repairs
|
|
fmt.Printf("Repairing database with multiple prefixes...\n")
|
|
fmt.Printf(" Issues with correct prefix (%s): %d\n", ui.RenderAccent(targetPrefix), len(correctIssues))
|
|
fmt.Printf(" Issues to repair: %d\n\n", len(incorrectIssues))
|
|
|
|
// Pattern to match any issue ID reference in text (both hash and sequential IDs)
|
|
oldPrefixPattern := regexp.MustCompile(`\b[a-z][a-z0-9-]*-[a-z0-9]+\b`)
|
|
|
|
// Rename each issue
|
|
for _, is := range incorrectIssues {
|
|
oldID := is.issue.ID
|
|
newID := renameMap[oldID]
|
|
|
|
// Apply text replacements in all issue fields
|
|
issue := is.issue
|
|
issue.ID = newID
|
|
|
|
// Replace all issue IDs in text fields using the rename map
|
|
replaceFunc := func(match string) string {
|
|
if newID, ok := renameMap[match]; ok {
|
|
return newID
|
|
}
|
|
return match
|
|
}
|
|
|
|
issue.Title = oldPrefixPattern.ReplaceAllStringFunc(issue.Title, replaceFunc)
|
|
issue.Description = oldPrefixPattern.ReplaceAllStringFunc(issue.Description, replaceFunc)
|
|
if issue.Design != "" {
|
|
issue.Design = oldPrefixPattern.ReplaceAllStringFunc(issue.Design, replaceFunc)
|
|
}
|
|
if issue.AcceptanceCriteria != "" {
|
|
issue.AcceptanceCriteria = oldPrefixPattern.ReplaceAllStringFunc(issue.AcceptanceCriteria, replaceFunc)
|
|
}
|
|
if issue.Notes != "" {
|
|
issue.Notes = oldPrefixPattern.ReplaceAllStringFunc(issue.Notes, replaceFunc)
|
|
}
|
|
|
|
// Update the issue in the database
|
|
if err := st.UpdateIssueID(ctx, oldID, newID, issue, actorName); err != nil {
|
|
return fmt.Errorf("failed to update issue %s -> %s: %w", oldID, newID, err)
|
|
}
|
|
|
|
fmt.Printf(" Renamed %s -> %s\n", ui.RenderWarn(oldID), ui.RenderAccent(newID))
|
|
}
|
|
|
|
// Set the new prefix in config
|
|
if err := st.SetConfig(ctx, "issue_prefix", targetPrefix); err != nil {
|
|
return fmt.Errorf("failed to update config: %w", err)
|
|
}
|
|
|
|
fmt.Printf("\n%s Successfully consolidated %d prefixes into %s\n",
|
|
ui.RenderPass("✓"), len(prefixes), ui.RenderAccent(targetPrefix))
|
|
fmt.Printf(" %d issues repaired, %d issues unchanged\n", len(incorrectIssues), len(correctIssues))
|
|
|
|
if jsonOutput {
|
|
result := map[string]interface{}{
|
|
"target_prefix": targetPrefix,
|
|
"prefixes_found": len(prefixes),
|
|
"issues_repaired": len(incorrectIssues),
|
|
"issues_unchanged": len(correctIssues),
|
|
}
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
_ = enc.Encode(result)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func renamePrefixInDB(ctx context.Context, oldPrefix, newPrefix string, issues []*types.Issue) error {
|
|
// NOTE: Each issue is updated in its own transaction. A failure mid-way could leave
|
|
// the database in a mixed state with some issues renamed and others not.
|
|
// For production use, consider implementing a single atomic RenamePrefix() method
|
|
// in the storage layer that wraps all updates in one transaction.
|
|
|
|
oldPrefixPattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(oldPrefix) + `-(\d+)\b`)
|
|
|
|
replaceFunc := func(match string) string {
|
|
return strings.Replace(match, oldPrefix+"-", newPrefix+"-", 1)
|
|
}
|
|
|
|
for _, issue := range issues {
|
|
oldID := issue.ID
|
|
numPart := strings.TrimPrefix(oldID, oldPrefix+"-")
|
|
newID := fmt.Sprintf("%s-%s", newPrefix, numPart)
|
|
|
|
issue.ID = newID
|
|
|
|
issue.Title = oldPrefixPattern.ReplaceAllStringFunc(issue.Title, replaceFunc)
|
|
issue.Description = oldPrefixPattern.ReplaceAllStringFunc(issue.Description, replaceFunc)
|
|
if issue.Design != "" {
|
|
issue.Design = oldPrefixPattern.ReplaceAllStringFunc(issue.Design, replaceFunc)
|
|
}
|
|
if issue.AcceptanceCriteria != "" {
|
|
issue.AcceptanceCriteria = oldPrefixPattern.ReplaceAllStringFunc(issue.AcceptanceCriteria, replaceFunc)
|
|
}
|
|
if issue.Notes != "" {
|
|
issue.Notes = oldPrefixPattern.ReplaceAllStringFunc(issue.Notes, replaceFunc)
|
|
}
|
|
|
|
if err := store.UpdateIssueID(ctx, oldID, newID, issue, actor); err != nil {
|
|
return fmt.Errorf("failed to update issue %s: %w", oldID, err)
|
|
}
|
|
}
|
|
|
|
if err := store.SetConfig(ctx, "issue_prefix", newPrefix); err != nil {
|
|
return fmt.Errorf("failed to update config: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// generateRepairHashID generates a hash-based ID for an issue during repair.
|
|
// Uses content hashing and checks usedIDs for batch collision avoidance.
|
|
func generateRepairHashID(prefix string, issue *types.Issue, actor string, usedIDs map[string]bool) (string, error) {
|
|
// Generate a hash ID from issue content (same approach as generateHashIDForIssue)
|
|
content := fmt.Sprintf("%s|%s|%s|%d|%d",
|
|
issue.Title,
|
|
issue.Description,
|
|
actor,
|
|
issue.CreatedAt.UnixNano(),
|
|
0, // nonce
|
|
)
|
|
h := sha256.Sum256([]byte(content))
|
|
shortHash := hex.EncodeToString(h[:4]) // 4 bytes = 8 hex chars
|
|
newID := fmt.Sprintf("%s-%s", prefix, shortHash)
|
|
|
|
// Check if this ID was already used in this batch
|
|
// If so, we need to generate a new one with a different nonce
|
|
attempts := 0
|
|
for usedIDs[newID] && attempts < 100 {
|
|
attempts++
|
|
content = fmt.Sprintf("%s|%s|%s|%d|%d",
|
|
issue.Title,
|
|
issue.Description,
|
|
actor,
|
|
issue.CreatedAt.UnixNano(),
|
|
attempts,
|
|
)
|
|
h = sha256.Sum256([]byte(content))
|
|
shortHash = hex.EncodeToString(h[:4])
|
|
newID = fmt.Sprintf("%s-%s", prefix, shortHash)
|
|
}
|
|
|
|
if usedIDs[newID] {
|
|
return "", fmt.Errorf("failed to generate unique ID after %d attempts", attempts)
|
|
}
|
|
|
|
return newID, nil
|
|
}
|
|
|
|
func init() {
|
|
renamePrefixCmd.Flags().Bool("dry-run", false, "Preview changes without applying them")
|
|
renamePrefixCmd.Flags().Bool("repair", false, "Repair database with multiple prefixes by consolidating them")
|
|
rootCmd.AddCommand(renamePrefixCmd)
|
|
}
|