store

package
v0.24.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 30 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 store owns the SQLite mirror: schema, migrations, transactions, full-text index and the derived fields the source does not provide.

0.x promises three things, documented in specs/000-product/data-model.md: the issues_full view plus the RECIPES queries, gadak sql stdout, and views open --keys - semantics. Everything else in the schema is documented so you can read it, not promised so you can build on it.

Index

Constants

View Source
const (
	FeedWindowDays   = 30
	FeedDefaultLimit = 80
	FeedMaxLimit     = 200
)

Feed window and default page size match the client contract (web/src/lib/api.ts getFeed / FeedFocus).

View Source
const (
	VisitKindIssue = "issue"
	VisitKindPage  = "page"
)

VisitKind is visits.kind / searches.opened_kind: "issue" or "page".

View Source
const (
	VisitSourceCLI = "cli"
	VisitSourceUI  = "ui"
	VisitSourceMCP = "mcp"
)

Visit sources: the surface that caused the read. Decided by the recorder (the CLI knows it is the CLI; the server knows the request is its UI), so a client can never claim one — the POST body does not carry source.

View Source
const ArtifactDSNParam = "gadak_artifact"

ArtifactDSNParam is the DSN query parameter that marks an open as a standalone artifact — a database this process is building to hand to someone else, not a workspace mirror. Append `&gadak_artifact=1` to a raw driver DSN (OpenArtifact sets it for store-level opens); attachLocalHook reads it and gives the connection a private in-memory `local` instead of adopting whatever local.db sits beside the file (GDK-1934). Both the modernc driver and SQLite core ignore query parameters they do not know, so the flag rides the DSN with no side effects elsewhere.

View Source
const CategoryDone = "done"

CategoryDone is the only status category with meaning to the derived rules. Every rule keys on the category, never on a status name: the internal tool this was extracted from matched "Reopened" / "다시 열림" and broke on any other site or account language (contracts/sync.md, "Localization hazard").

View Source
const CategoryInProgress = "inprogress"

CategoryInProgress pairs with CategoryDone for the lifecycle spans. Like every rule here it keys on the category, never a status name.

View Source
const CycleP85MinSamples = 11

CycleP85MinSamples is the fewest finished issues before a p85 cycle time is a distribution rather than a coincidence. The server omits the flow block below it (read.go flowFields), and the client ignores a carried flow below it, so a mocked or hand-written payload cannot lower the bar either.

Eleven, not ten (2026-09-06, second literature round): nearest-rank p85 returns the maximum observation at n ≤ 6 and the second-largest at n ≤ 13, so a thin sample quotes an outlier as a percentile. The flow canon's own landmarks are five points for a credible median, eleven before the range says anything, and about twenty for useful limits (ProKanban, "How much data do I need to start forecasting?"); eleven is the first of those that this number can honestly stand on.

View Source
const DominantSharePct = 70

DominantSharePct is the doctor-warning threshold of GDK-1413: a single priority value holding this share of the open issues. Attribution: the number is the issue's own ("한 값이 70% 이상이면"), pinned 2026-09-10, round w11-server — not derived from a measurement, so moving it is a product decision to argue, not a tuning round. The comparison that uses it is exact integer math (100*count >= 70*open) so a boundary case never rides a float rounding.

View Source
const SessionGap = 30 * time.Minute

SessionGap is the read gap that splits person reads into sessions: a counted visit more than this after the previous one starts a new session; exactly the gap is still the same session (strictly greater splits). This is the single owner of the 30-minute boundary (GDK-1439) — local.sessions rows are chained at exactly this value, retro re-exports it as retro.SessionGap, and both LastSessionEnd callers pass it. retro's --session-gap may still re-bin visits for its own report; that walk deliberately does not read this table (a custom gap re-bins, and the report needs per-session issue keys the table does not carry).

Variables

View Source
var ErrInvalidCursor = errors.New("invalid cursor")

ErrInvalidCursor means a pagination cursor did not parse. The server's history handler maps it to HTTP 400 by identity — errors.Is against this value, not message text (GDK-609) — so cursor parsing must return this sentinel and never a fresh errors.New with a similar sentence.

View Source
var ErrKeyAmbiguous = errors.New("this key is mirrored from more than one source — scope one side out (projects / linear.teamIds) before writing to it")

ErrKeyAmbiguous means one key exists under more than one source (a Jira project ENG and a Linear team key ENG both mint ENG-1). A write routed by that key could land on the wrong tracker while the UI shows the other row (GDK-400), so callers refuse instead of picking one.

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

ErrNotFound means a single-row lookup (Detail, etc.) found no matching key. Callers map it to 404 / "not in the mirror"; store code still uses sql.ErrNoRows internally and wraps at the package boundary.

View Source
var ErrSprintNotFound = errors.New("store: no such sprint in the mirror")

ErrSprintNotFound is what SprintBurnup answers for an id the mirror's sprints table does not hold. The server maps it to 404 and the CLI prints it beside the pointer to `gadak sprint list`, which has the ids.

Functions

func ActorPeople added in v0.21.0

func ActorPeople(people []ActorPerson) []jql.Person

ActorPeople turns the narrow actor projection (QueryActorPeople) into the roster jql.ResolveIdentity matches assignee/reporter tokens against. Single owner since GDK-1574; a surface that needs the roster calls this, it does not re-copy the six-field loop.

func AliasIssueKey added in v0.17.0

func AliasIssueKey(m map[string]any)

AliasIssueKey copies m["issue_key"] onto m["key"] so map-built JSON cannot emit one name without the other (GDK-255).

func BackfillBlockedTx added in v0.22.0

func BackfillBlockedTx(tx *sql.Tx) error

BackfillBlockedTx is blockedSpec on a caller's transaction — the snapshot pipeline's seat beside BackfillCarryoverTx: the column-bag mover does not know the derived columns, so the fixture recomputes them from its own rows through the single owner of the rule. Absence is an answer here: those rows reached the fixture through this build's sync, which writes the flagged changelog under the stable name.

func BackfillCarryoverTx added in v0.22.0

func BackfillCarryoverTx(tx *sql.Tx) error

BackfillCarryoverTx is backfillCarryover on a caller's transaction. The snapshot pipeline builds its own fixture and never goes through the sync write path, so it derives the sprint history itself and then asks this package — the single owner of the rule — for the columns. Exported for that one caller, the same reason BackfillFlow is.

func DevCopyHint added in v0.23.0

func DevCopyHint(rootDir string) string

DevCopyHint is the "work on a copy" recipe for a versioned file a dev build refused to migrate forward, derived from the workspace directory that owns it so it stays true without naming files that may not exist: a named profile is self-contained under profiles/<name> (its config.json travels with the directory), and the root profile's directory is itself a whole GADAK_HOME. rootDir is the directory to copy — the mirror's own, or the persist's workspace (its origin/ parent). The copy is still behind, so the recipe carries the same override once — after it, the copy is at head and opens without it. Shared by the mirror and persist refusals (GDK-1967) so the prose has one owner.

func EnsureLocal added in v0.13.0

func EnsureLocal(mirrorPath string) error

EnsureLocal creates local.db next to the mirror if needed and migrates it. Failures are returned; callers of Open log them and still open the mirror.

func EnsureLocalWith added in v0.22.0

func EnsureLocalWith(mirrorPath string, opts OpenOptions) error

EnsureLocalWith is EnsureLocal under an explicit open policy.

func FTSCJKBigramColumn added in v0.17.0

func FTSCJKBigramColumn(title, labels, body, comments string) string

FTSCJKBigramColumn is the items_fts.cjk_bigram value for one row: the CJK bigrams of the title, label, body and comment text, space-joined. Labels joined the source set in GDK-1021 — a Korean label like 간편결제 must mid-compound-match 결제 exactly like a title token would, and the plain labels column alone only gives whole-token matching. Exported because internal/snapshot writes rows through the same shape — any writer that fills only the scored columns leaves CJK mid-match silently empty rather than broken, which is this design's named trap (0009 §Consequences).

func FTSLabelsText added in v0.22.0

func FTSLabelsText(labelsJSON string) string

FTSLabelsText is the items_fts.labels value for one row: the stored JSON label array (issues_raw.labels / pages.labels, both "[]" when absent) as space-joined text. The single owner of the column's text form — writeFTS callers, the rebuild, the snapshot pipeline and scripts/scrub-demo-db.py's portable twin must all emit this shape, or a label-only issue silently drops out of search again (GDK-1021).

func FTSScriptRunsColumn added in v0.24.0

func FTSScriptRunsColumn(title, labels, body, comments string) string

FTSScriptRunsColumn is the items_fts.script_runs value for one row: the CJK-adjacent Latin/digit runs of the title, label, body and comment text, space-joined in scan order, so the phrase query ["nmb","110"*] matches the rescued `NMB 110` of 追跡issueはNMB-110で the same way it matches Korean's space-spelled NMB-110이며. The sixth and last items_fts column (GDK-1978); exported for the same writers as FTSCJKBigramColumn — a writer that omits it leaves the axis silently empty, the contentless trap of 0009 §Consequences a third time.

func FormatDuration added in v0.17.0

func FormatDuration(d time.Duration) string

FormatDuration renders a span with its single largest unit — the scale the durations line reads at. Sub-minute spans keep seconds.

func HumanBytes added in v0.22.0

func HumanBytes(n int64) string

HumanBytes renders a byte count at its largest 1024-based unit — the single owner of that string for every surface (GDK-927). Two implementations used to coexist: this one, and a CLI copy that stopped at MB and printed "1024.0 MB" for a gigabyte and a negative count verbatim. Callers pass raw sizes from the filesystem, so negatives clamp to zero rather than leak a "-1 B" into the UI.

func IsBusy added in v0.17.1

func IsBusy(err error) bool

IsBusy reports whether err is SQLITE_BUSY (5) or SQLITE_BUSY_SNAPSHOT (517). Match on the driver's Code(), never on prose (store.go sqliteBusy).

func IsSelfActor added in v0.21.0

func IsSelfActor(me FeedIdentity, authorID, author string) bool

IsSelfActor is isSelfActor for read paths outside the store (gadak retro's resume row): the identity rule stays in one place instead of a second copy that can drift.

func LiteToIssue added in v0.21.0

func LiteToIssue(l IssueLite) jql.Issue

LiteToIssue maps a mirror row onto jql's neutral match shape. Every IssueLite column jql.Match can key on must cross here — the field table in jqlbind_test.go fails by name if one goes missing again (GDK-1564 was exactly such a hole, in the CLI copy of this mapping).

func LocalPath added in v0.13.0

func LocalPath(mirrorPath string) string

LocalPath is local.db beside the mirror at mirrorPath.

func LocalSchemaSkew added in v0.22.0

func LocalSchemaSkew(mirrorPath string) (have, want int, skewed bool)

LocalSchemaSkew reports whether local.db beside the mirror carries a schema newer than this build supports (GDK-596). It is the queryable form of the notice migrateLocal logs: the notice is a short pointer, and `gadak doctor` prints what this returns. Read-only by design — no EnsureLocal, no migration — and a missing or unreadable file reads as "no skew" rather than as a verdict doctor cannot stand behind.

func LocalSchemaVersion added in v0.23.0

func LocalSchemaVersion() int

LocalSchemaVersion is the local.db schema level this build writes (len(localMigrations)) — the local half of doctor's have/head schema line (GDK-1967), and the `want` LocalSchemaSkew reports.

func MarshalWithIssueKeyAlias added in v0.17.0

func MarshalWithIssueKeyAlias(issueKey string, v any) ([]byte, error)

MarshalWithIssueKeyAlias encodes v then sets `"key"` equal to issueKey. Callers pass a named type alias of themselves so this is not recursive. Map-built JSON uses AliasIssueKey.

func MirrorChangedAt added in v0.19.0

func MirrorChangedAt(path string) time.Time

MirrorChangedAt is when the mirror bytes last moved — the newest mtime among the files MirrorVersion keys on. Zero when path is empty or nothing exists. This is the diagnostic half: `gadak doctor` reports it so "why is the board not updating?" is answered by looking at one timestamp instead of guessing.

func MirrorSchemaVersion added in v0.23.0

func MirrorSchemaVersion() int

MirrorSchemaVersion is the mirror schema level this build writes (len(migrations)) — the head of a have/head pair. `gadak doctor` prints it beside the file's own stamp so a dev-build refusal names both sides without a second command (GDK-1967); issuetap.PersistSchemaVersion is the persist side's twin.

func MirrorSidecarBytes added in v0.22.0

func MirrorSidecarBytes(path string) (wal, shm int64)

MirrorSidecarBytes reports the byte sizes of the mirror's WAL sidecars — gadak.db-wal and gadak.db-shm next to the mirror at path. An absent file is 0, not an error: a mirror with no -wal is a legitimate state (never opened, or checkpointed on close), and the diagnostic the caller prints is "wal=0" rather than a missing-file error — MirrorVersion's rule, one file over.

This is the GDK-307 observability seam. store.Open sets journal_mode=WAL and no journal_size_limit caps the sidecar, so the -wal file is bounded only by checkpointing — and a serve process that holds the mirror open never gets the checkpoint-on-close. Whether that ever starves in practice is not this function's claim; the claim is that without these bytes being visible, "the -wal file grew" and "SQLite is broken" are indistinguishable from outside the machine. Callers report them before store.Open (opening mints the sidecars when absent — doctor's existing mirror Stat has the same ordering note).

func MirrorVersion added in v0.19.0

func MirrorVersion(path string) string

MirrorVersion is the disk identity of a mirror: "did this move?" answered for a caller that has to ask twice a second (GDK-1170, the ui-focus poll). Only equality is defined — the shape is not a contract, and a client that stores one and compares the next is using it correctly.

The technique is config.ConfigVersionOfDir's: mtime+size, no open, no query, no read of the bytes. Two os.Stat calls, so a 500ms poll costs nothing.

It keys on the -wal sidecar and not on the database file alone, and that is the whole point. store.Open sets journal_mode=WAL, so a write from another process (a `gadak claim` in a terminal) lands in gadak.db-wal and leaves gadak.db untouched until a checkpoint — and while `gadak serve` holds the mirror open there is no checkpoint-on-close to move it. Measured on macOS/APFS with serve running: over `gadak claim` and `gadak edit`, gadak.db's mtime and size never moved while gadak.db-wal moved on both (mtime and size, every write). Keyed on gadak.db alone this would have been a version that never changes for exactly the writes it exists to notice.

gadak.db-shm is excluded on purpose: it is the reader's shared index, so folding it in would report movement for reads. Measured in the same run — a `gadak issue` read moved none of the three.

A missing file is "0", not an error: a mirror that does not exist yet is a legitimate state, and it has to compare equal to itself on the next poll.

func Now

func Now() string

Now returns UTC now in config.ISOMilli. The server hands this value to clients as the `delta` cursor; see that constant for why milliseconds are required.

func OpenReadOnly added in v0.13.0

func OpenReadOnly(path string) (*sql.DB, error)

OpenReadOnly opens the mirror with SQLite mode=ro and ATTACHes local.db (created empty if missing so SELECT local.visits never fails the connection).

func PageIDFromQuery added in v0.22.0

func PageIDFromQuery(s string) string

PageIDFromQuery is the exported half of rePageIDParam: the page id in a `pageId=<digits>` parameter, case-insensitively, or "" when absent. It exists so the sync pass answers comment-container webui strings with the same case policy refs extraction uses — one grammar, one owner.

func ReopenTransition added in v0.22.0

func ReopenTransition(from, to string) bool

ReopenTransition is the single owner of what a "reopened" move is: the category going backwards. Leaving done is the classic reopen; leaving in-progress back to new is its sibling on workflows whose resolved states sit in the in-progress category — there 'QA testing → Reopened' is how work comes back, and under the done-only rule this replaced, those rows read reopen_count = 0 (59% of the real reopens on the mirror that reported it). Unknown ids stay what they always were: not done, not new — a category the map cannot name never counts as the destination of a backwards move, so an uncatalogued status cannot invent a reopen.

Every consumer of the verdict routes through this one function (GDK-1753): Derive's ReopenCount/ReopenedAt columns, the server's per-history-row is_reopen on the detail wire, the CLI --derive listing, and the retro materials. A second spelling of the predicate anywhere else is what the sourcelint gate TestReopenVerdictHasOneOwner exists to keep from coming back.

func SetDefaultOpenOptions added in v0.22.0

func SetDefaultOpenOptions(opts OpenOptions)

SetDefaultOpenOptions installs the policy Open applies from now on. Call it once, at boot, before any workspace is opened.

func SortDisplay added in v0.21.0

func SortDisplay(list []IssueLite, d jql.Display)

SortDisplay applies the parsed ORDER BY to matched rows: dir defaults to desc, priority breaks ties on updated_at, everything else sorts on the asked axis. The ordering contract "a JQL dashboard and `gadak search --jql` list the same order" is gated by TestSearchJQLOrdersLikeDashboardJQL in cmd/gadak — this function is the one sort both surfaces ride.

func SyncProgressCutoff added in v0.22.0

func SyncProgressCutoff(now time.Time) string

SyncProgressCutoff is the updated_at floor below which a row is stale. The single owner of the comparison stamp, so the SQL reader here and the plain- SQL reader in cmd/gadak cannot disagree. Returned in config.ISOMilli — the fixed-width UTC layout Now() writes, which is what makes a lexicographic >= in SQL a time comparison (and a foreign-format row safely stale).

func ValidateRecipeName added in v0.17.0

func ValidateRecipeName(name string) error

ValidateRecipeName is the recipes save NAME rule. Empty and anything outside recipeNameRe are refused.

func WithBusyHint added in v0.17.1

func WithBusyHint(err error) error

WithBusyHint wraps a SQLITE_BUSY error so Error() names the likely holder. Non-busy errors and nil pass through. Already-hinted values are unchanged.

Types

type APIUsageDay

type APIUsageDay struct {
	Day             string  `json:"day"`
	Requests        int64   `json:"requests"`
	Throttled       int64   `json:"throttled"`
	ServerErrors    int64   `json:"server_errors"`
	Retries         int64   `json:"retries"`
	WaitMS          int64   `json:"wait_ms"`
	LastThrottledAt *string `json:"last_throttled_at,omitempty"`
}

APIUsageDay is one row of daily accumulated outbound API volume.

type APIUsageDelta

type APIUsageDelta struct {
	Requests        int64
	Throttled       int64
	ServerErrors    int64
	Retries         int64
	WaitMS          int64
	LastThrottledAt string // RFC3339 UTC, empty if unknown this flush
}

APIUsageDelta is a non-negative increment to accumulate into one UTC day. Numbers only — this package must not import jira (layering).

type APIUsageSum

type APIUsageSum struct {
	Requests        int64   `json:"requests"`
	Throttled       int64   `json:"throttled"`
	ServerErrors    int64   `json:"server_errors"`
	Retries         int64   `json:"retries"`
	WaitMS          int64   `json:"wait_ms"`
	LastThrottledAt *string `json:"last_throttled_at,omitempty"`
}

APIUsageSum is a multi-day total (no day key).

type APIUsageSummary

type APIUsageSummary struct {
	Today     APIUsageDay `json:"today"`
	Last7Days APIUsageSum `json:"last_7_days"`
}

APIUsageSummary is the shape status --json and GET settings/ runtime expose: today's row plus a 7-day rollup of our outbound call volume.

type ActorPerson added in v0.17.1

type ActorPerson struct {
	AssigneeName  string
	AssigneeEmail string
	AssigneeID    string
	ReporterName  string
	ReporterEmail string
	ReporterID    string
}

ActorPerson is the assignee/reporter triple JQL people resolution needs — the narrow projection PeopleFromIssues consumes, without IssueLite's twenty-odd columns (GDK-748: loading full lites made every --jql path pay a whole-mirror row scan).

type AgentWrite added in v0.22.0

type AgentWrite struct {
	ID     int64  `json:"id"`
	Key    string `json:"key"`
	At     string `json:"at"`
	Verb   string `json:"verb"`
	Source string `json:"source"`
}

AgentWrite is one row of the write ledger (GDK-1440): what a CLI/MCP session wrote, when, under which verb. Export reads it raw; the epoch column is workspace-local bookkeeping and stays out of the file.

type Attachment

type Attachment struct {
	ID         string
	ExternalID string
	Filename   string
	MimeType   string
	Size       int64
	Author     string
	AuthorID   string
	CreatedAt  string
	// URL is the origin content URL when the source does not share Jira's
	// /attachment/content/{id} shape. Empty for Jira (the proxy builds it).
	URL string
}

Attachment is metadata only. Bytes are proxied on demand, never mirrored.

type AuthorComment

type AuthorComment struct {
	Key       string `json:"key"`
	Kind      string `json:"kind"` // "issue" | "page"
	Title     string `json:"title"`
	Snippet   string `json:"snippet"`
	CreatedAt string `json:"created_at"`
}

AuthorComment is one row in GET people/{author_id}/comments/.

type Batch

type Batch struct {
	Categories map[string]string // status id -> status category
	Priorities []string          // priority display names, most urgent first
	// LinkTypes is the origin's issue-link-type catalog, fetched once per
	// sync run (not per batch page — every batch of the run attaches the same
	// rows) and cached into link_types. open_blockers resolves which types
	// block from this catalog, never from a hardcoded display name.
	LinkTypes []LinkType
	// NoHistory marks a batch from an origin that supplies no changelog
	// (Linear). Derive then refuses to infer a start from an empty history:
	// started_at stays NULL for issues with no transition into progress and
	// no StartedAtHint, instead of guessing created_at. Jira and the built-in
	// origin leave it false — their empty changelog means "never moved".
	NoHistory bool
	Records   []IssueRecord
	// Force rewrites rows whose updated_at is unchanged. Off, an unchanged row
	// is skipped entirely, which is what keeps an incremental re-run from
	// bumping sync_state.version.
	//
	// A full pass sets it (GDK-1457). The skip is defined on the origin's
	// `updated`, but the mirror's derived columns are defined on gadak's own
	// rules — and those change when gadak does. A row whose `updated` has not
	// moved since a rule was added therefore keeps a column derived under the
	// old rule until someone edits the issue, which for Linear's started_at /
	// cycle_hours is forever: the flow stamps ride the payload as hints
	// (IssueRecord.StartedAtHint) and the mirror stores no raw copy, so no
	// backfill over mirrored rows can reconstruct them. A full pass has the
	// payload in hand and is the one pass that promises the mirror is rebuilt
	// from it.
	Force bool
}

Batch is one page of sync output. Categories, Priorities and LinkTypes come from the site's own metadata endpoints (which are not localized) and feed the derived field rules.

type BoardRow added in v0.22.0

type BoardRow struct {
	ID         int64
	Name       string
	Type       string
	ProjectKey string
}

BoardRow is one board in the mirror (GDK-1654) — a Jira Software board or, on a Linear source, one row per team, typed "cycles" (GDK-1667).

type BoardRowWithSprints added in v0.22.0

type BoardRowWithSprints struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	Type       string `json:"type"`
	ProjectKey string `json:"project_key,omitempty"`
	HasSprints bool   `json:"has_sprints"`
}

BoardRowWithSprints is one mirrored board. `HasSprints` says whether the board can answer a sprint-cut report (GDK-1713) — a board with no dated sprint is not a choice a retro picker should offer.

type BurnupDay added in v0.22.0

type BurnupDay struct {
	Date      string `json:"date"`
	Scope     int    `json:"scope"`
	Started   int    `json:"started"`
	Completed int    `json:"completed"`
}

BurnupDay is one calendar day of the burn-up, UTC-bucketed: an event counts from the day its stamp lands in. Scope is how many issues were in the sprint that day; started and completed are counted inside that scope, so 0 ≤ completed ≤ started ≤ scope holds by construction.

type BurnupDoc added in v0.22.0

type BurnupDoc struct {
	ID         int64       `json:"id"`
	Name       string      `json:"name"`
	State      string      `json:"state"`
	StartAt    string      `json:"start_at,omitempty"`
	EndAt      string      `json:"end_at,omitempty"`
	CompleteAt string      `json:"complete_at,omitempty"`
	SourceKind string      `json:"source_kind"`
	Days       []BurnupDay `json:"days"`
}

BurnupDoc is the daily reconstruction of one sprint from the changelog — the data the sparkline and `gadak sprint show` read (GDK-1710). Days is empty on a sprint whose window cannot be placed (no start_at and no sprint-field event anywhere) or that has not started yet; those are different from a day series and the callers say so rather than drawing an empty chart. SourceKind is the sprint's own source kind ("linear", …) so the origin-capability judgement — an origin with no changelog cannot answer this question at all — stays with its single owner (retro.OriginSuppliesChangelog), one package up.

type ChangeEntry

type ChangeEntry struct {
	ID        string
	At        string
	Author    string
	AuthorID  string
	Field     string // "status", "assignee", "priority", ...
	FromValue string
	FromID    string
	ToValue   string
	ToID      string
}

ChangeEntry is one field change. Status entries carry ids because display names are localized per account.

type Comment

type Comment struct {
	ID         string // "<source_id>:<comment_id>"
	ExternalID string
	Author     string
	AuthorID   string
	BodyADF    json.RawMessage
	BodyText   string
	CreatedAt  string
	UpdatedAt  string
	ParentID   *string
	// VisibilityType/VisibilityValue are the origin restriction (Jira
	// visibility.type/value). Empty means unrestricted. Linear and wiki
	// comments have no such field and stay empty.
	VisibilityType  string
	VisibilityValue string
	// JsdPublic is JSM's jsdPublic marker. nil means the origin omitted
	// the key (not a JSM project, or Jira did not send it); false is an
	// internal comment. Absence and false are distinct.
	JsdPublic *bool
}

Comment is stored flat for origins that expose no thread parent (Jira, Linear). Wiki comments are threaded, so ParentID says which it is: nil = parent unknown (pre-v52 rows, flat origins), pointer to "" = a top-level wiki comment, pointer to an external id = a wiki reply. NULL must never fold into "" — an unknown parent is the scan's cue to re-fetch, not a claim of top-level (schemaV52).

type CommentsByAuthorResult

type CommentsByAuthorResult struct {
	// Author is the display name from the newest matching comment ("" when none).
	Author   string          `json:"author"`
	Total    int             `json:"total"`
	Comments []AuthorComment `json:"comments"`
}

CommentsByAuthorResult is the response body for comments by author.

type DB

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

DB is a handle on the mirror. Safe for concurrent use; writes are serialized.

func Open

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

Open opens or creates the mirror at path and migrates it forward. A database written by a newer gadak is refused rather than used.

The data directory is created (and existing owner-writable dirs tightened) to 0700; an owner-locked directory (0555) is left locked. The DB file and any -wal/-shm sidecars are set to 0600. Chmod failures are logged and ignored so unsupported filesystems (or Windows) still work.

func OpenArtifact added in v0.23.0

func OpenArtifact(path string) (*DB, error)

OpenArtifact opens a file this process is building as a standalone, shareable artifact — the snapshot pipeline's temp and published files (GDK-1934). Such an open never adopts, migrates or creates a local.db beside the file: connections get a private in-memory `local` instead (attachMemoryLocal), so the artifact's schema is decided by this build alone, not by whatever local.db sits in the output directory. The open policy is the process default, exactly like Open — an artifact build must not silently flip the dev-lockout decision either way.

func OpenWith added in v0.22.0

func OpenWith(path string, opts OpenOptions) (*DB, error)

OpenWith is Open with an explicit open policy. Everything else — directory and file modes, local.db handling, the too-new refusal — is exactly Open's.

func (*DB) APIUsage

func (db *DB) APIUsage(ctx context.Context, days int) ([]APIUsageDay, error)

APIUsage returns up to the most recent days rows, newest day first. days <= 0 means all rows. Reads local.api_usage (GDK-1906) — never the mirror-side frozen leftover, which an unprefixed name would resolve to.

func (*DB) APIUsageSummary

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

APIUsageSummary builds today + last 7 days from local.db. Missing days are zeros. last_throttled_at on the rollup is the latest timestamp in the window.

func (*DB) AbsorbDashboards added in v0.17.2

func (db *DB) AbsorbDashboards(ctx context.Context, incoming []Dashboard) error

AbsorbDashboards merges incoming rows (an export file, another machine) into local.dashboards — AbsorbViews, for dashboards. Same rules: a name the server already owns wins (incoming row dropped), an id that collides gets a fresh one so an insert can never overwrite a stored row.

func (*DB) AbsorbRecents added in v0.16.0

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

AbsorbRecents merges a localStorage dump into local.recents. Existing server rows stay in front (they are already the owner); incoming values not already present fill the remainder, still capped at recentCap per kind. Incoming slices are newest-first, same as recentOf().

func (*DB) AbsorbViews added in v0.17.0

func (db *DB) AbsorbViews(ctx context.Context, incoming []SavedView) error

AbsorbViews merges browser-local (localStorage) views into local.saved_views — the GDK-437 promotion day must not look like data loss. Same rules as AbsorbRecents: the server is already the owner, so an incoming view whose name exists there is dropped (server row wins), the rest are inserted. Reads order by name, so "server rows in front" reduces to that conflict rule. Kept ids stay stable — the client hides its absorbed rows by id — and an id that already exists gets a fresh one so an insert can never overwrite a server row (PutSavedView's upsert is deliberately not used here).

func (*DB) AddAPIUsage

func (db *DB) AddAPIUsage(ctx context.Context, day string, u APIUsageDelta) error

AddAPIUsage UPSERTs delta into the given UTC day (YYYY-MM-DD), adding to any existing counters. last_throttled_at keeps the latest non-empty timestamp. Writes go to local.api_usage (GDK-1906): the mirror-side table is a frozen copy-leftover, and this is the data `rm gadak.db` must not delete.

func (*DB) AppendSyncRun

func (db *DB) AppendSyncRun(ctx context.Context, sourceID string, r SyncRun) error

AppendSyncRun stores one run and prunes the history to the newest 100.

func (*DB) AttachmentBelongs added in v0.14.1

func (db *DB) AttachmentBelongs(ctx context.Context, issueKey, attachmentID string) (bool, error)

AttachmentBelongs reports whether the mirror lists attachmentID on issueKey. The id is the Jira external id when that column is set, otherwise the store row id — the same rule handleDetail uses when it builds content URLs. One EXISTS query: serving bytes must not pay for Detail's comments/history/links/refs.

func (*DB) AttachmentMime added in v0.23.0

func (db *DB) AttachmentMime(ctx context.Context, issueKey, attachmentID string) (string, error)

AttachmentMime is the mirror's recorded media type for one issue attachment: the artifact route's gate reads it to decide whether the id may be served as a sandboxed HTML document — the mirror row, not the bytes or an upstream claim, is the authority. Same join and id rule as AttachmentBelongs, so ErrNotFound here is also that route's membership answer. An empty string (no error) means the row carries no mime, which the caller treats as not-an-artifact.

func (*DB) AttachmentOrigin added in v0.16.1

func (db *DB) AttachmentOrigin(ctx context.Context, issueKey, attachmentID string) (sourceID, contentURL string, err error)

AttachmentOrigin is the proxy's lookup: which source owns this attachment and, when stored, the origin content URL. Matches AttachmentBelongs' id rule (external_id when set, else store id).

func (*DB) AttachmentSize added in v0.22.0

func (db *DB) AttachmentSize(ctx context.Context, issueKey, attachmentID string) (int64, error)

AttachmentSize is the byte count the origin recorded for one attachment, or 0 when the mirror has no number for it (GDK-1616). It is a claim, not a measurement: an origin may state a size and send a different one, so a caller that needs certainty still has to count what arrives. What it is good for is deciding, before a byte moves, whether an attachment could ever fit a cache with a per-entry cap.

func (*DB) BackfillFlow added in v0.21.0

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

BackfillFlow is backfillFlow on an open handle's own transaction. The snapshot builder calls it after copying rows into a fresh database: the copy lands the flow columns at their DEFAULT (the column-bag mover does not know them), and this recomputes them from the destination's own rows so they agree with whatever timestamps the snapshot spread.

func (*DB) BeginSyncProgress added in v0.22.0

func (db *DB) BeginSyncProgress(ctx context.Context, sourceID string, first bool) error

BeginSyncProgress starts (or restarts) the heartbeat row for one source: fetched 0, no total. An upsert, not an insert — a stale row from a crashed pass or a BUSY retry must be overwritten, never stacked beside. This is bookkeeping in the AddAPIUsage sense: it goes through write() and never bumps the mirror's ETag version.

func (*DB) Boards added in v0.22.0

func (db *DB) Boards(ctx context.Context) ([]BoardRowWithSprints, error)

Boards lists the mirror's boards by id, with the sprint-bearing flag the retro's board picker keys on. The sprint predicate is the same one retro.SprintBuckets uses to decide the report is ambiguous — a dated sprint on this board — so the picker offers exactly the boards the report would have accepted, and not one more.

func (*DB) ClearLocalHistory added in v0.22.0

func (db *DB) ClearLocalHistory(ctx context.Context) (visits, searches int64, err error)

ClearLocalHistory empties every personal-history table — the personal timeline and nothing else (GDK-106). Recents and saved views are not history: they are the pickers' own memory, and the clear verb the settings and history surfaces offer must not reach them. The tables it walks are personalHistoryTables, the same list the retention prune walks, so the promise the button makes ("cannot be undone") cannot drift from what the file keeps (GDK-1807).

The visits and searches counts come back so the endpoint can say what it removed (a repeat call answers zeros); the derived tables cleared alongside them — sessions, the visit timeline rolled up, and the agent_writes ledger — have no count on the wire because the surface reports the events, not their summaries.

func (*DB) Close

func (db *DB) Close() error

func (*DB) CommentsByAuthor

func (db *DB) CommentsByAuthor(ctx context.Context, authorID string, limit int) (CommentsByAuthorResult, error)

CommentsByAuthor returns comments for an exact author_id match, newest first. Missing author_id yields total 0 and an empty list (not an error). limit defaults to 50 and is capped at 200.

func (*DB) ComputeFieldUsage

func (db *DB) ComputeFieldUsage(ctx context.Context, aliases []string) ([]FieldUsageRow, error)

ComputeFieldUsage builds field_usage rows from issues.custom for the given aliases. total is the issue count per project; filled is how many issues have a non-empty value for that alias.

func (*DB) ConfluenceSpaceWatermarks added in v0.13.0

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

ConfluenceSpaceWatermarks returns each space key's incremental floor for sourceID. A missing or NULL watermark is "". Callers treat empty as "not yet backfilled" and run a full fetch for that space.

func (*DB) CountAttachments added in v0.22.0

func (db *DB) CountAttachments(ctx context.Context) (int, error)

CountAttachments is how many attachment rows the mirror holds. doctor pairs it with the byte cache's own count so one line says whether this workspace's attachment bytes are local yet (GDK-1616).

func (*DB) CountAttachmentsOfSize added in v0.22.0

func (db *DB) CountAttachmentsOfSize(ctx context.Context, size int64) (int, error)

CountAttachmentsOfSize counts the mirrored attachments whose recorded size is exactly size. It exists for one question a workspace on the built-in origin has to be able to answer without opening every issue: how many attachments may have been cut off by the old 8 MiB upload cap (GDK-1615). Count only, no names — doctor's document is paste-safe, and the names come from a `gadak sql` one-liner the line itself prints.

func (db *DB) CountDevLinks(ctx context.Context) (rows, issues int, err error)

CountDevLinks is how many development-panel rows the mirror holds, and over how many issues. doctor pairs it with config.MirrorsDevLinks so an empty table reads as "not synced" rather than "really zero" (GDK-1496): on a connected Cloud workspace the fetch is off by default, and the two states were indistinguishable from SQL alone.

func (*DB) CountIssuesInScope added in v0.21.0

func (db *DB) CountIssuesInScope(ctx context.Context, sourceID string, projects []string) (int, error)

CountIssuesInScope counts the issues one source mirrors under a project scope — the mirror's half of the divergence probe (GDK-1400), matched against the count the origin reports for the same scope. An empty projects list means the whole source, which is what an empty `projects` config means to the sync pass. Project keys compare case-insensitively: the config carries whatever the user typed and the origin's own casing is canonical.

It is a COUNT, not a listing, because it runs on every incremental tick: a mirror with a hundred thousand issues must not load them all to answer "how many".

func (db *DB) CountOneSidedLinks(ctx context.Context) (int, error)

CountOneSidedLinks counts stored link rows whose far end is in the mirror and holds no counterpart row. Both ends must be mirrored for a row to count: a link pointing outside the synced scope has no counterpart to expect, and counting those would report every cross-project link as damage.

It is a diagnostic, not a verdict (GDK-1507). Jira and Linear both report a relationship from both sides, so on a mirror synced from either, a non-zero number is the standing symptom of an incremental window that carried one end and not the other — one `gadak sync --full` levels it. A mirror seeded by other means can hold one-sided rows by construction, which is why doctor prints the number and draws no conclusion from it.

func (*DB) CycleTimeP85Hours added in v0.21.0

func (db *DB) CycleTimeP85Hours(ctx context.Context, since time.Time) (float64, int, error)

CycleTimeP85Hours is the learned half of the stale threshold: how long the slowest 15% of recently finished work actually took, in hours. Since v43 it reads the stored cycle_hours column (resolved_at − started_at, both Derive columns kept current by every upsert and backfilled at migration) instead of walking the changelog: `resolved_at >= since` selects the same window the walk's "done entry at or after since" did, and cycle_hours is NULL exactly for the issues the walk skipped — never in progress, finished before the window, or reopened and not re-finished (a non-cycle must not drag the percentile down; this deliberately diverges from Durations' span(), which clamps).

`reopen_count = 0` (2026-09-07, second literature round): an issue that was finished, reopened and finished again carries the parked interval in cycle_hours — under gadak's elapsed definition that is one long cycle, which neither Jira's control chart nor Swarmia would report, and the flow canon keeps items that took an unusual path out of the SLE sample. Their cycle_hours stays stored (the column is the fact); only this sample — the one that becomes the learned stale threshold — leaves them out. The retro's cycle rows apply the same clause so the two never disagree.

The changelog walk this replaced lives on in cycle_time_test.go as the oracle the column read is proven equal against — on a seeded fixture and on a migrated copy of examples/demo.db. If the two ever disagree, the columns drifted from Derive's rules and that is the bug to fix, not the test.

The percentile is nearest-rank with integer arithmetic, rank (85n+99)/100 — the formula internal/retro P85 owns (it moved out of cmd/gadak with the whole compute). Keep the two in lockstep.

`since` is compared as a string in the stamps' own format (millisecond RFC3339, UTC): every column this reads is written by Derive in that one format, so the comparison never crosses precisions.

func (*DB) Dashboard added in v0.17.2

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

Dashboard looks up one row by id. Unknown id is ErrNotFound.

func (*DB) DashboardVersion added in v0.17.2

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

DashboardVersion is the monotonic change counter for dashboard writes (0 before the first save). It moves on save and delete — the two events an open tab must reflect.

func (*DB) Dashboards added in v0.17.2

func (db *DB) Dashboards(ctx context.Context) ([]Dashboard, error)

Dashboards lists every dashboard by name.

func (*DB) DeleteDashboard added in v0.17.2

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

DeleteDashboard removes one row by id and bumps the change counter. Unknown id is ErrNotFound.

func (*DB) DeleteItems

func (db *DB) DeleteItems(ctx context.Context, sourceID string, keys []string) (int, error)

DeleteItems removes items whose keys have left the source's scope and records a tombstone so `delta` can report the deletion to a client that missed it.

func (*DB) DeletePagesIfUnchanged added in v0.23.0

func (db *DB) DeletePagesIfUnchanged(ctx context.Context, sourceID string, stamps map[string]PageStamp) (int, error)

DeletePagesIfUnchanged removes pages only while they still match the pre-listing mirror snapshot. A concurrent page refresh or create must win over a reconcile whose origin listing predates that write.

func (*DB) DeleteRecipe added in v0.17.0

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

DeleteRecipe removes one recipe. Unknown name is ErrNotFound.

func (*DB) DeleteSavedView

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

func (*DB) DeletedKeysSince

func (db *DB) DeletedKeysSince(ctx context.Context, since string, scope TombstoneScope) ([]string, error)

DeletedKeysSince lists keys tombstoned after the cursor, within one scope. `delta` must report these: a missed deletion leaves a tombstone visible in the client forever. The issue delta asks for TombstoneIssues so a page id never reaches the issue client as a stray key.

func (*DB) Detail

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

Detail assembles one issue. An unknown key returns ErrNotFound so the handler can answer 404 without importing database/sql. Bodies present as the markdown dialect — the pre-GDK-1637 shape; callers that hold the workspace config say which dialect with DetailWithDialect.

func (*DB) DetailWithDialect added in v0.22.0

func (db *DB) DetailWithDialect(ctx context.Context, key string, dialect adf.Dialect) (*Detail, error)

DetailWithDialect is Detail with the body dialect chosen by the caller — the one holding the workspace config (GDK-1637): DialectWiki on a Jira Server origin, whose bodies are wiki markup carried verbatim. The mirror layer never derives the dialect itself; internal/store does not import internal/config.

func (*DB) DistinctCount

func (db *DB) DistinctCount(ctx context.Context, table, column string) (int, error)

DistinctCount returns COUNT(DISTINCT col) for a fixed known table.column used by doctor. Empty/NULL values are excluded.

func (*DB) DropSourceMirror added in v0.16.1

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

DropSourceMirror deletes everything one source mirrored: its items (and their cascaded children), FTS rows, spaces, tombstones, sync state and sync runs — so the next sync starts full against the new origin. Used when a built-in workspace converts to connected: a pre-namespace mirror holds `jira:N` / `confluence:N` rows the new site's upsert would silently overwrite on an id collision. The disposable cache is dropped whole rather than reconciled row by row, and the personal rows keyed into it go with it.

This is the per-source half. ResetForNewOrigin is the whole conversion and is what the surfaces call; this stays exported for a single-source drop.

func (*DB) EndSyncProgress added in v0.22.0

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

EndSyncProgress deletes the row when a pass returns, success or error.

func (*DB) EnrichmentsByKind

func (db *DB) EnrichmentsByKind(ctx context.Context, kind string) (map[string]json.RawMessage, error)

EnrichmentsByKind returns every payload of one kind, keyed by issue key. The list and delta responses merge it in.

func (*DB) EnrichmentsFor

func (db *DB) EnrichmentsFor(ctx context.Context, key string) (map[string]json.RawMessage, error)

EnrichmentsFor returns every kind attached to one issue, for the detail view.

func (*DB) ExternalID added in v0.17.0

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

ExternalID is the origin's own id for a mirrored issue key — what Jira's dev-status calls issueId (numeric on Cloud, issuetap's id builtIn).

func (*DB) Favorites

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

func (*DB) Feed

func (db *DB) Feed(ctx context.Context, opts FeedOpts) (FeedResult, error)

Feed computes personal-feed events from the mirror at query time.

func (*DB) FieldUsage

func (db *DB) FieldUsage(ctx context.Context) ([]FieldUsageRow, error)

FieldUsage returns every field_usage row.

func (*DB) FreshenSyncClock

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

FreshenSyncClock stamps every sync timestamp as now. It exists for throwaway fixtures — `gadak demo` and the demo recordings — where the snapshot's real age would surface as a stale-sync warning about data that is deliberately frozen. Never call this on a mirror that syncs for real: it would hide a stalled sync.

func (*DB) GroupQueryHits added in v0.16.0

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

GroupQueryHits is the result of Config.GroupQuery. Keys not in the map fall through to groupRules / assignee. A present empty string means unclassified (stop).

func (*DB) HasCustomFieldKeysInRaw

func (db *DB) HasCustomFieldKeysInRaw(ctx context.Context) (bool, error)

HasCustomFieldKeysInRaw reports whether any stored raw document contains a customfield_ key under fields. Used by `gadak fields --apply` to refuse when the mirror was never synced with custom fields. The substring probe runs in SQL and stops at the first hit — the previous Go-side parse of every raw document cost ~1.5 s of JSON unmarshal at 20k issues (measured 2026-08-23, GDK-749). On a corpus with no custom fields the probe still walks every document (~12 KB each), which is the price of an exact no.

func (*DB) HasCustomFieldKeysInRawSampled added in v0.17.1

func (db *DB) HasCustomFieldKeysInRawSampled(ctx context.Context, limit int) (bool, error)

HasCustomFieldKeysInRawSampled is the doctor-hint twin of the probe above: it looks at at most limit documents and reports whether any carried a customfield_ key. A miss is not proof of absence — the hint it feeds says "none seen", not "none exist" — but it keeps `gadak doctor` off the whole-mirror path (GDK-749: the exact probe measured 600-860 ms on a custom-field-free 20k mirror; fields --apply keeps the exact one).

func (*DB) HasPageVersion added in v0.16.0

func (db *DB) HasPageVersion(ctx context.Context, itemID string, number int) (bool, error)

HasPageVersion reports whether a stamp for this version number is already stored. Sync uses it as the incremental gate: if the incoming page version is already on disk, history cannot have grown and must not be refetched.

func (*DB) HasSource

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

HasSource reports whether a sources row exists for id.

func (*DB) History added in v0.13.0

func (db *DB) History(ctx context.Context, opts HistoryOpts) (HistoryPage, error)

History returns visits and searches newest-first. Cursor is opaque.

func (*DB) ImportRecents added in v0.16.0

func (db *DB) ImportRecents(ctx context.Context, items []Recent) error

ImportRecents upserts export-file rows. File used_at wins for a (kind, value) pair; each kind is then trimmed to recentCap newest. Local-only pairs stay if they still fit in the cap.

func (*DB) IssueCommentCount added in v0.17.0

func (db *DB) IssueCommentCount(ctx context.Context) (int, error)

IssueCommentCount returns SUM(issues.comment_count): the comment figure the settings runtime shows, which counts issue comments only. It is deliberately not TableCount(ctx, "comments") — page comments share the comments table (upsertPageRecord rewrites them through the same insertComment helper), so the raw table count would mix wiki comments into an issue figure and move the number the settings UI has always shown (GDK-610).

func (*DB) IssueLites

func (db *DB) IssueLites(ctx context.Context) ([]IssueLite, error)

IssueLites returns the whole mirror, which is what `bootstrap` sends.

func (*DB) IssueLitesByKeys added in v0.14.1

func (db *DB) IssueLitesByKeys(ctx context.Context, keys []string) ([]IssueLite, error)

IssueLitesByKeys returns the IssueLite rows for keys, in the order asked. Missing and empty keys are skipped. Duplicate keys yield duplicate rows. The SQL IN-list is de-duplicated; callers that need FTS rank pass the ranked key list and get that order back.

func (*DB) IssueLitesSince

func (db *DB) IssueLitesSince(ctx context.Context, since string) ([]IssueLite, error)

IssueLitesSince returns rows written at or after the given cursor. Only a row whose content actually changed has a newer synced_at, so an idle poll returns none. The bound is inclusive on purpose: re-sending a row the client already has is a harmless upsert, while missing one leaves it stale forever.

func (*DB) IssueStamps added in v0.19.0

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

IssueStamps returns the mirror's updated_at per issue external id, for the ids asked about. The Jira incremental pass uses it the way the Confluence pass uses PageStamps: a search hit whose stamp the mirror already holds is the watermark's overlap window echoing, not a change, so the pass spends no build (and none of build's per-issue child fetches) on it (GDK-1075). Jira's `updated` moves on comments and transitions too, so stamp equality really does mean nothing changed.

func (*DB) IssueSyncState added in v0.17.0

func (db *DB) IssueSyncState(ctx context.Context) (SyncState, error)

IssueSyncState is the issue-origin freshness row status --json and gadak_status publish as top-level watermark / sync_count / last_error. Jira wins when it has activity so dual-source workspaces keep the historical shape; Linear wins when it is the only issue source that has run.

func (*DB) KeySource added in v0.16.1

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

KeySource returns the source_id owning key in the mirror, "" when the key is not mirrored, and ErrKeyAmbiguous when two sources both mint it — silently preferring one source sent writes to a tracker the screen was not showing (GDK-400).

func (*DB) KeysBySource added in v0.16.1

func (db *DB) KeysBySource(ctx context.Context, sourceID string) ([]string, error)

KeysBySource returns issue keys mirrored from one source, in key order.

func (*DB) KeysInSprint added in v0.22.0

func (db *DB) KeysInSprint(ctx context.Context, sprintID int64) ([]string, error)

KeysInSprint lists the mirrored issue keys in one sprint.

func (*DB) LastSessionEnd added in v0.21.0

func (db *DB) LastSessionEnd(ctx context.Context, now time.Time, gap time.Duration) (*time.Time, error)

LastSessionEnd returns the viewed_at of the newest person read that is not part of the session containing `now` — i.e. where the previous session ended. nil when there is no previous session (zero visits, or only the current session's reads).

The session rule is SessionGap above (retro re-exports it): person reads are visits with source ui or the empty pre-V7 source, and a gap to the previous read *exceeding* the gap starts a new session — exactly the gap is still the same session. Since GDK-1439 the boundary is read from local.sessions (the table RecordVisit maintains at exactly that rule); lastSessionEndSQL's visit walk below remains as the fallback for a local.db whose sessions table holds no current-epoch rows — a file seeded beside this build (tests, and any state that wrote visits without the migration's backfill). Person reads only, and the epoch clause for the same GDK-418 reason: a visit from a replaced origin is not this workspace's session.

func (*DB) LastVisits added in v0.21.0

func (db *DB) LastVisits(ctx context.Context, kind, key string, n int) ([]Visit, error)

LastVisits returns the newest n visits of one (kind, key), newest first — the two rows the issue detail turns into last/previous_visit_at. Person reads only: source ui, or the empty source of a row recorded before V7 (unknown counts with the person — the same rule `gadak retro`'s sessions use). Agent cli reads are excluded on purpose: a terminal `gadak issue` run is not the reader returning. RecentVisits' epoch clause for the same reason — a visit from a replaced origin names a key the current origin may re-mint (GDK-418).

func (*DB) LinkTypePhrases added in v0.22.0

func (db *DB) LinkTypePhrases() map[string][2]string

LinkTypePhrases reads the cached link-type catalog as a name → (inward, outward) map, lowercased by name. The one owner of that SQL (GDK-1215): the detail response's phrase field and the CLI's human link line both render through origin.LinkPhrase and neither writes its own query any more. An unreadable or empty catalog answers nil — callers fall back to the wire pair wording, the contract the CLI had before the catalog existed (GDK-1734). Sources are not distinguished: a name two sources share is one entry, last row wins — same semantics the CLI's copy had.

func (*DB) MarkEpicParents added in v0.22.0

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

MarkEpicParents raises to hierarchy_level 1 every issue that is the parent of a standard (non-subtask) issue. It exists for Jira Server, which does not publish hierarchyLevel on issue types, so an epic arrives at level 0 and the epic_key walk finds nothing (GDK-1658). Deriving it from who has a standard child needs no extra request and no display name — and an epic with no children is exactly the case where epic_key answers nothing anyway. Levels the origin did state are never lowered.

func (*DB) MarkFeedRead

func (db *DB) MarkFeedRead(ctx context.Context, opts MarkFeedReadOpts) (MarkFeedReadResult, error)

MarkFeedRead upserts read receipts and returns the refreshed unread counts.

func (*DB) MirrorVersion added in v0.19.0

func (db *DB) MirrorVersion() string

MirrorVersion is this handle's own file's version. The mirror file is the single owner of "the mirror moved": every writer — the web UI's write-through, a CLI verb's RefreshIssue, the watch loop — reaches it by writing those bytes, so no writer has to remember to announce anything.

func (*DB) OpenPriorityDistribution added in v0.22.0

func (db *DB) OpenPriorityDistribution(ctx context.Context) (PriorityDistribution, error)

OpenPriorityDistribution is the census query: one GROUP BY over issues_raw, the physical table every issue writer touches — the same population doctor's issues count already walks, so the two numbers cannot disagree about what an issue is. COALESCE keeps a NULL status_category in the open side (it is certainly not done); done rows are excluded wherever they carry the category.

func (*DB) OptimizePlannerStats added in v0.24.3

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

OptimizePlannerStats rebuilds sqlite_stat1 for the whole mirror. The full issue pass calls it once at its end (internal/sync/run.go); it is safe on any handle at any time and idempotent. A failure is the caller's to log, never a reason to fail a sync: a missed refresh costs query plans, not data. ANALYZE writes no row for an empty table, so a fresh mirror's empty links table carries no statistics until it holds rows — which is exactly when they would say something.

func (*DB) PageAttachment added in v0.22.0

func (db *DB) PageAttachment(ctx context.Context, pageKey, attachmentID string) (sourceID, contentURL string, size int64, err error)

PageAttachment is the byte route's one lookup for a page attachment (GDK-1541): the source that owns it, the stored origin content URL, and the origin's size claim — AttachmentBelongs + AttachmentOrigin + AttachmentSize folded into one query, because the page path reaches the mirror through items (kind='page') rather than the issues join, and one round trip answers all three. The id rule matches theirs: external_id when set, else the store row id. ErrNotFound when the mirror lists no such attachment on that page — which is also the membership answer.

func (*DB) PageAttachmentIDs added in v0.23.0

func (db *DB) PageAttachmentIDs(ctx context.Context, sourceID, spaceKey string) (map[string]map[string]bool, error)

PageAttachmentIDs returns every mirrored page's attachment external ids in one space, keyed by the page's source id (items.external_id → set of attachments.external_id). It is the reconcile scan's comparison base for the search-side children.attachment expansion (GDK-1888): adding or deleting an attachment bumps no page version, so the id set is the only thing that can disagree. Every mirrored page of the space has an entry — an empty set is "no attachments", not absence, which is what makes a page whose attachments were all deleted comparable. Absence means the page is not mirrored (the stamp gate has already answered "fetch" for it). A row without an external id stays out of the sets: no origin id can ever match it, and the fetch the difference triggers rewrites the row with one.

func (*DB) PageAttachmentMime added in v0.23.0

func (db *DB) PageAttachmentMime(ctx context.Context, pageKey, attachmentID string) (string, error)

PageAttachmentMime is AttachmentMime's page half: the mirror's mime row for one page attachment, reached through the items/kind='page' join the page routes take. ErrNotFound is the membership answer, exactly as PageAttachment's.

func (*DB) PageCommentCount added in v0.19.0

func (db *DB) PageCommentCount(ctx context.Context) (int, error)

PageCommentCount returns the wiki-page share of the comments table: comment rows whose item is kind "page". It is the counterpart of IssueCommentCount — the two split what TableCount(ctx, "comments") mixes, so status can label each figure by meaning instead of one "comments" row that disagrees with the settings runtime on every mirror with wiki comments (GDK-628).

func (*DB) PageCommentStamps added in v0.19.0

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

PageCommentStamps returns one space's mirrored wiki-comment stamps keyed by the comment's source id (external_id → updated_at). The comments-only sync pass uses it the way PageStamps gates page bodies: a comment search hit the mirror already holds at the same stamp is inside cqlTime's overlap window, not a change, so its container page body is not re-read (GDK-1074 — a comment pinned inside the window re-read its page on every tick, forever).

func (*DB) PageDetail

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

PageDetail assembles one page. An unknown key returns (nil, nil).

func (*DB) PageLites

func (db *DB) PageLites(ctx context.Context) ([]PageLite, error)

PageLites returns every mirrored page, ordered by space then title.

func (*DB) PageStamps added in v0.14.2

func (db *DB) PageStamps(ctx context.Context, sourceID, spaceKey string) (map[string]PageStamp, error)

PageStamps returns the version stamp of every mirrored page in one space, keyed by the source's own page id (items.external_id). It exists so an incremental sync can answer "do I already hold this page?" from the mirror instead of spending a body fetch to find out — a search hit already carries version.number and version.when.

The mirror is a disposable cache, so a missing or malformed row simply means "fetch it": callers must treat an absent key as unknown, never as unchanged.

func (*DB) PageTopCommentIDs added in v0.23.0

func (db *DB) PageTopCommentIDs(ctx context.Context, sourceID, spaceKey string) (top map[string]map[string]bool, unknown map[string]bool, err error)

PageTopCommentIDs returns, for one space's mirrored pages, the external-id set of each page's top-level comments and the set of pages whose parent is still unknown — the comparison base for the search-side children.comment expansion (GDK-1888): deleting a comment bumps no page version, so the top-level id set is the only thing that can disagree. Every mirrored page of the space has a top entry (an empty set is "no top-level comments", not absence); replies stay out of the sets — the expansion lists top-level ids only, so a reply in the set would make every reply-bearing page compare unequal forever. A page with any NULL parent_id row lands in unknown: its set cannot be trusted, and the scan's answer is one comments-backfill fetch that heals the column (schemaV52) rather than a guess.

func (*DB) PageVersions added in v0.16.0

func (db *DB) PageVersions(ctx context.Context, itemID string) ([]PageVersion, error)

PageVersions returns stamps for itemID in number order. Missing item is empty.

func (*DB) PoolStats added in v0.16.0

func (db *DB) PoolStats() sql.DBStats

PoolStats reports the connection pool's state. A caller that has finished with a mirror can assert nothing is still checked out: a connection that outlives Close belongs to something still running, and under WAL it writes journal files back into a directory the caller may already have removed (GDK-270).

func (*DB) ProjectIssueCounts added in v0.19.0

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

ProjectIssueCounts returns the issue count per project key for one source's mirrored issues (GDK-973). Keys the source holds no issues under do not appear; callers read absence as zero. sourceID is the items.source_id slug ("jira"), so a Linear team key never counts toward a Jira scope verdict.

func (*DB) ProjectSource added in v0.17.0

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

ProjectSource is KeySource for a project key: the source_id owning issues.project_key in the mirror. Create has no issue key yet, so routing a Linear-team create uses this. Empty when the project is not mirrored; ErrKeyAmbiguous when Jira and Linear both mint it.

func (*DB) PruneConfluenceSpaces added in v0.13.0

func (db *DB) PruneConfluenceSpaces(ctx context.Context, sourceID string, keepKeys []string) (int, error)

PruneConfluenceSpaces deletes mirrored wiki pages (and their items, FTS rows, and cascaded children) whose space_key is not in keepKeys, then drops the matching spaces rows. keepKeys empty is a no-op so a zero-scope call cannot wipe the mirror. The returned count is the number of pages removed (space-row-only cleanup is not counted).

func (*DB) PruneLocalHistory added in v0.13.0

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

PruneLocalHistory deletes visit/search rows older than localRetention. Called from the same pass as tombstone expiry (DeleteItems).

func (*DB) PurgeIssueIDsOutsideNamespace added in v0.16.1

func (db *DB) PurgeIssueIDsOutsideNamespace(ctx context.Context, sourceID, ns string) (int, error)

PurgeIssueIDsOutsideNamespace deletes one source's issue rows whose item id does not start with ns+":". Upgrade path for GDK-241: a built-in mirror written before ids were namespaced holds `jira:N` rows whose keys the next sync re-inserts as `standalone-jira:N` — same (source_id, key), new id — which UNIQUE(source_id, key) rejects. The rows re-mirror immediately under the new namespace, so no tombstones are written. Children go via ON DELETE CASCADE; items_fts is contentless and needs the explicit delete.

func (*DB) PurgePageIDsOutsideNamespace added in v0.16.1

func (db *DB) PurgePageIDsOutsideNamespace(ctx context.Context, sourceID, ns string) (int, error)

PurgePageIDsOutsideNamespace is the wiki sibling of PurgeIssueIDsOutsideNamespace (GDK-344). A built-in page's key is its numeric external id, so a pre-namespace `confluence:N` row and the namespaced `standalone-confluence:N` insert share UNIQUE(source_id, key).

func (*DB) PutRecipe added in v0.17.0

func (db *DB) PutRecipe(ctx context.Context, name, query string) (Recipe, error)

PutRecipe inserts or overwrites a recipe. Same name keeps created_at and refreshes sql / updated_at. Name and SQL are validated here so every writer shares the rule.

func (*DB) PutSavedView

func (db *DB) PutSavedView(ctx context.Context, v SavedView) error

PutSavedView inserts or replaces a view. The caller owns id generation.

func (*DB) Query added in v0.17.0

func (db *DB) Query(query string, args ...any) (*sql.Rows, error)

Query runs a multi-row read on the same held connection (GDK-635 parent hierarchy hint). Same rule as QueryRow: do not open a second handle.

func (*DB) QueryActorPeople added in v0.17.1

func (db *DB) QueryActorPeople(ctx context.Context) ([]ActorPerson, error)

QueryActorPeople streams the assignee/reporter columns across all issues. It reads six narrow columns instead of the full IssueLite row set; the JQL resolver deduplicates in memory (people count ≪ issue count).

func (*DB) QueryIssueActors added in v0.17.0

func (db *DB) QueryIssueActors(ctx context.Context) ([]IssueActor, error)

QueryIssueActors returns every (issue, actor) touch, unordered. The set is small — bounded by comments + changelog + dev_links rows — and the caller (buildView) only folds it into a map, so no LIMIT.

func (*DB) QueryRow added in v0.17.0

func (db *DB) QueryRow(query string, args ...any) *sql.Row

QueryRow runs a single-row read on the mirror. It exists so a caller that already holds this connection (the CLI's staleness warning, GDK-314) does not open a second one — writes still go through the store API only.

func (*DB) QueryRowContext added in v0.19.2

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext is QueryRow with a deadline — for reads against a mirror another process owns, where a lock wait must not outlive the request (GDK-1032 cross-workspace hydration).

func (*DB) ReadOnly added in v0.17.2

func (db *DB) ReadOnly() (*sql.DB, error)

ReadOnly opens this DB's mirror with OpenReadOnly — mode=ro, local.db attached — for executing untrusted SQL (dashboard datasources). The single purpose is that a datasource statement cannot take the mirror's write lock or mutate a row no matter what the config contains: the "writes pass through origin" invariant's integrity axis for arbitrary SQL.

func (*DB) RecentVisits added in v0.17.0

func (db *DB) RecentVisits(ctx context.Context, limit int) ([]RecentVisit, error)

RecentVisits lists the distinct (kind, key) pairs newest-first, at most limit: docs/MIRROR.md's "recently viewed" recipe (MAX(viewed_at) GROUP BY key) as a typed accessor, both kinds at once. It carries History's epoch clause for the same reason History does: after a workspace changes origin, a retired pair names a key the new origin can mint (GDK-418), and this list exists precisely so its reader goes on to open those keys.

func (*DB) Recents added in v0.16.0

func (db *DB) Recents(ctx context.Context, kind string) ([]Recent, error)

Recents returns recent-use rows newest-first. Empty kind lists every kind.

func (*DB) Recipe added in v0.17.0

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

Recipe looks up one named recipe. Unknown name is ErrNotFound.

func (*DB) RecipeNames added in v0.17.0

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

RecipeNames is the saved-name list a missing-name error quotes.

func (*DB) Recipes added in v0.17.0

func (db *DB) Recipes(ctx context.Context) ([]Recipe, error)

Recipes lists every recipe, newest update first.

func (*DB) RecomputeEpicKeys added in v0.17.1

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

RecomputeEpicKeys rewrites issues.epic_key for the whole table. Full sync calls this once after every page has been upserted; per-batch upserts only recompute the batch and its parent-chain dependents (GDK-755).

func (*DB) RecomputeOpenBlockers added in v0.21.0

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

RecomputeOpenBlockers rewrites open_blockers for every issue of every source. A full sync calls this once after the last page, beside RecomputeEpicKeys: page-scoped recomputes cannot see a link the origin added to an issue no page carried. The walk itself is recomputeOpenBlockersAllSources — the same function the v43 migration hook's closing sweep runs, so the two cannot disagree (GDK-1576).

func (*DB) RecordAgentWrite added in v0.22.0

func (db *DB) RecordAgentWrite(ctx context.Context, key, verb, source string) error

RecordAgentWrite appends one row to local.agent_writes (GDK-1440): a write the calling surface landed at the origin. One row per accepted write — a refused or dry-run write never reaches this. When the write lands while a person session is open (within SessionGap of its end), it also stamps that session's first_write_at, keeping the earliest.

func (*DB) RecordRecent added in v0.16.0

func (db *DB) RecordRecent(ctx context.Context, kind, value string) (Recent, error)

RecordRecent puts value at the front of kind (de-dup, cap recentCap). Empty kind or value is refused. Kind is an opaque string — same names the web helper already used (assignee, transition:<project>, create-type:<project>, …).

func (*DB) RecordReconcile added in v0.21.0

func (db *DB) RecordReconcile(ctx context.Context, sourceID string, r ReconcileStats) error

RecordReconcile stores one two-way reconcile pass's tally. It is a separate write from RecordSync because the reconcile runs after it: the watermark and last_error belong to the search pass, and the counts belong to the key scan that followed. Like RecordSync it never bumps `version` — a reconcile that changed no rows must leave the ETag alone, and the upserts and deletes it did make bumped it themselves.

func (*DB) RecordSearch added in v0.13.0

func (db *DB) RecordSearch(ctx context.Context, query string, resultCount int, openedKind, openedKey string) (Search, error)

RecordSearch appends one search. openedKind/openedKey may both be empty, or both set to the item opened from this search.

func (*DB) RecordSync

func (db *DB) RecordSync(ctx context.Context, sourceID string, r SyncResult) error

RecordSync stores the run's bookkeeping. It does not bump `version`: a run that changed no rows must leave the ETag alone. A successful run advances first_sync_at (once) and sync_count.

func (*DB) RecordVisit added in v0.13.0

func (db *DB) RecordVisit(ctx context.Context, kind, key, source string) (Visit, error)

RecordVisit appends one view. Same (kind, key) twice is two rows. The insert uses a dedicated local.db connection so a writer holding the mirror (BEGIN IMMEDIATE / _txlock=immediate) does not block recording (GDK-753). Reads that join visits to the mirror stay on the ATTACH path. source is decided here, once, from the caller's identity: the CLI passes cli, the server passes ui — never anything a request body named.

func (*DB) RecordWhoAmI added in v0.22.0

func (db *DB) RecordWhoAmI(w config.WhoAmI) error

RecordWhoAmI stamps this workspace's identity into local.me (GDK-1438). The row is the one local.my_open / local.handed_off match against, so this is what makes "select * from my_open" answerable without a :me parameter.

Idempotent and cheap: the common case is a rewrite of identical values. An empty identity is still written — clearing a credential must clear the answer, not leave the previous person's rows looking like mine.

func (*DB) ReingestCustom

func (db *DB) ReingestCustom(ctx context.Context, specs []fields.SpecIDs, bodyFieldIDs []string) (int, error)

ReingestCustom recomputes issues.custom and the FTS body from the stored raw JSON — no network. Returns the number of issues rewritten.

func (db *DB) RemoteLinks(ctx context.Context, key string) ([]RemoteLink, error)

RemoteLinks reads one issue's mirrored remote links (GDK-1032). An issue with none — or one this mirror does not carry — is an empty list, not an error: a pointer list is a read, and callers print what is there.

func (*DB) ReplaceAgile added in v0.22.0

func (db *DB) ReplaceAgile(ctx context.Context, sourceID string, boards []BoardRow, sprints []SprintRow) error

ReplaceAgile writes the board and sprint listing for a source, wholesale: what the origin no longer lists is gone from the mirror. Both are cheap full listings, so there is no incremental path to drift from (GDK-1654).

It also re-derives every issue row's sprint_state from the sprint rows it just wrote (GDK-1661): the denormalized column is projected from the issue payload, and closing a sprint moves no `updated` on the done issues that stay in it, so the issue pass can never refresh it — the sprint listing is the only observation path the state change has. A correlated subquery, not UPDATE … FROM: the driver's SQLite version is not pinned. An issue whose sprint_id has no sprints row (a board list the credential cannot read) is untouched — the projected value stays as the answer.

func (db *DB) ReplaceDevLinks(ctx context.Context, key string, update DevLinksUpdate) error

ReplaceDevLinks swaps one issue's dev_links rows for a successful origin answer — the mirror-refresh half of a dev-link write-through (GDK-497). Never a source of truth: the same rows are rebuilt by any later sync. update is a complete pull-request answer (empty Links drains the PR rows — GDK-580); deployment/build rows are not part of a dev-status answer and survive, written only by `gadak dev deploy`/`dev build` (GDK-592).

func (*DB) ReplaceFieldUsage

func (db *DB) ReplaceFieldUsage(ctx context.Context, rows []FieldUsageRow) error

ReplaceFieldUsage replaces the entire field_usage table.

func (*DB) ReplacePageVersions added in v0.16.0

func (db *DB) ReplacePageVersions(ctx context.Context, itemID string, vers []PageVersion) error

ReplacePageVersions writes the complete stamp list for one item. The caller must have a successful full listing; an empty slice clears stored rows. Re-running with the same numbers is a no-op on cardinality (PK upsert).

func (*DB) ReplaceProjectVersions added in v0.17.0

func (db *DB) ReplaceProjectVersions(ctx context.Context, projectKey string, rows []VersionRow) error

ReplaceProjectVersions upserts one project's version catalog and deletes rows for that project whose id is no longer in the catalog. The catalog is the origin; this table is a cache (GDK-532). An empty list clears the project. Rows with an empty id are skipped (no join key).

func (db *DB) ReplaceRemoteLinks(ctx context.Context, key string, update RemoteLinksUpdate) error

ReplaceRemoteLinks swaps one issue's remote_links rows for a successful origin answer — the mirror-refresh half of a remote-link write-through (GDK-1032). Same never-a-source-of-truth contract as ReplaceDevLinks.

func (*DB) ReplaceSourceQueries added in v0.13.0

func (db *DB) ReplaceSourceQueries(ctx context.Context, sourceID string, queries []SourceQuery) error

ReplaceSourceQueries swaps one source's named queries in a single write. An empty list clears that source (the account deleted every filter).

func (*DB) ResetForNewOrigin added in v0.17.0

func (db *DB) ResetForNewOrigin(ctx context.Context, sourceIDs []string) (OriginReset, error)

ResetForNewOrigin is the one owner of "this workspace's origin is being replaced". Both conversion surfaces reach it through originbind.DropBuiltInProjection, so the decision cannot exist on the CLI path and not the HTTP one (GDK-247).

One transaction: a conversion that dropped the mirror but left the feed marks behind would be the same class of half-state this function exists to remove.

func (*DB) SaveDashboard added in v0.17.2

func (db *DB) SaveDashboard(ctx context.Context, name, config string) (Dashboard, error)

SaveDashboard inserts a dashboard, or updates the row that already owns name (keeping its id and created_at). The id is minted here so the CLI and the API cannot disagree about who owns id generation. Config is stored verbatim; validation of the document is internal/dashboards' job, at every writer that accepts one from a user.

func (*DB) SavedViews

func (db *DB) SavedViews(ctx context.Context) ([]SavedView, error)

func (*DB) ScanFieldFill

func (db *DB) ScanFieldFill(ctx context.Context, fn func(projectKey string, fieldVals map[string]json.RawMessage) error) error

ScanFieldFill streams every issue's project key and the fields object from stored raw JSON. Rows with empty or unparseable raw are skipped (older rows). fn receives field id → raw value for custom and system fields present in raw.

func (*DB) SchemaAudit added in v0.17.0

func (db *DB) SchemaAudit(ctx context.Context) (SchemaAuditResult, error)

SchemaAudit compares the open mirror against a fresh :memory: database that ran this build's migrate() path. It issues only reads against the open file. It is a doctor entry point, not part of Open: running migrate() on :memory: on every command would be wasted work.

func (*DB) SchemaVersion

func (db *DB) SchemaVersion() int

SchemaVersion is the migration level this binary applied.

func (*DB) Search

func (db *DB) Search(ctx context.Context, query string, limit int) (SearchResult, error)

Search runs a key lookup (when the query looks like a key) then an FTS5 query over titles, labels, bodies and comment text. Key hits are reserved at the front of Keys/Pages so FTS cannot drop them when filling limit. Bare terms are rewritten as quoted prefix queries (see ftsPrefixQuery). A query FTS5 cannot parse is retried as a literal phrase rather than surfaced as an error, because this is fed raw user input. limit applies to the combined result (key hits + FTS), with key hits taking slots first.

func (*DB) SearchExplain added in v0.15.0

func (db *DB) SearchExplain(ctx context.Context, query string, limit int) (SearchResult, error)

SearchExplain is Search plus a per-hit reason list. The FTS query is the same; only the returned Explain slice is extra.

func (*DB) SetFavorite

func (db *DB) SetFavorite(ctx context.Context, key string, on bool) error

SetFavorite adds or removes a favorite issue key.

func (*DB) SetLastNotifiedAt

func (db *DB) SetLastNotifiedAt(ctx context.Context, sourceID, at string) error

SetLastNotifiedAt advances the OS-notification watermark. Never touches feed_reads.

func (*DB) SetSearchOpened added in v0.13.0

func (db *DB) SetSearchOpened(ctx context.Context, id int64, kind, key string) (Search, error)

SetSearchOpened stamps the item opened from an existing search row.

func (*DB) SetSpaceWatermark added in v0.13.0

func (db *DB) SetSpaceWatermark(ctx context.Context, sourceID, key, watermark string) error

SetSpaceWatermark writes one space's incremental floor. An unknown key is inserted so a just-scoped space can be stamped after its first successful pass without a separate UpsertSpaces.

func (*DB) SetWatch

func (db *DB) SetWatch(ctx context.Context, key string, on bool) error

SetWatch adds or removes a watched issue key.

func (*DB) SourceQueries added in v0.13.0

func (db *DB) SourceQueries(ctx context.Context, sourceID string) ([]SourceQuery, error)

SourceQueries returns one source's named queries, starred first then by name.

func (*DB) SprintBurnup added in v0.22.0

func (db *DB) SprintBurnup(ctx context.Context, sprintID int64, now time.Time) (BurnupDoc, error)

SprintBurnup reconstructs the sprint's scope/started/completed series from the mirror's own rows. Nothing is stored — data-model.md keeps time-in-status a computed answer, and the daily buckets are the same class of question (GDK-591's rule, one window wider).

The walk is a state replay, not a tally: per issue it replays sprint membership (field='sprint' changelog rows — arrival is the id appearing in to_id, departure its disappearance, which reads both origin shapes the carry-over rule reads) and status (field='status' rows mapped through the status id → category catalog, never a display name), then evaluates both at each day boundary. That is why scope can dip and completed can hold while scope does: both are "what was true that day", not running totals.

`now` is an input so tests and the server agree on which day an open sprint's series ends on.

func (*DB) Sprints added in v0.22.0

func (db *DB) Sprints(ctx context.Context) ([]SprintRowWithCount, error)

Sprints lists the mirror's sprints, active first, then future, then closed — the order a person reads a sprint list in (GDK-1654). Ordering is by the stored lowercase state, never a display name.

func (*DB) StatusCategories added in v0.17.0

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

StatusCategories is the mirror's status id -> category map: the cached origin catalog (status_catalog, written by every sync pass) overlaid on the reconstruction from issue rows that carry one — the same query loadDeriveContext runs for `issue --derive`, kept so a mirror migrated to the catalog but not yet re-synced still resolves what it can. Durations needs this to walk the changelog, which stores bare ids.

func (*DB) SyncProgress added in v0.22.0

func (db *DB) SyncProgress(ctx context.Context) ([]SyncProgressRow, error)

SyncProgress returns the live rows only — liveness (updated_at within the window of now) is decided here, inside the store, so no reader re-derives it. Ordered by start for stable presentation.

func (*DB) SyncRuns

func (db *DB) SyncRuns(ctx context.Context, sourceID string, limit int) ([]SyncRun, error)

SyncRuns returns the newest runs first, at most limit.

func (*DB) SyncState

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

SyncState reads the state for one source. A source that has never synced returns a zero state, not an error.

func (*DB) TableCount

func (db *DB) TableCount(ctx context.Context, table string) (int, error)

TableCount returns SELECT COUNT(*) for a fixed known table name used by status and doctor. Only whitelisted table names are accepted.

func (*DB) TouchSyncProgress added in v0.22.0

func (db *DB) TouchSyncProgress(ctx context.Context, sourceID string, fetched int, total *int) error

TouchSyncProgress advances the heartbeat after a committed page. total nil means this call has no denominator and the stored one, if any, is kept — the Jira reconcile phase resets its count to unknown mid-pass and must not wipe the total the search phase learned. A row that no longer exists (the pass already ended) matches zero rows; that is not an error.

func (*DB) UpsertIssues

func (db *DB) UpsertIssues(ctx context.Context, b Batch) (int, error)

UpsertIssues writes one page of sync output in a single transaction and returns how many items it actually changed. Derived fields are recomputed from the batch's changelog, never carried over (contracts/sync.md invariant 5).

An item whose updated_at is unchanged is skipped whole — children, FTS and the version counter included — unless Batch.Force is set. That is what makes an incremental re-run over the watermark overlap window a no-op.

func (*DB) UpsertPages

func (db *DB) UpsertPages(ctx context.Context, records []PageRecord) (int, error)

UpsertPages writes document records in a single transaction and returns how many items it actually changed. A page whose stored body, meta and comments match the incoming record is skipped (no version bump). Comment-only edits still bump because comments are part of the compare — that is the comments- only trap the old always-rewrite path existed to close.

func (*DB) UpsertSource

func (db *DB) UpsertSource(ctx context.Context, s Source) error

UpsertSource records a connector instance. Credentials never come near it (Constitution Article 8).

func (*DB) UpsertSpaces

func (db *DB) UpsertSpaces(ctx context.Context, sourceID string, rows []SpaceRow) error

UpsertSpaces writes wiki space rows (key → name/kind/homepage_id) for a source. Empty name/kind/homepage_id on conflict keeps the previous value so page-hit upserts (name only) do not wipe kind or homepage filled by a full space listing or per-space GET.

func (*DB) UserCatalog added in v0.17.0

func (db *DB) UserCatalog(ctx context.Context) ([]UserAccount, error)

UserCatalog reads the cached origin account catalog (GDK-590): every account sync has seen, with the origin's account_type spelling. Callers judge bots through the connector's one judgement function, never here — the store is source-neutral.

func (*DB) VisitedKeys added in v0.20.0

func (db *DB) VisitedKeys(ctx context.Context, kind string, limit int) ([]RecentVisit, error)

VisitedKeys is RecentVisits narrowed to one kind — the set a list needs to mark rows already opened (GDK-1344), newest first. The cap is the caller's; the list asks for the whole set once and answers per row from a map.

func (*DB) Watches

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

func (*DB) WhoAmI added in v0.22.0

func (db *DB) WhoAmI() config.WhoAmI

WhoAmI reads back the recorded identity. Used by the CLI's status surface and by tests; a missing row (a local.db older than V8, or one this build could not migrate) answers the zero value rather than an error, the same bias every other local.db read has.

func (*DB) WriteBusyRetries added in v0.16.0

func (db *DB) WriteBusyRetries() uint64

WriteBusyRetries is how many times write() has retried SQLITE_BUSY (5 or 517) on this handle. Same shape as PoolStats: a cheap accessor, no logs.

type Dashboard added in v0.17.2

type Dashboard struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Config    json.RawMessage `json:"config"`
	CreatedAt string          `json:"created_at,omitempty"`
	UpdatedAt string          `json:"updated_at,omitempty"`
}

Dashboard is one row of local.dashboards (GDK-781). Config is the {html, datasources} document internal/dashboards owns; the store keeps it as raw bytes so a newer config shape round-trips through an older binary.

type DeriveInput

type DeriveInput struct {
	// CreatedAt is the item's creation stamp (ISO-8601 UTC). An issue born
	// into an in-progress status has no transition to find, so its start is
	// its creation — see the started_at rule below.
	CreatedAt string
	// NoHistory says the origin supplies no changelog at all (Linear), so an
	// empty Changelog carries no information about the initial status and the
	// born-in-progress rule must not guess from CurrentCategory.
	NoHistory       bool
	Changelog       []ChangeEntry
	Categories      map[string]string // status id -> new | inprogress | done
	CurrentCategory string            // the issue's category right now
	Priority        string
	Priorities      []string // site priority names, most urgent first
	Comments        []Comment
	Links           []Link
	// UpdatedAt is the item's updated stamp (items.updated_at). It feeds
	// last_activity_at — the mirror's own notion of when the origin last
	// touched the issue, which can outrank every changelog entry.
	UpdatedAt string
	// StartedAtHint / ResolvedAtHint are the flow stamps an origin with no
	// changelog carries on the issue itself (Linear: Issue.startedAt, and
	// completedAt — else canceledAt — as the finish), ISO-8601 UTC or empty.
	// They are consulted only under NoHistory: an origin that supplies a
	// changelog derives both columns from transitions and ignores them. They
	// are stamps, not history — status_changed_at, reopen_count and
	// reopened_at never come from them, and the undone-resolution and
	// positive-span rules below still run after them.
	StartedAtHint  string
	ResolvedAtHint string
}

DeriveInput is everything the derived-field rules need. Changelog entries carry only status ids, so the id -> category map has to come from the site's status list, which the connector supplies per batch.

type Derived

type Derived struct {
	StatusChangedAt   *string
	ResolvedAt        *string
	ReopenCount       int
	ReopenedAt        *string
	ReopenReason      string
	AssigneeChangedAt *string
	CommentCount      int
	PriorityRank      int
	ClonedFrom        string
	// StartedAt is the first transition into an in-progress category. Nil
	// when the issue never entered progress (cycle_hours is nil with it).
	StartedAt *string
	// CycleHours is ResolvedAt minus StartedAt in hours, kept only while the
	// issue is done now and the span is positive — the CycleTimeP85Hours
	// rule, stored instead of walked. Nil otherwise.
	CycleHours *float64
	// CarryoverCount is how many times the issue was carried into a sprint
	// after the first — the number of distinct sprints it has ever entered,
	// minus one. Nil, never 0, when the origin supplies no changelog: an
	// issue that was never carried and an issue whose history cannot be read
	// are different answers, and the reopen columns' plain int does not
	// distinguish them (GDK-1694, and GDK-1690's rule).
	CarryoverCount *int
	// FirstSprintID / FirstSprintAt are the first sprint the issue entered
	// and when. The scope-creep question — was this added after the sprint
	// began? — is FirstSprintAt against that sprint's start_at, so the stamp
	// is the column with leverage, not the count. The id lives in the
	// sprints(source_id, id) space.
	FirstSprintID *int64
	FirstSprintAt *string
	// BlockedHours is the time the issue has spent flagged, in hours — every
	// closed flag interval summed (GDK-1449). A flag still up does not
	// contribute: only a clear closes an interval, so the number never moves
	// while the user watches it. 0.0 with a changelog and no flag rows means
	// never flagged; nil, never 0, under NoHistory — the carryover_count
	// doctrine: never blocked and cannot be read are different answers.
	BlockedHours *float64
	// BlockedSince is the open flag interval's start — when the issue was
	// last flagged and never unflagged. Nil when no flag is up, and nil under
	// NoHistory with BlockedHours (an origin that cannot say how long cannot
	// say since when). A stamp, not a live duration: aging against it is the
	// reader's query, and the flag's own age is `now − blocked_since`, which
	// is why the stamp is the column.
	BlockedSince *string
	// LastActivityAt is the newest of the item's updated stamp, the newest
	// changelog entry and the newest comment. Nil when all three are absent.
	// ISO-8601 UTC strings compare lexicographically, so "newest" is a string
	// max. Not a live duration: it is a stamp, and aging against it is the
	// reader's query.
	LastActivityAt *string
}

Derived holds the columns gadak computes because the source does not provide them. Rules are documented in docs/DERIVE.md, and a test there requires every field of this struct to appear in that file.

func Derive

func Derive(in DeriveInput) Derived

Derive computes every derived field in one pass over the issue's changelog. A status id missing from the category map counts as not-done, which can only ever miss a reopen — never invent one.

type Detail

type Detail struct {
	// JSON alias "key" is added by issueDoc / detailResponse / AliasIssueKey,
	// not by MarshalJSON on this type: an anonymous Marshaler embed would
	// replace the whole `gadak issue --json` object (GDK-255).
	IssueKey       string          `json:"issue_key"`
	DescriptionADF json.RawMessage `json:"description_adf"`
	// DescriptionText is items.body_text. Linear (and any source that does not
	// store ADF) lands markdown/plain here; surfaces fall back to it when
	// DescriptionADF is empty. Never stuff markdown into DescriptionADF.
	DescriptionText string `json:"description_text,omitempty"`
	// DescriptionMD is the markdown an editor opens with — adf.Present's
	// Source, the one owner the web and the CLI share (GDK-1394). Derived on
	// read, never stored: the mirror keeps the origin's shape.
	DescriptionMD string             `json:"description_md,omitempty"`
	Comments      []DetailComment    `json:"comments"`
	Attachments   []DetailAttachment `json:"attachments"`
	History       []DetailChange     `json:"history"`
	LinkedIssues  []DetailLink       `json:"linked_issues"`
	// RefPages are wiki pages this issue's body/comments mention (item_refs,
	// target_kind=page). Only pages present in the mirror; empty omitted.
	RefPages []PageLite `json:"ref_pages,omitempty"`
	// BacklinkPages are wiki pages that mention this issue key. Empty omitted.
	BacklinkPages []PageLite `json:"backlink_pages,omitempty"`
	// Custom is the issue's full alias→value map. List rows strip body-role
	// values (they can be document-sized); detail is where they surface.
	Custom map[string]any `json:"-"`
	// Created is items.created_at — the origin stamp Durations measures the
	// wait span from. Internal like Custom: the wire already carries the
	// lites' created_at, and the detail response exposes only the derived
	// spans (wait_ms / progress_ms), not this raw input.
	Created string `json:"-"`
	// DevLinks are the development-panel links (GDK-497), newest first.
	DevLinks []DevLink `json:"dev_links"`
	// Refs are cross-workspace / external pointers (GDK-1032). Hydration —
	// the target's live state out of that workspace's own mirror — is the
	// server's job, not this loader's: it opens a second mirror file.
	Refs []RemoteLink `json:"refs,omitempty"`
}

Detail is everything the on-demand detail view needs, assembled from the mirror with no call to the source.

type DetailAttachment

type DetailAttachment struct {
	ID         string `json:"id"`
	ExternalID string `json:"external_id"`
	Filename   string `json:"filename"`
	MimeType   string `json:"mime_type"`
	Size       int64  `json:"size"`
	Author     string `json:"author,omitempty"`
	AuthorID   string `json:"author_id,omitempty"`
	CreatedAt  string `json:"created_at"`
	URL        string `json:"url,omitempty"`
}

DetailAttachment is metadata only; the handler turns ExternalID into the content proxy path. URL is the origin content URL when stored (Linear); empty for Jira.

type DetailChange

type DetailChange struct {
	At        string `json:"at"`
	Author    string `json:"author"`
	AuthorID  string `json:"author_id,omitempty"`
	Field     string `json:"field"`
	FromValue string `json:"from_value"`
	FromID    string `json:"from_id"`
	ToValue   string `json:"to_value"`
	ToID      string `json:"to_id"`
}

DetailChange is one history row. The ids come along because display values are localized: a caller that wants the `from_category` / `to_category` the detail contract allows has to resolve them from an id, never from a name.

type DetailComment

type DetailComment struct {
	ID         string          `json:"id"`
	ExternalID string          `json:"external_id"`
	Author     string          `json:"author"`
	AuthorID   string          `json:"author_id"`
	BodyADF    json.RawMessage `json:"body_adf"`
	Body       string          `json:"body"`              // flattened; the client's fallback when ADF will not render
	BodyMD     string          `json:"body_md,omitempty"` // adf.Present Source (GDK-1394)
	CreatedAt  string          `json:"created_at"`
	UpdatedAt  string          `json:"updated_at"`
	// VisibilityType/VisibilityValue are empty when the origin sent no
	// restriction. JsdPublic is nil when the jsdPublic key was absent.
	VisibilityType  string `json:"visibility_type"`
	VisibilityValue string `json:"visibility_value"`
	JsdPublic       *bool  `json:"jsd_public"`
}

DetailComment is one comment as the detail panel renders it.

type DetailLink struct {
	Key            string `json:"key"`
	Type           string `json:"type"`
	Direction      string `json:"direction"`
	Summary        string `json:"summary"`
	StatusCategory string `json:"status_category"`
}

DetailLink is an edge plus whatever the mirror knows about the far side. A target outside the mirror keeps an empty summary and category.

type DevLink struct {
	Kind       string // pullrequest | deployment | build (GDK-592)
	ExternalID string
	URL        string
	Title      string
	// Status is the stored form of the origin's OPEN|MERGED|DECLINED
	// vocabulary (lowercase). Produced by jira.DevPRStatus.Stored();
	// unknown origin tokens stay the lowercased payload.
	Status string
	// Author is the pull request's author (login). Actor/ActorName are who
	// wrote the link (issuetap's X-Issuetap-Actor accountId and display
	// name). Different axes — a bot links a human's PR — never merged
	// (GDK-589). Branch is the PR head ref. All ” when the origin sent
	// nothing (v33 columns are NOT NULL DEFAULT ”).
	Author    string
	Actor     string
	ActorName string
	Branch    string
	// Environment is a deployment row's target (production, staging, …)
	// — kind data with its own v36 column, never a title slot. Empty on
	// pull-request and build rows (GDK-592).
	Environment string
	UpdatedAt   string
}

DevLink is one development-panel link (GDK-497): a pull request the origin associates with the issue. URL is the idempotent key per issue.

type DevLinksUpdate added in v0.17.0

type DevLinksUpdate struct {
	Links []DevLink
}

DevLinksUpdate is a successful origin answer for one issue's development-panel links. The type exists only after a completed fetch (or a deliberate drain such as Cloud opt-out). Nil *DevLinksUpdate skips the rewrite; a non-nil value with empty Links drains. A fetch error cannot construct this value, so it cannot reach ReplaceDevLinks or the upsert rewrite (GDK-536 / GDK-580).

type DurationsInput added in v0.17.0

type DurationsInput struct {
	Created    string
	Changelog  []DetailChange
	Categories map[string]string // status id -> new | inprogress | done
	Now        time.Time
}

DurationsInput is everything the two lifecycle spans need. Changelog entries carry status ids only, so the id -> category map comes with them; Now is an input so the computation stays deterministic for tests and the server (GDK-590) can reuse it verbatim.

type FeedFocus

type FeedFocus string

FeedFocus is the focus tab the client sends: all | assignee | reporter | mention. "watched" is a reason, not a focus filter.

const (
	FeedFocusAll      FeedFocus = "all"
	FeedFocusAssignee FeedFocus = "assignee"
	FeedFocusReporter FeedFocus = "reporter"
	FeedFocusMention  FeedFocus = "mention"
)

type FeedIdentity

type FeedIdentity struct {
	AccountID   string
	Email       string
	DisplayName string // TokenOwner / display name for author matching
}

FeedIdentity is the local user, used for relevance and self-action exclusion. AccountID comes from config (Jira /myself); Email/DisplayName fall back when the mirror still only has display names on some rows.

func FeedIdentityOf added in v0.17.2

func FeedIdentityOf(cfg *config.Config) FeedIdentity

FeedIdentityOf maps the configured credential onto the feed identity. The sync notifier and the HTTP feed handler both build this — one owner, not two copies that can drift when the credential shape grows (GDK-820). A nil config reads as the zero identity, which the notifier's degraded path already treats as "no focus".

type FeedItem

type FeedItem struct {
	ID            int            `json:"id"`
	EventID       string         `json:"event_id"`
	IssueKey      string         `json:"issue_key"`
	Summary       string         `json:"summary"`
	CurrentStatus string         `json:"current_status"`
	EventType     string         `json:"event_type"`
	OccurredAt    *string        `json:"occurred_at"`
	ActorName     string         `json:"actor_name"`
	Payload       map[string]any `json:"payload"`
	Reasons       []string       `json:"reasons"`
	ReadAt        *string        `json:"read_at"`
}

FeedItem is one activity row the client renders (web/src/lib/types.ts FeedItem).

func (FeedItem) MarshalJSON added in v0.17.0

func (f FeedItem) MarshalJSON() ([]byte, error)

MarshalJSON adds `key` as an alias of `issue_key` (GDK-255).

type FeedOpts

type FeedOpts struct {
	Focus FeedFocus
	Limit int
	Me    FeedIdentity
	// Now, when set, freezes the 30-day window for tests.
	Now time.Time
}

FeedOpts configures a personal-feed query.

type FeedResult

type FeedResult struct {
	Items        []FeedItem       `json:"items"`
	UnreadCounts FeedUnreadCounts `json:"unread_counts"`
}

FeedResult is GET feed/ response body (without the outer wrapper keys).

type FeedUnreadCounts

type FeedUnreadCounts struct {
	All      int `json:"all"`
	Assignee int `json:"assignee"`
	Reporter int `json:"reporter"`
	Mention  int `json:"mention"`
}

FeedUnreadCounts is the badge counts per focus tab.

type FieldUsageRow

type FieldUsageRow struct {
	ProjectKey string
	Alias      string
	Filled     int
	Total      int
}

FieldUsageRow is one (project, alias) fill statistic from field_usage.

type ForwardMigration added in v0.22.0

type ForwardMigration int

ForwardMigration says whether an open may move a mirror's schema forward. It is a parameter at the open boundary because the decision has one owner outside this package: the caller knows whether this binary is a release or a checkout build (skillinstall.IsDevBuild), and store must not import that knowledge (dev-lockout, GDK-1687).

const (
	// MigrateForward migrates a mirror behind this build up to head. Release
	// builds pass this: an installed upgrade must keep working with no prompt.
	MigrateForward ForwardMigration = iota
	// RefuseForward refuses the open of a behind mirror with
	// SchemaForwardRefusedError — reading a v44 file with v47 code is not
	// safe either. A dev build passes this so one `gadak status` from a
	// checkout cannot lock the installed release out of the workspace
	// (the 2026-09-09 incident: 44→46, 11,880 issues, full re-sync to
	// recover).
	RefuseForward
)

func (ForwardMigration) String added in v0.22.0

func (f ForwardMigration) String() string

String names the policy in test failures and logs.

type HistoryItem added in v0.13.0

type HistoryItem struct {
	Type        string  `json:"type"` // visit | search
	ID          int64   `json:"id"`
	Kind        string  `json:"kind,omitempty"`
	Key         string  `json:"key,omitempty"`
	Query       string  `json:"query,omitempty"`
	ResultCount *int    `json:"result_count,omitempty"`
	OpenedKind  *string `json:"opened_kind,omitempty"`
	OpenedKey   *string `json:"opened_key,omitempty"`
	At          string  `json:"at"`
}

HistoryItem is one row of the mixed timeline (newest first).

type HistoryOpts added in v0.13.0

type HistoryOpts struct {
	// Kind is "issue", "page", or "search". Empty means all three.
	Kind   string
	Limit  int
	Cursor string
}

HistoryOpts filters the mixed visit+search timeline.

type HistoryPage added in v0.13.0

type HistoryPage struct {
	Items      []HistoryItem `json:"items"`
	NextCursor string        `json:"next_cursor,omitempty"`
}

HistoryPage is one cursor page of History.

type Issue

type Issue struct {
	ProjectKey     string
	IssueType      string
	IssueTypeID    string
	Status         string
	StatusID       string
	StatusCategory string // new | inprogress | done
	Priority       string
	PriorityID     string
	Assignee       string
	AssigneeID     string
	AssigneeEmail  string
	Reporter       string
	ReporterID     string
	ReporterEmail  string
	ParentKey      string
	// HierarchyLevel is the source-neutral tree rank of this issue's type
	// (e.g. epic=1, standard=0, sub-task=-1). Used to derive EpicKey.
	HierarchyLevel int
	Labels         []string
	Components     []string
	FixVersions    []string
	// FixVersionIDs is the same-order source ids for FixVersions (column
	// fix_version_ids). Join the versions catalog on these, not on names —
	// names rename. Empty slice stores "[]", same rule as FixVersions.
	FixVersionIDs   []string
	AffectsVersions []string
	EnvironmentText string
	Duedate         string
	Resolution      string
	ResolutionID    string
	// SprintID/SprintName/SprintState are the one sprint projected from the
	// origin's sprint payload — Jira's sprint array (active > future >
	// closed, then larger id), Linear's single cycle membership (the id
	// derived from the cycle UUID, the state from its dates; GDK-1667). Nil /
	// empty when Jira's site has no sprint field, the array is empty, an
	// element was not an object, or the Linear issue is in no cycle.
	SprintID    *int64
	SprintName  string
	SprintState string
	// SecurityLevelID/SecurityLevel are the origin issue security level.
	// Empty when the origin sent no security object (unrestricted, or a
	// source that has none — Linear). Id is the key; the name is
	// display-only and localizes. nz() stores empty as NULL.
	SecurityLevelID string
	SecurityLevel   string
	DescriptionADF  json.RawMessage
	Custom          map[string]any // mapped custom fields, keyed by config alias
	Raw             json.RawMessage
}

Issue is the tracker projection. `item_id`, `key`, `created_at`, `updated_at` are taken from the record's Item and every derived field is computed by the store, so a connector fills none of them.

type IssueActor added in v0.17.0

type IssueActor struct {
	IssueKey  string
	SourceID  string
	ActorID   string
	ActorName string
	Via       string // "comment" | "changelog" | "dev_link"
}

IssueActor is one touch of one issue by one account: a comment, a changelog entry, or a development-panel link (GDK-590). The union is also the issue_actors view, so `gadak sql` and documented recipes see the same axis the server builds members from.

type IssueLite

type IssueLite struct {
	IssueKey       string  `json:"issue_key"`
	Summary        string  `json:"summary"`
	ProjectKey     string  `json:"project_key"`
	IssueType      string  `json:"issue_type"`
	IssueTypeID    string  `json:"issue_type_id"`
	Status         string  `json:"status"`
	StatusID       string  `json:"status_id"`
	StatusCategory string  `json:"status_category"`
	Priority       *string `json:"priority"`
	// PriorityID is the stable Jira priority id (issues.priority_id). Empty
	// on rows a sync has not rewritten since the column was added — clients
	// fall back to the display name for those, the same way they do for a
	// missing status_id / issue_type_id.
	PriorityID    string  `json:"priority_id"`
	PriorityRank  int     `json:"priority_rank"`
	Assignee      *string `json:"assignee"`
	AssigneeID    *string `json:"assignee_id"`
	AssigneeEmail *string `json:"assignee_email"`
	Reporter      *string `json:"reporter"`
	ReporterID    *string `json:"reporter_id"`
	ReporterEmail *string `json:"reporter_email"`
	// EpicKey is the nearest hierarchy_level==1 ancestor (derived). Nil when
	// none. Distinct from ParentKey, which is the direct parent only.
	EpicKey *string `json:"epic_key"`
	// ParentKey is the direct parent issue key (source field), not the epic.
	ParentKey *string `json:"parent_key"`
	// HierarchyLevel is issues.hierarchy_level as stored (epic 1, standard
	// 0, sub-task −1). Projected, not recomputed.
	HierarchyLevel int      `json:"hierarchy_level"`
	Labels         []string `json:"labels"`
	Components     []string `json:"components"`
	FixVersions    []string `json:"fix_versions"`
	Duedate        *string  `json:"duedate"`
	Resolution     *string  `json:"resolution"`
	// ResolutionID is the stable Jira resolution id (issues.resolution_id).
	// Empty on rows a sync has not rewritten since the column was added —
	// the same contract as priority_id. Unresolved issues also store ”.
	ResolutionID    string  `json:"resolution_id"`
	CreatedAt       *string `json:"created_at"`
	UpdatedAt       *string `json:"updated_at"`
	StatusChangedAt *string `json:"status_changed_at"`
	ResolvedAt      *string `json:"resolved_at"`
	ReopenCount     int     `json:"reopen_count"`
	ReopenedAt      *string `json:"reopened_at"`
	ReopenReason    *string `json:"reopen_reason"`
	ClonedFrom      *string `json:"cloned_from"`
	// SourceProject is ClonedFrom's project prefix, precomputed because the
	// list filter groups by it.
	SourceProject *string `json:"source_project"`
	CommentCount  int     `json:"comment_count"`
	// Custom holds the configured field aliases from issues.custom. The server
	// spreads them into the response as top-level keys, which is where the client
	// reads severity and friends.
	Custom map[string]any `json:"custom,omitempty"`
	// Source is items.source_id (jira / linear / …). Write pickers key on it
	// so a Linear row does not consume a Jira catalog or credential.
	Source string `json:"source,omitempty"`
	// SprintID/SprintName/SprintState are the projected sprint (GDK-518).
	// Nil when the origin had none, the site has no sprint field, or the
	// row predates the next sync after v30.
	SprintID    *int64  `json:"sprint_id"`
	SprintName  *string `json:"sprint_name"`
	SprintState *string `json:"sprint_state"`
	// SecurityLevelID/SecurityLevel are the origin issue security level
	// (v32). Nil when the issue is unrestricted, the origin sent no
	// security object, or the row predates the next sync after v32.
	// Id is the key (names localize); the name is display-only.
	SecurityLevelID *string `json:"security_level_id"`
	SecurityLevel   *string `json:"security_level"`
	// URL is items.url — the origin's own page for the row, exactly as the
	// sync stored it: Jira writes <site>/browse/KEY, Linear the url its API
	// minted (workspace slug and title slug included), the built-in tracker
	// a relative /browse/KEY. It is the deep-link source for every origin
	// (GDK-1149): a Linear workspace has no site to join a key onto, and
	// sources.base_url carries no workspace slug. Clients accept only an
	// absolute http(s) value here — the same rule as `gadak open`.
	URL string `json:"url,omitempty"`
	// Flow columns (v43, Derive-owned — DERIVE.md). StartedAt is the first
	// in-progress transition; CycleHours is resolved−started kept only while
	// the issue is done now; LastActivityAt is the newest of item stamp,
	// changelog and comments; OpenBlockers counts inward blocking links whose
	// target is in the mirror and not done. Nil/0 mean "not observed", never
	// "unknown" — clients can filter on them directly.
	StartedAt      *string  `json:"started_at"`
	LastActivityAt *string  `json:"last_activity_at"`
	CycleHours     *float64 `json:"cycle_hours"`
	OpenBlockers   int      `json:"open_blockers"`
	// CarryoverCount is issues_raw.carryover_count (v48, Derive-owned —
	// DERIVE.md): distinct sprints the issue has ever entered, minus one.
	// Nil, never 0, on an origin that supplies no changelog (Linear) — the
	// column was written that way on purpose, and flattening it to 0 here
	// would tell a reader "never carried" where the mirror means "cannot be
	// read" (GDK-1711).
	CarryoverCount *int `json:"carryover_count"`
	// BlockedHours / BlockedSince are the flagged columns (v51, Derive-owned
	// — DERIVE.md): closed flag intervals summed in hours, and the open
	// interval's start. BlockedHours is nil only on an origin that supplies
	// no changelog (the same nil-vs-0 rule as CarryoverCount); 0 means never
	// flagged. BlockedSince is nil when no flag is up — a stamp, not a live
	// duration, so "how long blocked" is the reader's now − blocked_since.
	BlockedHours *float64 `json:"blocked_hours"`
	BlockedSince *string  `json:"blocked_since"`
}

IssueLite is the row shape the read API hydrates the client with. Field names are the ones web/src/lib/types.ts already parses (contracts/api.md, "IssueLite"): adding is safe, renaming is not.

func (IssueLite) MarshalJSON added in v0.17.0

func (l IssueLite) MarshalJSON() ([]byte, error)

MarshalJSON adds `key` as an alias of `issue_key` so JSON surfaces and SQL (`issues_full.key`) share a name (GDK-255). Derived at marshal time so a constructor cannot emit one without the other.

type IssueRecord

type IssueRecord struct {
	Item        Item
	Issue       Issue
	Comments    []Comment
	Attachments []Attachment
	Changelog   []ChangeEntry
	Links       []Link
	// Users feeds the account catalog cache. Unlike the child lists above it
	// merges rather than replaces: a row with an empty name or account_type
	// keeps what the catalog already knows (some payloads carry less than the
	// first one that mentioned the account).
	Users []UserAccount
	// DevLinks, when non-nil, is a complete origin answer (including
	// empty). Nil means the origin was not observed and existing rows
	// stay (GDK-536 / GDK-580).
	DevLinks *DevLinksUpdate
	// RemoteLinks follows the same nil-skips contract (GDK-1032).
	RemoteLinks *RemoteLinksUpdate
	// StartedAtHint / ResolvedAtHint carry the origin's own flow stamps into
	// Derive's NoHistory path (Linear: Issue.startedAt, and completedAt —
	// else canceledAt — as the finish). Inputs to the derive pass, not
	// stored columns: the mirror schema has no slot for the raw stamps, so
	// they re-arrive with every batch that carries the row.
	StartedAtHint  string
	ResolvedAtHint string
	// LinksPartial says the origin answer for Links was cut short, so an
	// absent link proves nothing. The store still replaces this issue's own
	// rows (it always has), but skips the far-end deletion links.go would
	// otherwise do — a truncated list must not delete another issue's rows
	// (GDK-1507). Only the Linear pass can set it: relations arrive over a
	// paged connection there, while a Jira issuelinks payload is whole.
	LinksPartial bool
}

IssueRecord is one item and everything hanging off it. Child lists are replaced wholesale on upsert, so a partial list would delete rows.

type Item

type Item struct {
	ID         string // "<source_id>:<external_id>"
	SourceID   string
	Kind       string // "issue" in v0.1
	ExternalID string
	Key        string // human-facing key, unique per source
	Title      string
	BodyText   string // flattened body, what FTS indexes
	Author     string
	AuthorID   string
	URL        string
	CreatedAt  string
	UpdatedAt  string
}

Item is the neutral spine row: anything with a title, body, author and timestamp fits it.

type ItemRef

type ItemRef struct {
	TargetKind string // "issue" | "page"
	TargetKey  string // issue key or page id (numeric string)
	Via        string // "url" | "text"
}

ItemRef is one outgoing reference from an item. Pure extraction returns these; the write path persists them into item_refs.

func ExtractIssueRefsFromPage

func ExtractIssueRefsFromPage(bodyADF, bodyText string, knownProjects map[string]bool) []ItemRef

ExtractIssueRefsFromPage finds issue keys in a page's ADF (URL paths) and plain body_text (bare keys filtered by knownProjects). Same key from both sources yields one row with via=url. knownProjects may be empty (no text hits).

func ExtractPageRefsFromIssue

func ExtractPageRefsFromIssue(bodyADF, bodyText string, commentBodies []string) []ItemRef

ExtractPageRefsFromIssue finds Confluence page IDs in an issue description (raw ADF + flattened text) and its comment bodies. Scanning ADF is what picks up link marks and inlineCards that PlainText drops — the same raw scan ExtractIssueRefsFromPage already does in the other direction. Both URL shapes use via=url. Duplicates collapse to one.

type Link struct {
	Type      string
	Direction string // inward | outward
	TargetKey string
}

Link is an edge out of an item. TargetKey may point outside the mirror.

type LinkType added in v0.21.0

type LinkType struct {
	ID      string
	Name    string
	Inward  string
	Outward string
}

LinkType is one row of the origin's issue-link-type catalog (Jira GET /issueLinkType; Linear has one, "blocks", so its connector attaches a synthetic row). The connector fetches it once per sync run and the store caches it in link_types — the same contract as status_catalog: origin reference data, a wipe costs one re-sync. ID is the stable key; Name/Inward/Outward are the display phrases, which localize per account.

type MarkFeedReadOpts

type MarkFeedReadOpts struct {
	EventIDs  []string
	IssueKeys []string
	All       bool
	Me        FeedIdentity
	Now       time.Time
}

MarkFeedReadOpts is POST feed/read/ body semantics.

type MarkFeedReadResult

type MarkFeedReadResult struct {
	Updated      int              `json:"updated"`
	UnreadCounts FeedUnreadCounts `json:"unread_counts"`
}

MarkFeedReadResult is POST feed/read/ response.

type OpenOptions added in v0.22.0

type OpenOptions struct {
	// ForwardMigration defaults to MigrateForward (the zero value), so
	// OpenOptions{} behaves exactly like Open.
	ForwardMigration ForwardMigration

	// BuildVersion is the caller's version string; it lands in
	// SchemaForwardRefusedError so the error says which build refused.
	BuildVersion string
}

OpenOptions is the open policy plus the facts the policy's errors print.

func DefaultOpenOptions added in v0.23.0

func DefaultOpenOptions() OpenOptions

DefaultOpenOptions is the process default Open and OpenArtifact apply — the policy a binary's main installed at boot (GDK-1687). The built-in origin reads it too, so "is this a dev build refusing forward moves" has one answer for both of a workspace's versioned files, gadak.db and issuetap.db, instead of two judgments that can drift (GDK-1967).

type OriginReset added in v0.17.0

type OriginReset struct {
	// Removed is table → rows deleted. Only tables whose rows named the
	// retired origin appear; the mirror's own cascade is not itemised.
	Removed map[string]int `json:"removed"`
	// RetiredHistory is visit and search rows still on disk but no longer in
	// the timeline: they name keys the new origin would resolve to other
	// issues. Readable with `gadak sql` (local.visits / local.searches).
	RetiredHistory int `json:"retired_history"`
	// OriginEpoch is the generation history is stamped with from now on.
	OriginEpoch int `json:"origin_epoch"`
	// SavedViews are authored views whose stored query mentions a project the
	// retired origin owned. Kept — the user wrote them — and named here,
	// because `project = STD` now means the new site's STD. A text match on
	// the opaque config: the web owns that shape, so this over-reports rather
	// than staying silent.
	SavedViews []string `json:"saved_views_naming_retired_projects"`
}

OriginReset is what a conversion took, so a surface can say it instead of leaving the user to discover an empty feed. Keyed by table rather than by field so a rule added later reports itself without a struct change.

func (OriginReset) MarshalJSON added in v0.17.0

func (r OriginReset) MarshalJSON() ([]byte, error)

MarshalJSON keeps Removed non-nil so `--json` never emits a bare null for a field a caller iterates.

func (OriginReset) String added in v0.17.0

func (r OriginReset) String() string

String renders the reset for a human: one line, empty when nothing went.

type Page

type Page struct {
	SpaceKey string
	ParentID string
	Version  int
	Status   string
	// Labels are source-neutral tag names (JSON array column). Empty slice is
	// stored as "[]", never NULL. Sync sorts alphabetically for determinism.
	Labels []string
	// BodyADF is the raw Atlas Document Format body for rendering. Empty when
	// the mirror only has flattened body_text (pre-v10 rows).
	BodyADF json.RawMessage
}

Page is the document projection (one row in the pages table). Field names match the projection columns, not any source API (same status as Issue).

type PageComment

type PageComment struct {
	Author    string          `json:"author"`
	CreatedAt string          `json:"created_at"`
	BodyADF   json.RawMessage `json:"body_adf"`
	BodyText  string          `json:"body_text"`
}

PageComment is one comment on a page detail response.

type PageDetail

type PageDetail struct {
	PageLite
	BodyADF json.RawMessage `json:"body_adf"`
	// BodyText is BodyADF flattened by adf.PlainText — the same walker FTS
	// indexes. Always present (empty when the body is empty) so a text client
	// does not have to parse ADF.
	BodyText string `json:"body_text"`
	// BodyMD is the markdown an editor opens with — adf.Present's Source,
	// placeholders included (GDK-1394/GDK-1396). Derived on read, never stored.
	BodyMD   string        `json:"body_md,omitempty"`
	Comments []PageComment `json:"comments"`
	// RefIssueKeys are issue keys this page's body mentions (item_refs). Only
	// issues present in the mirror, sorted ascending. Empty omitted.
	RefIssueKeys []string `json:"ref_issue_keys,omitempty"`
	// BacklinkIssueKeys are issue keys that mention this page. Empty omitted.
	BacklinkIssueKeys []string `json:"backlink_issue_keys,omitempty"`
	// Attachments are the page's rows in the shared attachments table
	// (GDK-1541), read with the same query the issue detail reads. Serialized
	// by the server into the wire shape the issue detail also carries —
	// json:"-" keeps this raw form off the wire.
	Attachments []DetailAttachment `json:"-"`
}

PageDetail is PageLite plus the raw ADF body, its plain-text form, and comments.

type PageLite

type PageLite struct {
	Key      string `json:"key"`
	Title    string `json:"title"`
	SpaceKey string `json:"space_key"`
	// SpaceName is the human-readable space title from the spaces table join.
	// Empty when no spaces row is mirrored for this key (never omitted in JSON).
	SpaceName string `json:"space_name"`
	// SpaceHomepageID is the content id of the space root page (spaces.homepage_id).
	// Empty when the space row is missing or homepage has not been learned yet.
	SpaceHomepageID string `json:"space_homepage_id"`
	ParentID        string `json:"parent_id"`
	Author          string `json:"author"`
	// AuthorID is items.author_id. Empty on legacy rows that only have a
	// display name — clients group by this when present and fall back to Author.
	AuthorID  string `json:"author_id"`
	UpdatedAt string `json:"updated_at"`
	Version   int    `json:"version"`
	URL       string `json:"url"`
	// Excerpt is a one-line body preview derived from body_adf (schema v15):
	// whitespace-normalized, at most 200 runes. Empty when the body is empty.
	Excerpt string   `json:"excerpt"`
	Labels  []string `json:"labels"`
}

PageLite is the list/search row for a mirrored wiki page. Field names are snake_case JSON to match IssueLite and the read API contract.

type PageRecord

type PageRecord struct {
	Item        Item
	Page        Page
	Comments    []Comment
	Attachments []Attachment
}

PageRecord is one document item plus its projection and comments. Comments and attachments are replaced wholesale on upsert, matching IssueRecord — the same attachments table, distinguished by item_id (GDK-1541).

type PageStamp added in v0.14.2

type PageStamp struct {
	Version   int
	UpdatedAt string
	SyncedAt  string
}

PageStamp is the mirror's record of one page's upstream identity: the source's version number and lastModified, plus this mirror's synced_at. The latter guards a reconcile against concurrent writes after its listing. Version and lastModified stay paired because a rollback can reuse a number.

type PageVersion added in v0.16.0

type PageVersion struct {
	Number     int
	CreatedAt  string
	AuthorID   string
	AuthorName string
	Message    string
	MinorEdit  bool
}

PageVersion is one history stamp on a wiki page. Bodies are never stored — only the number, when, who, the editor's note, and the minor-edit flag. Field names match the page_versions columns, not the Confluence payload.

type PriorityCount added in v0.22.0

type PriorityCount struct {
	Rank  int `json:"rank"`
	Count int `json:"count"`
}

PriorityCount is one row of the open-issue priority census (GDK-1413): how many open issues carry this priority_rank. Rank 0 is "unset" and is a row of its own on purpose — "72% 미설정" and "72%가 rank 1" are the same fact about an axis carrying no information, and folding unset into the total would hide it.

type PriorityDistribution added in v0.22.0

type PriorityDistribution struct {
	Rows []PriorityCount `json:"rows"`
	Open int             `json:"open"`
}

PriorityDistribution is the whole census: one row per distinct priority_rank among open issues, plus the total they sum to. Open keys on status_category (new|inprogress are open, done is not) — the category, never a status display name, which localizes per account and silently returns zero rows (my_open's rule).

func (PriorityDistribution) Concentrated added in v0.22.0

func (d PriorityDistribution) Concentrated() (row PriorityCount, pct int, ok bool)

Concentrated names the largest row when one priority value holds DominantSharePct or more of the open issues — the fact the doctor line states ("72%가 rank 1"), which is a census sentence, not a verdict on the workspace. ok=false when there are no open issues or the values are spread out, the healthy shapes both.

type Recent added in v0.16.0

type Recent struct {
	Kind   string `json:"kind"`
	Value  string `json:"value"`
	UsedAt string `json:"used_at"`
}

Recent is one (kind, value) pair in local.recents. Unlike visits, the same pair is one row: recording it again only moves used_at to now.

type RecentVisit added in v0.17.0

type RecentVisit struct {
	Kind     string `json:"kind"`
	Key      string `json:"key"`
	ViewedAt string `json:"viewed_at"`
}

RecentVisit is one (kind, key) pair folded to its newest visit — the row `gadak recents` prints. Unlike Visit there is no ID: dedup happened in SQL.

type Recipe added in v0.17.0

type Recipe struct {
	Name      string `json:"name"`
	SQL       string `json:"sql"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

Recipe is a named read-only SQL query in local.recipes (GDK-503).

type ReconcileStats added in v0.21.0

type ReconcileStats struct {
	At             string `json:"at,omitempty"`
	UpstreamKeys   int    `json:"upstream_keys"`
	MissingFetched int    `json:"missing_fetched"`
	GoneDeleted    int    `json:"gone_deleted"`
}

ReconcileStats is one two-way reconcile pass's tally: how many keys the origin holds in scope, how many of them the mirror was missing and this pass fetched, and how many mirror rows were gone upstream and deleted. UpstreamKeys is the number `gadak status` compares the mirror's own count against — the comparison that took a second machine to make in the field (GDK-1400).

func (ReconcileStats) Ran added in v0.21.0

func (r ReconcileStats) Ran() bool

Ran reports whether a reconcile pass has recorded a tally here.

type RemoteLink struct {
	ID           string `json:"id"`
	GlobalID     string `json:"global_id,omitempty"`
	Relationship string `json:"relationship,omitempty"`
	URL          string `json:"url"`
	Title        string `json:"title,omitempty"`
	Summary      string `json:"summary,omitempty"`
}

RemoteLink is one remote issue link (GDK-1032): a pointer at something outside the origin tracker. url is the identity; gadak://<ws>/<KEY> rows hydrate live from that workspace's own mirror.

type RemoteLinksUpdate added in v0.19.2

type RemoteLinksUpdate struct {
	Links []RemoteLink
}

RemoteLinksUpdate is a successful origin answer for one issue's remote links — same contract as DevLinksUpdate: nil skips the rewrite, non-nil with empty Links drains.

type SavedView

type SavedView struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Config    json.RawMessage `json:"config"`
	CreatedAt string          `json:"created_at"`
	UpdatedAt string          `json:"updated_at"`
}

SavedView is a user's stored filter set. Personal state is the only thing in this database a user would miss, so it is also the only thing `gadak export` has to dump (Constitution Article 1). Since GDK-105 it lives in local.db, which survives `rm gadak.db`.

type SchemaAuditResult added in v0.17.0

type SchemaAuditResult struct {
	Stamp     int      // PRAGMA user_version of the open file
	Supported int      // len(migrations) — the level this build writes
	Missing   []string // "table", "table.column", or a named index
	Extra     []string
}

SchemaAuditResult is the diagnosis of "does this file's sqlite_master match the schema this build migrates to?". Missing is the damage signal (expected tables/columns/views/indexes that are absent). Extra is informational leftover on the file.

func (SchemaAuditResult) OK added in v0.17.0

func (r SchemaAuditResult) OK() bool

OK reports whether the file is missing anything this build expects. Surplus objects do not fail the audit.

type SchemaForwardRefusedError added in v0.22.0

type SchemaForwardRefusedError struct {
	Path         string // the mirror file
	Have         int    // schema version found in the file
	Head         int    // schema version this build would migrate this file to, holds applied
	BuildVersion string // the dev build's own version string
	// FullHead is len(migrations) at refusal time. Greater than Head exactly
	// when a localCopyMigrations hold lowered the target below the build's
	// own head, and then the message says so: a "writes 52" with no word
	// about the hold reads like this build's head is 52 (GDK-1933).
	FullHead int
}

SchemaForwardRefusedError means this open refused to migrate a mirror forward because the binary is a dev build and the mirror may still belong to an installed release (dev-lockout). Migrating anyway would leave the file at a schema the release rejects with SchemaTooNewError — the lockout the refusal exists to prevent. Recognise it with errors.As.

func (*SchemaForwardRefusedError) Error added in v0.22.0

func (e *SchemaForwardRefusedError) Error() string

type SchemaTooNewError added in v0.17.0

type SchemaTooNewError struct {
	Path      string // the mirror file
	Have      int    // schema version found in the file
	Supported int    // highest schema version this build migrates to
}

SchemaTooNewError means the file was migrated by a gadak that reads a later schema than this build does — the app and the CLI ship as separately versioned formulae, so one build opening the mirror once is enough to lock the other out of that workspace (GDK-498).

It is a type, not a string, because more than one surface has to say the same true thing about it: nothing is lost, since the mirror is a cache the origin can rebuild. Recognise it with errors.As rather than matching text.

func (*SchemaTooNewError) Error added in v0.17.0

func (e *SchemaTooNewError) Error() string
type Search struct {
	ID          int64   `json:"id"`
	Query       string  `json:"query"`
	SearchedAt  string  `json:"searched_at"`
	ResultCount int     `json:"result_count"`
	OpenedKind  *string `json:"opened_kind"`
	OpenedKey   *string `json:"opened_key"`
}

Search is one append-only search execution. OpenedKind/OpenedKey name the item opened from that search, when one was.

type SearchExplain added in v0.15.0

type SearchExplain struct {
	Key    string   `json:"key"`
	Reason string   `json:"reason"`
	Field  string   `json:"field,omitempty"`
	Score  *float64 `json:"score,omitempty"`
}

SearchExplain is why one returned hit sits where it does. Reason is "key-exact", "key-prefix", or "fts". Field and Score are set only for fts (winning column and bm25). Filled only by SearchExplain; Search leaves Explain nil so the normal path does not allocate it.

type SearchMatch

type SearchMatch struct {
	Field   string `json:"field"`
	Snippet string `json:"snippet"`
}

SearchMatch says which FTS column matched and shows a plain-text snippet. Field is "title" | "labels" | "body" | "comment". Snippet has no HTML or highlight markers — the client highlights against its own query string.

type SearchResult

type SearchResult struct {
	Keys    []string               `json:"keys"`
	Pages   []PageLite             `json:"pages"`
	Total   int                    `json:"total"`
	Matches map[string]SearchMatch `json:"matches"`
	Explain []SearchExplain        `json:"explain,omitempty"`
	// ElapsedMS is the searchAll wall time in milliseconds. Search leaves it
	// 0 (omitted from JSON); SearchExplain fills it so --explain can name
	// the query cost without changing the default Search contract.
	ElapsedMS float64 `json:"elapsed_ms,omitempty"`
	// contains filtered or unexported fields
}

SearchResult is a kind-aware hit list. Keys are issue keys (key-lookup hits first, then FTS among issues); Pages are page hits in the same window. Total is the number of hits returned (keys + pages), matching the pre-R2 meaning of total = len(results after limit). Matches maps each returned issue or page key to the winning FTS column match when FTS contributed one.

type Session added in v0.22.0

type Session struct {
	StartedAt    string `json:"started_at"`
	EndedAt      string `json:"ended_at"`
	FirstWriteAt string `json:"first_write_at"`
	Visits       int    `json:"visits"`
}

Session is one row of local.sessions: a run of person reads no two of which are more than SessionGap apart (GDK-1439). Visits is the person-read count in the run; FirstWriteAt is the first recorded CLI write that landed inside it (GDK-1440), empty until one does.

type Source

type Source struct {
	ID      string // stable slug, e.g. "jira"
	Kind    string
	BaseURL string
}

Source is one configured connector instance.

type SourceQuery added in v0.13.0

type SourceQuery struct {
	ID          string          `json:"id"`
	SourceID    string          `json:"source_id"`
	ExternalID  string          `json:"external_id"`
	Name        string          `json:"name"`
	QueryText   string          `json:"query_text"`
	Config      json.RawMessage `json:"config"`
	Favourite   bool            `json:"favourite"`
	Owner       string          `json:"owner"`
	Applied     []string        `json:"applied"`
	Unsupported []string        `json:"unsupported"`
	UpdatedAt   string          `json:"updated_at"`
}

SourceQuery is a named query mirrored from a connector (Jira saved filter). Jira is the record: ReplaceSourceQueries rewrites one source's rows.

type SpaceRow

type SpaceRow struct {
	Key        string
	Name       string
	Kind       string
	HomepageID string
}

SpaceRow is one wiki space (key + human name + kind). Source-neutral: a connector maps its space listing or page-embedded space ref onto this. Kind is the source type string (e.g. "global", "personal"); empty is allowed when only a name is known from a page hit. HomepageID is the content id of the space root page when known; empty on page-hit upserts so they do not wipe a value filled by a space listing.

type Spans added in v0.17.0

type Spans struct {
	Wait     *time.Duration // created -> first entry into in-progress
	Progress *time.Duration // latest entry into in-progress -> done, or Now while in progress
}

Spans holds the two lifecycle spans `gadak issue` shows. nil means the changelog cannot answer: never entered progress (Wait), or no in-progress entry to measure from (Progress).

func Durations added in v0.17.0

func Durations(in DurationsInput) Spans

Durations computes the spans from the changelog — the same walk Derive does, with two questions asked of it. Nothing is stored: data-model.md keeps time-in-status deliberately absent, so this stays a query-time computation (GDK-591).

Progress measures from the latest in-progress entry, not the first: a reopened issue that re-enters progress restarts the clock, which pairs with "still in progress means until now" — first-entry would report the whole history of a reopened issue as one uninterrupted run.

func (Spans) Line added in v0.17.0

func (d Spans) Line() string

Line is the one-line form `gadak issue` prints: "wait 3d · progress 5h". Empty when neither span exists — the caller omits the line, not its parts.

type SprintRow added in v0.22.0

type SprintRow struct {
	ID          int64
	BoardID     int64
	Name        string
	Goal        string
	State       string
	StartAt     string
	EndAt       string
	CompleteAt  string
	ActivatedAt string
	// ExternalID is the origin's own sprint id verbatim (v46, GDK-1667):
	// Jira's integer as a string, Linear's cycle UUID. The integer ID above
	// is derived on Linear (linear.SprintID); this column is the wire truth
	// the write path resolves back to.
	ExternalID string
}

SprintRow is one sprint. state is lowercase active|future|closed — the value queries are told to ask for, never a display name.

type SprintRowWithCount added in v0.22.0

type SprintRowWithCount struct {
	ID         int64  `json:"id"`
	BoardID    int64  `json:"board_id"`
	Name       string `json:"name"`
	Goal       string `json:"goal"`
	State      string `json:"state"`
	StartAt    string `json:"start_at,omitempty"`
	EndAt      string `json:"end_at,omitempty"`
	IssueCount int    `json:"issue_count"`
	Done       int    `json:"done"`
	InProgress int    `json:"in_progress"`
	Todo       int    `json:"todo"`

	Points     *float64 `json:"points,omitempty"`
	DonePoints *float64 `json:"done_points,omitempty"`
}

SprintRowWithCount is one sprint plus how many mirrored issues sit in it, split by status category so a reader can draw progress without holding the issues (GDK-1709). Done + InProgress + Todo always equals IssueCount: Todo is the remainder, not a fourth COUNT, so a mirror carrying a category outside the three lands in "to do" instead of vanishing from the bar.

Points/DonePoints are the story-point sums when the workspace maps a `story_points` alias (config custom fields) and nil when it does not — a zero would read as "nobody estimated", which is a different answer from "this origin has no points at all".

type SyncProgressRow added in v0.22.0

type SyncProgressRow struct {
	SourceID  string
	First     bool
	StartedAt string
	UpdatedAt string
	Fetched   int
	Total     *int // nil when the origin gave no count
}

SyncProgressRow is one live pass's heartbeat.

type SyncResult

type SyncResult struct {
	Watermark string // ignored when empty or not greater than the stored one
	FullSync  bool   // stamps last_full_sync_at
	Err       error  // recorded as last_error; nil clears it
	// Locale records the origin locale this pass fetched display names
	// under (GDK-597). Empty leaves the stored marker alone — an error
	// path or a source that does not localize must not clobber it.
	Locale string
	// Scope records the configured scope signature this pass mirrored under
	// (GDK-1400). Empty leaves the stored signature alone, so a source that
	// has no scope concept never clobbers another's.
	Scope string
}

SyncResult is what a finished sync run reports.

type SyncRun

type SyncRun struct {
	Kind       string `json:"kind"` // full | incremental (+reconcile)
	StartedAt  string `json:"started_at"`
	FinishedAt string `json:"finished_at"`
	Fetched    int    `json:"fetched"`
	Changed    int    `json:"changed"`
	Deleted    int    `json:"deleted"`
	Error      string `json:"error,omitempty"`
}

SyncRun is one recorded sync pass. Only meaningful runs are stored: ones that changed something, were a full pass, or failed — the watch loop's no-op incrementals would otherwise bury the history in noise.

type SyncState

type SyncState struct {
	SourceID  string `json:"source_id"`
	Watermark string `json:"watermark"`
	// SyncedAt is the last run that finished without an error — the only field
	// here that means "the mirror is fresh". A watermark stalls on its own
	// whenever the project is simply quiet.
	SyncedAt       *string `json:"synced_at"`
	Version        int64   `json:"version"`
	LastFullSyncAt *string `json:"last_full_sync_at"`
	LastError      *string `json:"last_error"`
	// SchemaVersion is the mirror's migration level (PRAGMA user_version).
	// Diagnostic surfaces (status --json, MCP gadak_status, doctor) all
	// publish this field. The sync_state.schema_version column can lag
	// when Open migrates after the last sync wrote the row (GDK-526), so
	// SyncState overwrites the scanned column with the live PRAGMA rather
	// than introducing a second JSON name for the same fact.
	SchemaVersion int `json:"schema_version"`
	// SchemaVersionRow is the stored column. json omitted so it cannot
	// collide with schema_version on the wire; doctor uses it to name a lag.
	SchemaVersionRow int `json:"-"`
	// FirstSyncAt is the first successful sync for this source (retention).
	FirstSyncAt *string `json:"first_sync_at,omitempty"`
	// SyncCount is the number of successful sync runs (retention).
	SyncCount int64 `json:"sync_count"`
	// LastNotifiedAt is the OS-notification watermark. Independent of
	// feed_reads: delivering a desktop alert must not mark the feed read.
	LastNotifiedAt *string `json:"last_notified_at,omitempty"`
	// Locale is the origin locale the jira source's display names were
	// fetched under (GDK-597). NULL (pre-v35 mirror) reads as "" = English.
	Locale string `json:"locale,omitempty"`
	// ScopeHash is the configured scope signature this source last mirrored
	// under (GDK-1400). Empty means unrecorded — a pre-v44 mirror, or a
	// source that has never run — and forces nothing.
	ScopeHash string `json:"scope_hash,omitempty"`
	// Reconcile is the last two-way reconcile's tally. Zero At means no
	// reconcile has run since the mirror reached v44.
	Reconcile ReconcileStats `json:"reconcile"`
}

SyncState is the per-source sync bookkeeping.

type TombstoneScope added in v0.24.2

type TombstoneScope int

TombstoneScope says whose tombstones DeletedKeysSince lists. deleted_items holds issue keys and wiki page ids side by side (GDK-1890); a client of one must never be handed the other's.

const (
	// TombstoneIssues is every source except the wiki: Jira, Linear and the
	// built-in tracker. It is the exclusion, not a list, so a new issue
	// source id needs no edit here.
	TombstoneIssues TombstoneScope = iota
	// TombstoneWiki is the Confluence source only.
	TombstoneWiki
)

type UserAccount added in v0.17.0

type UserAccount struct {
	AccountID   string
	Name        string
	Email       string
	AccountType string
}

UserAccount is one row of the origin's account catalog (GDK-590). The connector collects every user payload the sync already reads — assignee, reporter, creator, comment/changelog/attachment authors — and the store caches the union in the users table. AccountType keeps the origin's spelling ("agent", "app", "atlassian", …); source-neutral on purpose, the bot judgement on those values lives in the jira package.

type VersionRow added in v0.17.0

type VersionRow struct {
	ID          string
	ProjectKey  string
	Name        string
	Released    bool
	Archived    bool
	ReleaseDate string
}

VersionRow is one row of the project version catalog (GDK-532). Id is the join key; names rename. Released/Archived are origin flags; ReleaseDate is a date-only string or empty.

type Visit added in v0.13.0

type Visit struct {
	ID       int64  `json:"id"`
	Kind     string `json:"kind"`
	Key      string `json:"key"`
	ViewedAt string `json:"viewed_at"`
	Source   string `json:"source"`
	// SeenUpdatedAt is the item's updated_at at the moment of this read
	// (GDK-1451); empty when the mirror had no row to stamp from.
	SeenUpdatedAt string `json:"seen_updated_at"`
}

Visit is one append-only view event.

Jump to

Keyboard shortcuts

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