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:maxAttempts3,runAfter=createdAt, emptyoptionsandlog. -
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.ClaimRulesname analyzer kinds:exclusivekinds change their repository,aftermaps a kind to the kinds whose results it reads,delayMslimits the claim to jobs due at least that long beforenow,onlyto jobs of the listed kinds andexceptto jobs of other kinds (worker pools),prioritylists latency-sensitive kinds whose due jobs go before every other job and ignoredelayMs. “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
afterjob 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
rulesonly the first rule applies, so jobs of different analyzers of one repository run side by side. -
heartbeat(id, workerId, now)—falseonce 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 andretryAtis given),block(id, { at, error })(a running job becomesblockedfor good),cancel,recoverStale(heartbeatBefore, at)for jobs of dead workers. -
attemptsHistoryhas oneJobAttempt { n, status, startedAt, finishedAt?, workerId?, error?, step? }per attempt:claimappends arunningone, andcomplete,fail,block,cancelandrecoverStaleend it (succeeded,failed,blocked,canceled,failed). Logs are not in the store: the worker writes them to the artifact store (see @holtkeeper/jobs). -
errorSignatureiserrorSignature(error)of the latest failure, set byfailandrecoverStaleand cleared bycompleteandblock: 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
schedulename, also when someone ran the schedule by hand (actoris set then). A job queued by automation that decided on its own carries itsreason(freshness:sha 1a2b3c4 != head 5d6e7f8); thereasoncolumn came with sqlite v19 and postgres v18. -
list({ status, repo, analyzer, schedule, trigger, before, errorSignature, analysisId, repos, search, limit })newest first.reposlimits to those repositories (group-scope jobs by{ forge, path: <team key> }; an empty list matches nothing), so callers apply visibility beforelimit.analysisIdfinds the job (or jobs) that produced an analysis.search: { text, analyzers? }keeps jobs whose id starts withtextor whose repository path, team (group) or analyzer contains it, ignoring case (%,_and backslashes are literal;likeTextescapes them for SQL,matchesJobSearchis the in-memory check), plus jobs of the listedanalyzers.counttakes the same filters. -
count({ ...the list filters, since })—JobCounts { total, byStatus }over the jobs that match (no paging;sincekeeps jobs created at or after it).byStatushas every status, zero included, and sums tototal(jobCountsbuilds it). -
failures({ since, analyzer?, repos?, limit? })groups jobs that failed for good sincesinceby analyzer anderrorSignature:count, distinctrepos,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 assignsversion(1, then +1 per put) and moves the previous version into the history witheditedBy(itsupdatedBy, orauthor) andeditedAt(itsupdatedAt). WithexpectedVersion, the put throwsRuleVersionConflictError { 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 oftextis a prefix (migrfindsmigration), 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.
Learnings
Section titled “Learnings”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? })newestupdatedAtfirst, 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 oftextas prefixes; same safety rules as rule search.claim(key, at)istrueonly 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 withoutrepo, 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,promptVersionandhumanReplies; 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.
Team chat
Section titled “Team chat”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? }:contextReposare repositories (forge:path) people attached as context, in their order without duplicates (createThreadand thecontextRepospatch drop repeats; threads stored before the column existed read[]);participantsare principal ids in order of first appearance (they decide theParticipant A/Blabels),people(ChatPerson { id, name?, email? }) the name and email each poster last wrote under, so prompts can scrub them without ausersaccount (rememberPeoplein a patch replaces or adds entries by id),summary { text, uptoMessageId, tokens }stands for every message up to and includinguptoMessageId.createThreadstarts unarchived withupdatedAt = createdAt;titlePendingmarks a placeholder title waiting to be named from the first message; atitlepatch (a person’s) clears it, andgeneratedTitlesets 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)changestitle,archived,autoReply,participants,contextReposandsummary(nullclears it), and answersundefinedfor unknown ids. It applies the patch to the thread as stored, under the row lock or transaction, soaddParticipants(append ids not yet there) never loses a concurrent addition, andclaimReply { by, at, staleBefore }takes the reply claim (replyingSince,replyingBy) only when nobody holds it or the held claim started beforestaleBefore;releaseReply: bydrops it whilebystill holds it;listThreads({ archived?, q? })returns unarchived threads by newestupdatedAt(archived: trueonly archived ones,'all'both) whose title containsq, 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? }:seqis assigned by the store and grows across the store, so it orders messages and serves as the cursor.refsare 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;addMessagedefaults them to[]and messages stored before the column existed read[].addMessagemoves the thread’supdatedAt;updateMessage(id, { card?, body?, refs?, updatedAt })changes a message in place (deploy cards).listMessages(threadId, { after?, before?, changedSince?, limit? })answers oldest first: the oldestlimit(default 50, at most 500) afterafter, else the newest beforebefore, plus messages changed in place sincechangedSince(selectChatMessagesholds 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 (aGROUP BYin SQL, no message is read).context(threadId)→ChatThreadContext { messageCount, costUsd, repos, tools, participants }over every message of the thread (undefinedfor unknown threads): the sum ofcostUsd(0 without any),contextReposfollowed by the repositories of messagerefsin order of first mention without duplicates, calls per tool summed overtoolTrace(most calls first, then by name) and human authors with their message counts in order of first message.chatThreadContextholds 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.
Slack messages
Section titled “Slack messages”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.
Agent tasks
Section titled “Agent tasks”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 ingroup), an MCP client or the API) and its targets asforge:path.requestsare repositories a running task asked to add (pending | approved | rejected, with who decided).kindisfix | 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.statusisproposed | 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/putGroupinsert or replace,transition(task, from)replaces a task only while its stored status is one offrom(atomic;falsewhen it is missing or changed meanwhile, so two approvals never both queue it),get/getGroupby id,list({ groupIds?, repos?, status?, requester?, limit? })andlistGroups({ sourceType?, repos?, proposedBy?, limit? })newestupdatedAtfirst, then by id (byTaskUpdate,matchesAgentTaskFilter,matchesAgentGroupFilter).agentGroupStatus(tasks)derives a group’s status:proposedwhile any task waits, then the most advanced active status (running,queued,approved), thenmr-open,cancelledwhen all were cancelled,failedwhen any of the rest failed, elsedone.finalTaskStatusesaredone,failedandcancelled.
AI usage
Section titled “AI usage”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 ofgroupByvalues (day,week= its Monday,month, all UTC;repoasforge:path,team(a record counts once in each of its teams, records without teams under''),model,provider,taskKind,analyzer,originasinteractiveorautomatic,phase,mergeRequestas the iid in decimal), sorted by key. Each bucket sums tokens per kind and cost and countsruns,errors,deniedandunknownCost(runs that were not denied whose cost is unknown, so the sum understates them), withavgDurationMsover 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(interactiveorautomatic),model,provider,taskKind,taskKinds(records of any of them; an empty list matches nothing),analyzer,outcome,jobId, andscopes— records covered by any of them (an empty list matches nothing), used for access filtering and scoped budgets. Fields combine with AND, soteamsonly ever narrowsscopes.
CI jobs
Section titled “CI jobs”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;undefinedwithout records.prune(before)— removes records of every repository created beforebefore, 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).
Config documents and key-value state
Section titled “Config documents and key-value state”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’sinclude/excludepath globs),team(TeamDocumentData:title?,owns,exclude,consumes,members),repoTraits,scheduleandtrigger(both targetteams?andrepos?path patterns) (shapes inConfigDocumentDataMap, see @holtkeeper/managed-config).putcreates or replaces by(type, id), bumpsversionand keeps the previous version inhistory(type, id)(newest first);list(type?)orders by type, then id;removedrops the document and its history.kv(KvStore) is small JSON state with optional expiry:get,set(key, value, ttlSeconds?),delete, andsweep(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 atnoworholderalready has it; resolves with the lease as it is afterwards) andreleaseLease(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).
Audit log
Section titled “Audit log”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 assignsid,seq(one more than the newest event ever appended; never reused, not even after a sweep) and the chain:prevHashis the previous event’shash(64 zeros forseq1),hashthe SHA-256 ofcanonicalJsonof every other field (keys sorted,undefineddropped). Appends are serialized.list({ ...filter, cursor, limit = 50 })→{ events, nextCursor? }, newest first byseq; passnextCursorback ascursor.repos()— every distincttarget.repoamong the kept events, sorted; callers filter it by permission to buildrepos.summary(filter)→{ total, days, actions, actors, repos }, each dimension a list of{ key, count }:daysare UTC calendar days (YYYY-MM-DD) with events, oldest first;actionsare full action names,actorsactor ids with thenameof the actor’s newest matching event,reposthetarget.repoof events that have one; those three are sorted by count, most first, then by key. Passreposin the filter to summarize only a set of repositories.sortAuditSummaryapplies that order for implementations.count(filter);export(filter)— an async iterable, oldest first, read in batches ofAUDIT_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:credentialmatchescredential.update),targetType,targetId,repo(exactforge:path),repos(the event’starget.repois 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 afterbefore, so the kept events stay one contiguous chain even whenatis not monotonic. Returns how many it removed; the store remembers the last sweptseq.verifyChain({ fromSeq?, toSeq? })→{ ok, checked, firstSeq?, lastSeq?, broken? }. Everyseqfrom the requested start (or the first unswept one) to the requested end (or the newest appended) must be present once, hash to itshashand 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.
External accounts
Section titled “External accounts”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.
Libraries
Section titled “Libraries”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/putVersioncreate or replace aLibraryRecordby(ecosystem, name)and aLibraryVersionRecordby(ecosystem, name, version); both round-trip whole, optional fields stay absent.getLibrary,getVersion.listLibraries({ ecosystem?, query? })— by ecosystem, then name (code-unit order);querykeeps names containing it, case-insensitively.listVersions(ref)— highest semantic version first (compareLibraryVersions):1.10.0above1.9.0, a prerelease below its release (rc.1abovebeta.11abovebeta.2), a Govprefix and+buildmetadata ignored; strings that are not versions sort last.replaceChunks(ref, version, source, chunks)— makeschunksexactly whatversionships fromsource. 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 thatsource(chunks of other sources keep it), and chunks left without versions are deleted. The order ofchunksis their document order; a reused chunk takes its position from the latest call.versionsgiven 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.versionsis highest first.LibraryChunkFilter:ecosystem,name,version(only chunks that version ships),source,path(exact). Heading matches outrank text matches.libraryStats({ ecosystem? }):Mapkeyed by<ecosystem>:<name>of every stored library (zero counts included) toLibraryStats { versions, chunks, issues }, in one query;versionscounts 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.
Analyses
Section titled “Analyses”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.
Database inspector
Section titled “Database inspector”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 againstmax_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 whetherresetQueries()is permitted; or{ available: false, reason }(SQLite, or nopg_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.
Implementations
Section titled “Implementations”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.
Contract tests
Section titled “Contract tests”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.