@jini-ai/registry 0.1.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +134 -0
  3. package/dist/database-backend.d.ts +24 -9
  4. package/dist/database-backend.js +18 -20
  5. package/dist/github-backend.d.ts +22 -9
  6. package/dist/github-backend.js +13 -12
  7. package/dist/github-client.d.ts +11 -22
  8. package/dist/github-client.js +52 -53
  9. package/dist/index.d.ts +57 -1
  10. package/dist/ports.d.ts +4 -0
  11. package/dist/ports.js +2 -0
  12. package/dist/static-backend.d.ts +24 -12
  13. package/dist/static-backend.js +25 -22
  14. package/dist/tool-catalog/index.d.ts +27 -0
  15. package/dist/tool-catalog/index.js +2 -0
  16. package/dist/tool-catalog/sqlite.d.ts +73 -0
  17. package/dist/tool-catalog/sqlite.js +87 -0
  18. package/dist/tool-catalog-builder/index.d.ts +4 -0
  19. package/dist/tool-catalog-builder/index.js +4 -0
  20. package/dist/tool-catalog-builder/ports.d.ts +60 -0
  21. package/dist/tool-catalog-builder/ports.js +2 -0
  22. package/dist/tool-catalog-builder/query.d.ts +32 -0
  23. package/dist/tool-catalog-builder/query.js +68 -0
  24. package/dist/tool-catalog-builder/search-enricher.d.ts +13 -0
  25. package/dist/tool-catalog-builder/search-enricher.js +26 -0
  26. package/dist/tool-catalog-builder/sqlite.d.ts +14 -0
  27. package/dist/tool-catalog-builder/sqlite.js +17 -0
  28. package/dist/trust.d.ts +14 -3
  29. package/dist/trust.js +5 -5
  30. package/dist/versioning.d.ts +8 -2
  31. package/dist/versioning.js +2 -2
  32. package/package.json +55 -6
  33. package/dist/database-backend.d.ts.map +0 -1
  34. package/dist/database-backend.js.map +0 -1
  35. package/dist/github-backend.d.ts.map +0 -1
  36. package/dist/github-backend.js.map +0 -1
  37. package/dist/github-client.d.ts.map +0 -1
  38. package/dist/github-client.js.map +0 -1
  39. package/dist/index.d.ts.map +0 -1
  40. package/dist/index.js.map +0 -1
  41. package/dist/static-backend.d.ts.map +0 -1
  42. package/dist/static-backend.js.map +0 -1
  43. package/dist/trust.d.ts.map +0 -1
  44. package/dist/trust.js.map +0 -1
  45. package/dist/versioning.d.ts.map +0 -1
  46. package/dist/versioning.js.map +0 -1
@@ -1,3 +1,30 @@
1
+ /**
2
+ * @module github-client
3
+ *
4
+ * A concrete `GithubRegistryClient` (the interface `github-backend.ts`
5
+ * defines and takes as an injected dependency) implemented against GitHub's
6
+ * real REST API. Per `archived provenance ledger`'s "2026-07-21 hardening pass": "No
7
+ * concrete `GithubRegistryClient` HTTP implementation exists in this
8
+ * package — `readManifest`/`createPublishPullRequest` are an injected
9
+ * interface with no concrete implementation anywhere in this repo." This
10
+ * file closes that gap.
11
+ *
12
+ * Built directly against GitHub's published REST API docs (Contents API,
13
+ * Git Data API, Pulls API — see each function's doc comment for the exact
14
+ * endpoint/behavior it was verified against), following the same "raw
15
+ * `fetch`, no SDK dependency" convention `@jini-ai/deploy`'s `netlify.ts`/
16
+ * `github-pages.ts` already establish (this package has no `@jini-ai/deploy`
17
+ * dependency and does not gain one — the blob/tree/commit/ref mechanics
18
+ * below are written fresh for this package, not shared cross-package, since
19
+ * there is no existing shared low-level GitHub REST helper package).
20
+ * The HTTP orchestration now uses a host-injected transport port: hosts can
21
+ * bind that established timeout helper while preserving its cancellation and
22
+ * error semantics, and tests can exercise the request flow without global I/O.
23
+ * The kernel HttpClientPort owns timeout/cancellation and timeout error types. Requests retain
24
+ * the QUICK total bound and an explicit idle budget; request orchestration never chooses global
25
+ * fetch. Hosts can bind the existing helper or a policy-enforcing egress client without a new port.
26
+ */
27
+ import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
1
28
  const GITHUB_API = 'https://api.github.com';
2
29
  /** Pinned per GitHub's own recommendation (`X-GitHub-Api-Version` header), matching `@jini-ai/deploy`'s `github-pages.ts` — see that file's doc comment for the sourcing rationale. */
3
30
  const GITHUB_API_VERSION = '2026-03-10';
@@ -10,7 +37,9 @@ const GITHUB_API_VERSION = '2026-03-10';
10
37
  export class GithubApiRegistryClient {
11
38
  token;
12
39
  apiUrl;
13
- constructor(options = {}) {
40
+ http;
41
+ constructor({ http }, options = {}) {
42
+ this.http = http;
14
43
  this.token = options.token;
15
44
  this.apiUrl = options.apiUrl ?? GITHUB_API;
16
45
  }
@@ -37,14 +66,14 @@ export class GithubApiRegistryClient {
37
66
  * @throws If the file does not exist, is a directory, is too large for
38
67
  * this endpoint's inline-content response, or is not valid JSON.
39
68
  */
40
- async readManifest(owner, repo, ref, path) {
69
+ async readManifest({ owner, repo, ref, path }) {
41
70
  const url = `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(path)}?${new URLSearchParams({ ref }).toString()}`;
42
- const resp = await fetch(url, { headers: githubHeaders(this.token) });
71
+ const resp = await this.http.send({ request: { url, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
43
72
  if (resp.status === 404) {
44
73
  throw new Error(`Registry manifest not found: ${owner}/${repo}@${ref}:${path}`);
45
74
  }
46
75
  const json = await readGithubJson(resp);
47
- if (!resp.ok) {
76
+ if (!(resp.status >= 200 && resp.status < 300)) {
48
77
  throw githubError(Array.isArray(json) ? {} : json, resp.status, `Failed to read registry manifest ${owner}/${repo}@${ref}:${path}.`);
49
78
  }
50
79
  if (Array.isArray(json)) {
@@ -98,24 +127,20 @@ export class GithubApiRegistryClient {
98
127
  return this.ensurePullRequest(owner, repo, request);
99
128
  }
100
129
  async getRefSha(owner, repo, branch) {
101
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/ref/heads/${enc(branch)}`, {
102
- headers: githubHeaders(this.token),
103
- });
130
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/ref/heads/${enc(branch)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
104
131
  if (resp.status === 404)
105
132
  return undefined;
106
133
  const json = await readGithubJson(resp);
107
- if (!resp.ok)
134
+ if (!(resp.status >= 200 && resp.status < 300))
108
135
  throw githubError(json, resp.status, 'GitHub ref lookup failed.');
109
136
  const object = json.object;
110
137
  return typeof object?.sha === 'string' ? object.sha : undefined;
111
138
  }
112
139
  /** `GET /repos/{owner}/{repo}/git/commits/{sha}` (Git Data API) — the tree API's `base_tree` param needs a *tree* sha, not the commit sha `getRefSha` returns. */
113
140
  async getCommitTreeSha(owner, repo, commitSha) {
114
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(commitSha)}`, {
115
- headers: githubHeaders(this.token),
116
- });
141
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(commitSha)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
117
142
  const json = await readGithubJson(resp);
118
- if (!resp.ok)
143
+ if (!(resp.status >= 200 && resp.status < 300))
119
144
  throw githubError(json, resp.status, 'GitHub base commit lookup failed.');
120
145
  const tree = json.tree;
121
146
  const sha = typeof tree?.sha === 'string' ? tree.sha : '';
@@ -124,13 +149,9 @@ export class GithubApiRegistryClient {
124
149
  return sha;
125
150
  }
126
151
  async createBlob(owner, repo, content) {
127
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/blobs`, {
128
- method: 'POST',
129
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
130
- body: JSON.stringify({ content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' }),
131
- });
152
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/blobs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
132
153
  const json = await readGithubJson(resp);
133
- if (!resp.ok)
154
+ if (!(resp.status >= 200 && resp.status < 300))
134
155
  throw githubError(json, resp.status, 'GitHub blob creation failed.');
135
156
  const sha = typeof json.sha === 'string' ? json.sha : '';
136
157
  if (!sha)
@@ -143,13 +164,9 @@ export class GithubApiRegistryClient {
143
164
  const blobSha = await this.createBlob(owner, repo, file.content);
144
165
  tree.push({ path: file.path, mode: '100644', type: 'blob', sha: blobSha });
145
166
  }
146
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/trees`, {
147
- method: 'POST',
148
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
149
- body: JSON.stringify({ base_tree: baseTreeSha, tree }),
150
- });
167
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/trees`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ base_tree: baseTreeSha, tree }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
151
168
  const json = await readGithubJson(resp);
152
- if (!resp.ok)
169
+ if (!(resp.status >= 200 && resp.status < 300))
153
170
  throw githubError(json, resp.status, 'GitHub tree creation failed.');
154
171
  const sha = typeof json.sha === 'string' ? json.sha : '';
155
172
  if (!sha)
@@ -157,13 +174,9 @@ export class GithubApiRegistryClient {
157
174
  return sha;
158
175
  }
159
176
  async createCommit(owner, repo, message, treeSha, parents) {
160
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits`, {
161
- method: 'POST',
162
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
163
- body: JSON.stringify({ message, tree: treeSha, parents }),
164
- });
177
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ message, tree: treeSha, parents }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
165
178
  const json = await readGithubJson(resp);
166
- if (!resp.ok)
179
+ if (!(resp.status >= 200 && resp.status < 300))
167
180
  throw githubError(json, resp.status, 'GitHub commit creation failed.');
168
181
  const sha = typeof json.sha === 'string' ? json.sha : '';
169
182
  if (!sha)
@@ -180,24 +193,16 @@ export class GithubApiRegistryClient {
180
193
  * `@jini-ai/deploy`'s `github-pages.ts` already documents for its own ref update.
181
194
  */
182
195
  async ensureBranch(owner, repo, branch, sha) {
183
- const createResp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs`, {
184
- method: 'POST',
185
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
186
- body: JSON.stringify({ ref: `refs/heads/${branch}`, sha }),
187
- });
188
- if (createResp.ok)
196
+ const createResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ ref: `refs/heads/${branch}`, sha }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
197
+ if ((createResp.status >= 200 && createResp.status < 300))
189
198
  return;
190
199
  if (createResp.status !== 409 && createResp.status !== 422) {
191
200
  const json = await readGithubJson(createResp);
192
201
  throw githubError(json, createResp.status, 'GitHub branch creation failed.');
193
202
  }
194
- const updateResp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs/heads/${enc(branch)}`, {
195
- method: 'PATCH',
196
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
197
- body: JSON.stringify({ sha, force: true }),
198
- });
203
+ const updateResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs/heads/${enc(branch)}`, method: 'PATCH', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ sha, force: true }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
199
204
  const json = await readGithubJson(updateResp);
200
- if (!updateResp.ok)
205
+ if (!(updateResp.status >= 200 && updateResp.status < 300))
201
206
  throw githubError(json, updateResp.status, 'GitHub branch update failed.');
202
207
  }
203
208
  /**
@@ -210,13 +215,9 @@ export class GithubApiRegistryClient {
210
215
  * analogous "create-or-find" race.
211
216
  */
212
217
  async ensurePullRequest(owner, repo, request) {
213
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls`, {
214
- method: 'POST',
215
- headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }),
216
- body: JSON.stringify({ title: request.title, body: request.body, head: request.branchName, base: request.baseRef }),
217
- });
218
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ title: request.title, body: request.body, head: request.branchName, base: request.baseRef }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
218
219
  const json = await readGithubJson(resp);
219
- if (resp.ok) {
220
+ if ((resp.status >= 200 && resp.status < 300)) {
220
221
  const url = typeof json.html_url === 'string' ? json.html_url : '';
221
222
  if (!url)
222
223
  throw new Error('GitHub pull request response did not include an html_url.');
@@ -232,11 +233,9 @@ export class GithubApiRegistryClient {
232
233
  }
233
234
  async findOpenPullRequest(owner, repo, base, branch) {
234
235
  const query = new URLSearchParams({ head: `${owner}:${branch}`, base, state: 'open' });
235
- const resp = await fetch(`${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls?${query.toString()}`, {
236
- headers: githubHeaders(this.token),
237
- });
236
+ const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls?${query.toString()}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
238
237
  const json = await readGithubJson(resp);
239
- if (!resp.ok || !Array.isArray(json))
238
+ if (!(resp.status >= 200 && resp.status < 300) || !Array.isArray(json))
240
239
  return undefined;
241
240
  const first = json[0];
242
241
  return first && typeof first.html_url === 'string' ? first.html_url : undefined;
@@ -259,7 +258,7 @@ function githubHeaders(token, extra = {}) {
259
258
  }
260
259
  async function readGithubJson(resp) {
261
260
  try {
262
- return (await resp.json());
261
+ return JSON.parse(resp.bodyText);
263
262
  }
264
263
  catch (cause) {
265
264
  throw new Error('GitHub returned a non-JSON response.', { cause });
package/dist/index.d.ts CHANGED
@@ -5,8 +5,63 @@
5
5
  * (`static`/`github`/`database`) plus the shared version-resolution helpers
6
6
  * they build on. Wire types (`RegistryEntry`, `RegistryManifest`,
7
7
  * `RegistryBackend`, ...) live in `@jini-ai/protocol`; this package only adds
8
- * concrete backend logic, matching `@jini-ai/sqlite`'s split (protocol defines
8
+ * concrete backend logic, matching concern-owned storage adapters' split (protocol defines
9
9
  * the port, a leaf package implements adapters against it).
10
+
11
+ * Archived provenance rationale:
12
+ * ## Why a new package instead of folding into `@jini/core` or `@jini/sqlite`
13
+ *
14
+ * The task brief suggested `@jini/core` as a likely home. Read `@jini/core`'s
15
+ * own `archived provenance ledger` first: its charter is explicitly composition-only — "a
16
+ * from-scratch implementation of the typed composition contract... there is
17
+ * nothing to port" — it holds zero concrete port/adapter implementations
18
+ * today (`token.ts`/`pack.ts`/`bindings.ts`/`daemon.ts` are all pure DI
19
+ * machinery). Adding stateful backend classes (in-memory, GitHub-PR-mutating,
20
+ * sqlite-backed) would be a first-of-its-kind widening of that charter, which
21
+ * reads as exactly the kind of ad-hoc scope creep extraction-plan.md §9 warns
22
+ * against ("a new kernel token requires a kernel invariant, not merely a need
23
+ * discovered by the first consumer").
24
+ *
25
+ * `@jini/sqlite` was the other candidate (it already holds one concrete
26
+ * `better-sqlite3`-backed adapter, `event-log.ts`, implementing `@jini/daemon`'s
27
+ * `EventLog` port). But `@jini/sqlite`'s own archived provenance ledger scopes it
28
+ * specifically to durable adapters for daemon/core kernel ports; a registry
29
+ * backend is not a kernel port and two of the three backends here
30
+ * (`static`/`github`) have no sqlite dependency at all.
31
+ *
32
+ * Instead this follows the same shape as `@jini/sqlite` itself: `@jini/protocol`
33
+ * defines the pure wire types and the `RegistryBackend` port (already true
34
+ * before this change — see "What already existed" below); this new leaf
35
+ * package holds concrete backend implementations against that port, exactly
36
+ * as `@jini/sqlite` holds concrete `EventLog` implementations against
37
+ * `@jini/daemon`'s port.
38
+ *
39
+ * ## 2026-10-02 registry merge and object arguments (dbpkg-registry)
40
+ *
41
+ * The catalog-builder subpath keeps descriptor enumeration, source classification,
42
+ * search vocabulary and clock policy behind host ports. Its SQLite bridge lives in
43
+ * `src/tool-catalog-builder/sqlite.ts`, separately from the provider-free barrel,
44
+ * so a browser or alternate search backend never acquires a storage dependency.
45
+ * The bridge borrows its connection; the caller allocates one database per independent
46
+ * snapshot and owns retirement. Reusing the same database intentionally reseeds that
47
+ * shared snapshot rather than allocating or closing an implicit default database.
48
+ *
49
+ * All existing public export names are retained. Functions and constructors now take
50
+ * required argument objects followed by optional argument objects; no old-shape
51
+ * wrappers or aliases were added. Backend methods match the current protocol port.
52
+ * `src/ports.ts` defines database, HTTP and clock seams. The GitHub client passes the
53
+ * existing QUICK timeout to its required transport port, which owns timeout error
54
+ * and cancellation behavior. Default timestamps still use the system clock. SQL,
55
+ * transaction boundaries, canonical signing bytes, BM25 weights and error messages
56
+ * for valid argument shapes remain unchanged. Unknown trust/backend modes now fail
57
+ * closed through the existing protocol schemas.
58
+ *
59
+ * No rationale comment was removed by this job. Manifest/barrel/changelog merge
60
+ * proposals and cross-package caller needs are recorded in
61
+ * `dbpkg-registry-merge-needs.json` and `dbpkg-registry-handoff.md`. The existing dirty
62
+ * manifest, root barrel and changelog remain owned by their previous writers.
63
+ * Tests are written; execution, typecheck, build and packaging are UNPROVEN because
64
+ * the owner explicitly deferred verification. No version change or lockfile edit.
10
65
  */
11
66
  export type { ParsedRegistrySpecifier, ResolvedRegistryEntryVersion } from './versioning.js';
12
67
  export { parseRegistrySpecifier, resolveRegistryEntryVersion } from './versioning.js';
@@ -20,4 +75,5 @@ export type { GithubOidcTrustRoot, RegistryTrustRoot, SignatureVerificationResul
20
75
  export { GITHUB_ACTIONS_OIDC_ISSUER, canonicalRegistrySigningPayload, verifyRegistryEntrySignatures, verifyRegistrySignature } from './trust.js';
21
76
  export type { GithubApiRegistryClientOptions } from './github-client.js';
22
77
  export { GithubApiRegistryClient } from './github-client.js';
78
+ export type { RegistryDatabasePort } from './ports.js';
23
79
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { SqliteDb } from '@jini-ai/db/sqlite';
2
+ /** The host owns the connection and its lifetime; registry never opens a default database. */
3
+ export type RegistryDatabasePort = Pick<SqliteDb, 'prepare' | 'exec' | 'transaction'>;
4
+ //# sourceMappingURL=ports.d.ts.map
package/dist/ports.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -4,17 +4,17 @@
4
4
  * A read-mostly `RegistryBackend` over an in-memory {@link RegistryManifest}:
5
5
  * list/search/resolve/doctor computed directly from `manifest.entries`, no
6
6
  * publish/yank support. The base class every other backend in this package
7
- * extends — `github-backend` overrides `getManifest()`'s source and adds
8
- * publish/yank over a GitHub PR mutation; `database-backend` overrides
7
+ * extends — `github-backend` loads one manifest snapshot during construction and adds
8
+ * publish/yank over a GitHub PR mutation without refreshing that snapshot; `database-backend` overrides
9
9
  * `getManifest()` to read from sqlite and adds publish/yank as direct writes.
10
10
  */
11
11
  import { type RegistryBackend, type RegistryBackendKind, type RegistryDoctorReport, type RegistryEntry, type RegistryListFilter, type RegistryManifest, type RegistryPublishRequest, type RegistrySearchQuery, type RegistrySearchResult, type RegistryTrust, type ResolvedRegistryEntry } from '@jini-ai/protocol';
12
+ import type { Clock } from '@jini-ai/core/primitives';
12
13
  import { type RegistryTrustRoot } from './trust.js';
13
14
  export interface StaticRegistryBackendOptions {
14
- id: string;
15
15
  kind?: RegistryBackendKind;
16
- trust: RegistryTrust;
17
- manifest: RegistryManifest;
16
+ /** Inject the kernel clock for reproducible storage and diagnostic timestamps. */
17
+ clock?: Clock;
18
18
  /**
19
19
  * Optional per-entry signature trust root (currently `github-oidc` only —
20
20
  * see `trust.ts`). Omitting this is the pre-existing, unchanged default:
@@ -31,12 +31,24 @@ export declare class StaticRegistryBackend implements RegistryBackend {
31
31
  readonly trust: RegistryTrust;
32
32
  protected readonly manifestData: RegistryManifest;
33
33
  protected readonly trustRoot: RegistryTrustRoot | undefined;
34
- constructor(options: StaticRegistryBackendOptions);
35
- list(filter?: RegistryListFilter): Promise<RegistryEntry[]>;
36
- search(input: RegistrySearchQuery): Promise<RegistrySearchResult[]>;
37
- resolve(name: string, range?: string): Promise<ResolvedRegistryEntry | null>;
38
- manifest(name: string, version: string): Promise<RegistryEntry | null>;
39
- doctor(): Promise<RegistryDoctorReport>;
34
+ protected readonly clock: Clock;
35
+ constructor(required: {
36
+ id: string;
37
+ trust: RegistryTrust;
38
+ manifest: RegistryManifest;
39
+ }, options?: StaticRegistryBackendOptions);
40
+ list(_required: Record<string, never>, filter?: NonNullable<RegistryListFilter>): Promise<RegistryEntry[]>;
41
+ search(required: Pick<RegistrySearchQuery, 'query'>, optional?: Omit<RegistrySearchQuery, 'query'>): Promise<RegistrySearchResult[]>;
42
+ resolve({ name }: {
43
+ name: string;
44
+ }, { range }?: {
45
+ range?: string | undefined;
46
+ }): Promise<ResolvedRegistryEntry | null>;
47
+ manifest({ name, version }: {
48
+ name: string;
49
+ version: string;
50
+ }): Promise<RegistryEntry | null>;
51
+ doctor(_required: Record<string, never>): Promise<RegistryDoctorReport>;
40
52
  protected getManifest(): RegistryManifest;
41
53
  }
42
54
  /**
@@ -64,5 +76,5 @@ export declare class StaticRegistryBackend implements RegistryBackend {
64
76
  * @returns The schema-parsed (and thus schema-shaped) request.
65
77
  * @throws If `request` does not conform to `RegistryPublishRequestSchema`.
66
78
  */
67
- export declare function assertValidPublishRequest(request: RegistryPublishRequest): RegistryPublishRequest;
79
+ export declare function assertValidPublishRequest(required: Pick<RegistryPublishRequest, 'entry'>, optional?: Omit<RegistryPublishRequest, 'entry'>): RegistryPublishRequest;
68
80
  //# sourceMappingURL=static-backend.d.ts.map
@@ -4,11 +4,11 @@
4
4
  * A read-mostly `RegistryBackend` over an in-memory {@link RegistryManifest}:
5
5
  * list/search/resolve/doctor computed directly from `manifest.entries`, no
6
6
  * publish/yank support. The base class every other backend in this package
7
- * extends — `github-backend` overrides `getManifest()`'s source and adds
8
- * publish/yank over a GitHub PR mutation; `database-backend` overrides
7
+ * extends — `github-backend` loads one manifest snapshot during construction and adds
8
+ * publish/yank over a GitHub PR mutation without refreshing that snapshot; `database-backend` overrides
9
9
  * `getManifest()` to read from sqlite and adds publish/yank as direct writes.
10
10
  */
11
- import { RegistryEntrySchema, RegistryListFilterSchema, RegistryPublishRequestSchema, RegistrySearchQuerySchema, } from '@jini-ai/protocol';
11
+ import { RegistryBackendKindSchema, RegistryEntrySchema, RegistryListFilterSchema, RegistryPublishRequestSchema, RegistrySearchQuerySchema, RegistryTrustSchema, } from '@jini-ai/protocol';
12
12
  import { parseRegistrySpecifier, resolveRegistryEntryVersion } from './versioning.js';
13
13
  import { verifyRegistryEntrySignatures } from './trust.js';
14
14
  export class StaticRegistryBackend {
@@ -17,14 +17,17 @@ export class StaticRegistryBackend {
17
17
  trust;
18
18
  manifestData;
19
19
  trustRoot;
20
- constructor(options) {
21
- this.id = options.id;
22
- this.kind = options.kind ?? 'http';
23
- this.trust = options.trust;
24
- this.manifestData = options.manifest;
20
+ clock;
21
+ constructor(required, options = {}) {
22
+ this.id = required.id;
23
+ // Trust is host policy, never inferred from the transport; reject unknown modes.
24
+ this.kind = RegistryBackendKindSchema.parse(options.kind ?? 'http');
25
+ this.trust = RegistryTrustSchema.parse(required.trust);
26
+ this.manifestData = required.manifest;
25
27
  this.trustRoot = options.trustRoot;
28
+ this.clock = options.clock ?? { nowMs: () => Date.now() };
26
29
  }
27
- async list(filter) {
30
+ async list(_required, filter = {}) {
28
31
  const parsedFilter = RegistryListFilterSchema.parse(filter);
29
32
  let entries = validEntries(this.getManifest());
30
33
  if (!parsedFilter?.includeYanked) {
@@ -49,13 +52,13 @@ export class StaticRegistryBackend {
49
52
  }
50
53
  return entries;
51
54
  }
52
- async search(input) {
53
- const query = RegistrySearchQuerySchema.parse(input);
55
+ async search(required, optional = {}) {
56
+ const query = RegistrySearchQuerySchema.parse({ ...required, ...optional });
54
57
  const terms = query.query.toLowerCase().split(/\s+/g).filter(Boolean);
55
58
  const tags = new Set((query.tags ?? []).map((tag) => tag.toLowerCase()));
56
59
  // Pass `includeYanked` through to `list` so search honors the same
57
60
  // filter contract instead of unconditionally dropping yanked entries.
58
- const entries = await this.list({ includeYanked: query.includeYanked });
61
+ const entries = await this.list({}, { includeYanked: query.includeYanked });
59
62
  const results = [];
60
63
  for (const entry of entries) {
61
64
  if (tags.size > 0) {
@@ -77,12 +80,12 @@ export class StaticRegistryBackend {
77
80
  .sort((left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name))
78
81
  .slice(0, query.limit ?? 100);
79
82
  }
80
- async resolve(name, range) {
81
- const parsed = parseRegistrySpecifier(range ? `${name}@${range}` : name);
83
+ async resolve({ name }, { range } = {}) {
84
+ const parsed = parseRegistrySpecifier({ input: range ? `${name}@${range}` : name });
82
85
  const entry = validEntries(this.getManifest()).find((candidate) => candidate.name.toLowerCase() === parsed.name.toLowerCase());
83
86
  if (!entry)
84
87
  return null;
85
- const resolvedVersion = resolveRegistryEntryVersion(entry, parsed.range);
88
+ const resolvedVersion = resolveRegistryEntryVersion({ entry }, { requestedRange: parsed.range });
86
89
  if (!resolvedVersion)
87
90
  return null;
88
91
  // Additive alongside `trust`: never replaces or narrows the
@@ -90,7 +93,7 @@ export class StaticRegistryBackend {
90
93
  // as before. A backend with no `trustRoot` configured (the unchanged
91
94
  // default) always resolves `verified: false` here without attempting
92
95
  // any cryptographic work — see `trust.ts`'s `verifyRegistryEntrySignatures`.
93
- const verification = verifyRegistryEntrySignatures(entry, this.trustRoot);
96
+ const verification = verifyRegistryEntrySignatures({ entry }, { trustRoot: this.trustRoot });
94
97
  return {
95
98
  backendId: this.id,
96
99
  backendKind: this.kind,
@@ -113,11 +116,11 @@ export class StaticRegistryBackend {
113
116
  manifestDigest: resolvedVersion.manifestDigest,
114
117
  };
115
118
  }
116
- async manifest(name, version) {
117
- const resolved = await this.resolve(name, version);
119
+ async manifest({ name, version }) {
120
+ const resolved = await this.resolve({ name }, { range: version });
118
121
  return resolved?.entry ?? null;
119
122
  }
120
- async doctor() {
123
+ async doctor(_required) {
121
124
  const issues = [];
122
125
  // Deliberately audits the RAW manifest entries (not the `validEntries()`
123
126
  // schema-filtered set `list`/`search`/`resolve` use) — doctor's whole
@@ -202,7 +205,7 @@ export class StaticRegistryBackend {
202
205
  return {
203
206
  ok: !issues.some((issue) => issue.severity === 'error'),
204
207
  backendId: this.id,
205
- checkedAt: Date.now(),
208
+ checkedAt: this.clock.nowMs(),
206
209
  entriesChecked: entries.length,
207
210
  issues,
208
211
  };
@@ -257,8 +260,8 @@ function validEntries(manifest) {
257
260
  * @returns The schema-parsed (and thus schema-shaped) request.
258
261
  * @throws If `request` does not conform to `RegistryPublishRequestSchema`.
259
262
  */
260
- export function assertValidPublishRequest(request) {
261
- const parsed = RegistryPublishRequestSchema.safeParse(request);
263
+ export function assertValidPublishRequest(required, optional = {}) {
264
+ const parsed = RegistryPublishRequestSchema.safeParse({ ...required, ...optional });
262
265
  if (!parsed.success) {
263
266
  throw new Error(`Invalid registry publish request: ${parsed.error.message}`);
264
267
  }
@@ -0,0 +1,27 @@
1
+ /** Searchable tool descriptors; no SQL, driver, or content-registry coupling. */
2
+ export interface ToolCatalogEntry {
3
+ readonly id: string;
4
+ readonly description: string;
5
+ /** JSON-Schema-shaped, `unknown` for the same reason `@jini-ai/core`'s `ToolDescriptor.inputSchema` is — this table never parses or validates it. */
6
+ readonly inputSchema?: unknown;
7
+ /** `first-party | plugin | unverified` — carried into what a model sees, per `PROP` §7.1. Every entry seeded from an in-tree `ToolRegistry` today is `first-party`. */
8
+ readonly source: string;
9
+ }
10
+ export interface ToolCatalogSearchHit {
11
+ readonly id: string;
12
+ readonly description: string;
13
+ readonly source: string;
14
+ readonly score: number;
15
+ }
16
+ /** Structural search/describe seam for HTTP or assistant composition. */
17
+ export interface ToolCatalogQuery {
18
+ search(required: {
19
+ query: string;
20
+ }, optional?: {
21
+ limit?: number;
22
+ }): readonly ToolCatalogSearchHit[];
23
+ describe(required: {
24
+ id: string;
25
+ }): ToolCatalogEntry | null;
26
+ }
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @module db/tool-catalog/tool-catalog
3
+ *
4
+ * A durable, searchable snapshot of a `ToolRegistry`'s public descriptors (id/description/
5
+ * inputSchema — never the handler or policy) — v0 of `ai-control-plane.md` §29 /
6
+ * `PROP-tool-catalog-discovery-2026-07-26.md`, scoped down for a first real end-to-end proof
7
+ * rather than the full design: no versioning, no principal narrowing, no provider indirection.
8
+ * Every row's id is still resolved against a live `ToolRegistry`/`ToolExecutor` at call time —
9
+ * this table only makes that id *discoverable* before the caller already knows it.
10
+ *
11
+ * Deliberately NOT wired into `schema/migrate.ts` — `migrate.ts`'s own header explains why
12
+ * (`capability_definitions`/`capability_executions` were added there 2026-07-24 and removed
13
+ * 2026-07-25 for having zero consumers in every daemon's database). `ensureToolCatalogTables`
14
+ * is called only by a host that actually seeds and queries this table, mirroring
15
+ * `@jini-ai/registry`'s `ensureRegistryTables` precedent — the same discipline, applied this time
16
+ * without reviving the earlier mistake of a table nothing reads.
17
+ *
18
+ * Ranking is **FTS5 + `bm25()`**, not `LIKE` — verified against this repo's own `better-sqlite3`
19
+ * build (FTS5 is compiled in). `PROP` §5.3 sequences `LIKE` first and treats FTS5 as a later
20
+ * swap once row counts justify it; at v0's actual row count (tens of tools) that swap costs
21
+ * nothing extra to do now, so there is no hand-rolled scorer to throw away later. `tool_catalog`
22
+ * is FTS5's external-content table (`content='tool_catalog', content_rowid='rowid'`) — the
23
+ * canonical row lives once, in a plain table any other query/dump tool can read; the FTS index is
24
+ * rebuilt wholesale on every reseed rather than kept in sync via triggers, since `reseedToolCatalog`
25
+ * already replaces the entire table in one transaction. Column weights (id 6x description, matching
26
+ * the asymmetry `examples/nlweb-demo`'s keyword-scoring spike measured) are passed to `bm25()` at
27
+ * query time, not baked into the index.
28
+ */
29
+ import type { SqliteDb } from '@jini-ai/db/sqlite';
30
+ import type { ToolCatalogEntry, ToolCatalogSearchHit } from './index.js';
31
+ export type { ToolCatalogEntry, ToolCatalogSearchHit } from './index.js';
32
+ /** Idempotent. Safe to call repeatedly (`IF NOT EXISTS`), matching `migrate()`'s own convention. */
33
+ export declare function ensureToolCatalogTables({ db }: {
34
+ db: SqliteDb;
35
+ }): void;
36
+ /**
37
+ * Replaces the entire catalog with `entries` in one transaction — this table is a *snapshot* of
38
+ * whatever `ToolRegistry` a host assembled at boot, not an independently-edited store (§7.2's
39
+ * "the agent may never write the catalog" holds trivially at v0: nothing here accepts writes
40
+ * from a run at all). A tool no longer registered — the id simply is not in `entries` — is gone
41
+ * from the snapshot on the next reseed, which is the correct behavior for an append-only
42
+ * `ToolRegistry`: this table can only ever lag it, never diverge from it.
43
+ *
44
+ * Rebuilds the FTS5 index wholesale afterward (`INSERT INTO tool_catalog_fts(tool_catalog_fts)
45
+ * VALUES('rebuild')`) rather than via triggers — correct and sufficient because every reseed
46
+ * already replaces 100% of the rows in the same transaction.
47
+ */
48
+ export declare function reseedToolCatalog({ db, entries }: {
49
+ db: SqliteDb;
50
+ entries: readonly ToolCatalogEntry[];
51
+ }, { now }?: {
52
+ now?: number;
53
+ }): void;
54
+ export declare function getToolCatalogEntry({ db, id }: {
55
+ db: SqliteDb;
56
+ id: string;
57
+ }): ToolCatalogEntry | null;
58
+ /**
59
+ * `PROP` §6.1's `search_tools`: candidates only, no schemas — loading schemas at search time is
60
+ * what blows the context budget. Never returns an empty-query "everything" page (§6.1's staged
61
+ * discovery loses its point if the first call already dumps the whole catalog).
62
+ *
63
+ * Terms are OR'd (`term1 OR term2 OR ...`), not FTS5's implicit AND, so a multi-word query still
64
+ * surfaces a tool matching only one significant word — the same behavior a hand-rolled
65
+ * any-term-scores scorer would give, but ranked by real BM25 instead of a hand-tuned weight sum.
66
+ */
67
+ export declare function searchToolCatalog({ db, query }: {
68
+ db: SqliteDb;
69
+ query: string;
70
+ }, { limit }?: {
71
+ limit?: number;
72
+ }): readonly ToolCatalogSearchHit[];
73
+ //# sourceMappingURL=sqlite.d.ts.map