DevelopAI
@holtkeeper/libraries
Version-exact documentation of the third-party libraries the fleet depends on, for agents: a server-side indexer keeps, per library, a small matrix of versions (the ones in use and the ones an upgrade would land on) with their docs, release notes, API surface and, on demand, a source snapshot; libraryDocs answers questions about them as compact Markdown. The design is docs/library-docs.md.
The server wires it up (setting libraries, the indexing duty, the Dependencies and library index admin routes, and the packages toolset of MCP and internal agents): see Libraries in the server docs.
Everything lives in a LibraryStore (@holtkeeper/store) and an ArtifactStore (@holtkeeper/artifacts); registries and GitHub are injected, so tests run without network.
Public API
Section titled “Public API”Indexing
Section titled “Indexing”indexLibraries(options): Promise<LibraryIndexSummary>— one indexing run. Options:store: LibraryStore,artifacts: ArtifactStore;registries: Partial<Record<LibraryEcosystem, LibraryRegistry>>—npmRegistry(),goRegistry(), or fakes;github?: GitHubClient— without itrepository,releasesand the default issue hook are skipped;uses: LibraryUse[]— every repository’s resolved version of every external library (Go module paths with/vNare joined withlibraryOfModule);settings: LibraryIndexSettings—enabled,exclude/includeglobs (@types/*, optionally prefixednpm:orGo:; plain names inincludeare indexed even without uses),maxVersions,firstOfMajor,sourcesswitches,graceDays;isInternal?(ref)— libraries the fleet defines itself, left toapi-surface;apiExtractors?— per-ecosystem API readers, defaultdefaultApiExtractors(npmApiExtractor,goApiExtractor);issueIndexer?: LibraryHook— defaultindexIssuesfromsrc/issueswhengithubis given; runs withsources.issues;onProgress?(progress)—{ total, done, library?, libraries? }whenever a library starts (librariesare the ones in work,<ecosystem>:<name>,librarythe first of them;donecounts finished ones) and once withdone = totalat the end;siteSource?: SiteSource— runs withsources.site;latest?: LatestVersions— receives the registry’s newest release of every third-party library in use at the end of the run: indexed ones from the registry metadata the run fetches, librariesexcludeleaves out from a registry lookup of their own (never internal ones); entries of libraries no longer used are dropped, a failed lookup keeps the previous entry;maxRepositoryKb?(default 500 000),now?,signal?,log?.- The summary is
{ libraries, versionsAdded, versionsRemoved, librariesRemoved, failures: { library, version?, source, message }[] }.
latestVersions(kv): LatestVersions— the one place that knows the newest published version per library, by<ecosystem>:<name>(Go by module path without/vN), kept as one document (libraries:latest) in aKvStoreand written atomically where it hascompareAndSet:get(ref),all()andrecord(entries, keep?), each entry{ latest, checkedAt }.majorsBehind(version, latest)— breaking releases between them: majors, and minors below 1.0; 0 when not older or unparsable.LibraryHook = (library, { versions, oldestUsedReleaseAt?, now, signal? }) => Promise<unknown>— a library-wide source; it records its own status, and the indexer recordsfailedwhen it throws.parseLibraryName('npm:x' | 'Go:x' | 'x')— a setting entry as aLibraryRef(a bare name is Go when its first segment contains a dot).versionMatrix(uses, published, settings): MatrixVersion[]androlePriority— see Version matrix.LibraryRegistry.library(ref, inUse?)— the published library,undefinedwhen the registry does not know it;inUseare versions repositories resolve, so a registry can look where they point (Go: a/vNmodule path past a gap in the majors). Registries that need no hint ignore it.npmRegistry({ fetch?, url?, maxTarballBytes?, headers?, archive? }): LibraryRegistry— npmjs or any registry speaking its protocol aturl;headers(url)adds request headers per URL (a token for a private registry’s host),archivereplaces what archives keep (defaultkeepNpmFile, text only, 2 MB per file);normalizeRepository(field),keepNpmFile(path).tagResolver(github, { maxPages? }),tagCandidates(name, version, directory?),tagPrefixes,versionOfTag(tag, name, directory?),githubPath(repository),encodeRef(ref).readTarball(bytesOrStream, { stripTop?, keep?, maxFileBytes?, maxTotalBytes?, textOnly? }): Promise<ArchiveFiles>,isText(data),fileText(files, path)— tar and tar.gz (detected by its magic bytes) read as a stream: ustar, pax (xrecords,gglobal headers skipped) and GNU long names; headers are checked by checksum, unsafe paths and entries that are not kept are skipped without being held, so memory follows the kept files rather than the archive.createGitHubClient({ token?, tokens?, fetch?, apiUrl?, maxWaitMs?, cache?, cacheTtlSeconds?, signal?, log? }):GitHubClientwithrest,graphqlanddownload(path, { maxBytes }).- Token pool: every request goes to the token with the most of that request’s limit left, counting
core,searchandgraphqlapart from theX-RateLimit-*headers. A token whose limit ran out (or that got a secondary limit’sRetry-After) is passed over until its reset. With two or more tokens, each is identified once (GET /user); tokens of an account already in the pool are dropped with a log line, since GitHub counts limits per account. - Waiting: when every token is exhausted the client waits for the earliest reset when it is at most
maxWaitMsaway (default 60 s), aborted bysignal; otherwise it throwsGitHubRateLimitError. - Conditional requests: with a
cache(Store.kvfits), RESTGETs sendIf-None-Matchwith the storedETag, and a304, which does not count against GitHub’s limit, is answered with the stored body andnextlink. Bodies are keptcacheTtlSeconds(30 days). - Events:
onEvent(event)hears every answer ({ kind: 'request', token?, resource, status, notModified, limited },tokenthe index intokens) and every wait ({ kind: 'wait', resource, ms }), e.g. to count use per token. downloadreturns a stream that fails withDownloadTooLargeErrorpastmaxBytes(up front whenContent-Lengthsays so);limitStream(response, maxBytes, what)does the same for anyfetchresponse.
- Token pool: every request goes to the token with the most of that request’s limit left, counting
githubTokenInfo(token?, { fetch?, apiUrl?, signal? })→{ login?, limits?, error? }: the token’s account (GET /user) and live limits by resource (GET /rate_limit, not counted by GitHub); never throws.chunkMarkdown(markdown, max?),documentChunks(ref, source, path, markdown, { url?, prefix?, max? }),chunkId(ref, source, path, headings, text),slug(title),cleanHeading,headingVersion,headingMajors,chunkChars(1500).- Semver:
parseSemver,compareSemver,compareParsed,isPrerelease,majorOf,inRange(version, from?, to?)((from, to]),sameVersion. Accepts Govprefixes and+incompatible, orders prereleases by the semver rules, so it agrees withcompareGoVersions.
Sources
Section titled “Sources”Each per-version source returns a SourceOutcome { status: LibrarySourceStatus, patch? } that the indexer stores on the version.
archiveSource(store, target, files),archiveChunks,isArchiveDoc,archiveFileUrl— sourcearchive.apiSource(artifacts, target, files, extractor),ApiExtractor,npmApiExtractor,goApiExtractor,defaultApiExtractors— sourceapi.repositorySource(store, github, target, gitRef),repositoryChunks,keepRepositoryFile(path, directory?)— sourcerepository.listReleases(github, path, maxPages?),assignReleases(releases, versions, name, directory?),releaseChunks(ref, release),releasePath(tag),tagOfReleasePath(path)— sourcereleases.sourceSnapshots({ store, artifacts, github?, registries?, maxRepositoryKb?, maxBytes?, maxFileBytes?, now? }): SourceSnapshot— sourcesource, on demand:(ref, version) => Promise<{ id?, message? }>. A registry withsource(the Go module proxy) is asked first.resolveLibrary(store, { package, ecosystem? })→{ ref, library? }— the indexed library a tool argument names: withoutecosystema name with a/, a dotted first element and no@scopeis Go (isGoModuleName), else npm; a Go name may carry/vNor be a package import path inside the module, and the longest indexed module path prefixing it wins. Used bylibraryDocs,libraryIssuesand the server’s API tools.
Answers
Section titled “Answers”libraryDocs({ store, artifacts, issues?, source?, maxChars?, ownPackage?, ownSource? }): LibraryDocs— the interface ofaccess.ts, used by the MCP server and agent tools.issuesislibraryIssues(...)fromsrc/issues;sourceis asourceSnapshots(...).ownPackage(name)names the organization package a name (or a deep import path into it) belongs to; a library missing from the index that has one is answered with a pointer topackage_api <package>andpackage_sourceinstead of “not indexed”. WithownSource,sourcefor such a package is answered by it (called with the package nameownPackagegave), so the organization’s own code is readable too.libraryApi({ store, artifacts }): LibraryApi—get(ref, version): Promise<ApiPackage[] | undefined>andversions(ref): Promise<string[]>(versions with an API, highest first), sopackage_apiandpackage_changescan answer for external packages.thirdParty(origin, text),fenceFor(text)— the marker every answer wraps library text in.
Version matrix
Section titled “Version matrix”versionMatrix keeps, highest first:
- every version some repository resolves to (
used), with the repositories inusedBy; - the newest release of each used
major.minor(patch); - the newest release of each used major (
minor); - the newest stable release (
latest): the registry’slatesttag when it is stable, else the highest stable version; nothing above it is considered; - the newest release of every major above the highest used one, up to
latest(major); - with
firstOfMajor, the first release of each of those majors (first).
Prereleases count only when used. One version can carry several roles. Over maxVersions, versions are dropped by their best role in rolePriority order used > latest > minor > patch > major > first, older before newer within a role; used versions are always kept, even beyond the cap. Used versions the registry does not list stay in the matrix.
Example from the design: the fleet uses react 18.2.0, 18.3.1, 19.0.0, the newest release is 19.2.1: the matrix is 19.2.1 (latest, minor), 19.0.1 (patch), 19.0.0 (used), 18.3.1 (used, minor, patch), 18.2.0 (used, patch).
How indexing works
Section titled “How indexing works”indexLibraries groups uses by library, drops excluded (unless also included) and internal ones, adds plain names from include, and then works through the libraries, sorted by <ecosystem>:<name>: Libraries are indexed settings.concurrency at a time (default 3): each worker takes the next library when it finishes one, the run’s summary, tag cache and repository sizes are shared, and an unexpected error (a store failure, not a source failure) lets the other workers finish their library, takes no new ones and rejects the run.
- Registry metadata (
registrystatus on the library). A library the registry does not know (a private package, a typo) is not kept: a stored one is removed with its versions and counted inlibrariesRemoved. For known ones: description, homepage, normalized repository, latest, versions with dates, deprecations and commits. A failed lookup recordsfailedand leaves the library’s versions untouched. - Matrix: versions in it get their roles,
usedBy, date and deprecation, and loseleftAt; versions that left it get empty roles andleftAt, and are removedgraceDayslater (their chunks go with them unless other versions share them). - Per-version sources, skipped when the version already has them
okormissing(failedandskippedare retried next run):archiveandapishare one archive download;repositoryresolves the tag first (stored astag/commit) and is skipped for repositories overmaxRepositoryKb;- before that, the
apiandsourceArchiveartifacts are opened once, which refreshes their access time; when one is gone the field and its status are cleared, so the source runs again.
- Releases, library-wide: listed once and spread over the matrix versions whenever a version lacks the source or the matrix changed (see below).
- Hooks: the issue indexer (
sources.issues), then the docs site (sources.site, only when no version hasrepositorydocs, forlatestand the highest used version when it is in another major, refreshed aftergraceDays).
Libraries no longer used are marked like versions that left the matrix and removed with their versions, chunks and issues once both the library and every version are older than graceDays. Failures are isolated per source, recorded on it and listed in the summary; only an aborted signal rejects.
Artifacts are tagged { kind: 'library', library: '<ecosystem>:<name>', version, content: 'api' | 'source' } and named <ecosystem>/<name>/<version>/api.json or source.zip. Artifact refs do not protect blobs from sweep (retention looks only at access times), so the indexer keeps referenced artifacts alive by reading them each run and heals versions whose artifacts were swept. A maxBytes retention can still remove them between runs; the next run fetches them again.
Sources
Section titled “Sources”| Source | Kind | What |
|---|---|---|
archive |
chunks | Markdown (.md, .mdx, .markdown) and llms*.txt in the package archive, except licence, security, contributing and similar files and anything under node_modules or test folders; up to 300 files. npm chunk URLs point at unpkg. Go modules also get each package’s doc comment (goPackageDocs), under the path of its file and linked to pkg.go.dev. |
api |
artifact | npm: .d.ts/.d.mts/.d.cts and package.json files written to a temp folder and read with extractApi. Go: goApi over the module zip with the module path of the version’s major. JSON ApiPackage[], id in LibraryVersionRecord.api. |
repository |
chunks | GitHub tarball at the tag or commit: llms.txt, llms-full.txt, Markdown under docs/, website/docs/ and examples/ at the root and under the package directory; the root changelog and migration guides; the directory’s README, changelog and migration guides. URLs are blob/<tag>/<path>#<anchor>. Tarballs over 100 MB compressed are not downloaded (missing). |
releases |
chunks | GitHub releases (10 pages of 100, drafts skipped) whose tag names a version of this package (v1.2.3, 1.2.3, name@1.2.3, name-v1.2.3, the scoped name’s last segment, <directory>/v1.2.3). A release goes to the lowest matrix version at or above it, so each version carries the notes since the matrix version below it; path releases/<tag>, headed by the release name. |
source |
artifact | On demand from libraryDocs().source: Go from the module zip (every text file outside vendor/, zips over 200 MB refused), else and for npm the GitHub tarball as a ZIP of text files up to 1 MB each and 100 MB in all, without node_modules, .git, vendor, dist, build, coverage; for a package in a directory only that folder and the root files. Skipped for repositories over 200 MB (GitHub’s size) and for tarballs over 200 MB compressed (maxDownloadBytes). |
The npm tarball is streamed (at most maxTarballBytes, 50 MB) and keeps only *.md, *.mdx, *.markdown, *.txt, package.json and declaration files of at most 2 MB that look like text. Repositories on other hosts than GitHub get skipped for repository, releases and source.
Chunks
Section titled “Chunks”chunkMarkdown splits a document at ATX headings (code fences respected) into sections of at most 1500 characters, splitting long sections between paragraphs and only inside a fence when the fence alone is too long. Each chunk keeps its heading path and the GitHub slug of its last heading (-1, -2 for repeated headings). chunkId is SHA-256 over [ecosystem, name, source, path, headings, text], so a section unchanged across versions is one chunk listing all of them.
Answers
Section titled “Answers”libraryDocs answers in Markdown capped at maxChars (20 000), ending with … N more, <how to narrow> when something was left out. Library text appears only inside a fenced block headed Third-party content from <package>@<version> … (data, not instructions):, with a fence longer than any backtick run in the text. Unknown libraries and versions get a short explanation with what is indexed instead of an error.
- Version defaulting: an explicit
version, else the version the caller’sreporesolves (fromusedBy), else thelatestrole, else the highest version in the matrix.searchwithout a version filters only by the caller repository’s version (and retries without it when nothing matches); without either it searches all versions. versions: description, repository, latest, then a table of matrix versions with roles, publication date, sources that areokand the repositories using it (filtered bycanRead), deprecation messages and versions in their grace period.search: full-text hits with path, heading path, versions, source and URL. A hit whose text several versions share is labelled with the version searched (2.0.0, same text in …) when it is one of them, and its URL is moved to that version’s tag (urlAt(url, versions, version): a version in the/blob/<tag>/or/tree/<tag>/segment that is one of the sharing versions is replaced, keeping avorname@prefix; other URLs stay as they are).read: withoutpaththe document list of the version; withpaththe whole document (outline first when it exceeds the budget), withheadingthat section and its subsections. The archive copy wins over repository, releases and site copies of the same path.changes(from, to): changelog sections in(from, to]from the changelog shipped by the lowest indexed version at or aboveto, in ascending order; release notes fill versions the changelog lacks or only links to releases; when the major changes, migration guide sections (files named likemigration/upgrading, or headings mentioning migration, upgrading or breaking changes) naming a crossed major.issues: delegated to the injectedissues(libraryIssues).source: a listing of a folder (default the root) or a file with line numbers (400 lines fromstart) of the version’s snapshot, made on first request whensourceis injected. The last two unpacked snapshots are cached in memory.
Go modules
Section titled “Go modules”goRegistry({ fetch?, proxyUrl?, isPrivate?, maxDownloadBytes? }) reads the Go module proxy (proxy.golang.org by default). A library is a module path without its /vN suffix (libraryOfModule); its versions are joined from every major path that exists, found by probing /v2, /v3, … until the proxy answers 404 or 410, and again upward from every major in use (inUse), so a module that skips majors (v6 or v11 after v1) is found; latest is the newest major’s release. Pseudo-versions are left out, +incompatible versions are kept, versions keep Go’s v prefix and publish dates come from .info. A // Deprecated: comment in the go.mod of a major’s newest version marks every version of that major. The repository comes from the module path on GitHub, GitLab and Bitbucket, otherwise from the go-source/go-import meta tags of https://<path>?go-get=1; the homepage is pkg.go.dev. archive downloads the module zip of the right major path and keeps Markdown, text, go.mod and non-test .go files under 1 MB, without vendor/ and testdata/; source keeps every text file of the zip outside vendor/, for source snapshots. A module zip over maxDownloadBytes (default 200 MB) fails with DownloadTooLargeError before it is unzipped: up front from Content-Length, else once that many bytes arrived; a source snapshot then falls back to GitHub, or is skipped without a repository. Module paths isPrivate matches are never requested (neither the proxy nor go-get): library, archive and source answer undefined. goPrivateMatcher(patterns) builds it from GOPRIVATE-style patterns: comma-separated globs that each match a prefix of whole path elements.
goPackageDocs(files, module) reads the package doc comments of a module zip: one per importable directory (not internal/, vendor/, testdata/, nested modules or main packages), from doc.go when it has one, as Markdown headed # Package <import path> (goDocMarkdown: Go doc headings become ##, indented spans fenced code or list items; goPackageComment reads the comment group above a package clause without //go: directives).
Tags of a Go module are exactly v<version>, or <directory>/v<version> for a module in a repository folder (tagPrefixes), so a submodule never takes the root module’s tags or release notes.
goApi(files, { module?, version?, maxSymbols? }) from @holtkeeper/go-source turns those files into ApiPackage[] (ecosystem: 'Go', module set): one package per importable directory named by its import path, with exported functions, methods (Type.Method), types, constants and variables, their doc comments and Deprecated: notes. It scans gofmt-formatted source rather than parsing Go, so build constraints other than ignore are not applied and platform variants are deduplicated by name; internal/, package main and _test.go files are skipped. Go does not need to be installed. This package re-exports goApi, parseGoDoc and the module helpers (libraryOfModule, modulePathOf, isPseudoVersion, compareGoVersions, isStableGoVersion, escapeModulePath) from @holtkeeper/go-source for existing callers.
Docs sites
Section titled “Docs sites”siteSource({ fetch?, maxPages = 200, maxBytes = 5_000_000, delayMs = 500 }) is an optional fallback (sources.site, off by default) that the indexer runs only when no version has repository docs. It starts from the library’s homepage, ignoring homepages on GitHub, GitLab, Bitbucket, npm, pkg.go.dev and godoc.org. It reads llms-full.txt; failing that, llms.txt and the same-host pages it links; failing that, sitemap pages (from robots.txt or /sitemap.xml, nested indexes followed), preferring /docs, /guide, /api and /reference. HTML is reduced to the main content as Markdown and chunked like other documents. It honours robots.txt for * and holtkeeper, makes one request at a time with a pause between, and never throws: the status is missing when nothing usable was found. Sites that need JavaScript are out of scope. Chunks go to the latest version and to the highest used version when that is in another major.
Issues
Section titled “Issues”Issue threads of a library’s repository answer “this error after upgrading”. GitHub only; other hosts are recorded as skipped.
Index — indexIssues({ store, github, library, oldestUsedReleaseAt?, now, maxIssues = 400, minReactions = 5, maxPages = 10 }), called by the indexer’s default issue hook when a GitHub client is given and sources.issues is on.
- Incremental by
updatedAtfromLibraryRecord.issuesCursor(JSON{ issues?, discussions? }); writes back the cursor andsources.issuesand never throws for GitHub failures. - Window: threads created since six months before the oldest used release, else two years back.
- Kept: closed issues with a closing or merged cross-referencing pull request of the same repository, a label containing
bug,regressionorbreaking, or at leastminReactionsreactions; answered discussions. Duplicates are skipped; open issues are left to live search. - Bodies are trimmed to about 2000 characters, without HTML comments, checklists or empty template headings.
- With a token, GraphQL: linked pull requests, the first maintainer reply (OWNER, MEMBER, COLLABORATOR) as
answer, discussions with their accepted answer. Without one, REST/repos/{o}/{r}/issues?state=closed&since=…without answers or discussions. fixedIncomes from a version-like milestone of a linked pull request or the issue, else from a maintainer reply saying “fixed in / released in X”.- At most
maxPagespages andmaxIssuesthreads per run, so a backlog is indexed over several runs. - Monorepos (
repository.directory): threads whose title or labels name the package come first; threads whose package-scoped label (pkg:,package:,scope:,area/,module:) names another package are dropped; others fill the remaining room.
Live search — liveIssueSearch({ github, cache?, ttlSeconds = 86400 }) calls GET /search/issues?q=<terms> repo:o/r is:issue with GitHub qualifiers removed from the query, cached a day per repository and query (Store.kv fits the cache). Past GitHub’s 30 searches a minute the answer is the cached result or nothing, with a note.
Digests — digestIssue(issue, summarize) and digestOnDemand({ store, summarize?, maxPerCall = 3 }): one model call per thread through an injected summarize(prompt, signal?), so the caller charges the AI budget. The prompt fences the thread as untrusted data and asks for JSON { problem, symptoms[], affected?, fixedIn?, workaround? }, parsed defensively. On demand, the top hits without a digest are digested and stored.
Answer — libraryIssues({ store, live?, digest?, budgetChars = 20000 }) implements LibraryDocs['issues']: error messages and stack frames are searched as quoted phrases (plain words when the phrase finds nothing), live hits fill up to limit (default 5, at most 20), and each hit renders as #123 [closed, fixed in 1.2.3] Title — url with labels, reactions, pull requests, the digest or trimmed body and answer, and a note whether the fix is after the caller’s version. Thread text sits inside a <third-party-content> block marked as data.