@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/compose.ts ADDED
@@ -0,0 +1,699 @@
1
+ // embedded-manifest: {"category": "production_schema_constructor", "rationale": "production include inspector constructs a transient schema header from its root", "signatures": ["schema_shape"]}
2
+ //
3
+ // SRD ACTOR-BEHAVIOR cluster builder — the shared machine behind the per-actor
4
+ // behavior drivers (#238 / #708).
5
+ //
6
+ // ADR-0072 D-1 / #1526: promoted verbatim from the old scripts/srd/behavior-cluster.ts
7
+ // (now a re-export shim at packages/spellkave-srd/src/author/behavior-cluster.ts,
8
+ // #1968 slice 2; retired with #1526 step 5). This module is the
9
+ // canonical composition layer — new shapes are added HERE. Node-only (uses fs
10
+ // at call time, never at import); the browser entry does not re-export it.
11
+ //
12
+ // #835 — the capability+action+tags+outcome IDENTITY core of a spell now also has a
13
+ // standalone, fs-free primitive in the package: `emitSpell` (@spellkave/world-author),
14
+ // which a general author uses to declare ONE spell identity. This cluster predates it and
15
+ // carries the full effect-chain machine. The cast_x/affordance ACTION twin is GONE
16
+ // (#836-B, below: one canonical action_definition; the materialiser resolves via
17
+ // outcome.manipulation_action_id, not the affordance template_id). Fully delegating the
18
+ // remaining identity-row emission to `emitSpell` is the last render-discipline step under
19
+ // #836. What this cluster DOES use today is the shared `assertSpellCatalogBinding` (see
20
+ // authorBehaviorFragment) — the author-time guard that a self-emitted `srd/spell/*`
21
+ // capability has a matching catalog entity_definition.
22
+ //
23
+ // #836 Parts C/D (shipped): `just srd-lint-bundle` (= `manifest lint --bundle`) reports the
24
+ // author-time duplication / binding smells across the merged bundle — twin-action,
25
+ // tag-repetition, spell-delimiter-drift, orphan/dangling capability. Best-practice rationale:
26
+ // packages/spellkave-world-author/docs/spell-authoring-best-practices.md + the spell-identity-minimal worked example.
27
+ //
28
+ // One actor BEHAVIOR = a cast/attack effect chain (capability → outcome →
29
+ // affordance → action → consequence → frame_write) plus the live-wiring rows that
30
+ // let it fire (the actor holds the capability; its node carries the niche). The
31
+ // kernel does NOT distinguish "spell" from "monster attack" — both are just an
32
+ // actor performing an action whose consequence modifies a resource — so this
33
+ // builder is shared by both drivers; only the id namespace + output file differ:
34
+ // • author-spell-behavior.ts → base/spell-actions.toml (caps srd/spell/<key>, actions srd/cast_<key>)
35
+ // • author-monster-actions.ts → base/monster-actions.toml (caps srd/monster-action/<key>, actions srd/<key>)
36
+ //
37
+ // Substrate: ADR-0045 (issue #266) makes the two tabletop mechanics authorable as
38
+ // generic DSL carriers the kernel stays ignorant of:
39
+ // - dice damage / heal → ModifyResource.delta_source (Int expression)
40
+ // - per-target save → ForEachActorInRadius.predicate_source (Bool, per actor)
41
+ // The save DC / attack AC is authored as a literal (8 + prof + ability ≈ 13); the
42
+ // target's modifier folds into that threshold. Damage-TYPE routing (resist / vuln /
43
+ // immune) is the ONE remaining gap (ADR-0045 G-3 / #763), carried as documentary
44
+ // tags only — no behavior here has a resistance rider, so none needs it.
45
+ //
46
+ // The SHAPES (each moves WHERE the to-hit / save roll sits — or drops it):
47
+ // • AoE save-negate — ForEachActorInRadius sphere; predicate_source GATES the
48
+ // body (a save runs no body → 0 effect). delta_source = "0 - dN".
49
+ // • AoE save-for-half — sphere, body NOT gated (predicate_source = ""); the save
50
+ // halves inside delta via a typed ternary (ADR-0045 D-3 `cond`):
51
+ // delta_source = "cond(d20 >= DC, 0 - (NdM / 2), 0 - NdM)".
52
+ // • single-target ATTACK — one TargetActor; body = bare ModifyResource(TargetActor).
53
+ // As of #1891/PR #2075, the attack roll does NOT sit on the AFFORDANCE predicate
54
+ // (`predicateSource` on `affordance_templates.predicate_source` — a stochastic
55
+ // comparison there is treated as SATISFIED at materialise time, so it no longer
56
+ // gates OFFER attemptability/visibility). Instead, `predicateSource` stays
57
+ // deterministic ELIGIBILITY only ("" or empty is fine — an ungated attack), and
58
+ // the die goes on `resolutionPredicateSource` ("d20 >= AC", `resolutionMode:
59
+ // "Stochastic"`), evaluated ONCE at act time by `r_manipulate` against the real
60
+ // Actor/TargetActor facts; a MISS applies `onFailure`'s consequence instead of
61
+ // `on_success`'s (composer-resolution-fields — see the field doc comments
62
+ // below). No `roll_at_least` kernel op — the attack composes from the raw `>=`
63
+ // Compare primitive (ADR-0021). A monster drives this identically with caster =
64
+ // the monster (no turn-loop: r_manipulate takes actor_id as a plain param; the
65
+ // claim gate is on the TARGET only).
66
+ // • single-target HEAL — same topology, NO affordance gate (predicate_bool = true),
67
+ // POSITIVE delta ("NdM"); `saturating_add` raises HP, the resource max_value
68
+ // clamps overheal. The kernel does not know heal from damage — only the sign.
69
+
70
+ import { readFile, writeFile } from "node:fs/promises";
71
+ import { dirname, resolve } from "node:path";
72
+ import { cluster_rows_json } from "@spellkave/authoring-wasm";
73
+ import { inspectManifest } from "./inspect";
74
+ import { renderSchemaManifestJson } from "./manifest";
75
+ import { stripManifestHeaders } from "./manifest-text";
76
+ import { assertSpellCatalogBinding } from "./spell";
77
+
78
+ // One actor's full behavior slice. The builder turns a list of these into the
79
+ // combined row tables; nothing here is spell- or monster-specific to the kernel.
80
+ export interface ActorBehavior {
81
+ // capability `srd/<capPrefix>/<key>` + action `srd/<actionPrefix><key>` derive from this.
82
+ key: string;
83
+ // #835 — explicit capability id, overriding the `srd/<capPrefix>/<key>` derivation.
84
+ // For a CATALOG spell this MUST equal the catalog `entity_definition.entity_def_id`
85
+ // (`srd/spell/<foundry-slug>`), so a single spell is ONE identity: the behavior
86
+ // `capability_id` == the catalog `entity_def_id` == the action's `required_capability`
87
+ // (the cluster always sets `required_capability = cap`). Leaving it unset keeps the
88
+ // legacy per-namespace derivation (monster actions, synthetic consumer affordances).
89
+ // The action id is deliberately NOT touched — the `cast_*` verb keeps its name; only
90
+ // the spell IDENTITY is unified. A `srd/spell/*` capability with no matching catalog
91
+ // entity_definition draws the MF-VAL-264 convention warning.
92
+ capabilityId?: string;
93
+ displayName: string;
94
+ // Render the capability_definition (+tags) here? False when the capability is
95
+ // already authored elsewhere (e.g. Acid Splash's lives in base/spells.toml).
96
+ emitCapability: boolean;
97
+ capabilityDescription?: string;
98
+ capabilityTags?: string[];
99
+ actionTags: string[];
100
+ // "aoe" — ForEachActorInRadius sphere; gate in the body (negate,
101
+ // predicate_source != "") or the delta cond (half, "").
102
+ // "single-target" — one TargetActor; bare ModifyResource. The gate, if any, sits
103
+ // on the AFFORDANCE: non-empty predicate_source = an attack/check
104
+ // roll (miss skips the consequence); "" = no gate (e.g. a heal).
105
+ // "zone" — a LINGERING hazard: ordinal-0 frame_write INSCRIBES a
106
+ // spatial_environment_state marker on the caster's cell at RUNTIME
107
+ // (the Inscribe{kind:"spatial_environment_state"} apply-path overload,
108
+ // server inscribe.rs:103 — resolves any place_node incl. ephemeral grid
109
+ // cells), ordinal-1 PULSES a node-local ForEachActorInRadius
110
+ // (core/area/node_ball, ball_radius 0) over every actor on that cell.
111
+ // The marker LINGERS (observable); re-casting re-pulses. The state def
112
+ // is emitted automatically (writer_policy "world_interaction" so the
113
+ // apply path may write it; a "manifest"-only policy would reject it).
114
+ // "scheduled-zone" — a TRUE lingering hazard (ADR-0054 caster-attributed pulse). Like
115
+ // "zone" the CAST inscribes the marker (success consequence, ordinal 0),
116
+ // but instead of pulsing once at cast it schedules a subject-bound
117
+ // `ScheduleAutonomyJob` effect (success.effect_refs_csv → an
118
+ // effect_definition). The job captures the caster as `subject` and, on
119
+ // the world clock, RE-FIRES a separate pulse consequence_template
120
+ // (ForEachActorInRadius + ModifyResource damage, OR — when
121
+ // `applyCondition` is set — ForEachActorInRadius + ApplyStatus condition)
122
+ // each `scheduleFrequencyMs` for `scheduleRepeats` rounds — the zone
123
+ // damages OR conditions whoever stands in it on its own, then expires. The
124
+ // fire-time fence (`is_executable_frame_write_now`) admits both
125
+ // ModifyResource and ApplyStatus on the autonomy clock, but NOT Inscribe,
126
+ // so the marker Inscribe MUST stay on the cast, never the pulse. WHERE the
127
+ // pulse + marker center is set by `zoneCenterRef` (ADR-0055, #776 CLOSED):
128
+ // "TargetSpatialRef" ANCHORS on the cast's target cell (fixed where
129
+ // dropped — the captured anchor_place_node_id), "ActorSpatialRef" follows
130
+ // the caster. `scheduleSource` may carry {Actor}/{tick} placeholders →
131
+ // per-cast-unique job_id (concurrent casts no longer collide on the PK).
132
+ // "env-state" — an AMBIENT-EFFECT spell (Darkness/Silence/Fog, #796/ADR-0056).
133
+ // The cast's ONLY frame_write is the marker Inscribe (no actor
134
+ // effect, no pulse): it writes a `spatial_environment_state` row
135
+ // (value_type BOOL, value = `envStateValue ?? true`) on the
136
+ // `zoneCenterRef` cell at RUNTIME. Nothing here touches HP — the
137
+ // EFFECT lives in a SEPARATELY-authored consumer affordance whose
138
+ // predicate reads `target.state("<zoneStateId>")` (now authorable
139
+ // since #796 retired the hardcoded r_move/r_manipulate gate). The
140
+ // kernel default-populates an absent env-state fact to false, so a
141
+ // fresh cell reads "off" with no manifest seed; the cast flips it on.
142
+ // "summon" — a SUMMONING spell (Find Familiar / Conjure / Animate Dead, Brief 26
143
+ // `EffectPrimitive::Spawn`). The cast has NO frame_write at all; its
144
+ // success consequence carries `effect_refs_csv` → an effect_definition
145
+ // whose `primitives_csv = "Spawn"` instantiates a catalog blueprint
146
+ // (`summonBlueprint`, any `entity_definition.entity_def_id` — e.g. one of
147
+ // the 385 `srd/monster/*` defs). The spawn location is one of two forms:
148
+ // • `summonLocationNode` → a LITERAL authored `place_node` id (a fixed,
149
+ // known-location summon).
150
+ // • `summonAtCaster: true` → DYNAMIC: the Spawn's `location_ref` is the
151
+ // `ActorSpatialRef` binding, so the creature materialises at the
152
+ // CASTER'S CURRENT cell (#849 RESOLVED by #859 — the apply path now
153
+ // threads `bindings` into `execute_spawn` and `resolve_spawn_location_ref`
154
+ // → `resolve_spatial_ref` substitutes the caster's spatial ref). This is
155
+ // the faithful "summon appears next to you" model — the summon follows the
156
+ // caster, independent of the cast's `target_ref`.
157
+ // The affordance is ungated (a summon always succeeds).
158
+ // "outcome-graph" — a BRANCH-ON-OUTCOME spell (#858/ADR-0058). The action's outcome
159
+ // carries `outcome_expression_source = invoke_outcome_graph(<graph>)`
160
+ // (the success consequence stays empty — no direct frame_write). The
161
+ // graph branches root→<node> by each `branches[]` entry's `guard`
162
+ // predicate; `authored_order` = array index, so the FIRST true edge
163
+ // wins and the LAST branch should carry a `"1 == 1"` fallthrough. The
164
+ // selected TERMINAL node carries its own `consequence_template`
165
+ // (one ModifyResource on TargetActor, `branch.deltaSource`) which the
166
+ // layer-2 commit sink applies via `r_apply_consequence` (the #865
167
+ // node-effect wiring). ADR-0061 / #874 also threads the invoking
168
+ // interaction's actor/target int-state, status, and tag facts into the
169
+ // guard context, so a guard can branch on both dice (`d20`) and resolved
170
+ // state (`target.stat("srd/hp")`). Unlike single-target ATTACK (a miss
171
+ // skips the whole consequence → 0 effect), EVERY branch can carry an
172
+ // effect, so a "miss" arm still deals half damage (Melf's Acid Arrow:
173
+ // hit 4d4 / miss 2d4).
174
+ // "clock" — a SELF-TARGETED multi-ordinal tally/threshold pattern (#1968 finding
175
+ // C2, the death-saves shape — archive/world-fixtures/srd/base/death-saves.toml).
176
+ // Unlike every shape above (each writes a TargetActor or a radius-
177
+ // selected OTHER actor), a clock's every ordinal writes the ACTING
178
+ // subject ALONE: N bare ModifyResource(actor="Actor", ...) tally
179
+ // ordinals (0..N-1, `clockTallies`) — plain read-modify-writes against
180
+ // a resource this behavior does not own exclusively (a death-save pool,
181
+ // a corruption counter, any user-named tally) — followed by M
182
+ // ForEachActorInRadius(node_ball, ball_radius 0) threshold ordinals
183
+ // (`clockThresholds`) wrapping an ApplyStatus/RemoveCondition on
184
+ // "Actor" — never TargetActor, and never a BARE top-level ApplyStatus:
185
+ // this substrate's ApplyStatus/RemoveCondition frame_write ops carry no
186
+ // delta/predicate of their own to fold a `cond(...)` into (unlike
187
+ // ModifyResource), so the ForEachActorInRadius wrapper's OWN
188
+ // predicate_source is the only way to gate one. That radius-0 wrapper is
189
+ // SAFE here specifically because every tally ordinal already wrote
190
+ // "Actor" alone — a co-located bystander's OWN pool value can never
191
+ // reflect someone else's roll (death-saves.toml's own header walks
192
+ // through this exact reasoning, the A3 co-location fix this shape
193
+ // generalises). A clock's affordance predicate (`predicateSource`) is
194
+ // the ELIGIBILITY gate for the whole action (e.g. "actor.status('dying')
195
+ // == true && ..."), the same seam single-target's attack-roll gate uses
196
+ // — a SEPARATE concept from each threshold's own `when` (which gates
197
+ // ONLY that threshold's ApplyStatus/RemoveCondition, post-tally).
198
+ shape:
199
+ | "aoe"
200
+ | "single-target"
201
+ | "zone"
202
+ | "scheduled-zone"
203
+ | "env-state"
204
+ | "summon"
205
+ | "outcome-graph"
206
+ | "clock";
207
+ // outcome-graph only — the branch arms (see the shape doc). Each is one terminal
208
+ // graph node + its edge guard + the HP delta its consequence applies on selection.
209
+ branches?: OutcomeBranch[];
210
+ // summon only — the blueprint to instantiate (an entity_definition.entity_def_id, e.g.
211
+ // `srd/monster/cat`). The spawn location is EITHER a LITERAL `summonLocationNode` OR, when
212
+ // `summonAtCaster` is set, the DYNAMIC `ActorSpatialRef` binding (the caster's current cell;
213
+ // #849 RESOLVED). Set exactly one — `summonAtCaster` wins if both are present.
214
+ summonBlueprint?: string;
215
+ summonLocationNode?: string;
216
+ summonAtCaster?: boolean;
217
+ // env-state only — the bool value the marker Inscribe writes (default true = "on").
218
+ envStateValue?: boolean;
219
+ radiusM?: number; // aoe only
220
+ // aoe shape only — override the default "core/area/sphere" + `radiusM` metric
221
+ // geometry with a specific area-shape id + its raw JSON params (e.g.
222
+ // "core/area/node_ball" + '{"ball_radius": 0}', a TOPOLOGICAL radius unrelated to
223
+ // `radiusM`'s metric one). Unset = the original sphere/radiusM behavior, byte-
224
+ // identical for every existing caller (#1968 FIX③ de-fork: a bundle-generic
225
+ // substrate verb sets these instead of hand-mirroring this whole branch).
226
+ areaShapeId?: string; // default "core/area/sphere"
227
+ areaShapeParamsJson?: string; // default `{"radius_m": <radiusM>}`
228
+ // aoe shape only — the resource the per-target ModifyResource body writes.
229
+ // Defaults to "srd/hp" (every SRD aoe spell today) — unset is byte-identical for
230
+ // existing callers; a bundle-generic caller sets its own resource_definition_id.
231
+ aoeResource?: string; // default "srd/hp"
232
+ // Metric PLACEMENT range on the affordance (ADR-0053). 0 (default) = touch /
233
+ // same place_node = pre-0053 behavior. Non-zero lets the cast act on a DISTANT
234
+ // cell/entity within straight-line metric range. Author via the `ft()` feet→metric
235
+ // helper, never raw feet. Governs placement only; AoE membership is still
236
+ // for_each_actor_in_radius after the cell is targeted.
237
+ rangeM?: number;
238
+ // zone only — the lingering-marker state. The state def is emitted with
239
+ // writer_policy "world_interaction" (the apply path may write) + a long freshness so
240
+ // the marker persists. `zoneIntensity` is the value_int stamped on the cell.
241
+ zoneStateId?: string;
242
+ zoneIntensity?: number;
243
+ zoneVisibility?: string; // default "Public"
244
+ // Where the marker + pulse center (both zone shapes). ADR-0055:
245
+ // "ActorSpatialRef" (default) — follows the caster's CURRENT cell each fire (mobile aura).
246
+ // "TargetSpatialRef" — ANCHORS on the cast's target cell (the job's captured
247
+ // `anchor_place_node_id`), fixed even if the caster moves — the
248
+ // faithful "dropped at range" hazard (Cloudkill). At cast time the
249
+ // marker Inscribe also resolves TargetSpatialRef to the target cell,
250
+ // so marker + pulse stay co-located.
251
+ zoneCenterRef?: "ActorSpatialRef" | "TargetSpatialRef"; // default "ActorSpatialRef"
252
+ // scheduled-zone only — the ADR-0054 autonomy-pulse cadence. `scheduleRepeats` bounds
253
+ // the duration (a subject-bound actor-reaching job MUST be bounded — server fence +
254
+ // MF-VAL-249); `scheduleFrequencyMs` is the fiction-ms period between pulses;
255
+ // `requiresSubjectAlive` picks the liveness policy (false = the zone persists for its
256
+ // full duration even if the caster leaves, the SRD Cloudkill behaviour; true = it
257
+ // dissipates when the caster's entity is removed, the concentration variant). `source`
258
+ // is the cancel-by-source/provenance key on the runtime job; author it with the
259
+ // {Actor}/{ResponsibleSubject}/{tick} placeholders (ADR-0055 D-3) and the scheduler
260
+ // interpolates them at cast time → per-cast-unique job_id, so concurrent casts no longer
261
+ // collide on the PK (identity stays in the typed `subject` column).
262
+ scheduleRepeats?: number; // default 10
263
+ scheduleFrequencyMs?: number; // default 6000
264
+ requiresSubjectAlive?: boolean; // default false
265
+ scheduleSource?: string; // default `srd/<key>`
266
+ selfEligible?: boolean; // action_definition.self_eligible — set true for a self-targeting action (e.g. a self-heal); default false
267
+ predicateSource: string; // aoe body gate / "" ; or single-target affordance gate / ""
268
+ deltaSource: string; // "0 - dN" damages (negative) ; "NdM" heals (positive, clamps). IGNORED when `attacks`, `applyCondition`, or `removeCondition` is set.
269
+ // ACT-TIME STOCHASTIC RESOLUTION (composer-resolution-fields, #1891/#2075
270
+ // docs/behavior-composition.md's now-resolved gap note) — all three OPTIONAL,
271
+ // mapping 1:1 onto the `action_definitions.resolution_mode` /
272
+ // `.resolution_predicate_source` / `.on_failure` columns, naming mirrored
273
+ // from the shared tool runtime `spellkave_define_action`/`spellkave_define_behavior`
274
+ // verb params (packages/spellkave-tool-authoring/src/authoring-verbs.ts).
275
+ // Omitting all three renders BYTE-IDENTICAL `action_definitions` output to
276
+ // before this field existed (no key is emitted at all — not even the schema
277
+ // default) — this is the composer's half of the canon-ideal split #1891
278
+ // established: the OFFER predicate (`predicateSource` above, on
279
+ // `affordance_templates.predicate_source`) stays deterministic ELIGIBILITY
280
+ // only (a stochastic comparison there is now treated as always-satisfied at
281
+ // materialise time, per #1891 — it no longer gates attemptability), while the
282
+ // dice move here, to the ACT-TIME resolution seam `r_manipulate` re-evaluates
283
+ // for real. Wired for `shape: "single-target"` (the documented gap; also
284
+ // works for "clock", whose own `predicateSource` is likewise a pure
285
+ // eligibility gate) — NOT wired as a body-shape concern for "aoe" /
286
+ // "outcome-graph" / "zone"/"scheduled-zone", each of which already has its
287
+ // own idiom for branching on a roll INSIDE the body/graph (aoe's `cond(...)`
288
+ // delta, outcome-graph's branch guards, a zone's per-actor pulse predicate)
289
+ // and needs no `on_failure` consequence — a miss there already resolves to
290
+ // "no effect" or "half effect" within the SAME consequence template. Setting
291
+ // these on a non-single-target/clock shape is not rejected (the row-level
292
+ // field is shape-agnostic — every shape shares this ONE `action_definitions`
293
+ // push) but has no established idiom backing it yet; treat it as forward-prep,
294
+ // not a proven pattern, until a second shape actually needs it.
295
+ // resolutionMode — action_definitions.resolution_mode
296
+ // ("Deterministic" | "Stochastic" | "Deferred"). Omit for the schema
297
+ // default ("Deterministic") — set "Stochastic" alongside
298
+ // resolutionPredicateSource for the attack-roll idiom above.
299
+ // resolutionPredicateSource — action_definitions.resolution_predicate_source,
300
+ // the authored boolean DSL `r_manipulate` evaluates ONCE at act time with
301
+ // the real Actor/TargetActor facts (e.g. "d20 >= 15" — the SAME roll that
302
+ // used to sit on `predicateSource` pre-#1891). Omit for empty.
303
+ // onFailure — action_definitions.on_failure, a bare
304
+ // `consequence_templates` id applied when resolutionPredicateSource
305
+ // evaluates false (a MISS). This composer does NOT auto-emit that
306
+ // template the way it auto-emits the `on_success` one (`ids().success`,
307
+ // always rendered from THIS behavior) — `on_success` is a derived,
308
+ // always-present identity for this behavior; a miss consequence is
309
+ // optional and often SHARED across several behaviors (e.g. one generic
310
+ // "no effect" template), so it stays a plain id reference, author it
311
+ // separately (e.g. `spellkave_define_consequence`, or a sibling
312
+ // behavior/extraRows entry in the same fragment) and pass its id here —
313
+ // the SAME "bare id, no ref-check, no auto-creation" contract
314
+ // `spellkave_define_action`'s own `on_failure` param already documents.
315
+ // Omit for none (schema default: empty string).
316
+ resolutionMode?: "Deterministic" | "Stochastic" | "Deferred";
317
+ resolutionPredicateSource?: string;
318
+ onFailure?: string;
319
+ applyCondition?: string;
320
+ // CONDITION-REMOVING (single-target) — the INVERSE of applyCondition: instead of
321
+ // landing a condition, the body REMOVES one from the target via a `RemoveCondition`
322
+ // frame_write (the restoration / cleanse family — Lesser Restoration, Remove Curse,
323
+ // Protection from Poison; it also makes a spell-applied condition curable). The kernel
324
+ // frame-write arm (server `r_apply_consequence/remove_condition.rs`) deletes primary
325
+ // `target_condition` row(s) matching `(target, target_kind, condition_definition_id,
326
+ // parent_row_id IS NULL)` and runs each removed condition's authored remove-time cascade
327
+ // policy on its children — so cleansing srd/paralyzed also clears its implied
328
+ // core/incapacitated per the condition def, NOT per this spell. The shape is
329
+ // `{target_kind:"entity", target_ref:"TargetActor", condition_definition_id, source_match}`.
330
+ // `source_match` is `Any` for source-agnostic cleanse or `Exact(source_id)` for ending one
331
+ // specific source's effect.
332
+ // Cleanse spells have no save (Lesser Restoration just works on touch): leave
333
+ // `predicateSource` empty → the affordance is ungated (predicate_bool = true). Both
334
+ // `deltaSource` and `applyCondition` are ignored when this is set.
335
+ removeCondition?: string;
336
+ // removeCondition only — optional exact source key. Absent means source-agnostic `Any`;
337
+ // present means `Exact(<source>)` for spells/effects that should end one source's effect.
338
+ removeConditionSource?: string;
339
+ // MULTIATTACK (single-target only): N independent self-gating attacks in ONE
340
+ // action/consequence — a monster's Multiattack (e.g. Polar Bear's two Rends).
341
+ // Each entry emits its OWN consequence_frame_write (ordinals 0..N), each a bare
342
+ // ModifyResource(TargetActor, srd/hp, deltaSource) whose attack roll is FOLDED
343
+ // INTO the delta as `cond(d20 >= AC, 0 - dmg, 0)` — so a per-attack miss zeroes
344
+ // only THAT attack, not the whole action. The affordance therefore carries NO
345
+ // gate (predicate_bool = true): each sub-attack self-gates in its own frame_write.
346
+ // The server threads one reducer rng across sibling frame_writes (ADR-0045 COND-3
347
+ // postscript) so the N rolls are INDEPENDENT (two Rends can hit-then-miss). When
348
+ // set, `deltaSource`/`predicateSource` are ignored. Generalises to any N.
349
+ attacks?: MultiAttack[];
350
+ // RESOURCE-GATED CAST (any shape) — a LEVELED spell that consumes a pool
351
+ // (e.g. `srd/spell_slot_1`) instead of casting free (a cantrip). Two effects:
352
+ // (1) the AFFORDANCE gains an extra `actor.stat('<resource>') >= <amount>`
353
+ // gate clause (ANDed with any existing body-gate predicate that already sits on
354
+ // the affordance) — this is the ONLY seam that also reaches a Multiattack
355
+ // (`attacks`), whose affordance is otherwise ungated; (2) the success
356
+ // consequence gains one more ModifyResource frame_write (last ordinal) debiting
357
+ // the pool on the CASTER (`actor = "Actor"`). SRD-MAP B8 (#1561 stage 3a).
358
+ resourceCost?: { resource: string; amount: number };
359
+ // SKILL-CHECK / NON-HP STATE TARGET (single-target only): the `object_state` the
360
+ // single-target ModifyResource body writes. Defaults to `srd/hp` (every combat shape).
361
+ // Set to a non-resource social/disposition state (e.g. `srd/attitude`) to make the
362
+ // success consequence change a NON-HP state — the foundational social-check shape: an
363
+ // actor-initiated `d20 + ability_mod vs DC` affordance gate whose success shifts a
364
+ // target NPC's disposition. ModifyResource works on ANY object_state Int row
365
+ // (modify_resource.rs §12.5b), clamping to a `resource_definition`'s [min,max] when one
366
+ // exists. Ignored when `attacks`/`applyCondition`/`removeCondition` is set.
367
+ resourceStateId?: string;
368
+ // SPEECH-ACT (Searle lens) — when set, the action's outcome_template carries this
369
+ // `communication_speech_act_id`, so the affordance SURFACES as a communication speech
370
+ // act (`communication.speech_act=<id>`, the verb-class discriminator — mod.rs:993). The
371
+ // row still carries `manipulation_action_id` so r_manipulate EXECUTES the gated
372
+ // consequence normally (selection.rs:425); the empty perception `action_id` is the
373
+ // observer-facing descriptor only. This is how a social skill check is framed as a
374
+ // speech act (Persuasion = a directive) WITHOUT a new resolution mode (mode_selection.rs:
375
+ // "Communication intents are ordinary action_definition rows … speech-act ids are
376
+ // descriptor metadata and do not select runtime mode").
377
+ communicationSpeechActId?: string;
378
+ // #1968 B-9: authored PLAYER-facing observation narrative — when set, the
379
+ // action's outcome_template carries this as its `description` column, the
380
+ // authored source `observation.ts` (shared tool runtime) reads for the
381
+ // manipulate/sensing observation contract. Distinct from
382
+ // `capabilityDescription` above, which stays operator-only on
383
+ // `capability_definitions` — see `outcome_template.rs`'s doc comment for
384
+ // the widened, presentation-only contract this field rides. May reference
385
+ // the frozen `{target_name}`/`{actor_name}`/`{place_name}` placeholders
386
+ // only; the validator rejects anything else.
387
+ observation?: string;
388
+ // The acting entity (holds the capability + niche). Defaults to cfg.defaultCaster
389
+ // (the PC), but any actor with an [[actors]] row can act — a MONSTER caster wires
390
+ // identically.
391
+ caster?: string;
392
+ casterNode?: string;
393
+ // Emit an `[[actors]]` steering row for the caster (entity_key + name). A monster
394
+ // caster needs one (r_manipulate drives a bound actor); a PC already has it. No
395
+ // `[[actor_identities]]` is needed — r_manipulate takes actor_id as a plain param,
396
+ // it does not validate the sender's identity against the caster (B6a finding).
397
+ emitCasterActor?: boolean;
398
+ // Emit placement rows for a newly fan-out monster actor. This is fixture wiring,
399
+ // not behavior substrate: the monster still attacks through the same capability
400
+ // cluster as an already placed actor.
401
+ emitCasterEntity?: boolean;
402
+ casterEntityDefId?: string;
403
+ casterKind?: "npc" | "player" | "item" | "place";
404
+ casterName?: string; // [[actors]].name when emitCasterActor is set
405
+ // #728 — DEF-LEVEL capability binding. When set, emit an
406
+ // `entity_definition_initial_capability` row binding THIS behavior's capability
407
+ // to the named `entity_definition`. At instance birth (manifest placement or
408
+ // runtime spawn) the server's `apply_definition_seeds` copies the capability onto
409
+ // the placed entity (an entity-anchored `capability` row, ADR-0028 D-5) — so every
410
+ // instance of the definition is born combat-capable, with NO per-instance
411
+ // `actor_capabilities` grant. This is the SCALE unlock that lets the 385-strong
412
+ // `monsters.toml` catalog carry its proven actions by definition, not by hand.
413
+ bindToDefinition?: string;
414
+ // #728 PROOF instance. Place a fresh entity carrying `bindToDefinition` as its
415
+ // `entity_def_id`, with a steering `[[actors]]` body but deliberately NO
416
+ // `actor_capabilities` row. r_manipulate's selection gates on the caster actually
417
+ // HOLDING the capability (selection.rs — it distinguishes "capability-not-held"
418
+ // from "niche-not-anchored"), so this instance can act ONLY if it inherited the
419
+ // capability from the definition seed. A successful attack is therefore
420
+ // proof-positive of inheritance. The niche is shared via `node` (defaults to the
421
+ // caster's node, where this behavior already attaches the capability niche).
422
+ defInstance?: { entityKey: string; name: string; node?: string };
423
+ // CLOCK only (#1968 finding C2) — N self-targeted tally ordinals, each a bare
424
+ // ModifyResource(actor="Actor", ...). Order is preserved (ordinal = array index),
425
+ // so author a scratch-cell capture BEFORE the tallies that read it (the death-
426
+ // saves idiom: ordinal 0 captures one d20 draw into a scratch resource via
427
+ // `delta: "d20 - actor.stat('<scratch>')"`, ordinals 1+ then tally that captured
428
+ // value via `predicate` against the SAME scratch resource). Required, non-empty,
429
+ // when `shape` is "clock".
430
+ clockTallies?: ClockTally[];
431
+ // CLOCK only — M threshold ordinals, appended AFTER every tally ordinal (so each
432
+ // threshold's `when` can read the tallies' post-write values, the same
433
+ // ordinal-sorted-sequential-commit idiom the lethal attack write and this shape's
434
+ // own fixture precedent both rely on). Each becomes a
435
+ // ForEachActorInRadius(node_ball, ball_radius 0) wrapping ONE ApplyStatus/
436
+ // RemoveCondition on "Actor" — see the shape's own doc comment for why the radius
437
+ // wrapper is safe despite every tally writing "Actor" alone. Required, non-empty,
438
+ // when `shape` is "clock".
439
+ clockThresholds?: ClockThreshold[];
440
+ }
441
+
442
+ // One sub-attack of a Multiattack. The full damage-or-nothing Int expression
443
+ // (`cond(<roll> >= AC, 0 - <dice+bonus>, 0)`) is the frame_write's delta_source.
444
+ export interface MultiAttack {
445
+ deltaSource: string;
446
+ label?: string; // human tag for the report (e.g. "Rend")
447
+ }
448
+
449
+ // One tally ordinal of a "clock" behavior (#1968 finding C2) — a bare
450
+ // ModifyResource(actor="Actor", resource, delta_source) frame_write. `resource` must
451
+ // already be an authored resource_definitions row (this builder never auto-creates a
452
+ // write-target resource, same posture as every other ModifyResource shape). The
453
+ // delta_source itself is EITHER:
454
+ // • `delta` alone (no `predicate`) — the raw arithmetic idiom a scratch-cell
455
+ // capture needs (death-saves.toml ordinal 0: `"d20 - actor.stat('<scratch>')"`,
456
+ // a set-via-delta that lands exactly on the fresh draw — not a conditional).
457
+ // • `predicate` (+ optional `delta`) — the increment-on-condition idiom every
458
+ // tally-split ordinal needs (death-saves.toml ordinals 1/2: "tally the
459
+ // just-captured roll into exactly one pool"); expands to
460
+ // `cond(<predicate>, <delta ?? "1">, 0)` so the common "+1 on condition" case
461
+ // needs only `predicate`, while a non-unit increment still overrides `delta`.
462
+ // Exactly one of `predicate`/`delta` must be set at the CALLER layer (this type
463
+ // itself allows either or both — `predicate` set makes `delta` the increment amount
464
+ // rather than the whole expression).
465
+ export interface ClockTally {
466
+ resource: string;
467
+ predicate?: string;
468
+ delta?: string;
469
+ }
470
+
471
+ // One threshold ordinal of a "clock" behavior (#1968 finding C2) — a
472
+ // ForEachActorInRadius(center_ref="ActorSpatialRef", core/area/node_ball,
473
+ // ball_radius 0) wrapping ONE ApplyStatus (`applyStatus`) or RemoveCondition
474
+ // (`removeCondition`) body targeting "Actor". `when` is the wrapper's own
475
+ // predicate_source, evaluated against the POST-tally state (this ordinal runs after
476
+ // every `clockTallies` ordinal) — e.g. `"actor.stat('death_save_failures') >= 3"`, or
477
+ // an OR-branched short-circuit like death-saves.toml's nat-20 stable-immediately
478
+ // check. Exactly one of `applyStatus`/`removeCondition` must be set.
479
+ export interface ClockThreshold {
480
+ when: string;
481
+ applyStatus?: string;
482
+ removeCondition?: string;
483
+ // removeCondition only — optional exact source key, mirrors `ActorBehavior.
484
+ // removeConditionSource`. Absent means source-agnostic `Any`.
485
+ removeConditionSource?: string;
486
+ }
487
+
488
+ // One branch arm of an "outcome-graph" spell (#858/ADR-0058). The graph evaluates
489
+ // each root→<node> edge in `authored_order` (= the branches[] index); the first edge
490
+ // whose `guard` predicate is true selects that terminal node, and the node's
491
+ // consequence applies `deltaSource` to `subject`'s `resource` (both default to
492
+ // TargetActor/srd/hp — the damage-against-target shape every branch authored before
493
+ // playable-fighter-l1-20 D-1). Because the guard context has NO actor/target-state
494
+ // bindings (only dice + world-tick), guards branch on a ROLL (`d20 >= AC`,
495
+ // `roll_under(d20, DC)`) — and the last branch is a `"1 == 1"` fallthrough. A single
496
+ // d20 is rolled by the first guard; on a miss it falls through.
497
+ export interface OutcomeBranch {
498
+ node: string; // graph node id (e.g. "hit" / "miss"); also the outcome/consequence id stem.
499
+ guard: string; // edge guard predicate (dice/world-tick only); "1 == 1" = fallthrough.
500
+ deltaSource: string; // resource delta the selected node applies ("0 - 4d4" damages).
501
+ label?: string; // human tag for the report.
502
+ // Playable-fighter-l1-20 D-1: the branch's own write subject/resource — a
503
+ // kernel symbolic actor ref ("Actor" / "TargetActor"). Both omitted keeps
504
+ // the byte-identical pre-D-1 shape: ModifyResource(TargetActor, srd/hp, ...).
505
+ subject?: string; // default "TargetActor"
506
+ resource?: string; // default "srd/hp"
507
+ }
508
+
509
+ export interface BehaviorConfig {
510
+ bundleId: string;
511
+ manifestPath: string;
512
+ // capability id = `<idNamespace>/${capPrefix}/${key}` ; action id =
513
+ // `<idNamespace>/${actionPrefix}${key}`.
514
+ capPrefix: string;
515
+ actionPrefix: string;
516
+ defaultCaster: string;
517
+ defaultCasterNode: string;
518
+ objectStateSeeds?: ObjectStateSeed[];
519
+ // Bundle/namespace override for the derived capability/action/outcome/affordance/
520
+ // success ids (#1968 FIX③ de-fork). Defaults to "srd" — unset is byte-identical for
521
+ // every existing SRD driver (none of which sets it today). A bundle-generic caller
522
+ // (e.g. the shared tool runtime `spellkave_define_behavior` verb) sets this to its OWN
523
+ // `bundleId` so `ids()` derives `<bundle>/spell/<key>` / `<bundle>/cast_<key>`
524
+ // instead of hardcoded `srd/...`. Follows the same override-hook precedent
525
+ // `ActorBehavior.capabilityId` already set for the id as a WHOLE — this overrides
526
+ // only the leading namespace segment, so `capPrefix`/`actionPrefix` keep composing
527
+ // normally underneath it.
528
+ idNamespace?: string; // default "srd"
529
+ }
530
+
531
+ export interface ObjectStateSeed {
532
+ entityKey: string;
533
+ stateId: string;
534
+ valueInt: number;
535
+ sourceTemplateId: string;
536
+ }
537
+
538
+ // FIXTURE-HYGIENE INVARIANT (#1267 follow-up): the generic `srd` bundle's `base/**`
539
+ // fragments carry ONLY definitions/templates/vocab — never INSTANCE rows. An instance
540
+ // row places/binds a CONCRETE actor or cell into the world; shipping one in the generic
541
+ // bundle drags fake townsfolk + proof cells into every world that loads `srd`. These are
542
+ // the instance-row tables: they belong in a CONTENT bundle (phandelver/demos) or a
543
+ // TEST-ONLY proof fragment the harness loads explicitly, never in `base/**`. The
544
+ // mechanical lint (retired 2026-08-11, archived to
545
+ // `archive/scripts/ci/check-srd-fixture-hygiene.sh`) used to fatal on any of these in
546
+ // `archive/world-fixtures/srd/base/*.toml`. `clusterRows` emits several of them (the live-wiring
547
+ // rows that let a behavior fire); a split driver (see author-persuasion.ts) partitions
548
+ // them out into the proof fragment by this exact set.
549
+ export const INSTANCE_ROW_TABLES: ReadonlySet<string> = new Set([
550
+ "entities",
551
+ "actors",
552
+ "actor_spatial_locations",
553
+ "actor_capabilities",
554
+ "object_state",
555
+ "place_nodes",
556
+ "spatial_niche_attachments",
557
+ "actor_identities",
558
+ ]);
559
+
560
+ // #1968 R7 slice 4.10 (ADR-0087): `clusterRows` is now a thin forwarder to
561
+ // spellkave-authoring's Rust `compose::cluster_rows` — the final assembly of
562
+ // every shape/modifier ported across tasks.md 4.1-4.9 (`ids`, live-wiring,
563
+ // single-target, aoe, attacks/resourceCost, zone/env-state/scheduled-zone,
564
+ // summon, outcome-graph, clock). See that module's own doc comment for the
565
+ // full per-row provenance this function used to carry directly.
566
+ export function clusterRows(
567
+ behaviors: ActorBehavior[],
568
+ cfg: BehaviorConfig,
569
+ ): Record<string, unknown> {
570
+ return JSON.parse(cluster_rows_json(JSON.stringify(behaviors), JSON.stringify(cfg))) as Record<
571
+ string,
572
+ unknown
573
+ >;
574
+ }
575
+
576
+ // Concat-merge a set of row-table maps (later sets append after earlier ones),
577
+ // preserving the per-table array shape clusterRows / extraRows use.
578
+ export function mergeRowTables(
579
+ ...sets: (Record<string, unknown[]> | Record<string, unknown> | undefined)[]
580
+ ): Record<string, unknown[]> {
581
+ const out: Record<string, unknown[]> = {};
582
+ for (const set of sets) {
583
+ for (const [table, rows] of Object.entries(set ?? {})) {
584
+ out[table] = [...(out[table] ?? []), ...(rows as unknown[])];
585
+ }
586
+ }
587
+ return out;
588
+ }
589
+
590
+ // Strip the [[bundles]]/[metadata] headers from a rendered manifest, leaving only
591
+ // row tables — the shape an [[include]] fragment carries (the root manifest.toml owns
592
+ // schema_version/[[bundles]]/[metadata]). Exported (#1968 srd verb-layer migration):
593
+ // a verb-driven fragment generator (packages/spellkave-shared tool runtime's
594
+ // AuthorToolContext/memoryWorkspace) accumulates a fragment's rows via tool calls
595
+ // rather than an explicit `rows` object, so it needs this same header-stripping
596
+ // applied to the WORKSPACE's own rendered TOML — see
597
+ // packages/spellkave-srd/src/author/verb-fixture.ts.
598
+ export { stripManifestHeaders } from "./manifest-text";
599
+
600
+ // Render a header-stripped [[include]] fragment off the real manifest header, from an
601
+ // explicit set of row tables (already merged). Goes through the SAME author SDK render
602
+ // path (renderSchemaManifestJson) — never hand-rolled TOML.
603
+ export function renderFragmentFromRows(
604
+ baseManifest: Record<string, unknown>,
605
+ rows: Record<string, unknown[]>,
606
+ ): string {
607
+ const base = JSON.parse(JSON.stringify(baseManifest)) as Record<string, unknown>;
608
+ delete base.include;
609
+ Object.assign(base, rows);
610
+ return stripManifestHeaders(renderSchemaManifestJson(JSON.stringify(base)));
611
+ }
612
+
613
+ // Render a COMPLETE standalone manifest (headers KEPT) from a schema-shaped object
614
+ // (schema_version + [metadata] + [[bundles]] + row tables). Used for a TEST-ONLY proof
615
+ // fragment that is applied on its own (not [[include]]-d into a shipped manifest).
616
+ export function renderCompleteManifest(manifestObj: Record<string, unknown>): string {
617
+ return renderSchemaManifestJson(JSON.stringify(manifestObj));
618
+ }
619
+
620
+ // Render a header-stripped [[include]] fragment off the real manifest header.
621
+ function buildFragment(
622
+ baseManifest: Record<string, unknown>,
623
+ behaviors: ActorBehavior[],
624
+ cfg: BehaviorConfig,
625
+ extraRows?: Record<string, unknown[]>,
626
+ ): string {
627
+ // Bespoke rows (e.g. an ambient-effect spell's CONSUMER scene: a node-anchored
628
+ // affordance + niche + counter-capability) that the per-behavior cluster shape
629
+ // cannot express. Merged (concat) into the same schema JSON so they render through
630
+ // the SAME author SDK path — never hand-rolled TOML.
631
+ const merged = mergeRowTables(clusterRows(behaviors, cfg), extraRows);
632
+ return renderFragmentFromRows(baseManifest, merged);
633
+ }
634
+
635
+ // Read the manifest header, build the cluster fragment, write it with a banner.
636
+ // #835 safeguard data — every `entity_definition.entity_def_id` across the bundle's
637
+ // `[[include]]` closure (the catalog). The package's `assertSpellCatalogBinding` is
638
+ // fs-free, so the driver (which HAS fs) gathers the known ids here and feeds them in.
639
+ async function collectBundleEntityDefIds(manifestPath: string): Promise<Set<string>> {
640
+ const ids = new Set<string>();
641
+ const add = (m: Record<string, unknown>) => {
642
+ const defs = Array.isArray(m.entity_definitions) ? m.entity_definitions : [];
643
+ for (const d of defs) {
644
+ const id = (d as { entity_def_id?: string }).entity_def_id;
645
+ if (id) ids.add(id);
646
+ }
647
+ };
648
+ const rootToml = await readFile(manifestPath, "utf8");
649
+ const root = inspectManifest(rootToml).manifest as Record<string, unknown>;
650
+ add(root);
651
+ const dir = dirname(manifestPath);
652
+ // Include fragments are header-stripped row tables, but inspectManifest requires a
653
+ // `#:schema` directive + schema_version — lift both from the root and prepend per
654
+ // fragment (the same trick the author-CLI's `inspect --bundle` / `validate --bundle` use).
655
+ const schemaLine = rootToml.split("\n").find((l) => l.startsWith("#:schema")) ?? "";
656
+ const version = typeof root.schema_version === "string" ? root.schema_version : "1.0.0";
657
+ const fragHeader = `${schemaLine}\nschema_version = "${version}"\n\n`;
658
+ const includes = Array.isArray(root.include) ? root.include : [];
659
+ for (const entry of includes) {
660
+ const rel = (entry as { path?: string })?.path;
661
+ if (!rel) continue;
662
+ try {
663
+ const frag = await readFile(resolve(dir, rel), "utf8");
664
+ add(inspectManifest(`${fragHeader}${frag}`).manifest as Record<string, unknown>);
665
+ } catch {
666
+ // a missing include is the validator's problem (MF-VAL), not the safeguard's.
667
+ }
668
+ }
669
+ return ids;
670
+ }
671
+
672
+ export async function authorBehaviorFragment(opts: {
673
+ out: string;
674
+ header: string;
675
+ behaviors: ActorBehavior[];
676
+ cfg: BehaviorConfig;
677
+ // Bespoke schema rows merged into the same render (see buildFragment). Keyed by
678
+ // table name (e.g. `niche_definitions`, `affordance_templates`, `actors`).
679
+ extraRows?: Record<string, unknown[]>;
680
+ }): Promise<void> {
681
+ const baseManifest = inspectManifest(await readFile(opts.cfg.manifestPath, "utf8"))
682
+ .manifest as Record<string, unknown>;
683
+
684
+ // #835 — fail at author time if a self-emitted `srd/spell/*` capability has no
685
+ // matching catalog entity_definition (the immediate-error form of MF-VAL-264). Only
686
+ // behaviors that EMIT their own capability are guarded; `emitCapability:false` spells
687
+ // reuse an externally-authored cap on purpose (guidance, the accepted stragglers).
688
+ const catalogIds = await collectBundleEntityDefIds(opts.cfg.manifestPath);
689
+ for (const b of opts.behaviors) {
690
+ if (!b.emitCapability) continue;
691
+ assertSpellCatalogBinding(b.capabilityId ?? `srd/${opts.cfg.capPrefix}/${b.key}`, catalogIds);
692
+ }
693
+
694
+ const body = buildFragment(baseManifest, opts.behaviors, opts.cfg, opts.extraRows);
695
+ await writeFile(opts.out, `${`${opts.header}\n${body}`.replace(/\n+$/, "")}\n`, "utf8");
696
+ console.log(
697
+ `[behavior-cluster] wrote ${opts.out} (run full-bundle validate to gate cross-refs).`,
698
+ );
699
+ }