db

package
v0.1.0-alpha.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StatusPending    = "pending"
	StatusProcessing = "processing"
	StatusIdle       = "idle"
	StatusCompleted  = "completed"
	StatusFailed     = "failed"
	StatusMerged     = "merged"
)

Status constants for bead tracking.

View Source
const (
	PRStateOpen   = "open"
	PRStateClosed = "closed"
	PRStateMerged = "merged"
)

PR state constants

View Source
const (
	CIStatusPending = "pending"
	CIStatusSuccess = "success"
	CIStatusFailure = "failure"
)

CI status constants

View Source
const (
	ApprovalStatusPending          = "pending"
	ApprovalStatusApproved         = "approved"
	ApprovalStatusChangesRequested = "changes_requested"
)

Approval status constants

View Source
const (
	MergeableStateClean    = "CLEAN"    // Ready to merge
	MergeableStateDirty    = "DIRTY"    // Has conflicts
	MergeableStateBlocked  = "BLOCKED"  // Blocked by checks
	MergeableStateBehind   = "BEHIND"   // Behind base branch
	MergeableStateDraft    = "DRAFT"    // Draft PR
	MergeableStateUnstable = "UNSTABLE" // CI unstable
	MergeableStateUnknown  = "UNKNOWN"  // Unknown state
)

Mergeable state constants (from GitHub API mergeStateStatus)

View Source
const (
	ProcessTypeControlPlane = "control_plane"
	ProcessTypeOrchestrator = "orchestrator"
)

Process types

View Source
const (
	DefaultHeartbeatInterval  = 10 * time.Second
	DefaultStalenessThreshold = 30 * time.Second
)

Default intervals for heartbeat monitoring

View Source
const (
	TaskTypePRFeedback          = "pr_feedback"
	TaskTypeCommentResolution   = "comment_resolution"
	TaskTypeGitPush             = "git_push"
	TaskTypeGitHubComment       = "github_comment"
	TaskTypeGitHubResolveThread = "github_resolve_thread"
	TaskTypeCreateWorktree      = "create_worktree"
	TaskTypeImportPR            = "import_pr"
	TaskTypeSpawnOrchestrator   = "spawn_orchestrator"
	TaskTypeDestroyWorktree     = "destroy_worktree"
	TaskTypeWatchWorkflowRun    = "watch_workflow_run"
)

Task types for the scheduler

View Source
const (
	TaskStatusPending   = "pending"
	TaskStatusExecuting = "executing"
	TaskStatusCompleted = "completed"
	TaskStatusFailed    = "failed"
)

Task statuses

View Source
const DefaultMaxAttempts = 5

DefaultMaxAttempts is the default max attempts for retry tasks.

View Source
const OptimisticExecutionDelay = 30 * time.Second

OptimisticExecutionDelay is how long to wait before the scheduler picks up a task that was scheduled with optimistic execution. This prevents a race condition where both the optimistic execution and the scheduler try to execute the same task concurrently.

Variables

This section is empty.

Functions

func HashDescription

func HashDescription(description string) string

HashDescription creates a SHA256 hash of a description string.

func MigrationStatusContext

func MigrationStatusContext(ctx context.Context, db *sql.DB) ([]string, error)

MigrationStatusContext returns the current migration status

func RollbackMigration

func RollbackMigration(ctx context.Context, db *sql.DB) error

RollbackMigration rolls back the last applied migration

func RollbackMigrationForFS

func RollbackMigrationForFS(ctx context.Context, db *sql.DB, fsys embed.FS) error

RollbackMigrationForFS rolls back the last applied migration. It first tries to get down_sql from the database (stored when migration was applied). Falls back to reading from the filesystem if not available in DB.

func RunMigrations

func RunMigrations(ctx context.Context, db *sql.DB) error

RunMigrations applies all pending migrations from the embedded migrationsFS

func RunMigrationsForFS

func RunMigrationsForFS(ctx context.Context, db *sql.DB, fsys embed.FS) error

RunMigrationsForFS applies all pending migrations from the specified filesystem

func TabNameForBead

func TabNameForBead(beadID string) string

TabNameForBead returns the zellij tab name for a bead's planning session.

Types

type CreatePRFeedbackParams

type CreatePRFeedbackParams struct {
	WorkID       string
	PRURL        string
	FeedbackType string
	Title        string
	Description  string
	Source       github.SourceInfo       // Structured source info
	Context      *github.FeedbackContext // Structured context (optional)
	Priority     int
}

CreatePRFeedbackParams holds parameters for creating a PR feedback record.

type DB

type DB struct {
	*sql.DB
	// contains filtered or unexported fields
}

DB wraps the SQLite database connection and sqlc queries.

func OpenPath

func OpenPath(ctx context.Context, dbPath string) (*DB, error)

OpenPath initializes the database at the specified path and runs migrations.

func (*DB) AddBeadToWork

func (db *DB) AddBeadToWork(ctx context.Context, workID, beadID string) error

AddBeadToWork associates a bead with a work. The bead is added at the next available position.

func (*DB) AddTaskDependency

func (db *DB) AddTaskDependency(ctx context.Context, taskID, dependsOnTaskID string) error

AddTaskDependency adds a dependency between two tasks. The task with taskID will depend on the task with dependsOnTaskID, meaning dependsOnTaskID must complete before taskID can run.

func (*DB) AddTaskToWork

func (db *DB) AddTaskToWork(ctx context.Context, workID, taskID string, position int) error

AddTaskToWork associates a task with a work.

func (*DB) AddWorkBead

func (db *DB) AddWorkBead(ctx context.Context, workID, beadID string, position int64) error

AddWorkBead adds a bead to a work with the specified position.

func (*DB) AddWorkBeads

func (db *DB) AddWorkBeads(ctx context.Context, workID string, beadIDs []string) error

AddWorkBeads adds multiple beads to a work. Beads are positioned sequentially starting from the next available position. Returns an error if any bead already exists in the work.

func (*DB) AreAllBeadsEstimated

func (db *DB) AreAllBeadsEstimated(ctx context.Context, beadIDs []string) (bool, error)

AreAllBeadsEstimated checks if all beads in the list have complexity estimates.

func (*DB) CacheComplexity

func (db *DB) CacheComplexity(ctx context.Context, beadID, descHash string, score, tokens int) error

CacheComplexity stores a complexity estimate for a bead in the cache.

func (*DB) CheckAndCompleteTask

func (db *DB) CheckAndCompleteTask(ctx context.Context, taskID string, prURL string) (bool, error)

CheckAndCompleteTask checks if all beads in a task are completed and marks the task as complete if so. Returns true if the task was auto-completed, false if it still has pending beads.

func (*DB) CleanupOldTasks

func (db *DB) CleanupOldTasks(ctx context.Context, olderThan time.Duration) error

CleanupOldTasks removes completed/failed tasks older than the specified duration.

func (*DB) CleanupStaleControlPlane

func (db *DB) CleanupStaleControlPlane(ctx context.Context) error

CleanupStaleControlPlane removes any existing control plane record if its heartbeat is stale. This is used before registering a new control plane to handle cases where the previous control plane was killed without proper cleanup. Returns nil if no control plane exists or if it was successfully cleaned up. Returns an error if the control plane has a fresh heartbeat (likely still alive).

func (*DB) CleanupStaleOrchestrator

func (db *DB) CleanupStaleOrchestrator(ctx context.Context, workID string) error

CleanupStaleOrchestrator removes any existing orchestrator record for a work ID if its heartbeat is stale. This is used before registering a new orchestrator to handle cases where the previous orchestrator was killed without proper cleanup. Returns nil if no orchestrator exists or if it was successfully cleaned up. Returns an error if the orchestrator has a fresh heartbeat (likely still alive).

func (*DB) CleanupStalePlanSessions

func (db *DB) CleanupStalePlanSessions(ctx context.Context) error

CleanupStalePlanSessions removes registrations for processes that are no longer running.

func (*DB) CleanupStaleProcesses

func (db *DB) CleanupStaleProcesses(ctx context.Context, threshold time.Duration) error

CleanupStaleProcesses removes processes with heartbeats older than the threshold.

func (*DB) CompleteBead

func (db *DB) CompleteBead(ctx context.Context, id, prURL string) error

CompleteBead marks a bead as completed with a PR URL.

func (*DB) CompleteTask

func (db *DB) CompleteTask(ctx context.Context, id string, prURL string) error

CompleteTask marks a task as completed.

func (*DB) CompleteTaskBead

func (db *DB) CompleteTaskBead(ctx context.Context, taskID, beadID string) error

CompleteTaskBead marks a specific bead within a task as completed.

func (*DB) CompleteWork

func (db *DB) CompleteWork(ctx context.Context, id, prURL string) error

CompleteWork marks a work as completed with a PR URL.

func (*DB) CompleteWorkAndScheduleFeedback

func (db *DB) CompleteWorkAndScheduleFeedback(ctx context.Context, id, prURL string, prFeedbackInterval, commentResolutionInterval time.Duration) error

CompleteWorkAndScheduleFeedback atomically marks a work as completed and schedules PR feedback polling if a PR URL is provided. This ensures feedback polling is set up exactly when the PR is created, using a transaction to prevent race conditions.

func (*DB) CountTaskBeadStatuses

func (db *DB) CountTaskBeadStatuses(ctx context.Context, taskID string) (total int, completed int, err error)

CountTaskBeadStatuses returns the total and completed count of beads in a task.

func (*DB) CountUnresolvedFeedbackForWork

func (db *DB) CountUnresolvedFeedbackForWork(ctx context.Context, workID string) (int, error)

CountUnresolvedFeedbackForWork returns the count of PR feedback items that have beads which are not yet assigned to any task and not resolved/closed.

func (*DB) CreatePRFeedbackFromParams

func (db *DB) CreatePRFeedbackFromParams(ctx context.Context, params CreatePRFeedbackParams) (*PRFeedback, error)

CreatePRFeedback creates a new PR feedback record with structured source info.

func (*DB) CreateTask

func (db *DB) CreateTask(ctx context.Context, id string, taskType string, beadIDs []string, complexityBudget int, workID string) error

CreateTask creates a new task with the given beads.

func (*DB) CreateWork

func (db *DB) CreateWork(ctx context.Context, id, name, worktreePath, branchName, baseBranch, rootIssueID string, auto bool) error

CreateWork creates a new work unit.

func (*DB) CreateWorkAndSchedulePush

func (db *DB) CreateWorkAndSchedulePush(ctx context.Context, id, name, worktreePath, branchName, baseBranch, rootIssueID string, auto bool) (string, error)

CreateWorkAndSchedulePush creates a work record and schedules a git push task atomically. This implements the transactional outbox pattern to ensure both operations succeed or fail together. Returns the idempotency key for the scheduled push task.

func (*DB) DeleteTask

func (db *DB) DeleteTask(ctx context.Context, taskID string) error

DeleteTask deletes a task and its associated records.

func (*DB) DeleteTaskDependencies

func (db *DB) DeleteTaskDependencies(ctx context.Context, taskID string) error

DeleteTaskDependencies removes all dependencies for a task.

func (*DB) DeleteTaskDependenciesForWork

func (db *DB) DeleteTaskDependenciesForWork(ctx context.Context, workID string) error

DeleteTaskDependenciesForWork removes all task dependencies for tasks in a work.

func (*DB) DeleteTaskDependency

func (db *DB) DeleteTaskDependency(ctx context.Context, taskID, dependsOnTaskID string) error

DeleteTaskDependency removes a single dependency between two tasks.

func (*DB) DeleteWork

func (db *DB) DeleteWork(ctx context.Context, workID string) error

DeleteWork deletes a work and all associated records. This includes: - Task beads associations for all tasks in the work - Tasks belonging to the work - Work-task relationships - Work-bead associations - Scheduled tasks for this work - The work record itself

func (*DB) DeleteWorkBeads

func (db *DB) DeleteWorkBeads(ctx context.Context, workID string) error

DeleteWorkBeads removes all beads from a work.

func (*DB) FailBead

func (db *DB) FailBead(ctx context.Context, id, errMsg string) error

FailBead marks a bead as failed with an error message.

func (*DB) FailTask

func (db *DB) FailTask(ctx context.Context, id string, errorMessage string) error

FailTask marks a task as failed with an error message.

func (*DB) FailTaskBead

func (db *DB) FailTaskBead(ctx context.Context, taskID, beadID string) error

FailTaskBead marks a specific bead within a task as failed.

func (*DB) FailWork

func (db *DB) FailWork(ctx context.Context, id, errMsg string) error

FailWork marks a work as failed with an error message.

func (*DB) GenerateNextWorkID

func (db *DB) GenerateNextWorkID(ctx context.Context) (string, error)

GenerateNextWorkID generates a work ID using content-based hashing. This is a compatibility wrapper that generates a temporary ID.

func (*DB) GenerateWorkID

func (db *DB) GenerateWorkID(ctx context.Context, branchName string, projectName string) (string, error)

GenerateWorkID generates a content-based hash ID for a work. Uses the branch name as the primary content for hashing.

func (*DB) GetAllAssignedBeads

func (db *DB) GetAllAssignedBeads(ctx context.Context) (map[string]string, error)

GetAllAssignedBeads returns a map of bead IDs to work IDs for all beads that are assigned to any work. This is used by plan mode to show which beads are already assigned.

func (*DB) GetAllCachedComplexity

func (db *DB) GetAllCachedComplexity(ctx context.Context) (map[string]struct{ Score, Tokens int }, error)

GetAllCachedComplexity returns all cached complexity estimates.

func (*DB) GetAllProcesses

func (db *DB) GetAllProcesses(ctx context.Context) ([]*Process, error)

GetAllProcesses retrieves all registered processes.

func (*DB) GetAllTaskMetadata

func (db *DB) GetAllTaskMetadata(ctx context.Context, taskID string) (map[string]string, error)

GetAllTaskMetadata returns all metadata for a task as a map.

func (*DB) GetBead

func (db *DB) GetBead(ctx context.Context, id string) (*TrackedBead, error)

GetBead retrieves a tracking record by ID.

func (*DB) GetBeadsWithActiveSessions

func (db *DB) GetBeadsWithActiveSessions(ctx context.Context, zellijSession string) (map[string]bool, error)

GetBeadsWithActiveSessions returns a map of bead IDs that have active planning sessions. It validates that processes are still alive and cleans up stale sessions.

func (*DB) GetCachedComplexity

func (db *DB) GetCachedComplexity(ctx context.Context, beadID, descHash string) (score, tokens int, found bool, err error)

GetCachedComplexity retrieves cached complexity for a bead if it exists and the description hash matches.

func (*DB) GetControlPlaneProcess

func (db *DB) GetControlPlaneProcess(ctx context.Context) (*Process, error)

GetControlPlaneProcess retrieves the control plane process.

func (*DB) GetFeedbackByBeadID

func (db *DB) GetFeedbackByBeadID(ctx context.Context, beadID string) (*PRFeedback, error)

GetFeedbackByBeadID returns the feedback associated with a bead.

func (*DB) GetFeedbackBySourceID

func (db *DB) GetFeedbackBySourceID(ctx context.Context, workID, sourceID string) (*PRFeedback, error)

GetFeedbackBySourceID returns the feedback associated with a source ID (e.g., GitHub comment ID). Returns nil if no feedback exists for this source ID.

func (*DB) GetLastWorkID

func (db *DB) GetLastWorkID(ctx context.Context) (string, error)

GetLastWorkID returns the ID of the most recently created work.

func (*DB) GetNextScheduledTask

func (db *DB) GetNextScheduledTask(ctx context.Context) (*ScheduledTask, error)

GetNextScheduledTask gets the next pending task that's ready to run.

func (*DB) GetNextTaskNumber

func (db *DB) GetNextTaskNumber(ctx context.Context, workID string) (int, error)

GetNextTaskNumber returns the next available task number for a work. Tasks are numbered sequentially within each work (w-abc.1, w-abc.2, etc.) This uses an atomic counter to avoid race conditions.

func (*DB) GetOrchestratorProcess

func (db *DB) GetOrchestratorProcess(ctx context.Context, workID string) (*Process, error)

GetOrchestratorProcess retrieves the orchestrator process for a work ID.

func (*DB) GetPRTaskForWork

func (db *DB) GetPRTaskForWork(ctx context.Context, workID string) (*Task, error)

GetPRTaskForWork returns the most recent PR task for a work, if one exists. Only returns tasks with status pending, processing, or completed. Returns nil if no PR task exists.

func (*DB) GetPendingTaskByType

func (db *DB) GetPendingTaskByType(ctx context.Context, workID string, taskType string) (*ScheduledTask, error)

GetPendingTaskByType gets the next pending task of a specific type for a work.

func (*DB) GetPlanSession

func (db *DB) GetPlanSession(ctx context.Context, beadID string) (*PlanSession, error)

GetPlanSession gets the plan session for a specific bead. Returns nil if no session is registered.

func (*DB) GetReadyTasksForWork

func (db *DB) GetReadyTasksForWork(ctx context.Context, workID string) ([]*Task, error)

GetReadyTasksForWork returns tasks that are pending and have all dependencies satisfied. Tasks are returned in position order.

func (*DB) GetScheduledTasksForWork

func (db *DB) GetScheduledTasksForWork(ctx context.Context, workID string) ([]*ScheduledTask, error)

GetScheduledTasksForWork gets all pending scheduled tasks for a work.

func (*DB) GetStaleProcesses

func (db *DB) GetStaleProcesses(ctx context.Context, threshold time.Duration) ([]*Process, error)

GetStaleProcesses returns all processes with heartbeats older than the threshold.

func (*DB) GetTask

func (db *DB) GetTask(ctx context.Context, id string) (*Task, error)

GetTask retrieves a task by ID.

func (*DB) GetTaskBeadStatus

func (db *DB) GetTaskBeadStatus(ctx context.Context, taskID, beadID string) (string, error)

GetTaskBeadStatus returns the status of a specific bead within a task.

func (*DB) GetTaskBeads

func (db *DB) GetTaskBeads(ctx context.Context, taskID string) ([]string, error)

GetTaskBeads returns the list of bead IDs for a task.

func (*DB) GetTaskBeadsForWork

func (db *DB) GetTaskBeadsForWork(ctx context.Context, workID string) ([]TaskBeadInfo, error)

GetTaskBeadsForWork returns all task beads for a work in a single query.

func (*DB) GetTaskBeadsWithStatus

func (db *DB) GetTaskBeadsWithStatus(ctx context.Context, taskID string) ([]TaskBeadInfo, error)

GetTaskBeadsWithStatus returns all beads in a task with their status.

func (*DB) GetTaskByIdempotencyKey

func (db *DB) GetTaskByIdempotencyKey(ctx context.Context, idempotencyKey string) (*ScheduledTask, error)

GetTaskByIdempotencyKey retrieves a task by its idempotency key.

func (*DB) GetTaskDependencies

func (db *DB) GetTaskDependencies(ctx context.Context, taskID string) ([]string, error)

GetTaskDependencies returns the IDs of tasks that the given task depends on.

func (*DB) GetTaskDependents

func (db *DB) GetTaskDependents(ctx context.Context, taskID string) ([]string, error)

GetTaskDependents returns the IDs of tasks that depend on the given task.

func (*DB) GetTaskForBead

func (db *DB) GetTaskForBead(ctx context.Context, beadID string) (string, error)

GetTaskForBead returns the task ID that contains a specific bead.

func (*DB) GetTaskMetadata

func (db *DB) GetTaskMetadata(ctx context.Context, taskID, key string) (string, error)

GetTaskMetadata gets a metadata value by task ID and key. Returns empty string and nil error if the key doesn't exist.

func (*DB) GetUnassignedFeedbackBeadIDs

func (db *DB) GetUnassignedFeedbackBeadIDs(ctx context.Context, workID string) ([]string, error)

GetUnassignedFeedbackBeadIDs returns bead IDs from PR feedback items that are not yet assigned to any task and not resolved/closed.

func (*DB) GetUnassignedWorkBeads

func (db *DB) GetUnassignedWorkBeads(ctx context.Context, workID string) ([]*WorkBead, error)

GetUnassignedWorkBeads returns beads in a work that are not yet in any task.

func (*DB) GetUnprocessedFeedback

func (db *DB) GetUnprocessedFeedback(ctx context.Context, workID string) ([]PRFeedback, error)

GetUnprocessedFeedback returns all unprocessed feedback for a work.

func (*DB) GetUnresolvedFeedbackForBeads

func (db *DB) GetUnresolvedFeedbackForBeads(ctx context.Context, beadIDs []string) ([]PRFeedback, error)

GetUnresolvedFeedbackForBeads returns feedback items for specific beads that are not yet resolved on GitHub.

func (*DB) GetUnresolvedFeedbackForWork

func (db *DB) GetUnresolvedFeedbackForWork(ctx context.Context, workID string) ([]PRFeedback, error)

GetUnresolvedFeedbackForWork returns feedback items for the work where the associated issue is closed but not resolved on GitHub.

func (*DB) GetWork

func (db *DB) GetWork(ctx context.Context, id string) (*Work, error)

GetWork retrieves a work by ID.

func (*DB) GetWorkBeads

func (db *DB) GetWorkBeads(ctx context.Context, workID string) ([]*WorkBead, error)

GetWorkBeads returns all beads assigned to a work.

func (*DB) GetWorkByDirectory

func (db *DB) GetWorkByDirectory(ctx context.Context, pathPattern string) (*Work, error)

GetWorkByDirectory returns the work that has a worktree path matching the pattern.

func (*DB) GetWorkTasks

func (db *DB) GetWorkTasks(ctx context.Context, workID string) ([]*Task, error)

GetWorkTasks returns all tasks for a work in order.

func (*DB) GetWorksWithPRs

func (db *DB) GetWorksWithPRs(ctx context.Context) ([]*Work, error)

GetWorksWithPRs returns all works that have a PR URL.

func (*DB) GetWorksWithUnseenChanges

func (db *DB) GetWorksWithUnseenChanges(ctx context.Context) ([]*Work, error)

GetWorksWithUnseenChanges returns all works with unseen PR changes.

func (*DB) HasExistingFeedback

func (db *DB) HasExistingFeedback(ctx context.Context, workID, title string, sourceType github.SourceType, sourceName string) (bool, error)

HasExistingFeedback checks if feedback already exists for a specific source. Falls back to checking by title, source_type, and source_name.

func (*DB) HasExistingFeedbackBySourceID

func (db *DB) HasExistingFeedbackBySourceID(ctx context.Context, workID, sourceID string) (bool, error)

HasExistingFeedbackBySourceID checks if feedback already exists for a specific source ID. This is the preferred method for checking duplicates when a unique source ID is available.

func (*DB) HasPendingDependencies

func (db *DB) HasPendingDependencies(ctx context.Context, taskID string) (bool, error)

HasPendingDependencies checks if a task has any dependencies that haven't completed.

func (*DB) IdleWork

func (db *DB) IdleWork(ctx context.Context, id string) error

IdleWork marks a work as idle (all tasks complete, waiting for more). Returns nil if the work is already in a terminal status (merged/completed).

func (*DB) IdleWorkWithPR

func (db *DB) IdleWorkWithPR(ctx context.Context, id, prURL string) error

IdleWorkWithPR marks a work as idle and optionally sets the PR URL. PR feedback polling is scheduled separately when the PR is first created (via SetWorkPRURLAndScheduleFeedback), not when work goes idle.

func (*DB) IsBeadInTask

func (db *DB) IsBeadInTask(ctx context.Context, workID, beadID string) (bool, error)

IsBeadInTask checks if a bead is already assigned to a task in the work.

func (*DB) IsCompleted

func (db *DB) IsCompleted(ctx context.Context, id string) (bool, error)

IsCompleted checks if a bead is completed or failed.

func (*DB) IsControlPlaneAlive

func (db *DB) IsControlPlaneAlive(ctx context.Context, threshold time.Duration) (bool, error)

IsControlPlaneAlive checks if the control plane has a recent heartbeat.

func (*DB) IsOrchestratorAlive

func (db *DB) IsOrchestratorAlive(ctx context.Context, workID string, threshold time.Duration) (bool, error)

IsOrchestratorAlive checks if an orchestrator for the given work ID has a recent heartbeat.

func (*DB) IsPlanSessionRunning

func (db *DB) IsPlanSessionRunning(ctx context.Context, beadID string) (bool, error)

IsPlanSessionRunning checks if a plan session is running for the given bead. It also validates that the registered process is still alive.

func (*DB) IsWorkCompleted

func (db *DB) IsWorkCompleted(workID string) (bool, error)

IsWorkCompleted checks if all tasks in a work are completed.

func (*DB) ListBeads

func (db *DB) ListBeads(ctx context.Context, statusFilter string) ([]*TrackedBead, error)

ListBeads returns all beads, optionally filtered by status.

func (*DB) ListPlanSessions

func (db *DB) ListPlanSessions(ctx context.Context, zellijSession string) ([]*PlanSession, error)

ListPlanSessions returns all plan sessions for a zellij session.

func (*DB) ListTasks

func (db *DB) ListTasks(ctx context.Context, statusFilter string) ([]*Task, error)

ListTasks returns all tasks.

func (*DB) ListWorks

func (db *DB) ListWorks(ctx context.Context, statusFilter string) ([]*Work, error)

ListWorks returns all works, optionally filtered by status.

func (*DB) MarkFeedbackProcessed

func (db *DB) MarkFeedbackProcessed(ctx context.Context, feedbackID, beadID string) error

MarkFeedbackProcessed marks feedback as processed and associates it with a bead.

func (*DB) MarkFeedbackResolved

func (db *DB) MarkFeedbackResolved(ctx context.Context, feedbackID string) error

MarkFeedbackResolved marks feedback as resolved on GitHub.

func (*DB) MarkFeedbackResolvedAndScheduleTasks

func (db *DB) MarkFeedbackResolvedAndScheduleTasks(ctx context.Context, feedbackID string, tasks []ScheduledTaskParams) error

MarkFeedbackResolvedAndScheduleTasks atomically marks feedback as resolved and schedules the associated GitHub tasks in a single transaction. This implements the transactional outbox pattern correctly.

func (*DB) MarkTaskCompleted

func (db *DB) MarkTaskCompleted(ctx context.Context, taskID string) error

MarkTaskCompleted marks a task as completed.

func (*DB) MarkTaskCompletedByIdempotencyKey

func (db *DB) MarkTaskCompletedByIdempotencyKey(ctx context.Context, idempotencyKey string) error

MarkTaskCompletedByIdempotencyKey marks a task as completed using its idempotency key.

func (*DB) MarkTaskExecuting

func (db *DB) MarkTaskExecuting(ctx context.Context, taskID string) error

MarkTaskExecuting marks a task as currently executing.

func (*DB) MarkTaskFailed

func (db *DB) MarkTaskFailed(ctx context.Context, taskID string, errorMessage string) error

MarkTaskFailed marks a task as failed with an error message.

func (*DB) MarkWorkPRSeen

func (db *DB) MarkWorkPRSeen(ctx context.Context, id string) error

MarkWorkPRSeen marks the PR changes as seen for a work.

func (*DB) MergeWork

func (db *DB) MergeWork(ctx context.Context, id string) error

MergeWork marks a work as merged (PR was merged on GitHub).

func (*DB) RegisterPlanSession

func (db *DB) RegisterPlanSession(ctx context.Context, beadID, zellijSession, tabName string, pid int) error

RegisterPlanSession registers a plan session for a specific bead. It also cleans up any stale sessions (where the process is no longer running).

func (*DB) RegisterProcess

func (db *DB) RegisterProcess(ctx context.Context, id, processType string, workID *string, pid int) error

RegisterProcess registers or updates a process in the database.

func (*DB) RemoveWorkBead

func (db *DB) RemoveWorkBead(ctx context.Context, workID, beadID string) error

RemoveWorkBead removes a bead from a work.

func (*DB) RescheduleWithBackoff

func (db *DB) RescheduleWithBackoff(ctx context.Context, taskID string, errorMessage string) error

RescheduleWithBackoff reschedules a failed task with exponential backoff. The backoff formula is: baseDelay * 2^attemptCount (capped at maxDelay).

func (*DB) ResetExecutingTasksToPending

func (db *DB) ResetExecutingTasksToPending(ctx context.Context) (int64, error)

ResetExecutingTasksToPending resets any scheduled tasks stuck in 'executing' status back to 'pending'. This is used when the control plane starts up to recover from a crash that left tasks in an incomplete state.

func (*DB) ResetTaskBeadStatus

func (db *DB) ResetTaskBeadStatus(ctx context.Context, taskID, beadID string) error

ResetTaskBeadStatus resets a single bead's status in a task to pending.

func (*DB) ResetTaskBeadStatuses

func (db *DB) ResetTaskBeadStatuses(ctx context.Context, taskID string) error

ResetTaskBeadStatuses resets all bead statuses for a task to pending.

func (*DB) ResetTaskStatus

func (db *DB) ResetTaskStatus(ctx context.Context, taskID string) error

ResetTaskStatus resets a task status to pending.

func (*DB) RestartWork

func (db *DB) RestartWork(ctx context.Context, id string) error

RestartWork transitions a failed work back to processing. Only works if the work is currently in failed status.

func (*DB) ResumeWork

func (db *DB) ResumeWork(ctx context.Context, id string) error

ResumeWork transitions an idle or completed work back to processing. Use this when new tasks are added to a work that was idle/completed.

func (*DB) ScheduleOrUpdateTask

func (db *DB) ScheduleOrUpdateTask(ctx context.Context, workID string, taskType string, scheduledAt time.Time) (*ScheduledTask, error)

ScheduleOrUpdateTask schedules a new task or updates existing one. If a pending task of the same type exists, it updates the scheduled time. Otherwise, it creates a new scheduled task.

func (*DB) ScheduleTask

func (db *DB) ScheduleTask(ctx context.Context, workID string, taskType string, scheduledAt time.Time, metadata map[string]string) (*ScheduledTask, error)

ScheduleTask schedules a new task for a work.

func (*DB) ScheduleTaskWithRetry

func (db *DB) ScheduleTaskWithRetry(ctx context.Context, workID, taskType string, scheduledAt time.Time, metadata map[string]string, idempotencyKey string, maxAttempts int) error

ScheduleTaskWithRetry schedules a new task with retry support and an idempotency key. If a task with the same idempotency key already exists, it returns that task instead.

func (*DB) SetTaskMetadata

func (db *DB) SetTaskMetadata(ctx context.Context, taskID, key, value string) error

SetTaskMetadata sets a metadata key-value pair on a task. If the key already exists, it updates the value.

func (*DB) SetWorkHasUnseenPRChanges

func (db *DB) SetWorkHasUnseenPRChanges(ctx context.Context, id string, hasChanges bool) error

SetWorkHasUnseenPRChanges sets the has_unseen_pr_changes flag for a work.

func (*DB) SetWorkPRURLAndScheduleFeedback

func (db *DB) SetWorkPRURLAndScheduleFeedback(ctx context.Context, id, prURL string, prFeedbackInterval, commentResolutionInterval time.Duration) error

SetWorkPRURLAndScheduleFeedback atomically sets the PR URL on a work and schedules PR feedback polling tasks. This should be called when a PR is first created, ensuring feedback polling starts immediately rather than waiting for work to go idle. The PR URL is only set if it's not already set (idempotent).

func (*DB) SpawnTask

func (db *DB) SpawnTask(ctx context.Context, taskID string, status string) error

SpawnTask updates spawn metadata for a task.

func (*DB) StartBead

func (db *DB) StartBead(ctx context.Context, id, title, zellijSession, zellijPane string) error

StartBead marks a bead as processing with session info.

func (*DB) StartBeadWithWorktree

func (db *DB) StartBeadWithWorktree(ctx context.Context, id, title, zellijSession, zellijPane, worktreePath string) error

StartBeadWithWorktree marks a bead as processing with session and worktree info.

func (*DB) StartTask

func (db *DB) StartTask(ctx context.Context, id string, worktreePath string) error

StartTask marks a task as processing and sets its worktree path.

func (*DB) StartWork

func (db *DB) StartWork(ctx context.Context, id, zellijSession, zellijTab string) error

StartWork marks a work as processing with session info.

func (*DB) TriggerTaskNow

func (db *DB) TriggerTaskNow(ctx context.Context, workID string, taskType string) (*ScheduledTask, error)

TriggerTaskNow schedules a task to run immediately.

func (*DB) UnregisterPlanSession

func (db *DB) UnregisterPlanSession(ctx context.Context, beadID string) error

UnregisterPlanSession removes a plan session by bead ID.

func (*DB) UnregisterProcess

func (db *DB) UnregisterProcess(ctx context.Context, id string) error

UnregisterProcess removes a process from the database.

func (*DB) UpdateHeartbeat

func (db *DB) UpdateHeartbeat(ctx context.Context, id string) error

UpdateHeartbeat updates the heartbeat timestamp for a process.

func (*DB) UpdateHeartbeatWithTime

func (db *DB) UpdateHeartbeatWithTime(ctx context.Context, id string, t time.Time) error

UpdateHeartbeatWithTime updates the heartbeat timestamp for a process with an explicit time. This is useful for testing where time needs to be controlled.

func (*DB) UpdateScheduledTaskTime

func (db *DB) UpdateScheduledTaskTime(ctx context.Context, taskID string, scheduledAt time.Time) error

UpdateScheduledTaskTime updates the scheduled time for a task.

func (*DB) UpdateTaskActivity

func (db *DB) UpdateTaskActivity(ctx context.Context, taskID string, timestamp time.Time) error

UpdateTaskActivity updates the last_activity timestamp for a processing task.

func (*DB) UpdateWorkPRStatus

func (db *DB) UpdateWorkPRStatus(ctx context.Context, id, ciStatus, approvalStatus, approvers, prState, mergeableState string) error

UpdateWorkPRStatus updates the PR status fields for a work. ciStatus: pending, success, failure approvalStatus: pending, approved, changes_requested approvers: JSON array of approver usernames mergeableState: CLEAN, DIRTY, BLOCKED, BEHIND, DRAFT, UNSTABLE, UNKNOWN

func (*DB) UpdateWorkWorktreePath

func (db *DB) UpdateWorkWorktreePath(ctx context.Context, id, worktreePath string) error

UpdateWorkWorktreePath updates the worktree path for a work. Used by the control plane after creating a worktree asynchronously.

func (*DB) WatchSchedulerChanges

func (db *DB) WatchSchedulerChanges(ctx context.Context, since time.Time) ([]*ScheduledTask, error)

WatchSchedulerChanges returns tasks that have been updated since the given time.

type Migration

type Migration struct {
	Version string
	Name    string
	UpSQL   string
	DownSQL string
}

Migration represents a single migration file

type PRFeedback

type PRFeedback struct {
	ID           string
	WorkID       string
	PRURL        string
	FeedbackType string
	Title        string
	Description  string
	SourceURL    string                  // URL to the source item
	SourceID     *string                 // GitHub comment/check ID for resolution tracking
	SourceType   github.SourceType       // Structured type: ci, workflow, review_comment, issue_comment
	SourceName   string                  // Human-readable name (check name, workflow name, reviewer)
	Context      *github.FeedbackContext // Structured context data
	Priority     int
	BeadID       *string
	CreatedAt    time.Time
	ProcessedAt  *time.Time
	ResolvedAt   *time.Time // When the GitHub comment was resolved
}

PRFeedback represents a piece of feedback from a PR.

func (*PRFeedback) IsReviewComment

func (f *PRFeedback) IsReviewComment() bool

IsReviewComment returns true if this feedback is from a GitHub review comment that can be replied to and resolved.

type PlanSession

type PlanSession struct {
	BeadID        string
	ZellijSession string
	TabName       string
	PID           int
	StartedAt     time.Time
}

PlanSession represents a running plan mode Claude session for a specific bead.

type Process

type Process struct {
	ID          string
	ProcessType string
	WorkID      *string
	PID         int
	Hostname    string
	Heartbeat   time.Time
	StartedAt   time.Time
}

Process represents a running process (orchestrator or control plane).

type ScheduledTask

type ScheduledTask struct {
	ID             string
	WorkID         string
	TaskType       string
	ScheduledAt    time.Time
	ExecutedAt     *time.Time
	Status         string
	ErrorMessage   *string
	Metadata       map[string]string
	AttemptCount   int
	MaxAttempts    int
	IdempotencyKey *string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

ScheduledTask represents a scheduled task in the database.

func (*ScheduledTask) ShouldRetry

func (task *ScheduledTask) ShouldRetry() bool

ShouldRetry returns true if the task should be retried based on attempt count.

type ScheduledTaskParams

type ScheduledTaskParams struct {
	WorkID         string
	TaskType       string
	ScheduledAt    time.Time
	Metadata       map[string]string
	IdempotencyKey string
	MaxAttempts    int
}

ScheduledTaskParams contains the parameters for scheduling a task.

type Task

type Task struct {
	ID               string
	Status           string
	TaskType         string
	ComplexityBudget int
	ActualComplexity int
	WorkID           string
	WorktreePath     string
	PRURL            string
	ErrorMessage     string
	StartedAt        *time.Time
	CompletedAt      *time.Time
	CreatedAt        time.Time
	SpawnedAt        *time.Time
	SpawnStatus      string
}

Task represents a virtual task (group of beads) in the database.

type TaskBead

type TaskBead struct {
	TaskID string
	BeadID string
	Status string
}

TaskBead represents a bead within a task.

type TaskBeadInfo

type TaskBeadInfo struct {
	TaskID string
	BeadID string
	Status string
}

TaskBeadInfo represents a task bead with its status.

type TrackedBead

type TrackedBead struct {
	ID            string
	Status        string
	Title         string
	PRURL         string
	ErrorMessage  string
	ZellijSession string
	ZellijPane    string
	WorktreePath  string
	StartedAt     *time.Time
	CompletedAt   *time.Time
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

TrackedBead represents a bead tracking record in the database.

type Work

type Work struct {
	ID                 string
	Status             string
	Name               string
	ZellijSession      string
	ZellijTab          string
	WorktreePath       string
	BranchName         string
	BaseBranch         string
	RootIssueID        string
	PRURL              string
	ErrorMessage       string
	StartedAt          *time.Time
	CompletedAt        *time.Time
	CreatedAt          time.Time
	Auto               bool
	CIStatus           string // pending, success, failure
	ApprovalStatus     string // pending, approved, changes_requested
	Approvers          string // JSON array of usernames
	LastPRPollAt       *time.Time
	HasUnseenPRChanges bool
	PRState            string // open, closed, merged
	MergeableState     string // CLEAN, DIRTY, BLOCKED, BEHIND, DRAFT, UNSTABLE, UNKNOWN
}

Work represents a work unit (group of tasks) in the database.

type WorkBead

type WorkBead struct {
	WorkID    string
	BeadID    string
	Position  int64
	CreatedAt time.Time
}

WorkBead represents a bead assigned to a work.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL