@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
package/src/damage.ts ADDED
@@ -0,0 +1,75 @@
1
+ export interface RouteDamageOptions {
2
+ /**
3
+ * DSL variable name used to bind the raw damage roll once.
4
+ *
5
+ * The default emits `let dmg = <amountExpr>; ...`.
6
+ */
7
+ variableName?: string;
8
+ /** DSL subject whose tags are read. Defaults to `target`. */
9
+ subject?: "actor" | "target";
10
+ /**
11
+ * Defense tag stem. The emitted tags are
12
+ * `<tagPrefix>_immune:<type>`, `<tagPrefix>_resist:<type>`, and
13
+ * `<tagPrefix>_vulnerable:<type>`.
14
+ */
15
+ tagPrefix?: string;
16
+ }
17
+
18
+ /**
19
+ * Build the routing ladder over an already-bound `${variableName}`, shared by
20
+ * {@link routeDamage} (negated, the `ModifyResource` delta convention) and
21
+ * {@link routeDamageMagnitude} (bare positive magnitude, for a caller that
22
+ * negates/clamps itself — e.g. an `entity_definition_item_dsl_source` slot
23
+ * read back through `.source(...)`).
24
+ */
25
+ function routeDamageLadder(
26
+ variableName: string,
27
+ subject: "actor" | "target",
28
+ tagPrefix: string,
29
+ damageType: string,
30
+ ): string {
31
+ const immuneTag = `${tagPrefix}_immune:${damageType}`;
32
+ const resistTag = `${tagPrefix}_resist:${damageType}`;
33
+ const vulnerableTag = `${tagPrefix}_vulnerable:${damageType}`;
34
+ return `cond(${subject}.has_tag('${immuneTag}'), 0, cond(${subject}.has_tag('${resistTag}'), ${variableName} / 2, cond(${subject}.has_tag('${vulnerableTag}'), ${variableName} * 2, ${variableName})))`;
35
+ }
36
+
37
+ /**
38
+ * Build the canonical damage-type routing `delta_source` expression.
39
+ *
40
+ * This is deliberately just a string emitter. The validator remains the single
41
+ * source of truth for parsing and type-checking the generated DSL expression.
42
+ */
43
+ export function routeDamage(
44
+ amountExpr: string,
45
+ damageType: string,
46
+ opts: RouteDamageOptions = {},
47
+ ): string {
48
+ const variableName = opts.variableName ?? "dmg";
49
+ const subject = opts.subject ?? "target";
50
+ const tagPrefix = opts.tagPrefix ?? "damage";
51
+ return `let ${variableName} = ${amountExpr}; -${routeDamageLadder(variableName, subject, tagPrefix, damageType)}`;
52
+ }
53
+
54
+ /**
55
+ * The un-negated sibling of {@link routeDamage}: the SAME routing ladder over
56
+ * the SAME bound `amountExpr`, but without the leading `-` — a bare positive
57
+ * magnitude (0 on immune, halved on resist, doubled on vulnerable, else
58
+ * unchanged) rather than a ready-to-apply `ModifyResource` delta.
59
+ *
60
+ * First consumer: a weapon-like item's own `entity_definition_item_dsl_source`
61
+ * slot (`srd/damage`, `dsl-grammar.md`'s `DslSource`/`.source(...)` node) —
62
+ * the slot carries the full positive damage magnitude (die + ability
63
+ * modifier, already type-routed); the READING archetype negates and clamps
64
+ * the whole thing exactly once, so the routing math must not pre-negate it.
65
+ */
66
+ export function routeDamageMagnitude(
67
+ amountExpr: string,
68
+ damageType: string,
69
+ opts: RouteDamageOptions = {},
70
+ ): string {
71
+ const variableName = opts.variableName ?? "dmg";
72
+ const subject = opts.subject ?? "target";
73
+ const tagPrefix = opts.tagPrefix ?? "damage";
74
+ return `let ${variableName} = ${amountExpr}; ${routeDamageLadder(variableName, subject, tagPrefix, damageType)}`;
75
+ }
@@ -0,0 +1,59 @@
1
+ /** Severity of a validator diagnostic — mirrors `spellkave_validate::Severity`. */
2
+ export type DiagnosticSeverity = "info" | "warning" | "fatal";
3
+
4
+ /** Source span of a diagnostic — mirrors `spellkave_validate::Span`. */
5
+ export interface DiagnosticSpan {
6
+ startLine: number;
7
+ startCol: number;
8
+ endLine: number;
9
+ endCol: number;
10
+ }
11
+
12
+ /** One validator diagnostic — mirrors `spellkave_validate::Diagnostic` (canonical JSON). */
13
+ export interface Diagnostic {
14
+ /** Stable diagnostic code, e.g. "MF-FMT-001", "MF-VAL-210". */
15
+ code: string;
16
+ severity: DiagnosticSeverity;
17
+ message: string;
18
+ /** Dotted path into the manifest the diagnostic points at, e.g. "$". */
19
+ path: string;
20
+ span?: DiagnosticSpan;
21
+ hint?: string;
22
+ details?: unknown;
23
+ }
24
+
25
+ /** Raw canonical-JSON diagnostic shape (snake_case, as the wasm emits it). */
26
+ interface RawDiagnostic {
27
+ code: string;
28
+ severity: DiagnosticSeverity;
29
+ message: string;
30
+ path: string;
31
+ span?: { start_line: number; start_col: number; end_line: number; end_col: number } | null;
32
+ hint?: string | null;
33
+ details?: unknown;
34
+ }
35
+
36
+ function toDiagnostic(raw: RawDiagnostic): Diagnostic {
37
+ const d: Diagnostic = {
38
+ code: raw.code,
39
+ severity: raw.severity,
40
+ message: raw.message,
41
+ path: raw.path,
42
+ };
43
+ if (raw.span) {
44
+ d.span = {
45
+ startLine: raw.span.start_line,
46
+ startCol: raw.span.start_col,
47
+ endLine: raw.span.end_line,
48
+ endCol: raw.span.end_col,
49
+ };
50
+ }
51
+ if (raw.hint != null) d.hint = raw.hint;
52
+ if (raw.details !== undefined && raw.details !== null) d.details = raw.details;
53
+ return d;
54
+ }
55
+
56
+ export function diagnosticsFromJson(json: string): Diagnostic[] {
57
+ const raw = JSON.parse(json) as RawDiagnostic[];
58
+ return raw.map(toDiagnostic);
59
+ }
@@ -0,0 +1,393 @@
1
+ // Semantic manifest diff by row identity (sk-0m4.46).
2
+ //
3
+ // Two SchemaManifests (the snake_case shape `filter-manifest.ts` / export
4
+ // uses) are compared order-insensitively: each row kind is indexed by its
5
+ // natural or composite key, then reported as onlyLeft (in the reference,
6
+ // missing from the export ⇒ GAP), onlyRight (export-only ⇒ SNAPSHOT/PLAY),
7
+ // or changed (same key, field-level differences).
8
+ //
9
+ // Identity sources, in order:
10
+ // 1. ROW_KIND_NATURAL_KEY (Rust-owned single-column keys)
11
+ // 2. ROW_KIND_COMPOSITE_KEY (Rust-owned `*_tag` pairs + tag_capability_grant)
12
+ // 3. DIFF_JUNCTION_IDENTITY — junction kinds the Rust tables deliberately
13
+ // omit (non-uniform satellites). Each entry cites the server upsert key.
14
+ //
15
+ // `identityOf` is NOT used here: for `entities`/`actors` it demands a LIVE
16
+ // surrogate id. A manifest-to-manifest diff keys those kinds on `entity_key`
17
+ // (ROW_KIND_NATURAL_KEY), which is the authoring-time identity.
18
+
19
+ import { parse as parseToml } from "smol-toml";
20
+
21
+ import type { SchemaManifest } from "./filter-manifest";
22
+ import {
23
+ exportNotRoundTrippedFields,
24
+ rowKindCompositeKey,
25
+ rowKindNaturalKey,
26
+ } from "./row-kinds-data";
27
+
28
+ /**
29
+ * Junction / satellite kinds with no entry in ROW_KIND_NATURAL_KEY or
30
+ * ROW_KIND_COMPOSITE_KEY. Cited against the server upsert, not invented.
31
+ *
32
+ * - actor_capabilities: commit.rs ADR-0085 D-1 upsert on (entity_id, capability_id)
33
+ * - object_state: entity_authoring.rs matches (target_id, state_id)
34
+ * - entity_containment: brief asks container+entity (export identity); the
35
+ * live upsert is entity_id PK (one container per contained entity)
36
+ * - actor_equipment_slots: commit.rs ADR-0085 G-1 (entity_id, slot_id)
37
+ * - actor_spatial_locations: commit.rs keyed on entity_id
38
+ */
39
+ export const DIFF_JUNCTION_IDENTITY: Readonly<Record<string, readonly string[]>> = Object.freeze({
40
+ actor_capabilities: Object.freeze(["actor_entity_key", "capability_id"]),
41
+ object_state: Object.freeze(["entity_key", "state_id"]),
42
+ entity_containment: Object.freeze(["container_entity_key", "entity_key"]),
43
+ actor_equipment_slots: Object.freeze(["actor_entity_key", "slot_id"]),
44
+ actor_spatial_locations: Object.freeze(["entity_key"]),
45
+ });
46
+
47
+ /**
48
+ * Snapshot / enrichment noise every diff ignores by default: the fields
49
+ * `r_export_manifest` does not round-trip, read from the Rust-owned list
50
+ * (`spellkave_schema::export_round_trip`, sk-jay0.7.174.15) that
51
+ * `sk diff -k` masks with too.
52
+ */
53
+ export function defaultDiffIgnoreFields(kind: string): readonly string[] {
54
+ return exportNotRoundTrippedFields(kind);
55
+ }
56
+
57
+ /**
58
+ * Parse a manifest or include-fragment TOML into SchemaManifest (snake_case).
59
+ *
60
+ * Integers above 2^53 (H3 cell ids such as `cell_res10 = 622215095455449087`
61
+ * in every elven-mini world fragment) are read as BigInt and then carried as
62
+ * their decimal string, so a diff or subset check compares them exactly
63
+ * instead of refusing the whole file ("integer value cannot be represented
64
+ * losslessly", sk-jay0.7.171.2). This parser feeds read-only comparisons
65
+ * (`sk diff`, the `live-delta-subset` gate); nothing re-renders its output
66
+ * as TOML, which is why a string stands in for the wide integer here.
67
+ */
68
+ export function parseSchemaManifestToml(toml: string): SchemaManifest {
69
+ const parsed = widenBigInts(parseToml(toml, { integersAsBigInt: "asNeeded" }));
70
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
71
+ throw new Error("parseSchemaManifestToml: TOML root is not a table");
72
+ }
73
+ return parsed as SchemaManifest;
74
+ }
75
+
76
+ function widenBigInts(value: unknown): unknown {
77
+ if (typeof value === "bigint") return value.toString();
78
+ if (Array.isArray(value)) return value.map(widenBigInts);
79
+ if (value !== null && typeof value === "object") {
80
+ const out: Record<string, unknown> = {};
81
+ for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {
82
+ out[key] = widenBigInts(inner);
83
+ }
84
+ return out;
85
+ }
86
+ return value;
87
+ }
88
+
89
+ export type DiffIgnoreFields = {
90
+ global?: readonly string[];
91
+ byKind?: Readonly<Record<string, readonly string[]>>;
92
+ };
93
+
94
+ export type KeyMap = {
95
+ from: string;
96
+ to: string;
97
+ };
98
+
99
+ export type DiffManifestsOpts = {
100
+ /** Extra ignores, merged with the default snapshot/enrichment list. */
101
+ ignoreFields?: DiffIgnoreFields;
102
+ /** Restrict the report to these kinds (sorted). */
103
+ kinds?: readonly string[];
104
+ /** Rewrite entity/actor key prefixes (and fields that carry them) before compare. */
105
+ mapKeys?: readonly KeyMap[];
106
+ };
107
+
108
+ export type FieldChange = {
109
+ field: string;
110
+ left: unknown;
111
+ right: unknown;
112
+ };
113
+
114
+ export type KindDiff = {
115
+ kind: string;
116
+ onlyLeft: Array<{ key: string; row: Record<string, unknown> }>;
117
+ onlyRight: Array<{ key: string; row: Record<string, unknown> }>;
118
+ changed: Array<{ key: string; fields: FieldChange[] }>;
119
+ };
120
+
121
+ export type ManifestDiff = {
122
+ kinds: KindDiff[];
123
+ /** Array-valued kinds present in either side with no registered identity. */
124
+ unkeyedKinds: string[];
125
+ };
126
+
127
+ function isRecord(value: unknown): value is Record<string, unknown> {
128
+ return typeof value === "object" && value !== null && !Array.isArray(value);
129
+ }
130
+
131
+ /** Parse one `--map-key from=to` token. First `=` splits; both sides required. */
132
+ export function parseMapKey(token: string): KeyMap {
133
+ const eq = token.indexOf("=");
134
+ if (eq <= 0 || eq === token.length - 1) {
135
+ throw new Error(`map-key: expected from=to, got ${JSON.stringify(token)}`);
136
+ }
137
+ return { from: token.slice(0, eq), to: token.slice(eq + 1) };
138
+ }
139
+
140
+ function rewriteKeyString(value: string, from: string, to: string): string {
141
+ if (value === from) return to;
142
+ if (value.startsWith(`${from}/`)) return to + value.slice(from.length);
143
+ const embed = `:${from}`;
144
+ if (value.includes(embed)) return value.split(embed).join(`:${to}`);
145
+ return value;
146
+ }
147
+
148
+ /** Rewrite every string field that is, or embeds, a mapped entity/actor key. */
149
+ export function applyKeyMaps(manifest: SchemaManifest, maps: readonly KeyMap[]): SchemaManifest {
150
+ if (maps.length === 0) return manifest;
151
+ const ordered = [...maps].sort((a, b) => b.from.length - a.from.length);
152
+ const out: SchemaManifest = { ...manifest };
153
+ for (const [kind, rows] of Object.entries(manifest)) {
154
+ if (!Array.isArray(rows)) continue;
155
+ out[kind] = rows.map((row) => {
156
+ if (!isRecord(row)) return row;
157
+ const next: Record<string, unknown> = { ...row };
158
+ for (const [field, value] of Object.entries(row)) {
159
+ if (typeof value !== "string") continue;
160
+ let mapped = value;
161
+ for (const { from, to } of ordered) {
162
+ mapped = rewriteKeyString(mapped, from, to);
163
+ }
164
+ next[field] = mapped;
165
+ }
166
+ return next;
167
+ });
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /** Identity field list for `kind`, or undefined if the kind is unkeyed. */
173
+ export function identityFieldsOf(kind: string): readonly string[] | undefined {
174
+ const natural = rowKindNaturalKey()[kind];
175
+ if (natural !== undefined) return [natural];
176
+ const composite = rowKindCompositeKey()[kind];
177
+ if (composite !== undefined) return composite;
178
+ return DIFF_JUNCTION_IDENTITY[kind];
179
+ }
180
+
181
+ export function rowIdentityKey(kind: string, row: Record<string, unknown>): string | undefined {
182
+ const fields = identityFieldsOf(kind);
183
+ if (fields === undefined) return undefined;
184
+ return fields.map((field) => String(row[field] ?? "")).join("::");
185
+ }
186
+
187
+ function rowKindsIn(manifest: SchemaManifest): string[] {
188
+ const kinds: string[] = [];
189
+ for (const [key, value] of Object.entries(manifest)) {
190
+ if (Array.isArray(value)) kinds.push(key);
191
+ }
192
+ return kinds;
193
+ }
194
+
195
+ function rowsOf(manifest: SchemaManifest, kind: string): Record<string, unknown>[] {
196
+ const value = manifest[kind];
197
+ if (!Array.isArray(value)) return [];
198
+ return value.filter(isRecord);
199
+ }
200
+
201
+ function indexByKey(
202
+ kind: string,
203
+ rows: Record<string, unknown>[],
204
+ ): Map<string, Record<string, unknown>> {
205
+ const index = new Map<string, Record<string, unknown>>();
206
+ for (const row of rows) {
207
+ const key = rowIdentityKey(kind, row);
208
+ if (key === undefined) continue;
209
+ index.set(key, row);
210
+ }
211
+ return index;
212
+ }
213
+
214
+ function ignoreSet(kind: string, extra: DiffIgnoreFields | undefined): Set<string> {
215
+ const set = new Set<string>(defaultDiffIgnoreFields(kind));
216
+ for (const field of extra?.global ?? []) set.add(field);
217
+ for (const field of extra?.byKind?.[kind] ?? []) set.add(field);
218
+ for (const field of identityFieldsOf(kind) ?? []) set.add(field);
219
+ return set;
220
+ }
221
+
222
+ function carriesValueIntOrText(row: Record<string, unknown>): boolean {
223
+ if (row.value_int !== undefined && row.value_int !== null) return true;
224
+ return typeof row.value_text === "string" && row.value_text.length > 0;
225
+ }
226
+
227
+ function comparableFields(
228
+ _kind: string,
229
+ row: Record<string, unknown>,
230
+ ignored: Set<string>,
231
+ ): string[] {
232
+ const fields = Object.keys(row).filter((field) => !ignored.has(field));
233
+ if (fields.includes("value_bool") && carriesValueIntOrText(row)) {
234
+ return fields.filter((field) => field !== "value_bool");
235
+ }
236
+ return fields;
237
+ }
238
+
239
+ function valuesEqual(left: unknown, right: unknown): boolean {
240
+ if (left === right) return true;
241
+ if (left === undefined || right === undefined) return left === right;
242
+ if (typeof left === "bigint" || typeof right === "bigint") return String(left) === String(right);
243
+ if (typeof left === "object" || typeof right === "object") {
244
+ return JSON.stringify(left) === JSON.stringify(right);
245
+ }
246
+ return false;
247
+ }
248
+
249
+ function fieldChanges(
250
+ kind: string,
251
+ left: Record<string, unknown>,
252
+ right: Record<string, unknown>,
253
+ ignored: Set<string>,
254
+ ): FieldChange[] {
255
+ const names = new Set([
256
+ ...comparableFields(kind, left, ignored),
257
+ ...comparableFields(kind, right, ignored),
258
+ ]);
259
+ const changes: FieldChange[] = [];
260
+ for (const field of [...names].sort()) {
261
+ if (valuesEqual(left[field], right[field])) continue;
262
+ changes.push({ field, left: left[field], right: right[field] });
263
+ }
264
+ return changes;
265
+ }
266
+
267
+ /**
268
+ * Order-insensitive semantic diff. Empty `kinds` in the result means the two
269
+ * manifests agree under the ignore list. Report order is sorted by kind, then
270
+ * by identity key.
271
+ */
272
+ export function diffManifests(
273
+ left: SchemaManifest,
274
+ right: SchemaManifest,
275
+ opts: DiffManifestsOpts = {},
276
+ ): ManifestDiff {
277
+ const mappedLeft = applyKeyMaps(left, opts.mapKeys ?? []);
278
+ const mappedRight = applyKeyMaps(right, opts.mapKeys ?? []);
279
+ const requested = opts.kinds === undefined ? undefined : new Set(opts.kinds);
280
+ const allKinds = new Set([...rowKindsIn(mappedLeft), ...rowKindsIn(mappedRight)]);
281
+ const unkeyedKinds: string[] = [];
282
+ const kinds: KindDiff[] = [];
283
+
284
+ for (const kind of [...allKinds].sort()) {
285
+ if (requested !== undefined && !requested.has(kind)) continue;
286
+ if (identityFieldsOf(kind) === undefined) {
287
+ if (
288
+ (mappedLeft[kind] as unknown[] | undefined)?.length ||
289
+ (mappedRight[kind] as unknown[] | undefined)?.length
290
+ ) {
291
+ unkeyedKinds.push(kind);
292
+ }
293
+ continue;
294
+ }
295
+
296
+ const leftIndex = indexByKey(kind, rowsOf(mappedLeft, kind));
297
+ const rightIndex = indexByKey(kind, rowsOf(mappedRight, kind));
298
+ const ignored = ignoreSet(kind, opts.ignoreFields);
299
+
300
+ const onlyLeft: KindDiff["onlyLeft"] = [];
301
+ const onlyRight: KindDiff["onlyRight"] = [];
302
+ const changed: KindDiff["changed"] = [];
303
+
304
+ for (const key of [...leftIndex.keys()].sort()) {
305
+ const leftRow = leftIndex.get(key) as Record<string, unknown>;
306
+ const rightRow = rightIndex.get(key);
307
+ if (rightRow === undefined) {
308
+ onlyLeft.push({ key, row: leftRow });
309
+ continue;
310
+ }
311
+ const fields = fieldChanges(kind, leftRow, rightRow, ignored);
312
+ if (fields.length > 0) changed.push({ key, fields });
313
+ }
314
+ for (const key of [...rightIndex.keys()].sort()) {
315
+ if (!leftIndex.has(key)) {
316
+ onlyRight.push({ key, row: rightIndex.get(key) as Record<string, unknown> });
317
+ }
318
+ }
319
+
320
+ if (onlyLeft.length === 0 && onlyRight.length === 0 && changed.length === 0) continue;
321
+ kinds.push({ kind, onlyLeft, onlyRight, changed });
322
+ }
323
+
324
+ return { kinds, unkeyedKinds };
325
+ }
326
+
327
+ export type DiffOnlyFilter = "gaps" | "snapshot" | "changed";
328
+
329
+ /** Flatten a ManifestDiff into the compact tables `sk diff` prints. */
330
+ export function flattenManifestDiff(
331
+ diff: ManifestDiff,
332
+ only?: DiffOnlyFilter,
333
+ ): {
334
+ gaps: Array<{ kind: string; key: string }>;
335
+ snapshot: Array<{ kind: string; key: string }>;
336
+ changes: Array<{ kind: string; key: string; field: string; left: unknown; right: unknown }>;
337
+ kindCounts: Array<{
338
+ kind: string;
339
+ only_left: number;
340
+ only_right: number;
341
+ changed: number;
342
+ }>;
343
+ } {
344
+ const gaps: Array<{ kind: string; key: string }> = [];
345
+ const snapshot: Array<{ kind: string; key: string }> = [];
346
+ const changes: Array<{
347
+ kind: string;
348
+ key: string;
349
+ field: string;
350
+ left: unknown;
351
+ right: unknown;
352
+ }> = [];
353
+ const kindCounts: Array<{
354
+ kind: string;
355
+ only_left: number;
356
+ only_right: number;
357
+ changed: number;
358
+ }> = [];
359
+
360
+ for (const entry of diff.kinds) {
361
+ if (only === undefined || only === "gaps") {
362
+ for (const row of entry.onlyLeft) gaps.push({ kind: entry.kind, key: row.key });
363
+ }
364
+ if (only === undefined || only === "snapshot") {
365
+ for (const row of entry.onlyRight) snapshot.push({ kind: entry.kind, key: row.key });
366
+ }
367
+ if (only === undefined || only === "changed") {
368
+ for (const row of entry.changed) {
369
+ for (const field of row.fields) {
370
+ changes.push({
371
+ kind: entry.kind,
372
+ key: row.key,
373
+ field: field.field,
374
+ left: field.left,
375
+ right: field.right,
376
+ });
377
+ }
378
+ }
379
+ }
380
+ const onlyLeft = only === undefined || only === "gaps" ? entry.onlyLeft.length : 0;
381
+ const onlyRight = only === undefined || only === "snapshot" ? entry.onlyRight.length : 0;
382
+ const changed = only === undefined || only === "changed" ? entry.changed.length : 0;
383
+ if (onlyLeft === 0 && onlyRight === 0 && changed === 0) continue;
384
+ kindCounts.push({
385
+ kind: entry.kind,
386
+ only_left: onlyLeft,
387
+ only_right: onlyRight,
388
+ changed,
389
+ });
390
+ }
391
+
392
+ return { gaps, snapshot, changes, kindCounts };
393
+ }
@@ -0,0 +1,5 @@
1
+ // The Node entry initializes Rust-owned row identities synchronously; the
2
+ // browser tooling initializes the same shared pure algorithm from web wasm.
3
+ import "./row-kinds";
4
+
5
+ export * from "./diff-manifest-core";
@@ -0,0 +1,105 @@
1
+ import { type AuthoringDoc, type AuthoringExample, isSupportedAuthoringDoc } from "./corpus";
2
+
3
+ // Must match this doc's own PROSE_DOCS id in `corpus.ts` ("index").
4
+ const DOCS_INDEX_ID = "index";
5
+
6
+ const ONRAMP_ID = "onramp";
7
+
8
+ /** The onramp's PROSE_DOCS id has no matching filename stem — its real file
9
+ * is `README.md` (same special-casing `corpus.ts`'s own generator uses). */
10
+ function docFilename(doc: AuthoringDoc): string {
11
+ if (doc.source_path) return `../../${doc.source_path.replace(/^packages\//, "")}`;
12
+ if (doc.id === ONRAMP_ID) return "README.md";
13
+ if (doc.id === "patterns") return "patterns/index.md";
14
+ if (doc.kind === "repair" && doc.id !== "running-an-authored-act") {
15
+ return `repairs/${doc.id}.md`;
16
+ }
17
+ return `${doc.id}.md`;
18
+ }
19
+
20
+ function docRow(doc: AuthoringDoc): string {
21
+ return `| [\`${doc.id}\`](./${docFilename(doc)}) | ${doc.summary} |`;
22
+ }
23
+
24
+ function docSection(title: string, docs: AuthoringDoc[]): string {
25
+ if (docs.length === 0) return "";
26
+ const rows = docs
27
+ .slice()
28
+ .sort((a, b) => a.id.localeCompare(b.id))
29
+ .map(docRow)
30
+ .join("\n");
31
+ return `### ${title}\n\n| Doc | Summary |\n|---|---|\n${rows}\n`;
32
+ }
33
+
34
+ export function renderAuthoringDocsIndex(
35
+ allDocs: readonly AuthoringDoc[],
36
+ examples: readonly AuthoringExample[],
37
+ ): string {
38
+ const docs = allDocs.filter((d) => d.id !== DOCS_INDEX_ID);
39
+ const supported = docs.filter(isSupportedAuthoringDoc);
40
+
41
+ const onramp = supported.filter((d) => d.id === "onramp");
42
+ const toolReference = supported.filter((d) => d.id === "tool-reference");
43
+ const guides = supported.filter((d) => d.kind === "guide" && d.id !== "onramp");
44
+ const planning = docs.filter(
45
+ (d) => d.publication && d.publication.content_status !== "implemented",
46
+ );
47
+ const references = supported.filter((d) => d.kind === "reference" && d.id !== "tool-reference");
48
+ const repairs = supported.filter((d) => d.kind === "repair");
49
+ const exampleDocs = supported
50
+ .filter((d) => d.kind === "example")
51
+ .slice()
52
+ .sort((a, b) => a.id.localeCompare(b.id));
53
+
54
+ const exampleRows = exampleDocs
55
+ .map((doc) => {
56
+ const example = examples.find((e) => e.id === doc.id);
57
+ const tags = example ? example.tags.join(", ") : "";
58
+ return `| [\`${doc.id}\`](./examples/${doc.id}.md) | ${doc.summary} | ${tags} |`;
59
+ })
60
+ .join("\n");
61
+
62
+ const sections = [
63
+ docSection("Onramp — start here", onramp),
64
+ docSection("Guides", guides),
65
+ docSection("Planning references — unimplemented or historical", planning),
66
+ docSection("Reference", references),
67
+ docSection("Troubleshooting", repairs),
68
+ docSection("Tool reference (generated)", toolReference),
69
+ ]
70
+ .filter((s) => s.length > 0)
71
+ .join("\n");
72
+
73
+ const total = docs.length + 1; // +1 for this index page itself
74
+
75
+ return `# Authoring docs — corpus index
76
+
77
+ <!-- GENERATED by scripts/generate-authoring-docs-index.ts. Do not edit by hand. -->
78
+
79
+ Every doc in the composed public corpus, grouped by kind, with a one-line
80
+ summary from its owning metadata. World-author owns authoring prose and
81
+ patterns; CLI owns its workflow guide. This is the same corpus \`spellkave_docs\` serves to an
82
+ authoring agent — this page exists for browsing it as plain markdown (GitHub
83
+ render, no external site generator) instead of calling the tool or reading
84
+ \`corpus.ts\` source. ${total} docs, ${exampleDocs.length} of them worked
85
+ \`.toml\` examples.
86
+
87
+ New here? Start at [\`README.md\`](./README.md) (\`onramp\` — AUTHOR + PLAYER tools).
88
+ AUTHOR verb deep-dive: [\`getting-started-with-verbs.md\`](./getting-started-with-verbs.md).
89
+ Something broken? Troubleshooting repairs below, or \`sk docs --query "<symptom>"\`.
90
+
91
+ The PLAYER/DM tool surface is a separate registry in a separate package, not
92
+ part of this corpus — see
93
+ [\`../../spellkave-tool-player/docs/tool-reference.md\`](../../spellkave-tool-player/docs/tool-reference.md).
94
+
95
+ ${sections}
96
+ ### Worked examples (\`docs/examples/**\`)
97
+
98
+ Each example is a validated \`.toml\` fixture plus a \`.md\` walkthrough. Tags
99
+ come from the example's own sidecar metadata.
100
+
101
+ | Example | Intent | Tags |
102
+ |---|---|---|
103
+ ${exampleRows}
104
+ `;
105
+ }
package/src/dsl.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Mark a TypeScript string as Spellkave DSL without changing the emitted
3
+ * source. Editors and generators can grep for `dsl\`...\``.
4
+ *
5
+ * The tagged template interpolates like String.raw and returns the same
6
+ * text a plain string literal would have produced.
7
+ */
8
+ export function dsl(strings: TemplateStringsArray, ...values: unknown[]): string {
9
+ return String.raw({ raw: strings }, ...values);
10
+ }