ravensight-playtest 0.7.5 → 0.8.1

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.
@@ -1,15 +1,22 @@
1
- import { createHash } from 'node:crypto';
2
- import { mkdir, open, access, rename } from 'node:fs/promises';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, access, rename, readFile, readdir, rm } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CliError, ExitCode } from '../errors.js';
5
5
  import { ApiError } from '../api/errors.js';
6
6
  import { stableStringify } from '../fsutil.js';
7
7
  import { printable } from '../ui/index.js';
8
+ import { chooseProfile } from './buildUpload.js';
9
+ import { displayName } from '../run/controllers.js';
10
+ import { queueInfo } from './status.js';
8
11
 
9
12
  const MAX_QUOTE_BYTES = 1024 * 1024;
10
13
  const CONSENT_KEYS = ['quoteId', 'planHash', 'profileVersion', 'controllers', 'includeVideo', 'includeTranscript',
11
14
  'totalPriceCents', 'dueNowCents', 'priceVersion', 'policyVersion'];
12
15
  const PROVIDERS = ['anthropic', 'openai'];
16
+ // Customers choose Geri's model provider by role, never by vendor name. The
17
+ // server's wire values stay; ravensight.io/legal/subprocessors names both.
18
+ export const GERI_PROVIDERS = Object.freeze({ primary: 'anthropic', alternate: 'openai' });
19
+ const providerLabel = wire => ({ anthropic: 'primary model provider', openai: 'alternate model provider' }[wire] || 'model provider');
13
20
  const base = game => `/api/v1/games/${encodeURIComponent(game)}/playtest/hosted`;
14
21
  const digest = value => createHash('sha256').update(stableStringify(value)).digest('hex');
15
22
  const fail = message => { throw new CliError(message); };
@@ -58,7 +65,7 @@ export async function readHostedQuote(filename) {
58
65
  function requestFor({ buildId, profileVersion, persona, standardProvider, includeVideo = false, includeTranscript = false }, profile) {
59
66
  if (!id(buildId) || !id(profileVersion) || typeof persona !== 'string' || persona.length > 48
60
67
  || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(persona)) fail('Choose a validated build, ready profile and one persona.');
61
- if (standardProvider !== undefined && !PROVIDERS.includes(standardProvider)) fail('Choose anthropic or openai for Standard.');
68
+ if (standardProvider !== undefined && !PROVIDERS.includes(standardProvider)) fail('Choose primary or alternate for the Geri model provider.');
62
69
  if (typeof includeVideo !== 'boolean' || typeof includeTranscript !== 'boolean') fail('Choose explicit video and transcript options.');
63
70
  return { kind: 'recorded_graphical', buildId, personas: [persona], controllers: ['standard', 'jev'],
64
71
  driver: profile.driver, runLength: 'standard', profileVersion, includeVideo, includeTranscript,
@@ -70,13 +77,16 @@ async function available(api, gameId, profileVersion, standardProvider) {
70
77
  const caps = answer.body, recorded = caps?.recorded;
71
78
  if (!recorded?.available || recorded.intakeEnabled !== true || !Array.isArray(recorded.profiles)
72
79
  || !Array.isArray(recorded.controllers) || !['standard', 'jev'].every(value => recorded.controllers.includes(value))) {
73
- fail('This server does not currently advertise ready recorded Standard/Jev runs. Nothing was charged.');
80
+ fail('This server does not currently advertise ready hosted Geri and Freki runs. Nothing was charged.');
74
81
  }
75
- const matches = recorded.profiles.filter(value => value.profileVersion === profileVersion);
82
+ // The same rule as "build upload": the one named, or the only one
83
+ // advertised; with several and none named, the error lists them.
84
+ const chosen = chooseProfile(recorded.profiles, profileVersion);
85
+ const matches = recorded.profiles.filter(value => value.profileVersion === chosen);
76
86
  if (matches.length !== 1 || !['playwright_web', 'godot_driver'].includes(matches[0].driver)) fail('Choose exactly one currently advertised ready hosted profile. Nothing was charged.');
77
87
  if (standardProvider !== undefined && (!PROVIDERS.includes(standardProvider)
78
88
  || !Array.isArray(recorded.standardProviders) || !recorded.standardProviders.includes(standardProvider))) {
79
- fail(`This server does not advertise ready Standard ${standardProvider}. No provider fallback or charge was requested.`);
89
+ fail(`This server does not advertise Geri on the ${providerLabel(standardProvider)} as ready. No provider fallback or charge was requested.`);
80
90
  }
81
91
  return { profile: matches[0], funding: caps.funding };
82
92
  }
@@ -101,11 +111,11 @@ export function hostedConsent(quote, request, now = Date.now()) {
101
111
  || sum(quote.localBreakdown, row => BigInt(row.count) * BigInt(row.unitCents)) !== quote.localPriceCents
102
112
  || !Array.isArray(quote.computeBreakdown) || quote.computeBreakdown.length !== 2
103
113
  || !quote.computeBreakdown.every((row, index) => row.controller === request.controllers[index] && row.profileVersion === request.profileVersion && cents(row.priceCents))
104
- || sum(quote.computeBreakdown, row => BigInt(row.priceCents)) !== quote.computePriceCents) fail('The server did not quote every Standard/Jev price. Nothing was charged.');
114
+ || sum(quote.computeBreakdown, row => BigInt(row.priceCents)) !== quote.computePriceCents) fail('The server did not quote every Geri and Freki price. Nothing was charged.');
105
115
  const explicit = request.standardProvider !== undefined;
106
116
  if (explicit ? quote.standardProvider !== request.standardProvider || !hex(quote.standardProviderPolicyHash)
107
117
  : Object.hasOwn(quote, 'standardProvider') || Object.hasOwn(quote, 'standardProviderPolicyHash')) {
108
- fail('The quoted Standard provider policy does not match the requested choice. Nothing was charged.');
118
+ fail('The quoted Geri provider policy does not match the requested choice. Nothing was charged.');
109
119
  }
110
120
  return Object.fromEntries([...CONSENT_KEYS, ...(explicit ? ['standardProvider', 'standardProviderPolicyHash'] : [])].map(key => [key, quote[key]]));
111
121
  }
@@ -123,7 +133,7 @@ export async function quoteHostedRun({ api, apiUrl, gameId, output, now = Date.n
123
133
  try { await access(output); fail('That saved quote already exists. Choose a new output path; the original was preserved.'); }
124
134
  catch (error) { if (error.code !== 'ENOENT') throw error; }
125
135
  const { profile } = await available(api, gameId, options.profileVersion, options.standardProvider);
126
- const request = requestFor(options, profile);
136
+ const request = requestFor({ ...options, profileVersion: profile.profileVersion }, profile);
127
137
  const response = await api.request('POST', `${base(gameId)}/quotes`, { body: request, idempotent: false });
128
138
  if (response.status !== 200) fail('The server did not return a hosted quote. No admission was requested.');
129
139
  const quote = response.body, consent = hostedConsent(quote, request, now());
@@ -136,95 +146,296 @@ export async function quoteHostedRun({ api, apiUrl, gameId, output, now = Date.n
136
146
  export function hostedQuoteLines(offer) {
137
147
  const { quote: q, request: r } = offer;
138
148
  return [`Game ${offer.gameId}; build ${r.buildId}; persona ${r.personas[0]}; profile ${r.profileVersion}.`,
139
- `Two separate playthroughs: Standard (${r.standardProvider || 'server default Anthropic'}) then Jev.`,
140
- ...(r.standardProvider ? [`Standard provider policy: ${q.standardProviderPolicyHash}.`] : []),
149
+ `Two separate playthroughs: Geri (${r.standardProvider ? providerLabel(r.standardProvider) : 'server default model provider'}) then Freki.`,
150
+ ...(r.standardProvider ? [`Geri provider policy: ${q.standardProviderPolicyHash}.`] : []),
141
151
  ...q.localBreakdown.map(row => `${row.count} ${row.unit} at ${money(row.unitCents)} each: ${money(row.count * row.unitCents)}.`),
142
- ...q.computeBreakdown.map(row => `${row.controller} hosted compute: ${money(row.priceCents)}.`),
152
+ ...q.computeBreakdown.map(row => `${displayName(row.controller)} hosted compute: ${money(row.priceCents)}.`),
143
153
  `Total ${money(q.totalPriceCents)}; already reserved ${money(q.alreadyReservedCents)}; due now ${money(q.dueNowCents)} from prepaid funds. No top-up is performed.`,
144
154
  `Video: ${r.includeVideo ? 'included' : 'off'}. Hosted runs save no transcript.`,
145
155
  `Customer failure: ${q.customerFailure}; cancellation after start: ${q.cancelAfterStart}. Price ${q.priceVersion}; refund policy ${q.policyVersion}.`,
146
156
  `Quote expires ${new Date(q.expiresAt).toISOString()}.`];
147
157
  }
148
158
 
149
- // A saved durable intent is never retried, even with the same quote or a new
150
- // capability response. The server also receives a stable key for this plan.
151
- export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now }) {
159
+ const journalDir = repoRoot => path.join(repoRoot, '.ravensight', 'hosted-runs');
160
+ const journalFor = (repoRoot, { apiUrl, gameId, planHash }) => path.join(journalDir(repoRoot), `${digest({ apiUrl, gameId, planHash })}.json`);
161
+ const offerJournal = (repoRoot, offer) => journalFor(repoRoot, { apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
162
+ // The longest a server quote lives (recordedPlan QUOTE_MS). An older journal
163
+ // without the quote's own expiry is resolved after this much time.
164
+ const QUOTE_LIFETIME_MS = 300000;
165
+ const SERVER_CLOCK_MARGIN_MS = 15000;
166
+
167
+ async function readJournal(filename) {
168
+ try { return JSON.parse(await readFile(filename, 'utf8')); }
169
+ catch (error) { if (error.code === 'ENOENT') return null; return { unreadable: true }; }
170
+ }
171
+
172
+ // Removes the intent and every response captured for it. Only called when the
173
+ // server said for certain that nothing was admitted. The idempotency key is
174
+ // derived from the plan, so a later attempt with the same quote sends the same
175
+ // key and the server still deduplicates it.
176
+ async function clearIntent(journal) {
177
+ const dir = path.dirname(journal), name = path.basename(journal);
178
+ let names = [];
179
+ try { names = await readdir(dir); } catch (error) { if (error.code !== 'ENOENT') throw error; }
180
+ await Promise.all(names.filter(row => row === name || row.startsWith(name + '.')).map(row => rm(path.join(dir, row), { force: true })));
181
+ }
182
+
183
+ // A saved durable intent whose outcome is unknown is never retried here; only
184
+ // "hosted status" asks the server about it. The server receives a stable key.
185
+ export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now, admit = admitHostedOffer }) {
152
186
  const offer = validateHostedOffer(await readHostedQuote(filename), apiUrl, now());
153
- const identity = digest({ apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
154
- const journal = path.join(repoRoot, '.ravensight', 'hosted-runs', `${identity}.json`);
155
- try { await access(journal); fail(`This hosted quote already has an admission intent at ${journal}. Reconcile the original outcome; no POST was repeated.`); }
156
- catch (error) { if (error.code !== 'ENOENT') throw error; }
187
+ const journal = offerJournal(repoRoot, offer), prior = await readJournal(journal);
188
+ if (prior?.phase === 'charged_blocked' && admissionPattern.test(prior.admission?.admissionId || '')) {
189
+ fail(`This quote already started hosted run ${prior.admission.admissionId}. Check it with: ravensight-playtest hosted status ${prior.admission.admissionId}`);
190
+ }
191
+ if (prior) fail(`This quote's earlier admission has no known outcome yet (${journal}). Ask the server what happened with: ravensight-playtest hosted status. No request was repeated.`);
157
192
  const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
158
193
  if (profile.driver !== offer.request.driver || funding?.eligible === false || offer.quote.funding?.eligible === false) fail('The server no longer advertises this profile or sufficient prepaid funding. Nothing was charged.');
159
194
  await onPrepared(offer);
160
195
  if (typeof confirm !== 'function') fail('The full hosted quote must be confirmed before admission.');
161
196
  if (!await confirm(confirmQuestion(offer))) return { state: 'declined', walletMutationRequested: false };
162
- return admitHostedOffer({ offer, api, apiUrl, repoRoot, now });
197
+ return admit({ offer, api, apiUrl, repoRoot, now });
163
198
  }
164
199
 
165
- export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Standard then Jev runs and the evidence options shown?`;
200
+ export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Geri then Freki runs and the evidence options shown?`;
166
201
 
167
- // Refusals the server makes before any charge: the quote or consent was not
168
- // accepted, funding or capacity said no, or the quote is gone. The original
169
- // intent is kept on disk all the same; only the message differs.
170
- const DEFINITE_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found', 'recorded_unavailable',
202
+ // Refusals the server makes with its own code, before any charge: the request
203
+ // failed inside the admission's transaction, which rolled back, or before it.
204
+ // These are certain, so the local intent is cleared and the same quote can be
205
+ // tried again. A 5xx or a status the server did not explain is not certain.
206
+ const CERTAIN_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found',
171
207
  'recorded_setup_required', 'hosted_global_capacity', 'too_many_active_hosted_runs', 'hosted_daily_capacity',
172
- 'hosted_build_too_large', 'hosted_build_safety_hold']);
208
+ 'hosted_build_too_large', 'hosted_build_safety_hold', 'quote_expired', 'recorded_quote_changed',
209
+ 'hosted_game_unavailable', 'hosted_studio_unavailable']);
210
+ // Refused by the server with its own code, but a 5xx: reported plainly, intent kept for "hosted status".
211
+ const EXPLAINED_UNAVAILABLE = new Set(['recorded_unavailable', 'hosted_execution_budget_unconfigured']);
212
+ export const CAPACITY_CODES = Object.freeze(['hosted_global_capacity', 'too_many_active_hosted_runs']);
213
+ // The server keeps an attempt it refused under the plan's key and answers a
214
+ // repeat with this, so that quote cannot start a run. Nothing was charged.
215
+ export const REFUSED_EARLIER = 'hosted_quote_refused_earlier';
216
+
217
+ export const certainRefusal = error => error instanceof ApiError
218
+ && (error.status === 401 || error.status >= 400 && error.status < 500 && CERTAIN_REFUSALS.has(error.code));
173
219
 
174
220
  export function hostedRefusalMessage(error) {
175
221
  const code = error?.code;
176
222
  if (code === 'hosted_funding_required') {
177
223
  const f = error.body?.funding;
178
224
  const topUp = Number.isSafeInteger(f?.requiredTopUpCents) && f.requiredTopUpCents > 0 ? ` Add at least ${money(f.requiredTopUpCents)} of prepaid funds, then request a new quote.` : ' Add prepaid funds, then request a new quote.';
179
- return `The server refused the run for funding. Nothing was charged.${topUp}`;
225
+ return `The server refused the run for funding. No run was started and nothing was charged.${topUp}`;
180
226
  }
181
227
  if (code === 'quote_not_accepted') return 'The server did not accept this consent for the quote. Nothing was charged; request a new quote.';
182
- if (['hosted_global_capacity', 'too_many_active_hosted_runs'].includes(code)) return 'Hosted capacity is busy. Nothing was charged. Wait for an existing run to finish, then retry. Adding funds does not increase capacity.';
183
- if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. Nothing was charged. Try again after the daily limit resets.';
228
+ if (CAPACITY_CODES.includes(code)) return 'Hosted capacity is busy, so no run was started and nothing was charged. Run the same command again with --wait-for-capacity to wait for room and start then; it never charges twice. Adding funds does not increase capacity.';
229
+ if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. No run was started and nothing was charged. Try again after the daily limit resets at 00:00 UTC.';
184
230
  if (code === 'recorded_setup_required') return `${error.message || 'Complete the playtest brief and choose an available persona.'} Nothing was charged.`;
185
231
  if (code === 'not_found') return 'The quote is no longer available. Nothing was charged; request a new quote.';
232
+ if (code === 'quote_expired' || code === 'recorded_quote_changed') return 'The quote expired before the run was admitted. No run was started and nothing was charged; request a new quote.';
186
233
  if (code === 'hosted_build_too_large') return 'This build is too large to play on a hosted machine: hosted playtests play builds up to 300 MiB unpacked. Make the build smaller and upload it again. Nothing was charged.';
187
234
  if (code === 'hosted_build_safety_hold') return 'This build was stopped for safety during a hosted playtest and cannot run again until an admin reviews and clears it in the dashboard. Nothing was charged.';
235
+ if (code === REFUSED_EARLIER) return 'The server already refused an earlier attempt with this quote, so it will not start a run from it. No run was started and nothing was charged; request a new quote, or use "hosted run" without a quote file.';
188
236
  return 'Hosted playtests are not available right now. Nothing was charged.';
189
237
  }
190
238
 
191
- // A saved durable intent is never retried. The journal is fsynced before the
192
- // only wallet-mutating POST and the server receives a stable key for the plan.
239
+ const refusalError = (code, error = { code }) => Object.assign(new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT),
240
+ { refusal: { code, certain: true, retryAfter: Number.isFinite(error.retryAfter) ? error.retryAfter : null } });
241
+
242
+ // What a 202 from POST /runs says: the acknowledgement of a new or replayed
243
+ // admission, the server's record that this key's attempt was refused, or an
244
+ // outcome the server itself cannot yet state.
245
+ function readAdmissionAnswer(answer, totalPriceCents) {
246
+ if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
247
+ || typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) return { kind: 'unknown' };
248
+ let ack;
249
+ try { ack = JSON.parse(answer.body); } catch { return { kind: 'unknown' }; }
250
+ if (ack && same(ack, { state: 'failed', dispatchAllowed: false })) return { kind: 'refused_earlier' };
251
+ // A queued admission also carries its queue place; it is read through queueInfo, never trusted as money.
252
+ const keys = ack && typeof ack === 'object' ? Object.keys(ack).filter(key => key !== 'queue').sort() : [];
253
+ if (Object.hasOwn(ack || {}, 'queue') && !queueInfo(ack)) return { kind: 'unknown' };
254
+ if (!ack || !same(keys, ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'])
255
+ || ack.state !== 'charged_blocked' || ack.dispatchAllowed !== false || ack.totalPriceCents !== totalPriceCents
256
+ || !admissionPattern.test(ack.admissionId || '') || !/^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '')) return { kind: 'unknown' };
257
+ return { kind: 'admitted', ack };
258
+ }
259
+
260
+ async function postAdmission(api, { gameId, consent, idempotencyKey }, captureFile) {
261
+ let responseCaptured = false;
262
+ const answer = await api.request('POST', `${base(gameId)}/runs`, { body: consent,
263
+ headers: { 'Idempotency-Key': idempotencyKey }, idempotent: false, raw: true,
264
+ onResponseRaw: async ({ status, contentType, bytes, bodyComplete }) => {
265
+ await exclusiveJson(captureFile, { status, contentType, bodyComplete,
266
+ bodyBase64: bytes.toString('base64'), bodyBytes: bytes.length,
267
+ bodySha256: createHash('sha256').update(bytes).digest('hex') });
268
+ responseCaptured = true;
269
+ } });
270
+ return responseCaptured ? answer : null;
271
+ }
272
+
273
+ async function recordAdmitted(journal, state, ack) {
274
+ state.phase = 'charged_blocked'; state.admission = ack; state.resolvedAt = new Date().toISOString();
275
+ await rm(journal + '.acknowledged.json', { force: true });
276
+ await exclusiveJson(journal + '.acknowledged.json', state);
277
+ await rename(journal + '.acknowledged.json', journal);
278
+ }
279
+
280
+ // The journal is fsynced before the only wallet-mutating POST and the server
281
+ // receives a stable key for the plan. A certain refusal clears the journal;
282
+ // anything else keeps it as admission_unknown for "hosted status" to resolve.
193
283
  export async function admitHostedOffer({ offer, api, apiUrl, repoRoot, now = Date.now }) {
194
284
  validateHostedOffer(offer, apiUrl, now());
195
- const identity = digest({ apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
196
- const journal = path.join(repoRoot, '.ravensight', 'hosted-runs', `${identity}.json`);
285
+ const journal = offerJournal(repoRoot, offer);
197
286
  const state = { schema: 'ravensight-hosted-admission-journal/v1', apiUrl: offer.apiUrl, gameId: offer.gameId,
198
287
  quoteId: offer.quote.quoteId, planHash: offer.quote.planHash, consent: offer.consent,
199
- idempotencyKey: `hosted-${offer.quote.planHash}`, phase: 'admission_unknown', createdAt: new Date(now()).toISOString() };
288
+ idempotencyKey: `hosted-${offer.quote.planHash}`, quoteExpiresAt: offer.quote.expiresAt,
289
+ phase: 'admission_unknown', createdAt: new Date(now()).toISOString() };
200
290
  await exclusiveJson(journal, state); // fsync BEFORE the only wallet-mutating POST
201
- try {
202
- let responseCaptured = false;
203
- const answer = await api.request('POST', `${base(offer.gameId)}/runs`, { body: offer.consent,
204
- headers: { 'Idempotency-Key': state.idempotencyKey }, idempotent: false, raw: true,
205
- onResponseRaw: async ({ status, contentType, bytes, bodyComplete }) => {
206
- await exclusiveJson(journal + '.response.json', { status, contentType, bodyComplete,
207
- bodyBase64: bytes.toString('base64'), bodyBytes: bytes.length,
208
- bodySha256: createHash('sha256').update(bytes).digest('hex') });
209
- responseCaptured = true;
210
- } });
211
- if (!responseCaptured) fail('The admission response was not captured. Preserve the original intent.');
212
- if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
213
- || typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) fail('The admission acknowledgement needs reconciliation.');
214
- const ack = JSON.parse(answer.body);
215
- if (!same(Object.keys(ack).sort(), ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'])
216
- || ack.state !== 'charged_blocked' || ack.dispatchAllowed !== false || ack.totalPriceCents !== offer.quote.totalPriceCents
217
- || !/^ha_[a-f0-9-]{36}$/.test(ack.admissionId || '') || !/^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '')) fail('The admission acknowledgement needs reconciliation.');
218
- state.phase = 'charged_blocked'; state.admission = ack;
219
- await exclusiveJson(journal + '.acknowledged.json', state);
220
- await rename(journal + '.acknowledged.json', journal);
221
- return { state: 'charged_blocked', ...ack, journal, replayAuthorized: false, gameplayProven: false };
222
- } catch (error) {
223
- if (error instanceof ApiError && error.status === 401) throw error;
224
- if (error instanceof ApiError && DEFINITE_REFUSALS.has(error.code) && error.status >= 400 && error.status < 600) {
225
- throw new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT);
291
+ let answer;
292
+ try { answer = await postAdmission(api, state, journal + '.response.json'); }
293
+ catch (error) {
294
+ if (certainRefusal(error)) {
295
+ await clearIntent(journal);
296
+ if (error.status === 401) throw error;
297
+ throw refusalError(error.code, error);
298
+ }
299
+ if (error instanceof ApiError && EXPLAINED_UNAVAILABLE.has(error.code)) {
300
+ throw new CliError(`${hostedRefusalMessage(error)} To confirm and free this quote, run: ravensight-playtest hosted status`, ExitCode.ENVIRONMENT);
301
+ }
302
+ fail(`The admission's outcome is not known: ${unknownAdvice(journal)}`);
303
+ }
304
+ const read = answer ? readAdmissionAnswer(answer, offer.quote.totalPriceCents) : { kind: 'unknown' };
305
+ if (read.kind === 'refused_earlier') { await clearIntent(journal); throw refusalError(REFUSED_EARLIER); }
306
+ if (read.kind !== 'admitted') fail(`The admission acknowledgement needs reconciliation: ${unknownAdvice(journal)}`);
307
+ await recordAdmitted(journal, state, read.ack);
308
+ return { state: 'charged_blocked', ...read.ack, queue: queueInfo(read.ack), journal, replayAuthorized: false, gameplayProven: false };
309
+ }
310
+
311
+ const unknownAdvice = journal => `the run may or may not have started. Preserve ${journal}; nothing was retried. Ask the server what happened with: ravensight-playtest hosted status`;
312
+
313
+ /**
314
+ * Settle every saved admission intent whose outcome is unknown by asking the
315
+ * server, which answers from its own record under the same idempotency key.
316
+ * The question is only sent once the quote has expired, so it can report an
317
+ * admission but never start one. A certain answer that nothing was admitted
318
+ * clears the intent; an admission is recorded; anything else is kept.
319
+ */
320
+ export async function resolveHostedIntents({ api, apiUrl, repoRoot, now = Date.now }) {
321
+ const dir = journalDir(repoRoot), here = origin(apiUrl), results = [];
322
+ let names = [];
323
+ try { names = (await readdir(dir)).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).sort(); }
324
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
325
+ for (const name of names) {
326
+ const journal = path.join(dir, name), state = await readJournal(journal);
327
+ if (!state || state.phase !== 'admission_unknown') continue;
328
+ if (state.unreadable || state.schema !== 'ravensight-hosted-admission-journal/v1' || !id(state.gameId) || !hex(state.planHash)
329
+ || state.idempotencyKey !== `hosted-${state.planHash}` || !state.consent || typeof state.consent !== 'object'
330
+ || journalFor(repoRoot, state) !== journal) {
331
+ results.push({ journal, state: 'unreadable', message: `${journal} is not a hosted admission record this version can read. Nothing was sent.` });
332
+ continue;
333
+ }
334
+ if (state.apiUrl !== here) {
335
+ results.push({ journal, gameId: state.gameId, state: 'other_api', message: `${journal} belongs to ${state.apiUrl}. Run this with --api-url ${state.apiUrl} to resolve it.` });
336
+ continue;
337
+ }
338
+ const created = Date.parse(state.createdAt);
339
+ const expiresAt = Number.isSafeInteger(state.quoteExpiresAt) ? state.quoteExpiresAt : (Number.isFinite(created) ? created + QUOTE_LIFETIME_MS : null);
340
+ const askAt = expiresAt === null ? null : expiresAt + SERVER_CLOCK_MARGIN_MS;
341
+ if (askAt === null || now() < askAt) {
342
+ results.push({ journal, gameId: state.gameId, state: 'wait', askAt,
343
+ message: askAt === null ? `${journal} has no readable time. Nothing was sent.`
344
+ : `Game ${state.gameId}: asking before ${new Date(askAt).toISOString()} could still start the run, so nothing was sent. Run "hosted status" again after that time.` });
345
+ continue;
346
+ }
347
+ let answer;
348
+ try { answer = await postAdmission(api, state, `${journal}.reconcile-${now()}-${randomUUID().slice(0, 8)}.json`); }
349
+ catch (error) {
350
+ if (certainRefusal(error) && error.status !== 401) {
351
+ await clearIntent(journal);
352
+ results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: error.code,
353
+ message: `Game ${state.gameId}: the server has no run for this quote. No run was started and nothing was charged. The record is cleared.` });
354
+ continue;
355
+ }
356
+ if (error instanceof ApiError && error.status === 401) throw error;
357
+ results.push({ journal, gameId: state.gameId, state: 'unknown', message: `Game ${state.gameId}: the server did not answer clearly (${error.code || error.message}). The record is kept; try again later.` });
358
+ continue;
359
+ }
360
+ const read = answer ? readAdmissionAnswer(answer, state.consent.totalPriceCents) : { kind: 'unknown' };
361
+ if (read.kind === 'refused_earlier') {
362
+ await clearIntent(journal);
363
+ results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: REFUSED_EARLIER,
364
+ message: `Game ${state.gameId}: the server refused that attempt. No run was started and nothing was charged. The record is cleared.` });
365
+ } else if (read.kind === 'admitted') {
366
+ await recordAdmitted(journal, state, read.ack);
367
+ results.push({ journal, gameId: state.gameId, state: 'admitted', admissionId: read.ack.admissionId, jobId: read.ack.jobId,
368
+ totalPriceCents: read.ack.totalPriceCents, message: `Game ${state.gameId}: the run was admitted as ${read.ack.admissionId} and charged ${money(read.ack.totalPriceCents)}.` });
369
+ } else {
370
+ results.push({ journal, gameId: state.gameId, state: 'unknown',
371
+ message: `Game ${state.gameId}: the server cannot state the outcome yet. The record is kept; nothing was retried. If this persists, write to support@realityse.com with ${path.basename(journal)}.` });
372
+ }
373
+ }
374
+ return results;
375
+ }
376
+
377
+ // The terms a person accepted. A fresh quote taken while waiting for capacity
378
+ // must match them exactly, or nothing is admitted without asking again.
379
+ const TERMS = ['buildId', 'profileVersion', 'driver', 'controllers', 'includeVideo', 'includeTranscript', 'currency',
380
+ 'localPriceCents', 'computePriceCents', 'totalPriceCents', 'dueNowCents', 'alreadyReservedCents', 'localBreakdown',
381
+ 'computeBreakdown', 'priceVersion', 'policyVersion', 'customerFailure', 'cancelAfterStart', 'standardProvider',
382
+ 'standardProviderPolicyHash'];
383
+ const sameTerms = (a, b) => TERMS.every(key => same(a[key] ?? null, b[key] ?? null));
384
+
385
+ /** A fresh quote for exactly the request of an accepted offer. Charges nothing. */
386
+ export async function requoteOffer({ api, apiUrl, offer, now = Date.now }) {
387
+ const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
388
+ if (profile.driver !== offer.request.driver) fail('The server no longer advertises this build profile. No run was started and nothing was charged.');
389
+ const response = await api.request('POST', `${base(offer.gameId)}/quotes`, { body: offer.request, idempotent: false });
390
+ if (response.status !== 200) fail('The server did not return a hosted quote. No run was started and nothing was charged.');
391
+ const quote = response.body, consent = hostedConsent(quote, offer.request, now());
392
+ if (fundingShortfall(quote, funding)) fail('The balance no longer meets this hosted run\'s funding requirement. No run was started and nothing was charged. Add prepaid funds, then run the command again.');
393
+ if (!sameTerms(offer.quote, quote)) fail(`The price or terms changed while waiting for capacity, so no run was started and nothing was charged. Run the command again to see the new quote (it was ${money(offer.quote.totalPriceCents)}, now ${money(quote.totalPriceCents)}).`);
394
+ const value = { apiUrl: origin(apiUrl), gameId: offer.gameId, request: offer.request, quote, consent };
395
+ return { schema: 'ravensight-hosted-recorded-quote/v1', ...value, integrity: digest(value) };
396
+ }
397
+
398
+ export const CAPACITY_POLL_MS = 60000;
399
+ export const CAPACITY_JITTER_MS = 30000;
400
+ const CAPACITY_RETRY_AFTER_MAX_MS = 15 * 60000;
401
+
402
+ /** The wait before asking again: at least a minute, longer if the server says so, plus jitter. */
403
+ export function capacityDelay(error, random = Math.random) {
404
+ const server = Number.isFinite(error?.retryAfter) && error.retryAfter > 0 ? Math.min(error.retryAfter * 1000, CAPACITY_RETRY_AFTER_MAX_MS) : 0;
405
+ return Math.max(CAPACITY_POLL_MS, server) + Math.floor(random() * CAPACITY_JITTER_MS);
406
+ }
407
+
408
+ /**
409
+ * Admit an accepted offer, and while the server answers that hosted capacity
410
+ * is busy, ask again about once a minute until there is room or maxWaitMs
411
+ * passes. Every busy answer is a certain refusal that charged nothing and
412
+ * cleared its intent; any other outcome ends the wait, so an unknown outcome
413
+ * is never retried. Quotes last minutes, so each new attempt takes a fresh
414
+ * quote and refuses unless its terms equal the accepted ones exactly.
415
+ */
416
+ export async function admitWithCapacityWait({ offer, api, apiUrl, repoRoot, maxWaitMs, now = Date.now,
417
+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), random = Math.random, onBusy = () => {}, onRequote = () => {} }) {
418
+ if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 1) fail('Choose how long to wait for capacity.');
419
+ const started = now(), deadline = started + maxWaitMs;
420
+ let current = offer, requoteNext = false, busy = 0;
421
+ for (;;) {
422
+ if (requoteNext) { current = await requoteOffer({ api, apiUrl, offer, now }); onRequote(current); }
423
+ try { return { ...await admitHostedOffer({ offer: current, api, apiUrl, repoRoot, now }), offer: current, busyAnswers: busy }; }
424
+ catch (error) {
425
+ const code = error?.refusal?.code;
426
+ // The server will not admit this quote again: take a fresh one straight away, once.
427
+ if (!requoteNext && [REFUSED_EARLIER, 'quote_expired', 'recorded_quote_changed'].includes(code)) { requoteNext = true; continue; }
428
+ if (!CAPACITY_CODES.includes(code)) throw error;
429
+ busy += 1;
430
+ const delay = capacityDelay(error.refusal, random);
431
+ if (now() + delay > deadline) {
432
+ const waited = Math.max(1, Math.round((now() - started) / 60000));
433
+ throw Object.assign(new CliError(`Hosted capacity stayed busy for ${waited} minute${waited === 1 ? '' : 's'}, so no run was started and nothing was charged. Run the command again later, or with a longer --wait-for-capacity.`, ExitCode.ENVIRONMENT), { refusal: error.refusal });
434
+ }
435
+ onBusy({ attempt: busy, delayMs: delay, waitedMs: now() - started, maxWaitMs });
436
+ await sleep(delay);
437
+ requoteNext = true;
226
438
  }
227
- fail(`The original admission outcome needs reconciliation. Preserve ${journal}; no retry or replacement admission was requested.`);
228
439
  }
229
440
  }
230
441
 
@@ -288,7 +499,7 @@ export function fundingShortfall(quote, funding) {
288
499
  export function hostedConsentLines(offer) {
289
500
  const q = offer.quote;
290
501
  return [
291
- 'One persona plays the same build twice, once with Standard and once with Jev, on isolated hosted machines. These are AI playtests, not human feedback.',
502
+ 'One persona plays the same build twice, once with Geri and once with Freki, on isolated hosted machines. These are AI playtests, not human feedback.',
292
503
  'The game runs without network access. Shared capacity, daily limits and the quoted runtime bounds still apply; funding does not guarantee an immediate start.',
293
504
  `If the build fails, hosted compute is ${q.customerFailure === 'refund' ? 'refunded' : 'kept'}. Canceling after a confirmed start ${q.cancelAfterStart === 'refund' ? 'refunds' : 'keeps'} that run's compute charge. Unstarted work is refunded during settlement.`,
294
505
  'The build\'s validation hold is separate and is returned after safe cleanup. It does not reduce this price.',
@@ -5,6 +5,8 @@
5
5
  // words. Change both together. The admission owns the provider and payment
6
6
  // lifecycle; the job and its runs own gameplay, report capture and aggregation.
7
7
 
8
+ import { DISPLAY_NAMES } from '../run/controllers.js';
9
+
8
10
  const FAILED = new Set(['failed', 'budget_exceeded', 'interrupted', 'stalled', 'refused']);
9
11
  const CANCELED = new Set(['canceled']);
10
12
  const boundedReason = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 240);
@@ -70,10 +72,9 @@ export function hostedPlaytestStatus(admission, job = null, runs = [], now = Dat
70
72
  };
71
73
  }
72
74
 
73
- const MODE_NAMES = Object.freeze({ standard: 'Standard', jev: 'Jev' });
74
75
 
75
76
  /**
76
- * One row per hosted mode (Standard, Jev), from the job's persona runs. A mode
77
+ * One row per hosted mode (Geri, Freki), from the job's persona runs. A mode
77
78
  * whose run the server has not created yet reads as not started.
78
79
  * @param {Array<object>} runs
79
80
  * @param {Array<string>} [controllers]
@@ -85,7 +86,7 @@ export function modeOutcomes(runs = [], controllers = ['standard', 'jev']) {
85
86
  const report = run?.report || null;
86
87
  return {
87
88
  mode: controller,
88
- name: MODE_NAMES[controller] || controller,
89
+ name: DISPLAY_NAMES[controller] || 'Playtester',
89
90
  runId: run?.run_id || null,
90
91
  state: run?.state || 'not_started',
91
92
  reason: run?.state_reason ? boundedReason(run.state_reason) : null,
@@ -97,7 +98,7 @@ export function modeOutcomes(runs = [], controllers = ['standard', 'jev']) {
97
98
  });
98
99
  }
99
100
 
100
- /** "Standard: completed, 4 findings, video saved." */
101
+ /** "Geri: completed, 4 findings, video saved." */
101
102
  export function modeLine(row) {
102
103
  const parts = [row.state.replace(/_/g, ' ')];
103
104
  if (row.findings !== null) parts.push(`${row.findings} finding${row.findings === 1 ? '' : 's'}`);
@@ -106,3 +107,24 @@ export function modeLine(row) {
106
107
  if (row.reason) parts.push(row.reason);
107
108
  return `${row.name}: ${parts.join(', ')}.`;
108
109
  }
110
+
111
+ // The server's FIFO queue for hosted runs (game_tracker fix/hosted-capacity-and-reaper).
112
+ // ASSUMED field names, read in this one place until that branch's contract lands:
113
+ // `queue: { position: <whole number, 1 is next>, estimatedStartAt: <ISO time or null> }`
114
+ // on the admission acknowledgement and on GET /hosted/runs/:admissionId.
115
+ // Position 0, or an estimate already past, reads as starting now.
116
+ export function queueInfo(source) {
117
+ const q = source?.queue;
118
+ if (!q || typeof q !== 'object' || !Number.isSafeInteger(q.position) || q.position < 0) return null;
119
+ const at = typeof q.estimatedStartAt === 'string' ? Date.parse(q.estimatedStartAt) : NaN;
120
+ return { position: q.position, estimatedStartAt: Number.isFinite(at) ? new Date(at).toISOString() : null };
121
+ }
122
+
123
+ /** "Queued, position 2, expected to start in about 14 minutes." or "Queued, starting now." */
124
+ export function queueLine(queue, now = Date.now()) {
125
+ if (!queue) return null;
126
+ const minutes = queue.estimatedStartAt === null ? null : Math.ceil((Date.parse(queue.estimatedStartAt) - Number(now)) / 60000);
127
+ if (queue.position === 0 || minutes !== null && minutes <= 0) return 'Queued, starting now.';
128
+ const eta = minutes === null ? '' : `, expected to start in about ${minutes} minute${minutes === 1 ? '' : 's'}`;
129
+ return `Queued, position ${queue.position}${eta}.`;
130
+ }
@@ -1,4 +1,6 @@
1
1
  // Deterministic comparison of the reports already paid for. No new model call.
2
+ // The JSON keeps the wire ids; the markdown a person reads names the playtesters.
3
+ import { displayName } from './controllers.js';
2
4
  export function compareControllers(runs) {
3
5
  const planned = runs.filter(run => run.controller);
4
6
  const controllers = [...new Set(planned.map(run => run.controller))];
@@ -19,14 +21,14 @@ export function compareControllers(runs) {
19
21
  const findings = [...groups.values()].map(group => ({ ...group,
20
22
  match: new Set(group.occurrences.map(row => row.controller)).size > 1 ? 'reported_by_multiple_controllers' : 'reported_by_one_controller' }));
21
23
  return { schema_version: '1.0', controllers, status: rows.some(row => row.partial) ? 'inconclusive' : 'reports_complete',
22
- limits: ['Controllers use separate game sessions. Server saves and random state are not proven identical.', 'Matches use the same persona, category and exact normalized title. Agreement does not verify a bug; absence does not prove a pass.'], runs: rows, findings };
24
+ limits: ['Playtesters use separate game sessions. Server saves and random state are not proven identical.', 'Matches use the same persona, category and exact normalized title. Agreement does not verify a bug; absence does not prove a pass.'], runs: rows, findings };
23
25
  }
24
26
  export function comparisonMarkdown(comparison) {
25
27
  if (!comparison) return '';
26
28
  const safe = value => String(value ?? '').replace(/[\r\n|]/g, ' ');
27
- return '\n\n## Controller comparison\n\n' + comparison.limits.join(' ') + '\n\n' +
29
+ return '\n\n## Playtester comparison\n\n' + comparison.limits.join(' ') + '\n\n' +
28
30
  (comparison.status === 'inconclusive' ? 'At least one playthrough is missing or partial. This comparison is inconclusive.\n\n' : '') +
29
- '| Controller | Persona | Run | Report |\n| --- | --- | --- | --- |\n' +
30
- comparison.runs.map(row => `| ${safe(row.controller)} | ${safe(row.persona)} | ${safe(row.run_id)} | ${row.partial ? 'Incomplete' : 'Complete'} |`).join('\n') +
31
- '\n\n' + comparison.findings.map(group => `- ${safe(group.title)}: ${[...new Set(group.occurrences.map(row => row.controller))].join(', ')} (${group.occurrences.map(row => safe(row.run_id)).join(', ')}).`).join('\n');
31
+ '| Playtester | Persona | Run | Report |\n| --- | --- | --- | --- |\n' +
32
+ comparison.runs.map(row => `| ${safe(displayName(row.controller))} | ${safe(row.persona)} | ${safe(row.run_id)} | ${row.partial ? 'Incomplete' : 'Complete'} |`).join('\n') +
33
+ '\n\n' + comparison.findings.map(group => `- ${safe(group.title)}: ${[...new Set(group.occurrences.map(row => displayName(row.controller)))].join(', ')} (${group.occurrences.map(row => safe(row.run_id)).join(', ')}).`).join('\n');
32
34
  }
@@ -1,9 +1,21 @@
1
1
  export const CONTROLLERS = ['standard', 'jev', 'rune'];
2
+ // The playtesters by name. `geri` and `freki` are the documented flag values;
3
+ // the server's wire ids `standard` and `jev` stay accepted as hidden aliases
4
+ // so older scripts and saved jobs keep working. Every value is mapped to its
5
+ // wire id before it reaches the server or a journal.
6
+ export const DISPLAY_NAMES = Object.freeze({ standard: 'Geri', jev: 'Freki', rune: 'Experimental playtester' });
7
+ const ALIASES = Object.freeze({ geri: 'standard', freki: 'jev', standard: 'standard', jev: 'jev', rune: 'rune' });
8
+ /** The wire id for a flag value, or the value unchanged when it names nothing known. */
9
+ export function wireId(value) {
10
+ const key = String(value).trim().toLowerCase();
11
+ return Object.hasOwn(ALIASES, key) ? ALIASES[key] : String(value);
12
+ }
13
+ export function displayName(id) { return DISPLAY_NAMES[id] || 'Playtester'; }
2
14
  export function controllerPlan(options = {}) {
3
15
  if (options.compareWith && options.controller) throw new Error('Use --controller for one playthrough or --compare-with for a comparison.');
4
16
  if (!options.compareWith && !options.controller) return null;
5
- const plan = options.compareWith ? ['standard', ...String(options.compareWith).split(',')] : [options.controller];
6
- if (plan.length > 3 || plan.some(x => !CONTROLLERS.includes(x)) || new Set(plan).size !== plan.length) throw new Error('Choose standard, jev or rune once each. --compare-with jev runs standard and Jev separately.');
17
+ const plan = (options.compareWith ? ['standard', ...String(options.compareWith).split(',')] : [options.controller]).map(wireId);
18
+ if (plan.length > 3 || plan.some(x => !CONTROLLERS.includes(x)) || new Set(plan).size !== plan.length) throw new Error('Choose geri or freki once each. --compare-with freki plays Geri and Freki separately.');
7
19
  return plan;
8
20
  }
9
21
  export function quoteMatchesPlan(quote, plan, personas) {