Skip to main content

Database

Struct Database 

Source
pub struct Database { /* private fields */ }
Expand description

Database handle wrapping a SQLite connection.

Implementations§

Source§

impl Database

Source

pub fn register_worker( &self, worker_id: Option<String>, tags: Vec<String>, force: bool, ids_config: &IdsConfig, workflow: Option<String>, overlays: Vec<String>, max_claims: Option<i32>, ) -> Result<Worker>

Register a new worker.

If worker_id is provided, it must be at most 36 characters. If not provided, a human-readable petname will be generated (e.g., “happy-turtle”). If force is true and the worker already exists, it will be re-registered (useful for stuck worker recovery). If workflow is provided, the worker will use that named workflow (e.g., “swarm” for workflow-swarm.yaml). If overlays is provided, those overlays will be applied on top of the workflow.

Source

pub fn get_worker(&self, worker_id: &str) -> Result<Option<Worker>>

Get a worker by ID.

Source

pub fn require_worker(&self, worker_id: &str) -> Result<Worker>

Check if a worker exists. Returns error if not found.

Source

pub fn update_worker( &self, worker_id: &str, tags: Option<Vec<String>>, max_claims: Option<i32>, ) -> Result<Worker>

Update a worker.

Source

pub fn update_worker_overlays( &self, worker_id: &str, overlays: Vec<String>, ) -> Result<Worker>

Update only the overlays for a worker.

Source

pub fn update_worker_state( &self, worker_id: &str, new_status: Option<&str>, new_phase: Option<&str>, task_id: Option<&str>, ) -> Result<(Option<String>, Option<String>)>

Update worker’s last seen state (status and phase) for transition prompt tracking. Returns the previous state (old_status, old_phase) for prompt calculation.

Source

pub fn heartbeat( &self, worker_id: &str, states_config: &StatesConfig, ) -> Result<i32>

Update worker heartbeat.

Source

pub fn unregister_worker( &self, worker_id: &str, final_status: &str, ) -> Result<DisconnectSummary>

Unregister a worker (releases all claims). Returns a summary of released tasks and files.

Source

pub fn list_workers(&self) -> Result<Vec<Worker>>

List all workers.

Source

pub fn list_workers_info( &self, states_config: &StatesConfig, ) -> Result<Vec<WorkerInfo>>

List all workers with extended info (claim count, current thought).

Source

pub fn list_workers_filtered( &self, tags: Option<&Vec<String>>, file: Option<&str>, task_id: Option<&str>, depth: i32, states_config: &StatesConfig, ) -> Result<Vec<WorkerInfo>>

List workers with optional filters by tags, file claimed, or related task.

  • tags: Workers must have ALL of these tags
  • file: Workers that have claimed this file
  • task_id: Workers working on tasks related to this task
  • depth: Task relationship depth (-3 to 3). Negative: ancestors, positive: descendants
Source

pub fn get_stale_workers(&self, timeout_seconds: i64) -> Result<Vec<Worker>>

Get workers with stale heartbeats.

Source

pub fn cleanup_stale_workers( &self, timeout_seconds: i64, final_status: &str, ) -> Result<CleanupSummary>

Cleanup stale workers by evicting them and releasing their claims.

For each stale worker, individual task_sequence entries are inserted for every released task before calling unregister_worker(). This allows polling agents to discover released tasks gradually via the sequence table rather than all tasks becoming available simultaneously (which would cause scheduling storms when an agent holding many tasks times out).

Returns a summary of the cleanup operation.

Source

pub fn expire_worker( &self, worker_id: &str, final_status: &str, ) -> Result<DisconnectSummary>

Force-expire a specific worker, releasing all its claimed tasks and file locks, then unregistering it. Unlike cleanup_stale_workers, this does not check heartbeat staleness – it unconditionally expires the worker.

Source

pub fn get_claim_count( &self, worker_id: &str, states_config: &StatesConfig, ) -> Result<i32>

Get claim count for a worker (counts tasks in any timed state).

Source§

impl Database

Source

pub fn add_attachment( &self, task_id: &str, attachment_type: String, name: String, content: String, mime_type: Option<String>, file_path: Option<String>, ) -> Result<i32>

Add an attachment to a task with auto-increment sequence per type. Returns the sequence number of the new attachment. If file_path is provided, content should be empty (stored externally).

Source

pub fn get_attachments_full( &self, task_id: &str, include_content: bool, ) -> Result<Vec<Attachment>>

Get attachments for a task, optionally including content. Note: For file-based attachments, content is NOT loaded here - use get_attachment for that.

Source

pub fn get_attachments(&self, task_id: &str) -> Result<Vec<AttachmentMeta>>

Get attachments for a task (metadata only).

Source

pub fn get_attachments_filtered( &self, task_id: &str, type_pattern: Option<&str>, mime_pattern: Option<&str>, ) -> Result<Vec<AttachmentMeta>>

Get attachments for a task with optional filtering (metadata only).

  • type_pattern: Optional glob pattern (with * wildcard) to filter by attachment_type
  • mime_pattern: Optional prefix to filter by MIME type (e.g., “image/” matches “image/png”)
Source

pub fn get_attachment( &self, task_id: &str, attachment_type: &str, sequence: i32, ) -> Result<Option<Attachment>>

Get a full attachment by (task_id, attachment_type, sequence). Note: For file-based attachments, content field contains the DB content (empty). The caller should read from file_path if set.

Source

pub fn get_attachment_file_paths_by_type( &self, task_id: &str, attachment_type: &str, ) -> Result<Vec<String>>

Get file_paths for all attachments of a given type (useful before deletion).

Source

pub fn delete_attachment( &self, task_id: &str, attachment_type: &str, sequence: i32, ) -> Result<bool>

Delete an attachment by (task_id, attachment_type, sequence).

Source

pub fn delete_attachments_by_type( &self, task_id: &str, attachment_type: &str, ) -> Result<Vec<String>>

Delete all attachments of a given type (for replace behavior). Returns the file_paths of deleted attachments (for cleanup).

Source

pub fn delete_attachments_by_type_ex( &self, task_id: &str, attachment_type: &str, ) -> Result<(usize, Vec<String>)>

Delete all attachments of a given type and return count plus file_paths. Returns (deleted_count, file_paths).

Source§

impl Database

Source

pub fn get_task_stats(&self) -> Result<(i64, i64, i64)>

Get task statistics for the dashboard (total, working, completed).

Source

pub fn get_active_worker_count(&self) -> Result<i64>

Get count of active workers (those with recent heartbeats).

Source

pub fn get_recent_tasks(&self, limit: i32) -> Result<Vec<DashboardTask>>

Get recent tasks for dashboard display.

Source

pub fn get_active_workers(&self) -> Result<Vec<DashboardWorker>>

Get active workers for dashboard display.

Source

pub fn query_tasks(&self, query: &TaskListQuery) -> Result<TaskListResult>

Query tasks with filters for the task list view.

Source

pub fn get_worker_claimed_tasks( &self, worker_id: &str, ) -> Result<Vec<WorkerClaimedTask>>

Get tasks claimed by a specific worker for the detail view.

Source

pub fn dashboard_update_task( &self, task_id: &str, status: Option<&str>, priority: Option<i32>, description: Option<&str>, tags: Option<Vec<String>>, ) -> Result<()>

Simple task update for dashboard (bypasses state machine validation). This is an admin-level operation that allows direct field updates.

Source

pub fn dashboard_delete_task(&self, task_id: &str) -> Result<()>

Simple task deletion for dashboard (soft delete).

Source

pub fn dashboard_force_release_task(&self, task_id: &str) -> Result<()>

Force release a task claim (admin operation for dashboard). Sets status to pending and clears worker_id, claimed_at.

Source

pub fn get_activity_stats(&self) -> Result<ActivityStats>

Get activity statistics for the last 24 hours.

Source

pub fn query_activity( &self, query: &ActivityListQuery, ) -> Result<ActivityListResult>

Query activity events with filters and pagination.

Source

pub fn get_all_file_marks(&self) -> Result<Vec<DashboardFileMark>>

Get all file marks with full details for the dashboard.

Source

pub fn get_file_marks_stats(&self) -> Result<FileMarksStats>

Get file marks statistics for the dashboard.

Source

pub fn force_unmark_file(&self, file_path: &str) -> Result<bool>

Force-remove a file mark (admin operation for dashboard). Unlike normal unlock, this doesn’t require the worker_id to match.

Source

pub fn get_metrics_overview(&self) -> Result<MetricsOverview>

Get metrics overview statistics.

Source

pub fn get_status_distribution(&self) -> Result<HashMap<String, i64>>

Get task counts by status for distribution chart.

Source

pub fn get_velocity( &self, period: &str, num_periods: i32, ) -> Result<Vec<VelocityDataPoint>>

Get velocity data (completed tasks per period). Period can be “day” or “week”.

Source

pub fn get_time_in_status(&self) -> Result<Vec<TimeInStatusStats>>

Get average time spent in each status.

Source

pub fn get_cost_by_agent(&self) -> Result<Vec<AgentCostStats>>

Get cost breakdown by agent/worker.

Source

pub fn get_custom_metrics(&self) -> Result<CustomMetricsAggregate>

Get aggregate of custom metrics (metric_0 through metric_7).

Source

pub fn get_dependency_graph( &self, dep_type: Option<&str>, focus_task: Option<&str>, depth: i32, ) -> Result<DependencyGraph>

Get dependency graph data for visualization. Returns nodes (tasks) and edges (dependencies) for rendering as a DAG.

Source

pub fn get_dependency_graph_stats(&self) -> Result<DependencyGraphStats>

Get dependency graph statistics.

Source

pub fn get_available_phases(&self) -> Result<Vec<String>>

Get all unique phases used by tasks.

Source§

impl Database

Source

pub fn task_exists(&self, task_id: &str) -> Result<bool>

Check if a task exists by ID.

Source

pub fn add_dependency( &self, from_task_id: &str, to_task_id: &str, dep_type: &str, deps_config: &DependenciesConfig, ) -> Result<()>

Add a typed dependency (from blocks/contains to). Returns Ok(()) on success. For soft linking with warnings, use add_dependency_soft.

Source

pub fn add_dependency_soft( &self, from_task_id: &str, to_task_id: &str, dep_type: &str, deps_config: &DependenciesConfig, ) -> Result<AddDependencyResult>

Add a typed dependency with soft failure (returns result status instead of error). Use this when you want to handle missing tasks as warnings.

Source

pub fn would_create_cycle( &self, from_task_id: &str, to_task_id: &str, dep_type: &str, deps_config: &DependenciesConfig, ) -> Result<bool>

Check if adding a dependency would create a cycle. For horizontal deps: check cycle in the start-blocking graph. For vertical deps: check containment cycle.

Source

pub fn remove_dependency( &self, from_task_id: &str, to_task_id: &str, dep_type: &str, ) -> Result<bool>

Remove a typed dependency. Returns true if a row was deleted.

Source

pub fn remove_all_outgoing_dependencies( &self, from_task_id: &str, dep_type: &str, ) -> Result<Vec<Dependency>>

Remove all dependencies of a given type from a task (outgoing edges). Returns the list of removed dependencies.

Source

pub fn remove_all_incoming_dependencies( &self, to_task_id: &str, dep_type: &str, ) -> Result<Vec<Dependency>>

Remove all dependencies of a given type to a task (incoming edges). Returns the list of removed dependencies.

Source

pub fn get_all_dependencies(&self) -> Result<Vec<Dependency>>

Get all dependencies.

Source

pub fn get_dependencies_by_type( &self, task_id: &str, dep_type: &str, direction: &str, ) -> Result<Vec<Dependency>>

Get dependencies of a specific type for a task.

Source

pub fn get_start_blockers( &self, task_id: &str, deps_config: &DependenciesConfig, ) -> Result<Vec<String>>

Get tasks that block a given task from starting (dep_type with blocks: start).

Source

pub fn get_completion_blockers( &self, task_id: &str, deps_config: &DependenciesConfig, ) -> Result<Vec<String>>

Get tasks that block a given task from completing (dep_type with blocks: completion). For a parent task, this returns children that must complete first.

Source

pub fn get_parent(&self, task_id: &str) -> Result<Option<String>>

Get the parent of a task (via ‘contains’ dependency).

Source

pub fn get_children_ids(&self, task_id: &str) -> Result<Vec<String>>

Get children of a task (via ‘contains’ dependency).

Source

pub fn get_blockers(&self, task_id: &str) -> Result<Vec<String>>

Get all tasks that block a given task (backwards compatible). Returns tasks from both ‘blocks’ and ‘follows’ dependencies.

Source

pub fn get_unsatisfied_blockers( &self, task_id: &str, states_config: &StatesConfig, ) -> Result<Vec<String>>

Get unsatisfied blockers for a given task. Returns only blocker task IDs whose status is still in a blocking state (i.e., the dependency is not yet satisfied). Blockers in terminal states like completed/cancelled/failed are excluded.

Source

pub fn get_blocking(&self, task_id: &str) -> Result<Vec<String>>

Get tasks that a given task blocks.

Source

pub fn get_blocked_tasks( &self, states_config: &StatesConfig, deps_config: &DependenciesConfig, sort_by: Option<&str>, sort_order: Option<&str>, ) -> Result<Vec<Task>>

Get tasks that are blocked by incomplete start dependencies. A task is blocked if any of its start-blocking dependencies are in a blocking state. Excludes soft-deleted tasks.

Source

pub fn get_ready_tasks( &self, agent_id: Option<&str>, states_config: &StatesConfig, deps_config: &DependenciesConfig, sort_by: Option<&str>, sort_order: Option<&str>, ) -> Result<Vec<Task>>

Get tasks that are ready to be claimed (all start dependencies satisfied). A task is ready if it’s in the initial state, unclaimed, and all start-blocking deps are not blocking. When agent_id is provided, also filters by agent’s tag qualifications using junction tables. Excludes soft-deleted tasks.

Source

pub fn has_unmet_start_dependencies( &self, task_id: &str, states_config: &StatesConfig, deps_config: &DependenciesConfig, ) -> Result<bool>

Check if a task has unmet start dependencies.

Source

pub fn has_incomplete_children( &self, task_id: &str, states_config: &StatesConfig, ) -> Result<bool>

Check if a task has incomplete children (blocking completion).

Source

pub fn list_tasks_with_tag_filters( &self, status: Option<Vec<String>>, owner: Option<&str>, parent_id: Option<Option<&str>>, tags_any: Option<Vec<String>>, tags_all: Option<Vec<String>>, qualified_for_agent_tags: Option<Vec<String>>, limit: Option<i32>, offset: i32, sort_by: Option<&str>, sort_order: Option<&str>, ) -> Result<Vec<Task>>

Get tasks with tag-based filtering using junction tables for indexed lookups.

  • tags_any: Task must have at least one of these tags (OR)
  • tags_all: Task must have all of these tags (AND)
  • qualified_for_agent_tags: If provided, only return tasks where these tags satisfy the task’s agent_tags_all/agent_tags_any

Excludes soft-deleted tasks.

Source

pub fn get_agent_tags(&self, agent_id: &str) -> Result<Vec<String>>

Get agent tags by agent ID.

Atomically relink dependencies: unlink all prev_from→prev_to, then link all from→to. This is a transaction-safe operation for moving children between parents. Returns a result with unlinked and linked pairs.

Source

pub fn get_predecessors(&self, task_id: &str, depth: i32) -> Result<Vec<Task>>

Get predecessors (tasks that block this task) via blocks/follows dependencies. depth: 0 = none, N = N levels, -1 = all

Source

pub fn get_successors(&self, task_id: &str, depth: i32) -> Result<Vec<Task>>

Get successors (tasks that this task blocks) via blocks/follows dependencies. depth: 0 = none, N = N levels, -1 = all

Source

pub fn get_ancestors(&self, task_id: &str, depth: i32) -> Result<Vec<Task>>

Get ancestors (parent chain) via contains dependency. depth: 0 = none, N = N levels up, -1 = all

Source

pub fn get_descendants(&self, task_id: &str, depth: i32) -> Result<Vec<Task>>

Get descendants (children tree) via contains dependency. depth: 0 = none, N = N levels down, -1 = all

Source§

impl Database

Source

pub fn export_tables(&self, options: &ExportOptions) -> Result<ExportTables>

Export all project data tables to an ExportTables struct.

Tables are queried with deterministic ordering per the export spec:

  • tasks: ORDER BY id
  • dependencies: ORDER BY from_task_id, to_task_id, dep_type
  • attachments: ORDER BY task_id, attachment_type, sequence
  • task_tags: ORDER BY task_id, tag
  • task_needed_tags: ORDER BY task_id, tag
  • task_wanted_tags: ORDER BY task_id, tag
  • task_sequence: ORDER BY task_id, id
Source§

impl Database

Source

pub fn import_snapshot( &self, snapshot: &Snapshot, options: &ImportOptions, ) -> Result<ImportResult>

Import data from a snapshot into the database.

This function:

  1. Validates schema version compatibility
  2. Based on mode:
    • Fresh: Validates the database is empty
    • Replace: Clears existing project data (preserves runtime tables)
    • Merge: Keeps existing data, adds only new items
  3. Inserts all rows in the correct order (respecting foreign keys)
  4. Rebuilds FTS indexes
§Arguments
  • snapshot - The snapshot to import
  • options - Import options
§Returns
  • Ok(ImportResult) - Import statistics
  • Err - If import fails
Source

pub fn preview_import( &self, snapshot: &Snapshot, options: &ImportOptions, ) -> DryRunResult

Preview what an import would do without making any changes.

This is the dry-run mode: it analyzes the snapshot against the current database state and reports what would be inserted, deleted, or skipped.

§Arguments
  • snapshot - The snapshot to preview importing
  • options - Import options (determines mode)
§Returns
  • DryRunResult - Preview of what would happen
Source

pub fn clear_project_data(&self) -> Result<BTreeMap<String, usize>>

Clear all project data tables, preserving runtime tables.

Tables are deleted in reverse order to respect foreign key constraints (children deleted before parents).

Runtime tables preserved:

  • workers: Session-based worker registrations
  • file_locks: Active file marks (advisory locks)
  • claim_sequence: File lock audit log
§Returns

A map of table names to number of rows deleted.

Source

pub fn rebuild_fts_indexes(&self) -> Result<()>

Rebuild FTS indexes from the base tables.

This is called after import to populate the FTS virtual tables since triggers don’t fire during bulk import.

Source§

impl Database

Source

pub fn lock_file_exclusive( &self, file_path: String, worker_id: &str, reason: Option<String>, task_id: Option<String>, ) -> Result<ExclusiveLockResult>

Acquire an exclusive lock on a resource.

Unlike advisory lock_file, this method enforces mutual exclusion:

  • If the lock is free, it is acquired.
  • If the lock is already held by the same agent, it is refreshed (timestamp/reason updated).
  • If the lock is held by another agent, returns HeldByOther(agent_id).

The file_path parameter stores the full lock:resource string for consistent storage in the file_locks table.

Source

pub fn lock_file( &self, file_path: String, worker_id: &str, reason: Option<String>, task_id: Option<String>, ) -> Result<Option<String>>

Lock a file (advisory). Returns Ok with optional warning if already locked by another worker.

Source

pub fn unlock_file( &self, file_path: &str, worker_id: &str, reason: Option<String>, ) -> Result<bool>

Unlock a file with optional reason for next claimant.

Source

pub fn unlock_files_verbose( &self, file_paths: Vec<String>, worker_id: &str, reason: Option<String>, ) -> Result<Vec<(String, String)>>

Unlock multiple files with verbose return. Returns a list of (file_path, worker_id) pairs for files that were actually released.

Source

pub fn release_worker_locks_verbose( &self, worker_id: &str, reason: Option<String>, ) -> Result<Vec<(String, String)>>

Release all files held by a worker with verbose return. Returns a list of (file_path, worker_id) pairs for files that were released.

Source

pub fn release_task_locks_verbose( &self, task_id: &str, reason: Option<String>, ) -> Result<Vec<(String, String)>>

Release all files associated with a task with verbose return. Returns a list of (file_path, worker_id) pairs for files that were released.

Source

pub fn claim_updates(&self, worker_id: &str) -> Result<ClaimUpdates>

Get claim updates since worker’s last poll. Returns all claim/release events since the agent’s last poll position.

Source

pub fn get_file_locks( &self, file_paths: Option<Vec<String>>, agent_id: Option<&str>, task_id: Option<&str>, ) -> Result<HashMap<String, FileLock>>

Get file locks with full details.

Source

pub fn get_all_file_locks(&self) -> Result<Vec<FileLock>>

Get all file locks as FileLock objects.

Source

pub fn find_file_contention( &self, task_id: &str, worker_id: &str, ) -> Result<Vec<(String, Option<String>, String)>>

Find file marks held by other active workers that may conflict with a task being claimed.

Since file_locks uses file_path as PK (only one mark per file), this method finds files currently marked by workers OTHER than the claiming worker where those workers have active tasks (status in working/assigned). This gives the claiming worker awareness of which files are currently being worked on by others.

Specifically checks for marks held by workers on sibling tasks (tasks sharing the same parent as the claimed task), which represents the most likely source of file contention in practice.

Returns a list of (file_path, other_task_id, other_worker_id) tuples. Excludes lock: prefixed entries (exclusive locks, not file marks).

Source

pub fn release_worker_locks(&self, worker_id: &str) -> Result<i32>

Release all locks held by a worker.

Source

pub fn release_task_locks(&self, task_id: &str) -> Result<i32>

Release all locks associated with a task. Called automatically when a task completes.

Source§

impl Database

Source

pub fn get_schema(&self, include_sql: bool) -> Result<DatabaseSchema>

Get complete schema information for the database.

Source

pub fn get_table_names(&self) -> Result<Vec<String>>

Get a list of table names only (lightweight).

Source§

impl Database

Source

pub fn search_tasks( &self, query: &str, limit: Option<i32>, offset: i32, include_attachments: bool, status_filter: Option<&str>, ) -> Result<Vec<SearchResult>>

Search tasks using FTS5 full-text search.

The query supports FTS5 MATCH syntax:

  • Simple words: error handling
  • Phrases: "error handling"
  • Prefix: error*
  • Boolean: error AND NOT warning
  • Column-specific: title:error or description:handling

Results are ranked by BM25 relevance score. Search tasks with pagination support.

Accepts limit and offset for pagination. The offset parameter skips the first N results.

Source§

impl Database

Source

pub fn get_task_sequence_history( &self, task_id: &str, ) -> Result<Vec<TaskSequenceEvent>>

Get the unified sequence history for a task (both status and phase changes).

Source

pub fn get_task_state_history( &self, task_id: &str, ) -> Result<Vec<TaskSequenceEvent>>

Get the state transition history for a task (status changes only, for backward compat).

Source

pub fn get_current_state_duration( &self, task_id: &str, states_config: &StatesConfig, ) -> Result<Option<i64>>

Get the current duration in the current state (for active time tracking). Only returns a duration if the current state is a timed state.

Source

pub fn get_project_state_history( &self, from_timestamp: Option<i64>, to_timestamp: Option<i64>, state_filter: Option<&[String]>, limit: Option<i64>, ) -> Result<Vec<TaskSequenceEvent>>

Get project-wide state transition history with optional time range filter. Returns all state transitions across all tasks within the specified time range.

Source

pub fn get_project_sequence_history( &self, from_timestamp: Option<i64>, to_timestamp: Option<i64>, limit: Option<i64>, ) -> Result<Vec<TaskSequenceEvent>>

Get project-wide sequence history (both status and phase changes).

Source

pub fn get_project_state_stats( &self, from_timestamp: Option<i64>, to_timestamp: Option<i64>, ) -> Result<ProjectStateStats>

Get aggregate project statistics for state transitions within a time range. Returns counts of transitions per state and per agent.

Source§

impl Database

Source

pub fn get_stats( &self, agent_id: Option<&str>, task_id: Option<&str>, states_config: &StatesConfig, ) -> Result<Stats>

Get aggregate statistics with dynamic state counting.

Source

pub fn get_status_summary( &self, parent: Option<&str>, states_config: &StatesConfig, ) -> Result<(HashMap<String, i64>, i64)>

Get a lightweight status summary: task counts grouped by state. When parent is provided, counts only descendants of that task.

Source§

impl Database

Source

pub fn create_task( &self, id: Option<String>, title: String, description: Option<String>, parent_id: Option<String>, phase: Option<String>, priority: Option<Priority>, points: Option<i32>, time_estimate_ms: Option<i64>, agent_tags_all: Option<Vec<String>>, agent_tags_any: Option<Vec<String>>, tags: Option<Vec<String>>, states_config: &StatesConfig, ids_config: &IdsConfig, ) -> Result<Task>

Create a new task. If id is provided, uses it as the task ID; otherwise generates a petname ID. If parent_id is provided, creates a ‘contains’ dependency from parent to this task. title is the short task title; description is optional longer detail.

Source

pub fn create_task_simple( &self, description: impl Into<String>, states_config: &StatesConfig, ids_config: &IdsConfig, ) -> Result<Task>

Convenience method to create a task with just a description string. Uses the description as both title and description. Useful for tests.

Source

pub fn create_task_tree( &self, opts: CreateTreeOptions<'_>, ) -> Result<(String, Vec<String>, Vec<String>, Vec<String>)>

Create a task tree from nested input. Uses child_type for parent-child dependencies (default: “contains”). Uses sibling_type for sibling dependencies (default: none/parallel).

Source

pub fn get_task(&self, task_id: &str) -> Result<Option<Task>>

Get a task by ID.

Source

pub fn rename_task(&self, old_id: &str, new_id: &str) -> Result<()>

Rename a task’s ID, updating all references atomically.

Disables foreign key enforcement, updates every table that references tasks.id inside a transaction, then re-enables and verifies FK integrity.

Source

pub fn get_task_tree(&self, task_id: &str) -> Result<Option<TaskTree>>

Get a task with all its children (tree).

Source

pub fn get_children(&self, parent_id: &str) -> Result<Vec<Task>>

Get direct children of a task (via ‘contains’ dependency).

Source

pub fn update_task( &self, task_id: &str, title: Option<String>, description: Option<Option<String>>, status: Option<String>, priority: Option<Priority>, points: Option<Option<i32>>, tags: Option<Vec<String>>, states_config: &StatesConfig, ) -> Result<Task>

Update a task.

Source

pub fn update_task_unified( &self, task_id: &str, agent_id: &str, assignee: Option<&str>, title: Option<String>, description: Option<Option<String>>, status: Option<String>, phase: Option<String>, priority: Option<Priority>, points: Option<Option<i32>>, tags: Option<Vec<String>>, needed_tags: Option<Vec<String>>, wanted_tags: Option<Vec<String>>, time_estimate_ms: Option<i64>, reason: Option<String>, force: bool, states_config: &StatesConfig, deps_config: &DependenciesConfig, auto_advance: &AutoAdvanceConfig, ) -> Result<(Task, Vec<String>, Vec<String>, Vec<(String, String)>)>

Update a task with unified claim/release logic.

  • Transition to timed state = CLAIM (set owner, validate tags, check limit)
  • Transition from timed to non-timed = RELEASE (clear owner)
  • Transition to terminal = COMPLETE (check children, release file locks)
  • With assignee = ASSIGN (set owner to assignee, transition to ‘assigned’ state)
  • Only the owner can update a claimed task (unless force=true)

Returns (task, unblocked, auto_advanced):

  • task: The updated task
  • unblocked: Task IDs that are now ready (all dependencies satisfied)
  • auto_advanced: Subset of unblocked that were actually transitioned
Source

pub fn delete_task( &self, task_id: &str, worker_id: &str, cascade: bool, reason: Option<String>, obliterate: bool, force: bool, ) -> Result<()>

Delete a task (soft delete by default, hard delete with obliterate=true).

  • worker_id: The worker attempting to delete (required for ownership check)
  • cascade: Whether to delete children (default: false)
  • reason: Optional reason for deletion
  • obliterate: If true, permanently deletes the task; if false (default), soft deletes
  • force: If true, allows deletion even if owned by another worker
Source

pub fn list_tasks(&self, query: ListTasksQuery<'_>) -> Result<Vec<Task>>

List tasks with optional filters. Returns full Task objects. Excludes soft-deleted tasks.

Source

pub fn set_thought( &self, agent_id: &str, thought: Option<String>, task_ids: Option<Vec<String>>, ) -> Result<i32>

Set the current thought for tasks owned by an agent.

Source

pub fn log_time(&self, task_id: &str, duration_ms: i64) -> Result<i64>

Log time for a task.

Source

pub fn log_metrics( &self, task_id: &str, cost_usd: Option<f64>, values: &[i64], ) -> Result<Task>

Log metrics and cost for a task. Values in the metrics array are aggregated (added) to existing values.

Source

pub fn claim_task( &self, task_id: &str, agent_id: &str, states_config: &StatesConfig, ) -> Result<Task>

Claim a task for an agent. Uses the first timed state (typically “working”) as the claiming state.

Source

pub fn release_task( &self, task_id: &str, agent_id: &str, states_config: &StatesConfig, ) -> Result<()>

Release a task claim.

Source

pub fn force_release( &self, task_id: &str, states_config: &StatesConfig, ) -> Result<()>

Force release a task regardless of owner.

Source

pub fn force_claim_task( &self, task_id: &str, agent_id: &str, states_config: &StatesConfig, ) -> Result<Task>

Force claim a task even if owned by another agent.

Source

pub fn release_task_with_state( &self, task_id: &str, agent_id: &str, state: &str, states_config: &StatesConfig, ) -> Result<()>

Release a task claim with a specified state.

Source

pub fn force_release_stale( &self, timeout_seconds: i64, states_config: &StatesConfig, ) -> Result<i32>

Force release stale claims.

Source

pub fn complete_task( &self, task_id: &str, agent_id: &str, states_config: &StatesConfig, ) -> Result<Task>

Complete a task and release file locks held by the agent. Uses “completed” state by default, which should be a terminal state. Checks that all children (via ‘contains’ dependencies) are complete.

Source

pub fn get_all_tasks(&self) -> Result<Vec<Task>>

Get all tasks. Excludes soft-deleted tasks.

Source

pub fn get_tasks_by_status(&self, status: &str) -> Result<Vec<Task>>

Get tasks by status.

Source

pub fn get_claimed_tasks(&self, agent_id: Option<&str>) -> Result<Vec<Task>>

Get claimed tasks. Excludes soft-deleted tasks.

Source§

impl Database

Source

pub fn instantiate_template( &self, snapshot: &Snapshot, name: &str, source_path: Option<&str>, ids_config: &IdsConfig, options: &InstantiateOptions, ) -> Result<InstantiateResult>

Instantiate a template from a Snapshot into the database.

This is the main entry point for template instantiation:

  1. Analyzes the template to detect entry/exit points
  2. Remaps all IDs to fresh petname-based IDs
  3. Applies instantiation transformations (status reset, title prefix, etc.)
  4. Imports the prepared snapshot via merge mode
  5. Optionally attaches entry points to a parent task
§Arguments
  • snapshot - The template snapshot to instantiate
  • name - Template name (for metadata/tracking)
  • source_path - Optional source file path
  • ids_config - ID generation configuration
  • options - Instantiation options
§Returns
  • Ok(InstantiateResult) - Instantiation results including ID mapping
  • Err - If instantiation fails
Source

pub fn instantiate_template_file( &self, template_path: &Path, ids_config: &IdsConfig, options: &InstantiateOptions, ) -> Result<InstantiateResult>

Instantiate a template from a file path.

Convenience method that loads the snapshot from a file and delegates to instantiate_template.

Source§

impl Database

Source

pub fn open<P: AsRef<Path>>(path: P) -> Result<Self>

Open or create the database at the given path.

Source

pub fn open_in_memory() -> Result<Self>

Open an in-memory database (for testing).

Source

pub fn with_conn<F, T>(&self, f: F) -> Result<T>
where F: FnOnce(&Connection) -> Result<T>,

Execute a function with exclusive access to the connection.

Recovers from poisoned mutex to prevent cascading failures if another thread panicked while holding the lock.

Source

pub fn with_conn_mut<F, T>(&self, f: F) -> Result<T>
where F: FnOnce(&mut Connection) -> Result<T>,

Execute a function with mutable access to the connection (for transactions).

Recovers from poisoned mutex to prevent cascading failures if another thread panicked while holding the lock.

Trait Implementations§

Source§

impl Clone for Database

Source§

fn clone(&self) -> Database

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,