@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,339 @@
1
+ // embedded-manifest: {"category":"production_schema_constructor","rationale":"The opt-in DM compiler derives bounded metadata documents and their exact declared read authority from shared Rust admission; it never applies rows or activates a host.","signatures":["schema_object","schema_shape"]}
2
+ /** Job-only DM carrier. No IO, connection, credential or activation callback. */
3
+ import {
4
+ derive_dm_document_authority_json,
5
+ validate_dm_artifact_shape_json,
6
+ validate_dm_duty_document_json,
7
+ validate_dm_presentation_document_json,
8
+ validate_dm_source_references_json,
9
+ validate_dm_source_shape_json,
10
+ } from "@spellkave/validate-wasm";
11
+ import { projectDmAuthorityWorlds } from "./npc-dm-authority-projection.ts";
12
+ import type {
13
+ DmDutySource,
14
+ DmLocatorReferenceLocators,
15
+ DmPresentationContent,
16
+ DmPrincipalPlan,
17
+ DmReads,
18
+ } from "./npc-dm-types.ts";
19
+ import {
20
+ type NpcQuestArtifact,
21
+ type NpcQuestReferenceDiagnostic,
22
+ parseNpcQuestArtifact,
23
+ } from "./npc-quests.ts";
24
+
25
+ export type * from "./npc-dm-types.ts";
26
+
27
+ type Row = Record<string, unknown>;
28
+
29
+ export interface NpcDmSource {
30
+ schema_version: number;
31
+ bundle_id: string;
32
+ body_key: string;
33
+ principal_plan: DmPrincipalPlan;
34
+ reads: DmReads;
35
+ catalog: NpcQuestArtifact;
36
+ presentation: DmPresentationContent;
37
+ duties: DmDutySource;
38
+ reference_locators: DmLocatorReferenceLocators;
39
+ }
40
+ export interface NpcDmLocator {
41
+ catalog_namespace: string;
42
+ reader_binding_id: string;
43
+ }
44
+ export interface NpcDmReadGrant {
45
+ socket_role: "principal" | "body";
46
+ target_kind: "bundle" | "entity";
47
+ target_ref: string;
48
+ namespace: string;
49
+ read_capability_id: string;
50
+ content_hash: string;
51
+ publication_id: string;
52
+ }
53
+ export interface NpcDmMetadataAttachment {
54
+ bundle_id: string;
55
+ target_kind: "entity" | "bundle";
56
+ target_ref: string;
57
+ namespace: string;
58
+ payload_json: string;
59
+ source: "manifest";
60
+ }
61
+ export interface NpcDmManifest {
62
+ schema_version: "1.0.0";
63
+ capability_definitions: {
64
+ bundle_id: string;
65
+ capability_id: string;
66
+ actor_kind: "entity";
67
+ display_name: string;
68
+ description: string;
69
+ default_visibility: "Public";
70
+ }[];
71
+ /** Every DM read capability is a service-only audience
72
+ * (`SERVICE_ONLY_AUDIENCE_TAG`). */
73
+ capability_definition_tag: {
74
+ bundle_id: string;
75
+ capability_id: string;
76
+ tag: string;
77
+ source: "manifest";
78
+ }[];
79
+ role_definitions: {
80
+ bundle_id: string;
81
+ role_id: string;
82
+ display_name: string;
83
+ description: string;
84
+ capability_ids: string[];
85
+ }[];
86
+ metadata_namespaces: {
87
+ bundle_id: string;
88
+ namespace: string;
89
+ audience: string;
90
+ on_demand: false;
91
+ }[];
92
+ actor_capabilities: {
93
+ bundle_id: string;
94
+ actor_entity_key: string;
95
+ capability_id: string;
96
+ source: string;
97
+ source_args_hash: string;
98
+ elevation_class: string;
99
+ extent_kind_ref: string;
100
+ extent_ref: string;
101
+ }[];
102
+ metadata_attachments: NpcDmMetadataAttachment[];
103
+ }
104
+ export interface NpcDmArtifact {
105
+ schema_version: 1;
106
+ npc_kind: "dm";
107
+ artifact_digest: string;
108
+ source_content_hash: string;
109
+ source: NpcDmSource;
110
+ manifest: NpcDmManifest;
111
+ principal_plan: DmPrincipalPlan;
112
+ locator: NpcDmLocator;
113
+ read_grants: NpcDmReadGrant[];
114
+ reference_diagnostics: NpcQuestReferenceDiagnostic[];
115
+ }
116
+
117
+ const PRESENTATION_NAMESPACE = "npc/dm/presentation/v1";
118
+ const DUTIES_NAMESPACE = "npc/dm/duties/v1";
119
+ const MAX_DOCUMENT_BYTES = 256 * 1024;
120
+
121
+ /** JSON key order follows JS UTF-16 ordering, matching existing quest hashes.
122
+ * Refuse values that JSON.stringify would silently omit/coerce, plus class
123
+ * serializers, accessors, sparse arrays and cycles in canonical world inputs. */
124
+ function canonical(value: unknown, ancestors = new Set<object>()): string {
125
+ if (value === null || typeof value === "string" || typeof value === "boolean")
126
+ return JSON.stringify(value);
127
+ if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value);
128
+ if (typeof value !== "object" || ancestors.has(value))
129
+ throw new Error("DM carrier requires acyclic JSON values");
130
+ const prototype: unknown = Object.getPrototypeOf(value);
131
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
132
+ throw new Error("DM carrier requires plain JSON objects");
133
+ ancestors.add(value);
134
+ try {
135
+ if (Object.getOwnPropertySymbols(value).length)
136
+ throw new Error("DM carrier refuses symbol fields");
137
+ if (Array.isArray(value)) {
138
+ if (
139
+ Object.getOwnPropertyNames(value).some(
140
+ (key) =>
141
+ key !== "length" && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length),
142
+ )
143
+ )
144
+ throw new Error("DM carrier refuses extra array fields");
145
+ const items: string[] = [];
146
+ for (let i = 0; i < value.length; i++) {
147
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
148
+ if (!descriptor || !("value" in descriptor))
149
+ throw new Error("DM carrier refuses sparse/accessor arrays");
150
+ items.push(canonical(descriptor.value, ancestors));
151
+ }
152
+ return `[${items.join(",")}]`;
153
+ }
154
+ const descriptors = Object.getOwnPropertyDescriptors(value);
155
+ return `{${Object.keys(descriptors)
156
+ .sort()
157
+ .map((key) => {
158
+ const descriptor = descriptors[key]!;
159
+ if (!("value" in descriptor) || !descriptor.enumerable)
160
+ throw new Error("DM carrier refuses accessors/non-JSON fields");
161
+ return `${JSON.stringify(key)}:${canonical(descriptor.value, ancestors)}`;
162
+ })
163
+ .join(",")}}`;
164
+ } finally {
165
+ ancestors.delete(value);
166
+ }
167
+ }
168
+ async function digest(value: unknown): Promise<string> {
169
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
170
+ return `sha256:${Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
171
+ }
172
+ function checked(diagnostics: string, context: string): void {
173
+ const errors: string[] = JSON.parse(diagnostics);
174
+ if (errors.length) throw new Error(`Invalid DM ${context}: ${errors.join("; ")}`);
175
+ }
176
+ function deriveAuthority(
177
+ input: Row,
178
+ worlds: readonly unknown[],
179
+ ): {
180
+ principal_plan: DmPrincipalPlan;
181
+ manifest: Omit<NpcDmManifest, "metadata_attachments">;
182
+ } {
183
+ try {
184
+ return JSON.parse(
185
+ derive_dm_document_authority_json(
186
+ canonical(input),
187
+ canonical(projectDmAuthorityWorlds(worlds)),
188
+ ),
189
+ );
190
+ } catch (error) {
191
+ throw new Error(`Invalid DM read authority: ${String(error)}`);
192
+ }
193
+ }
194
+ async function document(
195
+ content: Row,
196
+ publication: string,
197
+ ): Promise<Row & { content_hash: string; publication_id: string }> {
198
+ const result = { ...content, content_hash: await digest(content), publication_id: publication };
199
+ if (new TextEncoder().encode(canonical(result)).byteLength > MAX_DOCUMENT_BYTES)
200
+ throw new Error("DM document exceeds 256 KiB including its publication envelope");
201
+ return result;
202
+ }
203
+
204
+ /** canonicalWorlds contains complete admitted flattened roots, followed by the
205
+ * independently parsed quest artifact contribution. Never a filtered cache or
206
+ * self-composed nested catalog. Old no-document artifacts use their old parser. */
207
+ export async function compileNpcDmSource(
208
+ sourceJson: string,
209
+ canonicalWorlds: readonly unknown[],
210
+ ): Promise<NpcDmArtifact> {
211
+ checked(validate_dm_source_shape_json(sourceJson), "source");
212
+ const source = JSON.parse(sourceJson) as NpcDmSource;
213
+ const worldsJson = canonical(canonicalWorlds);
214
+ checked(validate_dm_source_references_json(sourceJson, worldsJson), "references");
215
+ const catalog = await parseNpcQuestArtifact(canonical(source.catalog), canonicalWorlds);
216
+ const catalogNamespace = catalog.source.catalog_namespace;
217
+ const authority = deriveAuthority(
218
+ {
219
+ schema_version: 1,
220
+ bundle_id: source.bundle_id,
221
+ body_key: source.body_key,
222
+ principal_plan: source.principal_plan,
223
+ reads: source.reads,
224
+ catalog_namespace: catalogNamespace,
225
+ },
226
+ canonicalWorlds,
227
+ );
228
+ const attachments = catalog.manifest.metadata_attachments as Row[];
229
+ const catalogRow = attachments.find(
230
+ (row) =>
231
+ row.target_kind === "bundle" &&
232
+ row.target_ref === source.bundle_id &&
233
+ row.bundle_id === source.bundle_id &&
234
+ row.namespace === catalogNamespace,
235
+ );
236
+ if (!catalogRow || typeof catalogRow.payload_json !== "string")
237
+ throw new Error("DM catalog publication is missing");
238
+ const catalogDocument = JSON.parse(catalogRow.payload_json) as { publication_id: string };
239
+ const sourceHash = await digest(source);
240
+ const publication = `source:${sourceHash}`;
241
+ const presentation = await document({ ...source.presentation }, publication);
242
+ const duties = await document(
243
+ {
244
+ ...source.duties,
245
+ creation: {
246
+ ...source.duties.creation,
247
+ kits: source.duties.creation.kits.map(({ items: _items, ...kit }) => kit),
248
+ },
249
+ catalog_namespace: catalogNamespace,
250
+ catalog_content_hash: catalog.catalog_content_hash,
251
+ catalog_publication_id: catalogDocument.publication_id,
252
+ presentation_content_hash: presentation.content_hash,
253
+ },
254
+ publication,
255
+ );
256
+ checked(validate_dm_presentation_document_json(canonical(presentation)), "presentation document");
257
+ checked(validate_dm_duty_document_json(canonical(duties)), "duty document");
258
+ const attachment = (
259
+ kind: "entity" | "bundle",
260
+ target: string,
261
+ namespace: string,
262
+ payload: Row,
263
+ ): NpcDmMetadataAttachment => ({
264
+ bundle_id: source.bundle_id,
265
+ target_kind: kind,
266
+ target_ref: target,
267
+ namespace,
268
+ payload_json: canonical(payload),
269
+ source: "manifest",
270
+ });
271
+ const manifest: NpcDmManifest = {
272
+ ...authority.manifest,
273
+ metadata_attachments: [
274
+ attachment("entity", source.body_key, PRESENTATION_NAMESPACE, presentation),
275
+ attachment("bundle", source.bundle_id, DUTIES_NAMESPACE, duties),
276
+ ],
277
+ };
278
+ const grants: NpcDmReadGrant[] = [
279
+ {
280
+ socket_role: "principal",
281
+ target_kind: "bundle",
282
+ target_ref: source.bundle_id,
283
+ namespace: catalogNamespace,
284
+ read_capability_id: source.reads.catalog_read_capability_id,
285
+ content_hash: catalog.catalog_content_hash,
286
+ publication_id: catalogDocument.publication_id,
287
+ },
288
+ {
289
+ socket_role: "principal",
290
+ target_kind: "bundle",
291
+ target_ref: source.bundle_id,
292
+ namespace: DUTIES_NAMESPACE,
293
+ read_capability_id: source.reads.duty_read_capability_id,
294
+ content_hash: duties.content_hash,
295
+ publication_id: publication,
296
+ },
297
+ {
298
+ socket_role: "body",
299
+ target_kind: "entity",
300
+ target_ref: source.body_key,
301
+ namespace: PRESENTATION_NAMESPACE,
302
+ read_capability_id: source.reads.presentation_read_capability_id,
303
+ content_hash: presentation.content_hash,
304
+ publication_id: publication,
305
+ },
306
+ ];
307
+ const content = {
308
+ schema_version: 1 as const,
309
+ npc_kind: "dm" as const,
310
+ source_content_hash: sourceHash,
311
+ source,
312
+ manifest,
313
+ principal_plan: authority.principal_plan,
314
+ locator: {
315
+ catalog_namespace: catalogNamespace,
316
+ reader_binding_id: source.reads.reader_binding_id,
317
+ },
318
+ read_grants: grants,
319
+ reference_diagnostics: catalog.reference_diagnostics,
320
+ };
321
+ const artifact = { ...content, artifact_digest: await digest(content) };
322
+ checked(validate_dm_artifact_shape_json(canonical(artifact)), "artifact shape");
323
+ return artifact;
324
+ }
325
+
326
+ /** Publication repeats raw JSON admission and every derivation. Unknown fields,
327
+ * altered rows/plan/grants/locators/hash and stale catalog publications refuse. */
328
+ export async function parseNpcDmArtifact(
329
+ artifactJson: string,
330
+ canonicalWorlds: readonly unknown[],
331
+ ): Promise<NpcDmArtifact> {
332
+ checked(validate_dm_artifact_shape_json(artifactJson), "artifact shape");
333
+ const value: unknown = JSON.parse(artifactJson);
334
+ if (value === null || typeof value !== "object" || Array.isArray(value) || !("source" in value))
335
+ throw new Error("Invalid DM artifact envelope");
336
+ const expected = await compileNpcDmSource(canonical(value.source), canonicalWorlds);
337
+ if (canonical(value) !== canonical(expected)) throw new Error("DM artifact derivation mismatch");
338
+ return expected;
339
+ }
@@ -0,0 +1,17 @@
1
+ /** Presentation component admission only; no world rows or engine activation. */
2
+ import { validate_dm_presentation_json } from "@spellkave/validate-wasm";
3
+
4
+ /** Preserve raw JSON for duplicate-field checks in the authoritative Rust schema. */
5
+ export function validateDmPresentationJson(json: string): void {
6
+ const errors: string[] = JSON.parse(validate_dm_presentation_json(json));
7
+ if (errors.length) throw new Error(`Invalid DM presentation: ${errors.join("; ")}`);
8
+ }
9
+
10
+ /** Used inside a future document compiler. This does not construct a publication,
11
+ * hash, locator, capability, trusted duty configuration or mounted engine. */
12
+ export function compileDmPresentationJson(value: unknown): string {
13
+ const json = JSON.stringify(value);
14
+ if (json === undefined) throw new Error("DM presentation requires JSON data");
15
+ validateDmPresentationJson(json);
16
+ return json;
17
+ }
@@ -0,0 +1,51 @@
1
+ // embedded-manifest: {"category":"production_schema_constructor","rationale":"The offline DM data compiler constructs a versioned data envelope over admitted tables, not an embedded world manifest or runtime authority grant.","signatures":["schema_shape"]}
2
+ /** Offline data compilation only. No runtime authority or publication grant. */
3
+ import { validate_dm_srd_tables_json } from "@spellkave/validate-wasm";
4
+
5
+ export interface DmSrdData {
6
+ schema_version: 1;
7
+ tables: Record<string, unknown>;
8
+ content_hash: string;
9
+ }
10
+ function canonical(value: unknown): string {
11
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
12
+ if (value !== null && typeof value === "object") {
13
+ return `{${Object.entries(value)
14
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
15
+ .map(([key, value]) => `${JSON.stringify(key)}:${canonical(value)}`)
16
+ .join(",")}}`;
17
+ }
18
+ const encoded = JSON.stringify(value);
19
+ if (encoded === undefined) throw new Error("DM SRD data requires JSON values");
20
+ return encoded;
21
+ }
22
+ /** Lossless JSON source values only; the shared Rust validator admits the shape. */
23
+ export async function compileDmSrdData(tables: unknown): Promise<DmSrdData> {
24
+ const encoded = canonical(tables);
25
+ const errors: string[] = JSON.parse(validate_dm_srd_tables_json(encoded));
26
+ if (errors.length) throw new Error(`Invalid DM SRD tables: ${errors.join("; ")}`);
27
+ const content = { schema_version: 1 as const, tables: JSON.parse(encoded) };
28
+ const digest = await crypto.subtle.digest(
29
+ "SHA-256",
30
+ new TextEncoder().encode(canonical(content)),
31
+ );
32
+ const hash = Array.from(new Uint8Array(digest), (byte) =>
33
+ byte.toString(16).padStart(2, "0"),
34
+ ).join("");
35
+ return { ...content, content_hash: `sha256:${hash}` };
36
+ }
37
+ /** Publish-time tooling must derive again, rather than trust a supplied hash. */
38
+ export async function parseDmSrdData(encoded: string): Promise<DmSrdData> {
39
+ const value: unknown = JSON.parse(encoded);
40
+ if (value === null || typeof value !== "object" || Array.isArray(value))
41
+ throw new Error("Invalid DM SRD data envelope");
42
+ const fields = value as Record<string, unknown>;
43
+ if (
44
+ fields.schema_version !== 1 ||
45
+ Object.keys(fields).sort().join(",") !== "content_hash,schema_version,tables"
46
+ )
47
+ throw new Error("Invalid DM SRD data envelope");
48
+ const compiled = await compileDmSrdData(fields.tables);
49
+ if (canonical(compiled) !== canonical(value)) throw new Error("DM SRD data hash mismatch");
50
+ return compiled;
51
+ }