@opennodes/registry 0.1.50 → 0.1.52
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.
- package/README.md +18 -2
- package/bin.js +6 -2
- package/package.json +2 -2
- package/src/counts.js +135 -0
- package/src/data/locations-ua.json +93 -0
- package/src/export.js +6 -1
- package/src/locations.js +7 -5
- package/src/mcp.js +25 -8
- package/src/probes.js +24 -2
- package/src/search.js +43 -6
- package/src/server.js +67 -9
- package/src/stageb.js +18 -6
- package/src/stagec.js +25 -6
- package/src/store-pg.js +24 -1
- package/src/store.js +31 -1
- package/src/web/index.html +62 -11
package/src/server.js
CHANGED
|
@@ -3,19 +3,19 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import {
|
|
4
4
|
createApp, listen, closeApp, sendJson, problem, readJson,
|
|
5
5
|
validateCard, verifyCardSignature, keyFromJwk, estimateBounds,
|
|
6
|
-
extractFeatures, recommend,
|
|
6
|
+
extractFeatures, recommend, trustedView, DEFAULT_TRUSTED_JURISDICTIONS,
|
|
7
7
|
} from '@opennodes/core';
|
|
8
8
|
import { resolveTxt } from 'node:dns/promises';
|
|
9
9
|
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
11
|
import { generateKeypair, keypairFromPem } from '@opennodes/core';
|
|
12
12
|
import { createStore } from './store.js';
|
|
13
|
-
import { runStageA } from './probes.js';
|
|
13
|
+
import { runStageA, verificationOf } from './probes.js';
|
|
14
14
|
import { runStageB, captureFingerprints } from './stageb.js';
|
|
15
15
|
import { startStageC } from './stagec.js';
|
|
16
16
|
import { startReimport } from './reimport.js';
|
|
17
17
|
import { makeSafeFetch } from './safefetch.js';
|
|
18
|
-
import { searchOfferings, searchOfferingsPaged, collectOfferings, watchStoreWrites, setSeedPlacements, RANK_COMPONENTS, pricePublished } from './search.js';
|
|
18
|
+
import { searchOfferings, searchOfferingsPaged, collectOfferings, watchStoreWrites, setSeedPlacements, setTrustedView, RANK_COMPONENTS, pricePublished } from './search.js';
|
|
19
19
|
import { mcpRoutes } from './mcp.js';
|
|
20
20
|
import { hostControlsNamespace, isPrivateHost, makeRateLimiter } from './namespace.js';
|
|
21
21
|
import { exportRoutes } from './export.js';
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
HF_ROUTER_URL, HF_HUB_URL, OPENROUTER_URL, OPENROUTER_PROVIDERS_URL, OLLAMA_LIBRARY_URL,
|
|
29
29
|
} from './importers.js';
|
|
30
30
|
import { locationRoutes, loadLocationSeeds, seedPlacements, seedNodeSites, nodeServes } from './locations.js';
|
|
31
|
+
import { makeRequestCounter, nodeIdsIn } from './counts.js';
|
|
31
32
|
|
|
32
33
|
/** Default basemap. OSM's tile policy asks for attribution and light use; busy registries set their own. */
|
|
33
34
|
export const OSM_TILES = {
|
|
@@ -52,8 +53,11 @@ export async function startRegistry({
|
|
|
52
53
|
location = null, // { selfSite, agents, intervalMs, fetchImpl, resolve, rtt } to check server locations
|
|
53
54
|
locationSeeds = false, // import the bundled curated location seeds (src/data/locations-*.json) at start
|
|
54
55
|
mapTiles = OSM_TILES, // basemap for the "Where models run" map: { tiles, attribution, max_zoom }, or null for no map
|
|
56
|
+
requestCountFlushMs = 60_000, // how often request counts move from memory to the store (reads flush first)
|
|
57
|
+
trustedJurisdictions = DEFAULT_TRUSTED_JURISDICTIONS, // the trusted pool's operator jurisdictions (ONP_TRUSTED_JURISDICTIONS)
|
|
55
58
|
} = {}) {
|
|
56
59
|
const store = watchStoreWrites(await createStore(dbPath)); // sqlite path/:memory: or postgres:// URL; writes refresh the cached catalog
|
|
60
|
+
const requests = makeRequestCounter(store, { flushMs: requestCountFlushMs }); // node ids + counts only
|
|
57
61
|
const safeFetch = makeSafeFetch({ allowPrivate: allowPrivateTargets });
|
|
58
62
|
const seeds = locationSeeds ? loadLocationSeeds() : [];
|
|
59
63
|
for (const seed of seeds) {
|
|
@@ -61,6 +65,9 @@ export async function startRegistry({
|
|
|
61
65
|
if (result.skipped.length) console.warn(`location seed ${seed.seed}: skipped ${result.skipped.join('; ')}`);
|
|
62
66
|
}
|
|
63
67
|
setSeedPlacements(store, seedPlacements(seeds));
|
|
68
|
+
const trusted = trustedView(trustedJurisdictions); // pool labels, trust=trusted, sensitive recommend
|
|
69
|
+
if (!trusted.countries.length) console.warn(`trusted jurisdictions "${trustedJurisdictions}" name no country: no hosted offering is trusted`);
|
|
70
|
+
setTrustedView(store, trusted);
|
|
64
71
|
const webApp = readFileSync(fileURLToPath(new URL('./web/index.html', import.meta.url)), 'utf8');
|
|
65
72
|
let registryKeys;
|
|
66
73
|
if (keyPath && existsSync(keyPath)) {
|
|
@@ -328,6 +335,7 @@ export async function startRegistry({
|
|
|
328
335
|
tier: node.state === 'indexed' ? 'unverified' : node.state,
|
|
329
336
|
source: node.source ?? 'registration',
|
|
330
337
|
institutional: Boolean(node.institutional),
|
|
338
|
+
founding: Boolean(node.founding),
|
|
331
339
|
updated_at: node.updated_at,
|
|
332
340
|
name: card?.node?.name ?? node.id,
|
|
333
341
|
operator: card?.node?.operator?.name ?? null,
|
|
@@ -360,17 +368,40 @@ export async function startRegistry({
|
|
|
360
368
|
['GET', '/v0/nodes/:id', async (req, res, { params }) => {
|
|
361
369
|
const node = await store.getNode(params.id);
|
|
362
370
|
if (!node) return problem(res, 404, 'unknown-node', params.id);
|
|
371
|
+
const card = await store.latestCard(params.id);
|
|
372
|
+
const nodeObs = await store.getObservations(params.id, '_node');
|
|
363
373
|
sendJson(res, 200, {
|
|
364
374
|
...node,
|
|
365
|
-
|
|
375
|
+
institutional: Boolean(node.institutional),
|
|
376
|
+
founding: Boolean(node.founding),
|
|
377
|
+
card,
|
|
366
378
|
probes: (await store.probesFor(params.id)).slice(0, 20),
|
|
367
379
|
history: await store.transitionsFor(params.id),
|
|
368
|
-
location:
|
|
380
|
+
location: nodeObs.location ?? null,
|
|
381
|
+
// What the tier covers (ONP-3 §4a): the offerings the tests could not call, and whether
|
|
382
|
+
// Stage C has had to skip blind probes because none could be called.
|
|
383
|
+
verification: verificationOf(card, nodeObs),
|
|
384
|
+
// How often search, recommend and MCP returned this node, last 12 ISO weeks, newest first.
|
|
385
|
+
request_counts: await requests.forNode(params.id),
|
|
386
|
+
});
|
|
387
|
+
}],
|
|
388
|
+
|
|
389
|
+
// Request counts (ONP-3 §6.6): per ISO week, the responses on each surface and the nodes they
|
|
390
|
+
// returned. ?weeks=1..52 (default 4), ?node_id= one node, ?limit= nodes per week (default 50).
|
|
391
|
+
['GET', '/v0/stats/requests', async (req, res, { query }) => {
|
|
392
|
+
const int = (k, dflt, max) => Math.min(max, Math.max(1, Math.floor(Number(query.get(k) ?? dflt)) || dflt));
|
|
393
|
+
sendJson(res, 200, {
|
|
394
|
+
counted: 'responses that returned the node, per ISO week (Monday 00:00 UTC): search = GET /v0/offerings, recommend = POST /v0/recommend, mcp = tools/call on /mcp; each response counts a node once. Only node ids and counts are stored, never the query, task or client.',
|
|
395
|
+
weeks: await requests.stats({ weeks: int('weeks', 4, 52), nodeId: query.get('node_id') || null, limit: int('limit', 50, 500) }),
|
|
369
396
|
});
|
|
370
397
|
}],
|
|
371
398
|
|
|
372
399
|
['GET', '/v0/offerings', async (req, res, { query }) => {
|
|
373
|
-
|
|
400
|
+
let page;
|
|
401
|
+
try { page = await searchOfferingsPaged(store, query); }
|
|
402
|
+
catch (err) { if (err.status === 400) return problem(res, 400, 'bad-query', err.message); throw err; }
|
|
403
|
+
const { offerings, total, offset, counts } = page;
|
|
404
|
+
requests.count('search', offerings.map((o) => o.node_id));
|
|
374
405
|
// total = matches before `offset`/`limit`; counts = hosted/local matches before the `local` filter
|
|
375
406
|
sendJson(res, 200, { offerings, total, offset, counts });
|
|
376
407
|
}],
|
|
@@ -397,7 +428,9 @@ export async function startRegistry({
|
|
|
397
428
|
if (!offering) return problem(res, 404, 'unknown-offering', step.offering);
|
|
398
429
|
} else if (step.select) {
|
|
399
430
|
const query = new URLSearchParams(step.select);
|
|
400
|
-
|
|
431
|
+
let results;
|
|
432
|
+
try { results = await searchOfferings(store, query); }
|
|
433
|
+
catch (err) { if (err.status === 400) return problem(res, 400, 'bad-query', err.message); throw err; }
|
|
401
434
|
if (!results.length) return problem(res, 404, 'no-offering-matches', JSON.stringify(step.select));
|
|
402
435
|
offering = results[0];
|
|
403
436
|
} else {
|
|
@@ -429,7 +462,12 @@ export async function startRegistry({
|
|
|
429
462
|
if (!features) return problem(res, 400, 'missing-task', 'body must carry "task" (text) or "features" (from extractFeatures)');
|
|
430
463
|
// only what a client could actually call: listing-only imports are never recommended
|
|
431
464
|
const all = (await collectOfferings(store)).filter((o) => o.invocable);
|
|
432
|
-
|
|
465
|
+
// policy.sensitive / policy.trust apply this registry's trusted view; a client cannot replace it
|
|
466
|
+
let advice;
|
|
467
|
+
try { advice = recommend(all, features, { ...(body.policy ?? {}), trusted }); }
|
|
468
|
+
catch (err) { if (err.status === 400) return problem(res, 400, 'bad-policy', err.message); throw err; }
|
|
469
|
+
requests.count('recommend', nodeIdsIn(advice)); // recommendations, scenario roles, embedders
|
|
470
|
+
sendJson(res, 200, advice);
|
|
433
471
|
}],
|
|
434
472
|
|
|
435
473
|
// Delist (admin): operator opt-out of an imported listing, or retiring a node. Search,
|
|
@@ -461,6 +499,23 @@ export async function startRegistry({
|
|
|
461
499
|
sendJson(res, 200, { id: node.id, state: 'indexed' });
|
|
462
500
|
}],
|
|
463
501
|
|
|
502
|
+
// Operator marks (admin, ONP-3 §4b): body {"institutional": true|false} or {"founding": true|false}.
|
|
503
|
+
// Labels shown with the listing, never rank inputs. Setting one needs a registered node (an
|
|
504
|
+
// unclaimed import has no proven operator); clearing always works.
|
|
505
|
+
...['institutional', 'founding'].map((flag) => ['POST', `/v0/admin/nodes/:id/${flag}`, async (req, res, { params }) => {
|
|
506
|
+
if (!adminOk(req, res)) return;
|
|
507
|
+
const node = await store.getNode(params.id);
|
|
508
|
+
if (!node) return problem(res, 404, 'unknown-node', params.id);
|
|
509
|
+
const body = await readJson(req);
|
|
510
|
+
if (typeof body[flag] !== 'boolean') return problem(res, 400, 'bad-flag', `body must be {"${flag}": true} or {"${flag}": false}`);
|
|
511
|
+
if (body[flag] && node.source === 'import') {
|
|
512
|
+
return problem(res, 409, 'imported-listing', `${node.id} is an unclaimed catalog import; the ${flag} mark needs a registered node`);
|
|
513
|
+
}
|
|
514
|
+
await store.setNodeFlag(node.id, flag, body[flag]);
|
|
515
|
+
const updated = await store.getNode(node.id);
|
|
516
|
+
sendJson(res, 200, { id: node.id, institutional: Boolean(updated.institutional), founding: Boolean(updated.founding) });
|
|
517
|
+
}]),
|
|
518
|
+
|
|
464
519
|
// Seed importer (admin): body {catalog} in models.dev shape, or {url} to fetch it.
|
|
465
520
|
['POST', '/v0/import/models-dev', async (req, res) => {
|
|
466
521
|
if (!adminOk(req, res)) return;
|
|
@@ -548,6 +603,8 @@ export async function startRegistry({
|
|
|
548
603
|
map: mapTiles,
|
|
549
604
|
signing_key: { ...registryKeys.publicJwk, kid: 'registry-1' },
|
|
550
605
|
stage_c: Boolean(stageC),
|
|
606
|
+
// What trust=trusted, policy.sensitive and each result's `pool` mean here (ONP-3 §5e).
|
|
607
|
+
trust: { pools: ['trusted', 'open'], trusted },
|
|
551
608
|
});
|
|
552
609
|
}],
|
|
553
610
|
|
|
@@ -557,7 +614,7 @@ export async function startRegistry({
|
|
|
557
614
|
res.end(webApp);
|
|
558
615
|
}],
|
|
559
616
|
|
|
560
|
-
...mcpRoutes(store, seeds),
|
|
617
|
+
...mcpRoutes(store, seeds, { onResult: (ids) => requests.count('mcp', ids), trusted }),
|
|
561
618
|
...exportRoutes(store, registryKeys),
|
|
562
619
|
...locationRoutes(store, seeds),
|
|
563
620
|
], { cors: true }); // public read API: third-party web clients may call it directly
|
|
@@ -604,6 +661,7 @@ export async function startRegistry({
|
|
|
604
661
|
reimportHandle?.stop();
|
|
605
662
|
locationHandle?.stop();
|
|
606
663
|
await closeApp(app);
|
|
664
|
+
await requests.stop(); // writes the counts still in memory
|
|
607
665
|
await store.close();
|
|
608
666
|
},
|
|
609
667
|
};
|
package/src/stageb.js
CHANGED
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
// verification with capping, capacity ramp with measured-over-claimed metrics.
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { fetchJsonCapped } from './safefetch.js';
|
|
5
|
+
import { testable, untestedOfferings, NO_TESTED_OFFERINGS } from './probes.js';
|
|
5
6
|
|
|
6
7
|
const sha256 = (s) => createHash('sha256').update(s).digest('hex');
|
|
7
8
|
|
|
9
|
+
/** Context probe sizes, as fractions of the claimed window (DS-ADM-03). */
|
|
10
|
+
export const CONTEXT_FRACTIONS = [0.25, 0.5, 0.9];
|
|
11
|
+
/** Capacity ramp (DS-ADM-04): parallel requests per step; one batch per step, all within one time budget. */
|
|
12
|
+
export const CAPACITY_RAMP = { steps: [1, 4, 8], durationMs: 3000 };
|
|
13
|
+
|
|
8
14
|
/** The fixed identity battery: deterministic prompts, temperature 0. */
|
|
9
15
|
export const FINGERPRINT_PROMPTS = [
|
|
10
16
|
'ONP identity probe 1: repeat exactly: correlation-4417',
|
|
@@ -97,7 +103,7 @@ async function probeContext(safeFetch, card, offering) {
|
|
|
97
103
|
const { charsPerToken, measured } = await calibrate(safeFetch, card, offering);
|
|
98
104
|
const results = [];
|
|
99
105
|
let cap = 0, unbroken = true;
|
|
100
|
-
for (const fraction of
|
|
106
|
+
for (const fraction of CONTEXT_FRACTIONS) {
|
|
101
107
|
const tokens = Math.floor(claimed * fraction);
|
|
102
108
|
const digits = String(Math.floor(tokens * 7919)); // deterministic per size
|
|
103
109
|
const fact = ` The magic number is ${digits}. `;
|
|
@@ -122,7 +128,7 @@ async function probeContext(safeFetch, card, offering) {
|
|
|
122
128
|
}
|
|
123
129
|
|
|
124
130
|
/** DS-ADM-04: stepped-concurrency ramp; measures TTFT p50/p95 and rough TPS. */
|
|
125
|
-
async function probeCapacity(safeFetch, card, offering, { steps =
|
|
131
|
+
async function probeCapacity(safeFetch, card, offering, { steps = CAPACITY_RAMP.steps, durationMs = CAPACITY_RAMP.durationMs } = {}) {
|
|
126
132
|
const latencies = [];
|
|
127
133
|
let completed = 0, failed = 0, outputTokens = 0;
|
|
128
134
|
const deadline = Date.now() + durationMs;
|
|
@@ -155,14 +161,20 @@ async function probeCapacity(safeFetch, card, offering, { steps = [1, 4, 8], dur
|
|
|
155
161
|
}
|
|
156
162
|
|
|
157
163
|
/**
|
|
158
|
-
* Run Stage B for every
|
|
164
|
+
* Run Stage B for every offering the tests can call (TESTED_PROFILES). Records probes + observations;
|
|
165
|
+
* returns per-offering verdicts, and in `untested` the offerings it could not call.
|
|
159
166
|
* Identity refs come from await store.getFingerprints(artifact); absence of refs is recorded, not failed
|
|
160
167
|
* (proprietary artifacts are guarded by the vendor-namespace rule instead).
|
|
168
|
+
* A card with no testable offering fails: nothing was measured, so nothing can be verified.
|
|
161
169
|
*/
|
|
162
170
|
export async function runStageB(store, nodeId, card, { safeFetch, capacity = {} } = {}) {
|
|
171
|
+
const untested = untestedOfferings(card);
|
|
172
|
+
if (!card.offerings.some(testable)) {
|
|
173
|
+
return { ok: false, identityFailed: false, reason: NO_TESTED_OFFERINGS, verdicts: [], untested };
|
|
174
|
+
}
|
|
163
175
|
const verdicts = [];
|
|
164
176
|
for (const offering of card.offerings) {
|
|
165
|
-
if (offering
|
|
177
|
+
if (!testable(offering)) continue;
|
|
166
178
|
const verdict = { offering_id: offering.offering_id, identity: null, context: null, capacity: null };
|
|
167
179
|
|
|
168
180
|
const refs = await store.getFingerprints(offering.model.artifact);
|
|
@@ -170,7 +182,7 @@ export async function runStageB(store, nodeId, card, { safeFetch, capacity = {}
|
|
|
170
182
|
verdict.identity = await probeIdentity(safeFetch, card, offering, refs);
|
|
171
183
|
if (verdict.identity.stale) {
|
|
172
184
|
// The node rejected our pinned revision (409). Abort without judging: the caller re-indexes and retries.
|
|
173
|
-
return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict] };
|
|
185
|
+
return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict], untested };
|
|
174
186
|
}
|
|
175
187
|
await store.recordProbe(nodeId, offering.offering_id, 'B', 'identity', verdict.identity.ok,
|
|
176
188
|
`${verdict.identity.matches}/${verdict.identity.total} reference matches`);
|
|
@@ -198,5 +210,5 @@ export async function runStageB(store, nodeId, card, { safeFetch, capacity = {}
|
|
|
198
210
|
|
|
199
211
|
const identityFailed = verdicts.some((v) => v.identity && !v.identity.ok);
|
|
200
212
|
const ok = !identityFailed && verdicts.every((v) => v.capacity?.ok);
|
|
201
|
-
return { ok, identityFailed, verdicts };
|
|
213
|
+
return { ok, identityFailed, verdicts, untested };
|
|
202
214
|
}
|
package/src/stagec.js
CHANGED
|
@@ -4,15 +4,22 @@
|
|
|
4
4
|
// - random blind invocations at unpredictable times (anti-"benchmark mode":
|
|
5
5
|
// a node cannot serve the real model only when it detects a test window)
|
|
6
6
|
import { fetchJsonCapped } from './safefetch.js';
|
|
7
|
+
import { testable, NO_TESTED_OFFERINGS } from './probes.js';
|
|
7
8
|
|
|
8
9
|
const OBSERVED_STATES = ['community', 'verified', 'attested'];
|
|
10
|
+
/** Mean gap between liveness sweeps (spec: <=5 min); each gap is drawn from 0.5x-1.5x (jitter). */
|
|
11
|
+
export const LIVENESS_INTERVAL_MS = 300_000;
|
|
12
|
+
/** Mean gap between blind-invocation sweeps: one chat call per node per sweep, same jitter. */
|
|
13
|
+
export const BLIND_INTERVAL_MS = 3_600_000;
|
|
14
|
+
/** Each gap is the mean times a uniform random factor in this range. */
|
|
15
|
+
export const JITTER = [0.5, 1.5];
|
|
9
16
|
|
|
10
17
|
export function startStageC(store, {
|
|
11
18
|
safeFetch,
|
|
12
19
|
fetchFor = null, // (nodeId, card) -> fetch that carries the node's probe key
|
|
13
20
|
refreshCard = null, // re-index a node's card when its revision moved (restart / reprice)
|
|
14
|
-
livenessIntervalMs =
|
|
15
|
-
blindIntervalMs =
|
|
21
|
+
livenessIntervalMs = LIVENESS_INTERVAL_MS, // tests shorten this
|
|
22
|
+
blindIntervalMs = BLIND_INTERVAL_MS,
|
|
16
23
|
failThreshold = 3,
|
|
17
24
|
recoverThreshold = 3, // consecutive liveness successes that lift a liveness suspension
|
|
18
25
|
} = {}) {
|
|
@@ -77,9 +84,21 @@ export function startStageC(store, {
|
|
|
77
84
|
await refreshCard?.(node.id);
|
|
78
85
|
const card = await store.latestCard(node.id);
|
|
79
86
|
if (!card) continue;
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
87
|
+
// Blind probes call only offerings the tests can call. A node with none is reported in the
|
|
88
|
+
// `blind_skipped` observation (node detail, export feed) instead of passing unobserved.
|
|
89
|
+
const callable = card.offerings.filter(testable);
|
|
90
|
+
const skipped = (await store.getObservations(node.id, '_node')).blind_skipped ?? null;
|
|
91
|
+
if (!callable.length) {
|
|
92
|
+
const profiles = [...new Set(card.offerings.map((o) => o.binding?.profile))];
|
|
93
|
+
if (skipped?.revision !== card.revision) {
|
|
94
|
+
await store.setObservation(node.id, '_node', 'blind_skipped', {
|
|
95
|
+
reason: NO_TESTED_OFFERINGS, profiles, revision: card.revision, since: new Date().toISOString(),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (skipped) await store.setObservation(node.id, '_node', 'blind_skipped', null);
|
|
101
|
+
const offering = callable[Math.floor(Math.random() * callable.length)];
|
|
83
102
|
try {
|
|
84
103
|
const f = fetchFor ? await fetchFor(node.id, card) : safeFetch;
|
|
85
104
|
const { status, body } = await fetchJsonCapped(f, `${card.endpoints.openai}/chat/completions`, {
|
|
@@ -106,7 +125,7 @@ export function startStageC(store, {
|
|
|
106
125
|
}
|
|
107
126
|
}
|
|
108
127
|
|
|
109
|
-
const jitter = (base) => base * (0
|
|
128
|
+
const jitter = (base) => base * (JITTER[0] + Math.random() * (JITTER[1] - JITTER[0]));
|
|
110
129
|
const loop = (fn, base) => {
|
|
111
130
|
const tick = async () => {
|
|
112
131
|
if (stopped) return;
|
package/src/store-pg.js
CHANGED
|
@@ -5,10 +5,11 @@ import pg from 'pg';
|
|
|
5
5
|
const SCHEMA = `
|
|
6
6
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
7
7
|
id TEXT PRIMARY KEY, origin TEXT NOT NULL, card_url TEXT NOT NULL,
|
|
8
|
-
state TEXT NOT NULL, institutional INTEGER DEFAULT 0,
|
|
8
|
+
state TEXT NOT NULL, institutional INTEGER DEFAULT 0, founding INTEGER DEFAULT 0,
|
|
9
9
|
source TEXT NOT NULL DEFAULT 'registration',
|
|
10
10
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
|
11
11
|
);
|
|
12
|
+
ALTER TABLE nodes ADD COLUMN IF NOT EXISTS founding INTEGER DEFAULT 0;
|
|
12
13
|
CREATE TABLE IF NOT EXISTS card_revisions (
|
|
13
14
|
node_id TEXT NOT NULL, revision TEXT NOT NULL, raw TEXT NOT NULL,
|
|
14
15
|
sig_ok INTEGER NOT NULL, fetched_at TEXT NOT NULL,
|
|
@@ -38,8 +39,14 @@ const SCHEMA = `
|
|
|
38
39
|
value TEXT NOT NULL, at TEXT NOT NULL,
|
|
39
40
|
PRIMARY KEY (node_id, offering_id, key)
|
|
40
41
|
);
|
|
42
|
+
CREATE TABLE IF NOT EXISTS request_counts (
|
|
43
|
+
node_id TEXT NOT NULL, week TEXT NOT NULL, surface TEXT NOT NULL, n INTEGER NOT NULL,
|
|
44
|
+
PRIMARY KEY (node_id, week, surface)
|
|
45
|
+
);
|
|
41
46
|
`;
|
|
42
47
|
|
|
48
|
+
const NODE_FLAGS = ['institutional', 'founding']; // same list as store.js
|
|
49
|
+
|
|
43
50
|
export async function createPgStore({ connectionString, pool } = {}) {
|
|
44
51
|
const p = pool ?? new pg.Pool({ connectionString, max: 10 });
|
|
45
52
|
for (const stmt of SCHEMA.split(';').map((s) => s.trim()).filter(Boolean)) {
|
|
@@ -60,6 +67,10 @@ export async function createPgStore({ connectionString, pool } = {}) {
|
|
|
60
67
|
async getNode(id) {
|
|
61
68
|
return (await q('SELECT * FROM nodes WHERE id = $1', [id]))[0];
|
|
62
69
|
},
|
|
70
|
+
async setNodeFlag(id, flag, value) {
|
|
71
|
+
if (!NODE_FLAGS.includes(flag)) throw new Error(`unknown node flag: ${flag}`);
|
|
72
|
+
await q(`UPDATE nodes SET ${flag} = $1 WHERE id = $2`, [value ? 1 : 0, id]);
|
|
73
|
+
},
|
|
63
74
|
async setState(id, toState, reason = null) {
|
|
64
75
|
const cur = await this.getNode(id);
|
|
65
76
|
await q('UPDATE nodes SET state = $1, updated_at = $2 WHERE id = $3', [toState, now(), id]);
|
|
@@ -135,6 +146,18 @@ export async function createPgStore({ connectionString, pool } = {}) {
|
|
|
135
146
|
const rows = await q('SELECT offering_id, key, value FROM observations WHERE node_id = $1', [nodeId]);
|
|
136
147
|
return rows.map((r) => ({ offering_id: r.offering_id, key: r.key, value: JSON.parse(r.value) }));
|
|
137
148
|
},
|
|
149
|
+
async addRequestCounts(rows) {
|
|
150
|
+
for (const r of rows) {
|
|
151
|
+
await q(`INSERT INTO request_counts (node_id, week, surface, n) VALUES ($1, $2, $3, $4)
|
|
152
|
+
ON CONFLICT (node_id, week, surface) DO UPDATE SET n = request_counts.n + excluded.n`,
|
|
153
|
+
[r.node_id, r.week, r.surface, r.n]);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
async requestCounts({ nodeId = null, sinceWeek = '0000-W00' } = {}) {
|
|
157
|
+
return nodeId
|
|
158
|
+
? q('SELECT * FROM request_counts WHERE node_id = $1 AND week >= $2 ORDER BY week DESC', [nodeId, sinceWeek])
|
|
159
|
+
: q('SELECT * FROM request_counts WHERE week >= $1 ORDER BY week DESC', [sinceWeek]);
|
|
160
|
+
},
|
|
138
161
|
async close() { await p.end(); },
|
|
139
162
|
};
|
|
140
163
|
}
|
package/src/store.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
// Every method is async so both drivers present the identical contract.
|
|
5
5
|
import { DatabaseSync } from 'node:sqlite';
|
|
6
6
|
|
|
7
|
+
/** Admin-set node labels: shown with a listing, never rank inputs (ONP-3 §4b). */
|
|
8
|
+
export const NODE_FLAGS = ['institutional', 'founding'];
|
|
9
|
+
|
|
7
10
|
/** config: ':memory:' | sqlite file path | postgres:// URL */
|
|
8
11
|
export async function createStore(config = ':memory:') {
|
|
9
12
|
if (typeof config === 'string' && /^postgres(ql)?:\/\//.test(config)) {
|
|
@@ -18,7 +21,7 @@ export async function createSqliteStore(path = ':memory:') {
|
|
|
18
21
|
db.exec(`
|
|
19
22
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
20
23
|
id TEXT PRIMARY KEY, origin TEXT NOT NULL, card_url TEXT NOT NULL,
|
|
21
|
-
state TEXT NOT NULL, institutional INTEGER DEFAULT 0,
|
|
24
|
+
state TEXT NOT NULL, institutional INTEGER DEFAULT 0, founding INTEGER DEFAULT 0,
|
|
22
25
|
source TEXT NOT NULL DEFAULT 'registration',
|
|
23
26
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
|
24
27
|
);
|
|
@@ -53,7 +56,17 @@ export async function createSqliteStore(path = ':memory:') {
|
|
|
53
56
|
value TEXT NOT NULL, at TEXT NOT NULL,
|
|
54
57
|
PRIMARY KEY (node_id, offering_id, key)
|
|
55
58
|
);
|
|
59
|
+
-- How often the registry returned each node to a client, per ISO week and surface
|
|
60
|
+
-- (search / recommend / mcp). Node ids and counts only: never the query, prompt or client.
|
|
61
|
+
CREATE TABLE IF NOT EXISTS request_counts (
|
|
62
|
+
node_id TEXT NOT NULL, week TEXT NOT NULL, surface TEXT NOT NULL, n INTEGER NOT NULL,
|
|
63
|
+
PRIMARY KEY (node_id, week, surface)
|
|
64
|
+
);
|
|
56
65
|
`);
|
|
66
|
+
// Databases created before the founding mark existed: add the column in place.
|
|
67
|
+
if (!db.prepare('PRAGMA table_info(nodes)').all().some((c) => c.name === 'founding')) {
|
|
68
|
+
db.exec('ALTER TABLE nodes ADD COLUMN founding INTEGER DEFAULT 0');
|
|
69
|
+
}
|
|
57
70
|
|
|
58
71
|
const now = () => new Date().toISOString();
|
|
59
72
|
|
|
@@ -67,6 +80,11 @@ export async function createSqliteStore(path = ':memory:') {
|
|
|
67
80
|
.run(id, origin, cardUrl, state, source, now(), now());
|
|
68
81
|
},
|
|
69
82
|
async getNode(id) { return db.prepare('SELECT * FROM nodes WHERE id = ?').get(id); },
|
|
83
|
+
/** Admin-set labels (`institutional`, `founding`). Not a state change: no transition, updated_at kept. */
|
|
84
|
+
async setNodeFlag(id, flag, value) {
|
|
85
|
+
if (!NODE_FLAGS.includes(flag)) throw new Error(`unknown node flag: ${flag}`);
|
|
86
|
+
db.prepare(`UPDATE nodes SET ${flag} = ? WHERE id = ?`).run(value ? 1 : 0, id);
|
|
87
|
+
},
|
|
70
88
|
async setState(id, toState, reason = null) {
|
|
71
89
|
const cur = await this.getNode(id);
|
|
72
90
|
db.prepare('UPDATE nodes SET state = ?, updated_at = ? WHERE id = ?').run(toState, now(), id);
|
|
@@ -136,6 +154,18 @@ export async function createSqliteStore(path = ':memory:') {
|
|
|
136
154
|
const rows = db.prepare('SELECT offering_id, key, value FROM observations WHERE node_id = ?').all(nodeId);
|
|
137
155
|
return rows.map((r) => ({ offering_id: r.offering_id, key: r.key, value: JSON.parse(r.value) }));
|
|
138
156
|
},
|
|
157
|
+
/** rows: [{node_id, week, surface, n}] — added to the stored counts. */
|
|
158
|
+
async addRequestCounts(rows) {
|
|
159
|
+
const add = db.prepare(`INSERT INTO request_counts (node_id, week, surface, n) VALUES (?, ?, ?, ?)
|
|
160
|
+
ON CONFLICT(node_id, week, surface) DO UPDATE SET n = request_counts.n + excluded.n`);
|
|
161
|
+
for (const r of rows) add.run(r.node_id, r.week, r.surface, r.n);
|
|
162
|
+
},
|
|
163
|
+
/** Counts from `sinceWeek` (ISO week, e.g. 2026-W46) on, newest week first; one node or all. */
|
|
164
|
+
async requestCounts({ nodeId = null, sinceWeek = '0000-W00' } = {}) {
|
|
165
|
+
return nodeId
|
|
166
|
+
? db.prepare('SELECT * FROM request_counts WHERE node_id = ? AND week >= ? ORDER BY week DESC').all(nodeId, sinceWeek)
|
|
167
|
+
: db.prepare('SELECT * FROM request_counts WHERE week >= ? ORDER BY week DESC').all(sinceWeek);
|
|
168
|
+
},
|
|
139
169
|
async close() { db.close(); },
|
|
140
170
|
};
|
|
141
171
|
}
|