@opennodes/registry 0.1.53 → 0.1.54

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/src/stageb.js CHANGED
@@ -1,24 +1,39 @@
1
1
  // Stage B admission probes (DS-ADM-02..04): identity fingerprinting, context
2
2
  // verification with capping, capacity ramp with measured-over-claimed metrics.
3
+ // Every prompt comes from the registry's probe corpus (corpus.js), never from text in this file.
3
4
  import { createHash } from 'node:crypto';
4
5
  import { fetchJsonCapped } from './safefetch.js';
5
6
  import { testable, untestedOfferings, NO_TESTED_OFFERINGS } from './probes.js';
7
+ import { loadCorpus, sample, IDENTITY_CAPTURE, IDENTITY_SAMPLE } from './corpus.js';
8
+ import { vendorClaim, vendorTable } from './vendors.js';
6
9
 
7
10
  const sha256 = (s) => createHash('sha256').update(s).digest('hex');
11
+ const DEV_CORPUS = loadCorpus(null);
8
12
 
9
13
  /** Context probe sizes, as fractions of the claimed window (DS-ADM-03). */
10
14
  export const CONTEXT_FRACTIONS = [0.25, 0.5, 0.9];
11
15
  /** Capacity ramp (DS-ADM-04): parallel requests per step; one batch per step, all within one time budget. */
12
16
  export const CAPACITY_RAMP = { steps: [1, 4, 8], durationMs: 3000 };
17
+ export { IDENTITY_CAPTURE, IDENTITY_SAMPLE };
13
18
 
14
- /** The fixed identity battery: deterministic prompts, temperature 0. */
15
- export const FINGERPRINT_PROMPTS = [
16
- 'ONP identity probe 1: repeat exactly: correlation-4417',
17
- 'ONP identity probe 2: repeat exactly: meridian-9022',
18
- 'ONP identity probe 3: repeat exactly: basalt-7301',
19
- ];
19
+ /** Why Stage B refuses `verified` without a signed card (ONP-2 §8). */
20
+ export const UNSIGNED_CARD = 'card signature not verified: a card must be signed for the verified tier (ONP-2 §8)';
21
+ /** Why an offering's identity could not be checked: nothing to compare against. */
22
+ export const NO_REFERENCE = 'no identity reference for this artefact';
23
+ /** Why a card-only listing that passes Stage B stays at community (ONP-3 §4, §4a). */
24
+ export const CUSTOMER_ACCESS_NEEDED = 'card-only listing: its probes carry the operator\'s own probe key, so verified needs probes sent with access the registry bought as a customer (ONP-3 §4)';
25
+ /**
26
+ * Output cap of an identity request: reference capture, Stage B and the blind identity check. Every
27
+ * Stage C blind invocation is sent with it too (and at temperature 0), so the ones carrying an
28
+ * identity prompt look like the rest.
29
+ */
30
+ export const IDENTITY_MAX_TOKENS = 64;
20
31
 
21
- async function chatOnce(safeFetch, card, offering, content, maxTokens = 64, timeoutMs = 60_000) {
32
+ /**
33
+ * One chat completion at temperature 0, the request every identity comparison is made with
34
+ * (Stage C blind invocations use it as well). Body keys in this order, every time.
35
+ */
36
+ export async function chatOnce(safeFetch, card, offering, content, maxTokens = IDENTITY_MAX_TOKENS, timeoutMs = 60_000) {
22
37
  const t0 = performance.now();
23
38
  const { status, body } = await fetchJsonCapped(safeFetch, `${card.endpoints.openai}/chat/completions`, {
24
39
  method: 'POST',
@@ -43,12 +58,12 @@ async function chatOnce(safeFetch, card, offering, content, maxTokens = 64, time
43
58
  }
44
59
 
45
60
  /**
46
- * Capture reference fingerprints for an artifact from a TRUSTED deployment
47
- * (run by the registry operator against a known-good serving of the weights).
61
+ * Capture reference fingerprints for an artifact from a TRUSTED deployment (run by the registry
62
+ * operator against a known-good serving of the weights). `prompts` come from the private corpus.
48
63
  */
49
- export async function captureFingerprints(safeFetch, card, offering) {
64
+ export async function captureFingerprints(safeFetch, card, offering, prompts = DEV_CORPUS.identityPrompts(IDENTITY_CAPTURE)) {
50
65
  const refs = [];
51
- for (const prompt of FINGERPRINT_PROMPTS) {
66
+ for (const prompt of prompts) {
52
67
  const { status, text } = await chatOnce(safeFetch, card, offering, prompt);
53
68
  if (status !== 200 || text === null) throw new Error(`reference capture failed: status ${status}`);
54
69
  refs.push({ prompt, expected_hash: sha256(text) });
@@ -56,16 +71,66 @@ export async function captureFingerprints(safeFetch, card, offering) {
56
71
  return refs;
57
72
  }
58
73
 
59
- /** DS-ADM-02: identity check against stored references. */
60
- async function probeIdentity(safeFetch, card, offering, refs) {
61
- let matches = 0, stale = false;
74
+ /** Whether a reply's text is the reference's: the exact-output comparison of ONP-3 §4a.4. */
75
+ export const matchesReference = (text, ref) => typeof text === 'string' && sha256(text) === ref.expected_hash;
76
+
77
+ /** 409s to identity prompts excused (the run stops unjudged and is retried) since the node's last judged Stage B. */
78
+ export const MAX_EXCUSED_409 = 3;
79
+ /** The probe record of an excused one. */
80
+ export const STAGE_B_409 = 'identity-409';
81
+
82
+ /**
83
+ * What a 409 to an identity prompt means (ONP-3 §4a.4), by Stage C's rule: the card is re-fetched,
84
+ * and only a really new revision excuses it. `revisionMoved()` re-fetches and returns the new
85
+ * revision, or null when the pinned one is still current.
86
+ * - `stale`: a new revision, within the bound: recorded, the run stops unjudged, the caller retries;
87
+ * - `refused`: the current revision was pinned: a reply that does not match;
88
+ * - `moved`: a new revision again, beyond the bound: the run ends as not passed, never as a dispute
89
+ * (the card the run holds is stale now, so even an honest node refuses what follows).
90
+ */
91
+ function makeOn409(store, nodeId, card, { revisionMoved, maxExcused409 }) {
92
+ return async (offering) => {
93
+ const fresh = revisionMoved ? await revisionMoved() : null;
94
+ if (!fresh) return { kind: 'refused' };
95
+ const since = (await store.getSchedule(nodeId, 'B'))?.last_at ?? '';
96
+ const excused = await store.countProbes(nodeId, STAGE_B_409, since);
97
+ if (excused >= maxExcused409) {
98
+ return { kind: 'moved', reason: `the card revision moved again during Stage B, after ${excused} such 409s since the last judged run (at most ${maxExcused409} are excused)` };
99
+ }
100
+ await store.recordProbe(nodeId, offering.offering_id, 'B', STAGE_B_409, false,
101
+ `409 with revision ${card.revision} pinned; card re-indexed at ${fresh}; Stage B runs again later`);
102
+ return { kind: 'stale' };
103
+ };
104
+ }
105
+
106
+ /**
107
+ * DS-ADM-02: identity check against stored references. A reply that does not match is asked once
108
+ * more before it counts (ONP-3 §6.3 disputes only a confirmed failure: batching on an engine with
109
+ * parallel slots can change a temperature-0 reply now and then). A 409 counts as a reply that does
110
+ * not match unless `on409` excuses it (makeOn409).
111
+ */
112
+ async function probeIdentity(safeFetch, card, offering, refs, on409) {
113
+ let matches = 0, retried = 0, refused = 0, stop = null;
114
+ const ask = async (prompt) => {
115
+ const { status, text } = await chatOnce(safeFetch, card, offering, prompt);
116
+ if (status === 409) {
117
+ const what = await on409(offering);
118
+ if (what.kind === 'refused') refused++; else stop = what;
119
+ return null;
120
+ }
121
+ return status === 200 && text !== null ? sha256(text) : null;
122
+ };
62
123
  for (const ref of refs) {
63
- const { status, text } = await chatOnce(safeFetch, card, offering, ref.prompt);
64
- if (status === 409) stale = true; // pinned revision is no longer current: not evidence about identity
65
- if (status === 200 && text !== null && sha256(text) === ref.expected_hash) matches++;
124
+ let hash = await ask(ref.prompt);
125
+ if (hash !== ref.expected_hash && !stop) { retried++; hash = await ask(ref.prompt); }
126
+ if (hash === ref.expected_hash) matches++;
127
+ if (stop) break;
66
128
  }
129
+ const extra = { ...(retried ? { retried } : {}), ...(refused ? { refused } : {}) };
130
+ if (stop?.kind === 'stale') return { ok: false, matches, total: refs.length, ...extra, stale: true };
131
+ if (stop?.kind === 'moved') return { ok: false, matches, total: refs.length, ...extra, moved: true, reason: stop.reason };
67
132
  // Deterministic battery: require all prompts to match the reference distribution.
68
- return { ok: matches === refs.length, matches, total: refs.length, ...(stale ? { stale: true } : {}) };
133
+ return { ok: matches === refs.length, matches, total: refs.length, ...extra };
69
134
  }
70
135
 
71
136
  /** The needle counts as retrieved if its number appears in the reply as a whole number. */
@@ -75,17 +140,14 @@ export function needleFound(text, digits) {
75
140
  return new RegExp(`(^|[^0-9])${number}([^0-9]|$)`).test(text);
76
141
  }
77
142
 
78
- const FILLER = 'lorem ipsum context filler segment. ';
79
- const fill = (chars) => FILLER.repeat(Math.ceil(Math.max(0, chars) / FILLER.length)).slice(0, Math.max(0, chars));
80
- const QUESTION = '\n\nWhat is the magic number mentioned in the text above? Reply with the number only.';
81
-
82
143
  /** Characters per token for this model's tokenizer, measured from a short prompt's reported usage. */
83
- async function calibrate(safeFetch, card, offering) {
84
- const chars = 4000;
144
+ async function calibrate(safeFetch, card, offering, corpus) {
145
+ const tail = `\n\n${corpus.chatPrompt()}`;
146
+ const prompt = corpus.haystack(4000 - tail.length) + tail;
85
147
  try {
86
- const { status, usage } = await chatOnce(safeFetch, card, offering, `${fill(chars)}\n\nReply with OK.`, 4);
148
+ const { status, usage } = await chatOnce(safeFetch, card, offering, prompt, 4);
87
149
  const reported = usage?.prompt_tokens;
88
- if (status === 200 && reported > 0) return { charsPerToken: chars / reported, measured: true };
150
+ if (status === 200 && reported > 0) return { charsPerToken: prompt.length / reported, measured: true };
89
151
  } catch { /* fall through to the default */ }
90
152
  return { charsPerToken: 4, measured: false };
91
153
  }
@@ -95,21 +157,23 @@ async function calibrate(safeFetch, card, offering) {
95
157
  * - Prompts are sized in the model's own tokens (calibrated from reported usage), not a chars/4 guess.
96
158
  * - The fact sits near the start: engines that silently drop the front of an over-long prompt lose it,
97
159
  * and a reported prompt_tokens well short of the target is failed as a cut prompt.
98
- * - The question is plain ("the magic number"): small models refuse or mangle odd tokens like NEEDLE.
160
+ * - The haystack, the fact and its question come from the corpus, and the number is random per probe.
99
161
  * - The cap is the largest size with every smaller size passing, so one lucky answer can't vouch for a window.
100
162
  */
101
- async function probeContext(safeFetch, card, offering) {
163
+ async function probeContext(safeFetch, card, offering, corpus) {
102
164
  const claimed = offering.serving?.context_window ?? 4096;
103
- const { charsPerToken, measured } = await calibrate(safeFetch, card, offering);
165
+ const { charsPerToken, measured } = await calibrate(safeFetch, card, offering, corpus);
104
166
  const results = [];
105
167
  let cap = 0, unbroken = true;
106
168
  for (const fraction of CONTEXT_FRACTIONS) {
107
169
  const tokens = Math.floor(claimed * fraction);
108
- const digits = String(Math.floor(tokens * 7919)); // deterministic per size
109
- const fact = ` The magic number is ${digits}. `;
110
- const body = Math.floor(tokens * charsPerToken) - fact.length - QUESTION.length - 40; // 40: chat template slack
170
+ const digits = String(10_000_000 + Math.floor(Math.random() * 89_999_999));
171
+ const needle = corpus.needle();
172
+ const fact = ` ${needle.fact.replace('{n}', digits)} `;
173
+ const question = `\n\n${needle.question}`;
174
+ const body = Math.floor(tokens * charsPerToken) - fact.length - question.length - 40; // 40: chat template slack
111
175
  const before = Math.floor(body * 0.1);
112
- const prompt = fill(before) + fact + fill(body - before) + QUESTION;
176
+ const prompt = corpus.haystack(before) + fact + corpus.haystack(body - before) + question;
113
177
  let found = false, why = null, promptTokens = null;
114
178
  try {
115
179
  // Prefill on modest hardware is slow: allow ~30 ms per claimed token on top of the base timeout.
@@ -128,7 +192,7 @@ async function probeContext(safeFetch, card, offering) {
128
192
  }
129
193
 
130
194
  /** DS-ADM-04: stepped-concurrency ramp; measures TTFT p50/p95 and rough TPS. */
131
- async function probeCapacity(safeFetch, card, offering, { steps = CAPACITY_RAMP.steps, durationMs = CAPACITY_RAMP.durationMs } = {}) {
195
+ async function probeCapacity(safeFetch, card, offering, corpus, { steps = CAPACITY_RAMP.steps, durationMs = CAPACITY_RAMP.durationMs } = {}) {
132
196
  const latencies = [];
133
197
  let completed = 0, failed = 0, outputTokens = 0;
134
198
  const deadline = Date.now() + durationMs;
@@ -136,7 +200,7 @@ async function probeCapacity(safeFetch, card, offering, { steps = CAPACITY_RAMP.
136
200
  while (Date.now() < deadline) {
137
201
  const batch = await Promise.all(Array.from({ length: concurrency }, async () => {
138
202
  try {
139
- const r = await chatOnce(safeFetch, card, offering, 'ONP capacity probe: reply with a short sentence.', 48);
203
+ const r = await chatOnce(safeFetch, card, offering, corpus.chatPrompt(), 48);
140
204
  return r.status === 200 ? r : null;
141
205
  } catch { return null; }
142
206
  }));
@@ -160,15 +224,43 @@ async function probeCapacity(safeFetch, card, offering, { steps = CAPACITY_RAMP.
160
224
  };
161
225
  }
162
226
 
227
+ /**
228
+ * The identity part of Stage B for one offering. Returns a verdict:
229
+ * - `{ok: true}` every sampled reference matched;
230
+ * - `{ok: false}` a reference did not match: evidence of a different model (the node is disputed);
231
+ * - `{ok: false, unverified: true, reason}` nothing could be compared, so identity is unknown and the
232
+ * offering cannot be verified: no usable reference for the artefact, or a proprietary artefact
233
+ * claimed outside the vendor's namespace.
234
+ */
235
+ async function identityOf(store, nodeId, safeFetch, card, offering, { corpus, vendors, identitySample, on409 }) {
236
+ const artifact = offering.model?.artifact;
237
+ const claim = vendorClaim(artifact, nodeId, vendors);
238
+ if (!claim.ok) return { ok: false, unverified: true, reason: `${artifact} is not this node's to claim (vendor namespace)` };
239
+ // References captured with public prompts prove nothing: a node could have recognised them.
240
+ const refs = (await store.getFingerprints(artifact)).filter((r) => corpus.usableReference(r.prompt));
241
+ if (!refs.length) return { ok: false, unverified: true, reason: NO_REFERENCE };
242
+ return probeIdentity(safeFetch, card, offering, sample(refs, identitySample), on409);
243
+ }
244
+
163
245
  /**
164
246
  * Run Stage B for every offering the tests can call (TESTED_PROFILES). Records probes + observations;
165
247
  * returns per-offering verdicts, and in `untested` the offerings it could not call.
166
- * Identity refs come from await store.getFingerprints(artifact); absence of refs is recorded, not failed
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.
248
+ * Not ok, with `reason`, when the card is unsigned (`signed: false`), when no offering can be
249
+ * tested, when any tested offering's identity could not be checked (no reference: unverified, not a
250
+ * dispute), or when the capacity ramp fails. `identityFailed` (a reference mismatch) means disputed.
251
+ * `stale`: an excused 409 stopped the run unjudged. `revisionMoved` (see makeOn409): without it,
252
+ * every 409 to an identity prompt counts as a reply that does not match.
169
253
  */
170
- export async function runStageB(store, nodeId, card, { safeFetch, capacity = {} } = {}) {
254
+ export async function runStageB(store, nodeId, card, {
255
+ safeFetch, capacity = {}, corpus = DEV_CORPUS, vendors = vendorTable(), signed = true, identitySample = IDENTITY_SAMPLE,
256
+ revisionMoved = null, maxExcused409 = MAX_EXCUSED_409,
257
+ } = {}) {
258
+ const on409 = makeOn409(store, nodeId, card, { revisionMoved, maxExcused409 });
171
259
  const untested = untestedOfferings(card);
260
+ if (!signed) {
261
+ await store.recordProbe(nodeId, null, 'B', 'signature', false, UNSIGNED_CARD);
262
+ return { ok: false, identityFailed: false, reason: UNSIGNED_CARD, verdicts: [], untested };
263
+ }
172
264
  if (!card.offerings.some(testable)) {
173
265
  return { ok: false, identityFailed: false, reason: NO_TESTED_OFFERINGS, verdicts: [], untested };
174
266
  }
@@ -177,20 +269,22 @@ export async function runStageB(store, nodeId, card, { safeFetch, capacity = {}
177
269
  if (!testable(offering)) continue;
178
270
  const verdict = { offering_id: offering.offering_id, identity: null, context: null, capacity: null };
179
271
 
180
- const refs = await store.getFingerprints(offering.model.artifact);
181
- if (refs.length) {
182
- verdict.identity = await probeIdentity(safeFetch, card, offering, refs);
183
- if (verdict.identity.stale) {
184
- // The node rejected our pinned revision (409). Abort without judging: the caller re-indexes and retries.
185
- return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict], untested };
186
- }
187
- await store.recordProbe(nodeId, offering.offering_id, 'B', 'identity', verdict.identity.ok,
188
- `${verdict.identity.matches}/${verdict.identity.total} reference matches`);
189
- } else {
190
- await store.recordProbe(nodeId, offering.offering_id, 'B', 'identity', true, 'no reference fingerprints for artifact; skipped');
272
+ verdict.identity = await identityOf(store, nodeId, safeFetch, card, offering, { corpus, vendors, identitySample, on409 });
273
+ if (verdict.identity.stale) {
274
+ // The card's revision really moved (an excused 409, recorded). Abort without judging: the caller retries.
275
+ return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict], untested };
276
+ }
277
+ const { matches, total, refused } = verdict.identity;
278
+ await store.recordProbe(nodeId, offering.offering_id, 'B', 'identity', verdict.identity.ok,
279
+ verdict.identity.unverified ? `identity unverified: ${verdict.identity.reason}`
280
+ : verdict.identity.moved ? `not judged: ${verdict.identity.reason}`
281
+ : `${matches}/${total} reference matches${refused ? `; ${refused} replies refused with 409, the current card revision pinned` : ''}`);
282
+ if (verdict.identity.moved) {
283
+ // Beyond the bound: not passed, and nothing more is sent on a card that is no longer current.
284
+ return { ok: false, identityFailed: false, reason: `${offering.offering_id}: ${verdict.identity.reason}`, verdicts: [...verdicts, verdict], untested };
191
285
  }
192
286
 
193
- verdict.context = await probeContext(safeFetch, card, offering);
287
+ verdict.context = await probeContext(safeFetch, card, offering, corpus);
194
288
  await store.recordProbe(nodeId, offering.offering_id, 'B', 'context', verdict.context.ok,
195
289
  `claimed ${verdict.context.claimed}, verified ${verdict.context.verified_cap}`,
196
290
  verdict.context);
@@ -198,7 +292,7 @@ export async function runStageB(store, nodeId, card, { safeFetch, capacity = {}
198
292
  // earlier cap; 0 = nothing verified, shown as unverified rather than trusting the claim.
199
293
  await store.setObservation(nodeId, offering.offering_id, 'context_cap', verdict.context.verified_cap);
200
294
 
201
- verdict.capacity = await probeCapacity(safeFetch, card, offering, capacity);
295
+ verdict.capacity = await probeCapacity(safeFetch, card, offering, corpus, capacity);
202
296
  await store.recordProbe(nodeId, offering.offering_id, 'B', 'capacity', verdict.capacity.ok, null, verdict.capacity);
203
297
  if (verdict.capacity.ttft_ms.p50 != null) {
204
298
  await store.setObservation(nodeId, offering.offering_id, 'ttft_ms', verdict.capacity.ttft_ms);
@@ -208,7 +302,13 @@ export async function runStageB(store, nodeId, card, { safeFetch, capacity = {}
208
302
  verdicts.push(verdict);
209
303
  }
210
304
 
211
- const identityFailed = verdicts.some((v) => v.identity && !v.identity.ok);
212
- const ok = !identityFailed && verdicts.every((v) => v.capacity?.ok);
213
- return { ok, identityFailed, verdicts, untested };
305
+ const identityFailed = verdicts.some((v) => !v.identity.ok && !v.identity.unverified);
306
+ const unverified = verdicts.filter((v) => v.identity.unverified);
307
+ const capacityFailed = verdicts.filter((v) => !v.capacity?.ok);
308
+ const reasons = [
309
+ ...unverified.map((v) => `${v.offering_id}: identity unverified (${v.identity.reason})`),
310
+ ...capacityFailed.map((v) => `${v.offering_id}: capacity ramp failed`),
311
+ ];
312
+ const ok = !identityFailed && reasons.length === 0;
313
+ return { ok, identityFailed, ...(ok || identityFailed ? {} : { reason: reasons.join('; ') }), verdicts, untested };
214
314
  }
package/src/stagec.js CHANGED
@@ -1,27 +1,84 @@
1
1
  // Stage C (DS-ADM-06): continuous observation of community+ nodes.
2
2
  // - liveness sweep on a fixed cadence -> rolling availability observation,
3
3
  // auto-suspension after consecutive failures
4
- // - random blind invocations at unpredictable times (anti-"benchmark mode":
5
- // a node cannot serve the real model only when it detects a test window)
4
+ // - random blind invocations at unpredictable times (anti-"benchmark mode": a node cannot serve the
5
+ // real model only when it detects a test window), worded from the registry's probe corpus like
6
+ // any customer request; repeated failures cost the node its tier
7
+ // - an excused 409 is followed by a fresh blind invocation within the hour (ONP-3 §4a.9), so
8
+ // publishing a new card revision to refuse a probe does not buy a quiet stretch
9
+ // - on verified and attested nodes some blind invocations ask an identity prompt instead: a light
10
+ // identity check between Stage B runs. A confirmed mismatch makes Stage B due within the hour;
11
+ // only Stage B can dispute.
12
+ // What the registry owes a node lives in the private `schedule` table (rows FOLLOW_UP, LIGHT_CHECK),
13
+ // never in a probe record: no API says when the next probe comes or which probes carried what.
6
14
  import { fetchJsonCapped } from './safefetch.js';
7
15
  import { testable, NO_TESTED_OFFERINGS } from './probes.js';
16
+ import { loadCorpus } from './corpus.js';
17
+ import { chatOnce, matchesReference, IDENTITY_MAX_TOKENS } from './stageb.js';
18
+ import { between } from './schedule.js';
8
19
 
9
20
  const OBSERVED_STATES = ['community', 'verified', 'attested'];
21
+ /** Tiers a Stage B pass gave: their blind invocations may carry the light identity check. */
22
+ const IDENTITY_STATES = ['verified', 'attested'];
23
+ const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR;
10
24
  /** Mean gap between liveness sweeps (spec: <=5 min); each gap is drawn from 0.5x-1.5x (jitter). */
11
25
  export const LIVENESS_INTERVAL_MS = 300_000;
12
26
  /** Mean gap between blind-invocation sweeps: one chat call per node per sweep, same jitter. */
13
27
  export const BLIND_INTERVAL_MS = 3_600_000;
14
28
  /** Each gap is the mean times a uniform random factor in this range. */
15
29
  export const JITTER = [0.5, 1.5];
30
+ /** Consecutive failed blind invocations (since the node's last state change) that demote it one tier. */
31
+ export const BLIND_FAIL_THRESHOLD = 3;
32
+ /**
33
+ * 409 answers to blind probes excused per node per 24 h. A 409 is excused only when the card's
34
+ * revision really moved (the registry re-fetches the card and retries once with the new pin, as
35
+ * since 4 Oct 2026); beyond this many, or with the current revision pinned, it counts as a failure.
36
+ */
37
+ export const MAX_EXCUSED_409_PER_DAY = 3;
38
+ /**
39
+ * Every excused 409 is followed by a fresh blind invocation at a random time in this window, pinned
40
+ * to the revision the node moved to. Its upper end leaves room for the follow-up tick (at most
41
+ * 1.5 x FOLLOW_UP_TICK_MS late), so it arrives within the hour.
42
+ */
43
+ export const FOLLOW_UP_MS = [0, 55 * MINUTE];
44
+ /** Mean gap between looks for follow-ups that are due (same jitter as the sweeps). */
45
+ export const FOLLOW_UP_TICK_MS = MINUTE;
46
+ /**
47
+ * Share of blind invocations on verified and attested nodes that ask one of the offering's identity
48
+ * references instead of an ordinary prompt (none when the artefact has no usable reference).
49
+ */
50
+ export const IDENTITY_SHARE = 0.25;
51
+ /** At most one Stage B per node in this long is made due by blind identity checks. */
52
+ export const IDENTITY_STAGE_B_GAP_MS = DAY;
53
+ /** Every blind invocation's output cap: the identity requests' (stageb.js), so all look alike. */
54
+ export const BLIND_MAX_TOKENS = IDENTITY_MAX_TOKENS;
55
+ /** Private schedule rows (store.setSchedule): the follow-up a node is owed, and its last light identity check. */
56
+ export const FOLLOW_UP = 'C:follow-up';
57
+ export const LIGHT_CHECK = 'C:identity';
58
+ /** Where tiers go when blind probes keep failing: one step down. */
59
+ const DEMOTE = { attested: 'verified', verified: 'community', community: 'indexed' };
60
+
61
+ const iso = (ms) => new Date(ms).toISOString();
16
62
 
17
63
  export function startStageC(store, {
18
64
  safeFetch,
19
65
  fetchFor = null, // (nodeId, card) -> fetch that carries the node's probe key
20
66
  refreshCard = null, // re-index a node's card when its revision moved (restart / reprice)
67
+ // (nodeId, card) -> make Stage B due within the hour, returns when (schedule.js stageBSoon); null
68
+ // when this registry runs no timetable: a confirmed light-check mismatch is then only recorded.
69
+ requestStageB = null,
70
+ corpus = loadCorpus(null), // probe prompts (corpus.js)
21
71
  livenessIntervalMs = LIVENESS_INTERVAL_MS, // tests shorten this
22
72
  blindIntervalMs = BLIND_INTERVAL_MS,
73
+ followUpTickMs = FOLLOW_UP_TICK_MS,
74
+ followUpMs = FOLLOW_UP_MS,
23
75
  failThreshold = 3,
24
76
  recoverThreshold = 3, // consecutive liveness successes that lift a liveness suspension
77
+ blindFailThreshold = BLIND_FAIL_THRESHOLD,
78
+ maxExcused409 = MAX_EXCUSED_409_PER_DAY,
79
+ identityShare = IDENTITY_SHARE,
80
+ identityStageBGapMs = IDENTITY_STAGE_B_GAP_MS,
81
+ random = Math.random,
25
82
  } = {}) {
26
83
  let stopped = false;
27
84
 
@@ -80,6 +137,7 @@ export function startStageC(store, {
80
137
 
81
138
  async function blindSweep() {
82
139
  for (const node of await store.allNodes()) {
140
+ if (stopped) return;
83
141
  if (!OBSERVED_STATES.includes(node.state)) continue;
84
142
  await refreshCard?.(node.id);
85
143
  const card = await store.latestCard(node.id);
@@ -98,34 +156,165 @@ export function startStageC(store, {
98
156
  continue;
99
157
  }
100
158
  if (skipped) await store.setObservation(node.id, '_node', 'blind_skipped', null);
101
- const offering = callable[Math.floor(Math.random() * callable.length)];
102
- try {
103
- const f = fetchFor ? await fetchFor(node.id, card) : safeFetch;
104
- const { status, body } = await fetchJsonCapped(f, `${card.endpoints.openai}/chat/completions`, {
105
- method: 'POST',
106
- headers: {
107
- 'content-type': 'application/json',
108
- 'onp-offering': `${card.node.id}/${offering.offering_id}`,
109
- 'onp-card-revision': card.revision,
110
- },
111
- body: JSON.stringify({
112
- model: offering.binding.model_id,
113
- messages: [{ role: 'user', content: `ONP continuous probe ${Math.floor(Math.random() * 1e9)}: reply briefly.` }],
114
- max_tokens: 32,
115
- }),
116
- }, 30_000);
117
- if (status === 409) { await refreshCard?.(node.id); continue; } // stale pin, not a failure of the node
118
- const usage = body?.usage;
119
- const ok = status === 200 && Number.isFinite(usage?.prompt_tokens) && Number.isFinite(usage?.completion_tokens);
120
- await store.recordProbe(node.id, offering.offering_id, 'C', 'blind', ok,
121
- ok ? null : `status ${status} or missing usage`, usage ? { usage } : null);
122
- } catch (err) {
123
- await store.recordProbe(node.id, offering.offering_id, 'C', 'blind', false, String(err.message ?? err));
159
+ await probeNode(node, card, callable);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * The fresh blind invocations owed after excused 409s: each due one runs now, pinned to the card
165
+ * the registry holds (the revision the node moved to), without fetching the card first. Its 409
166
+ * goes through the same rules as any other, so a node that refuses it again with yet another
167
+ * revision spends another of its daily excuses and is owed another follow-up.
168
+ */
169
+ async function followUpTick() {
170
+ for (const nodeId of await store.dueSchedules(FOLLOW_UP, iso(Date.now()))) {
171
+ if (stopped) return;
172
+ const row = await store.getSchedule(nodeId, FOLLOW_UP);
173
+ await store.setSchedule(nodeId, FOLLOW_UP, { ...row, next_at: null, last_at: iso(Date.now()) });
174
+ const node = await store.getNode(nodeId);
175
+ if (!OBSERVED_STATES.includes(node?.state)) continue; // delisted, disputed, suspended: nothing owed
176
+ const card = await store.latestCard(nodeId);
177
+ const callable = card?.offerings.filter(testable) ?? [];
178
+ if (callable.length) await probeNode(node, card, callable);
179
+ }
180
+ }
181
+
182
+ /** One blind invocation of a random callable offering, recorded as `blind` whatever it asked. */
183
+ async function probeNode(node, card, callable) {
184
+ const offering = callable[Math.floor(random() * callable.length)];
185
+ const ref = await identityReference(node, offering);
186
+ const result = await blindProbe(node, card, offering, ref);
187
+ // The record says only whether the reply conformed: never that it carried an identity prompt,
188
+ // nor how that comparison went (node detail publishes the last probe records).
189
+ await store.recordProbe(node.id, result.offeringId, 'C', 'blind', result.ok, result.detail, result.measured);
190
+ if (!result.ok) await demoteOnBlindFailures(node);
191
+ if (result.identity) await afterLightCheck(node, card, result.identity);
192
+ }
193
+
194
+ /**
195
+ * The light identity check rides on about `identityShare` of the blind invocations of verified and
196
+ * attested nodes: one of the offering's stored references, asked as the probe's prompt.
197
+ */
198
+ async function identityReference(node, offering) {
199
+ if (!IDENTITY_STATES.includes(node.state) || !offering.model?.artifact) return null;
200
+ if (random() >= identityShare) return null;
201
+ const refs = (await store.getFingerprints(offering.model.artifact)).filter((r) => corpus.usableReference(r.prompt));
202
+ return refs.length ? refs[Math.floor(random() * refs.length)] : null;
203
+ }
204
+
205
+ /**
206
+ * One blind chat call, in the identity requests' shape (temperature 0, the same output cap). A fresh
207
+ * 409 is excused within the daily bound: the card is re-indexed, the call retried once at once
208
+ * (conformance only: the node knows that one is a probe), and a fresh blind invocation is owed
209
+ * within the hour. With `ref`, a conforming reply is also compared with the reference.
210
+ */
211
+ async function blindProbe(node, card, offering, ref = null) {
212
+ const ask = async (c, o, prompt) => chatOnce(fetchFor ? await fetchFor(node.id, c) : safeFetch, c, o, prompt, BLIND_MAX_TOKENS, 30_000);
213
+ // `note` explains a 409 in the recorded detail.
214
+ const judge = ({ status, text, usage }, o, note = null) => {
215
+ const ok = status === 200 && typeof text === 'string'
216
+ && Number.isFinite(usage?.prompt_tokens) && Number.isFinite(usage?.completion_tokens);
217
+ const detail = ok ? null : status === 409 ? ['409', note].filter(Boolean).join(' ') : `status ${status} or missing content or usage`;
218
+ return { ok, offeringId: o.offering_id, detail, measured: usage ? { usage } : null };
219
+ };
220
+ try {
221
+ let reply = await ask(card, offering, ref ? ref.prompt : corpus.chatPrompt());
222
+ if (reply.status !== 409) {
223
+ const result = judge(reply, offering);
224
+ if (ref && result.ok) result.identity = await lightCheck(reply, () => ask(card, offering, ref.prompt), ref);
225
+ return result;
226
+ }
227
+ // 409: the pinned revision is no longer current (restart, reprice), or the node is refusing a
228
+ // request it took for a probe. Re-index the card; excuse it only if the revision really moved.
229
+ await refreshCard?.(node.id);
230
+ const fresh = await store.latestCard(node.id);
231
+ if (!fresh || fresh.revision === card.revision) return judge(reply, offering, 'with the current card revision pinned');
232
+ const excused = await store.countProbes(node.id, 'blind-409', iso(Date.now() - DAY));
233
+ if (excused >= maxExcused409) {
234
+ return judge(reply, offering, `again after ${excused} card revisions in 24 h (at most ${maxExcused409} are excused)`);
124
235
  }
236
+ await store.recordProbe(node.id, offering.offering_id, 'C', 'blind-409', false,
237
+ `409 with revision ${card.revision} pinned; card re-indexed at ${fresh.revision}, probe retried, a fresh one due within the hour`);
238
+ await oweFollowUp(node.id, fresh.revision);
239
+ const retryOffering = fresh.offerings.find((o) => o.offering_id === offering.offering_id && testable(o))
240
+ ?? fresh.offerings.find(testable);
241
+ if (!retryOffering) return { ok: false, offeringId: offering.offering_id, detail: `the new revision ${fresh.revision} has no tested offering`, measured: null };
242
+ reply = await ask(fresh, retryOffering, corpus.chatPrompt());
243
+ return judge(reply, retryOffering, reply.status === 409 ? 'on the retry with the re-indexed revision' : null);
244
+ } catch (err) {
245
+ return { ok: false, offeringId: offering.offering_id, detail: String(err.message ?? err), measured: null };
246
+ }
247
+ }
248
+
249
+ /**
250
+ * The light identity check (ONP-3 §4a.9) under Stage B's one-repeat rule: a reply that is not the
251
+ * reference's is asked once more, and only a second miss (or no answer to the repeat) counts.
252
+ */
253
+ async function lightCheck(reply, repeat, ref) {
254
+ if (matchesReference(reply.text, ref)) return { match: true, repeated: false };
255
+ let again = null;
256
+ try { again = await repeat(); } catch { /* no answer to the repeat: the miss stands */ }
257
+ return { match: again?.status === 200 && matchesReference(again.text, ref), repeated: true };
258
+ }
259
+
260
+ /**
261
+ * Record a light check in the node's private LIGHT_CHECK row; a confirmed mismatch makes Stage B
262
+ * due within the hour, at most once per `identityStageBGapMs`. The tier does not change here.
263
+ */
264
+ async function afterLightCheck(node, card, { match }) {
265
+ const prev = await store.getSchedule(node.id, LIGHT_CHECK);
266
+ const now = Date.now();
267
+ let asked = prev?.next_at ?? null; // when the last Stage B this check asked for was due
268
+ if (!match && requestStageB && (!asked || now - Date.parse(asked) >= identityStageBGapMs)) {
269
+ asked = await requestStageB(node.id, card) ?? asked;
270
+ }
271
+ await store.setSchedule(node.id, LIGHT_CHECK, {
272
+ last_at: iso(now), next_at: asked, ok: match, revision: card.revision,
273
+ failures: match ? 0 : (prev?.failures ?? 0) + 1,
274
+ });
275
+ }
276
+
277
+ /** After an excused 409: a fresh blind invocation within the hour (a sooner one already owed stays). */
278
+ async function oweFollowUp(nodeId, revision) {
279
+ const prev = await store.getSchedule(nodeId, FOLLOW_UP);
280
+ const due = Date.now() + between(followUpMs, random);
281
+ const owed = prev?.next_at ? Date.parse(prev.next_at) : Infinity;
282
+ await store.setSchedule(nodeId, FOLLOW_UP, {
283
+ last_at: prev?.last_at ?? null, next_at: iso(Math.min(owed, due)), ok: null, revision,
284
+ failures: (prev?.failures ?? 0) + 1, // excused 409s so far
285
+ });
286
+ }
287
+
288
+ /**
289
+ * A node that answers its health checks but keeps failing blind invocations is not serving what
290
+ * its tier says: after `blindFailThreshold` consecutive failures since its last state change it
291
+ * drops one tier. Getting it back takes the scheduled Stage A (community) and Stage B (verified).
292
+ */
293
+ async function demoteOnBlindFailures({ id }) {
294
+ const node = await store.getNode(id);
295
+ const to = DEMOTE[node?.state];
296
+ if (!to) return;
297
+ const since = (await store.transitionsFor(node.id)).at(-1)?.at ?? '';
298
+ let failures = 0;
299
+ for (const p of await store.probesFor(node.id)) {
300
+ if (p.stage !== 'C' || p.kind !== 'blind') continue;
301
+ if (p.at < since || p.ok) break;
302
+ failures++;
125
303
  }
304
+ if (failures < blindFailThreshold) return;
305
+ // Only a node that is up loses its tier this way: one that is down gets the liveness rules
306
+ // (a temporary suspension, reinstated when it answers again), not a demotion.
307
+ const card = await store.latestCard(node.id);
308
+ let healthy = false;
309
+ try {
310
+ const f = fetchFor ? await fetchFor(node.id, card) : safeFetch;
311
+ const { status, body } = await fetchJsonCapped(f, card.endpoints.health, {}, 5_000);
312
+ healthy = status === 200 && (body?.status === 'ok' || Array.isArray(body?.data));
313
+ } catch { healthy = false; }
314
+ if (healthy) await store.setState(node.id, to, `blind: ${failures} consecutive failed blind invocations`);
126
315
  }
127
316
 
128
- const jitter = (base) => base * (JITTER[0] + Math.random() * (JITTER[1] - JITTER[0]));
317
+ const jitter = (base) => base * (JITTER[0] + random() * (JITTER[1] - JITTER[0]));
129
318
  const loop = (fn, base) => {
130
319
  const tick = async () => {
131
320
  if (stopped) return;
@@ -136,6 +325,12 @@ export function startStageC(store, {
136
325
  };
137
326
  loop(livenessSweep, livenessIntervalMs);
138
327
  loop(blindSweep, blindIntervalMs);
328
+ loop(followUpTick, followUpTickMs);
139
329
 
140
- return { stop: () => { stopped = true; } };
330
+ return {
331
+ stop: () => { stopped = true; },
332
+ /** One blind sweep, or one look for due follow-ups, now (tests). */
333
+ blindSweep,
334
+ followUpTick,
335
+ };
141
336
  }