@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,397 @@
1
+ import {
2
+ type RenderManifestIncludeOptions,
3
+ renderManifestIncludeWith,
4
+ splitIncludedManifestMetadataWith,
5
+ } from "./included-manifest-metadata-core";
6
+
7
+ /** Browser AUTHOR tooling: web wasm at the boundary, shared pure helpers within. */
8
+
9
+ import initAuthoring, {
10
+ applyset_root_info_json,
11
+ classify_and_build_delta_json,
12
+ cluster_rows_json,
13
+ export_not_round_tripped_json,
14
+ extra_rows_by_natural_key_json,
15
+ live_manifest_row_identities_json,
16
+ manifest_row_identities_json,
17
+ patch_manifest_json,
18
+ row_kind_composite_key_json,
19
+ row_kind_natural_key_json,
20
+ row_kind_storage_key_json,
21
+ shape_params_json,
22
+ } from "@spellkave/authoring-wasm/browser";
23
+ import initValidate, {
24
+ core_bootstrap_manifest,
25
+ core_extent_kinds_json,
26
+ evaluate_dsl_expression_json as evaluate_dsl_expression_json_raw,
27
+ manifest_schema_json,
28
+ merged_role_capability_ids_json,
29
+ parse_manifest_toml_to_json,
30
+ render_manifest_include,
31
+ render_manifest_json_to_toml,
32
+ split_manifest_fragment,
33
+ validate_manifest_toml,
34
+ } from "@spellkave/validate-wasm/browser";
35
+ import type {
36
+ ApplysetDiffInput,
37
+ ApplysetDiffOutput,
38
+ ApplysetExtentScope,
39
+ ApplysetRootInfo,
40
+ } from "./applyset-diff-types";
41
+ import {
42
+ authoringDocMetadata,
43
+ extractAuthoringDocSection,
44
+ isSupportedAuthoringDoc,
45
+ listAuthoringDocSections,
46
+ listAuthoringDocs,
47
+ queryAuthoringDocs,
48
+ } from "./corpus";
49
+ import { routeDamage, routeDamageMagnitude } from "./damage";
50
+ import type { Diagnostic } from "./diagnostics";
51
+ import {
52
+ diffManifests,
53
+ flattenManifestDiff,
54
+ parseMapKey,
55
+ parseSchemaManifestToml as parseSchemaManifestTomlPure,
56
+ } from "./diff-manifest-core";
57
+ import type {
58
+ DslExpressionKind,
59
+ EvaluateDslExpressionOptions,
60
+ EvaluationRejection,
61
+ EvaluationResult,
62
+ EvaluationValue,
63
+ RollTableSelection,
64
+ StochasticDraw,
65
+ SubjectRef,
66
+ TraceEntry,
67
+ TraceScopeEntry,
68
+ } from "./evaluate";
69
+ import {
70
+ filteredRowCount,
71
+ filterManifestForActor,
72
+ type SchemaManifest,
73
+ } from "./filter-manifest-core";
74
+ import {
75
+ findRowByCompositeKey,
76
+ inspectRowRefs,
77
+ inspectSchemaManifest,
78
+ outboundRefsExcluding,
79
+ refTagOutboundRefs,
80
+ } from "./inspection";
81
+ import { stripManifestHeaders } from "./manifest-text";
82
+ import { validateMetadataRows } from "./metadata";
83
+ import { type RefTagFamily, resolveRefTagValue } from "./ref-tags";
84
+ import { setExportNotRoundTripped, setRowKindMaps } from "./row-kinds-data";
85
+ import { manifestTagPrefixFamilies } from "./tag-prefix-families";
86
+
87
+ export type { Diagnostic, RefTagFamily, SchemaManifest };
88
+ export type * from "./applyset-diff-types";
89
+ export type DiffOnlyFilter = "gaps" | "snapshot" | "changed";
90
+ export type ActorBehavior = import("./compose").ActorBehavior;
91
+ export type BehaviorConfig = import("./compose").BehaviorConfig;
92
+ export type InboundRowRef = { kind: string; id: string; field: string };
93
+ export type OutboundRowRef = { field: string; value: string };
94
+
95
+ let ready: Promise<void> | undefined;
96
+ export const ROW_KIND_NATURAL_KEY: Record<string, string> = {};
97
+ export const ROW_KIND_COMPOSITE_KEY: Record<string, readonly string[]> = {};
98
+ /** ADR-0146, sk-jay0.7.174.30 — see `row-kinds.ts`'s own doc comment. */
99
+ export const ROW_KIND_STORAGE_KEY: Record<string, readonly string[]> = {};
100
+
101
+ export function loadBrowserAuthorTooling(): Promise<void> {
102
+ ready ??= Promise.all([initValidate(), initAuthoring()]).then(() => {
103
+ Object.assign(ROW_KIND_NATURAL_KEY, decode(row_kind_natural_key_json()));
104
+ Object.assign(ROW_KIND_COMPOSITE_KEY, decode(row_kind_composite_key_json()));
105
+ Object.assign(ROW_KIND_STORAGE_KEY, decode(row_kind_storage_key_json()));
106
+ setRowKindMaps(ROW_KIND_NATURAL_KEY, ROW_KIND_COMPOSITE_KEY);
107
+ setExportNotRoundTripped(decode(export_not_round_tripped_json()));
108
+ });
109
+ return ready;
110
+ }
111
+
112
+ function requireReady(): void {
113
+ if (ready === undefined) {
114
+ throw new Error(
115
+ "AUTHOR browser tooling is not initialized; call loadBrowserAuthorTooling first.",
116
+ );
117
+ }
118
+ }
119
+
120
+ function decode<T>(value: string): T {
121
+ return JSON.parse(value) as T;
122
+ }
123
+
124
+ export function describeManifestSchema(): Record<string, unknown> {
125
+ requireReady();
126
+ return decode(manifest_schema_json());
127
+ }
128
+
129
+ export function renderSchemaManifest(manifest: Record<string, unknown>): string {
130
+ requireReady();
131
+ return render_manifest_json_to_toml(JSON.stringify(manifest));
132
+ }
133
+
134
+ export function inspectManifest(toml: string) {
135
+ requireReady();
136
+ return inspectSchemaManifest(decode<Record<string, unknown>>(parse_manifest_toml_to_json(toml)));
137
+ }
138
+
139
+ export function parseSchemaManifestToml(toml: string): SchemaManifest {
140
+ return parseSchemaManifestTomlPure(toml);
141
+ }
142
+
143
+ export function validateManifestToml(toml: string): Diagnostic[] {
144
+ requireReady();
145
+ const diagnostics = decode<Diagnostic[]>(validate_manifest_toml(toml));
146
+ try {
147
+ const manifest = parseSchemaManifestToml(toml);
148
+ diagnostics.push(
149
+ ...validateMetadataRows(
150
+ manifest.metadata_attachments as never,
151
+ manifest.metadata_namespaces as never,
152
+ ),
153
+ ...validateActorCapabilityRows(manifest.actor_capabilities as never),
154
+ ...validateCapabilityNicheProvider(
155
+ manifest.niche_definitions as never,
156
+ manifest.affordance_templates as never,
157
+ ),
158
+ );
159
+ } catch {
160
+ // Rust validation already contains parse diagnostics.
161
+ }
162
+ return diagnostics;
163
+ }
164
+
165
+ export function patchManifest(
166
+ manifest: Record<string, unknown>,
167
+ op: string,
168
+ payload: Record<string, unknown>,
169
+ ): void {
170
+ requireReady();
171
+ for (const [table, rows] of Object.entries(
172
+ decode<Record<string, unknown[]>>(
173
+ patch_manifest_json(JSON.stringify(manifest), op, JSON.stringify(payload)),
174
+ ),
175
+ ))
176
+ manifest[table] = rows;
177
+ }
178
+
179
+ export function clusterRows(
180
+ behaviors: ActorBehavior[],
181
+ cfg: BehaviorConfig,
182
+ ): Record<string, unknown> {
183
+ requireReady();
184
+ return decode(cluster_rows_json(JSON.stringify(behaviors), JSON.stringify(cfg)));
185
+ }
186
+
187
+ export function applysetRootInfo(rootToml: string): ApplysetRootInfo {
188
+ requireReady();
189
+ return decode(applyset_root_info_json(rootToml));
190
+ }
191
+
192
+ export function classifyAndBuildDelta(input: ApplysetDiffInput): ApplysetDiffOutput {
193
+ requireReady();
194
+ return decode(classify_and_build_delta_json(JSON.stringify(input)));
195
+ }
196
+
197
+ export function inspectRowReferences(manifest: Record<string, unknown>, kind: string, id: string) {
198
+ requireReady();
199
+ return inspectRowRefs(manifest, ROW_KIND_NATURAL_KEY, kind, id);
200
+ }
201
+
202
+ export {
203
+ authoringDocMetadata,
204
+ isSupportedAuthoringDoc,
205
+ diffManifests,
206
+ extractAuthoringDocSection,
207
+ extra_rows_by_natural_key_json,
208
+ findRowByCompositeKey,
209
+ filteredRowCount,
210
+ filterManifestForActor,
211
+ flattenManifestDiff,
212
+ inspectSchemaManifest,
213
+ listAuthoringDocs,
214
+ listAuthoringDocSections,
215
+ manifestTagPrefixFamilies,
216
+ outboundRefsExcluding,
217
+ parseMapKey,
218
+ queryAuthoringDocs,
219
+ refTagOutboundRefs,
220
+ resolveRefTagValue,
221
+ routeDamage,
222
+ routeDamageMagnitude,
223
+ shape_params_json,
224
+ stripManifestHeaders,
225
+ };
226
+
227
+ function validateActorCapabilityRows(
228
+ rows: Array<{ actor_entity_key: string; capability_id: string }> | undefined,
229
+ ): Diagnostic[] {
230
+ const seen = new Map<string, number>();
231
+ const diagnostics: Diagnostic[] = [];
232
+ for (const [index, row] of (rows ?? []).entries()) {
233
+ const key = `${row.actor_entity_key}::${row.capability_id}`;
234
+ const prior = seen.get(key);
235
+ if (prior === undefined) seen.set(key, index);
236
+ else
237
+ diagnostics.push({
238
+ code: "WA-CAP-001",
239
+ severity: "warning",
240
+ path: `actor_capabilities[${index}]`,
241
+ message: `duplicate actor_capabilities row for (actor_entity_key='${row.actor_entity_key}', capability_id='${row.capability_id}') at index ${index} (first at index ${prior})`,
242
+ details: row,
243
+ });
244
+ }
245
+ return diagnostics;
246
+ }
247
+ function validateCapabilityNicheProvider(
248
+ niches: Array<{ niche_id?: string; provider?: string }> | undefined,
249
+ affordances: Array<{ niche_id?: string }> | undefined,
250
+ ): Diagnostic[] {
251
+ const defined = new Set<string>();
252
+ const diagnostics: Diagnostic[] = [];
253
+ for (const [index, row] of (niches ?? []).entries())
254
+ if (row.niche_id?.startsWith("capability:")) {
255
+ defined.add(row.niche_id);
256
+ if (!row.provider?.trim())
257
+ diagnostics.push(capabilityDiagnostic(row.niche_id, `niche_definitions[${index}]`, row));
258
+ }
259
+ for (const [index, row] of (affordances ?? []).entries())
260
+ if (row.niche_id?.startsWith("capability:") && !defined.has(row.niche_id))
261
+ diagnostics.push(capabilityDiagnostic(row.niche_id, `affordance_templates[${index}]`, row));
262
+ return diagnostics;
263
+ }
264
+ function capabilityDiagnostic(nicheId: string, path: string, details: unknown): Diagnostic {
265
+ return {
266
+ code: "WA-CAP-002",
267
+ severity: "fatal",
268
+ path,
269
+ details,
270
+ message: `capability-shaped niche '${nicheId}' requires an explicit provider`,
271
+ };
272
+ }
273
+
274
+ export function renderManifestInclude(
275
+ rendered: string,
276
+ options: RenderManifestIncludeOptions = {},
277
+ ): string {
278
+ requireReady();
279
+ return renderManifestIncludeWith(render_manifest_include, rendered, options);
280
+ }
281
+ export function splitIncludedManifestMetadata(fragmentToml: string) {
282
+ requireReady();
283
+ return splitIncludedManifestMetadataWith(split_manifest_fragment, fragmentToml);
284
+ }
285
+
286
+ export type {
287
+ DslExpressionKind,
288
+ EvaluateDslExpressionOptions,
289
+ EvaluationRejection,
290
+ EvaluationResult,
291
+ EvaluationValue,
292
+ RollTableSelection,
293
+ StochasticDraw,
294
+ SubjectRef,
295
+ TraceEntry,
296
+ TraceScopeEntry,
297
+ };
298
+
299
+ export function evaluate_dsl_expression_json(
300
+ source: string,
301
+ kind: string,
302
+ factsJson: string,
303
+ diceJson: string,
304
+ manifestToml?: string | null,
305
+ ): string {
306
+ requireReady();
307
+ return evaluate_dsl_expression_json_raw(
308
+ source,
309
+ kind,
310
+ factsJson,
311
+ diceJson,
312
+ manifestToml ?? undefined,
313
+ );
314
+ }
315
+
316
+ export function evaluateDslExpression(options: EvaluateDslExpressionOptions): EvaluationResult {
317
+ requireReady();
318
+ const factsJson =
319
+ typeof options.facts === "string" ? options.facts : JSON.stringify(options.facts ?? {});
320
+ const diceJson =
321
+ typeof options.dice === "string" ? options.dice : JSON.stringify(options.dice ?? []);
322
+ const raw = evaluate_dsl_expression_json_raw(
323
+ options.expression,
324
+ options.kind,
325
+ factsJson,
326
+ diceJson,
327
+ options.manifestToml ?? undefined,
328
+ );
329
+ return JSON.parse(raw) as EvaluationResult;
330
+ }
331
+
332
+ export * from "./explain-core";
333
+
334
+ import {
335
+ type ExplainDisclosure,
336
+ type ExplainKind,
337
+ explainVocabularyWith,
338
+ type VocabularyLookup,
339
+ type VocabularyRow,
340
+ } from "./explain-core";
341
+ export function bootstrapVocabularyRows(kind: string): VocabularyRow[] {
342
+ requireReady();
343
+ if (kind === "extent_kind_definitions") return JSON.parse(core_extent_kinds_json());
344
+ const manifest = JSON.parse(parse_manifest_toml_to_json(core_bootstrap_manifest()));
345
+ return Array.isArray(manifest[kind]) ? manifest[kind] : [];
346
+ }
347
+ export function mergedRoleCapabilityIds(roleId: string, lookup: VocabularyLookup): string[] {
348
+ requireReady();
349
+ return JSON.parse(
350
+ merged_role_capability_ids_json(
351
+ roleId,
352
+ JSON.stringify(lookup("role_definitions")),
353
+ JSON.stringify(lookup("role_aggregations")),
354
+ ),
355
+ );
356
+ }
357
+ export function explainVocabulary(
358
+ kind: ExplainKind,
359
+ id: string,
360
+ source: "files" | "live",
361
+ lookup: VocabularyLookup,
362
+ disclosure?: ExplainDisclosure,
363
+ ) {
364
+ return explainVocabularyWith(kind, id, source, lookup, mergedRoleCapabilityIds, disclosure);
365
+ }
366
+
367
+ export type { GrantInput, GrantRow } from "./grants-core";
368
+
369
+ import { compose_grant_json, grant_delta_json } from "@spellkave/authoring-wasm/browser";
370
+ import { composeGrantWith, grantDeltaWith } from "./grants-core";
371
+ export const composeGrant = (
372
+ ...args: Parameters<typeof composeGrantWith> extends [unknown, ...infer T] ? T : never
373
+ ) => composeGrantWith(compose_grant_json, ...args);
374
+ export const grantDelta = (
375
+ ...args: Parameters<typeof grantDeltaWith> extends [unknown, ...infer T] ? T : never
376
+ ) => grantDeltaWith(grant_delta_json, ...args);
377
+
378
+ export { createInstanceProjector, type OwnerSnapshot } from "./owner-instance-read";
379
+ export * from "./scoped-instance-read";
380
+ export function renderSchemaManifestJson(manifestJson: string): string {
381
+ requireReady();
382
+ return render_manifest_json_to_toml(manifestJson);
383
+ }
384
+ export function manifestRowIdentities(
385
+ toml: string,
386
+ isRoot: boolean,
387
+ ): import("./applyset").ManifestRowIdentities {
388
+ requireReady();
389
+ return decode(manifest_row_identities_json(toml, isRoot));
390
+ }
391
+
392
+ export function liveManifestRowIdentities(
393
+ manifestJson: string,
394
+ ): import("./applyset").ManifestRowIdentities {
395
+ requireReady();
396
+ return decode(live_manifest_row_identities_json(manifestJson));
397
+ }
package/src/tooling.ts ADDED
@@ -0,0 +1,38 @@
1
+ /** Node/default author-tool surface. Browser builds select `tooling.browser`. */
2
+
3
+ // Export owning modules directly: importing the index here creates a conditional-export cycle.
4
+ export type { InstanceRead } from "@spellkave/tool-contracts";
5
+ export { extra_rows_by_natural_key_json, shape_params_json } from "@spellkave/authoring-wasm";
6
+ export * from "./applyset";
7
+ export { manifestRowIdentities } from "./applyset";
8
+ export * from "./authoring-harness";
9
+ export * from "./compose";
10
+ export * from "./corpus";
11
+ export * from "./damage";
12
+ export * from "./diff-manifest";
13
+ export * from "./dsl";
14
+ export * from "./evaluate";
15
+ export * from "./explain";
16
+ export * from "./filter-manifest";
17
+ export * from "./grants";
18
+ export * from "./included-manifest-metadata";
19
+ export * from "./inspect";
20
+ export { inspectManifest } from "./inspect";
21
+ export * from "./lint";
22
+ export * from "./manifest";
23
+ export { renderSchemaManifestJson } from "./manifest";
24
+ export * from "./metadata";
25
+ export * from "./owner-instance-read";
26
+ export * from "./patch";
27
+ export * from "./ref-tags";
28
+ export * from "./reference";
29
+ // Explicit exports retain live bindings through the conditional tooling cycle.
30
+ export { describeManifestSchema } from "./reference";
31
+ export * from "./row-identity";
32
+ export * from "./row-kinds";
33
+ export { ROW_KIND_NATURAL_KEY, ROW_KIND_STORAGE_KEY } from "./row-kinds";
34
+ export * from "./scoped-instance-read";
35
+ export * from "./session-predicates";
36
+ export * from "./spell";
37
+ export * from "./tag-prefix-families";
38
+ export * from "./validate";
@@ -0,0 +1,255 @@
1
+ // Pre-flight manifest validation for the authoring SDK.
2
+ //
3
+ // This is NOT a client-side reimplementation of the validator (which would drift
4
+ // from the server — the thing ADR-0009 D-2 forbids). It calls the SAME Rust
5
+ // `spellkave-validate` core, compiled to wasm (`spellkave-validate-wasm`), over
6
+ // the canonical TOML parse path — the identical code `r_apply_world_manifest`
7
+ // runs at admission. So a clean result here means "the server would admit this"
8
+ // (modulo a few cross-bundle checks the server defers to live admission). The
9
+ // crate stays the single source of truth; this is just an in-process front door
10
+ // to it — no live node, no shell-out.
11
+
12
+ import {
13
+ validate_manifest_toml,
14
+ validate_manifest_toml_with_containment_context,
15
+ } from "@spellkave/validate-wasm";
16
+ import { type Diagnostic, diagnosticsFromJson } from "./diagnostics";
17
+ import { inspectManifest } from "./inspect";
18
+ import { renderManifest, type WorldManifest } from "./manifest";
19
+ import {
20
+ type SchemaMetadataAttachmentRow,
21
+ type SchemaMetadataNamespaceRow,
22
+ validateMetadataRows,
23
+ } from "./metadata";
24
+
25
+ export type { Diagnostic, DiagnosticSeverity, DiagnosticSpan } from "./diagnostics";
26
+
27
+ interface SchemaActorCapabilityRow {
28
+ actor_entity_key: string;
29
+ capability_id: string;
30
+ }
31
+
32
+ interface SchemaAffordanceTemplateRow {
33
+ niche_id?: string;
34
+ template_id?: string;
35
+ }
36
+
37
+ interface SchemaNicheDefinitionRow {
38
+ niche_id?: string;
39
+ provider?: string;
40
+ }
41
+
42
+ export function validateActorCapabilityRows(
43
+ rows: SchemaActorCapabilityRow[] | undefined,
44
+ pathPrefix = "actor_capabilities",
45
+ ): Diagnostic[] {
46
+ const diags: Diagnostic[] = [];
47
+ const seen = new Map<string, number>();
48
+ for (const [index, row] of (rows ?? []).entries()) {
49
+ const key = `${row.actor_entity_key}::${row.capability_id}`;
50
+ const priorIndex = seen.get(key);
51
+ if (priorIndex !== undefined) {
52
+ diags.push({
53
+ code: "WA-CAP-001",
54
+ severity: "warning",
55
+ message:
56
+ `duplicate actor_capabilities row for (actor_entity_key='${row.actor_entity_key}', ` +
57
+ `capability_id='${row.capability_id}') at index ${index} (first at index ${priorIndex}) — ` +
58
+ "the ADR-0085 commit upsert keys on this pair alone, so this row silently replaces " +
59
+ "the earlier one's extent instead of adding a second one; mint a distinct capability_id " +
60
+ "per extent if both grants are intended (sk-dms.28)",
61
+ path: `${pathPrefix}[${index}]`,
62
+ details: row,
63
+ });
64
+ continue;
65
+ }
66
+ seen.set(key, index);
67
+ }
68
+ return diags;
69
+ }
70
+
71
+ function capabilityNicheProviderDiag(
72
+ nicheId: string,
73
+ path: string,
74
+ details: unknown,
75
+ why: string,
76
+ ): Diagnostic {
77
+ return {
78
+ code: "WA-CAP-002",
79
+ severity: "fatal",
80
+ message:
81
+ `capability-shaped niche '${nicheId}' ${why} — provider is required on capability:* ` +
82
+ 'niches (author provider = "actor" | "entity" | "place" explicitly). The empty/place ' +
83
+ "default is not allowed here: it fails closed silently, which is how class features " +
84
+ "became unusable outside one room (sk-0m4.69). Ordinary (non-capability:*) niches " +
85
+ "keep today's empty-provider = place-provided behaviour.",
86
+ path,
87
+ details,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * sk-0m4.69 / WA-CAP-002: `provider` is REQUIRED on any niche whose id carries
93
+ * the `capability:` prefix. Authoring one without a provider (a definition
94
+ * row with provider empty, or an affordance using `capability:*` with no
95
+ * definition row at all) is a fatal error, not a silent place-provided
96
+ * default. Do not flip the default to actor — fail-closed is correct; the
97
+ * defect is that the failure was silent and, for capability:* niches, the
98
+ * default was wrong in every observed case.
99
+ */
100
+ export function validateCapabilityNicheProvider(
101
+ nicheRows: SchemaNicheDefinitionRow[] | undefined,
102
+ affordanceRows: SchemaAffordanceTemplateRow[] | undefined,
103
+ nichePathPrefix = "niche_definitions",
104
+ affordancePathPrefix = "affordance_templates",
105
+ ): Diagnostic[] {
106
+ const diags: Diagnostic[] = [];
107
+ const defined = new Set<string>();
108
+ for (const [index, row] of (nicheRows ?? []).entries()) {
109
+ const nicheId = row.niche_id;
110
+ if (typeof nicheId !== "string" || !nicheId.startsWith("capability:")) continue;
111
+ defined.add(nicheId);
112
+ const provider = typeof row.provider === "string" ? row.provider.trim() : "";
113
+ if (provider === "") {
114
+ diags.push(
115
+ capabilityNicheProviderDiag(
116
+ nicheId,
117
+ `${nichePathPrefix}[${index}]`,
118
+ row,
119
+ "has a niche_definitions row with no provider",
120
+ ),
121
+ );
122
+ }
123
+ }
124
+ for (const [index, row] of (affordanceRows ?? []).entries()) {
125
+ const nicheId = row.niche_id;
126
+ if (typeof nicheId !== "string" || !nicheId.startsWith("capability:")) continue;
127
+ if (defined.has(nicheId)) continue;
128
+ diags.push(
129
+ capabilityNicheProviderDiag(
130
+ nicheId,
131
+ `${affordancePathPrefix}[${index}]`,
132
+ row,
133
+ "is used by an affordance but has no niche_definitions row, so no provider is authored",
134
+ ),
135
+ );
136
+ }
137
+ return diags;
138
+ }
139
+
140
+ /**
141
+ * sk-jay0.7.23.29: `commitOrReport` (`@spellkave/tool-authoring`'s
142
+ * `authoring-verbs.ts`) calls this function once per AUTHOR tool call, each
143
+ * time re-rendering (workspace ∪ augmented target) to a fresh TOML string and
144
+ * re-running the FULL wasm validator over it — so a caller that drives many
145
+ * calls against the SAME target (e.g. `spellkave-srd-cc`'s verb-runner, which
146
+ * re-issues the identical bundle-header/tag-vocabulary/action-economy/
147
+ * dsl-macro seed sequence for every generated unit) redundantly re-validates
148
+ * byte-identical input over and over: a CPU profile of the `classes` chapter
149
+ * put ~70% of self time inside the wasm validator alone.
150
+ *
151
+ * `validateManifestToml` is a pure function of its TOML and optional containment
152
+ * reference context (no side effects), so memoizing it by the exact input string is
153
+ * always correct — a cache hit returns EXACTLY what a fresh call would have
154
+ * computed, byte-identical diagnostics included. Bounded by total cache-key
155
+ * bytes (not entry count): a naive count cap would let a run's many
156
+ * large-but-unique final per-entity manifests (workspace ∪ whole target,
157
+ * never looked up again) evict the small, HIGH-REUSE seed-step entries that
158
+ * actually deliver the win; a byte budget with LRU eviction keeps the
159
+ * frequently-reused keys resident regardless of how many one-shot large keys
160
+ * pass through. Content-addressed by design: a target/workspace change
161
+ * produces a different TOML/context key, so there is no separate invalidation
162
+ * path to get wrong.
163
+ */
164
+ const VALIDATE_MANIFEST_TOML_CACHE_BYTE_BUDGET = 64 * 1024 * 1024;
165
+ const validateManifestTomlCache = new Map<string, Diagnostic[]>();
166
+ let validateManifestTomlCacheBytes = 0;
167
+
168
+ function validateManifestTomlCacheGet(toml: string): Diagnostic[] | undefined {
169
+ const hit = validateManifestTomlCache.get(toml);
170
+ if (hit === undefined) return undefined;
171
+ // Move to most-recently-used (Map iterates in insertion order).
172
+ validateManifestTomlCache.delete(toml);
173
+ validateManifestTomlCache.set(toml, hit);
174
+ return hit;
175
+ }
176
+
177
+ function validateManifestTomlCacheSet(toml: string, diagnostics: Diagnostic[]): void {
178
+ validateManifestTomlCache.set(toml, diagnostics);
179
+ validateManifestTomlCacheBytes += toml.length;
180
+ while (
181
+ validateManifestTomlCacheBytes > VALIDATE_MANIFEST_TOML_CACHE_BYTE_BUDGET &&
182
+ validateManifestTomlCache.size > 1
183
+ ) {
184
+ const oldestKey = validateManifestTomlCache.keys().next().value;
185
+ if (oldestKey === undefined) break;
186
+ validateManifestTomlCacheBytes -= oldestKey.length;
187
+ validateManifestTomlCache.delete(oldestKey);
188
+ }
189
+ }
190
+
191
+ /** Test-only: drop every cached entry (keeps cross-test isolation honest). */
192
+ export function clearValidateManifestTomlCache(): void {
193
+ validateManifestTomlCache.clear();
194
+ validateManifestTomlCacheBytes = 0;
195
+ }
196
+
197
+ /**
198
+ * Validate a manifest from its TOML source. Returns the validator's diagnostics
199
+ * (empty array = valid). Never throws on a rejected manifest — a rejection is a
200
+ * normal result, surfaced as diagnostics, so authoring loops can treat it as a
201
+ * finding rather than an exception.
202
+ *
203
+ * Memoized by exact TOML and optional containment context — see the cache doc comment above. Every
204
+ * caller gets its own shallow-copied array so no caller can mutate the
205
+ * cached entry (none currently do; the copy is defensive and cheap relative
206
+ * to the wasm validate call it protects).
207
+ */
208
+ export function validateManifestToml(toml: string, containmentContextJson?: string): Diagnostic[] {
209
+ const cacheKey =
210
+ containmentContextJson === undefined ? toml : JSON.stringify([toml, containmentContextJson]);
211
+ const cached = validateManifestTomlCacheGet(cacheKey);
212
+ if (cached !== undefined) return cached.slice();
213
+ const diagnostics = diagnosticsFromJson(
214
+ containmentContextJson === undefined
215
+ ? validate_manifest_toml(toml)
216
+ : validate_manifest_toml_with_containment_context(toml, containmentContextJson),
217
+ );
218
+ try {
219
+ const manifest = inspectManifest(toml).manifest as Record<string, unknown>;
220
+ diagnostics.push(
221
+ ...validateMetadataRows(
222
+ manifest.metadata_attachments as SchemaMetadataAttachmentRow[] | undefined,
223
+ manifest.metadata_namespaces as SchemaMetadataNamespaceRow[] | undefined,
224
+ ),
225
+ );
226
+ diagnostics.push(
227
+ ...validateActorCapabilityRows(
228
+ manifest.actor_capabilities as SchemaActorCapabilityRow[] | undefined,
229
+ ),
230
+ );
231
+ diagnostics.push(
232
+ ...validateCapabilityNicheProvider(
233
+ manifest.niche_definitions as SchemaNicheDefinitionRow[] | undefined,
234
+ manifest.affordance_templates as SchemaAffordanceTemplateRow[] | undefined,
235
+ ),
236
+ );
237
+ } catch {
238
+ // Parse errors are already represented by validate_manifest_toml.
239
+ }
240
+ validateManifestTomlCacheSet(cacheKey, diagnostics);
241
+ return diagnostics.slice();
242
+ }
243
+
244
+ /**
245
+ * Render a typed `WorldManifest` to TOML and validate it in one step — the
246
+ * common authoring path (build rows → check before apply).
247
+ */
248
+ export function validateManifest(manifest: WorldManifest): Diagnostic[] {
249
+ return validateManifestToml(renderManifest(manifest));
250
+ }
251
+
252
+ /** True iff the manifest has no fatal/warning diagnostics (clean for admission). */
253
+ export function isValid(diagnostics: Diagnostic[]): boolean {
254
+ return diagnostics.length === 0;
255
+ }