db

package
v0.3.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package db handles database operations for Drover

Package db provides database utilities for Drover

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractBaseID

func ExtractBaseID(id string) string

ExtractBaseID returns the base ID without sequence numbers

Examples:

"task-123.1.2" -> "task-123"
"task-123.1"   -> "task-123"
"task-123"     -> "task-123"

func GenerateHierarchicalID

func GenerateHierarchicalID(baseID string, level int, sequence int) string

GenerateHierarchicalID creates a new hierarchical ID baseID: parent task ID (e.g., "task-123") level: depth level (1 or 2) sequence: position among siblings (1-indexed)

Examples:

GenerateHierarchicalID("task-123", 1, 1) -> "task-123.1"
GenerateHierarchicalID("task-123.1", 2, 2) -> "task-123.1.2"

func GetIDDepth

func GetIDDepth(id string) int

GetIDDepth returns the depth level of a hierarchical ID Returns:

0 = base task (no dots)
1 = first-level sub-task
2 = second-level sub-task

func GetParentIDFromHierarchicalID

func GetParentIDFromHierarchicalID(id string) string

GetParentIDFromHierarchicalID returns the parent task ID from a hierarchical ID Returns empty string if the ID is already a base task (no parent)

Examples:

"task-123.1"   -> "task-123"
"task-123.1.2" -> "task-123.1"
"task-123"     -> ""

func IsSubTask

func IsSubTask(id string) bool

IsSubTask returns true if the ID represents a sub-task (has a dot separator)

func ParseHierarchicalID

func ParseHierarchicalID(id string) (string, int, int, error)

ParseHierarchicalID extracts components from a hierarchical ID Returns: (baseID, level1Seq, level2Seq, error)

Examples:

"task-123"           -> ("task-123", 0, 0, nil)
"task-123.1"         -> ("task-123", 1, 0, nil)
"task-123.1.2"       -> ("task-123", 1, 2, nil)
"task-123.5.10"      -> ("task-123", 5, 10, nil)
"invalid"            -> ("", 0, 0, error)

func ValidateHierarchicalID

func ValidateHierarchicalID(id string, maxDepth int) error

ValidateHierarchicalID checks if an ID is valid and within depth limit maxDepth: maximum allowed depth (typically 2)

Types

type ConversationStore

type ConversationStore interface {
	CreateConversation(ctx context.Context, taskID, worktree string) (*types.Conversation, error)
	GetConversation(ctx context.Context, conversationID string) (*types.Conversation, error)
	GetConversationByTask(ctx context.Context, taskID string) (*types.Conversation, error)
	UpdateConversationStatus(ctx context.Context, conversationID string, status types.ConversationStatus) error
	DeleteConversation(ctx context.Context, conversationID string) error
	AppendTurn(ctx context.Context, turn *types.ConversationTurn) error
	GetRecentTurns(ctx context.Context, conversationID string, limit int) ([]*types.ConversationTurn, error)
	GetTurnsByTokenBudget(ctx context.Context, conversationID string, maxTokens int) ([]*types.ConversationTurn, error)
	GetTurnsByRange(ctx context.Context, conversationID string, start, end int) ([]*types.ConversationTurn, error)
	SearchTurns(ctx context.Context, query string, limit int) ([]*types.ConversationSearchResult, error)
	SearchTurnsInConversation(ctx context.Context, conversationID, query string, limit int) ([]*types.ConversationSearchResult, error)
	BuildContext(ctx context.Context, taskID string, options *conversation.BuildContextOptions) (*types.ConversationContext, error)
	ResumeConversation(ctx context.Context, taskID string) (*types.ConversationContext, error)
	GetStats(ctx context.Context, conversationID string) (*types.ConversationStats, error)
	PruneConversation(ctx context.Context, conversationID string, options *conversation.PruneOptions) (int, error)
	ArchiveConversation(ctx context.Context, conversationID string) error
}

ConversationStore interface for db.Store

type FileSpec

type FileSpec struct {
	Path           string `json:"path"`
	Operation      string `json:"operation"`
	Reason         string `json:"reason,omitempty"`
	EstimatedLines int    `json:"estimated_lines,omitempty"`
}

FileSpec represents a file operation

type Operator

type Operator struct {
	ID         string
	Name       string
	APIKey     string
	CreatedAt  int64
	LastActive *int64
}

Operator represents a user/operator in the system

type Plan

type Plan struct {
	ID              string        `json:"id"`
	TaskID          string        `json:"task_id"`
	Title           string        `json:"title"`
	Description     string        `json:"description"`
	Steps           []PlanStep    `json:"steps"`
	FilesToCreate   []FileSpec    `json:"files_to_create,omitempty"`
	FilesToModify   []FileSpec    `json:"files_to_modify,omitempty"`
	Dependencies    []string      `json:"dependencies,omitempty"`
	EstimatedTime   time.Duration `json:"estimated_time,omitempty"`
	Complexity      string        `json:"complexity,omitempty"`
	RiskFactors     []string      `json:"risk_factors,omitempty"`
	Status          PlanStatus    `json:"status"`
	ApprovedBy      string        `json:"approved_by,omitempty"`
	ApprovedAt      *time.Time    `json:"approved_at,omitempty"`
	RejectionReason string        `json:"rejection_reason,omitempty"`
	Revision        int           `json:"revision"`
	ParentPlanID    string        `json:"parent_plan_id,omitempty"`
	Feedback        []string      `json:"feedback,omitempty"`
	CreatedAt       time.Time     `json:"created_at"`
	UpdatedAt       time.Time     `json:"updated_at"`
	CreatedBy       string        `json:"created_by,omitempty"`
}

Plan represents a stored implementation plan

type PlanStatus

type PlanStatus string

PlanStatus represents the approval status of a plan

const (
	PlanStatusDraft     PlanStatus = "draft"
	PlanStatusPending   PlanStatus = "pending"
	PlanStatusApproved  PlanStatus = "approved"
	PlanStatusRejected  PlanStatus = "rejected"
	PlanStatusExecuting PlanStatus = "executing"
	PlanStatusCompleted PlanStatus = "completed"
	PlanStatusFailed    PlanStatus = "failed"
)

type PlanStep

type PlanStep struct {
	Order         int           `json:"order"`
	Title         string        `json:"title"`
	Description   string        `json:"description"`
	Command       string        `json:"command,omitempty"`
	Files         []string      `json:"files,omitempty"`
	Dependencies  []int         `json:"dependencies,omitempty"`
	EstimatedTime time.Duration `json:"estimated_time,omitempty"`
	Verification  string        `json:"verification,omitempty"`
}

PlanStep represents a single step in the implementation plan

type ProjectStatus

type ProjectStatus struct {
	Total      int
	Ready      int
	Claimed    int
	InProgress int
	Paused     int
	Blocked    int
	Completed  int
	Failed     int
}

ProjectStatus summarizes the current state

type SessionExport

type SessionExport struct {
	Version      string                 `json:"version"`
	ExportedAt   string                 `json:"exportedAt"`
	Repository   string                 `json:"repository"`
	Tasks        []*types.Task          `json:"tasks"`
	Epics        []*types.Epic          `json:"epics"`
	Dependencies []types.TaskDependency `json:"dependencies"`
	Worktrees    []*WorktreeInfo        `json:"worktrees"`
}

SessionExport represents a complete exported session

type SessionShare

type SessionShare struct {
	ID          string
	Token       string
	SessionData string
	CreatedBy   string
	CreatedAt   int64
	ExpiresAt   *int64
	AccessCount int
}

SessionShare represents a shareable session link

type Store

type Store struct {
	DB *sql.DB
}

Store manages database operations

func Open

func Open(path string) (*Store, error)

Open opens a SQLite database at the given path

func (*Store) AddFeedback

func (s *Store) AddFeedback(planID string, feedback string) error

AddFeedback adds feedback to a plan

func (*Store) AddGuidance

func (s *Store) AddGuidance(taskID, message string) (*types.GuidanceMessage, error)

AddGuidance adds a guidance message to a task's queue

func (*Store) ApprovePlan

func (s *Store) ApprovePlan(planID, approvedBy string) error

ApprovePlan approves a plan

func (*Store) CancelTask

func (s *Store) CancelTask(taskID, reason string) error

CancelTask cancels a running or ready task

func (*Store) ClaimTask

func (s *Store) ClaimTask(workerID string) (*types.Task, error)

ClaimTask attempts to atomically claim a ready task

Uses UPDATE with ORDER BY and LIMIT to atomically find and claim a task in a single operation, avoiding race conditions between SELECT and UPDATE.

func (*Store) ClaimTaskForEpic

func (s *Store) ClaimTaskForEpic(workerID, epicID string) (*types.Task, error)

ClaimTaskForEpic attempts to atomically claim a ready task, optionally filtered by epic

Uses UPDATE with ORDER BY and LIMIT to atomically find and claim a task in a single operation, avoiding race conditions between SELECT and UPDATE. If epicID is empty, claims any ready task. If epicID is set, only claims tasks in that epic.

func (*Store) ClearGuidance

func (s *Store) ClearGuidance(taskID string) error

ClearGuidance removes all guidance messages for a task

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection

func (*Store) CompleteCheckpoint

func (s *Store) CompleteCheckpoint(taskID string, verdict types.TaskVerdict, reason string) error

CompleteCheckpoint marks a task checkpoint as completed

func (*Store) CompleteTask

func (s *Store) CompleteTask(taskID string) error

CompleteTask marks a task as completed and unblocks dependents

func (*Store) ConversationStore

func (s *Store) ConversationStore() ConversationStore

ConversationStore returns the conversation store for this database

func (*Store) CreateCheckpoint

func (s *Store) CreateCheckpoint(checkpoint *types.TaskCheckpoint) error

CreateCheckpoint creates a new checkpoint for a task

func (*Store) CreateEpic

func (s *Store) CreateEpic(title, description string) (*types.Epic, error)

CreateEpic creates a new epic

func (*Store) CreateOperator

func (s *Store) CreateOperator(name string) (*Operator, error)

CreateOperator creates a new operator with an API key

func (*Store) CreateSessionShare

func (s *Store) CreateSessionShare(sessionJSON, createdBy string, expiresHours int) (*SessionShare, error)

CreateSessionShare creates a new shareable session link

func (*Store) CreateSubTask

func (s *Store) CreateSubTask(title, description, parentID string, priority int, blockedBy []string) (*types.Task, error)

CreateSubTask creates a new sub-task with a hierarchical ID

func (*Store) CreateSubTaskWithSequence

func (s *Store) CreateSubTaskWithSequence(title, description, parentID string, sequence int, priority int, blockedBy []string) (*types.Task, error)

CreateSubTaskWithSequence creates a new sub-task with a specific hierarchical ID This is used when the user specifies a sequence number via CLI syntax (e.g., task-123.5)

func (*Store) CreateTask

func (s *Store) CreateTask(title, description, epicID string, priority int, blockedBy []string) (*types.Task, error)

CreateTask creates a new task with optional dependencies

func (*Store) CreateTaskWithOperator

func (s *Store) CreateTaskWithOperator(title, description, epicID string, priority int, blockedBy []string, operator string) (*types.Task, error)

CreateTaskWithOperator creates a new task with an operator (user/creator)

func (*Store) CreateTaskWithTestConfig

func (s *Store) CreateTaskWithTestConfig(title, description, epicID string, priority int, blockedBy []string, operator, testMode, testScope, testCommand string) (*types.Task, error)

CreateTaskWithTestConfig creates a new task with test configuration

func (*Store) CreateWorktree

func (s *Store) CreateWorktree(taskID, path, branch string) error

CreateWorktree records a new worktree in the database

func (*Store) DeleteCheckpoint

func (s *Store) DeleteCheckpoint(taskID string) error

DeleteCheckpoint removes a task's checkpoint

func (*Store) DeleteOperator

func (s *Store) DeleteOperator(name string) error

DeleteOperator deletes an operator by name

func (*Store) DeletePlan

func (s *Store) DeletePlan(planID string) error

DeletePlan deletes a plan

func (*Store) DeleteSessionShare

func (s *Store) DeleteSessionShare(token string) error

DeleteSessionShare deletes a session share by token

func (*Store) DeleteWorktree

func (s *Store) DeleteWorktree(taskID string) error

DeleteWorktree removes a worktree record from the database

func (*Store) FindOrphanedCheckpoints

func (s *Store) FindOrphanedCheckpoints(heartbeatTimeout int64) ([]*types.TaskCheckpoint, error)

FindOrphanedCheckpoints finds checkpoints that are in Running state but the worker is no longer alive

func (*Store) GetBlockedBy

func (s *Store) GetBlockedBy(taskID string) ([]string, error)

GetBlockedBy returns the list of task IDs that block the given task

func (*Store) GetCheckpoint

func (s *Store) GetCheckpoint(taskID string) (*types.TaskCheckpoint, error)

GetCheckpoint retrieves a task's checkpoint

func (*Store) GetOperatorByAPIKey

func (s *Store) GetOperatorByAPIKey(apiKey string) (*Operator, error)

GetOperatorByAPIKey retrieves an operator by API key

func (*Store) GetOperatorByName

func (s *Store) GetOperatorByName(name string) (*Operator, error)

GetOperatorByName retrieves an operator by name

func (*Store) GetOrphanedWorktrees

func (s *Store) GetOrphanedWorktrees(worktreeDir string) ([]string, error)

GetOrphanedWorktrees returns worktrees that exist on disk but not in the database or have no corresponding task (task was deleted)

func (*Store) GetParentTask

func (s *Store) GetParentTask(taskID string) (*types.Task, error)

GetParentTask retrieves the parent task of a sub-task

func (*Store) GetPendingGuidance

func (s *Store) GetPendingGuidance(taskID string) ([]*types.GuidanceMessage, error)

GetPendingGuidance retrieves undelivered guidance messages for a task

func (*Store) GetPlan

func (s *Store) GetPlan(planID string) (*Plan, error)

GetPlan retrieves a plan by ID

func (*Store) GetPlanByTaskID

func (s *Store) GetPlanByTaskID(taskID string) (*Plan, error)

GetPlanByTaskID retrieves the latest plan for a specific task

func (*Store) GetProjectStatus

func (s *Store) GetProjectStatus() (*ProjectStatus, error)

GetProjectStatus returns overall project status

func (*Store) GetRecentCompletedTasks

func (s *Store) GetRecentCompletedTasks(epicID string, limit int, maxAgeSeconds int64) ([]*types.Task, error)

GetRecentCompletedTasks returns recently completed tasks for context carrying epicID: filter to tasks in the same epic (empty string = all epics) limit: maximum number of tasks to return maxAge: only return tasks completed within this duration (in seconds, 0 = no limit)

func (*Store) GetSessionShareByToken

func (s *Store) GetSessionShareByToken(token string) (*SessionShare, error)

GetSessionShareByToken retrieves a session share by its token

func (*Store) GetSubTasks

func (s *Store) GetSubTasks(parentID string) ([]*types.Task, error)

GetSubTasks retrieves all direct sub-tasks of a parent task

func (*Store) GetTask

func (s *Store) GetTask(taskID string) (*types.Task, error)

GetTask retrieves a task by ID

func (*Store) GetTaskStatus

func (s *Store) GetTaskStatus(taskID string) (types.TaskStatus, error)

GetTaskStatus returns the current status of a task

func (*Store) GetTaskTree

func (s *Store) GetTaskTree(taskID string) (*types.Task, error)

GetTaskTree retrieves a task with all its descendants (sub-tasks recursively)

func (*Store) GetWorktreeStats

func (s *Store) GetWorktreeStats() (map[string]int64, error)

GetWorktreeStats returns statistics about worktrees

func (*Store) GetWorktreesForCleanup

func (s *Store) GetWorktreesForCleanup(completedOnly bool) ([]*WorktreeInfo, error)

GetWorktreesForCleanup returns worktrees that can be cleaned up

func (*Store) HasSubTasks

func (s *Store) HasSubTasks(taskID string) (bool, error)

HasSubTasks returns true if a task has any sub-tasks

func (*Store) ImportSession

func (s *Store) ImportSession(session *SessionExport) error

ImportSession imports a session from an export

func (*Store) IncrementShareAccess

func (s *Store) IncrementShareAccess(token string) error

IncrementShareAccess increments the access count for a session share

func (*Store) IncrementTaskAttempts

func (s *Store) IncrementTaskAttempts(taskID string) error

IncrementTaskAttempts increments the attempt counter for a task

func (*Store) InitSchema

func (s *Store) InitSchema() error

InitSchema creates the database schema

func (*Store) ListAllDependencies

func (s *Store) ListAllDependencies() ([]types.TaskDependency, error)

ListAllDependencies returns all task dependencies in the database

func (*Store) ListEpics

func (s *Store) ListEpics() ([]*types.Epic, error)

ListEpics returns all epics in the database

func (*Store) ListOperators

func (s *Store) ListOperators() ([]*Operator, error)

ListOperators returns all operators

func (*Store) ListPlans

func (s *Store) ListPlans(status PlanStatus) ([]*Plan, error)

ListPlans lists all plans, optionally filtered by status

func (*Store) ListTasks

func (s *Store) ListTasks() ([]*types.Task, error)

ListTasks returns all tasks in the database

func (*Store) ListTasksByEpic

func (s *Store) ListTasksByEpic(epicID string) ([]*types.Task, error)

ListTasksByEpic returns tasks filtered by epic ID If epicID is empty, returns all tasks

func (*Store) ListWorktrees

func (s *Store) ListWorktrees() ([]*WorktreeInfo, error)

ListWorktrees returns all worktrees with their task information

func (*Store) MarkGuidanceDelivered

func (s *Store) MarkGuidanceDelivered(guidanceIDs []string) error

MarkGuidanceDelivered marks guidance messages as delivered

func (*Store) MigrateSchema

func (s *Store) MigrateSchema() error

MigrateSchema runs database migrations for existing databases This adds new columns that weren't in the original schema

func (*Store) PauseTask

func (s *Store) PauseTask(taskID string) error

PauseTask pauses a running task, preserving its state

func (*Store) QueryEvents

func (s *Store) QueryEvents(eventTypes []string, epicID, taskID string, since, until int64, limit int) ([]map[string]any, error)

QueryEvents retrieves events from the database with optional filtering

func (*Store) RecordEvent

func (s *Store) RecordEvent(id string, eventType string, timestamp int64, taskID, epicID string, dataJSON string) error

RecordEvent records an event in the database

func (*Store) RejectPlan

func (s *Store) RejectPlan(planID, reason string) error

RejectPlan rejects a plan

func (*Store) ResetTasks

func (s *Store) ResetTasks(statusesToReset []types.TaskStatus) (int, error)

ResetTasks resets tasks with given statuses back to ready

func (*Store) ResetTasksByIDs

func (s *Store) ResetTasksByIDs(taskIDs []string) (int, error)

ResetTasksByIDs resets specific tasks by their IDs back to ready status

func (*Store) ResolveTask

func (s *Store) ResolveTask(taskID string, note string) error

ResolveTask removes all blockers for a blocked task, setting it to ready

func (*Store) ResumeTask

func (s *Store) ResumeTask(taskID string) error

ResumeTask resumes a paused task

func (*Store) RetryTask

func (s *Store) RetryTask(taskID string, force bool) error

RetryTask resets a failed task to ready status for retry If force is true, also resets the attempt counter

func (*Store) SavePlan

func (s *Store) SavePlan(plan *Plan) error

SavePlan saves a plan to the database

func (*Store) SetTaskTestConfig

func (s *Store) SetTaskTestConfig(taskID, testMode, testScope, testCommand string) error

SetTaskTestConfig updates the test configuration for a task

func (*Store) SetTaskVerdict

func (s *Store) SetTaskVerdict(taskID string, verdict types.TaskVerdict, reason string) error

SetTaskVerdict sets the structured verdict for a task

func (*Store) TouchWorktree

func (s *Store) TouchWorktree(taskID string) error

TouchWorktree updates the last_used_at timestamp

func (*Store) UpdateCheckpoint

func (s *Store) UpdateCheckpoint(taskID string, output string, heartbeat int64) error

UpdateCheckpoint updates a task's checkpoint (typically heartbeat or output)

func (*Store) UpdateOperatorLastActive

func (s *Store) UpdateOperatorLastActive(name string) error

UpdateOperatorLastActive updates the last active timestamp

func (*Store) UpdatePlanStatus

func (s *Store) UpdatePlanStatus(planID string, status PlanStatus, reason string) error

UpdatePlanStatus updates the status of a plan

func (*Store) UpdateTaskStatus

func (s *Store) UpdateTaskStatus(taskID string, status types.TaskStatus, lastError string) error

UpdateTaskStatus updates a task's status

func (*Store) UpdateWorktreeDiskSize

func (s *Store) UpdateWorktreeDiskSize(taskID string, size int64) error

UpdateWorktreeDiskSize updates the disk size of a worktree

func (*Store) UpdateWorktreeStatus

func (s *Store) UpdateWorktreeStatus(taskID, status string) error

UpdateWorktreeStatus updates the status of a worktree

type WorktreeInfo

type WorktreeInfo struct {
	TaskID     string
	Path       string
	Branch     string
	CreatedAt  int64
	LastUsedAt int64
	Status     string
	DiskSize   int64
	TaskStatus string
	TaskTitle  string
}

WorktreeInfo represents a worktree with its metadata

Jump to

Keyboard shortcuts

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