← back to jmgilman__sow

Function bodies 590 total

All specs Real LLM only Function bodies
standard.generateOrchestratorPrompt function · go · L18-L25 (8 LOC)
cli/internal/projects/standard/prompts.go
func generateOrchestratorPrompt(p *state.Project) string {
	// Render orchestrator guidance template
	prompt, err := templates.Render(templatesFS, "templates/orchestrator.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering orchestrator prompt: %v", err)
	}
	return prompt
}
standard.generateImplementationPlanningPrompt function · go · L29-L62 (34 LOC)
cli/internal/projects/standard/prompts.go
func generateImplementationPlanningPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Check if this is a rework iteration
	implPhase, exists := p.Phases["implementation"]
	if exists && implPhase.Iteration > 1 {
		// Show rework iteration number
		buf.WriteString(fmt.Sprintf("## 🔄 Rework Iteration: %d\n\n", implPhase.Iteration))

		// Show previous review failure context
		reviewPhase, rExists := p.Phases["review"]
		if rExists && reviewPhase.Status == "failed" {
			buf.WriteString("⚠️ **Previous review failed** - tasks must address identified issues.\n\n")
			addFailedReviewContext(&buf, &reviewPhase)
		}
	}

	// Render implementation planning guidance template
	guidance, err := templates.Render(templatesFS, "templates/im
standard.generateImplementationExecutingPrompt function · go · L66-L96 (31 LOC)
cli/internal/projects/standard/prompts.go
func generateImplementationExecutingPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Show iteration if this is rework
	if implPhase, exists := p.Phases["implementation"]; exists && implPhase.Iteration > 1 {
		buf.WriteString(fmt.Sprintf("## Implementation Iteration: %d\n\n", implPhase.Iteration))
	}

	// Add task summary
	if implPhase, exists := p.Phases["implementation"]; exists && len(implPhase.Tasks) > 0 {
		buf.WriteString(taskSummary(implPhase.Tasks))
		buf.WriteString("\n")
	}

	// Render execution guidance template
	guidance, err := templates.Render(templatesFS, "templates/implementation_executing.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering template: %v", err)
	}
	buf.WriteString(guidance)

	re
standard.generateReviewPrompt function · go · L100-L152 (53 LOC)
cli/internal/projects/standard/prompts.go
func generateReviewPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Display review iteration from metadata
	iteration := 1
	if reviewPhase, exists := p.Phases["review"]; exists && reviewPhase.Metadata != nil {
		if iter, ok := reviewPhase.Metadata["iteration"].(int); ok {
			iteration = iter
		} else if iter64, ok := reviewPhase.Metadata["iteration"].(int64); ok {
			iteration = int(iter64)
		}
	}
	buf.WriteString(fmt.Sprintf("## Review Iteration: %d\n\n", iteration))

	// Show previous review assessment if iteration > 1
	if iteration > 1 {
		buf.WriteString("### Previous Review\n\n")
		if prevReview := findPreviousReviewArtifact(p, iteration-1); prevReview != nil {
			assessment := extractReviewAssessment(prevReview)
	
standard.generateFinalizeChecksPrompt function · go · L156-L175 (20 LOC)
cli/internal/projects/standard/prompts.go
func generateFinalizeChecksPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Render finalize checks guidance template
	guidance, err := templates.Render(templatesFS, "templates/finalize_checks.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering template: %v", err)
	}
	buf.WriteString(guidance)

	return buf.String()
}
standard.generateImplementationDraftPRCreationPrompt function · go · L179-L198 (20 LOC)
cli/internal/projects/standard/prompts.go
func generateImplementationDraftPRCreationPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Render draft PR creation guidance template
	guidance, err := templates.Render(templatesFS, "templates/implementation_draft_pr_creation.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering template: %v", err)
	}
	buf.WriteString(guidance)

	return buf.String()
}
standard.generateFinalizePRReadyPrompt function · go · L202-L245 (44 LOC)
cli/internal/projects/standard/prompts.go
func generateFinalizePRReadyPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Show PR body artifact status if exists
	if finalizePhase, exists := p.Phases["finalize"]; exists && len(finalizePhase.Outputs) > 0 {
		buf.WriteString("## PR Body Artifact\n\n")
		for _, artifact := range finalizePhase.Outputs {
			if artifact.Type == "pr_body" {
				status := "pending approval"
				if artifact.Approved {
					status = "approved"
				}
				buf.WriteString(fmt.Sprintf("- %s (%s)\n\n", artifact.Path, status))
			}
		}
	}

	// Show PR info from implementation metadata
	if implPhase, exists := p.Phases["implementation"]; exists && implPhase.Metadata != nil {
		if prURL, ok := implPhase.Metadata["pr_url"].(string); ok && prURL != ""
Repobility · code-quality intelligence · https://repobility.com
standard.generateFinalizePRChecksPrompt function · go · L249-L275 (27 LOC)
cli/internal/projects/standard/prompts.go
func generateFinalizePRChecksPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Show PR URL if available
	if finalizePhase, exists := p.Phases["finalize"]; exists && finalizePhase.Metadata != nil {
		if prURL, ok := finalizePhase.Metadata["pr_url"].(string); ok && prURL != "" {
			buf.WriteString(fmt.Sprintf("## Pull Request\n\n%s\n\n", prURL))
		}
	}

	// Render PR checks guidance template
	guidance, err := templates.Render(templatesFS, "templates/finalize_pr_checks.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering template: %v", err)
	}
	buf.WriteString(guidance)

	return buf.String()
}
standard.addFailedReviewContext function · go · L278-L294 (17 LOC)
cli/internal/projects/standard/prompts.go
func addFailedReviewContext(buf *strings.Builder, reviewPhase *projschema.PhaseState) {
	// Find latest failed review
	for i := len(reviewPhase.Outputs) - 1; i >= 0; i-- {
		artifact := &reviewPhase.Outputs[i]
		if artifact.Type == "review" && artifact.Approved {
			assessment, ok := artifact.Metadata["assessment"].(string)
			if ok && assessment == "fail" {
				fmt.Fprintf(buf, "Review report: %s\n", artifact.Path)
				if reviewPhase.Failed_at.Year() > 1 {
					fmt.Fprintf(buf, "Failed at: %s\n", reviewPhase.Failed_at.Format("2006-01-02 15:04:05"))
				}
				buf.WriteString("\n")
				break
			}
		}
	}
}
standard.generateFinalizeCleanupPrompt function · go · L298-L324 (27 LOC)
cli/internal/projects/standard/prompts.go
func generateFinalizeCleanupPrompt(p *state.Project) string {
	var buf strings.Builder

	// Add project header
	buf.WriteString(fmt.Sprintf("# Project: %s\n", p.Name))
	buf.WriteString(fmt.Sprintf("Branch: %s\n", p.Branch))
	if p.Description != "" {
		buf.WriteString(fmt.Sprintf("Description: %s\n", p.Description))
	}
	buf.WriteString("\n")

	// Include PR URL if available
	if finalizePhase, exists := p.Phases["finalize"]; exists && finalizePhase.Metadata != nil {
		if prURL, ok := finalizePhase.Metadata["pr_url"].(string); ok && prURL != "" {
			buf.WriteString(fmt.Sprintf("## Pull Request\n\n%s\n\n", prURL))
		}
	}

	// Render finalize cleanup guidance template
	guidance, err := templates.Render(templatesFS, "templates/finalize_cleanup.md", p)
	if err != nil {
		return fmt.Sprintf("Error rendering template: %v", err)
	}
	buf.WriteString(guidance)

	return buf.String()
}
standard.taskSummary function · go · L330-L367 (38 LOC)
cli/internal/projects/standard/prompts.go
func taskSummary(tasks []projschema.TaskState) string {
	var buf strings.Builder

	total := len(tasks)
	completed := 0
	inProgress := 0
	pending := 0
	abandoned := 0

	for _, task := range tasks {
		switch task.Status {
		case "completed":
			completed++
		case "in_progress":
			inProgress++
		case "pending":
			pending++
		case "abandoned":
			abandoned++
		}
	}

	buf.WriteString(fmt.Sprintf("## Tasks (%d total)\n\n", total))
	if completed > 0 {
		buf.WriteString(fmt.Sprintf("- %d completed\n", completed))
	}
	if inProgress > 0 {
		buf.WriteString(fmt.Sprintf("- %d in progress\n", inProgress))
	}
	if pending > 0 {
		buf.WriteString(fmt.Sprintf("- %d pending\n", pending))
	}
	if abandoned > 0 {
		buf.WriteString(fmt.Sprintf("- %d abandoned\n", abandoned))
	}

	return buf.String()
}
standard.findPreviousReviewArtifact function · go · L370-L390 (21 LOC)
cli/internal/projects/standard/prompts.go
func findPreviousReviewArtifact(p *state.Project, targetIteration int) *projschema.ArtifactState {
	reviewPhase, exists := p.Phases["review"]
	if !exists {
		return nil
	}

	// Search backwards through artifacts for matching iteration
	for i := len(reviewPhase.Outputs) - 1; i >= 0; i-- {
		artifact := &reviewPhase.Outputs[i]
		if !isReviewArtifact(artifact) {
			continue
		}
		if iter, ok := artifact.Metadata["iteration"].(int); ok && iter == targetIteration {
			return artifact
		}
		if iter64, ok := artifact.Metadata["iteration"].(int64); ok && int(iter64) == targetIteration {
			return artifact
		}
	}
	return nil
}
standard.isReviewArtifact function · go · L393-L399 (7 LOC)
cli/internal/projects/standard/prompts.go
func isReviewArtifact(artifact *projschema.ArtifactState) bool {
	if artifact.Metadata == nil {
		return false
	}
	artifactType, ok := artifact.Metadata["type"].(string)
	return ok && artifactType == "review"
}
standard.extractReviewAssessment function · go · L402-L410 (9 LOC)
cli/internal/projects/standard/prompts.go
func extractReviewAssessment(artifact *projschema.ArtifactState) string {
	if artifact.Metadata == nil {
		return "unknown"
	}
	if assess, ok := artifact.Metadata["assessment"].(string); ok {
		return assess
	}
	return "unknown"
}
standard.NewStandardProjectConfig function · go · L17-L25 (9 LOC)
cli/internal/projects/standard/standard.go
func NewStandardProjectConfig() *project.ProjectTypeConfig {
	builder := project.NewProjectTypeConfigBuilder("standard")
	builder = configurePhases(builder)
	builder = configureTransitions(builder)
	builder = configureEventDeterminers(builder)
	builder = configurePrompts(builder)
	builder = builder.WithInitializer(initializeStandardProject)
	return builder.Build()
}
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
standard.initializeStandardProject function · go · L33-L58 (26 LOC)
cli/internal/projects/standard/standard.go
func initializeStandardProject(p *state.Project, initialInputs map[string][]projschema.ArtifactState) error {
	now := p.Created_at
	phaseNames := []string{"implementation", "review", "finalize"}

	for _, phaseName := range phaseNames {
		// Get initial inputs for this phase (empty slice if none provided)
		inputs := []projschema.ArtifactState{}
		if initialInputs != nil {
			if phaseInputs, exists := initialInputs[phaseName]; exists {
				inputs = phaseInputs
			}
		}

		p.Phases[phaseName] = projschema.PhaseState{
			Status:     "pending",
			Enabled:    false,
			Created_at: now,
			Inputs:     inputs, // Use provided initial inputs
			Outputs:    []projschema.ArtifactState{},
			Tasks:      []projschema.TaskState{},
			Metadata:   make(map[string]interface{}),
		}
	}

	return nil
}
standard.configurePhases function · go · L60-L81 (22 LOC)
cli/internal/projects/standard/standard.go
func configurePhases(builder *project.ProjectTypeConfigBuilder) *project.ProjectTypeConfigBuilder {
	return builder.
		WithPhase("implementation",
			project.WithStartState(project.State(ImplementationPlanning)),
			project.WithEndState(project.State(ImplementationExecuting)),
			project.WithOutputs("task_list"),
			project.WithTasks(),
			project.WithMetadataSchema(implementationMetadataSchema),
		).
		WithPhase("review",
			project.WithStartState(project.State(ReviewActive)),
			project.WithEndState(project.State(ReviewActive)),
			project.WithOutputs("review"),
			project.WithMetadataSchema(reviewMetadataSchema),
		).
		WithPhase("finalize",
			project.WithStartState(project.State(FinalizeChecks)),
			project.WithEndState(project.State(FinalizeCleanup)),
			project.WithOutputs("pr_body"),
			project.WithMetadataSchema(finalizeMetadataSchema),
		)
}
standard.configureTransitions function · go · L83-L211 (129 LOC)
cli/internal/projects/standard/standard.go
func configureTransitions(builder *project.ProjectTypeConfigBuilder) *project.ProjectTypeConfigBuilder {
	return builder.

		// ===== STATE MACHINE =====

		SetInitialState(project.State(ImplementationPlanning)).

		// Project initialization
		AddTransition(
			project.State(NoProject),
			project.State(ImplementationPlanning),
			project.Event(EventProjectInit),
			project.WithProjectDescription("Initialize project and begin implementation planning"),
		).

		// Implementation planning → draft PR creation
		AddTransition(
			project.State(ImplementationPlanning),
			project.State(ImplementationDraftPRCreation),
			project.Event(EventPlanningComplete),
			project.WithProjectDescription("Task descriptions approved, create draft PR"),
			project.WithProjectGuard("task descriptions approved", func(p *state.Project) bool {
				return allTaskDescriptionsApproved(p)
			}),
		).

		// Draft PR creation → execution
		AddTransition(
			project.State(ImplementationDraftPRCreation),
			project.St
standard.configureEventDeterminers function · go · L213-L238 (26 LOC)
cli/internal/projects/standard/standard.go
func configureEventDeterminers(builder *project.ProjectTypeConfigBuilder) *project.ProjectTypeConfigBuilder {
	return builder.
		OnAdvance(project.State(ImplementationPlanning), func(_ *state.Project) (project.Event, error) {
			return project.Event(EventPlanningComplete), nil
		}).
		OnAdvance(project.State(ImplementationDraftPRCreation), func(_ *state.Project) (project.Event, error) {
			return project.Event(EventDraftPRCreated), nil
		}).
		OnAdvance(project.State(ImplementationExecuting), func(_ *state.Project) (project.Event, error) {
			return project.Event(EventAllTasksComplete), nil
		}).
		// NOTE: ReviewActive OnAdvance is auto-generated by AddBranch (see configureTransitions)
		// The discriminator function getReviewAssessment determines pass/fail branching
		OnAdvance(project.State(FinalizeChecks), func(_ *state.Project) (project.Event, error) {
			return project.Event(EventChecksDone), nil
		}).
		OnAdvance(project.State(FinalizePRReady), func(_ *state.Project) (project.Ev
standard.configurePrompts function · go · L240-L254 (15 LOC)
cli/internal/projects/standard/standard.go
func configurePrompts(builder *project.ProjectTypeConfigBuilder) *project.ProjectTypeConfigBuilder {
	return builder.
		// Orchestrator-level prompt (how standard projects work)
		WithOrchestratorPrompt(generateOrchestratorPrompt).

		// State-level prompts (what to do in each state)
		WithPrompt(project.State(ImplementationPlanning), generateImplementationPlanningPrompt).
		WithPrompt(project.State(ImplementationDraftPRCreation), generateImplementationDraftPRCreationPrompt).
		WithPrompt(project.State(ImplementationExecuting), generateImplementationExecutingPrompt).
		WithPrompt(project.State(ReviewActive), generateReviewPrompt).
		WithPrompt(project.State(FinalizeChecks), generateFinalizeChecksPrompt).
		WithPrompt(project.State(FinalizePRReady), generateFinalizePRReadyPrompt).
		WithPrompt(project.State(FinalizePRChecks), generateFinalizePRChecksPrompt).
		WithPrompt(project.State(FinalizeCleanup), generateFinalizeCleanupPrompt)
}
refs.FileType.Init method · go · L35-L44 (10 LOC)
cli/internal/refs/file.go
func (f *FileType) Init(_ context.Context, cacheDir string) error {
	// Create file cache directory
	fileCacheDir := filepath.Join(cacheDir, "file")

	if err := os.MkdirAll(fileCacheDir, 0o755); err != nil {
		return fmt.Errorf("failed to create file cache directory: %w", err)
	}

	return nil
}
refs.FileType.Cache method · go · L47-L107 (61 LOC)
cli/internal/refs/file.go
func (f *FileType) Cache(_ context.Context, cacheDir string, ref *schemas.Ref) (string, error) {
	// Parse file URL to get source path
	sourcePath, err := FileURLToPath(ref.Source)
	if err != nil {
		return "", fmt.Errorf("failed to parse file URL: %w", err)
	}

	// Validate source path exists
	info, err := os.Stat(sourcePath)
	if err != nil {
		if os.IsNotExist(err) {
			return "", fmt.Errorf("source path does not exist: %s", sourcePath)
		}
		return "", fmt.Errorf("failed to stat source path: %w", err)
	}

	// Source must be a directory
	if !info.IsDir() {
		return "", fmt.Errorf("source path must be a directory: %s", sourcePath)
	}

	// Get cache path
	cachePath := f.CachePath(cacheDir, ref)

	// Check if symlink already exists
	linkInfo, err := os.Lstat(cachePath)
	if err == nil {
		// Symlink exists, verify it's actually a symlink
		if linkInfo.Mode()&os.ModeSymlink == 0 {
			return "", fmt.Errorf("cache path exists but is not a symlink: %s", cachePath)
		}

		// Check if it point
refs.FileType.Cleanup method · go · L128-L147 (20 LOC)
cli/internal/refs/file.go
func (f *FileType) Cleanup(_ context.Context, cacheDir string, ref *schemas.Ref) error {
	// Get cache path
	cachePath := f.CachePath(cacheDir, ref)

	// Check if it exists
	if _, err := os.Lstat(cachePath); err != nil {
		if os.IsNotExist(err) {
			// Already removed, nothing to do
			return nil
		}
		return fmt.Errorf("failed to stat cache path: %w", err)
	}

	// Remove the symlink
	if err := os.Remove(cachePath); err != nil {
		return fmt.Errorf("failed to remove symlink: %w", err)
	}

	return nil
}
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
refs.FileType.ValidateConfig method · go · L150-L164 (15 LOC)
cli/internal/refs/file.go
func (f *FileType) ValidateConfig(config schemas.RefConfig) error {
	// File type doesn't use additional config
	// Path is in the source URL itself

	// Validate that no git-specific config is set
	if config.Branch != "" {
		return fmt.Errorf("file refs do not support branch config")
	}

	if config.Path != "" {
		return fmt.Errorf("file refs do not support path config (path is in URL)")
	}

	return nil
}
refs.GitType.Init method · go · L42-L56 (15 LOC)
cli/internal/refs/git.go
func (g *GitType) Init(_ context.Context, cacheDir string) error {
	// Initialize the repository cache
	gitCacheDir := filepath.Join(cacheDir, "git")

	cache, err := cache.NewRepositoryCache(gitCacheDir)
	if err != nil {
		return fmt.Errorf("failed to create git cache: %w", err)
	}

	g.cacheMu.Lock()
	g.cache = cache
	g.cacheMu.Unlock()

	return nil
}
refs.GitType.ensureCache method · go · L59-L75 (17 LOC)
cli/internal/refs/git.go
func (g *GitType) ensureCache(cacheDir string) error {
	g.cacheMu.Lock()
	defer g.cacheMu.Unlock()

	if g.cache != nil {
		return nil
	}

	gitCacheDir := filepath.Join(cacheDir, "git")
	cache, err := cache.NewRepositoryCache(gitCacheDir)
	if err != nil {
		return fmt.Errorf("failed to create git cache: %w", err)
	}

	g.cache = cache
	return nil
}
refs.GitType.Cache method · go · L78-L105 (28 LOC)
cli/internal/refs/git.go
func (g *GitType) Cache(ctx context.Context, cacheDir string, ref *schemas.Ref) (string, error) {
	// Ensure cache is initialized
	if err := g.ensureCache(cacheDir); err != nil {
		return "", err
	}

	// Get git-compatible URL (strips git+ prefix for actual git operations)
	gitURL := toGitURL(ref.Source)

	// Build cache options
	opts := []cache.CacheOption{}

	// Add branch if specified
	if ref.Config.Branch != "" {
		opts = append(opts, cache.WithRef(ref.Config.Branch))
	}

	// Get checkout using ref.Id as stable cache key
	// This creates or reuses existing checkout
	checkoutPath, err := g.cache.GetCheckout(ctx, gitURL, ref.Id, opts...)
	if err != nil {
		return "", fmt.Errorf("failed to get checkout: %w", err)
	}

	// If a subpath is specified, we'll return the checkout path
	// The caller (symlink creation) will handle pointing to the subpath
	return checkoutPath, nil
}
refs.GitType.Update method · go · L108-L136 (29 LOC)
cli/internal/refs/git.go
func (g *GitType) Update(ctx context.Context, cacheDir string, ref *schemas.Ref, _ *schemas.CachedRef) error {
	// Ensure cache is initialized
	if err := g.ensureCache(cacheDir); err != nil {
		return err
	}

	// Get git-compatible URL
	gitURL := toGitURL(ref.Source)

	// Build cache options with update flag
	opts := []cache.CacheOption{
		cache.WithUpdate(), // Force refresh from remote
	}

	// Add branch if specified
	if ref.Config.Branch != "" {
		opts = append(opts, cache.WithRef(ref.Config.Branch))
	}

	// Update the checkout
	_, err := g.cache.GetCheckout(ctx, gitURL, ref.Id, opts...)
	if err != nil {
		return fmt.Errorf("failed to update checkout: %w", err)
	}

	// Note: The cache handles updating cached.Metadata internally
	// We don't need to manually update the CachedRef here
	return nil
}
refs.GitType.IsStale method · go · L139-L157 (19 LOC)
cli/internal/refs/git.go
func (g *GitType) IsStale(_ context.Context, cacheDir string, _ *schemas.Ref, _ *schemas.CachedRef) (bool, error) {
	// Ensure cache is initialized
	if err := g.ensureCache(cacheDir); err != nil {
		return false, err
	}

	// For now, we'll implement a simple check:
	// Try to update and see if anything changed
	// A more sophisticated implementation would fetch and compare SHAs without updating

	// TODO: Implement proper staleness check
	// This could involve:
	// 1. Fetching from remote (git fetch)
	// 2. Comparing local HEAD with remote HEAD
	// 3. Counting commits behind (git rev-list --count HEAD..@{u})
	//
	// For now, we return false and rely on explicit Update() calls
	return false, nil
}
refs.GitType.CachePath method · go · L160-L168 (9 LOC)
cli/internal/refs/git.go
func (g *GitType) CachePath(cacheDir string, ref *schemas.Ref) string {
	// The cache uses this structure:
	// {gitCacheDir}/checkouts/{normalized_url}/{branch}/{ref.Id}/
	//
	// Since we don't have the cache instance to normalize the URL,
	// we'll construct a simplified path
	gitCacheDir := filepath.Join(cacheDir, "git")
	return filepath.Join(gitCacheDir, "checkouts", ref.Id)
}
refs.GitType.Cleanup method · go · L171-L186 (16 LOC)
cli/internal/refs/git.go
func (g *GitType) Cleanup(_ context.Context, cacheDir string, ref *schemas.Ref) error {
	// Ensure cache is initialized
	if err := g.ensureCache(cacheDir); err != nil {
		return err
	}

	// Get git-compatible URL
	gitURL := toGitURL(ref.Source)

	// Remove the checkout using ref.Id as cache key
	if err := g.cache.RemoveCheckout(gitURL, ref.Id); err != nil {
		return fmt.Errorf("failed to remove checkout: %w", err)
	}

	return nil
}
Repobility — the code-quality scanner for AI-generated software · https://repobility.com
refs.GitType.ValidateConfig method · go · L198-L225 (28 LOC)
cli/internal/refs/git.go
func (g *GitType) ValidateConfig(config schemas.RefConfig) error {
	// Validate branch name if specified
	if config.Branch != "" {
		// Basic validation: no spaces, no special chars that would break git
		if len(config.Branch) == 0 {
			return fmt.Errorf("branch cannot be empty string")
		}

		// TODO: More comprehensive branch name validation
		// Git branch names can't contain: .., @{, \, ^, ~, :, ?, *, [, spaces at start/end
	}

	// Validate path if specified
	if config.Path != "" {
		// Ensure no path traversal attempts
		cleaned := filepath.Clean(config.Path)
		if filepath.IsAbs(cleaned) {
			return fmt.Errorf("path must be relative, not absolute: %s", config.Path)
		}

		// Check for .. traversal (cleaned path shouldn't start with .. or contain ../)
		if cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "..\\") {
			return fmt.Errorf("path contains invalid traversal: %s", config.Path)
		}
	}

	return nil
}
refs.Manager.Add method · go · L28-L142 (115 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) Add(ctx context.Context, url string, opts ...RefOption) (*Ref, error) {
	// Apply options
	cfg := &refConfig{
		semantic: "knowledge", // default
		local:    false,
	}
	for _, opt := range opts {
		opt(cfg)
	}

	// Validate required fields
	if cfg.link == "" {
		return nil, fmt.Errorf("ref link is required (use WithRefLink option)")
	}
	if cfg.description == "" {
		return nil, fmt.Errorf("ref description is required (use WithRefDescription option)")
	}

	// Validate semantic type
	if cfg.semantic != "knowledge" && cfg.semantic != "code" {
		return nil, fmt.Errorf("semantic must be 'knowledge' or 'code', got: %s", cfg.semantic)
	}

	// Infer type from URL
	typeName, err := InferTypeFromURL(url)
	if err != nil {
		return nil, fmt.Errorf("failed to infer type from URL: %w", err)
	}

	// Get type implementation
	refType, err := GetType(typeName)
	if err != nil {
		return nil, fmt.Errorf("unknown reference type: %s", typeName)
	}

	// Check if type is enabled
	enabled, err
refs.Manager.Get method · go · L145-L173 (29 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) Get(id string) (*Ref, error) {
	// Try committed index first
	committedIndex, err := m.loadCommittedRefIndex()
	if err != nil {
		return nil, fmt.Errorf("failed to load committed index: %w", err)
	}

	for _, ref := range committedIndex.Refs {
		if ref.Id == id {
			return &Ref{manager: m, id: id}, nil
		}
	}

	// Try local index
	localIndex, err := m.loadLocalRefIndex()
	if err != nil && !os.IsNotExist(err) {
		return nil, fmt.Errorf("failed to load local index: %w", err)
	}

	if localIndex != nil {
		for _, ref := range localIndex.Refs {
			if ref.Id == id {
				return &Ref{manager: m, id: id}, nil
			}
		}
	}

	return nil, fmt.Errorf("ref %q not found", id)
}
refs.Manager.List method · go · L176-L214 (39 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) List(opts ...RefListOption) ([]*Ref, error) {
	// Apply options
	cfg := &refListConfig{}
	for _, opt := range opts {
		opt(cfg)
	}

	var allRefs []schemas.Ref

	// Load committed refs unless localOnly
	if !cfg.localOnly {
		committedIndex, err := m.loadCommittedRefIndex()
		if err != nil {
			return nil, fmt.Errorf("failed to load committed index: %w", err)
		}
		allRefs = append(allRefs, committedIndex.Refs...)
	}

	// Load local refs unless committedOnly
	if !cfg.committedOnly {
		localIndex, err := m.loadLocalRefIndex()
		if err != nil && !os.IsNotExist(err) {
			return nil, fmt.Errorf("failed to load local index: %w", err)
		}
		if localIndex != nil {
			allRefs = append(allRefs, localIndex.Refs...)
		}
	}

	// Filter refs
	var filtered []*Ref
	for _, ref := range allRefs {
		if m.matchesRefFilters(ref, cfg) {
			filtered = append(filtered, &Ref{manager: m, id: ref.Id})
		}
	}

	return filtered, nil
}
refs.Manager.Remove method · go · L217-L265 (49 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) Remove(ctx context.Context, id string, pruneCache bool) error {
	// Find the ref in either index
	ref, isLocal, err := m.findRefInIndexes(id)
	if err != nil {
		return err
	}

	// Create cache manager
	sowDir := filepath.Join(m.ctx.RepoRoot(), ".sow")
	cacheManager, err := NewCacheManager(sowDir)
	if err != nil {
		return fmt.Errorf("failed to create refs cache manager: %w", err)
	}

	// Remove via cache manager (handles cache cleanup if pruneCache is true)
	if pruneCache {
		if err := cacheManager.Remove(ctx, ref); err != nil {
			return fmt.Errorf("failed to remove ref: %w", err)
		}
	} else {
		// Just remove the symlink, keep cache
		workspacePath := filepath.Join(m.ctx.RepoRoot(), ".sow", "refs", ref.Link)
		if err := os.Remove(workspacePath); err != nil && !os.IsNotExist(err) {
			return fmt.Errorf("failed to remove workspace symlink: %w", err)
		}
	}

	// Remove from index
	index, _, err := m.loadRefIndex(isLocal)
	if err != nil {
		return fmt.Errorf("failed to
refs.Manager.InitRefs method · go · L269-L313 (45 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) InitRefs(ctx context.Context) error {
	// Load committed index
	committedIndex, err := m.loadCommittedRefIndex()
	if err != nil {
		return fmt.Errorf("failed to load committed index: %w", err)
	}

	// Create cache manager
	sowDir := filepath.Join(m.ctx.RepoRoot(), ".sow")
	cacheManager, err := NewCacheManager(sowDir)
	if err != nil {
		return fmt.Errorf("failed to create refs cache manager: %w", err)
	}

	// Install each ref
	for _, ref := range committedIndex.Refs {
		// Check if type is enabled
		typeName, err := InferTypeFromURL(ref.Source)
		if err != nil {
			return fmt.Errorf("failed to infer type for ref %s: %w", ref.Id, err)
		}

		refType, err := GetType(typeName)
		if err != nil {
			return fmt.Errorf("unknown type for ref %s: %s", ref.Id, typeName)
		}

		enabled, err := refType.IsEnabled(ctx)
		if err != nil {
			return fmt.Errorf("failed to check if type enabled for ref %s: %w", ref.Id, err)
		}

		if !enabled {
			// Skip disabled types with warning (cal
refs.Manager.generateRefID method · go · L370-L414 (45 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) generateRefID(url, typeName string) string {
	// This logic mirrors the original generateIDFromURL in refs/refs.go
	switch typeName {
	case "git":
		// Remove scheme prefix
		for _, prefix := range []string{"git+https://", "git+ssh://", "git+http://", "git@"} {
			if len(url) > len(prefix) && url[:len(prefix)] == prefix {
				url = url[len(prefix):]
				break
			}
		}

		// Remove domain (take last 2 path components)
		parts := strings.Split(url, "/")
		if len(parts) >= 2 {
			url = parts[len(parts)-2] + "-" + parts[len(parts)-1]
		}

		// Remove .git suffix
		if len(url) > 4 && url[len(url)-4:] == ".git" {
			url = url[:len(url)-4]
		}

	case "file":
		// Get base directory name
		if len(url) > 7 && url[:7] == "file://" {
			url = url[7:]
		}
		if len(url) > 0 && url[len(url)-1] == '/' {
			url = url[:len(url)-1]
		}
		parts := strings.Split(url, "/")
		if len(parts) > 0 {
			url = parts[len(parts)-1]
		}
	}

	// Convert to kebab-case
	url = strings.ToLower(url)
	url
refs.Manager.loadRefIndex method · go · L417-L438 (22 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) loadRefIndex(isLocal bool) (*schemas.RefsCommittedIndex, bool, error) {
	if isLocal {
		localIndex, err := m.loadLocalRefIndex()
		if err != nil && !os.IsNotExist(err) {
			return nil, true, err
		}
		if localIndex == nil {
			localIndex = &schemas.RefsLocalIndex{
				Version: "1.0.0",
				Refs:    []schemas.Ref{},
			}
		}
		// Convert to committed index structure
		return &schemas.RefsCommittedIndex{
			Version: localIndex.Version,
			Refs:    localIndex.Refs,
		}, true, nil
	}

	committedIndex, err := m.loadCommittedRefIndex()
	return committedIndex, false, err
}
Repobility · code-quality intelligence · https://repobility.com
refs.Manager.saveRefIndex method · go · L441-L454 (14 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) saveRefIndex(index *schemas.RefsCommittedIndex, isLocal bool) error {
	fs := m.ctx.FS()

	if isLocal {
		localIndex := &schemas.RefsLocalIndex{
			Version: "1.0.0",
			Refs:    index.Refs,
		}
		return m.saveLocalRefIndex(fs, localIndex)
	}

	index.Version = "1.0.0"
	return m.saveCommittedRefIndex(fs, index)
}
refs.Manager.loadCommittedRefIndex method · go · L457-L483 (27 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) loadCommittedRefIndex() (*schemas.RefsCommittedIndex, error) {
	fs := m.ctx.FS()
	path := "refs/index.json"

	// Check if file exists
	if _, err := fs.Stat(path); err != nil {
		if os.IsNotExist(err) {
			// Return empty index
			return &schemas.RefsCommittedIndex{
				Version: "1.0.0",
				Refs:    []schemas.Ref{},
			}, nil
		}
		return nil, fmt.Errorf("failed to stat committed refs index: %w", err)
	}

	data, err := fs.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to read committed refs index: %w", err)
	}

	var index schemas.RefsCommittedIndex
	if err := unmarshalJSON(data, &index); err != nil {
		return nil, err
	}
	return &index, nil
}
refs.Manager.loadLocalRefIndex method · go · L486-L506 (21 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) loadLocalRefIndex() (*schemas.RefsLocalIndex, error) {
	fs := m.ctx.FS()
	path := "refs/index.local.json"

	// Check if file exists
	if _, err := fs.Stat(path); err != nil {
		// Return unwrapped so callers can check os.IsNotExist()
		return nil, err //nolint:wrapcheck // Intentionally unwrapped for os.IsNotExist() checks
	}

	data, err := fs.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to read local refs index: %w", err)
	}

	var index schemas.RefsLocalIndex
	if err := unmarshalJSON(data, &index); err != nil {
		return nil, err
	}
	return &index, nil
}
refs.Manager.saveCommittedRefIndex method · go · L509-L519 (11 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) saveCommittedRefIndex(fs sow.FS, index *schemas.RefsCommittedIndex) error {
	path := "refs/index.json"
	data, err := marshalJSON(index)
	if err != nil {
		return err
	}
	if err := fs.WriteFile(path, data, 0644); err != nil {
		return fmt.Errorf("failed to write committed refs index: %w", err)
	}
	return nil
}
refs.Manager.saveLocalRefIndex method · go · L522-L532 (11 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) saveLocalRefIndex(fs sow.FS, index *schemas.RefsLocalIndex) error {
	path := "refs/index.local.json"
	data, err := marshalJSON(index)
	if err != nil {
		return err
	}
	if err := fs.WriteFile(path, data, 0644); err != nil {
		return fmt.Errorf("failed to write local refs index: %w", err)
	}
	return nil
}
refs.Manager.findRefInIndexes method · go · L536-L564 (29 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) findRefInIndexes(id string) (*schemas.Ref, bool, error) {
	// Try committed index first
	committedIndex, err := m.loadCommittedRefIndex()
	if err != nil {
		return nil, false, fmt.Errorf("failed to load committed index: %w", err)
	}

	for _, ref := range committedIndex.Refs {
		if ref.Id == id {
			return &ref, false, nil
		}
	}

	// Try local index
	localIndex, err := m.loadLocalRefIndex()
	if err != nil && !os.IsNotExist(err) {
		return nil, false, fmt.Errorf("failed to load local index: %w", err)
	}

	if localIndex != nil {
		for _, ref := range localIndex.Refs {
			if ref.Id == id {
				return &ref, true, nil
			}
		}
	}

	return nil, false, fmt.Errorf("ref %q not found", id)
}
refs.Manager.matchesRefFilters method · go · L567-L598 (32 LOC)
cli/internal/refs/index_manager.go
func (m *Manager) matchesRefFilters(ref schemas.Ref, cfg *refListConfig) bool {
	// Filter by type
	if cfg.typeFilter != "" {
		refType, err := InferTypeFromURL(ref.Source)
		if err != nil || refType != cfg.typeFilter {
			return false
		}
	}

	// Filter by semantic
	if cfg.semanticFilter != "" && ref.Semantic != cfg.semanticFilter {
		return false
	}

	// Filter by tags
	if len(cfg.tagsFilter) > 0 {
		for _, filterTag := range cfg.tagsFilter {
			found := false
			for _, refTag := range ref.Tags {
				if refTag == filterTag {
					found = true
					break
				}
			}
			if !found {
				return false
			}
		}
	}

	return true
}
refs.NewCacheManager function · go · L21-L30 (10 LOC)
cli/internal/refs/manager.go
func NewCacheManager(sowDir string) (*CacheManager, error) {
	cacheDir, err := DefaultCacheDir()
	if err != nil {
		return nil, err
	}
	return &CacheManager{
		cacheDir: cacheDir,
		sowDir:   sowDir,
	}, nil
}
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
refs.NewCacheManagerWithCache function · go · L34-L39 (6 LOC)
cli/internal/refs/manager.go
func NewCacheManagerWithCache(cacheDir, sowDir string) *CacheManager {
	return &CacheManager{
		cacheDir: cacheDir,
		sowDir:   sowDir,
	}
}
refs.DefaultCacheDir function · go · L43-L49 (7 LOC)
cli/internal/refs/manager.go
func DefaultCacheDir() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("failed to get home directory: %w", err)
	}
	return filepath.Join(homeDir, ".cache", "sow", "refs"), nil
}
refs.CacheManager.Install method · go · L53-L91 (39 LOC)
cli/internal/refs/manager.go
func (m *CacheManager) Install(ctx context.Context, ref *schemas.Ref) (string, error) {
	// Infer type from URL
	typeName, err := InferTypeFromURL(ref.Source)
	if err != nil {
		return "", fmt.Errorf("failed to infer type from URL: %w", err)
	}

	// Get the ref type implementation
	refType, err := TypeForScheme(ctx, typeName)
	if err != nil {
		return "", fmt.Errorf("failed to get ref type: %w", err)
	}

	// Validate config for this type
	if err := refType.ValidateConfig(ref.Config); err != nil {
		return "", fmt.Errorf("invalid config for type %s: %w", typeName, err)
	}

	// Cache the ref (downloads/clones to cache directory)
	cachePath, err := refType.Cache(ctx, m.cacheDir, ref)
	if err != nil {
		return "", fmt.Errorf("failed to cache ref: %w", err)
	}

	// Apply subpath if specified (for git refs)
	if ref.Config.Path != "" {
		cachePath = filepath.Join(cachePath, ref.Config.Path)
	}

	// Determine workspace path based on semantic type
	workspacePath := m.workspacePath(ref)

	// Cre
‹ prevpage 8 / 12next ›