@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/lint.ts ADDED
@@ -0,0 +1,540 @@
1
+ // Author-time manifest lint (#836 Part C).
2
+ //
3
+ // Reasons over a PARSED manifest at AUTHOR time and emits NON-FATAL warnings for
4
+ // the duplication / binding smells the validator does not flag. It is the
5
+ // author-time companion to the runtime spell-identity binding checks #835 landed
6
+ // (MF-VAL-264/265 in `spellkave-validate`) and to `emitSpell`'s
7
+ // `assertSpellCatalogBinding` — surfacing the same drift across a whole merged
8
+ // bundle, plus the render-discipline smells (twin actions, repeated tag sets,
9
+ // delimiter drift) that have no validator rule.
10
+ //
11
+ // DELIBERATELY DISTINCT from two neighbours, do not conflate them:
12
+ // - `manifest validate` reasons over a manifest but FATALS (exit 2) on broken
13
+ // refs. Lint is advisory: every finding is a `warning`, the run never fails.
14
+ // - `just doctor` (ADR-0002) reasons over a LIVE world via the DoctorCheck
15
+ // registry. Lint never touches a running node — it reads rows only.
16
+ //
17
+ // Pure, fs-free (this package ships only `src/`): the caller supplies the parsed
18
+ // manifest object (`inspectManifest(...).manifest`), so the fs-having CLI owns
19
+ // file reads and `--bundle` include-merging, same split as `routeDamage`/`emitSpell`.
20
+
21
+ import { type RefTagFamily, resolveRefTagValueOutcome } from "./ref-tags";
22
+ import { bundleScope, resolveTagPrefixFamily, visibleRefTagFamilies } from "./tag-prefix-families";
23
+
24
+ const SPELL_CATALOG_PREFIX = "srd/spell/";
25
+
26
+ export type LintRule =
27
+ | "twin-action"
28
+ | "dangling-required-capability"
29
+ | "orphan-spell-capability"
30
+ | "spell-delimiter-drift"
31
+ | "tag-repetition"
32
+ | "dead-target-capability"
33
+ | "dangling-ref-tag"
34
+ | "ambiguous-ref-tag"
35
+ | "duplicate-exit-label";
36
+
37
+ export interface LintFinding {
38
+ rule: LintRule;
39
+ severity: "warning";
40
+ /** The row id the finding is about (action_id / capability_id / entity_def_id). */
41
+ id: string;
42
+ /** Owning bundle of the subject row, when authored. Never inferred from its id. */
43
+ bundleId?: string;
44
+ message: string;
45
+ }
46
+
47
+ function isRecord(value: unknown): value is Record<string, unknown> {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
50
+
51
+ /** Read a manifest row table as records, tolerating absent / malformed tables. */
52
+ function rows(manifest: Record<string, unknown>, kind: string): Record<string, unknown>[] {
53
+ const table = manifest[kind];
54
+ return Array.isArray(table) ? table.filter(isRecord) : [];
55
+ }
56
+
57
+ function str(row: Record<string, unknown>, key: string): string | undefined {
58
+ const value = row[key];
59
+ return typeof value === "string" ? value : undefined;
60
+ }
61
+
62
+ /** The tag multiset under one carrier id, as a stable sorted key (order-insensitive). */
63
+ function tagKey(
64
+ tagRows: Record<string, unknown>[],
65
+ idKey: string,
66
+ idValue: string,
67
+ ): string | undefined {
68
+ const tags = tagRows
69
+ .filter((r) => str(r, idKey) === idValue)
70
+ .map((r) => str(r, "tag"))
71
+ .filter((t): t is string => typeof t === "string");
72
+ if (tags.length === 0) return undefined;
73
+ return [...tags].sort().join(" ");
74
+ }
75
+
76
+ // R1 — twin action_definitions: two (or more) rows byte-identical except `action_id`.
77
+ // The #836 evidence #2 (`cast_X` ↔ `cast_X/affordance` ~50% of spell actions), but
78
+ // detected generally: any actions that canonicalize to the same row sans id are a
79
+ // copy-paste twin whose differing field should be the only thing authored.
80
+ function lintTwinActions(manifest: Record<string, unknown>): LintFinding[] {
81
+ const byCanonical = new Map<string, string[]>();
82
+ const owners = new Map<string, string | undefined>();
83
+ for (const row of rows(manifest, "action_definitions")) {
84
+ const id = str(row, "action_id");
85
+ if (!id) continue;
86
+ owners.set(id, str(row, "bundle_id"));
87
+ const { action_id: _omit, ...rest } = row;
88
+ const canonical = JSON.stringify(
89
+ Object.fromEntries(Object.entries(rest).sort(([a], [b]) => a.localeCompare(b))),
90
+ );
91
+ const ids = byCanonical.get(canonical) ?? [];
92
+ ids.push(id);
93
+ byCanonical.set(canonical, ids);
94
+ }
95
+ const findings: LintFinding[] = [];
96
+ for (const ids of byCanonical.values()) {
97
+ if (ids.length < 2) continue;
98
+ const sorted = [...ids].sort();
99
+ // Report the twin on each redundant sibling (all but the first), naming the kept one.
100
+ const [keep, ...twins] = sorted;
101
+ for (const twin of twins) {
102
+ findings.push({
103
+ rule: "twin-action",
104
+ severity: "warning",
105
+ id: twin,
106
+ bundleId: owners.get(twin),
107
+ message: `action_definition '${twin}' is byte-identical to '${keep}' except its id — a copy-paste twin; emit one canonical action (let the primitive render it).`,
108
+ });
109
+ }
110
+ }
111
+ return findings;
112
+ }
113
+
114
+ // R2 — a required_capability with no capability_definition (author-time MF-VAL-265).
115
+ function lintDanglingRequiredCapability(manifest: Record<string, unknown>): LintFinding[] {
116
+ const known = new Set(
117
+ rows(manifest, "capability_definitions")
118
+ .map((r) => str(r, "capability_id"))
119
+ .filter((id): id is string => typeof id === "string"),
120
+ );
121
+ const findings: LintFinding[] = [];
122
+ for (const row of rows(manifest, "action_definitions")) {
123
+ const id = str(row, "action_id");
124
+ const req = str(row, "required_capability");
125
+ if (!id || !req || known.has(req)) continue;
126
+ findings.push({
127
+ rule: "dangling-required-capability",
128
+ severity: "warning",
129
+ id,
130
+ bundleId: str(row, "bundle_id"),
131
+ message: `action '${id}' requires capability '${req}' with no capability_definition in the bundle (runtime MF-VAL-265). Author the capability or fix the ref.`,
132
+ });
133
+ }
134
+ return findings;
135
+ }
136
+
137
+ // R3 — a srd/spell/* capability with no matching catalog entity_definition of the
138
+ // same id (author-time MF-VAL-264 / the `assertSpellCatalogBinding` smell). Non-
139
+ // srd/spell ids (synthetic affordances, monster actions, routing variants) are
140
+ // exempt — they legitimately have no catalog entity (the #835 carve-out).
141
+ function lintOrphanSpellCapability(manifest: Record<string, unknown>): LintFinding[] {
142
+ const catalog = new Set(
143
+ rows(manifest, "entity_definitions")
144
+ .map((r) => str(r, "entity_def_id"))
145
+ .filter((id): id is string => typeof id === "string"),
146
+ );
147
+ const findings: LintFinding[] = [];
148
+ for (const row of rows(manifest, "capability_definitions")) {
149
+ const id = str(row, "capability_id");
150
+ if (!id || !id.startsWith(SPELL_CATALOG_PREFIX) || catalog.has(id)) continue;
151
+ findings.push({
152
+ rule: "orphan-spell-capability",
153
+ severity: "warning",
154
+ id,
155
+ bundleId: str(row, "bundle_id"),
156
+ message: `capability '${id}' is a srd/spell identity with no catalog entity_definition of the same id (#835, runtime MF-VAL-264). One catalog spell is one identity — author the entity, or use a non-srd/spell id for a synthetic affordance.`,
157
+ });
158
+ }
159
+ return findings;
160
+ }
161
+
162
+ // R4 — a srd/spell/<slug> identity whose slug carries an underscore, violating the
163
+ // #835 hyphen catalog convention (`srd/spell/magic_missile` vs the catalog's
164
+ // `srd/spell/magic-missile`). Read across all three identity carriers; dedup by id.
165
+ function lintSpellDelimiterDrift(manifest: Record<string, unknown>): LintFinding[] {
166
+ const seen = new Set<string>();
167
+ const findings: LintFinding[] = [];
168
+ const consider = (id: string | undefined, bundleId: string | undefined) => {
169
+ if (!id || !id.startsWith(SPELL_CATALOG_PREFIX) || seen.has(id)) return;
170
+ const slug = id.slice(SPELL_CATALOG_PREFIX.length);
171
+ if (!slug.includes("_")) return;
172
+ seen.add(id);
173
+ findings.push({
174
+ rule: "spell-delimiter-drift",
175
+ severity: "warning",
176
+ id,
177
+ bundleId,
178
+ message: `spell identity '${id}' uses '_' in its slug; the #835 catalog convention is hyphen-delimited (e.g. '${id.replace(/_/g, "-")}'). Mixed delimiters orphan the catalog binding.`,
179
+ });
180
+ };
181
+ for (const row of rows(manifest, "capability_definitions"))
182
+ consider(str(row, "capability_id"), str(row, "bundle_id"));
183
+ for (const row of rows(manifest, "entity_definitions"))
184
+ consider(str(row, "entity_def_id"), str(row, "bundle_id"));
185
+ for (const row of rows(manifest, "action_definitions"))
186
+ consider(str(row, "required_capability"), str(row, "bundle_id"));
187
+ return findings;
188
+ }
189
+
190
+ // R5 — IDENTITY tags re-carried on behavior rows: the catalog `entity_definition_tag`
191
+ // set (the spell's identity; under #835 the entity_def_id == the capability_id)
192
+ // duplicated VERBATIM onto the behavior `capability_definition_tag` and/or the cast
193
+ // action's `action_definition_tag`. That is the #836 evidence #3 smell — the same
194
+ // tag set on entity + capability + action.
195
+ //
196
+ // ⚠️ It does NOT fire on a capability+action pair that has no catalog identity tags:
197
+ // tags on those two carriers are exactly what `emitSpell` renders from ONE
198
+ // declaration (single-sourced in the author's intent, two rows in the output), and
199
+ // synthetic affordances / monster actions (`srd/buff/*`, `srd/monster-action/*`)
200
+ // legitimately tag both with no catalog entity. Flagging that would cry wolf on the
201
+ // blessed primitive. The smell is specifically the IDENTITY tags leaking onto behavior.
202
+ function lintTagRepetition(manifest: Record<string, unknown>): LintFinding[] {
203
+ const entityTags = rows(manifest, "entity_definition_tag");
204
+ const capabilityTags = rows(manifest, "capability_definition_tag");
205
+ const actionTags = rows(manifest, "action_definition_tag");
206
+ const actionByCapability = new Map<string, string>();
207
+ for (const row of rows(manifest, "action_definitions")) {
208
+ const req = str(row, "required_capability");
209
+ const id = str(row, "action_id");
210
+ if (req && id && !actionByCapability.has(req)) actionByCapability.set(req, id);
211
+ }
212
+ const findings: LintFinding[] = [];
213
+ const capabilityIds = new Set(
214
+ rows(manifest, "capability_definitions")
215
+ .map((r) => str(r, "capability_id"))
216
+ .filter((id): id is string => typeof id === "string"),
217
+ );
218
+ for (const capabilityId of capabilityIds) {
219
+ const entityKey = tagKey(entityTags, "entity_def_id", capabilityId);
220
+ if (entityKey === undefined) continue; // no catalog identity tags -> nothing to leak.
221
+ const capKey = tagKey(capabilityTags, "capability_id", capabilityId);
222
+ const actionKey = tagKey(
223
+ actionTags,
224
+ "action_id",
225
+ actionByCapability.get(capabilityId) ?? " none",
226
+ );
227
+ // The smell: the catalog identity tag set re-carried verbatim on a behavior
228
+ // carrier. Count carriers sharing the identity set (the entity itself + matches).
229
+ const carriers = 1 + (capKey === entityKey ? 1 : 0) + (actionKey === entityKey ? 1 : 0);
230
+ if (carriers < 2) continue;
231
+ findings.push({
232
+ rule: "tag-repetition",
233
+ severity: "warning",
234
+ id: capabilityId,
235
+ bundleId: str(
236
+ rows(manifest, "capability_definitions").find(
237
+ (row) => str(row, "capability_id") === capabilityId,
238
+ ) ?? {},
239
+ "bundle_id",
240
+ ),
241
+ message: `spell '${capabilityId}' re-carries its catalog identity tag set on ${carriers} carriers (entity/capability/action). Tags belong on the catalog entity_definition; do not duplicate identity tags onto the behavior capability/action rows.`,
242
+ });
243
+ }
244
+ return findings;
245
+ }
246
+
247
+ // R6 (#1846) — structurally dead DSL predicates: constructs that parse,
248
+ // validate, and seed cleanly but the runtime derivation provably never evaluates
249
+ // true. Falsifiable per construct (source-grounded, not a guess):
250
+ // - target.has_capability: `manipulation_facts` (r_manipulate/selection/
251
+ // candidates.rs) and `traversal_affordance_facts`/`edge_traversal_...`
252
+ // (r_move.rs) both build the DSL `capabilities` fact list from
253
+ // `DslSubjectRef::Actor` only — no code path anywhere ever emits a
254
+ // `DslSubjectRef::Target` capability fact, in ANY reducer context.
255
+ // R7 and R8 lived in this family and are both RETIRED; see their comment
256
+ // blocks below for what made each construct real.
257
+
258
+ const PREDICATE_SOURCE_ID_KEYS = [
259
+ "template_id",
260
+ "outcome_graph_node_id",
261
+ "outcome_graph_edge_id",
262
+ "niche_id",
263
+ "modifier_template_id",
264
+ "condition_definition_id",
265
+ "policy_id",
266
+ ];
267
+
268
+ /** Best-effort row label for a generic cross-table scan (falls back to the table name). */
269
+ function rowLabel(table: string, row: Record<string, unknown>): string {
270
+ for (const key of PREDICATE_SOURCE_ID_KEYS) {
271
+ const value = str(row, key);
272
+ if (value) return value;
273
+ }
274
+ return table;
275
+ }
276
+
277
+ /** Every `*predicate_source` string field on a row (the author-facing DSL-source columns). */
278
+ function predicateSourceFields(row: Record<string, unknown>): [string, string][] {
279
+ return Object.entries(row).filter(
280
+ (entry): entry is [string, string] =>
281
+ entry[0].endsWith("predicate_source") && typeof entry[1] === "string" && entry[1] !== "",
282
+ );
283
+ }
284
+
285
+ // R6 — `target.has_capability(...)`: dead in every kernel evaluation path (see above).
286
+ function lintDeadTargetCapability(manifest: Record<string, unknown>): LintFinding[] {
287
+ const findings: LintFinding[] = [];
288
+ for (const [table, table_rows] of Object.entries(manifest)) {
289
+ if (!Array.isArray(table_rows)) continue;
290
+ for (const row of table_rows) {
291
+ if (!isRecord(row)) continue;
292
+ for (const [field, source] of predicateSourceFields(row)) {
293
+ if (!source.includes("target.has_capability(")) continue;
294
+ findings.push({
295
+ rule: "dead-target-capability",
296
+ severity: "warning",
297
+ id: rowLabel(table, row),
298
+ bundleId: str(row, "bundle_id"),
299
+ message: `${table}.${field} calls 'target.has_capability(...)' — capability facts derive actor-only everywhere in the kernel (r_manipulate's manipulation_facts, r_move's traversal_affordance_facts); a target-subject capability check can never be true (#1846). Use 'target.has_niche(...)' via entity_definition_tag instead.`,
300
+ });
301
+ }
302
+ }
303
+ }
304
+ return findings;
305
+ }
306
+
307
+
308
+
309
+ // R9 (finding #2, srd-cc battle-test ledger) — a `*_tag` row's `tag` value
310
+ // matches a CALLER-SUPPLIED `refTagFamilies` prefix (e.g. "srd.ability.") but
311
+ // the value after the prefix doesn't resolve to any row of the declared
312
+ // `targetKind` — almost always a typo (e.g. `srd.ability.wsi`), invisible to
313
+ // the validator because `tag` is a free string with no ref-shaped FIELD NAME
314
+ // (`isRefField` in `./inspection.ts` never matches a bare `tag` field).
315
+ // Discovery is generic over every `*_tag`-suffixed table — no dependency on
316
+ // `ROW_KIND_COMPOSITE_KEY` needed, since the `_tag` suffix is itself the
317
+ // row-kind convention.
318
+ //
319
+ // `refTagFamilies` is caller-supplied, never seeded here (`./ref-tags.ts`'s
320
+ // own header explains why this engine declares no 5e-shaped vocabulary of
321
+ // its own) — an empty list (the default every caller gets unless it opts in,
322
+ // see `lintManifest` below) makes this rule fire on nothing, which is the
323
+ // correct behavior for a bundle that hasn't declared any ref-typed tag
324
+ // convention, not a regression.
325
+ function lintDanglingRefTag(
326
+ manifest: Record<string, unknown>,
327
+ refTagFamilies: readonly RefTagFamily[],
328
+ ): LintFinding[] {
329
+ const findings: LintFinding[] = [];
330
+ for (const [table, tableRows] of Object.entries(manifest)) {
331
+ if (!table.endsWith("_tag") || !Array.isArray(tableRows)) continue;
332
+ for (const row of tableRows) {
333
+ if (!isRecord(row)) continue;
334
+ const tag = str(row, "tag");
335
+ if (!tag) continue;
336
+ // The row's own "id" for the finding: whichever field isn't
337
+ // tag/bundle_id/source (mirrors outboundRefsExcluding's own exclusion idiom).
338
+ const id = Object.entries(row).find(
339
+ ([key, value]) =>
340
+ key !== "tag" && key !== "bundle_id" && key !== "source" && typeof value === "string",
341
+ )?.[1] as string | undefined;
342
+ if (!id) continue;
343
+ const family = resolveTagPrefixFamily(
344
+ tag,
345
+ visibleRefTagFamilies(manifest, str(row, "bundle_id"), refTagFamilies),
346
+ );
347
+ if (family !== undefined) {
348
+ const value = tag.slice(family.prefix.length);
349
+ const visible =
350
+ family.declaringBundleId === undefined
351
+ ? undefined
352
+ : bundleScope(manifest, family.declaringBundleId);
353
+ const outcome = resolveRefTagValueOutcome(
354
+ manifest,
355
+ family.targetKind,
356
+ family.naturalKeyField,
357
+ value,
358
+ tag,
359
+ visible,
360
+ );
361
+ if (outcome.kind === "resolved") {
362
+ continue;
363
+ }
364
+ if (outcome.kind === "ambiguous") {
365
+ findings.push({
366
+ rule: "ambiguous-ref-tag",
367
+ severity: "warning",
368
+ id,
369
+ bundleId: str(row, "bundle_id"),
370
+ message: `MF-VAL-303: ${table} '${id}' tags '${tag}' — candidates: ${outcome.candidates.join(", ")}; no outbound edge.`,
371
+ });
372
+ continue;
373
+ }
374
+ findings.push({
375
+ rule: "dangling-ref-tag",
376
+ severity: "warning",
377
+ id,
378
+ bundleId: str(row, "bundle_id"),
379
+ message: `${table} '${id}' tags '${tag}' — no ${family.targetKind} row's id matches '${value}'; check for a typo (finding #2).`,
380
+ });
381
+ }
382
+ }
383
+ }
384
+ return findings;
385
+ }
386
+
387
+ const COMPASS_SECTORS = [
388
+ "east",
389
+ "northeast",
390
+ "north",
391
+ "northwest",
392
+ "west",
393
+ "southwest",
394
+ "south",
395
+ "southeast",
396
+ ] as const;
397
+
398
+ function metricDirection(fromX: number, fromY: number, toX: number, toY: number): string {
399
+ const dx = toX - fromX;
400
+ const dy = toY - fromY;
401
+ const deg = Math.atan2(dy, dx) * (180 / Math.PI);
402
+ const normalised = deg < 0 ? deg + 360 : deg;
403
+ const sector = Math.floor((normalised + 22.5) / 45) % 8;
404
+ // biome-ignore lint/style/noNonNullAssertion: sector is always 0-7 via % 8.
405
+ return COMPASS_SECTORS[sector]!;
406
+ }
407
+
408
+ function num(row: Record<string, unknown>, key: string): number | undefined {
409
+ const value = row[key];
410
+ return typeof value === "number" ? value : undefined;
411
+ }
412
+
413
+ function bool(row: Record<string, unknown>, key: string): boolean {
414
+ return row[key] === true;
415
+ }
416
+
417
+ /** Mirrors `readCurrentScene`/`readLocationSnapshot`'s own exit-label rule:
418
+ * the compass direction when both endpoints carry an authored position,
419
+ * else the raw destination node id. */
420
+ function exitLabel(
421
+ edge: Record<string, unknown>,
422
+ nodesById: Map<string, Record<string, unknown>>,
423
+ ): string {
424
+ const toNodeId = str(edge, "to_node_id");
425
+ const fromNode = nodesById.get(str(edge, "from_node_id") ?? "");
426
+ const toNode = toNodeId !== undefined ? nodesById.get(toNodeId) : undefined;
427
+ if (
428
+ fromNode !== undefined &&
429
+ toNode !== undefined &&
430
+ bool(fromNode, "pos_present") &&
431
+ bool(toNode, "pos_present")
432
+ ) {
433
+ const fromX = num(fromNode, "pos_x");
434
+ const fromY = num(fromNode, "pos_y");
435
+ const toX = num(toNode, "pos_x");
436
+ const toY = num(toNode, "pos_y");
437
+ if (fromX !== undefined && fromY !== undefined && toX !== undefined && toY !== undefined) {
438
+ return metricDirection(fromX, fromY, toX, toY);
439
+ }
440
+ }
441
+ return toNodeId ?? "";
442
+ }
443
+
444
+ function lintDuplicateExitLabels(manifest: Record<string, unknown>): LintFinding[] {
445
+ const nodesById = new Map(
446
+ rows(manifest, "place_nodes")
447
+ .map((row) => [str(row, "node_id"), row] as const)
448
+ .filter((entry): entry is [string, Record<string, unknown>] => entry[0] !== undefined),
449
+ );
450
+ const byFromNode = new Map<string, { edgeKey: string; label: string }[]>();
451
+ for (const edge of rows(manifest, "place_edges")) {
452
+ const fromNodeId = str(edge, "from_node_id");
453
+ const edgeKey = str(edge, "edge_key");
454
+ if (!fromNodeId || !edgeKey) continue;
455
+ const label = exitLabel(edge, nodesById);
456
+ if (!label) continue;
457
+ const list = byFromNode.get(fromNodeId) ?? [];
458
+ list.push({ edgeKey, label });
459
+ byFromNode.set(fromNodeId, list);
460
+ }
461
+ const findings: LintFinding[] = [];
462
+ for (const [fromNodeId, edges] of byFromNode) {
463
+ const byLabel = new Map<string, string[]>();
464
+ for (const edge of edges) {
465
+ const list = byLabel.get(edge.label) ?? [];
466
+ list.push(edge.edgeKey);
467
+ byLabel.set(edge.label, list);
468
+ }
469
+ for (const [label, edgeKeys] of byLabel) {
470
+ if (edgeKeys.length < 2) continue;
471
+ const sorted = [...edgeKeys].sort();
472
+ for (const edgeKey of sorted) {
473
+ const siblings = sorted.filter((key) => key !== edgeKey);
474
+ findings.push({
475
+ rule: "duplicate-exit-label",
476
+ severity: "warning",
477
+ id: edgeKey,
478
+ bundleId: str(
479
+ rows(manifest, "place_edges").find((edge) => str(edge, "edge_key") === edgeKey) ?? {},
480
+ "bundle_id",
481
+ ),
482
+ message: `place_edge '${edgeKey}' from node '${fromNodeId}' shares the label '${label}' with ${siblings.length} other exit(s) from the same node (${siblings.join(", ")}) — spellkave_scene lists them identically, so a PLAYER cannot tell them apart without a spellkave_scene_detail probe per candidate (T3). Reposition an endpoint so the compass directions diverge, or author distinct pos_x/pos_y so the labels stop colliding.`,
483
+ });
484
+ }
485
+ }
486
+ }
487
+ return findings;
488
+ }
489
+
490
+ export interface LintManifestOptions {
491
+ /**
492
+ * The `dangling-ref-tag` rule's (R9) vocabulary of ref-typed `*_tag` value
493
+ * prefixes (e.g. `srd.ability.` → `resource_definitions`) — CALLER-SUPPLIED,
494
+ * never seeded by this package (`./ref-tags.ts`'s header explains why this
495
+ * game-agnostic engine declares no 5e-shaped vocabulary of its own).
496
+ * Defaults to an empty list: the rule fires on nothing unless a caller
497
+ * (e.g. a content bundle's own test/CLI invocation) opts in with its own
498
+ * declared families. `sk lint` run standalone against a fixtures path does
499
+ * not yet supply any — families are caller-declared until a manifest-level
500
+ * `tag_prefixes` declaration surface exists (proposed separately via
501
+ * OpenSpec; see `./ref-tags.ts`'s header).
502
+ */
503
+ refTagFamilies?: readonly RefTagFamily[];
504
+ }
505
+
506
+ /**
507
+ * Lint a parsed manifest for author-time duplication / binding smells (#836 Part C)
508
+ * plus structurally dead DSL predicate constructs (#1846). Every finding is a
509
+ * non-fatal `warning`; findings are sorted (rule, then id) for a deterministic
510
+ * report. Pass the merged-bundle manifest to catch cross-fragment drift.
511
+ */
512
+ export function lintManifest(
513
+ manifest: Record<string, unknown>,
514
+ options: LintManifestOptions = {},
515
+ ): LintFinding[] {
516
+ const findings = [
517
+ ...lintTwinActions(manifest),
518
+ ...lintDanglingRequiredCapability(manifest),
519
+ ...lintOrphanSpellCapability(manifest),
520
+ ...lintSpellDelimiterDrift(manifest),
521
+ ...lintTagRepetition(manifest),
522
+ ...lintDeadTargetCapability(manifest),
523
+ ...lintDanglingRefTag(manifest, options.refTagFamilies ?? []),
524
+ ...lintDuplicateExitLabels(manifest),
525
+ ];
526
+ return findings.sort((a, b) => a.rule.localeCompare(b.rule) || a.id.localeCompare(b.id));
527
+ }
528
+
529
+ /** The lint rule ids, for a documented author-time contract (CLI output / docs). */
530
+ export const LINT_RULES: LintRule[] = [
531
+ "twin-action",
532
+ "dangling-required-capability",
533
+ "orphan-spell-capability",
534
+ "spell-delimiter-drift",
535
+ "tag-repetition",
536
+ "dead-target-capability",
537
+ "dangling-ref-tag",
538
+ "ambiguous-ref-tag",
539
+ "duplicate-exit-label",
540
+ ];
@@ -0,0 +1,21 @@
1
+ /** Strip root-only headers when rendering a row-only include fragment. */
2
+ export function stripManifestHeaders(rendered: string): string {
3
+ const dropHeaders = new Set(["[[bundles]]", "[metadata]"]);
4
+ const kept: string[] = [];
5
+ let seenTable = false;
6
+ let dropping = false;
7
+ for (const line of rendered.split("\n")) {
8
+ const table = line.trim();
9
+ if (/^\[\[?[A-Za-z_.]+\]?\]$/.test(table)) {
10
+ seenTable = true;
11
+ dropping = dropHeaders.has(table);
12
+ if (!dropping) kept.push(line);
13
+ continue;
14
+ }
15
+ if (seenTable && !dropping) kept.push(line);
16
+ }
17
+ return `${kept
18
+ .join("\n")
19
+ .replace(/\n{3,}/g, "\n\n")
20
+ .trim()}\n`;
21
+ }