@spellkave/world-author 0.0.0-bootstrap

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 (57) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +62 -0
  3. package/package.json +57 -0
  4. package/src/applyset-diff-types.ts +158 -0
  5. package/src/applyset.ts +82 -0
  6. package/src/authoring-harness.ts +487 -0
  7. package/src/browser.ts +114 -0
  8. package/src/compose.ts +699 -0
  9. package/src/corpus.generated.ts +279 -0
  10. package/src/corpus.ts +1180 -0
  11. package/src/damage.ts +75 -0
  12. package/src/diagnostics.ts +59 -0
  13. package/src/diff-manifest-core.ts +393 -0
  14. package/src/diff-manifest.ts +5 -0
  15. package/src/docs-index.ts +105 -0
  16. package/src/dsl.ts +10 -0
  17. package/src/evaluate.ts +100 -0
  18. package/src/explain-core.ts +219 -0
  19. package/src/explain.ts +43 -0
  20. package/src/filter-manifest-core.ts +122 -0
  21. package/src/filter-manifest.ts +41 -0
  22. package/src/grants-core.ts +38 -0
  23. package/src/grants.ts +10 -0
  24. package/src/included-manifest-metadata-core.ts +63 -0
  25. package/src/included-manifest-metadata.ts +21 -0
  26. package/src/index.ts +30 -0
  27. package/src/inspect.ts +35 -0
  28. package/src/inspection.ts +239 -0
  29. package/src/lint.ts +540 -0
  30. package/src/manifest-text.ts +21 -0
  31. package/src/manifest.ts +403 -0
  32. package/src/metadata.ts +137 -0
  33. package/src/npc-dm-authority-projection.ts +95 -0
  34. package/src/npc-dm-documents.ts +339 -0
  35. package/src/npc-dm-presentation.ts +17 -0
  36. package/src/npc-dm-srd.ts +51 -0
  37. package/src/npc-dm-types.ts +723 -0
  38. package/src/npc-kinds.ts +404 -0
  39. package/src/npc-quests.ts +319 -0
  40. package/src/observation-tokens.browser.ts +31 -0
  41. package/src/observation-tokens.ts +27 -0
  42. package/src/owner-instance-read.ts +765 -0
  43. package/src/patch.ts +47 -0
  44. package/src/ref-tags.ts +149 -0
  45. package/src/reference.ts +48 -0
  46. package/src/row-identity.ts +105 -0
  47. package/src/row-kinds-data.ts +35 -0
  48. package/src/row-kinds.ts +93 -0
  49. package/src/scenario-guidance.ts +180 -0
  50. package/src/scoped-instance-read.ts +187 -0
  51. package/src/service-only-audience.ts +14 -0
  52. package/src/session-predicates.ts +6 -0
  53. package/src/spell.ts +119 -0
  54. package/src/tag-prefix-families.ts +143 -0
  55. package/src/tooling.browser.ts +397 -0
  56. package/src/tooling.ts +38 -0
  57. package/src/validate.ts +255 -0
@@ -0,0 +1,404 @@
1
+ // embedded-manifest: {"category":"production_schema_constructor","rationale":"The local ordinary-kind compiler publishes bounded client-readable configuration through existing metadata namespaces and narrow read grants.","signatures":["schema_object","schema_shape"]}
2
+ /** Ordinary-kind metadata compiler. No world connection, engine callbacks,
3
+ * bindings, drive authority, scripts or hosted publication side effects. */
4
+ import { serviceOnlyAudienceTag } from "./service-only-audience";
5
+
6
+ export { SERVICE_ONLY_AUDIENCE_TAG } from "./service-only-audience";
7
+
8
+ export type NpcKindJson =
9
+ | null
10
+ | boolean
11
+ | number
12
+ | string
13
+ | NpcKindJson[]
14
+ | { [key: string]: NpcKindJson };
15
+ type Row = Record<string, NpcKindJson>;
16
+ export type OrdinaryNpcKind = "menu-talker" | "role-combatant" | "companion";
17
+ export interface NpcKindActor {
18
+ readonly actor_key: string;
19
+ /** An unplaced late-cast blueprint receives only metadata-read capabilities. */
20
+ readonly blueprint_id?: string;
21
+ }
22
+ export interface NpcKindGroup {
23
+ readonly key: string;
24
+ readonly npc_kind: OrdinaryNpcKind;
25
+ readonly actors: readonly NpcKindActor[];
26
+ readonly config: Row;
27
+ }
28
+ export interface NpcKindSource {
29
+ readonly bundle_id: string;
30
+ readonly namespace_prefix: string;
31
+ readonly catalog: Row;
32
+ readonly groups: readonly NpcKindGroup[];
33
+ }
34
+ export interface NpcKindMount {
35
+ actor_key: string;
36
+ npc_kind: OrdinaryNpcKind;
37
+ schema_version: 1;
38
+ document_namespace: string;
39
+ catalog_namespace: string;
40
+ catalog_content_hash: string;
41
+ }
42
+ export interface NpcKindArtifact {
43
+ schema_version: 1;
44
+ source_content_hash: string;
45
+ /** The fixed-point source every row below is derived from: integer-only
46
+ * wire values, the form `source_content_hash` is taken over. A consumer
47
+ * that may not run the authoring code re-derives the artifact from it
48
+ * (`parseNpcKindArtifact`). */
49
+ source: NpcKindSource;
50
+ manifest: Row;
51
+ mounts: NpcKindMount[];
52
+ }
53
+ /** Add only the compiler-owned metadata/read-grant tables to a transient
54
+ * local world. Existing loader validation still owns all row references. */
55
+ export function composeNpcKindWorld(
56
+ world: Record<string, unknown>,
57
+ artifact: NpcKindArtifact,
58
+ ): Record<string, unknown> {
59
+ const result = { ...world };
60
+ for (const [kind, rows] of Object.entries(artifact.manifest)) {
61
+ if (kind === "schema_version") continue;
62
+ if (
63
+ ![
64
+ "capability_definitions",
65
+ "capability_definition_tag",
66
+ "role_definitions",
67
+ "role_bindings",
68
+ "actor_capabilities",
69
+ "entity_definition_initial_capability",
70
+ "metadata_namespaces",
71
+ "metadata_attachments",
72
+ ].includes(kind) ||
73
+ !Array.isArray(rows) ||
74
+ (result[kind] !== undefined && !Array.isArray(result[kind]))
75
+ )
76
+ throw new Error("Invalid NPC kind composition table");
77
+ result[kind] = [...((result[kind] as unknown[] | undefined) ?? []), ...rows];
78
+ }
79
+ return result;
80
+ }
81
+ function canonical(value: unknown): string {
82
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
83
+ if (value !== null && typeof value === "object")
84
+ return `{${Object.entries(value)
85
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
86
+ .map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`)
87
+ .join(",")}}`;
88
+ const encoded = JSON.stringify(value);
89
+ if (
90
+ encoded === undefined ||
91
+ (typeof value === "number" && (!Number.isSafeInteger(value) || value < 0))
92
+ )
93
+ throw new Error("NPC kind documents require unsigned JSON-safe integer wire values");
94
+ return encoded;
95
+ }
96
+ async function hash(value: unknown): Promise<string> {
97
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
98
+ return `sha256:${Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
99
+ }
100
+ function bounded(payload: unknown): string {
101
+ const encoded = canonical(payload);
102
+ if (new TextEncoder().encode(encoded).byteLength > 256 * 1024)
103
+ throw new Error("NPC kind document exceeds the metadata admission bound");
104
+ return encoded;
105
+ }
106
+ const PARAM_UNITS = {
107
+ minRangeCells: "minRangeCellsMilli",
108
+ fleeHpFraction: "fleeHpPermille",
109
+ holdUntilCells: "holdUntilCellsMilli",
110
+ healAllyBelowFraction: "healAllyBelowPermille",
111
+ };
112
+ const VOCABULARY_UNITS = {
113
+ defaultMeleeReach: "defaultMeleeReachCellsMilli",
114
+ flankBonus: "flankBonusPermille",
115
+ adjacencyCells: "adjacencyCellsMilli",
116
+ };
117
+ function scaled(value: NpcKindJson): NpcKindJson {
118
+ if (value === null) return null;
119
+ if (
120
+ typeof value !== "number" ||
121
+ !Number.isFinite(value) ||
122
+ value < 0 ||
123
+ !Number.isSafeInteger(value * 1000) ||
124
+ (value * 1000) / 1000 !== value
125
+ )
126
+ throw new Error("Ordinary NPC numeric parameter is not exact at milli/permille scale");
127
+ return value * 1000;
128
+ }
129
+ function fixedFields(
130
+ value: NpcKindJson | undefined,
131
+ units: Record<string, string>,
132
+ ): NpcKindJson | undefined {
133
+ if (value === undefined || value === null) return value;
134
+ if (typeof value !== "object" || Array.isArray(value))
135
+ throw new Error("Ordinary NPC parameter object required");
136
+ const result = { ...value };
137
+ for (const [source, target] of Object.entries(units))
138
+ if (Object.hasOwn(value, source)) {
139
+ if (Object.hasOwn(value, target)) throw new Error("Duplicate ordinary NPC parameter unit");
140
+ result[target] = scaled(value[source]!);
141
+ delete result[source];
142
+ }
143
+ return result;
144
+ }
145
+ function fixedActions(value: NpcKindJson | undefined): NpcKindJson | undefined {
146
+ if (value === undefined || value === null) return value;
147
+ if (typeof value !== "object" || Array.isArray(value))
148
+ throw new Error("Ordinary NPC action object required");
149
+ const result = { ...value };
150
+ if (Object.hasOwn(value, "attackRangeCells")) {
151
+ const ranges = value.attackRangeCells;
152
+ if (
153
+ ranges === null ||
154
+ typeof ranges !== "object" ||
155
+ Array.isArray(ranges) ||
156
+ Object.hasOwn(value, "attackRangeCellsMilli")
157
+ )
158
+ throw new Error("Ordinary NPC action range object required");
159
+ result.attackRangeCellsMilli = Object.fromEntries(
160
+ Object.entries(ranges).map(([id, range]) => [id, scaled(range)]),
161
+ );
162
+ delete result.attackRangeCells;
163
+ }
164
+ return result;
165
+ }
166
+ function fixedCombat(config: Row): Row {
167
+ const result = { ...config };
168
+ if (Object.hasOwn(result, "params")) result.params = fixedFields(result.params, PARAM_UNITS)!;
169
+ if (Object.hasOwn(result, "actions")) result.actions = fixedActions(result.actions)!;
170
+ return result;
171
+ }
172
+ /** UAC16744: ordinary envelopes use named fixed-point integers. The shared
173
+ * quest/DM hash continues to admit only unsigned JSON-safe integers. */
174
+ function fixedSource(source: NpcKindSource): NpcKindSource {
175
+ const catalog = { ...source.catalog };
176
+ if (catalog.role_vocabulary !== undefined)
177
+ catalog.role_vocabulary = fixedFields(catalog.role_vocabulary, VOCABULARY_UNITS)!;
178
+ if (catalog.roles !== undefined) {
179
+ if (catalog.roles === null || typeof catalog.roles !== "object" || Array.isArray(catalog.roles))
180
+ throw new Error("Ordinary NPC role map required");
181
+ catalog.roles = Object.fromEntries(
182
+ Object.entries(catalog.roles).map(([role, params]) => [
183
+ role,
184
+ fixedFields(params, PARAM_UNITS)!,
185
+ ]),
186
+ );
187
+ }
188
+ if (
189
+ catalog.combat !== undefined &&
190
+ catalog.combat !== null &&
191
+ typeof catalog.combat === "object" &&
192
+ !Array.isArray(catalog.combat)
193
+ )
194
+ catalog.combat = fixedCombat(catalog.combat);
195
+ return {
196
+ ...source,
197
+ catalog,
198
+ groups: source.groups.map((group) => {
199
+ if (group.npc_kind === "role-combatant")
200
+ return { ...group, config: fixedCombat(group.config) };
201
+ if (
202
+ group.npc_kind === "companion" &&
203
+ group.config.combat !== null &&
204
+ typeof group.config.combat === "object" &&
205
+ !Array.isArray(group.config.combat)
206
+ )
207
+ return { ...group, config: { ...group.config, combat: fixedCombat(group.config.combat) } };
208
+ return group;
209
+ }),
210
+ };
211
+ }
212
+ /** One shared role document covers an authored encounter cast. Other groups
213
+ * have an entity-targeted document unless a late blueprint requires a bundle
214
+ * attachment. Every document lists its admitted actor keys explicitly. */
215
+ export async function compileNpcKindDocuments(source: NpcKindSource): Promise<NpcKindArtifact> {
216
+ source = fixedSource(source);
217
+ if (
218
+ !source.bundle_id ||
219
+ !source.namespace_prefix ||
220
+ /\s/.test(source.namespace_prefix) ||
221
+ source.groups.length < 1 ||
222
+ source.groups.length > 128
223
+ )
224
+ throw new Error("Invalid NPC kind source bounds");
225
+ const keys = new Set<string>();
226
+ const actors = new Set<string>();
227
+ for (const group of source.groups) {
228
+ if (
229
+ !/^[a-z0-9-]+$/.test(group.key) ||
230
+ keys.has(group.key) ||
231
+ !["menu-talker", "role-combatant", "companion"].includes(group.npc_kind) ||
232
+ group.actors.length < 1 ||
233
+ group.actors.length > 128 ||
234
+ (group.actors.length > 1 && group.npc_kind !== "role-combatant")
235
+ )
236
+ throw new Error("Invalid or duplicate NPC kind group");
237
+ keys.add(group.key);
238
+ for (const actor of group.actors) {
239
+ if (!actor.actor_key || actors.has(actor.actor_key) || actor.blueprint_id === "")
240
+ throw new Error("Invalid or duplicate NPC kind actor");
241
+ actors.add(actor.actor_key);
242
+ }
243
+ }
244
+ const digest = await hash(source);
245
+ const publication = `source:${digest}`;
246
+ const prefix = source.namespace_prefix;
247
+ const catalogNamespace = `${prefix}/catalog`;
248
+ const catalogCapability = `${prefix}/read-catalog`;
249
+ const catalogContent = { ...source.catalog, schema_version: 1 };
250
+ const catalogHash = await hash(catalogContent);
251
+ const bundle = source.bundle_id;
252
+ const rows: Record<string, Row[]> = {
253
+ capability_definitions: [],
254
+ capability_definition_tag: [],
255
+ role_definitions: [],
256
+ role_bindings: [],
257
+ actor_capabilities: [],
258
+ entity_definition_initial_capability: [],
259
+ metadata_namespaces: [],
260
+ metadata_attachments: [],
261
+ };
262
+ const capability = (id: string) => {
263
+ rows.capability_definitions!.push({
264
+ bundle_id: bundle,
265
+ capability_id: id,
266
+ actor_kind: "entity",
267
+ display_name: "Read NPC configuration",
268
+ description: "Read the declared ordinary-kind metadata audience",
269
+ default_visibility: "Public",
270
+ });
271
+ // Service identities only: no person reads NPC configuration.
272
+ rows.capability_definition_tag!.push(serviceOnlyAudienceTag(bundle, id));
273
+ };
274
+ const attachment = (kind: string, target: string, namespace: string, payload: unknown) =>
275
+ rows.metadata_attachments!.push({
276
+ bundle_id: bundle,
277
+ target_kind: kind,
278
+ target_ref: target,
279
+ namespace,
280
+ payload_json: bounded(payload),
281
+ source: "manifest",
282
+ });
283
+ capability(catalogCapability);
284
+ rows.metadata_namespaces!.push({
285
+ bundle_id: bundle,
286
+ namespace: catalogNamespace,
287
+ audience: catalogCapability,
288
+ on_demand: false,
289
+ });
290
+ attachment("bundle", bundle, catalogNamespace, {
291
+ ...catalogContent,
292
+ content_hash: catalogHash,
293
+ publication_id: publication,
294
+ });
295
+ const mounts: NpcKindMount[] = [];
296
+ const privateCaps: string[] = [];
297
+ for (const group of source.groups) {
298
+ const namespace = `${prefix}/${group.key}`;
299
+ const read = `${prefix}/read-${group.key}`;
300
+ privateCaps.push(read);
301
+ capability(read);
302
+ rows.metadata_namespaces!.push({
303
+ bundle_id: bundle,
304
+ namespace,
305
+ audience: read,
306
+ on_demand: false,
307
+ });
308
+ const content = {
309
+ schema_version: 1,
310
+ npc_kind: group.npc_kind,
311
+ actor_keys: group.actors.map((actor) => actor.actor_key),
312
+ adapter_id: `${group.npc_kind}/v1`,
313
+ catalog_content_hash: catalogHash,
314
+ config: group.config,
315
+ hooks: {},
316
+ };
317
+ const single = group.actors.length === 1 && group.actors[0]!.blueprint_id === undefined;
318
+ attachment(
319
+ single ? "entity" : "bundle",
320
+ single ? group.actors[0]!.actor_key : bundle,
321
+ namespace,
322
+ { ...content, content_hash: await hash(content), publication_id: publication },
323
+ );
324
+ for (const actor of group.actors) {
325
+ for (const capability_id of [catalogCapability, read]) {
326
+ if (actor.blueprint_id !== undefined)
327
+ rows.entity_definition_initial_capability!.push({
328
+ bundle_id: bundle,
329
+ entity_def_id: actor.blueprint_id,
330
+ capability_id,
331
+ extent_kind_ref: "",
332
+ extent_ref: "",
333
+ });
334
+ else
335
+ rows.actor_capabilities!.push({
336
+ bundle_id: bundle,
337
+ actor_entity_key: actor.actor_key,
338
+ capability_id,
339
+ source: bundle,
340
+ source_args_hash: "",
341
+ elevation_class: "",
342
+ extent_kind_ref: "",
343
+ extent_ref: "",
344
+ });
345
+ }
346
+ mounts.push({
347
+ actor_key: actor.actor_key,
348
+ npc_kind: group.npc_kind,
349
+ schema_version: 1,
350
+ document_namespace: namespace,
351
+ catalog_namespace: catalogNamespace,
352
+ catalog_content_hash: catalogHash,
353
+ });
354
+ }
355
+ }
356
+ const role_id = `${prefix}/publisher-reader`;
357
+ rows.role_definitions!.push({
358
+ bundle_id: bundle,
359
+ role_id,
360
+ display_name: "NPC configuration publisher reader",
361
+ description: "Read configuration metadata for publication readback",
362
+ capability_ids: [catalogCapability, ...privateCaps],
363
+ });
364
+ rows.role_bindings!.push({
365
+ bundle_id: bundle,
366
+ binding_id: `${prefix}/publisher-reader`,
367
+ subject: "$sender",
368
+ role_id,
369
+ extent_kind_ref: "bundle",
370
+ extent_ref: bundle,
371
+ description: "Read ordinary-kind publication",
372
+ });
373
+ return {
374
+ schema_version: 1,
375
+ source_content_hash: digest,
376
+ source,
377
+ manifest: { schema_version: "1.0.0", ...rows },
378
+ mounts,
379
+ };
380
+ }
381
+ /** Admit a sealed ordinary-kind artifact without running the code that
382
+ * authored it. The complete row set is re-derived from the carried source by
383
+ * the generic compiler above and compared canonically, so extra rows, changed
384
+ * grants, changed document content, a source that is not its own fixed point
385
+ * and unknown envelope fields all refuse. Re-derivation also proves that no
386
+ * document carries hooks. Row references are not checked here: the loader
387
+ * that applies the rows owns that, and the caller binds them to a world. */
388
+ export async function parseNpcKindArtifact(json: string): Promise<NpcKindArtifact> {
389
+ const refuse = (): never => {
390
+ throw new Error("NPC kind artifact digest or derived rows mismatch");
391
+ };
392
+ let value: unknown;
393
+ let expected: NpcKindArtifact;
394
+ try {
395
+ value = JSON.parse(json);
396
+ const source = (value as { source?: unknown } | null)?.source;
397
+ if (source === null || typeof source !== "object" || Array.isArray(source)) return refuse();
398
+ expected = await compileNpcKindDocuments(source as NpcKindSource);
399
+ if (canonical(value) !== canonical(expected)) return refuse();
400
+ } catch {
401
+ return refuse();
402
+ }
403
+ return expected;
404
+ }