@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,319 @@
1
+ // embedded-manifest: {"category":"production_schema_constructor","rationale":"The quest compiler constructs a transient schema envelope from validated authored rows for metadata publication and reference closure.","signatures":["schema_object","schema_shape"]}
2
+ /** ADR-0165: one authoring compiler, JSON carrier, no adventure code at publish. */
3
+ import { parse } from "smol-toml";
4
+ import {
5
+ validate_npc_quest_references_json,
6
+ validate_npc_quest_source_json,
7
+ } from "@spellkave/validate-wasm";
8
+ import { serviceOnlyAudienceTag } from "./service-only-audience";
9
+
10
+ export { SERVICE_ONLY_AUDIENCE_TAG } from "./service-only-audience";
11
+
12
+ type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
13
+ type Row = { [key: string]: Json };
14
+ interface Source extends Row {
15
+ schema_version: number;
16
+ bundle_id: string;
17
+ catalog_namespace: string;
18
+ catalog_read_capability_id: string;
19
+ publisher_reader_role_id: string;
20
+ publisher_reader_binding_id: string;
21
+ known_missing_flags: Row;
22
+ bindings: Row;
23
+ quests: Row[];
24
+ givers: Row[];
25
+ }
26
+ export interface NpcQuestMount {
27
+ actor_key: string;
28
+ npc_kind: "quest-giver";
29
+ schema_version: 1;
30
+ document_namespace: string;
31
+ catalog_namespace: string;
32
+ catalog_content_hash: string;
33
+ }
34
+ /** Job-only authoring carrier. Never mount this source/artifact in the host. */
35
+ export interface NpcQuestArtifact {
36
+ schema_version: 1;
37
+ artifact_digest: string;
38
+ source_content_hash: string;
39
+ catalog_content_hash: string;
40
+ source: Source;
41
+ manifest: Row;
42
+ mounts: NpcQuestMount[];
43
+ reference_diagnostics: NpcQuestReferenceDiagnostic[];
44
+ }
45
+ export interface NpcQuestReferenceDiagnostic {
46
+ severity: "error" | "known-missing";
47
+ code: string;
48
+ reference_kind: string;
49
+ reference_id: string;
50
+ bead?: string;
51
+ }
52
+ export interface CompiledNpcQuests {
53
+ artifact: NpcQuestArtifact;
54
+ /** Static loader input for existing TS consumers, generated from the SAME source. */
55
+ legacy: {
56
+ quests: Row[];
57
+ promptLinesByQuest: Row;
58
+ spokenLinesByQuest: Row;
59
+ bindingsByQuest: Row;
60
+ runtimeBindings: Row;
61
+ };
62
+ }
63
+ function canonical(value: unknown): string {
64
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
65
+ if (value !== null && typeof value === "object") {
66
+ return `{${Object.entries(value)
67
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
68
+ .map(([key, value]) => `${JSON.stringify(key)}:${canonical(value)}`)
69
+ .join(",")}}`;
70
+ }
71
+ const encoded = JSON.stringify(value);
72
+ if (encoded === undefined) throw new Error("NPC documents require JSON values");
73
+ return encoded;
74
+ }
75
+ async function digest(value: unknown): Promise<string> {
76
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
77
+ return `sha256:${Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
78
+ }
79
+ function checkedSource(value: unknown): Source {
80
+ const encoded = JSON.stringify(value);
81
+ if (encoded === undefined) throw new Error("NPC quest source is missing");
82
+ const errors: string[] = JSON.parse(validate_npc_quest_source_json(encoded));
83
+ if (errors.length) throw new Error(`Invalid NPC quest source: ${errors.join("; ")}`);
84
+ return JSON.parse(encoded) as Source;
85
+ }
86
+ const legacyKeys = [
87
+ "id",
88
+ "name",
89
+ "rung",
90
+ "giverKey",
91
+ "giverName",
92
+ "acceptSlot",
93
+ "declineSlot",
94
+ "promptId",
95
+ "slotAcceptText",
96
+ "slotDeclineText",
97
+ "objective",
98
+ "terminal",
99
+ "rewardXp",
100
+ "bonusXp",
101
+ "bonusFlag",
102
+ "killXpCreatures",
103
+ ];
104
+ const driverKeys = [
105
+ "minimum_level",
106
+ "progress_home",
107
+ "progress_state_id",
108
+ "rewarded_state_id",
109
+ "awarded_state_id",
110
+ "acceptance_action_id",
111
+ "award_action_id",
112
+ "settle_action_id",
113
+ ];
114
+ function pick(row: Row, keys: string[]): Row {
115
+ return Object.fromEntries(keys.filter((key) => key in row).map((key) => [key, row[key]!]));
116
+ }
117
+ async function compileSource(
118
+ source: Source,
119
+ referenceDiagnostics: NpcQuestReferenceDiagnostic[],
120
+ ): Promise<CompiledNpcQuests> {
121
+ const sourceHash = await digest(source);
122
+ const publication = `source:${sourceHash}`;
123
+ const vocabulary: Row = {
124
+ speechTraceKindId: source.bindings.speech_trace_kind_id!,
125
+ speakActionId: source.bindings.speak_action_id!,
126
+ choiceActions: source.bindings.choice_actions!,
127
+ openActions: source.bindings.open_actions!,
128
+ promptActions: source.bindings.prompt_actions!,
129
+ };
130
+ const runtimeBindings = {
131
+ hero_blueprint_id: source.bindings.hero_blueprint_id!,
132
+ level_state_id: source.bindings.level_state_id!,
133
+ drafting_condition_id: source.bindings.drafting_condition_id!,
134
+ answer_count: source.bindings.answer_count!,
135
+ flag_state_ids: source.bindings.flag_state_ids!,
136
+ vocabulary,
137
+ };
138
+ const catalogContent = {
139
+ schema_version: 1,
140
+ bindings: runtimeBindings,
141
+ quests: source.quests.map((quest) => pick(quest, [...legacyKeys, ...driverKeys])),
142
+ };
143
+ const catalogHash = await digest(catalogContent);
144
+ const catalog = { ...catalogContent, content_hash: catalogHash, publication_id: publication };
145
+ const bundle = source.bundle_id;
146
+ const capability = (id: string) => ({
147
+ bundle_id: bundle,
148
+ capability_id: id,
149
+ actor_kind: "entity",
150
+ display_name: "Read NPC authoring document",
151
+ description: "Read only the declared NPC metadata audience",
152
+ default_visibility: "Public",
153
+ });
154
+ const role = (id: string, capabilities: string[]) => ({
155
+ bundle_id: bundle,
156
+ role_id: id,
157
+ display_name: "NPC document reader",
158
+ description: "Read declared NPC metadata without action or authoring authority",
159
+ capability_ids: capabilities,
160
+ });
161
+ const binding = (id: string, subject: string, roleId: string) => ({
162
+ bundle_id: bundle,
163
+ binding_id: id,
164
+ subject,
165
+ role_id: roleId,
166
+ extent_kind_ref: "bundle",
167
+ extent_ref: bundle,
168
+ description: "Read NPC authoring documents",
169
+ });
170
+ const namespace = (name: string, audience: string) => ({
171
+ bundle_id: bundle,
172
+ namespace: name,
173
+ audience,
174
+ on_demand: false,
175
+ });
176
+ const attachment = (kind: string, ref: string, name: string, payload: unknown) => ({
177
+ bundle_id: bundle,
178
+ target_kind: kind,
179
+ target_ref: ref,
180
+ namespace: name,
181
+ payload_json: canonical(payload),
182
+ source: "manifest",
183
+ });
184
+ const privateCaps = source.givers.map((giver) => String(giver.read_capability_id));
185
+ const publisherRole = source.publisher_reader_role_id;
186
+ const manifests: Record<string, Row[]> = {
187
+ capability_definitions: [
188
+ capability(source.catalog_read_capability_id),
189
+ ...privateCaps.map(capability),
190
+ ],
191
+ capability_definition_tag: [source.catalog_read_capability_id, ...privateCaps].map((id) =>
192
+ serviceOnlyAudienceTag(bundle, id),
193
+ ),
194
+ role_definitions: [role(publisherRole, [source.catalog_read_capability_id, ...privateCaps])],
195
+ role_bindings: [binding(source.publisher_reader_binding_id, "$sender", publisherRole)],
196
+ actor_capabilities: [],
197
+ metadata_namespaces: [namespace(source.catalog_namespace, source.catalog_read_capability_id)],
198
+ metadata_attachments: [attachment("bundle", bundle, source.catalog_namespace, catalog)],
199
+ };
200
+ const mounts: NpcQuestMount[] = [];
201
+ for (const giver of source.givers) {
202
+ const actor = String(giver.actor_key);
203
+ const refs = giver.quest_refs as string[];
204
+ const lines = Object.fromEntries(
205
+ refs.map((id) => [id, source.quests.find((quest) => quest.id === id)!.spoken_lines!]),
206
+ );
207
+ const content = {
208
+ schema_version: 1,
209
+ npc_kind: "quest-giver",
210
+ adapter_id: "quest-board/v1",
211
+ catalog_content_hash: catalogHash,
212
+ quest_refs: refs,
213
+ lines,
214
+ hooks: {},
215
+ };
216
+ const payload = {
217
+ ...content,
218
+ content_hash: await digest(content),
219
+ publication_id: publication,
220
+ };
221
+ for (const capabilityId of [
222
+ String(giver.read_capability_id),
223
+ source.catalog_read_capability_id,
224
+ ]) {
225
+ manifests.actor_capabilities!.push({
226
+ actor_entity_key: actor,
227
+ bundle_id: bundle,
228
+ capability_id: capabilityId,
229
+ source: bundle,
230
+ source_args_hash: "",
231
+ elevation_class: "",
232
+ extent_kind_ref: "",
233
+ extent_ref: "",
234
+ });
235
+ }
236
+ manifests.metadata_namespaces!.push(
237
+ namespace(String(giver.namespace), String(giver.read_capability_id)),
238
+ );
239
+ manifests.metadata_attachments!.push(
240
+ attachment("entity", actor, String(giver.namespace), payload),
241
+ );
242
+ mounts.push({
243
+ actor_key: actor,
244
+ npc_kind: "quest-giver",
245
+ schema_version: 1,
246
+ document_namespace: String(giver.namespace),
247
+ catalog_namespace: source.catalog_namespace,
248
+ catalog_content_hash: catalogHash,
249
+ });
250
+ }
251
+ const manifest: Row = { schema_version: "1.0.0", ...manifests };
252
+ const body = {
253
+ schema_version: 1 as const,
254
+ source_content_hash: sourceHash,
255
+ catalog_content_hash: catalogHash,
256
+ source,
257
+ manifest,
258
+ mounts,
259
+ reference_diagnostics: referenceDiagnostics,
260
+ };
261
+ return {
262
+ artifact: { ...body, artifact_digest: await digest(body) },
263
+ legacy: {
264
+ quests: source.quests.map((quest) => pick(quest, legacyKeys)),
265
+ promptLinesByQuest: Object.fromEntries(
266
+ source.quests.map((quest) => [String(quest.id), quest.prompt_lines!]),
267
+ ),
268
+ spokenLinesByQuest: Object.fromEntries(
269
+ source.quests.map((quest) => [String(quest.id), quest.spoken_lines!]),
270
+ ),
271
+ bindingsByQuest: Object.fromEntries(
272
+ source.quests.map((quest) => [String(quest.id), pick(quest, driverKeys)]),
273
+ ),
274
+ runtimeBindings,
275
+ },
276
+ };
277
+ }
278
+ /** No random publication ids, IO, world connection or authority-bearing callbacks. */
279
+ export async function compileNpcQuestSource(
280
+ toml: string,
281
+ canonicalWorlds: readonly unknown[],
282
+ ): Promise<CompiledNpcQuests> {
283
+ const source = checkedSource(parse(toml));
284
+ return compileSource(source, checkedReferences(source, canonicalWorlds));
285
+ }
286
+ /** Loader generation precedes world generation. This returns no publishable
287
+ * artifact; sealing one requires compileNpcQuestSource's canonical world input. */
288
+ export async function compileNpcQuestLegacySource(
289
+ toml: string,
290
+ ): Promise<CompiledNpcQuests["legacy"]> {
291
+ return (await compileSource(checkedSource(parse(toml)), [])).legacy;
292
+ }
293
+ function checkedReferences(
294
+ source: Source,
295
+ canonicalWorlds: readonly unknown[],
296
+ ): NpcQuestReferenceDiagnostic[] {
297
+ const diagnostics: NpcQuestReferenceDiagnostic[] = JSON.parse(
298
+ validate_npc_quest_references_json(JSON.stringify(source), JSON.stringify(canonicalWorlds)),
299
+ );
300
+ if (diagnostics.some((diagnostic) => diagnostic.severity === "error"))
301
+ throw new Error(`Invalid NPC quest references: ${JSON.stringify(diagnostics)}`);
302
+ return diagnostics;
303
+ }
304
+ /** Future artifact-consumer integration is owned by sk-jay0.3.33.32.
305
+ * Re-derive the complete row set from the Rust-validated sealed source. Extra
306
+ * rows, changed grants, changed private content or unknown envelope fields refuse. */
307
+ export async function parseNpcQuestArtifact(
308
+ json: string,
309
+ canonicalWorlds: readonly unknown[],
310
+ ): Promise<NpcQuestArtifact> {
311
+ const value: unknown = JSON.parse(json);
312
+ const source = (value as { source?: unknown } | null)?.source;
313
+ const admitted = checkedSource(source);
314
+ const expected = (await compileSource(admitted, checkedReferences(admitted, canonicalWorlds)))
315
+ .artifact;
316
+ if (canonical(value) !== canonical(expected))
317
+ throw new Error("NPC quest artifact digest or derived rows mismatch");
318
+ return expected;
319
+ }
@@ -0,0 +1,31 @@
1
+ // #1921 browser-wasm regression fix (#1968): browser counterpart of
2
+ // `./observation-tokens.ts` — see that file's header for the full root-cause
3
+ // explanation. Resolved automatically (via this package's "browser" export
4
+ // condition on `./observation-tokens`) by any bundler building for a browser
5
+ // target (Vite's default client-build resolve conditions include "browser");
6
+ // Node hosts (shared tool runtime's own tests, `world-explorer`, CLIs) keep
7
+ // resolving `./observation-tokens.ts` unchanged.
8
+ //
9
+ // Sources the SAME Rust single-source-of-truth token list
10
+ // (`spellkave_validate::OBSERVATION_PLACEHOLDER_TOKENS`) through the
11
+ // wasm-bindgen `--target web` sibling build (`spellkave-validate-wasm-web`,
12
+ // already vendored and already used by `./browser.ts`) instead of the
13
+ // `--target nodejs` one: its loader fetches the .wasm binary lazily on first
14
+ // call (`init()`), never at module-import time, so merely importing this
15
+ // file — even when bundled into `apps/world-play` — is inert until the
16
+ // function below is actually invoked.
17
+ import initValidateWasm, { observation_placeholder_tokens_json } from "@spellkave/validate-wasm/browser";
18
+
19
+ let wasmReady: Promise<void> | null = null;
20
+
21
+ function ensureWasm(): Promise<void> {
22
+ if (wasmReady === null) {
23
+ wasmReady = initValidateWasm().then(() => undefined);
24
+ }
25
+ return wasmReady;
26
+ }
27
+
28
+ export async function observationPlaceholderTokens(): Promise<string[]> {
29
+ await ensureWasm();
30
+ return JSON.parse(observation_placeholder_tokens_json()) as string[];
31
+ }
@@ -0,0 +1,27 @@
1
+ // #1921 browser-wasm regression fix (#1968): Node/default counterpart of
2
+ // `./observation-tokens.browser.ts`.
3
+ //
4
+ // `@spellkave/tool-authoring`'s `observation.ts` used to import
5
+ // `observationPlaceholderTokens` straight from this package's DEFAULT entry
6
+ // (`./index.ts` -> `./reference.ts`), whose static import graph also reaches
7
+ // `./compose.ts`/`./row-kinds.ts`/`./patch.ts`/`./manifest.ts`/`./validate.ts`
8
+ // /`./inspect.ts` — every one of which imports the `spellkave-authoring-wasm`
9
+ // / `spellkave-validate-wasm` wasm-bindgen `--target nodejs` builds. Those
10
+ // builds' generated loaders do `require('fs').readFileSync(path.join(__dirname,
11
+ // ...))` at MODULE TOP LEVEL: harmless under Node, fatal the instant a
12
+ // browser bundle (`apps/world-play`) merely imports the module graph that
13
+ // reaches them, whether or not any wasm function is ever actually called.
14
+ //
15
+ // This file (resolved via this package's "default"/"types" condition on the
16
+ // `./observation-tokens` export) exists ONLY to give `observation.ts` a
17
+ // single ASYNC call shape shared with the browser build
18
+ // (`./observation-tokens.browser.ts`, resolved instead via the "browser"
19
+ // condition) — the underlying value and Rust source
20
+ // (`spellkave_validate::OBSERVATION_PLACEHOLDER_TOKENS`) are identical; this
21
+ // wrapper adds no behavior beyond `Promise`-wrapping the existing synchronous
22
+ // `./reference.ts` accessor.
23
+ import { observationPlaceholderTokens as observationPlaceholderTokensSync } from "./reference";
24
+
25
+ export async function observationPlaceholderTokens(): Promise<string[]> {
26
+ return observationPlaceholderTokensSync();
27
+ }