Skip to content
GitHub

DevelopStorage

@holtkeeper/store

The persistence contract. Everything Holtkeeper stores goes through Store; implementations are interchangeable.

Part Holds
credentials Forge accounts, API keys and AI providers; secret is always sealed by a Vault, kind-specific options are stored as given, capabilities hold probe results ({ agentLoop, checkedAt, error? }); touch(id, at) moves lastUsedAt forward only, and put keeps the later of the stored and the given lastUsedAt, so a read-modify-write never moves it back
settings Scoped setting entries (see @holtkeeper/settings)
users Users, passkeys, OIDC identities and one-time link tokens (only hashes); touchUser(id, at) moves lastSeenAt forward only, and putUser keeps the later of the stored and the given lastSeenAt
analyses Analysis records (sha: the commit the analysis ran on, when known): list newest first by repository, kind and time (before exclusive, since inclusive, combined with limit), heads the same without data; latest the newest record of every (repository, kind), latestHeads the same without data
jobs The task queue for background analyses (see below)
rules Rules people wrote in the panel, with version history and search (see below)
learnings Rules Holtkeeper learned, handled reply notes and reaction counts on review comments (see below)
aiUsage One record per LLM agent run: tokens, cost, outcome (see below)
ciJobs Finished CI job attempts per repository, kept so job analytics fetch only what is new (see below)
tasks Agent tasks (write tasks people or automation asked for) and their groups (see below)
chat Team chat threads, their messages and read markers (see below)
audit The append-only, hash-chained audit log of who did what (see below)
slackMessages Optional. Slack messages that link merge requests, with the review status and emoji last set on them (see below)
externalAccounts Optional. External accounts (GitLab, GitHub and other ids) linked to principals (see below)
libraries Optional. Third-party library docs: libraries, indexed versions, document chunks and issues (see below)
database Optional. Read-only introspection of the underlying database for the admin UI (see below)

JobStore is the queue of @holtkeeper/jobs. A Job is one analyzer run for one repository (or one team’s repositories for a group-scope analyzer: repo is { forge, path: <team key> } and group holds the team key; the field keeps its name) with status queued | running | succeeded | failed | blocked | canceled (blocked: an AI budget refused or stopped the run; final, not retried, not a failure) and trigger schedule | manual | command | webhook | tag | push | poll | new-repo | freshness (manual and command, a merge request comment command, mean a person asked).

  • enqueue — defaults: maxAttempts 3, runAfter = createdAt, empty options and log.

  • claim(workerId, now, rules?) — atomically takes the first due queued job in (priority kind first, runAfter, enqueue order) that may start next to the running jobs of its repository, marks it running and counts the attempt. ClaimRules name analyzer kinds: exclusive kinds change their repository, after maps a kind to the kinds whose results it reads, delayMs limits the claim to jobs due at least that long before now, only to jobs of the listed kinds and except to jobs of other kinds (worker pools), priority lists latency-sensitive kinds whose due jobs go before every other job and ignore delayMs. “Queued ahead” below means (runAfter, enqueue order). A job is skipped while its repository:

    • runs a job of the same analyzer;
    • runs anything, when the job is exclusive;
    • runs an exclusive job or has one queued ahead of it, so readers neither overtake nor starve it;
    • runs a job of a kind the job comes after, or has one queued ahead of it.

    A priority job ignores the “queued ahead” parts of the last two rules: only a running exclusive or after job holds it back, so an exclusive job waiting deep in the queue never delays a review of its repository. The exclusive job then waits for the running review like for anything else. The SQL stores look for a startable priority job first and fall back to the plain claim, so both lookups walk the due index in claim order.

    Without rules only the first rule applies, so jobs of different analyzers of one repository run side by side.

  • heartbeat(id, workerId, now) — false once the job is no longer running for that worker (e.g. canceled).

  • complete, fail(id, { at, error, retryAt?, step? }) (back to the queue while attempts remain and retryAt is given), block(id, { at, error }) (a running job becomes blocked for good), cancel, recoverStale(heartbeatBefore, at) for jobs of dead workers.

  • attemptsHistory has one JobAttempt { n, status, startedAt, finishedAt?, workerId?, error?, step? } per attempt: claim appends a running one, and complete, fail, block, cancel and recoverStale end it (succeeded, failed, blocked, canceled, failed). Logs are not in the store: the worker writes them to the artifact store (see @holtkeeper/jobs).

  • errorSignature is errorSignature(error) of the latest failure, set by fail and recoverStale and cleared by complete and block: the first non-empty line with URLs, UUIDs, hex hashes, paths and numbers replaced by <url>, <id>, <hash>, <path> and <n>, at most 200 characters, so the same failure in different repositories and runs compares equal.

  • A job queued by a schedule carries its schedule name, also when someone ran the schedule by hand (actor is set then). A job queued by automation that decided on its own carries its reason (freshness: sha 1a2b3c4 != head 5d6e7f8); the reason column came with sqlite v19 and postgres v18.

  • list({ status, repo, analyzer, schedule, trigger, before, errorSignature, analysisId, repos, search, limit }) newest first. repos limits to those repositories (group-scope jobs by { forge, path: <team key> }; an empty list matches nothing), so callers apply visibility before limit. analysisId finds the job (or jobs) that produced an analysis. search: { text, analyzers? } keeps jobs whose id starts with text or whose repository path, team (group) or analyzer contains it, ignoring case (%, _ and backslashes are literal; likeText escapes them for SQL, matchesJobSearch is the in-memory check), plus jobs of the listed analyzers. count takes the same filters.

  • count({ ...the list filters, since }) — JobCounts { total, byStatus } over the jobs that match (no paging; since keeps jobs created at or after it). byStatus has every status, zero included, and sums to total (jobCounts builds it).

  • failures({ since, analyzer?, repos?, limit? }) groups jobs that failed for good since since by analyzer and errorSignature: count, distinct repos, firstAt, lastAt, the latest job and its raw error, the group that failed last first. targets() lists every distinct repository or team (group-scope jobs) that has jobs.

RuleStore holds the rules people write in the panel (Rule, see @holtkeeper/rules for how they reach prompts): title, Markdown body, scope (the repositories it applies to and its authority), and the optional files (path globs), agents (review, task, chat, release), description and alwaysApply. Optional fields read back absent when they were not written.

  • put(rule, expectedVersion?) — upsert by id. The store assigns version (1, then +1 per put) and moves the previous version into the history with editedBy (its updatedBy, or author) and editedAt (its updatedAt). With expectedVersion, the put throws RuleVersionConflictError { id, stored } and writes nothing unless the stored version equals it (0 for a rule that does not exist yet), so two editors of one rule cannot overwrite each other.
  • get(id), list() (by title ignoring case, then id), history(id) (previous versions, newest first), remove(id) (drops the history too).
  • search(text, limit = 20) → { rule, score }[], best first. Every word of text is a prefix (migr finds migration), any word may match, title matches outrank description matches, which outrank body matches. Quotes, operators and punctuation are plain text; blank text returns nothing. Scores are only comparable within one result.

ruleContent (the versioned part of a rule, as histories keep it) and searchWords (the word tokenizer every store searches with) are exported for implementations.

LearningStore holds the rules Holtkeeper learned (Learning, stored whole): one imperative text and its normalized key, scope, optional files, agents and reason, origin (reply, miner, agent, person), status (pending, active, rejected, expired), the sources that taught it, and the counters and dates of its lifecycle (activeAt, lastReinforcedAt, uses, actedOn, votesUp, votesDown). The lifecycle itself lives in @holtkeeper/rules; the store only keeps what it is given.

  • put (by id), get, remove, list({ status?, origin? }) newest updatedAt first, then by id (byLearningUpdate, matchesLearningFilter), find(key) the learning with that key (the oldest one, should there be several).
  • search(text, filter?, limit = 20) → { learning, score }[], best first, over the words of text as prefixes; same safety rules as rule search.
  • claim(key, at) is true only for the first caller of a key, atomically across processes; release(key) forgets it. Capture claims each reply note before its LLM call.
  • putReactions(signal) replaces the 👍/👎 counts of one review comment (repository, merge request, note) with its finding category; reactionTotals({ repos? }) sums them per category (sumReactions); reactions({ repo?, mergeRequests? }) returns the counts per comment (reactionsOf) of one repository, for the Reviews tab of the repository page, or of every repository without repo, for the review quality aggregate. A signal also keeps what became of the comment once its merge request ended: outcome (fixed, resolved, ignored, unknown), mergeRequestState, severity, source, model, promptVersion and humanReplies; all optional, so signals stored before them still read.

The SQL stores replaced the old notes (knowledge), Guide (guides, guide_history, guide_generated), families and embeddings tables with rules, rule_history and a new learnings table in sqlite migration 34 and postgres migration 33; nothing is carried over.

ChatStore holds the threads of the team chat (chat_threads, chat_messages, chat_thread_reads, chat_thread_mutes in SQLite and Postgres):

  • ChatThread { id, title, titlePending?, repo?, group? (a team key), createdBy, createdAt, updatedAt, archived, autoReply, participants, contextRepos, people?, summary?, replyingSince?, replyingBy? }: contextRepos are repositories (forge:path) people attached as context, in their order without duplicates (createThread and the contextRepos patch drop repeats; threads stored before the column existed read []); participants are principal ids in order of first appearance (they decide the Participant A/B labels), people (ChatPerson { id, name?, email? }) the name and email each poster last wrote under, so prompts can scrub them without a users account (rememberPeople in a patch replaces or adds entries by id), summary { text, uptoMessageId, tokens } stands for every message up to and including uptoMessageId. createThread starts unarchived with updatedAt = createdAt; titlePending marks a placeholder title waiting to be named from the first message; a title patch (a person’s) clears it, and generatedTitle sets the title and clears it only while it is still set, so a person’s title is never replaced and a title is generated once. updateThread(id, patch) changes title, archived, autoReply, participants, contextRepos and summary (null clears it), and answers undefined for unknown ids. It applies the patch to the thread as stored, under the row lock or transaction, so addParticipants (append ids not yet there) never loses a concurrent addition, and claimReply { by, at, staleBefore } takes the reply claim (replyingSince, replyingBy) only when nobody holds it or the held claim started before staleBefore; releaseReply: by drops it while by still holds it; listThreads({ archived?, q? }) returns unarchived threads by newest updatedAt (archived: true only archived ones, 'all' both) whose title contains q, ignoring case and surrounding blanks (matchesChatThreadFilter); callers count archived threads from the 'all' list after their own visibility filter.
  • ChatMessage { id, threadId, seq, authorType: human | agent | system, authorId?, body, card?, toolTrace?, costUsd?, transcriptRef?, mentions, refs, createdAt, updatedAt? }: seq is assigned by the store and grows across the store, so it orders messages and serves as the cursor. refs are the structured references the writer stored with the message (ChatMessageRef: repo { repo }, job { id, repo? }, task { id, repo? }, note { id }, mr { repo, iid }), so views never parse bodies; addMessage defaults them to [] and messages stored before the column existed read []. addMessage moves the thread’s updatedAt; updateMessage(id, { card?, body?, refs?, updatedAt }) changes a message in place (deploy cards). listMessages(threadId, { after?, before?, changedSince?, limit? }) answers oldest first: the oldest limit (default 50, at most 500) after after, else the newest before before, plus messages changed in place since changedSince (selectChatMessages holds the rule).
  • markRead(threadId, userId, messageId) moves a person’s marker forward only; reads(userId); unreadCounts(userId, threadIds) counts messages after the marker that others wrote (agent and system messages included), listing only threads with any; messageCounts(threadIds) counts every message per thread the same way (a GROUP BY in SQL, no message is read).
  • context(threadId) → ChatThreadContext { messageCount, costUsd, repos, tools, participants } over every message of the thread (undefined for unknown threads): the sum of costUsd (0 without any), contextRepos followed by the repositories of message refs in order of first mention without duplicates, calls per tool summed over toolTrace (most calls first, then by name) and human authors with their message counts in order of first message. chatThreadContext holds the rule; callers filter repositories and cost by the viewer’s rights.
  • setMuted(threadId, userId, muted) mutes or unmutes a thread for one person (idempotent); mutedThreads(userId) lists the muted thread ids, sorted.

SlackMessageStore (optional, slack_messages in SQLite and Postgres) keeps the Slack messages the server’s review status follows: one SlackMessageLink per message (channel, ts) and merge request (repo as forge:path, mergeRequest), with the status last known (reviewing, clean, minor, changes, skipped), the head it describes the emoji reaction currently on the message and, where merge request marks are on, the merge request’s marks (comments, approved, merged) and the mark emoji markReactions on the message. put upserts by those four keys, ofMessage lists a message’s links by repository and merge request, ofMergeRequest a merge request’s links oldest message first, delete(channel, ts, target?) drops a message’s link to one merge request (or all its links and its status reply without target), and prune(before) deletes links created before a time, plus status replies created before it whose message has no links left. A link also keeps the repository path in its own case for display (rows stored before may still carry a title, which nothing reads). replyOf(channel, ts) and putReply read and upsert the message’s SlackStatusReply (slack_replies): the replyTs of the bot’s reply in its thread and the text last set on it. byLinkTarget and byLinkMessage are those orders for implementations. tableDomain puts both tables under chat.

AgentTaskStore (agent_task_groups, agent_tasks in SQLite and Postgres) holds requests to change code:

  • AgentTaskGroup { id, kind, title, prompt, plan?, patch?, proposedBy, approvedBy?, approvedAt?, cancelledBy?, source, repos, budgetClass, requests?, createdAt, updatedAt }: one source (AgentTaskSource: a chat thread and its card message, a dependency upgrade, a propagate run (with the team key it started from in group), an MCP client or the API) and its targets as forge:path. requests are repositories a running task asked to add (pending | approved | rejected, with who decided). kind is fix | port | upgrade | propagate-fix | chat | tests.
  • AgentTask { id, groupId, kind, title, prompt, plan?, patch?, repo, requester, source, status, jobId?, budgetUsd?, costUsd?, transcriptRef?, mergeRequest?, error?, createdAt, updatedAt }: one repository’s part of a group. status is proposed | approved | queued | running | mr-open | done | failed | cancelled; mergeRequest { id, url, draft, state?, ci?, checkedAt? } with the forge’s state and the CI of the branch’s latest pipeline.
  • put/putGroup insert or replace, transition(task, from) replaces a task only while its stored status is one of from (atomic; false when it is missing or changed meanwhile, so two approvals never both queue it), get/getGroup by id, list({ groupIds?, repos?, status?, requester?, limit? }) and listGroups({ sourceType?, repos?, proposedBy?, limit? }) newest updatedAt first, then by id (byTaskUpdate, matchesAgentTaskFilter, matchesAgentGroupFilter).
  • agentGroupStatus(tasks) derives a group’s status: proposed while any task waits, then the most advanced active status (running, queued, approved), then mr-open, cancelled when all were cancelled, failed when any of the rest failed, else done. finalTaskStatuses are done, failed and cancelled.

AiUsageStore is the history behind @holtkeeper/ai-usage. An AiUsageRecord holds the repository and its owner teams at the time (teams), task kind, analyzer/job/analysis ids, actor, interactive (a person started the work; append defaults it to false, automatic), subject (what the run worked on in a few words, e.g. MR !42, when the caller said), mergeRequest (the iid, when the run worked on one), phase (the step of the work within the task kind, e.g. a review’s initial or reply; the SQLite and Postgres migrations that follow the columns fill both once for older records of review jobs from the job and earlier review records, keeping old rechecks in their review’s phase), provider, model, the four token counts, costUsd with costSource (reported | computed | unknown), duration, turns, outcome (ok | error | denied-budget) and transcriptRef (artifact id of the run’s JSONL transcript, when one was stored).

  • append(record); list({ ...filter, before, limit }) newest first.
  • aggregate({ from, to, groupBy, filter }) — one bucket per distinct combination of groupBy values (day, week = its Monday, month, all UTC; repo as forge:path, team (a record counts once in each of its teams, records without teams under ''), model, provider, taskKind, analyzer, origin as interactive or automatic, phase, mergeRequest as the iid in decimal), sorted by key. Each bucket sums tokens per kind and cost and counts runs, errors, denied and unknownCost (runs that were not denied whose cost is unknown, so the sum understates them), with avgDurationMs over runs that were not denied. A record in several groups counts once per group; records without groups (or analyzer, phase or merge request) fall under ''. No matching records, no buckets.
  • AiUsageFilter: from (inclusive), to (exclusive), repo, team, teams (records in any of them; an empty list matches nothing), actor, origin (interactive or automatic), model, provider, taskKind, taskKinds (records of any of them; an empty list matches nothing), analyzer, outcome, jobId, and scopes — records covered by any of them (an empty list matches nothing), used for access filtering and scoped budgets. Fields combine with AND, so teams only ever narrows scopes.

CiJobStore keeps finished CI job attempts (CiJobRecord: repository, job and pipeline ids, name, stage, success | failed | canceled, ref, sha, tag (the pipeline ran for a tag), times, duration and queue seconds, allowFailure, link) for @holtkeeper/ci-jobs.

  • put(records) inserts or replaces by repository and job id; times are stored in the contract’s ISO 8601 form (normalizeCiJob).
  • list(repo, { from?, to? }) — created in [from, to), oldest first, ties by job id (compareCiJobs).
  • coverage(repo) — oldest and newest creation time and count; undefined without records.
  • prune(before) — removes records of every repository created before before, returns how many.

aggregateAiUsage, matchesAiUsageFilter, aggregateFilter, sortAiUsageBuckets, storedAiUsage, weekStart, aiUsageDimensions and emptyAiUsageTotals are exported for implementations.

updateKv(kv, key, apply, attempts = 5) writes apply(current value) to a KvStore key, retrying when another write landed in between (compareAndSet); it resolves with the written value, or undefined when every attempt lost. apply answering keepKv leaves the key as it is (and resolves with undefined).

Both are optional parts of Store; servers without them use the file config only and keep such state in memory.

  • config (ConfigStore) holds panel-managed configuration as typed documents: forge (with the fleet’s include / exclude path globs), team (TeamDocumentData: title?, owns, exclude, consumes, members), repoTraits, schedule and trigger (both target teams? and repos? path patterns) (shapes in ConfigDocumentDataMap, see @holtkeeper/managed-config). put creates or replaces by (type, id), bumps version and keeps the previous version in history(type, id) (newest first); list(type?) orders by type, then id; remove drops the document and its history.
  • kv (KvStore) is small JSON state with optional expiry: get, set(key, value, ttlSeconds?), delete, and sweep(now?) removing expired keys. Expired keys read as missing even before a sweep. Merge request policies remember done actions here. Two atomic operations make it usable by several processes: acquireLease(key, holder, ttlSeconds, now?) takes or renews a lease (granted when none is live at now or holder already has it; resolves with the lease as it is afterwards) and releaseLease(key, holder); compareAndSet(key, expected, value, ttlSeconds?) writes only over the expected value (JSON equality, key order ignored, undefined = missing). The server’s leader election and the distributed limiter use them; memory, SQLite and Postgres implement them (they are optional in the contract for third-party stores).

AuditStore (store.audit) is the tamper-evident record of who changed what. It is mandatory in every Store and the only record of who did what; Settings › Audit log in the panel reads it. An AuditEvent is { id, seq, at, actor { id, name, provider }, via: ui | api | webhook | job | system, action, target { type, id?, repo? }, outcome: ok | denied | error, status?, request? { method, path, route?, params?, ip?, userAgent?, durationMs? }, changes? { field, before?, after? }[], details?, prevHash, hash }. Secret values in changes are «redacted» before they reach the store.

  • append(input) — the store assigns id, seq (one more than the newest event ever appended; never reused, not even after a sweep) and the chain: prevHash is the previous event’s hash (64 zeros for seq 1), hash the SHA-256 of canonicalJson of every other field (keys sorted, undefined dropped). Appends are serialized.
  • list({ ...filter, cursor, limit = 50 }) → { events, nextCursor? }, newest first by seq; pass nextCursor back as cursor.
  • repos() — every distinct target.repo among the kept events, sorted; callers filter it by permission to build repos.
  • summary(filter) → { total, days, actions, actors, repos }, each dimension a list of { key, count }: days are UTC calendar days (YYYY-MM-DD) with events, oldest first; actions are full action names, actors actor ids with the name of the actor’s newest matching event, repos the target.repo of events that have one; those three are sorted by count, most first, then by key. Pass repos in the filter to summarize only a set of repositories. sortAuditSummary applies that order for implementations.
  • count(filter); export(filter) — an async iterable, oldest first, read in batches of AUDIT_EXPORT_BATCH (500); formatAuditEvents(events, 'csv' | 'ndjson') turns it into text chunks (CSV cells starting with = + - @ are prefixed with ' against formula injection).
  • AuditFilter: actor (id), action (prefix: credential matches credential.update), targetType, targetId, repo (exact forge:path), repos (the event’s target.repo is one of the list; events without a repository never match, an empty list matches nothing), outcome, via, from (inclusive), to (exclusive).
  • sweep(before) — retention. Removes the oldest events up to the first one at or after before, so the kept events stay one contiguous chain even when at is not monotonic. Returns how many it removed; the store remembers the last swept seq.
  • verifyChain({ fromSeq?, toSeq? }) → { ok, checked, firstSeq?, lastSeq?, broken? }. Every seq from the requested start (or the first unswept one) to the requested end (or the newest appended) must be present once, hash to its hash and link to the hash before it. broken.reason: hash (content edited), link (re-hashed or inserted event), gap (event removed from the middle or start), tail (newest events removed).

What the chain does and does not prove: anyone who edits the database without also recomputing every later hash and the stored chain head is caught. Someone with full write access who rewrites the whole chain and the head is not — export the log regularly (or record hash of the newest event elsewhere) to anchor it.

canonicalJson, auditHash, sealAuditEvent, verifyAuditEvents, auditVerifyRange, matchesAuditFilter, auditCursorSeq and AUDIT_GENESIS_HASH are exported for implementations. SYSTEM_ACTOR ({ id: 'system', name: 'Holtkeeper', provider: 'system' }) is the actor of what Holtkeeper does on its own, such as seeding defaults. AUTO_ACCEPT_ACTOR ({ id: 'auto-accept', name: 'Auto-accept', provider: 'system' }, also at @holtkeeper/store/actors for the browser) is the actor of what a policy decides without a person, such as a learning activating after its approval delay; its id is what Learning.decidedBy holds then.

ExternalAccountStore (store.externalAccounts) holds the links of @holtkeeper/identities: get, find(provider, externalId), listByUser(userId) and list(provider?) (oldest link first), put (upsert by id; rejects with ExternalAccountConflictError when another id holds the same (provider, externalId)) and remove. removeUser also removes the user’s links. User.avatarSeed (optional) overrides the user id as the seed of the generated avatar.

LibraryStore (store.libraries, optional) holds the third-party documentation index of library docs. Libraries are keyed by LibraryRef (ecosystem, name); ecosystem is npm or Go.

  • putLibrary / putVersion create or replace a LibraryRecord by (ecosystem, name) and a LibraryVersionRecord by (ecosystem, name, version); both round-trip whole, optional fields stay absent. getLibrary, getVersion.
  • listLibraries({ ecosystem?, query? }) — by ecosystem, then name (code-unit order); query keeps names containing it, case-insensitively.
  • listVersions(ref) — highest semantic version first (compareLibraryVersions): 1.10.0 above 1.9.0, a prerelease below its release (rc.1 above beta.11 above beta.2), a Go v prefix and +build metadata ignored; strings that are not versions sort last.
  • replaceChunks(ref, version, source, chunks) — makes chunks exactly what version ships from source. A chunk is one heading section (id, path, headings, anchor?, text, url?); ids come from the caller and are stable for identical content, so an id stored before is reused and gains the version. The version is dropped from the library’s other chunks of that source (chunks of other sources keep it), and chunks left without versions are deleted. The order of chunks is their document order; a reused chunk takes its position from the latest call. versions given in the input are ignored.
  • listChunks(filter, limit = 200) — in path order (code units), then document order. removeVersion(ref, version) deletes the version record, drops the version from the library’s chunks and deletes orphans.
  • searchChunks(text, filter?, limit = 20) → { chunk, score }[], best first; chunk.versions is highest first. LibraryChunkFilter: ecosystem, name, version (only chunks that version ships), source, path (exact). Heading matches outrank text matches.
  • libraryStats({ ecosystem? }): Map keyed by <ecosystem>:<name> of every stored library (zero counts included) to LibraryStats { versions, chunks, issues }, in one query; versions counts every version record, those in their grace period included.
  • putIssues(issues) creates or replaces by id (<host>/<owner>/<repo>#<number>), getIssue(id), searchIssues(text, { ecosystem?, name?, state? }, limit = 20): title matches outrank digest matches (problem, symptoms, affected, fixed-in, workaround), which outrank first message and answer matches; ties go to the most recently updated.
  • removeLibrary(ref) removes the library with its versions, chunks and issues; other libraries keep theirs.

Search text is plain words: every word is a prefix (useEff finds useEffect), any word may match, operators and punctuation are plain text, and blank text returns nothing. A quoted phrase of several words ("cannot read property") matches only those words in that order; an unclosed quote is plain text. Scores are only comparable within one result.

compareLibraryVersions, newestVersionsFirst, libraryQueryTerms, libraryIssueDigestText, libraryIssueBodyText and plainChunk are exported for implementations.

AnalysisRecord.metrics holds the kind’s structured headline numbers (coverage percent, gzip per target, counts per severity, …), computed from data when the record is stored (see AnalysisKind.metrics in @holtkeeper/report). Stores keep it as the plain JSON object they are given and return it unchanged from get, list, heads, latest and latestHeads; records stored before metrics existed and kinds that define none have no metrics. Heads keep metrics, so lists and health read them without loading any data.

AnalysisStore.prune({ repo, kind, keep }) deletes a repository’s records of one kind except the newest keep and returns how many it deleted; the task engine and POST /api/analyses call it for analyzers with keepRecords. AnalysisStore.removeRepo(repo) deletes every record of a repository, of any kind and ref, and returns how many (the server’s repository cleanup). AnalysisStore.latest({ repo?, kind? }) returns the newest record of every (repository, kind) pair, newest first; among records created at the same time the last added wins; latestHeads returns the same records without their data. newestRecords(analyses, kind, read, accept?) builds on latest: the newest record of kind of every repository that read turns into a value, trying up to 20 older records of a repository only when read rejects its newest; accept leaves repositories out by their newest record.

DatabaseInspector (store.database) describes the database a store lives in; it reads catalog and statistics views only, never the store’s rows. SQLite and Postgres implement it, the memory store leaves it out.

  • engine — postgres | sqlite.
  • overview() — DatabaseOverview: version, size, SQLite free pages, start time, cache hit ratio, commits, rollbacks, deadlocks, statistics reset time, connections by state against max_connections, whether it is a standby, and streaming replicas with lag. Fields an engine cannot report are left out.
  • tables() / indexes() — the store schema’s tables (rows, data, index and TOAST bytes, dead rows, last vacuum and analyze, sequential and index scans) and indexes (size, scans, definition, unique, primary), largest first.
  • queries({ sort: total | mean | calls, limit = 50 }) — DatabaseQueries: the top normalized statements of this database with calls, total, mean and max time, rows and cache hit ratio, plus whether resetQueries() is permitted; or { available: false, reason } (SQLite, or no pg_stat_statements).
  • resetQueries?() — clears statement statistics; throws without the right.
  • sessions() — other client connections with state, statement, start times, wait event and the pids blocking them.
  • migrations() — applied schema versions with their time, oldest first.

tableDomain(name) puts a table into one of databaseDomains (jobs, analyses, audit, ai, knowledge (rules, learnings, reply claims and reaction counts), libraries, chat, tasks, config, accounts, other) for size reports; search side tables count with the table they index.

  • memoryStore() from @holtkeeper/store/memory — in process memory, for tests and throwaway runs.
  • sqliteStore({ path }) from @holtkeeper/store-sqlite — the default for real use.
  • postgresStore({ url }) from @holtkeeper/store-postgres — for several processes.

describeStoreContract(name, create) from @holtkeeper/store/testing is the behavior every implementation must have: ordering, filters, limits, upserts, cascades, round-tripping nested data. A new implementation (Postgres, …) is done when it passes this suite unchanged.