db

package
v0.63.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package db provides the SQLite persistence layer for td, handling issue storage, migrations, multi-process locking, and query execution.

Index

Constants

View Source
const CanonicalTimeLayout = "2006-01-02 15:04:05.999999999-07:00"

CanonicalTimeLayout is the timestamp format td writes to SQLite. It matches modernc.org/sqlite's `_time_format=sqlite` writer and its primary read-side parser, so values written this way always round-trip. Using a fixed numeric offset (`-07:00`) avoids the fragile Go time.Time.String() rendering (monotonic-clock suffixes and zone *names* like "PDT") that older/default driver configs produced and could not reliably parse back.

View Source
const PositionGap = 65536

PositionGap is the spacing between sparse sort keys for board positions.

View Source
const SchemaVersion = 38

SchemaVersion is the current database schema version.

It MUST equal the highest Version in Migrations. RunMigrations short-circuits on `currentVersion >= SchemaVersion`, so appending a migration without bumping this const means the migration never runs on any existing database — only on fresh ones, which start at 0. TestSchemaVersionMatchesMigrations enforces the invariant.

Variables

View Source
var ErrDatabaseUnavailable = errors.New("database unavailable")

ErrDatabaseUnavailable marks every failure to open the project database: no database yet, an unusable file, a failed migration. Callers that need to classify a failure (notably the CLI's top-level JSON error envelope) match on this instead of every RunE having to tag its own db.Open call — the classification belongs to the store, not to 150 call sites.

View Source
var ErrIssueNotFound = errors.New("issue not found")

ErrIssueNotFound marks a lookup for an issue ID that is not in the database, so "that id does not exist" is distinguishable from a storage failure without matching on message text.

View Source
var Migrations = []Migration{

	{
		Version:     2,
		Description: "Add action_log table for undo support",
		SQL: `
CREATE TABLE IF NOT EXISTS action_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT NOT NULL,
    action_type TEXT NOT NULL,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    previous_data TEXT DEFAULT '',
    new_data TEXT DEFAULT '',
    timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    undone INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_action_log_session ON action_log(session_id);
CREATE INDEX IF NOT EXISTS idx_action_log_timestamp ON action_log(timestamp);
`,
	},
	{
		Version:     3,
		Description: "Allow work session logs without issue_id",
		SQL: `
-- SQLite doesn't support ALTER COLUMN, so we need to recreate the table
CREATE TABLE logs_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    issue_id TEXT DEFAULT '',
    session_id TEXT NOT NULL,
    work_session_id TEXT DEFAULT '',
    message TEXT NOT NULL,
    type TEXT NOT NULL DEFAULT 'progress',
    timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO logs_new SELECT * FROM logs;
DROP TABLE logs;
ALTER TABLE logs_new RENAME TO logs;
CREATE INDEX IF NOT EXISTS idx_logs_issue ON logs(issue_id);
CREATE INDEX IF NOT EXISTS idx_logs_work_session ON logs(work_session_id);
`,
	},
	{
		Version:     4,
		Description: "Add minor flag to issues for self-reviewable tasks",
		SQL:         `ALTER TABLE issues ADD COLUMN minor INTEGER DEFAULT 0;`,
	},
	{
		Version:     5,
		Description: "Add created_branch to issues",
		SQL:         `ALTER TABLE issues ADD COLUMN created_branch TEXT DEFAULT '';`,
	},
	{
		Version:     6,
		Description: "Add creator_session for review enforcement",
		SQL:         `ALTER TABLE issues ADD COLUMN creator_session TEXT DEFAULT '';`,
	},
	{
		Version:     7,
		Description: "Add session history for review enforcement",
		SQL: `CREATE TABLE IF NOT EXISTS issue_session_history (
    id TEXT PRIMARY KEY,
    issue_id TEXT NOT NULL,
    session_id TEXT NOT NULL,
    action TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (issue_id) REFERENCES issues(id)
);
CREATE INDEX IF NOT EXISTS idx_ish_issue ON issue_session_history(issue_id);
CREATE INDEX IF NOT EXISTS idx_ish_session ON issue_session_history(session_id);`,
	},
	{
		Version:     8,
		Description: "Add timestamp indexes for activity queries",
		SQL: `CREATE INDEX IF NOT EXISTS idx_handoffs_timestamp ON handoffs(timestamp);
CREATE INDEX IF NOT EXISTS idx_issues_deleted_status ON issues(deleted_at, status);`,
	},
	{
		Version:     9,
		Description: "Add boards and board_issues tables",
		SQL: `
-- Boards table
CREATE TABLE IF NOT EXISTS boards (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL COLLATE NOCASE UNIQUE,
    last_viewed_at DATETIME,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Board-Issue membership with ordering
CREATE TABLE IF NOT EXISTS board_issues (
    board_id TEXT NOT NULL,
    issue_id TEXT NOT NULL,
    position INTEGER NOT NULL,
    added_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (board_id, issue_id),
    FOREIGN KEY (board_id) REFERENCES boards(id) ON DELETE CASCADE,
    FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_board_issues_position ON board_issues(board_id, position);
`,
	},
	{
		Version:     10,
		Description: "Query-based boards with sparse ordering and sprint field",
		SQL: `
-- Add query and is_builtin columns to boards
ALTER TABLE boards ADD COLUMN query TEXT NOT NULL DEFAULT '';
ALTER TABLE boards ADD COLUMN is_builtin INTEGER NOT NULL DEFAULT 0;

-- Rename board_issues to board_issue_positions for semantic clarity
DROP INDEX IF EXISTS idx_board_issues_position;
ALTER TABLE board_issues RENAME TO board_issue_positions;

-- Recreate index on positions
CREATE UNIQUE INDEX IF NOT EXISTS idx_board_positions_position
    ON board_issue_positions(board_id, position);

-- Add sprint field to issues
ALTER TABLE issues ADD COLUMN sprint TEXT DEFAULT '';

-- Create built-in "All Issues" board (empty query = all issues)
INSERT INTO boards (id, name, query, is_builtin, created_at, updated_at)
VALUES ('bd-all-issues', 'All Issues', '', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET
    query = excluded.query,
    is_builtin = 1,
    updated_at = CURRENT_TIMESTAMP;
`,
	},
	{
		Version:     11,
		Description: "Add view_mode to boards for swimlanes/backlog toggle",
		SQL:         `ALTER TABLE boards ADD COLUMN view_mode TEXT NOT NULL DEFAULT 'swimlanes';`,
	},
	{
		Version:     12,
		Description: "Add missing indices for monitor query performance",
		SQL: `CREATE INDEX IF NOT EXISTS idx_action_log_entity_type ON action_log(entity_id, action_type);
CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
CREATE INDEX IF NOT EXISTS idx_comments_created_at ON comments(created_at);`,
	},
	{
		Version:     13,
		Description: "Extend sessions table for full DB-backed session storage",

		SQL: "",
	},
	{
		Version:     14,
		Description: "Repair sessions table for DBs where v13 did not apply correctly",

		SQL: "",
	},
	{
		Version:     15,
		Description: "Migrate integer PK tables to text IDs for sync compatibility",

		SQL: "",
	},
	{
		Version:     16,
		Description: "Add sync_state table and sync columns to action_log",
		SQL: `
CREATE TABLE IF NOT EXISTS sync_state (
    project_id TEXT PRIMARY KEY,
    last_pushed_action_id INTEGER DEFAULT 0,
    last_pulled_server_seq INTEGER DEFAULT 0,
    last_sync_at DATETIME,
    sync_disabled INTEGER DEFAULT 0
);
ALTER TABLE action_log ADD COLUMN synced_at DATETIME;
ALTER TABLE action_log ADD COLUMN server_seq INTEGER;
`,
	},
	{
		Version:     17,
		Description: "Add sync_conflicts table for overwrite tracking",
		SQL: `
CREATE TABLE IF NOT EXISTS sync_conflicts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    server_seq INTEGER NOT NULL,
    local_data JSON,
    remote_data JSON,
    overwritten_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON sync_conflicts(entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_sync_conflicts_time ON sync_conflicts(overwritten_at);
CREATE INDEX IF NOT EXISTS idx_sync_conflicts_seq ON sync_conflicts(server_seq);
`,
	},
	{
		Version:     18,
		Description: "Add deterministic ID columns to composite-key tables for sync",

		SQL: "",
	},
	{
		Version:     19,
		Description: "Convert absolute file paths to repo-relative in issue_files",

		SQL: "",
	},
	{
		Version:     20,
		Description: "Normalize legacy action_log entries for composite-key entities",

		SQL: "",
	},
	{
		Version:     21,
		Description: "Add sync_history table for tracking sync operations",
		SQL: `
CREATE TABLE IF NOT EXISTS sync_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    direction TEXT NOT NULL,
    action_type TEXT NOT NULL,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    server_seq INTEGER,
    device_id TEXT DEFAULT '',
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sync_history_ts ON sync_history(timestamp);
`,
	},
	{
		Version:     22,
		Description: "Sparse positioning: drop unique position index, re-space with gaps",
		SQL: `
DROP INDEX IF EXISTS idx_board_positions_position;
UPDATE board_issue_positions SET position = position * 65536;
`,
	},
	{
		Version:     23,
		Description: "Drop UNIQUE(name) on boards to prevent sync data loss",
		SQL: `
CREATE TABLE boards_new (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL COLLATE NOCASE,
    last_viewed_at DATETIME,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    query TEXT NOT NULL DEFAULT '',
    is_builtin INTEGER NOT NULL DEFAULT 0,
    view_mode TEXT NOT NULL DEFAULT 'swimlanes'
);
INSERT INTO boards_new SELECT * FROM boards;
DROP TABLE boards;
ALTER TABLE boards_new RENAME TO boards;
`,
	},
	{
		Version:     24,
		Description: "Add deterministic id column to work_session_issues for sync",

		SQL: "",
	},
	{
		Version:     25,
		Description: "Add deleted_at to board_issue_positions for soft delete sync",

		SQL: "",
	},
	{
		Version:     26,
		Description: "Enforce NOT NULL on action_log.id by fixing NULL values and recreating table",

		SQL: "",
	},
	{
		Version:     27,
		Description: "Normalize NULL session fields in issues",
		SQL: `
UPDATE issues SET implementer_session = '' WHERE implementer_session IS NULL;
UPDATE issues SET reviewer_session = '' WHERE reviewer_session IS NULL;
UPDATE issues SET creator_session = '' WHERE creator_session IS NULL;
`,
	},
	{
		Version:     28,
		Description: "Add notes table for sidecar notes sync",
		SQL: `
CREATE TABLE IF NOT EXISTS notes (
    id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    pinned INTEGER DEFAULT 0,
    archived INTEGER DEFAULT 0,
    deleted_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_notes_updated ON notes(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_notes_deleted ON notes(deleted_at);
`,
	},
	{
		Version:     29,
		Description: "Add defer_until, due_date, defer_count columns to issues",
		SQL: `
ALTER TABLE issues ADD COLUMN defer_until TEXT;
ALTER TABLE issues ADD COLUMN due_date TEXT;
ALTER TABLE issues ADD COLUMN defer_count INTEGER DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_issues_defer_until ON issues(defer_until);
CREATE INDEX IF NOT EXISTS idx_issues_due_date ON issues(due_date);
`,
	},
	{
		Version:     30,
		Description: "FK orphan cleanup + ON DELETE CASCADE for FK enforcement (td-4846e6)",

		SQL: "",
	},
	{
		Version:     31,
		Description: "Add review-attestation columns to issues and issue_reviews table",

		SQL: "",
	},
	{
		Version:     32,
		Description: "Add self_review column to issue_reviews",

		SQL: "",
	},
	{
		Version:     33,
		Description: "Add match_context_id to sessions for sub-agent session keying (td-64dc09)",

		SQL: "",
	},
	{
		Version:     34,
		Description: "Add worktree identity metadata to sessions and work sessions (td-83cfc9)",

		SQL: "",
	},
	{
		Version:     35,
		Description: "Add local-only session_state table (td-3d427b)",
		SQL: `
CREATE TABLE IF NOT EXISTS session_state (
    session_id TEXT NOT NULL,
    worktree_id TEXT DEFAULT '',
    focused_issue_id TEXT DEFAULT '',
    active_work_session_id TEXT DEFAULT '',
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY(session_id, worktree_id)
);
`,
	},
	{
		Version:     36,
		Description: "Normalize legacy Go-format timestamps to canonical SQLite layout",

		SQL: "",
	},
	{
		Version:     37,
		Description: "Add reviewed_by attribution column to issue_reviews",

		SQL: "",
	},
	{
		Version:     38,
		Description: "Add sync_skipped_events table so an unappliable remote event cannot wedge the stream",

		SQL: `
CREATE TABLE IF NOT EXISTS sync_skipped_events (
    server_seq INTEGER PRIMARY KEY,
    device_id TEXT NOT NULL DEFAULT '',
    action_type TEXT NOT NULL DEFAULT '',
    entity_type TEXT NOT NULL DEFAULT '',
    entity_id TEXT NOT NULL DEFAULT '',
    reason TEXT NOT NULL,
    error TEXT NOT NULL DEFAULT '',
    payload JSON,
    skipped_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sync_skipped_time ON sync_skipped_events(skipped_at);
CREATE INDEX IF NOT EXISTS idx_sync_skipped_reason ON sync_skipped_events(reason);
`,
	},
}

Migrations is the list of all database migrations in order

View Source
var QueryValidator func(queryStr string) error

QueryValidator is set by main to validate TDQ queries without import cycle. Returns nil if valid, error describing parse failure otherwise.

Functions

func AnalyticsEnabled added in v0.7.0

func AnalyticsEnabled() bool

AnalyticsEnabled returns true unless TD_ANALYTICS is explicitly disabled

func BaseSchema added in v0.30.0

func BaseSchema() string

BaseSchema returns the initial database schema DDL. Used by the sync test harness to avoid schema duplication.

func BoardIssuePosID added in v0.30.0

func BoardIssuePosID(boardID, issueID string) string

BoardIssuePosID returns a deterministic ID for a board_issue_positions row.

func ClearAgentErrors added in v0.4.16

func ClearAgentErrors(baseDir string) error

ClearAgentErrors removes the agent errors file.

func ClearCommandUsage added in v0.7.0

func ClearCommandUsage(baseDir string) error

ClearCommandUsage removes the usage file

func ClearSecurityEvents added in v0.5.0

func ClearSecurityEvents(baseDir string) error

ClearSecurityEvents removes the security events file

func CountAgentErrors added in v0.4.16

func CountAgentErrors(baseDir string) (int, error)

CountAgentErrors returns the number of logged errors.

func CountCommandUsage added in v0.7.0

func CountCommandUsage(baseDir string) (int, error)

CountCommandUsage returns the number of logged events

func DependencyID added in v0.30.0

func DependencyID(issueID, dependsOnID, relationType string) string

DependencyID returns a deterministic ID for an issue_dependencies row.

func FormatCanonicalTime added in v0.51.2

func FormatCanonicalTime(t time.Time) string

FormatCanonicalTime renders t in the canonical SQLite layout td writes.

func IsAbsolutePath added in v0.30.0

func IsAbsolutePath(p string) bool

IsAbsolutePath returns true if the path looks like an absolute path (starts with / on Unix or a drive letter on Windows).

func IssueFileID added in v0.30.0

func IssueFileID(issueID, filePath string) string

IssueFileID returns a deterministic ID for an issue_files row. The file path is normalized to forward slashes before hashing so the same ID is generated regardless of OS path separators.

func LogAgentError added in v0.4.16

func LogAgentError(baseDir string, args []string, errMsg string, sessionID string) error

LogAgentError appends a failed command to the agent errors file. baseDir is the project root. If the .todos directory doesn't exist, the error is silently dropped (project not initialized).

func LogCommandUsage added in v0.7.0

func LogCommandUsage(baseDir string, event CommandUsageEvent) error

LogCommandUsage appends a usage event to the JSONL file

func LogCommandUsageAsync added in v0.7.0

func LogCommandUsageAsync(baseDir string, event CommandUsageEvent)

LogCommandUsageAsync logs without blocking the caller

func LogSecurityEvent added in v0.5.0

func LogSecurityEvent(baseDir string, event SecurityEvent) error

LogSecurityEvent appends a security event to the jsonl file

func LooksLikeGoTimeString added in v0.51.2

func LooksLikeGoTimeString(s string) bool

LooksLikeGoTimeString reports whether s appears to have been produced by time.Time.String() rather than the canonical SQLite layout. Such values carry a monotonic-clock suffix (" m=+...") and/or a trailing zone name, neither of which the SQLite driver can reliably parse back into a time.Time.

func NormalizeFilePathForID added in v0.30.0

func NormalizeFilePathForID(p string) string

NormalizeFilePathForID normalizes a file path to forward slashes for use in deterministic ID generation. This ensures the same ID is generated regardless of OS path separators.

func NormalizeIssueID added in v0.4.17

func NormalizeIssueID(id string) string

NormalizeIssueID ensures an issue ID has the td- prefix Accepts bare hex IDs like "abc123" and returns "td-abc123"

func OpenSQLite added in v0.44.0

func OpenSQLite(path string, opts OpenOptions) (*sql.DB, error)

OpenSQLite opens a SQLite database at path and applies td's standard pragma policy so every caller gets identical behaviour:

PRAGMA journal_mode = TRUNCATE
PRAGMA busy_timeout = 5000           (overridable via OpenOptions.BusyTimeout)
PRAGMA synchronous  = NORMAL
PRAGMA foreign_keys = ON             (unless OpenOptions.DisableForeignKeys)

journal_mode is TRUNCATE, not WAL, on purpose. modernc's WAL shared-memory coordination repeatedly corrupted issues.db ("database disk image is malformed") when a long-lived embedded connection (Sidecar's td monitor) ran concurrently with bursts of short-lived CLI processes — see td-adbf16. The rollback-journal path uses plain POSIX file locks, has no -shm/-wal state to race on, and td's write volumes make the concurrency cost of writers briefly blocking readers irrelevant. Do not switch back to WAL without a multi-process soak test covering that embedded-monitor pattern.

The pool is pinned with SetMaxOpenConns(1) unless OpenOptions.MaxOpenConns is set. ReadOnly connections open with mode=ro and skip write-only pragmas.

func ParseLenientTime added in v0.51.2

func ParseLenientTime(s string) (time.Time, bool)

ParseLenientTime parses a timestamp string that may be in the canonical SQLite layout or a legacy Go time.Time.String() rendering. It strips the monotonic-clock suffix, tolerates a nameless zone rendered as a repeated numeric offset, and tries a range of layouts. Returns ok=false if the value cannot be parsed by any known layout, so callers can degrade gracefully rather than fail hard.

func PruneSyncHistory added in v0.30.0

func PruneSyncHistory(tx *sql.Tx, maxRows int) error

PruneSyncHistory deletes rows not in the newest maxRows entries.

func ReadyToCloseByFilter added in v0.45.0

func ReadyToCloseByFilter(sessionID, mode string) (string, []interface{})

ReadyToCloseByFilter returns the SQL fragment and args for issues that are ready to close because an active approval review already exists. Under strict and balanced modes there is no close-after-recorded-review path, so the filter returns an always-false clause. Under delegated and trusted modes it matches in_review issues with a non-superseded approval in issue_reviews; the closing session is recorded for audit but does not gate the close.

Step 2 wires the CLI / monitor / snapshot-query-source callers; Batch 1c only ships the composer so it is ready.

func RecordSkippedEventsTx added in v0.60.0

func RecordSkippedEventsTx(tx *sql.Tx, events []SkippedSyncEvent) error

RecordSkippedEventsTx records skipped events inside the caller's transaction, so the record commits with the batch that skipped them — never one without the other.

Keyed on server_seq with INSERT OR REPLACE: re-recording the same event (e.g. a batch replayed after an unrelated rollback) updates the row instead of accumulating duplicates.

func RecordSyncHistoryTx added in v0.30.0

func RecordSyncHistoryTx(tx *sql.Tx, entries []SyncHistoryEntry) error

RecordSyncHistoryTx batch-inserts sync history entries within the provided transaction. Returns nil if entries is empty.

func ResolveBaseDir added in v0.12.0

func ResolveBaseDir(baseDir string) string

ResolveBaseDir checks for a .td-root file in the given directory. If found, it returns the path contained in that file (pointing to the main worktree's root). Otherwise, returns the original baseDir unchanged. This enables git worktrees to share a single td database with the main repo.

func ReviewableByFilter added in v0.40.0

func ReviewableByFilter(sessionID string, balanced bool) (string, []interface{})

ReviewableByFilter returns the SQL fragment and args for the ReviewableBy filter. It is exported so that other packages (e.g. internal/api) can reuse the same policy logic.

Mode mapping (Batch 1c):

  • balanced=false -> strict SQL
  • balanced=true -> balanced SQL

Delegated mode is driven by ReviewableByFilterForMode. The boolean signature is kept for backward compatibility; ListIssuesOptions still passes a bool so existing callers do not have to be rewritten. A delegated-mode caller (Step 2) uses ReviewableByFilterForMode directly.

func ReviewableByFilterForMode added in v0.45.0

func ReviewableByFilterForMode(sessionID, mode string) (string, []interface{})

ReviewableByFilterForMode composes the reviewable-by SQL fragment for the supplied mode string. Exported so other surfaces (monitor list helpers, snapshot query source, Step-2 CLI callers) can route through the same policy-aware composer as the primary list path.

For "delegated" the filter is based only on implementation independence: a session may review when it is not the current implementer and it has no started/unstarted history. Prior review/log/history involvement is not a review disqualifier in delegated mode.

func SanitizeFlags added in v0.7.0

func SanitizeFlags(flags map[string]string) map[string]string

SanitizeFlags redacts sensitive flag values

func ToRepoRelative added in v0.30.0

func ToRepoRelative(absPath, repoRoot string) (string, error)

ToRepoRelative converts an absolute file path to a repo-relative path using forward slashes for cross-platform stability. Returns an error if the path is outside the repo root.

func WithMaintenanceLock added in v0.52.0

func WithMaintenanceLock(baseDir string, fn func() error) error

WithMaintenanceLock runs fn while holding the same cross-process lock used by normal CLI writes. It is intended for database-file maintenance (such as snapshot replacement) that cannot safely overlap another td writer.

func WsiID added in v0.30.0

func WsiID(workSessionID, issueID string) string

WsiID returns a deterministic ID for a work_session_issues row.

Types

type AgentError added in v0.4.16

type AgentError struct {
	Timestamp time.Time `json:"ts"`
	Args      []string  `json:"args"`
	Error     string    `json:"error"`
	SessionID string    `json:"session,omitempty"`
}

AgentError represents a failed command invocation

func ReadAgentErrors added in v0.4.16

func ReadAgentErrors(baseDir string) ([]AgentError, error)

ReadAgentErrors reads all agent errors from the file. Returns empty slice if file doesn't exist.

func ReadAgentErrorsFiltered added in v0.4.16

func ReadAgentErrorsFiltered(baseDir string, sessionID string, since time.Time, limit int) ([]AgentError, error)

ReadAgentErrorsFiltered reads agent errors matching the filter criteria.

type AnalyticsSummary added in v0.7.0

type AnalyticsSummary struct {
	TotalCommands   int            `json:"total_commands"`
	UniqueCommands  int            `json:"unique_commands"`
	CommandCounts   map[string]int `json:"by_command"`
	FlagCounts      map[string]int `json:"by_flag"`
	DailyActivity   map[string]int `json:"daily"`
	ErrorRate       float64        `json:"error_rate"`
	ErrorsByCommand map[string]int `json:"errors_by_command"`
	SessionActivity map[string]int `json:"by_session"`
	AvgDurationMs   int64          `json:"avg_dur_ms"`
	NeverUsed       []string       `json:"never_used,omitempty"`
}

AnalyticsSummary holds aggregated analytics data

func ComputeAnalyticsSummary added in v0.7.0

func ComputeAnalyticsSummary(events []CommandUsageEvent, allCommands []string) *AnalyticsSummary

ComputeAnalyticsSummary aggregates events into summary stats

type BoardIssuePosition added in v0.10.0

type BoardIssuePosition struct {
	BoardID  string
	IssueID  string
	Position int
}

BoardIssuePosition represents an explicit position for an issue on a board

type ClaimRelease added in v0.55.0

type ClaimRelease struct {
	IssueID string
	// ExpectedHolder is the session the caller believes holds the claim.
	// Empty means "whoever holds it" — used by the named `td unstart <id>`
	// path, where the operator is naming the issue explicitly.
	ExpectedHolder string
	// LogMessage is written to the issue's history as a progress log.
	LogMessage string
}

ClaimRelease names one implementer claim to release.

ExpectedHolder, when non-empty, is a guard: the claim is released only if the issue is STILL held by that session at the moment the write lock is held. A sweep selects its targets from a snapshot taken before the lock, and between the snapshot and the write another process can legitimately unstart the issue, hand it off, or start it fresh under a new session. Releasing on the strength of a stale snapshot silently revokes that newer claim.

type ClaimReleaseOutcome added in v0.55.0

type ClaimReleaseOutcome struct {
	IssueID string
	// Released is true only when this call performed the state change.
	Released bool
	// Skipped is true when the guard did not hold — the issue was not
	// claimed any more, or a different session holds it now. This is not an
	// error: the claim moved on, and the caller must not count it as released.
	Skipped bool
	// Reason explains a Skipped outcome in caller-facing terms.
	Reason string
	// Issue is the post-release state, set only when Released.
	Issue *models.Issue
	// Err is a genuine failure (database error) for this issue.
	Err error
}

ClaimReleaseOutcome reports what happened to one ClaimRelease. Exactly one of Released / Skipped / Err is meaningful.

type CommandUsageEvent added in v0.7.0

type CommandUsageEvent struct {
	Timestamp  time.Time         `json:"ts"`
	Command    string            `json:"cmd"`
	Subcommand string            `json:"sub,omitempty"`
	Flags      map[string]string `json:"flags,omitempty"`
	SessionID  string            `json:"session,omitempty"`
	Success    bool              `json:"ok"`
	DurationMs int64             `json:"dur_ms"`
	Error      string            `json:"err,omitempty"`
}

CommandUsageEvent represents a single CLI invocation

func ReadCommandUsage added in v0.7.0

func ReadCommandUsage(baseDir string) ([]CommandUsageEvent, error)

ReadCommandUsage reads all usage events from the file

func ReadCommandUsageFiltered added in v0.7.0

func ReadCommandUsageFiltered(baseDir string, since time.Time, limit int) ([]CommandUsageEvent, error)

ReadCommandUsageFiltered reads usage events matching filter criteria

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB wraps the database connection

func Initialize

func Initialize(baseDir string) (*DB, error)

Initialize creates the database and runs migrations

func NewWithConn added in v0.45.0

func NewWithConn(conn *sql.DB, baseDir string) *DB

NewWithConn wraps an already-opened *sql.DB and a base directory in a *DB. This exists for callers that own the file layout (e.g., the td-sync API server, which keeps per-project DBs at non-standard paths like `{projectDir}/project.db`) and have already opened the connection via OpenSQLite. The returned *DB participates in the same DB API surface (Conn, BaseDir, etc.) as Open/Initialize.

func Open

func Open(baseDir string) (*DB, error)

Open opens the database and runs any pending migrations

func (*DB) AddComment

func (db *DB) AddComment(comment *models.Comment) error

AddComment adds a comment to an issue

func (*DB) AddDependency

func (db *DB) AddDependency(issueID, dependsOnID, relationType string) error

AddDependency adds a dependency between issues WITHOUT logging to action_log. For local mutations, use AddDependencyLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) AddDependencyLogged added in v0.30.0

func (db *DB) AddDependencyLogged(issueID, dependsOnID, relationType, sessionID string) error

AddDependencyLogged adds a dependency and logs the action atomically within a single withWriteLock call.

func (*DB) AddGitSnapshot

func (db *DB) AddGitSnapshot(snapshot *models.GitSnapshot) error

AddGitSnapshot records a git state snapshot

func (*DB) AddHandoff

func (db *DB) AddHandoff(handoff *models.Handoff) error

AddHandoff adds a handoff entry and logs it to action_log for sync/undo.

func (*DB) AddLog

func (db *DB) AddLog(log *models.Log) error

AddLog adds a log entry to an issue

func (*DB) ApplyBoardPositions added in v0.10.0

func (db *DB) ApplyBoardPositions(boardID string, issues []models.Issue) ([]models.BoardIssueView, error)

ApplyBoardPositions takes a list of issues and applies board positions. Issues with explicit positions are sorted by position and returned first, followed by unpositioned issues in their original order. This function should be used with query.Execute() results for boards with TDQ queries.

func (*DB) ArchiveNote added in v0.33.0

func (db *DB) ArchiveNote(id string) error

ArchiveNote sets a note's archived status to true.

func (*DB) BaseDir

func (db *DB) BaseDir() string

BaseDir returns the base directory for the database

func (*DB) CascadeUnblockDependents added in v0.24.0

func (db *DB) CascadeUnblockDependents(closedIssueID, sessionID string) (int, []string)

CascadeUnblockDependents checks issues that depend on closedIssueID. For each dependent in "blocked" status, if ALL its dependencies are now closed, it transitions the dependent from blocked → open. Returns the count and IDs of unblocked issues.

func (*DB) CascadeUpParentStatus added in v0.4.16

func (db *DB) CascadeUpParentStatus(issueID string, targetStatus models.Status, sessionID string) (int, []string)

CascadeUpParentStatus checks if all children of a parent epic have reached the target status, and if so, updates the parent to that status. Works recursively up the parent chain. Returns the number of parents that were cascaded and the list of cascaded parent IDs.

func (*DB) ClearActionLogSyncState added in v0.30.0

func (db *DB) ClearActionLogSyncState() (int64, error)

ClearActionLogSyncState sets synced_at and server_seq to NULL on all action_log entries, allowing them to be re-pushed to a new server. Returns the number of rows affected.

func (*DB) ClearActiveWorkSession added in v0.51.0

func (db *DB) ClearActiveWorkSession(scope SessionStateScope) error

ClearActiveWorkSession clears the scoped active work session in the local DB.

func (*DB) ClearFocus added in v0.51.0

func (db *DB) ClearFocus(scope SessionStateScope) error

ClearFocus clears the scoped focused issue in the local DB.

func (*DB) ClearReviewSupersededAt added in v0.45.0

func (db *DB) ClearReviewSupersededAt(reviewID string) error

ClearReviewSupersededAt removes the superseded_at timestamp on a review row, re-activating it. Used by undo to restore a prior active approval that the undone action superseded.

func (*DB) ClearReviewSupersededAtLogged added in v0.54.0

func (db *DB) ClearReviewSupersededAtLogged(reviewID, sessionID string) error

ClearReviewSupersededAtLogged reactivates a prior review during undo and emits the corresponding update event.

func (*DB) ClearSyncState added in v0.30.0

func (db *DB) ClearSyncState() error

ClearSyncState removes the sync state (used for unlink).

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection. It performs a PASSIVE checkpoint first to flush the WAL into the main DB file where possible without blocking readers/writers in other processes. TRUNCATE was avoided here because it can fail or stall when another td process still holds the -shm; SQLite autocheckpoints at 1000 pages so the aggressive variant is unnecessary on exit.

func (*DB) ComputeInsertPosition added in v0.30.0

func (db *DB) ComputeInsertPosition(boardID string, slot int) (int, []RespaceResult, error)

ComputeInsertPosition computes a sparse sort key for inserting at visual slot (1-based). If the board is empty, returns PositionGap. If slot <= 1 (top): returns min_position - PositionGap. If slot > count (bottom): returns max_position + PositionGap. Otherwise: returns midpoint of positions[slot-2] and positions[slot-1]. If the gap between neighbors is < 2, calls RespaceBoardPositions first and recomputes.

func (*DB) Conn added in v0.30.0

func (db *DB) Conn() *sql.DB

Conn returns the underlying *sql.DB connection for use in transactions (e.g., by the sync library which needs raw DB access).

func (*DB) CountPendingEvents added in v0.30.0

func (db *DB) CountPendingEvents() (int64, error)

CountPendingEvents returns the number of unsynced action_log entries.

func (*DB) CountSkippedEvents added in v0.60.0

func (db *DB) CountSkippedEvents() (map[string]int, error)

CountSkippedEvents returns how many remote events this peer has skipped, broken down by reason.

func (*DB) CountSyncedEvents added in v0.30.0

func (db *DB) CountSyncedEvents() (int64, error)

CountSyncedEvents returns the number of action_log entries with synced_at set.

func (*DB) CreateBoard added in v0.10.0

func (db *DB) CreateBoard(name, queryStr string) (*models.Board, error)

CreateBoard creates a new board with a TDQ query WITHOUT logging to action_log. For local mutations, use CreateBoardLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) CreateBoardLogged added in v0.30.0

func (db *DB) CreateBoardLogged(name, queryStr, sessionID string) (*models.Board, error)

CreateBoardLogged creates a board and logs the action atomically within a single withWriteLock call.

func (*DB) CreateIssue

func (db *DB) CreateIssue(issue *models.Issue) error

CreateIssue creates a new issue WITHOUT logging to action_log. For local mutations, use CreateIssueLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) CreateIssueLogged added in v0.30.0

func (db *DB) CreateIssueLogged(issue *models.Issue, sessionID string) error

CreateIssueLogged creates an issue and logs the action atomically within a single withWriteLock call.

func (*DB) CreateIssueReview added in v0.45.0

func (db *DB) CreateIssueReview(rv NewReview) (string, error)

CreateIssueReview inserts a new review row and returns its id. The caller is responsible for superseding any prior active review (see SupersedeActiveReviews) — this helper only appends history.

func (*DB) CreateIssueReviewAndUpdateIssueLogged added in v0.54.0

func (db *DB) CreateIssueReviewAndUpdateIssueLogged(
	rv NewReview, issue *models.Issue, expectedStatus models.Status,
	sessionID string, actionType models.ActionType,
) (string, error)

CreateIssueReviewAndUpdateIssueLogged persists an entire review lifecycle transition in one transaction: prior-review supersession, the new review and its sync event, the issue mutation, and the enclosing issue action event.

func (*DB) CreateNote added in v0.33.0

func (db *DB) CreateNote(title, content string) (*models.Note, error)

CreateNote creates a new note and logs the action for undo support.

func (*DB) CreateWorkSession

func (db *DB) CreateWorkSession(ws *models.WorkSession) error

CreateWorkSession creates a new work session

func (*DB) DeleteBoard added in v0.10.0

func (db *DB) DeleteBoard(id string) error

DeleteBoard deletes a board (fails for builtin boards) WITHOUT logging to action_log. For local mutations, use DeleteBoardLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) DeleteBoardLogged added in v0.30.0

func (db *DB) DeleteBoardLogged(boardID, sessionID string) error

DeleteBoardLogged deletes a board and logs the action atomically within a single withWriteLock call.

func (*DB) DeleteCommentLogged added in v0.39.0

func (db *DB) DeleteCommentLogged(commentID, sessionID string) error

DeleteCommentLogged hard-deletes a comment and logs the action atomically.

func (*DB) DeleteHandoff added in v0.4.16

func (db *DB) DeleteHandoff(handoffID string) error

DeleteHandoff removes a handoff by ID (for undo support)

func (*DB) DeleteIssue

func (db *DB) DeleteIssue(id string) error

DeleteIssue soft-deletes an issue WITHOUT logging to action_log. For local mutations, use DeleteIssueLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) DeleteIssueLogged added in v0.30.0

func (db *DB) DeleteIssueLogged(issueID, sessionID string) error

DeleteIssueLogged soft-deletes an issue and logs the action atomically within a single withWriteLock call.

func (*DB) DeleteIssueReview added in v0.45.0

func (db *DB) DeleteIssueReview(reviewID string) error

DeleteIssueReview removes a review row by id. Used by the undo path to roll back reviews that an action inserted; callers pass the CreatedReviewID recorded in the action's ReviewUndoPayload.

func (*DB) DeleteIssueReviewLogged added in v0.54.0

func (db *DB) DeleteIssueReviewLogged(reviewID, sessionID string) error

DeleteIssueReviewLogged removes a review as part of undo and emits a hard delete event so peers roll back the created approval too.

func (*DB) DeleteNote added in v0.33.0

func (db *DB) DeleteNote(id string) error

DeleteNote soft-deletes a note and logs the action for undo support.

func (*DB) DeleteSessionsByID added in v0.55.0

func (db *DB) DeleteSessionsByID(ids []string) (int64, error)

DeleteSessionsByID removes exactly the named session rows.

`td session cleanup` previews in Go and used to delete in SQL with a re-evaluated predicate, so the two could disagree — and the rows it must NOT delete (holders of live claims) are not expressible as a time predicate at all. Deleting the list that was previewed keeps the preview honest.

func (*DB) DeleteStaleSessions added in v0.27.0

func (db *DB) DeleteStaleSessions(before time.Time) (int64, error)

DeleteStaleSessions removes sessions with last_activity before the given time

func (*DB) GetActionLogByID added in v0.38.0

func (db *DB) GetActionLogByID(id string) (*models.ActionLog, error)

GetActionLogByID retrieves a single action log entry by ID

func (*DB) GetActiveApprovalReview added in v0.45.0

func (db *DB) GetActiveApprovalReview(issueID string) (*models.IssueReview, error)

GetActiveApprovalReview returns the current non-superseded approval review for an issue, or nil if none exists. Only decisions that represent an actual approval are considered (approved and approved_by_parent_cascade); a non-superseded changes_requested row does not mean the issue has an active approval and is therefore skipped.

func (*DB) GetActiveSessions

func (db *DB) GetActiveSessions(since time.Time) ([]string, error)

GetActiveSessions returns distinct session IDs with activity since the given time

func (*DB) GetActiveWorkSession added in v0.51.0

func (db *DB) GetActiveWorkSession(scope SessionStateScope) (string, error)

GetActiveWorkSession returns the scoped active work session. When no scoped DB row exists yet, it optionally falls back to config.json through the provided read-only hook.

func (*DB) GetAllDependencies added in v0.7.0

func (db *DB) GetAllDependencies() (map[string][]string, error)

GetAllDependencies returns all dependency relationships as a map

func (*DB) GetBlockedBy

func (db *DB) GetBlockedBy(issueID string) ([]string, error)

GetBlockedBy returns what issues are blocked by this issue

func (*DB) GetBlockersForIssues added in v0.48.0

func (db *DB) GetBlockersForIssues(issueIDs []string) (map[string][]string, error)

GetBlockersForIssues fetches, for each issue id, the list of issue ids it depends on (the depends_on direction: B blocks A when A depends_on B). Returns a map keyed by issue_id whose values are the depends_on_id targets. Runs a single IN (...) query. Empty input returns an empty map.

func (*DB) GetBoard added in v0.10.0

func (db *DB) GetBoard(id string) (*models.Board, error)

GetBoard retrieves a board by ID

func (*DB) GetBoardByName added in v0.10.0

func (db *DB) GetBoardByName(name string) (*models.Board, error)

GetBoardByName retrieves a board by name (case-insensitive)

func (*DB) GetBoardIssuePositions added in v0.10.0

func (db *DB) GetBoardIssuePositions(boardID string) ([]BoardIssuePosition, error)

GetBoardIssuePositions returns all explicit (non-deleted) positions for a board

func (*DB) GetBoardIssues added in v0.10.0

func (db *DB) GetBoardIssues(boardID, sessionID string, statusFilter []models.Status) ([]models.BoardIssueView, error)

GetBoardIssues returns issues for a board with their positions. For boards with empty query, it fetches all issues directly. For boards with TDQ queries, callers should use ApplyBoardPositions with pre-executed query results to avoid circular import issues. Issues are returned: positioned first (by position), then unpositioned (by query order).

func (*DB) GetChangeToken added in v0.39.0

func (db *DB) GetChangeToken() (string, error)

GetChangeToken returns the MAX(rowid) from action_log as a string. This serves as a lightweight change-detection token for the HTTP API: clients compare consecutive tokens to know whether any mutation has occurred.

func (*DB) GetCommentByID added in v0.38.0

func (db *DB) GetCommentByID(id string) (*models.Comment, error)

GetCommentByID retrieves a single comment by ID

func (*DB) GetComments

func (db *DB) GetComments(issueID string) ([]models.Comment, error)

GetComments retrieves comments for an issue

func (*DB) GetDependencies

func (db *DB) GetDependencies(issueID string) ([]string, error)

GetDependencies returns what an issue depends on

func (*DB) GetDependencyByDepID added in v0.39.0

func (db *DB) GetDependencyByDepID(depID string) (*models.IssueDependency, error)

GetDependencyByDepID retrieves a single dependency row by its deterministic dep_id.

func (*DB) GetDescendantIssues added in v0.4.16

func (db *DB) GetDescendantIssues(issueID string, statuses []models.Status) ([]*models.Issue, error)

GetDescendantIssues returns all descendant issues (children, grandchildren, etc.) filtered by the given statuses (empty = all statuses)

func (*DB) GetDirectChildren added in v0.4.16

func (db *DB) GetDirectChildren(issueID string) ([]*models.Issue, error)

GetDirectChildren returns the direct children of an issue (not recursive)

func (*DB) GetExtendedStats added in v0.4.1

func (db *DB) GetExtendedStats() (*models.ExtendedStats, error)

GetExtendedStats returns detailed statistics for dashboard/stats displays

func (*DB) GetFocus added in v0.51.0

func (db *DB) GetFocus(scope SessionStateScope) (string, error)

GetFocus returns the scoped focused issue. When no scoped DB row exists yet, it optionally falls back to config.json through the provided read-only hook.

func (*DB) GetHandoffs added in v0.43.0

func (db *DB) GetHandoffs(issueID string) ([]models.Handoff, error)

GetHandoffs retrieves all handoffs for an issue, ordered by timestamp descending.

func (*DB) GetIssue

func (db *DB) GetIssue(id string) (*models.Issue, error)

GetIssue retrieves an issue by ID Accepts bare IDs without the td- prefix (e.g., "abc123" becomes "td-abc123")

func (*DB) GetIssueDependencyRelations added in v0.43.0

func (db *DB) GetIssueDependencyRelations(issueID string) ([]models.IssueDependency, error)

GetIssueDependencyRelations returns all dependency relations for an issue, including relation_type. Used by export for lossless round-trips.

func (*DB) GetIssuePosition added in v0.30.0

func (db *DB) GetIssuePosition(boardID, issueID string) (int, error)

GetIssuePosition returns the current position of an issue on a board, or 0 if not positioned.

func (*DB) GetIssueSessionLog

func (db *DB) GetIssueSessionLog(sessionID string) ([]string, error)

GetIssueSessionLog returns issues touched by a session

func (*DB) GetIssueStatuses added in v0.7.0

func (db *DB) GetIssueStatuses(ids []string) (map[string]models.Status, error)

GetIssueStatuses fetches statuses for multiple issues in a single query

func (*DB) GetIssueTitles added in v0.7.0

func (db *DB) GetIssueTitles(ids []string) (map[string]string, error)

GetIssueTitles fetches titles for multiple issues in a single query

func (*DB) GetIssueTitlesAndStatuses added in v0.48.0

func (db *DB) GetIssueTitlesAndStatuses(ids []string) (map[string]IssueTitleStatus, error)

GetIssueTitlesAndStatuses fetches title+status for multiple issues in a single IN (...) query. Empty input returns an empty map.

func (*DB) GetIssuesByIDs added in v0.7.0

func (db *DB) GetIssuesByIDs(ids []string) ([]models.Issue, error)

GetIssuesByIDs fetches multiple issues in a single query

func (*DB) GetIssuesWithOpenDeps added in v0.16.0

func (db *DB) GetIssuesWithOpenDeps() (map[string]bool, error)

GetIssuesWithOpenDeps returns a set of issue IDs that have at least one open (non-closed) dependency. This is used by the is_ready() and has_open_deps() query functions.

func (*DB) GetLastAction

func (db *DB) GetLastAction(sessionID string) (*models.ActionLog, error)

GetLastAction returns the most recent undoable action for a session

func (*DB) GetLastViewedBoard added in v0.10.0

func (db *DB) GetLastViewedBoard() (*models.Board, error)

GetLastViewedBoard returns the most recently viewed board

func (*DB) GetLatestHandoff

func (db *DB) GetLatestHandoff(issueID string) (*models.Handoff, error)

GetLatestHandoff retrieves the latest handoff for an issue

func (*DB) GetLinkedFiles

func (db *DB) GetLinkedFiles(issueID string) ([]models.IssueFile, error)

GetLinkedFiles returns files linked to an issue

func (*DB) GetLogByID added in v0.38.0

func (db *DB) GetLogByID(id string) (*models.Log, error)

GetLogByID retrieves a single log entry by ID

func (*DB) GetLogs

func (db *DB) GetLogs(issueID string, limit int) ([]models.Log, error)

GetLogs retrieves logs for an issue, including work session logs

func (*DB) GetLogsByWorkSession

func (db *DB) GetLogsByWorkSession(wsID string) ([]models.Log, error)

GetLogsByWorkSession retrieves logs for a specific work session

func (*DB) GetMaxBoardPosition added in v0.13.0

func (db *DB) GetMaxBoardPosition(boardID string) (int, error)

GetMaxBoardPosition returns the highest position value for a board, or 0 if no positioned issues.

func (*DB) GetNote added in v0.33.0

func (db *DB) GetNote(id string) (*models.Note, error)

GetNote retrieves a note by ID. Returns error if not found or soft-deleted.

func (*DB) GetNoteIncludingDeleted added in v0.58.0

func (db *DB) GetNoteIncludingDeleted(id string) (*models.Note, error)

GetNoteIncludingDeleted retrieves a note by ID, including soft-deleted rows.

func (*DB) GetRecentActions

func (db *DB) GetRecentActions(sessionID string, limit int) ([]models.ActionLog, error)

GetRecentActions returns recent actions for a session

func (*DB) GetRecentActionsAll

func (db *DB) GetRecentActionsAll(limit int) ([]models.ActionLog, error)

GetRecentActionsAll returns recent action_log entries across all sessions

func (*DB) GetRecentCommentsAll

func (db *DB) GetRecentCommentsAll(limit int) ([]models.Comment, error)

GetRecentCommentsAll returns recent comments across all issues

func (*DB) GetRecentConflicts added in v0.30.0

func (db *DB) GetRecentConflicts(limit int, since *time.Time) ([]SyncConflict, error)

GetRecentConflicts returns recent sync conflicts, ordered by most recent first. If since is non-nil, only conflicts after that time are returned.

func (*DB) GetRecentHandoffs

func (db *DB) GetRecentHandoffs(limit int, since time.Time) ([]models.Handoff, error)

GetRecentHandoffs retrieves recent handoffs across all issues

func (*DB) GetRecentLogsAll

func (db *DB) GetRecentLogsAll(limit int) ([]models.Log, error)

GetRecentLogsAll returns recent logs across all issues

func (*DB) GetRejectedInProgressIssueIDs added in v0.8.0

func (db *DB) GetRejectedInProgressIssueIDs() (map[string]bool, error)

GetRejectedInProgressIssueIDs returns IDs of open or in_progress issues that have a recent ActionReject without a subsequent ActionReview (needs rework). Rejected issues are reset to open; they may then be picked up (in_progress).

func (*DB) GetSchemaVersion

func (db *DB) GetSchemaVersion() (int, error)

GetSchemaVersion returns the current schema version from the database

func (*DB) GetSessionByID added in v0.27.0

func (db *DB) GetSessionByID(id string) (*SessionRow, error)

GetSessionByID looks up a session by ID. Returns nil, nil if not found.

func (*DB) GetSessionByIdentity added in v0.51.0

func (db *DB) GetSessionByIdentity(branch, agentType string, agentPID int, contextID, worktreeID string) (*SessionRow, error)

GetSessionByIdentity looks up a session by its full identity key: branch + agent type + agent PID + match context ID + worktree ID.

The match context ID (sourced from TD_CONTEXT_ID) lets distinct sub-agent contexts that share one process/branch/checkout map to distinct sessions. When contextID is empty (the normal interactive case), this matches rows whose match_context_id is empty, preserving the historical behavior where the key was just branch + agent_type + agent_pid.

If worktreeID is set and no exact row exists, this does one legacy fallback lookup for rows with an empty worktree_id. That keeps pre-v34 session rows usable for one release while new rows are keyed by worktree.

Returns nil, nil if not found.

func (*DB) GetSessionHistory added in v0.4.26

func (db *DB) GetSessionHistory(issueID string) ([]models.IssueSessionHistory, error)

GetSessionHistory returns all session interactions for an issue

func (*DB) GetSkippedEvents added in v0.60.0

func (db *DB) GetSkippedEvents(limit int) ([]SkippedSyncEvent, error)

GetSkippedEvents returns the most recently skipped events, newest first.

func (*DB) GetStartSnapshot

func (db *DB) GetStartSnapshot(issueID string) (*models.GitSnapshot, error)

GetStartSnapshot returns the start snapshot for an issue

func (*DB) GetStats

func (db *DB) GetStats() (map[string]int, error)

GetStats returns database statistics

func (*DB) GetSyncHistory added in v0.30.0

func (db *DB) GetSyncHistory(afterID int64, limit int) ([]SyncHistoryEntry, error)

GetSyncHistory returns entries with id > afterID, ordered by id ASC, limited to limit. Used for follow-mode polling.

func (*DB) GetSyncHistoryTail added in v0.30.0

func (db *DB) GetSyncHistoryTail(limit int) ([]SyncHistoryEntry, error)

GetSyncHistoryTail returns the last N entries in chronological order (oldest first).

func (*DB) GetSyncState added in v0.30.0

func (db *DB) GetSyncState() (*SyncState, error)

GetSyncState returns the current sync state, or nil if the project is not linked.

func (*DB) GetWorkSession

func (db *DB) GetWorkSession(id string) (*models.WorkSession, error)

GetWorkSession retrieves a work session

func (*DB) GetWorkSessionIssues

func (db *DB) GetWorkSessionIssues(wsID string) ([]string, error)

GetWorkSessionIssues returns issues tagged to a work session

func (*DB) HasChildren added in v0.4.16

func (db *DB) HasChildren(issueID string) (bool, error)

HasChildren returns true if the issue has any child issues

func (*DB) HasImplementationHistory added in v0.44.0

func (db *DB) HasImplementationHistory(issueID string) (bool, error)

HasImplementationHistory checks whether any session ever entered implementation flow for an issue. This is used to keep creator-only close bypasses limited to never-started throwaway issues.

func (*DB) ImportItemRaw added in v0.43.0

func (db *DB) ImportItemRaw(issue *models.Issue, logs []models.Log, handoffs []models.Handoff, deps []models.IssueDependency, files []models.IssueFile, replace bool) error

ImportItemRaw atomically imports an issue with all associated data in a single transaction. When replace is true, existing associated data is deleted first. No action_log entries are created.

Review invalidation: when the incoming issue differs from the existing row in a review-invalidating way, or when the import brings new deps/files/tags onto an existing issue (replace=false with any non-empty slice) or wipes them (replace=true), the active approval is superseded post-commit. This covers the LinkedFilesChanged/DependenciesChanged invariants for the sync import path. The base-issue field diff is still handled by supersedeIfReviewInvalidating below.

func (*DB) InsertHandoffRaw added in v0.43.0

func (db *DB) InsertHandoffRaw(handoff *models.Handoff) error

InsertHandoffRaw inserts a handoff without generating an ID or writing to action_log. Skips duplicates via INSERT OR IGNORE.

func (*DB) InsertIssueFileRaw added in v0.43.0

func (db *DB) InsertIssueFileRaw(file *models.IssueFile) error

InsertIssueFileRaw inserts a linked file without writing to action_log. Preserves the original linked_at timestamp. Skips duplicates via INSERT OR IGNORE.

func (*DB) InsertLogRaw added in v0.43.0

func (db *DB) InsertLogRaw(log *models.Log) error

InsertLogRaw inserts a log entry without generating an ID or writing to action_log. Skips duplicates via INSERT OR IGNORE.

func (*DB) LatestIssueActivity added in v0.55.0

func (db *DB) LatestIssueActivity(issueIDs []string) (map[string]time.Time, error)

LatestIssueActivity returns, per issue id, the most recent timestamp of any recorded work on that issue: its own updated_at, its newest progress log, and its newest action_log entry — by ANY session.

Claim liveness cannot be read off the holder session row alone. Session identity is keyed by branch + agent fingerprint + context + worktree, so an agent that changes branch or worktree mid-task mints a NEW session row and stops heartbeating the row named in implementer_session. The old row then looks dead while the agent is alive and working — and the evidence that it is alive is exactly the writes it keeps making against the issue.

Missing ids are simply absent from the map. Timestamps that cannot be parsed are skipped rather than treated as the zero time, which would read as "ancient" and push a claim toward release.

func (*DB) LinkFile

func (db *DB) LinkFile(issueID, filePath string, role models.FileRole, sha string) error

LinkFile links a file to an issue WITHOUT logging to action_log. For local mutations, use LinkFileLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) LinkFileLogged added in v0.30.0

func (db *DB) LinkFileLogged(issueID, filePath string, role models.FileRole, sha, sessionID string) error

LinkFileLogged links a file and logs the action atomically within a single withWriteLock call.

func (*DB) ListAllSessions added in v0.27.0

func (db *DB) ListAllSessions() ([]SessionRow, error)

ListAllSessions returns all sessions ordered by last_activity descending

func (*DB) ListBoards added in v0.10.0

func (db *DB) ListBoards() ([]models.Board, error)

ListBoards returns all boards sorted by last_viewed_at DESC

func (*DB) ListDistinctLabels added in v0.45.0

func (db *DB) ListDistinctLabels() ([]string, error)

ListDistinctLabels returns the sorted set of labels found on non-deleted issues in the current database.

func (*DB) ListIssueReviews added in v0.45.0

func (db *DB) ListIssueReviews(issueID string) ([]*models.IssueReview, error)

ListIssueReviews returns all reviews for an issue in chronological order (oldest first). Superseded and active reviews are both returned so the caller can render full history.

func (*DB) ListIssues

func (db *DB) ListIssues(opts ListIssuesOptions) ([]models.Issue, error)

ListIssues returns issues matching the filter

func (*DB) ListNotes added in v0.33.0

func (db *DB) ListNotes(opts ListNotesOptions) ([]models.Note, error)

ListNotes returns notes matching the filter options.

func (*DB) ListWorkSessions

func (db *DB) ListWorkSessions(limit int) ([]models.WorkSession, error)

ListWorkSessions returns recent work sessions

func (*DB) LogAction

func (db *DB) LogAction(action *models.ActionLog) error

LogAction records an action for undo support

func (*DB) MarkActionUndone

func (db *DB) MarkActionUndone(actionID string) error

MarkActionUndone marks an action as undone

func (*DB) MigrateFileSystemSessions added in v0.27.0

func (db *DB) MigrateFileSystemSessions(baseDir string) error

MigrateFileSystemSessions migrates sessions from filesystem to DB. Safe to call multiple times—no-op if filesystem sessions don't exist. Uses INSERT OR IGNORE so concurrent calls are safe.

func (*DB) PinNote added in v0.33.0

func (db *DB) PinNote(id string) error

PinNote sets a note's pinned status to true.

func (*DB) QuickCheck added in v0.52.0

func (db *DB) QuickCheck() error

QuickCheck verifies SQLite's b-tree and index invariants without mutating the database. It is cheap enough to run before sync, where continuing after corruption could otherwise upload garbage produced by orphan backfill.

func (*DB) RecordSessionAction added in v0.4.26

func (db *DB) RecordSessionAction(issueID, sessionID string, action models.IssueSessionAction) error

RecordSessionAction logs a session's interaction with an issue

func (*DB) ReleaseClaims added in v0.55.0

func (db *DB) ReleaseClaims(reqs []ClaimRelease, sessionID string) ([]ClaimReleaseOutcome, error)

ReleaseClaims releases a batch of implementer claims in ONE write-lock acquisition and ONE transaction.

Two properties matter and neither is available by looping over UpdateIssueLogged:

  1. Atomic-per-issue guarding. Each issue is re-read inside the lock and the UPDATE carries a WHERE clause on the status and holder that were just read. A row whose claim moved under us reports Skipped, never Released. Nothing is written from the caller's pre-lock snapshot, so a concurrent `td update --title` on the same issue is not reverted.

  2. One lock acquisition for the whole batch. The per-issue path takes and releases the cross-process write lock about four times per issue (session action, issue update, log, focus). Under a large sweep that starves live agents: the lock timeout is 500ms and a real `td start` fails outright when it loses that race. A harness tick whose `td start` fails is a dead tick.

func (*DB) RemoveDependency

func (db *DB) RemoveDependency(issueID, dependsOnID string) error

RemoveDependency removes a dependency WITHOUT logging to action_log. For local mutations, use RemoveDependencyLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) RemoveDependencyLogged added in v0.30.0

func (db *DB) RemoveDependencyLogged(issueID, dependsOnID, sessionID string) error

RemoveDependencyLogged removes a dependency and logs the action atomically within a single withWriteLock call. If the dependency does not exist locally, this is a no-op (no action_log entry is created).

func (*DB) RemoveIssuePosition added in v0.10.0

func (db *DB) RemoveIssuePosition(boardID, issueID string) error

RemoveIssuePosition soft-deletes an explicit position for an issue by setting deleted_at. WARNING: This does NOT log to action_log. For local mutations, use RemoveIssuePositionLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) RemoveIssuePositionLogged added in v0.30.0

func (db *DB) RemoveIssuePositionLogged(boardID, issueID, sessionID string) error

RemoveIssuePositionLogged soft-deletes an issue's board position and logs the action atomically.

func (*DB) ReplaceIssueRaw added in v0.43.0

func (db *DB) ReplaceIssueRaw(issue *models.Issue) error

ReplaceIssueRaw deletes all associated data for an issue and then upserts the issue itself atomically. Equivalent to ImportItemRaw with no associated data.

func (*DB) ResolveBoardRef added in v0.10.0

func (db *DB) ResolveBoardRef(ref string) (*models.Board, error)

ResolveBoardRef resolves a board reference (ID or name)

func (*DB) RespaceBoardPositions added in v0.30.0

func (db *DB) RespaceBoardPositions(boardID string) ([]RespaceResult, error)

RespaceBoardPositions reassigns all positions on a board with fresh PositionGap gaps.

func (*DB) RestoreBoard added in v0.30.0

func (db *DB) RestoreBoard(board *models.Board) error

RestoreBoard re-inserts a previously deleted board from its stored state. This is used by undo to restore a deleted board.

func (*DB) RestoreIssue

func (db *DB) RestoreIssue(id string) error

RestoreIssue restores a soft-deleted issue

func (*DB) RestoreIssueLogged added in v0.30.0

func (db *DB) RestoreIssueLogged(issueID, sessionID string) error

RestoreIssueLogged restores a soft-deleted issue and logs the action atomically.

func (*DB) RestoreNote added in v0.58.0

func (db *DB) RestoreNote(id string) (*models.Note, error)

RestoreNote clears deleted_at on a soft-deleted note and logs the action.

func (*DB) RunMigrations

func (db *DB) RunMigrations() (int, error)

RunMigrations runs any pending database migrations

func (*DB) SearchIssues

func (db *DB) SearchIssues(query string, opts ListIssuesOptions) ([]models.Issue, error)

SearchIssues performs full-text search across issues

func (*DB) SearchIssuesRanked added in v0.4.9

func (db *DB) SearchIssuesRanked(query string, opts ListIssuesOptions) ([]SearchResult, error)

SearchIssuesRanked performs search with relevance scoring. Scope is the issue's own text plus the work logged against it: logs and handoff content. Matches found only in that activity rank below matches in the issue's title or description.

func (*DB) SessionsHoldingClaims added in v0.55.0

func (db *DB) SessionsHoldingClaims() (map[string]int, error)

SessionsHoldingClaims returns, per session id, how many issues name that session as implementer. `td session cleanup` uses it to avoid deleting the very rows that make a leaked claim reclaimable.

The selection is the same set ReleaseClaims calls releasable: in_progress, plus open-while-still-naming-a-holder. That second case is the leak this exists to protect — older builds of `td reopen` and `td unblock` left the implementer set on an open issue, and counting only in_progress meant cleanup deleted that holder's session row while the claim was still on the issue, leaving nothing any surface could reclaim.

Deliberately NOT widened past that. A closed issue keeps its implementer as the record of who did the work, and protecting those holders forever would mean cleanup could never delete a session that ever finished anything. A blocked issue keeps its holder on purpose and is reachable through `td list --status blocked`, so it is not invisible the way open+held is.

func (*DB) SetActiveWorkSession added in v0.51.0

func (db *DB) SetActiveWorkSession(scope SessionStateScope, wsID string) error

SetActiveWorkSession stores the active work session for the scope in the local DB.

func (*DB) SetFocus added in v0.51.0

func (db *DB) SetFocus(scope SessionStateScope, issueID string) error

SetFocus stores the focused issue for the scope in the local DB.

func (*DB) SetIssuePosition added in v0.10.0

func (db *DB) SetIssuePosition(boardID, issueID string, position int) error

SetIssuePosition sets an explicit sort-key position for an issue on a board. This directly sets the position value without shifting other rows. WARNING: This does NOT log to action_log. For local mutations, use SetIssuePositionLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) SetIssuePositionLogged added in v0.30.0

func (db *DB) SetIssuePositionLogged(boardID, issueID string, position int, sessionID string) error

SetIssuePositionLogged sets an issue's board position and logs the action atomically.

func (*DB) SetMaxOpenConns added in v0.19.0

func (db *DB) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database. For SQLite with single-writer semantics, this should typically be set to 1 to prevent connection pool growth in long-running applications.

func (*DB) SetSchemaVersion

func (db *DB) SetSchemaVersion(version int) error

SetSchemaVersion sets the schema version in the database

func (*DB) SetSyncState added in v0.30.0

func (db *DB) SetSyncState(projectID string) error

SetSyncState creates or replaces the sync state for a project (used for link).

func (*DB) SupersedeActiveReviews added in v0.45.0

func (db *DB) SupersedeActiveReviews(issueID string) error

SupersedeActiveReviews marks all non-superseded reviews for an issue as superseded with a NOW() timestamp. Idempotent: a second call is a no-op because no active rows remain.

func (*DB) SupersedeActiveReviewsLogged added in v0.54.0

func (db *DB) SupersedeActiveReviewsLogged(issueID, sessionID string) error

SupersedeActiveReviewsLogged supersedes active rows and emits one update event per row so superseded_at converges across peers.

func (*DB) SwapIssuePositions added in v0.10.0

func (db *DB) SwapIssuePositions(boardID, id1, id2 string) error

SwapIssuePositions swaps the positions of two issues on a board

func (*DB) TagIssueToWorkSession

func (db *DB) TagIssueToWorkSession(wsID, issueID, sessionID string) error

TagIssueToWorkSession links an issue to a work session

func (*DB) UnarchiveNote added in v0.33.0

func (db *DB) UnarchiveNote(id string) error

UnarchiveNote sets a note's archived status to false.

func (*DB) UndoIssueReviewEffectsLogged added in v0.54.0

func (db *DB) UndoIssueReviewEffectsLogged(createdReviewID, priorActiveReviewID, sessionID string) error

UndoIssueReviewEffectsLogged atomically rolls back all issue_reviews side-effects carried by a ReviewUndoPayload. If any sync-event insertion fails, neither the delete nor the reactivation is committed, so td undo can safely return an error and remain retryable.

func (*DB) UndoReviewAwareIssueActionLogged added in v0.54.0

func (db *DB) UndoReviewAwareIssueActionLogged(
	originalActionID string, restoredIssue *models.Issue,
	createdReviewID, priorActiveReviewID, sessionID string,
) error

UndoReviewAwareIssueActionLogged rolls back the review effects, restores the issue, emits the restoration event, and marks the original action undone in one transaction. A failure at any event boundary leaves the action retryable.

func (*DB) UnlinkFile

func (db *DB) UnlinkFile(issueID, filePath string) error

UnlinkFile removes a file link WITHOUT logging to action_log. For local mutations, use UnlinkFileLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) UnlinkFileLogged added in v0.30.0

func (db *DB) UnlinkFileLogged(issueID, filePath, sessionID string) error

UnlinkFileLogged removes a file link and logs the action atomically within a single withWriteLock call.

func (*DB) UnpinNote added in v0.33.0

func (db *DB) UnpinNote(id string) error

UnpinNote sets a note's pinned status to false.

func (*DB) UntagIssueFromWorkSession

func (db *DB) UntagIssueFromWorkSession(wsID, issueID, sessionID string) error

UntagIssueFromWorkSession removes an issue from a work session

func (*DB) UpdateBoard added in v0.10.0

func (db *DB) UpdateBoard(board *models.Board) error

UpdateBoard updates a board's name and/or query WITHOUT logging to action_log. For local mutations, use UpdateBoardLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) UpdateBoardLastViewed added in v0.10.0

func (db *DB) UpdateBoardLastViewed(boardID string) error

UpdateBoardLastViewed updates the last_viewed_at timestamp for a board

func (*DB) UpdateBoardLogged added in v0.30.0

func (db *DB) UpdateBoardLogged(board *models.Board, sessionID string) error

UpdateBoardLogged updates a board and logs the action atomically within a single withWriteLock call.

func (*DB) UpdateBoardViewMode added in v0.10.0

func (db *DB) UpdateBoardViewMode(boardID, viewMode string) error

UpdateBoardViewMode updates the view_mode for a board (swimlanes or backlog)

func (*DB) UpdateIssue

func (db *DB) UpdateIssue(issue *models.Issue) error

UpdateIssue updates an issue WITHOUT logging to action_log. For local mutations, use UpdateIssueLogged instead. This unlogged variant exists for sync receiver applying remote events.

func (*DB) UpdateIssueLogged added in v0.30.0

func (db *DB) UpdateIssueLogged(issue *models.Issue, sessionID string, actionType models.ActionType) error

UpdateIssueLogged updates an issue and logs the action atomically within a single withWriteLock call. It reads the current DB state for PreviousData before applying the update.

Guards against the caller's issue snapshot going stale: if issue.UpdatedAt (set when the caller loaded it, e.g. via GetIssue) no longer matches the persisted updated_at, some other write landed in between and this write is rejected rather than silently reverting it. Callers that intentionally restore an old snapshot regardless of intervening writes (undo) must use UpdateIssueLoggedUnconditional instead.

func (*DB) UpdateIssueLoggedIfStatus added in v0.44.0

func (db *DB) UpdateIssueLoggedIfStatus(issue *models.Issue, expectedStatus models.Status, sessionID string, actionType models.ActionType) error

UpdateIssueLoggedIfStatus updates an issue and logs the action atomically, but only if the current persisted status still matches expectedStatus.

func (*DB) UpdateIssueLoggedUnconditional added in v0.55.0

func (db *DB) UpdateIssueLoggedUnconditional(issue *models.Issue, sessionID string, actionType models.ActionType) error

UpdateIssueLoggedUnconditional updates an issue and logs the action atomically, without the staleness guard UpdateIssueLogged applies. It exists for undo, which intentionally restores an older snapshot over whatever is currently persisted; guarding that write against the very change it means to revert would make undo unusable.

func (*DB) UpdateIssueLoggedWithReviewMeta added in v0.45.0

func (db *DB) UpdateIssueLoggedWithReviewMeta(
	issue *models.Issue, expectedStatus models.Status, sessionID string,
	actionType models.ActionType,
	createdReviewID, priorActiveReviewID string,
) error

UpdateIssueLoggedWithReviewMeta performs the same atomic issue update + log as UpdateIssueLoggedIfStatus but records review-undo metadata in the action_log NewData column so cmd/undo.go can roll back issue_reviews side-effects. Used by the delegated-review flow (Step 2) for:

  • ActionApprove (direct reviewer close: inserted one review row)
  • ActionReviewApprove / ActionReviewChangesRequested (record-only)
  • ActionCloseAfterReview (no review row inserted, but may want audit of prior reviewer/closed-by fields; the Issue JSON in PreviousData already carries those)

createdReviewID and priorActiveReviewID are optional; empty strings are acceptable and produce a bare-Issue NewData (backward compatible).

func (*DB) UpdateNote added in v0.33.0

func (db *DB) UpdateNote(id, title, content string) (*models.Note, error)

UpdateNote updates a note's title and content, and logs the action for undo support.

func (*DB) UpdateSessionActivity added in v0.27.0

func (db *DB) UpdateSessionActivity(id string, t time.Time) error

UpdateSessionActivity updates the last_activity timestamp for a session

func (*DB) UpdateSessionName added in v0.27.0

func (db *DB) UpdateSessionName(id, name string) error

UpdateSessionName updates the name of a session

func (*DB) UpdateSessionWorktreeMetadata added in v0.51.0

func (db *DB) UpdateSessionWorktreeMetadata(id, worktreeID, worktreeRoot, repoRoot string) error

UpdateSessionWorktreeMetadata backfills worktree metadata on legacy session rows that were created before worktree identity participated in the key.

func (*DB) UpdateSyncPulled added in v0.30.0

func (db *DB) UpdateSyncPulled(lastServerSeq int64) error

UpdateSyncPulled updates the last pulled server sequence and sync time.

func (*DB) UpdateSyncPushed added in v0.30.0

func (db *DB) UpdateSyncPushed(lastActionID int64) error

UpdateSyncPushed updates the last pushed action ID and sync time.

func (*DB) UpdateWorkSession

func (db *DB) UpdateWorkSession(ws *models.WorkSession) error

UpdateWorkSession updates a work session

func (*DB) UpsertIssueRaw added in v0.42.1

func (db *DB) UpsertIssueRaw(issue *models.Issue) error

UpsertIssueRaw inserts or replaces an issue with all fields as-is. No ID generation, no status defaulting, no action_log entry.

Batch 1c: when the incoming issue differs from the existing row in a review-invalidating way (see internal/reviewpolicy.IsReviewInvalidatingMutation) the active approval review is superseded. This keeps sync-imported mutations from silently carrying a stale approval through a remote edit.

func (*DB) UpsertSession added in v0.27.0

func (db *DB) UpsertSession(sess *SessionRow) error

UpsertSession inserts or replaces a session in the database

func (*DB) WasSessionImplementationInvolved added in v0.40.0

func (db *DB) WasSessionImplementationInvolved(issueID, sessionID string) (bool, error)

WasSessionImplementationInvolved checks if a session ever touched implementation flow for an issue (start/unstart). This is used for balanced review policy: creator-only approvals are allowed only when creator never implemented.

func (*DB) WasSessionInvolved added in v0.4.26

func (db *DB) WasSessionInvolved(issueID, sessionID string) (bool, error)

WasSessionInvolved checks if a session ever interacted with an issue

type IssueTitleStatus added in v0.48.0

type IssueTitleStatus struct {
	Title  string
	Status models.Status
}

IssueTitleStatus is a compact (title, status) pair for an issue, used by batched lookups that only need these two fields.

type ListIssuesOptions

type ListIssuesOptions struct {
	Status               []models.Status
	Type                 []models.Type
	Priority             string
	Labels               []string
	IncludeDeleted       bool
	OnlyDeleted          bool
	Search               string
	Implementer          string
	Reviewer             string
	ReviewableBy         string // Issues that this session can review
	BalancedReviewPolicy bool   // Allow creator-only approvals/reviews when externally implemented
	// ReviewPolicyMode overrides the mode used by ReviewableBy/ReadyToCloseBy
	// filter composition. When empty, falls back to strict (or balanced when
	// BalancedReviewPolicy is true). Step 2 flips delegated-mode callers.
	ReviewPolicyMode string
	// ReadyToCloseBy returns issues where an active approval review exists
	// and the current mode allows close-after-review. In delegated mode any
	// session may close after independent approval; the session value is kept
	// for API symmetry but is not part of the SQL predicate.
	// Empty under strict/balanced; populated under delegated. Safe to set
	// regardless of mode; the SQL composer short-circuits to `0=1` when not
	// applicable.
	ReadyToCloseBy     string
	ParentID           string
	EpicID             string // Filter by epic (parent_id matches epic, recursively)
	PointsMin          int
	PointsMax          int
	CreatedAfter       time.Time
	CreatedBefore      time.Time
	UpdatedAfter       time.Time
	UpdatedBefore      time.Time
	ClosedAfter        time.Time
	ClosedBefore       time.Time
	SortBy             string
	SortDesc           bool
	Limit              int
	IDs                []string
	ExcludeDeferred    bool // Hide issues where defer_until > today
	DeferredOnly       bool // Show ONLY deferred issues (defer_until > today)
	OverdueOnly        bool // Show ONLY overdue issues (due_date < today, not closed)
	SurfacingOnly      bool // Show ONLY surfacing issues (defer_until <= today, defer_count > 0)
	DueSoonDays        int  // Show issues due within N days (0 = disabled)
	ExcludeHasOpenDeps bool // Hide issues that have unresolved (non-closed) dependencies
	// SearchActivity widens Search to also match log messages and handoff
	// content, not just id/title/description. Set by the `td search` path.
	SearchActivity bool
}

ListIssuesOptions contains filter options for listing issues

type ListNotesOptions added in v0.33.0

type ListNotesOptions struct {
	Pinned         *bool  // nil = don't filter, true = only pinned, false = only unpinned
	Archived       *bool  // nil = don't filter, true = only archived, false = only unarchived
	IncludeDeleted bool   // include soft-deleted notes
	Search         string // search title/content
	Limit          int    // max results; <=0 means unlimited
}

ListNotesOptions contains filter options for listing notes

type Migration

type Migration struct {
	Version     int
	Description string
	SQL         string
}

Migration defines a database migration

type NewReview added in v0.54.0

type NewReview struct {
	IssueID            string
	ReviewerSession    string // the session recording the row
	Decision           string // reviewpolicy.Decision* constant
	Summary            string
	RequestedBySession string

	// SelfReview marks the row as recorded by an implementation-involved
	// session. Callers must stamp this from the reviewpolicy decision, never
	// from raw user input, or a request could forge the flag in either
	// direction.
	SelfReview bool

	// ReviewedBy names who performed the review when that differs from
	// ReviewerSession. Empty means the recording session reviewed it itself.
	ReviewedBy string
}

NewReview describes a review row to append. It replaced a positional signature that had grown to six arguments and was about to take a seventh — at that width a caller transposing SelfReview and an attribution string would compile fine and write a false audit record.

type OpenOptions added in v0.44.0

type OpenOptions struct {
	// ReadOnly opens the database with mode=ro. When true, OpenSQLite still
	// applies busy_timeout but skips pragmas that require write access
	// (journal_mode=WAL, synchronous, foreign_keys).
	ReadOnly bool

	// MaxOpenConns caps the SQL connection pool size. 0 selects the default
	// of 1, which matches SQLite's single-writer semantics and prevents the
	// pool from opening extra connections that could corrupt WAL/SHM files
	// under concurrent multi-process access.
	MaxOpenConns int

	// BusyTimeout controls PRAGMA busy_timeout. 0 selects the default of 5s.
	BusyTimeout time.Duration

	// DisableForeignKeys, when true, skips `PRAGMA foreign_keys = ON`. This is
	// a temporary escape hatch for the CLI issues.db, which currently ships
	// with FK enforcement OFF. Flipping FK enforcement on for that DB is the
	// responsibility of td-4846e6 (which also adds the orphan-cleanup
	// migration); this flag keeps td-d4a67c scope-limited to pragma
	// centralization. Remove once td-4846e6 lands.
	DisableForeignKeys bool
}

OpenOptions configures a SQLite connection opened via OpenSQLite. Zero values select sensible defaults.

type OrphanCount added in v0.44.0

type OrphanCount struct {
	Relation     string // e.g. "handoffs.issue_id -> issues.id"
	ChildTable   string
	ChildColumn  string
	ParentTable  string
	ParentColumn string
	Count        int
}

OrphanCount reports the number of rows in a child table whose foreign-key column points at a non-existent row in the parent table.

Count = number of child rows where child.col NOT NULL / NOT ” AND no matching parent row exists. We treat empty-string and NULL as "no link" to match td's mixed-sentinel convention (many FK columns default to ”).

func AuditForeignKeys added in v0.44.0

func AuditForeignKeys(conn *sql.DB) ([]OrphanCount, error)

AuditForeignKeys performs a read-only audit: for every FK relation declared in schema.go it runs a SELECT COUNT(*) that finds child rows whose column value is non-empty but has no matching parent row. It never mutates data.

Tables that do not exist (e.g. on older DBs missing a migration) are skipped silently — their entry is omitted from the returned slice.

This function is independent of CLI ID semantics: it works on any td-shaped SQLite DB and takes a raw *sql.DB so callers can point it at either the CLI DB or a test DB.

type RespaceResult added in v0.30.0

type RespaceResult struct {
	IssueID     string
	OldPosition int
	NewPosition int
}

RespaceResult records a position change made during a respace operation.

type SearchResult added in v0.4.9

type SearchResult struct {
	Issue      models.Issue
	Score      int    // Higher = better match (0-100)
	MatchField string // Primary field that matched: 'id', 'title', 'description', 'labels'
}

SearchResult holds an issue with relevance scoring for ranked search

type SecurityEvent added in v0.5.0

type SecurityEvent struct {
	Timestamp time.Time `json:"ts"`
	IssueID   string    `json:"issue_id"`
	SessionID string    `json:"session_id"`
	AgentType string    `json:"agent_type,omitempty"`
	Reason    string    `json:"reason"`
}

SecurityEvent represents a security-relevant workflow exception (for example, self-close or creator-approval exceptions).

func ReadSecurityEvents added in v0.5.0

func ReadSecurityEvents(baseDir string) ([]SecurityEvent, error)

ReadSecurityEvents reads all security events from the file

type SessionRow added in v0.27.0

type SessionRow struct {
	ID                string
	Name              string
	Branch            string
	AgentType         string
	AgentPID          int
	ContextID         string // audit-only execution-context fingerprint
	MatchContextID    string // participates in the session identity key (TD_CONTEXT_ID)
	WorktreeID        string
	WorktreeRoot      string
	RepoRoot          string
	PreviousSessionID string
	StartedAt         time.Time
	LastActivity      time.Time
}

SessionRow represents a session record in the database

type SessionStateScope added in v0.51.0

type SessionStateScope struct {
	SessionID  string
	WorktreeID string

	// Legacy fallback hooks are read-only compatibility shims for the release
	// that moves current state out of config.json. They are optional so db does
	// not import internal/config.
	ConfigBaseDir              string
	LegacyGetFocus             func(baseDir string) (string, error)
	LegacyGetActiveWorkSession func(baseDir string) (string, error)
}

SessionStateScope identifies one local session/worktree state row. WorktreeID may be empty for legacy callers and non-git contexts.

type SkippedSyncEvent added in v0.60.0

type SkippedSyncEvent struct {
	ServerSeq  int64
	DeviceID   string
	ActionType string
	EntityType string
	EntityID   string
	Reason     string
	Error      string
	Payload    string
	SkippedAt  time.Time
}

SkippedSyncEvent is a row from sync_skipped_events: a remote event this peer did not apply, kept so it is auditable rather than silently discarded.

type StaleIssueStatusError added in v0.44.0

type StaleIssueStatusError struct {
	IssueID  string
	Expected models.Status
	Actual   models.Status
}

StaleIssueStatusError indicates the issue status changed after the caller loaded the issue but before the logged transition was persisted.

func (*StaleIssueStatusError) Error added in v0.44.0

func (e *StaleIssueStatusError) Error() string

type StaleIssueUpdateError added in v0.55.0

type StaleIssueUpdateError struct {
	IssueID string
	Loaded  time.Time
	Current time.Time
}

StaleIssueUpdateError indicates some other write persisted between the caller loading the issue and this write applying. Rejecting the write avoids silently reverting whatever the intervening write changed.

It is a conflict, not a fault: nothing was written, the intervening change is intact, and the caller's move is to re-read the issue and re-apply. API callers should map it to 409, never 500 (see serve.WriteIssueWriteError).

The guard keys off the caller's loaded UpdatedAt, so a caller that never loaded the row — one that builds an Issue from scratch, e.g. `td system import --force` — carries a zero UpdatedAt and is deliberately exempt. TestUpdateIssueLoggedAllowsUnloadedSnapshot pins that exemption; removing it would break import, so change it on purpose or not at all.

func (*StaleIssueUpdateError) Error added in v0.55.0

func (e *StaleIssueUpdateError) Error() string

type SyncConflict added in v0.30.0

type SyncConflict struct {
	ID            int64
	EntityType    string
	EntityID      string
	ServerSeq     int64
	LocalData     string
	RemoteData    string
	OverwrittenAt time.Time
}

SyncConflict represents a row from the sync_conflicts table.

type SyncHistoryEntry added in v0.30.0

type SyncHistoryEntry struct {
	ID         int64
	Direction  string // "push" or "pull"
	ActionType string // "create", "update", "delete"
	EntityType string // "issues", "logs", etc.
	EntityID   string
	ServerSeq  int64
	DeviceID   string
	Timestamp  time.Time
}

SyncHistoryEntry represents a row from the sync_history table.

type SyncState added in v0.30.0

type SyncState struct {
	ProjectID           string
	LastPushedActionID  int64
	LastPulledServerSeq int64
	LastSyncAt          *time.Time
	SyncDisabled        bool
}

SyncState holds the sync configuration for a linked project.

Jump to

Keyboard shortcuts

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