ravensight-playtest 0.13.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +99 -4
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +7 -5
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +14 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/fix.js +1 -1
  10. package/src/commands/run.js +26 -4
  11. package/src/commands/setup.js +176 -0
  12. package/src/packs/index.js +37 -5
  13. package/src/packs/keys.json +11 -0
  14. package/src/packs/pack-signing-hashes.json +7 -0
  15. package/src/packs/pack-signing-vectors.json +119 -0
  16. package/src/packs/signature.js +186 -0
  17. package/src/run/anygame/gamenotes.js +74 -12
  18. package/src/run/anygame/index.js +97 -34
  19. package/src/run/anygame/language.js +100 -10
  20. package/src/run/anygame/memory.js +70 -13
  21. package/src/run/anygame/shared-hashes.json +7 -7
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +2 -0
  24. package/src/run/claimwords.js +43 -7
  25. package/src/run/drivers/godot-cursor.js +96 -0
  26. package/src/run/drivers/godot-observation.js +29 -5
  27. package/src/run/drivers/godot.js +60 -5
  28. package/src/run/drivers/web.js +124 -14
  29. package/src/run/eventclaims.js +102 -6
  30. package/src/run/events.js +64 -6
  31. package/src/run/gameMemory.js +14 -5
  32. package/src/run/honesty.js +49 -2
  33. package/src/run/judge.js +22 -10
  34. package/src/run/liveFeed.js +254 -0
  35. package/src/run/personaLoop.js +103 -25
  36. package/src/run/pixels.js +491 -2
  37. package/src/run/replay.js +11 -0
  38. package/src/run/sdkSession.js +279 -16
  39. package/src/run/synthetic.js +12 -8
  40. package/src/run/tools.js +2 -2
@@ -3,6 +3,7 @@ import { paths } from '../paths.js';
3
3
  import { readJson, sha256, stableStringify, writeJson } from '../fsutil.js';
4
4
  import { CliError } from '../errors.js';
5
5
  import { ApiError } from '../api/errors.js';
6
+ import { verifyPack, PackSignatureError } from './signature.js';
6
7
 
7
8
  /**
8
9
  * The content pack cache.
@@ -16,14 +17,30 @@ import { ApiError } from '../api/errors.js';
16
17
  * - a sha256 over the cached body, verified on read, so a truncated write or a
17
18
  * half finished download cannot be mistaken for content;
18
19
  * - an offline path, because spec 17 requires a run to work after one online
19
- * fetch, with the answer honestly labelled `stale`.
20
+ * fetch, with the answer honestly labelled `stale`;
21
+ * - a signature (./signature.js): every bundle, fresh or cached, is used only
22
+ * when it verifies against a pinned Ravensight key for exactly the request
23
+ * it answers. A bundle that does not verify is never cached and never
24
+ * replaced by a cached copy; a cached copy that no longer verifies (its key
25
+ * retired) is refetched online and refused offline.
20
26
  *
21
27
  * The cache is keyed by API host (two servers can serve different packs under
22
28
  * the same version) and by the request that produced it (game id and module
23
29
  * list), so a bundle fetched for one game is never served for another.
24
30
  */
25
31
 
26
- const CACHE_FORMAT = 1;
32
+ // 2: bundles carry their signature. A format 1 entry is ignored and refetched.
33
+ const CACHE_FORMAT = 2;
34
+
35
+ /** What a bundle's signature must be bound to: this request's game, job and modules. */
36
+ function expectFor({ gameId, modules, jobId }) {
37
+ return { typ: 'playtest-pack/bundle', game_id: gameId || null, job_id: jobId || null, modules: modules || null };
38
+ }
39
+
40
+ function verified(bundle, { apiUrl, gameId, modules, jobId, fresh }) {
41
+ verifyPack(bundle, { apiUrl, expect: expectFor({ gameId, modules, jobId }), fresh });
42
+ return bundle;
43
+ }
27
44
 
28
45
  function cacheFile({ apiUrl, gameId, modules }) {
29
46
  const key = paths.cacheKey({ gameId: gameId || null, modules: modules || null });
@@ -53,7 +70,8 @@ function resultFrom(entry, { fromCache, stale }) {
53
70
  * Read the cache without touching the network. Answers null when there is no
54
71
  * entry, and throws when there is one whose hash does not match its body: a
55
72
  * corrupt cache has to be visible, because silently refetching would hide a
56
- * disk that is losing writes.
73
+ * disk that is losing writes. Throws PackSignatureError when the entry does not
74
+ * verify for this request.
57
75
  *
58
76
  * @param {{apiUrl: string, gameId?: string, modules?: string[]}} options
59
77
  * @returns {Promise<PackResult|null>}
@@ -71,6 +89,7 @@ export async function cached(options) {
71
89
  { hint: 'Delete that file and run the command again to refetch it.' }
72
90
  );
73
91
  }
92
+ verified(entry.bundle, { ...options, fresh: false });
74
93
  return resultFrom(entry, { fromCache: true, stale: true });
75
94
  }
76
95
 
@@ -97,6 +116,7 @@ async function writeCache(options, { bundle, etag }) {
97
116
  */
98
117
  export async function sync({ api, gameId, modules }) {
99
118
  const answer = await api.packs.bundle({ gameId, modules });
119
+ verified(answer.body, { apiUrl: api.apiUrl, gameId, modules, fresh: true });
100
120
  const entry = await writeCache({ apiUrl: api.apiUrl, gameId, modules }, {
101
121
  bundle: answer.body,
102
122
  etag: answer.etag
@@ -129,7 +149,7 @@ export async function get({ api, gameId, modules, jobId = null, offline = false
129
149
  if (jobId) {
130
150
  const answer = await api.packs.bundle({ gameId, modules, jobId });
131
151
  return {
132
- bundle: answer.body,
152
+ bundle: verified(answer.body, { apiUrl: api.apiUrl, gameId, modules, jobId, fresh: true }),
133
153
  etag: answer.etag || null,
134
154
  fromCache: false,
135
155
  fetchedAt: new Date().toISOString(),
@@ -137,7 +157,15 @@ export async function get({ api, gameId, modules, jobId = null, offline = false
137
157
  };
138
158
  }
139
159
  const key = { apiUrl: api.apiUrl, gameId, modules };
140
- const existing = await cached(key);
160
+ let existing;
161
+ try {
162
+ existing = await cached(key);
163
+ } catch (error) {
164
+ // A cached copy that no longer verifies (signed by a key since retired) is
165
+ // not used. Online it is simply refetched; offline there is nothing else.
166
+ if (!(error instanceof PackSignatureError) || offline) throw error;
167
+ existing = null;
168
+ }
141
169
 
142
170
  if (offline) {
143
171
  if (!existing) {
@@ -159,9 +187,13 @@ export async function get({ api, gameId, modules, jobId = null, offline = false
159
187
  const entry = await writeCache(key, { bundle: existing.bundle, etag: existing.etag });
160
188
  return resultFrom(entry, { fromCache: true, stale: false });
161
189
  }
190
+ verified(answer.body, { ...key, fresh: true });
162
191
  const entry = await writeCache(key, { bundle: answer.body, etag: answer.etag });
163
192
  return resultFrom(entry, { fromCache: false, stale: false });
164
193
  } catch (error) {
194
+ // A pack that does not verify is an answer, and the wrong one: never a
195
+ // reason to fall back to the cache.
196
+ if (error instanceof PackSignatureError) throw error;
165
197
  // Any 5xx is the server being unavailable, and they are all the same thing
166
198
  // from here: a 500 from a crashed handler is no more a reason to refuse to
167
199
  // run than the 503 a load balancer sends. A 4xx is not: it is an answer
@@ -0,0 +1,11 @@
1
+ {
2
+ "format": "ravensight-pack-keys/1",
3
+ "keys": [
4
+ {
5
+ "kid": "rsp1-5d32b40286fe81a0",
6
+ "alg": "Ed25519",
7
+ "public_key": "PqTDGOcvIp9xbR5P3YJHw0Kb-4tOZu8xoxamUtUaQgU",
8
+ "not_after": null
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "comment": "Hashes of the pack signing files the platform and the local CLI both carry: sha256 of the file with LF line endings. keys is the pinned public key list (platform src/playtest/packSigning/publicKeys.json and the runner's infrastructure/hosted-playtest/direct-runner/lib/pack-keys.json; CLI src/packs/keys.json), vectors the shared test vectors (platform docs/playtest/pack-signing-vectors.json; CLI src/packs/pack-signing-vectors.json). The same file in both repos, and each repo checks its own copies against it: after changing either file, copy it to the other repo and update this table in BOTH. scripts/playtest-pack-signing-setup.js --yes does that for a new key.",
3
+ "files": {
4
+ "keys": "6a861c57d6457df6e511d709998019e556ccc44b5758e9f03954dba377e97a0b",
5
+ "vectors": "96e017e1bfdc0788e55d0f008d7876e1345a0e71d162d98e3a61445d06c05edc"
6
+ }
7
+ }
@@ -0,0 +1,119 @@
1
+ {
2
+ "$comment": "Shared vectors for playtest pack signing (docs/playtest/pack-signing.md). Copied byte for byte into the CLI (src/packs/pack-signing-vectors.json) and run by the platform, runner and CLI tests. `json` is parsed with JSON.parse and must canonicalize to `canonical`. `signature` is a fixed signed body whose private key was discarded after signing; only its public half is here.",
3
+ "canonical": [
4
+ {
5
+ "name": "keys sorted",
6
+ "json": "{\"b\":1,\"a\":2,\"c\":{\"z\":0,\"y\":[3,2,1]}}",
7
+ "canonical": "{\"a\":2,\"b\":1,\"c\":{\"y\":[3,2,1],\"z\":0}}"
8
+ },
9
+ {
10
+ "name": "whitespace removed",
11
+ "json": " { \"a\" : [ 1 , 2 ] ,\n\t\"b\" : null } ",
12
+ "canonical": "{\"a\":[1,2],\"b\":null}"
13
+ },
14
+ {
15
+ "name": "array order kept",
16
+ "json": "[\"b\",\"a\",{\"b\":true,\"a\":false}]",
17
+ "canonical": "[\"b\",\"a\",{\"a\":false,\"b\":true}]"
18
+ },
19
+ {
20
+ "name": "keys sorted by UTF-16 code unit, not locale",
21
+ "json": "{\"a\":1,\"B\":2,\"_\":3,\"é\":4,\"😀\":5,\"~\":6}",
22
+ "canonical": "{\"B\":2,\"_\":3,\"a\":1,\"é\":4,\"😀\":5,\"~\":6}"
23
+ },
24
+ {
25
+ "name": "numbers in shortest form",
26
+ "json": "[1.0,1e2,0.000001,1e-7,-0,1.5e+21,123456789012345680000]",
27
+ "canonical": "[1,100,0.000001,1e-7,0,1.5e+21,123456789012345680000]"
28
+ },
29
+ {
30
+ "name": "string escapes",
31
+ "json": "[\"line\\nbreak\",\"tab\\t\",\"quote\\\"\",\"slash\\/\",\"\\u0001\",\"\\u00e9\",\"\\u2028\"]",
32
+ "canonical": "[\"line\\nbreak\",\"tab\\t\",\"quote\\\"\",\"slash/\",\"\\u0001\",\"é\",\"
\"]"
33
+ },
34
+ {
35
+ "name": "lone surrogate escaped",
36
+ "json": "[\"\\ud800\"]",
37
+ "canonical": "[\"\\ud800\"]"
38
+ },
39
+ {
40
+ "name": "duplicate key keeps the last",
41
+ "json": "{\"a\":1,\"a\":2}",
42
+ "canonical": "{\"a\":2}"
43
+ },
44
+ {
45
+ "name": "empty containers",
46
+ "json": "{\"a\":{},\"b\":[],\"c\":\"\"}",
47
+ "canonical": "{\"a\":{},\"b\":[],\"c\":\"\"}"
48
+ },
49
+ {
50
+ "name": "markdown body unchanged",
51
+ "json": "{\"body\":\"---\\nslug: x\\n---\\n# Title\\r\\n\\n- one\\n\"}",
52
+ "canonical": "{\"body\":\"---\\nslug: x\\n---\\n# Title\\r\\n\\n- one\\n\"}"
53
+ }
54
+ ],
55
+ "signature": {
56
+ "key": {
57
+ "kid": "rsp1-a60bc18647669d45",
58
+ "alg": "Ed25519",
59
+ "public_key": "leFPAz8cB4OHABeEfAXxZTf27T8UjXlwZF3sabD0_zA",
60
+ "not_after": null
61
+ },
62
+ "expect": {
63
+ "typ": "playtest-pack/bundle",
64
+ "game_id": "g_vector",
65
+ "job_id": null,
66
+ "modules": [
67
+ "persona_playtest",
68
+ "game_profile"
69
+ ]
70
+ },
71
+ "body": {
72
+ "pack_version": "0.1.10",
73
+ "personas": [
74
+ {
75
+ "slug": "fresh-eyes",
76
+ "name": "Fresh Eyes",
77
+ "body": "# Fresh eyes\n\nPlays as élève 😀.\n",
78
+ "patience_actions": 40
79
+ }
80
+ ],
81
+ "routing": {
82
+ "steps": {
83
+ "persona_playtest.act": {
84
+ "effort": "low",
85
+ "cost_prior": null
86
+ }
87
+ }
88
+ },
89
+ "z": [
90
+ 1.5,
91
+ 0,
92
+ 1e+21
93
+ ],
94
+ "signature": {
95
+ "format": "ravensight-pack-sig/1",
96
+ "context": {
97
+ "typ": "playtest-pack/bundle",
98
+ "game_id": "g_vector",
99
+ "job_id": null,
100
+ "modules": [
101
+ "game_profile",
102
+ "persona_playtest"
103
+ ],
104
+ "aud": null,
105
+ "pack_version": "0.1.10",
106
+ "iat": 1795780800
107
+ },
108
+ "signatures": [
109
+ {
110
+ "kid": "rsp1-a60bc18647669d45",
111
+ "alg": "Ed25519",
112
+ "sig": "xfB--I4IRnjNZdlYrrJqweYeyL-a5Nv6xTfuZbXKTQZ3lTFlmi8NcQlARXn1e5oFAoNegpCaf0eJ_JrhP-8yBQ"
113
+ }
114
+ ]
115
+ }
116
+ },
117
+ "signed_bytes": "{\"body\":{\"pack_version\":\"0.1.10\",\"personas\":[{\"body\":\"# Fresh eyes\\n\\nPlays as élève 😀.\\n\",\"name\":\"Fresh Eyes\",\"patience_actions\":40,\"slug\":\"fresh-eyes\"}],\"routing\":{\"steps\":{\"persona_playtest.act\":{\"cost_prior\":null,\"effort\":\"low\"}}},\"z\":[1.5,0,1e+21]},\"context\":{\"aud\":null,\"game_id\":\"g_vector\",\"iat\":1795780800,\"job_id\":null,\"modules\":[\"game_profile\",\"persona_playtest\"],\"pack_version\":\"0.1.10\",\"typ\":\"playtest-pack/bundle\"}}"
118
+ }
119
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Pack signing, the CLI's verifier (Ravensight docs/playtest/pack-signing.md in the platform repo).
3
+ *
4
+ * The API signs every content pack answer with Ed25519 over the canonical JSON of { context, body }, the context
5
+ * binding the answer to its kind, game, job and module list, its pack version and its issue time. This checks it
6
+ * against the public keys in keys.json (kept equal to the platform's pinned list) before any of it is used, and
7
+ * there is no unsigned fallback. Ported line for line from the platform's src/playtest/packSigning/index.js; both
8
+ * run pack-signing-vectors.json.
9
+ */
10
+ import crypto from 'node:crypto';
11
+ import { readFileSync } from 'node:fs';
12
+ import { CliError } from '../errors.js';
13
+
14
+ const SIG_FORMAT = 'ravensight-pack-sig/1';
15
+ const KEYS_FORMAT = 'ravensight-pack-keys/1';
16
+ const ALG = 'Ed25519';
17
+ export const MAX_FUTURE_MS = 10 * 60 * 1000;
18
+ export const MAX_AGE_MS = 24 * 60 * 60 * 1000;
19
+
20
+ export class CanonicalJsonError extends Error {}
21
+
22
+ export function canonicalJson(value) {
23
+ if (value === null) return 'null';
24
+ switch (typeof value) {
25
+ case 'string': return JSON.stringify(value);
26
+ case 'boolean': return value ? 'true' : 'false';
27
+ case 'number':
28
+ if (!Number.isFinite(value)) throw new CanonicalJsonError('A number that is not finite is not JSON.');
29
+ return JSON.stringify(value);
30
+ case 'object': {
31
+ if (Array.isArray(value)) {
32
+ const parts = [];
33
+ for (let i = 0; i < value.length; i += 1) {
34
+ if (!(i in value)) throw new CanonicalJsonError('An array with a hole is not JSON.');
35
+ parts.push(canonicalJson(value[i]));
36
+ }
37
+ return `[${parts.join(',')}]`;
38
+ }
39
+ const proto = Object.getPrototypeOf(value);
40
+ if (proto !== Object.prototype && proto !== null) throw new CanonicalJsonError('Only plain objects are JSON.');
41
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
42
+ }
43
+ default: throw new CanonicalJsonError(`A ${typeof value} is not JSON.`);
44
+ }
45
+ }
46
+
47
+ export function kidFor(publicKeyBase64url) {
48
+ const raw = Buffer.from(String(publicKeyBase64url), 'base64url');
49
+ return `rsp1-${crypto.createHash('sha256').update(raw).digest('hex').slice(0, 16)}`;
50
+ }
51
+
52
+ export function loadPinnedKeys(list) {
53
+ if (!list || list.format !== KEYS_FORMAT || !Array.isArray(list.keys)) throw new Error(`A pinned key list must have format ${KEYS_FORMAT} and a keys array.`);
54
+ const seen = new Set();
55
+ return list.keys.map(entry => {
56
+ if (!entry || entry.alg !== ALG) throw new Error('A pinned key must be Ed25519.');
57
+ const raw = Buffer.from(String(entry.public_key || ''), 'base64url');
58
+ if (raw.length !== 32 || raw.toString('base64url') !== entry.public_key) throw new Error('A pinned key must be a 32 byte base64url public key.');
59
+ if (entry.kid !== kidFor(entry.public_key)) throw new Error(`Pinned key id ${entry.kid} does not match its key.`);
60
+ if (seen.has(entry.kid)) throw new Error(`Pinned key ${entry.kid} is listed twice.`);
61
+ seen.add(entry.kid);
62
+ let notAfter = null;
63
+ if (entry.not_after !== null) {
64
+ notAfter = typeof entry.not_after === 'string' ? Date.parse(entry.not_after) : NaN;
65
+ if (!Number.isFinite(notAfter)) throw new Error(`Pinned key ${entry.kid} has a not_after that is not a date.`);
66
+ }
67
+ return { kid: entry.kid, publicKey: crypto.createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: entry.public_key }, format: 'jwk' }), notAfter };
68
+ });
69
+ }
70
+
71
+ const TYPES = new Set(['playtest-pack/manifest', 'playtest-pack/personas', 'playtest-pack/skills', 'playtest-pack/schemas',
72
+ 'playtest-pack/routing', 'playtest-pack/bundle', 'playtest-hosted/input']);
73
+ const normalModules = m => (Array.isArray(m) && m.length > 0 ? [...m].map(String).sort() : null);
74
+ const refuse = reason => ({ ok: false, reason });
75
+
76
+ function unsignedPart(body) { const rest = { ...body }; delete rest.signature; return rest; }
77
+
78
+ function validContext(c) {
79
+ return c && typeof c === 'object' && TYPES.has(c.typ) && (c.game_id === null || typeof c.game_id === 'string')
80
+ && (c.job_id === null || typeof c.job_id === 'string')
81
+ && (c.modules === null || (Array.isArray(c.modules) && c.modules.every(m => typeof m === 'string')))
82
+ && (c.aud === null || typeof c.aud === 'string') && (c.pack_version === null || typeof c.pack_version === 'string') && Number.isSafeInteger(c.iat);
83
+ }
84
+
85
+ /** Same rules and reasons as the platform's verifyBody. */
86
+ export function verifyBody(body, { trusted, expect, fresh = false, now = Date.now() }) {
87
+ if (!expect || !TYPES.has(expect.typ)) throw new Error('verifyBody needs the expected pack kind.');
88
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return refuse('malformed');
89
+ const envelope = body.signature;
90
+ if (envelope === undefined || envelope === null) return refuse('unsigned');
91
+ if (typeof envelope !== 'object' || envelope.format !== SIG_FORMAT || !validContext(envelope.context)
92
+ || !Array.isArray(envelope.signatures) || envelope.signatures.length === 0) return refuse('malformed');
93
+ for (const e of envelope.signatures) if (!e || typeof e.kid !== 'string' || e.alg !== ALG || typeof e.sig !== 'string') return refuse('malformed');
94
+ let bytes;
95
+ try { bytes = Buffer.from(canonicalJson({ context: envelope.context, body: unsignedPart(body) }), 'utf8'); } catch { return refuse('malformed'); }
96
+ const byKid = new Map(trusted.map(k => [k.kid, k]));
97
+ let accepted = null, retired = false;
98
+ for (const e of envelope.signatures) {
99
+ const key = byKid.get(e.kid);
100
+ if (!key) continue;
101
+ const sig = Buffer.from(e.sig, 'base64url');
102
+ if (sig.length !== 64 || !crypto.verify(null, bytes, key.publicKey, sig)) return refuse('bad_signature');
103
+ if (key.notAfter !== null && now >= key.notAfter) { retired = true; continue; }
104
+ accepted ??= key.kid;
105
+ }
106
+ if (!accepted) return refuse(retired ? 'retired_key' : 'unknown_key');
107
+ const c = envelope.context;
108
+ if (c.typ !== expect.typ || c.game_id !== (expect.game_id || null) || c.job_id !== (expect.job_id || null)
109
+ || canonicalJson(c.modules) !== canonicalJson(normalModules(expect.modules)) || c.aud !== (expect.aud || null)) return refuse('wrong_context');
110
+ if (c.pack_version !== (typeof body.pack_version === 'string' ? body.pack_version : null)) return refuse('wrong_context');
111
+ if (c.iat * 1000 > now + MAX_FUTURE_MS) return refuse('stale');
112
+ if (fresh && now - c.iat * 1000 > MAX_AGE_MS) return refuse('stale');
113
+ return { ok: true, kid: accepted, context: c };
114
+ }
115
+
116
+ const KEYS_FILE = new URL('./keys.json', import.meta.url);
117
+ const TRUST_ENV = 'RAVENSIGHT_PACK_TRUSTED_KEYS';
118
+ const warnedKids = new Set();
119
+
120
+ /**
121
+ * The keys this CLI trusts: the pinned list shipped in the package, plus any in RAVENSIGHT_PACK_TRUSTED_KEYS (the
122
+ * same list shape, JSON) for a local development server. An env key is marked so the CLI can say it was used.
123
+ */
124
+ export function trustedKeys(env = process.env) {
125
+ const pinned = loadPinnedKeys(JSON.parse(readFileSync(KEYS_FILE, 'utf8')));
126
+ const extra = env[TRUST_ENV];
127
+ if (!extra) return pinned;
128
+ let list;
129
+ try {
130
+ list = loadPinnedKeys(JSON.parse(extra));
131
+ } catch (error) {
132
+ throw new CliError(`${TRUST_ENV} is not a valid key list: ${error.message}`, 3, { hint: `Unset ${TRUST_ENV}, or set it to {"format":"ravensight-pack-keys/1","keys":[...]}.` });
133
+ }
134
+ const have = new Set(pinned.map(k => k.kid));
135
+ return [...pinned, ...list.filter(k => !have.has(k.kid)).map(k => ({ ...k, fromEnv: true }))];
136
+ }
137
+
138
+ const HINTS = {
139
+ unsigned: 'The server did not sign it. Check the API address you are using; an older server needs updating before this CLI can use it.',
140
+ malformed: 'Update the CLI with npm install -g ravensight-playtest@latest.',
141
+ unknown_key: 'Update the CLI with npm install -g ravensight-playtest@latest. If you are not using the Ravensight API, check the API address.',
142
+ retired_key: 'Run the command again online to fetch a freshly signed pack, or update the CLI.',
143
+ bad_signature: 'Something between you and the server changed it. Check for a proxy rewriting traffic, and try again.',
144
+ wrong_context: 'Something between you and the server answered with a pack made for another request. Try again; if it persists, check for a proxy.',
145
+ stale: 'Check that this computer\'s clock is right, then try again.'
146
+ };
147
+
148
+ /** Thrown when a pack does not verify; never treated as "offline", so it never falls back to a cached copy. */
149
+ export class PackSignatureError extends CliError {
150
+ constructor(host, result) {
151
+ super(`The content pack from ${host} is not signed by Ravensight (${MESSAGES[result.reason] || result.reason}), so it was not used.`, 1, { hint: HINTS[result.reason] });
152
+ this.name = 'PackSignatureError';
153
+ this.reason = result.reason;
154
+ }
155
+ }
156
+
157
+ const MESSAGES = {
158
+ malformed: 'its signature is not in a form this version understands',
159
+ unsigned: 'it is not signed',
160
+ unknown_key: 'it is signed with a key this version does not know',
161
+ bad_signature: 'its signature does not match its content',
162
+ retired_key: 'it is signed only with a key that has been retired',
163
+ wrong_context: 'it was signed for a different request',
164
+ stale: 'it was signed too long ago to be a fresh answer, or this computer\'s clock is wrong'
165
+ };
166
+
167
+ function hostOf(apiUrl) {
168
+ try { return new URL(apiUrl).host; } catch { return String(apiUrl); }
169
+ }
170
+
171
+ /**
172
+ * Verify a pack answer or throw PackSignatureError. `fresh` for a body that just came over the network.
173
+ * @param {Object} body
174
+ * @param {{apiUrl: string, expect: {typ: string, game_id?: string|null, job_id?: string|null, modules?: string[]|null}, fresh?: boolean, now?: number, env?: Object, warn?: (line: string) => void}} options
175
+ */
176
+ export function verifyPack(body, { apiUrl, expect, fresh = false, now = Date.now(), env = process.env, warn = line => process.stderr.write(`${line}\n`) }) {
177
+ const trusted = trustedKeys(env);
178
+ const result = verifyBody(body, { trusted, expect, fresh, now });
179
+ if (!result.ok) throw new PackSignatureError(hostOf(apiUrl), result);
180
+ const key = trusted.find(k => k.kid === result.kid);
181
+ if (key && key.fromEnv && !warnedKids.has(key.kid)) {
182
+ warnedKids.add(key.kid);
183
+ warn(`Warning: the content pack was verified with ${key.kid} from ${TRUST_ENV}, not a key shipped with this CLI.`);
184
+ }
185
+ return result;
186
+ }
@@ -7,7 +7,9 @@
7
7
  // and reads notes by exactly these rules, into the same records.
8
8
  const noDashes = s => String(s ?? '').replace(/[\u2013\u2014]/g, ',');
9
9
 
10
- export const MEMORY_SCHEMA = 'ravensight.game-memory.v1';
10
+ // v2: every note of the playtester's own that states a number has been held to the run's record (`holdToRecord`). The server
11
+ // keeps a v1 block's numbered playtester notes out of what it sends, since nothing held them.
12
+ export const MEMORY_SCHEMA = 'ravensight.game-memory.v2';
11
13
  export const NOTE_KINDS = Object.freeze(['about', 'start', 'control', 'progress', 'stuck', 'message', 'rule', 'as_designed']);
12
14
  export const NOTE_BASES = Object.freeze(['measured', 'game', 'playtester', 'check']);
13
15
  // At most this many notes one run hands on, and characters a note.
@@ -101,20 +103,78 @@ export function controlNotes(measured) {
101
103
  return out.filter(Boolean);
102
104
  }
103
105
 
104
- /** How far the run got: the places it reached, the goals it marked done, and its wins, levels and losses. */
105
- export function progressNote(combined, memory) {
106
+ /**
107
+ * How far the run got: the places it reached, the goals it marked done, and its wins, levels and losses. The counts come only
108
+ * from `counts`, what the run's record bears out (lib/ground.mjs groundRecord on a hosted run: the frames, the game's own signal),
109
+ * never from the playtester's notebook (`memory.events`), whose readings a later run would otherwise be told as fact ("5 losses" for
110
+ * a run whose frames show three). With no `counts` the note names no count.
111
+ */
112
+ export function progressNote(combined, memory, counts = null) {
106
113
  const places = (Array.isArray(memory?.places) ? memory.places : []).slice().sort((a, b) => (a.firstStep ?? 0) - (b.firstStep ?? 0)).map(p => cleanText(p.label, 30)).filter(Boolean);
107
114
  const done = (Array.isArray(combined?.goals) ? combined.goals : []).filter(g => g?.done && typeof g.text === 'string' && !RUNNER_GOAL.test(g.text.trim())).map(g => quote(cleanText(g.text, 60)));
108
- const e = memory?.events || {};
109
- const counts = [['level finished', 'levels finished', e.levelsFinished], ['win', 'wins', e.wins], ['loss', 'losses', e.losses], ['ending', 'endings', e.endings]]
115
+ const e = counts && typeof counts === 'object' ? counts : {};
116
+ const tally = [['level finished', 'levels finished', e.levelsFinished], ['win', 'wins', e.wins], ['loss', 'losses', e.losses], ['ending', 'endings', e.endings]]
110
117
  .filter(([, , n]) => Number.isSafeInteger(n) && n > 0).map(([one, many, n]) => `${n} ${n === 1 ? one : many}`);
111
118
  const parts = [];
112
119
  if (places.length) parts.push(`reached ${places.slice(0, 4).map(p => quote(p)).join(', ')}${places.length > 4 ? ` and ${places.length - 4} more screens` : ''}`);
113
120
  if (done.length) parts.push(`goals done: ${done.slice(0, 2).join('; ')}`);
114
- if (counts.length) parts.push(counts.join(', '));
121
+ if (tally.length) parts.push(`${tally.join(', ')} by the record`);
115
122
  return parts.length ? note('progress', `The last run ${parts.join('; ')}`, 'playtester', { subject: 'progress' }) : null;
116
123
  }
117
124
 
125
+ // A number a note states: digits standing on their own ("5 losses", "score 120", "2.5"), never part of a name ("2D", "F1", "m12").
126
+ // What a note quotes ("Room 1 of 3") is the screen's own name for a place or a goal, copied, and is not a count the note states.
127
+ const NUMBER = /(?<![\p{L}\p{N}_.])\d+(?:\.\d+)?(?![\p{L}\p{N}_])/gu;
128
+ const QUOTED = /"[^"]*"/g;
129
+ /** The numbers a note's text states, outside what it quotes. */
130
+ export const noteNumbers = t => [...String(t ?? '').replace(QUOTED, ' ').matchAll(NUMBER)].map(m => Number(m[0])).filter(Number.isFinite);
131
+ // A word as the game's own events spell it ("playerLives" is "player", "lives"), in any script, with a plain plural off.
132
+ const tokens = s => String(s ?? '').replace(/(\p{Ll})(\p{Lu})/gu, '$1 $2').toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w.length >= 2);
133
+ const stem = w => (w.length > 3 && w.endsWith('s') ? w.slice(0, -1) : w);
134
+
135
+ /**
136
+ * What a run's record holds that a note's number may rest on: `{ any, keyed }`. `any` is every number the record itself carries:
137
+ * the counts it bears out (`counts`), and each number in a text the game showed or said (`texts`: the game's own words, what was read
138
+ * off its screen). `keyed` is each number the game's own analytics events sent (`events`, `{ name, props }`), by the words of the
139
+ * event and the key it came in ("lives" for `{ name: 'player_hit', props: { lives: 2 } }`), so a note's 2 rests on it only when the
140
+ * note names lives in the game's own word for them. Nothing here reads English: the words are the game's own.
141
+ */
142
+ export function recordNumbers({ counts = null, texts = [], events = [] } = {}) {
143
+ const any = new Set();
144
+ for (const n of Object.values(counts && typeof counts === 'object' ? counts : {})) if (Number.isFinite(n)) any.add(n);
145
+ for (const t of Array.isArray(texts) ? texts : []) for (const n of noteNumbers(String(t ?? '').replace(/"/g, ' '))) any.add(n);
146
+ const keyed = new Map();
147
+ const put = (word, n) => { const w = stem(word); if (!keyed.has(w)) keyed.set(w, new Set()); keyed.get(w).add(n); };
148
+ for (const e of Array.isArray(events) ? events : []) {
149
+ const props = e?.props && typeof e.props === 'object' ? e.props : {};
150
+ for (const [k, v] of Object.entries(props)) {
151
+ if (typeof v !== 'number' || !Number.isFinite(v)) continue;
152
+ for (const w of [...tokens(k), ...tokens(e?.name)]) put(w, v);
153
+ }
154
+ }
155
+ return { any, keyed };
156
+ }
157
+
158
+ /**
159
+ * The rule that keeps the playtester's word from reaching a later run as fact: a note of the playtester's own (basis `playtester`)
160
+ * that states a number is kept only when the run's record holds that number (`record`, from `recordNumbers`): a count the record
161
+ * bears out, a number the game itself showed or said, or a value the game's own events sent under a word the note uses. One number
162
+ * the record does not hold, and the note is set aside. Without a record nothing can hold a number, so every such note is set aside.
163
+ * A note the runner measured, the game said, or a check settled stands as it is. Answers `{ kept, unverified }`.
164
+ */
165
+ export function holdToRecord(notes, record = null) {
166
+ const kept = [], unverified = [];
167
+ for (const n of Array.isArray(notes) ? notes : []) {
168
+ if (!n) continue;
169
+ const nums = n.basis === 'playtester' ? noteNumbers(n.text) : [];
170
+ const words = nums.length ? new Set(tokens(n.text).map(stem)) : null;
171
+ const held = x => Boolean(record) && (record.any.has(x) || [...words].some(w => record.keyed.get(w)?.has(x)));
172
+ if (nums.every(held)) kept.push(n);
173
+ else unverified.push({ ...n, unheld: nums.filter(x => !held(x)) });
174
+ }
175
+ return { kept, unverified };
176
+ }
177
+
118
178
  // A step number means nothing to the next run: "From step 6 onward I could not ..." is kept as "I could not ...".
119
179
  export const withoutSteps = t => cleanText(String(t).replace(/\(\s*steps?\s+\d+[^)]*\)/gi, '').replace(/\b(?:from|at|on|by|after|until|around|in|since|near)\s+steps?\s+\d+(?:\s*(?:to|and|-)\s*\d+)?(?:\s+onwards?)?,?\s*/gi, '').replace(/^steps?\s+\d+(?:\s*(?:to|and|-)\s*\d+)?(?:\s+onwards?)?,?\s*/i, '').replace(/^\W+/, ''));
120
180
 
@@ -168,20 +228,22 @@ export function designedNotes(turnedAway, same) {
168
228
  }
169
229
 
170
230
  /**
171
- * The notes one run hands on, from every candidate in order: notes of one kind that say the same thing are kept once (`same`
172
- * decides for the playtester's own words); at most PER_KIND of a kind and MAX_RUN_NOTES in all. Answers `{ schema, notes }`.
231
+ * The notes one run hands on, from every candidate in order: those of the playtester's own that state a number the run's record does
232
+ * not hold are set aside first (`holdToRecord`, against `record`), then notes of one kind that say the same thing are kept once
233
+ * (`same` decides for the playtester's own words); at most PER_KIND of a kind and MAX_RUN_NOTES in all. Answers
234
+ * `{ schema, notes, unverified }`: `unverified` counts what was set aside, and none of it is handed on.
173
235
  */
174
- export function collectNotes(all, same) {
236
+ export function collectNotes(all, same, record = null) {
237
+ const { kept: held, unverified } = holdToRecord(all.filter(n => n && NOTE_KINDS.includes(n.kind)), record);
175
238
  const kept = [], count = {};
176
- for (const n of all) {
177
- if (!n || !NOTE_KINDS.includes(n.kind)) continue;
239
+ for (const n of held) {
178
240
  if ((count[n.kind] || 0) >= PER_KIND[n.kind]) continue;
179
241
  if (kept.some(k => k.kind === n.kind && (k.subject && k.subject === n.subject || k.text.toLowerCase() === n.text.toLowerCase() || (n.basis === 'playtester' && same(k.text, n.text))))) continue;
180
242
  count[n.kind] = (count[n.kind] || 0) + 1;
181
243
  kept.push(n);
182
244
  if (kept.length >= MAX_RUN_NOTES) break;
183
245
  }
184
- return { schema: MEMORY_SCHEMA, notes: kept };
246
+ return { schema: MEMORY_SCHEMA, notes: kept, unverified: unverified.length };
185
247
  }
186
248
 
187
249
  /**