4 Commits
Author SHA1 Message Date
EnragedAntelope 4f4dcc5245 SceneWeaver 0.8.2
- nodes: drop the NaN fingerprint_inputs from both node classes so ComfyUI's input cache stops re-running every downstream node
- tests: registration test pins no fingerprint_inputs override; new test that a cached SCENE_ENTITY payload is reused unchanged
- engine: _rescope_slot revive is a required mutable set; generate_scene docstring matches _occupied_slots
- data/scifi.py: "spine-ringed shell" -> "spine-fringed shell", "concentric-ring rosettes" -> "concentric-banded rosettes", "coiling itself into a defensive ring" -> "looping itself into a defensive circle" (ring motif under its ceiling at 1000 seeds)
- ci.yml: sample_distribution runs 1000 seeds per pack
- pyproject: 0.8.2; ruff lint rules pinned to the set CI's ruff applies
- docs: architecture.md 0.8.2 section, AGENTS.md current state, registry release checks doc
2026-11-24 20:47:53 -05:00
EnragedAntelope f2ebabf6d1 SceneWeaver 0.8.1
- A locked value a drawn field contradicts re-draws that field instead of only warning (engine/scene.py _redraw_triggers)
- Fantasy: dormant undead on the seabed and dead flying ships in the sky, a courtyard or a quay get an act
- Fantasy: a wrecked airship in the sky plunges with a torn gasbag; torn gasbag form gains the falls stance
- Fantasy: rigging, not a gasbag, on wrecked sky galleons and cloud skiffs; no huge subjects in the forge; merfolk no longer brace against a gust underwater
- Thrown objects say their direction; renamed acts: "snapping at a spear hurled straight at it", "snatching a dagger thrown at them out of the air", "lying wrecked in a tangle of torn rigging", horror "lurching away from a torch thrust toward them"
- coherence_audit.py and coherence_sweep.py take --pack; CI sweeps fantasy and horror on both paths
- Version 0.8.1; AGENTS.md state
2026-10-17 12:12:05 -04:00
EnragedAntelope b63937b429 Round XXXI: audits take --pack; locks re-draw what contradicts them
- coherence_audit.py and coherence_sweep.py take --pack; the sweep runs pack classes and shape_classes for fantasy and horror
- Fantasy and horror fixes the sweeps found: dormant undead and dead flying ships with no act, gasbag act on gasbag-less ships, forge trait overwrite, merfolk gust act
- Thrown-object acts state their direction; TRAP_PHRASES rejects the undirected form; four acts renamed
- engine/scene.py: _redraw_triggers re-draws an unlocked field that makes a rule forbid a locked value
- Torn gasbag form gains the falls stance; the plunge act needs it
- CI: fantasy and horror coherence sweeps on both paths
- Regression rows for each fix; README, AGENTS.md, docs/architecture.md updated
2026-10-17 09:47:38 -04:00
EnragedAntelope c27d0fd843 SceneWeaver 0.8.0
- Hidden variant draw per type (VARIANT_FIELD, widget "hidden"): owned looks marked in value_variants, filtered by variant_mask after bans, spoken as a head modifier
- Owned-act weighting: genre.own_values; shared acts scale by reach ** -specificity_exponent (0.5 per pack)
- Scene globals: Placement (staging) and Place state (aspect) widgets after Context; scene_globals, ProseSpec.scene_field_moves, ResolvedScene.scene_values
- Foreground context framings gated by Sentence.traits and the near-prop trait
- Content in all three packs: variants, forms, own acts per group, contexts, placements and place states until every variety floor passes
- Viewer-facing acts rewritten against something in the place; verb-spread renames
- Shared placement and room state fit every place that draws them
- Weapon acts name the carried weapon ("their weapon"); dormant acts drop held weapons (fantasy, horror)
- POSTURE_VERBS in data/genre.py: a form naming a posture gives way to an act naming another
- Acts speak their subject's pronoun; half-human forms name a human face; hoofed-folk own acts are person acts
- Horror undead weapons tagged carried-weapon; clawing and dragging acts tagged both-hands-act; feeding acts need flesh
- Centaur: large scale only, no pony form, no horse tail, breastplate in place of war harness; faun speaks as plain "faun" with short horns; "long braid" in place of "long braided hair"
- Grandfather clock and family picture need a domestic place
- Render-trap renames: net, fire-damage, sheeting, ducting, spar and bow, salvage drones, coin-sized, scythe, bare spectral flame, sampling scoop
- validate_data: variety floors (FORMFLOOR, VARIANTFLOOR, ACTSPEC, CONTEXTFLOOR, STAGEFLOOR, ASPECTFLOOR, VIEWER, FRAMING), TYPEECHO, REPEAT
- reach_audit: --variety mode, --seed, locked path by name; shared subjects and reach helpers in data/genre.py
- concern_flags_0914: drag-without-grip no longer matches "toward"
- Example workflows carry Placement and Place state
- Tests: widget_fields helper, variant mask and specificity, context floor, regression rows from three render batches, PronounTests
- pyproject 0.8.0; AGENTS.md, README and architecture Round XXX
- Breaking: saved workflows that locked a renamed or removed act, form or variant report "value not in list"; seeds do not reproduce 0.7.0 prompts
2026-10-13 22:57:42 -04:00
36 changed files with 6134 additions and 834 deletions
+13 -3
View File
@@ -55,15 +55,25 @@ jobs:
# Bias is measured, not assumed: a distribution defect has no
# single-scene symptom. Fails if one kind or the scale extremes break
# their documented ceiling; the baseline is in docs/architecture.md.
run: python scripts/sample_distribution.py --seeds 500
run: python scripts/sample_distribution.py --seeds 1000
- name: Measure the fantasy distribution
run: python scripts/sample_distribution.py --pack fantasy --seeds 500
run: python scripts/sample_distribution.py --pack fantasy --seeds 1000
- name: Measure the horror distribution
run: python scripts/sample_distribution.py --pack horror --seeds 500
run: python scripts/sample_distribution.py --pack horror --seeds 1000
- name: Audit the reported concern classes
# The user's own graph: a Scene Entity wired into the Scene Weaver. Every class a
# reported image fell into must stay absent; the flags are frozen in scripts/concern_flags.py.
run: python scripts/concern_audit.py --seeds 600 --gate
- name: Sweep the fantasy pack for coherence
# The pack tests sweep 400-500 seeds; these sweep thousands, which is what
# finds a rare draw. Ceilings live in scripts/coherence_sweep.py.
run: |
python scripts/coherence_sweep.py --pack fantasy --gate
python scripts/coherence_sweep.py --pack fantasy --gate --path unwired
- name: Sweep the horror pack for coherence
run: |
python scripts/coherence_sweep.py --pack horror --gate
python scripts/coherence_sweep.py --pack horror --gate --path unwired
frontend:
name: Frontend tests
+51 -12
View File
@@ -8,15 +8,25 @@ genre is a data module and two registration lines.
## Current state
_Last verified: 2026-10-07_
_Last verified: 2026-11-24_
- **Status:** v0.7.0 on `main`, released on GitHub and published to the ComfyUI
- **Status:** `main` is v0.8.2, released on GitHub and published to the ComfyUI
Registry by `publish.yml`; all three genres on one coherence engine. 0.6.0
added user_options keys that follow the scope chain, a working recreate, the
speedup and gates, a content round in all three packs, and two render-test
rounds of fixes. 0.7.0 adds Round XXVIII's fixes and Round XXIX's subgenre
content (post-collapse horror places, grown sci-fi places and void-order rites,
fantasy brass beasts and weather). The repo is public at `EnragedAntelope/comfyui-sceneweaver`;
fantasy brass beasts and weather). 0.8.0 is the variety release (Round XXX):
a hidden variant draw per type, owned-act weighting, the Placement and Place
state widgets, foreground context framings and the variety floors. 0.8.1 is
Round XXXI: the audits take `--pack`, the fixes they found in fantasy and
horror, and a locked value re-drawing the field that contradicts it. 0.8.2
drops the nodes' `NaN` cache fingerprint, which re-ran every downstream node
on each queue ("0.8.2: the input cache is ComfyUI's" in
`docs/architecture.md`), and rewords three sci-fi values that pushed the
`ring` motif over its ceiling. Registry: 0.8.1 was still Flagged on 2026-11-24 on
the recreate code's known false positive, review request open (see
`docs/registry-release-checks.md`). The repo is public at `EnragedAntelope/comfyui-sceneweaver`;
the full pre-release history stays local (a git bundle outside the repo, and
the `coherence-round-*` branches).
- **Works:** both node classes per genre register through the V3
@@ -28,27 +38,39 @@ _Last verified: 2026-10-07_
order and validates both example workflows. Every gate under "Build and test"
is green. The mechanisms and every round's decisions and measurements are in
`docs/architecture.md` ("Round XV" to "Round XXVIII" are the render-test rounds;
"Round XXIX" is the subgenre content round).
- **In progress:** nothing is open. Rounds XXVIII and XXIX are released in 0.7.0
but not yet render-tested by the maintainer, who keeps render-testing;
"Round XXIX" is the subgenre content round; "Round XXX" is the variety round;
"Round XXXI" gives the audits `--pack` and fixes what they found). Scene
output is a pure function of the inputs, so ComfyUI's input cache is correct
for both nodes; no `fingerprint_inputs` override.
- **In progress:** nothing unmerged. Every merge to `main` beyond docs carries a
version bump, which publishes. 0.8.0 went through three render batches
(Round XXX), two of them reviewed by the maintainer, who keeps
render-testing;
each reported image becomes a fix plus a regression row. Head cropping on tall
subjects was seen and deliberately not addressed yet (no forced "full figure"
framing until it recurs). Not built: a headless horseman, carrion crows, an
exorcist and a mortician (the last two would only reskin the village priest).
- **Known gaps:**
- A situation can disagree with the pose a model draws (a fire drake breathing
fire instead of "snapping at a spear") with no text contradiction behind it.
It is a model-fidelity limit; there is no wording fix.
fire instead of snapping at a spear) with no text contradiction behind it.
It is a model-fidelity limit. The one wording fix is direction: an object
thrown by someone off-frame says it comes "at it" (`TRAP_PHRASES`).
- Small alien creatures still name limbs, a natural weapon, senses and a mouth
by design, so a render can show odd protrusions. Watch small creatures.
- `scripts/reach_audit.py --gate` samples, so a low seed count lists rare
place-and-kind combinations as never drawn; use 30000 seeds. CI does not run it.
- Only `scripts/reach_audit.py` and `scripts/sample_distribution.py` take
`--pack`. `concern_audit.py`, `coherence_sweep.py` and `coherence_audit.py`
measure sci-fi only, and the frozen `concern_flags*` are sci-fi's.
- `concern_audit.py` is sci-fi only, by design: it replays the frozen
`concern_flags*` of reported sci-fi batches, and fantasy and horror have
none. Every other script takes `--pack`. CI runs `coherence_sweep.py`
for fantasy and horror on both paths, and the sci-fi classes run as
unit tests; it does not run `reach_audit.py`.
- Renaming or removing a dropdown value makes a saved workflow that locked it
report "value not in list" (0.7.0 renamed the sci-fi situation "writhing in a
tight coil" to "thrashing violently in place"). Release notes live in commit messages, never in
tight coil" to "thrashing violently in place"; 0.8.0 rewrote the acts aimed
at "the viewer" and renamed many acts for verb spread; Round XXXI renames
four acts, listed there; 0.8.2 rewords three sci-fi values, listed in
its section). Seeds do not
reproduce 0.7.0 prompts: the variant and the new scene fields are drawn. Release notes live in commit messages, never in
the README (maintainer's rule).
- Cross-genre trait conflicts fail open: a wired foreign entity carries no
traits into the host scene (`docs/genre-roadmap.md` proposes carrying them). A
@@ -83,6 +105,11 @@ _Last verified: 2026-10-07_
all three packs, and one section per render-test round. `docs/genre-roadmap.md`
- the genre content brainstorm and the decisions behind it.
## Registry releases
Before publishing or investigating Manager visibility, read
[Registry release checks](docs/registry-release-checks.md).
## Layout
| Path | What lives there |
@@ -120,6 +147,10 @@ python scripts/coherence_audit.py --seeds 2000
python scripts/concern_audit.py --seeds 600 --gate
python scripts/coherence_sweep.py --gate
python scripts/coherence_sweep.py --gate --path unwired
python scripts/coherence_sweep.py --pack fantasy --gate
python scripts/coherence_sweep.py --pack fantasy --gate --path unwired
python scripts/coherence_sweep.py --pack horror --gate
python scripts/coherence_sweep.py --pack horror --gate --path unwired
npm ci && npm run test:frontend
python -m ruff check .
```
@@ -158,6 +189,14 @@ that reads a gitignored file passes locally and fails on a clean checkout.
exempt only as stranger vocabulary (`_default` alone) or when every archetype
that reaches it lists the field in `omits`. There is no allowlist -- fix the
scope, the need, or replace the value.
- **A variant is a mask, not a scope.** Its owned looks live in the type's own
pool literals, marked in `value_variants`; `variant_mask` filters the drawn
pool. Making it a scope key would break the frontend's dropdown narrowing for
a field with no widget.
- **Placement is relative to the place, never the camera.** Placement says how
far off the subject is and what it stands beside; pose and heading stay the
act's. A shared Placement or Place state pool must fit every place that
draws it (an attic is never flooded, snowbound woods have no long grass).
- **A secondary actor is a machine, not a crowd.** A wreck is examined by a
hovering survey drone, not by a survey team; a small crew stays only in
interiors and in a spacefarer's own situations.
+11 -1
View File
@@ -125,13 +125,23 @@ Every dropdown offers `Random`, then its values, then `None`:
* **a value** - **lock it.** Set `Creature type: cephalopod` and every scene is a
cephalopod, with everything else still rolling around it. Lock the creature
type and the hull colour and the environment; leave the rest wild. A locked
field is never cut and never overruled.
field is never cut and never overruled: a rolled field that contradicts it is
rolled again.
* **`None`** - omit it. Switch a slot's `kind` to `None` and that entity leaves
the scene entirely, which is how you get a pure-landscape shot.
Locking is the whole workflow: find a creature you like, pin the two or three
fields that made it work, and generate a hundred variations of *that*.
Two scene dropdowns sit right after **Context**:
* **Placement**: where the subject is in the place, such as "at the far end of
the hall" or "half-hidden among the reeds". It never says anything about the
camera. Set it to `None` if your own prompt already frames the shot.
* **Place state**: the weather, the season, or what has happened to the place,
such as "under a fresh fall of snow", "freshly ransacked" or "scorched by a
recent wildfire".
Coherence is enforced while it draws, not patched afterwards. Pick
**Type: gas giant** and the **Form** dropdown narrows, live, to sphere shapes -
you will not get a gas giant shaped like a spiral coil, or a gelatinous mass
+1757 -307
View File
File diff suppressed because it is too large Load Diff
+305 -23
View File
@@ -38,7 +38,7 @@ from dataclasses import MISSING, dataclass, field, fields as dataclass_fields, r
from itertools import combinations
from string import Formatter
from types import MappingProxyType
from typing import Any, Mapping
from typing import Any, Iterator, Mapping
# ---------------------------------------------------------------------------
# Widget vocabulary
@@ -105,6 +105,21 @@ ENVIRONMENT_FIELD = "environment"
#: declares no ``context`` field simply renders no context sentence.
CONTEXT_FIELD = "context"
SITUATION_FIELD = "situation"
#: An act's first word that sets the body's posture. A pack tags its forms that
#: name a posture, and an act naming another overrules them.
POSTURE_VERBS: dict[str, frozenset[str]] = {
"stand": frozenset({
"standing", "walking", "striding", "pacing", "lurching", "shambling", "marching", "stalking",
"running", "sprinting", "charging", "stepping", "wandering", "limping", "dancing",
}),
"sit": frozenset({"sitting", "seated"}),
"kneel": frozenset({"kneeling"}),
"lie": frozenset({"lying", "sprawling", "sprawled", "reclining"}),
}
#: A subject's hidden design line (an orc war-band, a mech lineage). Never a
#: widget: it is drawn per entity and masks the looks it owns -- see
#: ``variant_mask``. A pack that declares no such field is unaffected.
VARIANT_FIELD = "variant"
RELATION_FIELD = "relation"
RELATION_POSITION_FIELD = "relation_position"
@@ -122,6 +137,11 @@ SCENE_FIELD_NAMES: tuple[str, ...] = (
ENVIRONMENT_FIELD, SITUATION_FIELD, RELATION_FIELD, RELATION_POSITION_FIELD
)
#: Where a scene global is spoken -- see ``ProseSpec.scene_field_moves``.
MOVE_ENVIRONMENT = "environment"
MOVE_LEAD = "lead"
SCENE_FIELD_MOVES: frozenset[str] = frozenset({MOVE_ENVIRONMENT, MOVE_LEAD})
#: Pool key used when a field has no per-kind override. Reading through to it is
#: a *documented fallback*, not an accident -- see ``pool_for``.
POOL_DEFAULT_KEY = "_default"
@@ -260,16 +280,24 @@ class FieldSpec:
#: field's clause (a count into its noun, a glow colour into its emitter).
#: Such fields are absent from ``prose.entity_clause_order`` by construction.
renders_with: str | None = None
#: "combo" or "int". Only ``seed`` is an int, but the contract carries the
#: distinction rather than special-casing one field name in the node code.
#: "combo", "int" or "hidden". Only ``seed`` is an int, but the contract
#: carries the distinction rather than special-casing one field name in the
#: node code. A hidden field is resolved and written to ``prompt_json`` but
#: has no widget, so it never moves the widget order.
widget: str = "combo"
#: Widget default. Descriptive fields default to ``RANDOM`` -- full random
#: with no configuration is the pack's headline behaviour.
default: Any = RANDOM
def __post_init__(self) -> None:
if self.widget not in ("combo", "int"):
raise ValueError(f"FieldSpec.widget must be 'combo' or 'int', got {self.widget!r}")
if self.widget not in ("combo", "int", "hidden"):
raise ValueError(
f"FieldSpec.widget must be 'combo', 'int' or 'hidden', got {self.widget!r}"
)
if self.widget == "hidden" and (self.brief or self.control):
raise ValueError(
f"hidden field {self.label!r} cannot be brief or a control: it has no widget"
)
if self.control and self.optional:
raise ValueError(
f"control field {self.label!r} cannot be optional: a control is read "
@@ -684,9 +712,16 @@ class Sentence:
#: until it has a reason to say otherwise. Genre-blind: the engine only
#: checks that one set of words contains another.
needs: frozenset[str] = frozenset()
#: Traits the drawn value must carry before this sentence may be drawn.
#:
#: The context counterpart of ``needs``: "In the foreground is a water
#: trough" suits a thing that can sit near, and puts a moon in front of the
#: subject. Empty means any value; the engine only tests containment.
traits: frozenset[str] = frozenset()
def __post_init__(self) -> None:
object.__setattr__(self, "needs", frozenset(self.needs))
object.__setattr__(self, "traits", frozenset(self.traits))
object.__setattr__(self, "_segments", _parse_sentence(self.text))
@@ -834,6 +869,13 @@ class ProseSpec:
#: text-to-image model grounds anything it is not told floats: a station in a
#: debris belt is drawn standing on the debris.
environment_staging: tuple[tuple[str, str], ...] = ()
#: ``{scene global field: move}`` -- where a scene-wide value beyond the
#: context is spoken. ``"environment"`` appends ", {value}" to the setting
#: sentence ("Set in a village green, under a fresh fall of snow");
#: ``"lead"`` opens the hero's first sentence with it ("At the far end of the
#: hall, a banshee is ..."). A scene global with no move is never voiced,
#: which construction refuses.
scene_field_moves: Mapping[str, str] = field(default_factory=dict)
#: The context sentence plan, emitted once per scene after the entities when
#: the pack declares a ``context`` field. One pattern is drawn at random per
#: scene; ``{context}`` is the value bare, ``{a_context}`` its articled form,
@@ -906,6 +948,13 @@ class ProseSpec:
self, "environment_staging",
tuple((affordance, suffix) for affordance, suffix in self.environment_staging),
)
object.__setattr__(self, "scene_field_moves", _freeze(self.scene_field_moves))
for name, move in self.scene_field_moves.items():
if move not in SCENE_FIELD_MOVES:
raise ValueError(
f"scene_field_moves[{name!r}] is {move!r}; expected one of "
f"{sorted(SCENE_FIELD_MOVES)}"
)
self._validate_templates()
def _check_template(self, name: str, template: str) -> None:
@@ -1103,6 +1152,18 @@ class GenrePack:
#: class, a state). Expanded with ``trait_conflicts`` into ordinary exclusion
#: rules by genre-blind code; the engine never learns what a trait means.
value_traits: Mapping[str, Mapping[str, frozenset[str]]] = field(default_factory=dict)
#: ``{field: {value: frozenset(variant)}}`` -- which design lines own a look.
#:
#: An owned value is drawn only when one of its owners is the entity's
#: ``VARIANT_FIELD`` value; an unowned one only when no owner of anything in
#: that pool was drawn. So "war-painted hide" comes with its war-band and a
#: frost-clan orc gets the frost-clan's furs, without either being a scope
#: key the node face would have to narrow by. See ``variant_mask``.
value_variants: Mapping[str, Mapping[str, frozenset[str]]] = field(default_factory=dict)
#: How strongly an act many subjects share is outweighed by one few do.
#: Each situation weight is multiplied by ``reach ** -exponent``, where
#: reach is the number of subjects whose pool holds the act. 0 is flat.
specificity_exponent: float = 0.0
#: ``{field: {value: stances}}`` -- how a shape can hold itself up. A torus
#: cannot stand on the ground; a walker chassis cannot hang in vacuum doing
#: something that needs footing; a world only orbits. Place affordances
@@ -1285,6 +1346,7 @@ class GenrePack:
object.__setattr__(self, "value_needs", _freeze_nested_sets(self.value_needs))
object.__setattr__(self, "default_needs", _freeze_nested_sets(self.default_needs))
object.__setattr__(self, "value_traits", _freeze_nested_sets(self.value_traits))
object.__setattr__(self, "value_variants", _freeze_nested_sets(self.value_variants))
object.__setattr__(self, "value_stances", _freeze_nested_sets(self.value_stances))
object.__setattr__(self, "place_stances", _freeze_sets(self.place_stances))
object.__setattr__(
@@ -1458,6 +1520,8 @@ class GenrePack:
raise ValueError(f"{name!r} renders_with {spec.renders_with!r}, which is not a field")
self._validate_declarations()
self._validate_variants()
self._validate_scene_globals()
self._validate_tiers()
self._validate_vocabularies()
self._validate_prose_addresses()
@@ -1492,6 +1556,80 @@ class GenrePack:
f"shared_vocabulary names {name!r}, which is not an entity field"
)
def _validate_variants(self) -> None:
"""A variant owns real values of real fields, and is drawn before them.
The mask reads the entity's variant from the values already resolved,
so a masked field declared before ``VARIANT_FIELD`` would be drawn
against no variant at all. And the variant is never a scope control:
the node face narrows a dropdown by its scope, and a field with no
widget has nothing to narrow by.
"""
if self.specificity_exponent < 0:
raise ValueError(
f"specificity_exponent is {self.specificity_exponent}; a negative "
"exponent favours the most widely shared acts"
)
if not self.value_variants:
return
if VARIANT_FIELD not in self.entity_fields:
raise ValueError(
f"value_variants is populated but {VARIANT_FIELD!r} is not an entity "
"field, so no variant is ever drawn and every owned value is dead"
)
for name, other in {**self.entity_fields, **self.scene_fields}.items():
if VARIANT_FIELD in other.scope:
raise ValueError(
f"{name!r} scopes on {VARIANT_FIELD!r}; a variant masks pools, it "
"never keys them"
)
variants = set(pool_options(self, VARIANT_FIELD))
order = tuple(self.entity_fields)
for field_name, owned in self.value_variants.items():
if field_name == VARIANT_FIELD:
raise ValueError(
f"value_variants names {VARIANT_FIELD!r}; a variant owns no variant"
)
if field_name not in self.entity_fields and field_name not in self.scene_fields:
raise ValueError(f"value_variants names {field_name!r}, which is not a field")
if (
field_name in self.entity_fields
and order.index(field_name) < order.index(VARIANT_FIELD)
):
raise ValueError(
f"value_variants names {field_name!r}, which resolves before "
f"{VARIANT_FIELD!r}; the mask would never see the variant"
)
options = set(pool_options(self, field_name))
for value, owners in owned.items():
if value not in options:
raise ValueError(
f"value_variants[{field_name!r}] names {value!r}, which is not a "
f"value of {field_name!r}"
)
for owner in owners:
if owner not in variants:
raise ValueError(
f"value_variants[{field_name!r}][{value!r}] names {owner!r}, "
f"which is not a value of {VARIANT_FIELD!r}"
)
def _validate_scene_globals(self) -> None:
"""Every scene-wide field beyond the context has a place to be spoken."""
globals_ = scene_globals(self)
for name in globals_:
if name != CONTEXT_FIELD and name not in self.prose.scene_field_moves:
raise ValueError(
f"scene field {name!r} has no prose.scene_field_moves entry, so it "
"would be drawn every render and never voiced"
)
for name in self.prose.scene_field_moves:
if name not in globals_ or name == CONTEXT_FIELD:
raise ValueError(
f"prose.scene_field_moves names {name!r}, which is not a scene "
"global of this pack (the context has its own sentence)"
)
def _validate_tiers(self) -> None:
"""Structural checks only -- never pool contents.
@@ -2182,7 +2320,8 @@ class GenrePack:
knowing about the other. A field with no tiers keeps its plain weights
and is absent from this map; ``weights_for`` falls through to them.
"""
if not self.value_tiers:
exponent = self.specificity_exponent
if not self.value_tiers and not exponent:
return _EMPTY_MAP
derived: dict[str, Mapping[str, float]] = {}
for field_name, tiers in self.value_tiers.items():
@@ -2195,6 +2334,28 @@ class GenrePack:
for value in pool_options(self, field_name)
}
)
# Specificity: an act a hundred subjects share is the act nobody
# remembers, and a flat draw spends most scenes on it. Scaling by reach
# lets a type's own acts carry it without the engine knowing which those
# are. A type that falls through to a shared pool gets one factor on
# every value, so its draw is unchanged.
if exponent and SITUATION_FIELD in self.pools:
current = derived.get(SITUATION_FIELD)
if current is None:
spec = self.scene_fields.get(SITUATION_FIELD)
current = spec.weights if spec is not None and spec.weights else {}
# An owned act -- one type's, or one whole group's -- is not
# discounted at all: scaling those by reach too would let a type's
# one solo act drown the acts its group owns.
reach = value_reach(self, SITUATION_FIELD)
owned = own_values(self, SITUATION_FIELD)
derived[SITUATION_FIELD] = MappingProxyType(
{
value: current.get(value, 1.0)
* (1.0 if value in owned else max(1, len(reach.get(value, ()))) ** -exponent)
for value in pool_options(self, SITUATION_FIELD)
}
)
return MappingProxyType(derived)
@property
@@ -2332,8 +2493,7 @@ def constraint_address_space(pack: GenrePack, slots: int = SCENE_NODE_SLOTS) ->
``entity5.kind`` is outside the space, because ``slots`` is what a scene has.
"""
space = {ENVIRONMENT_FIELD}
space.add(CONTEXT_FIELD)
space = {ENVIRONMENT_FIELD, CONTEXT_FIELD, *scene_globals(pack)}
for slot in range(1, slots + 1):
space.add(slot_path(slot, SITUATION_FIELD))
for name in pack.entity_fields:
@@ -2635,6 +2795,102 @@ def type_field(pack: GenrePack) -> str | None:
return None
def subjects(pack: GenrePack) -> "Iterator[tuple[str, str | None]]":
"""Every ``(kind, type)`` a scene can hold; ``(kind, None)`` for a kind with no types."""
name = type_field(pack)
for kind in pack.kinds:
values = pool_for(pack, name, {KIND_FIELD: kind}) if name else ()
for value in values or (None,):
yield kind, value
def scene_globals(pack: GenrePack) -> tuple[str, ...]:
"""The scene-wide fields drawn once per scene: the context, placement and so on.
Every ``scene_fields`` entry that is not one of the fixed four, in
declaration order -- which is also their widget order, after the relations.
"""
return tuple(name for name in pack.scene_fields if name not in SCENE_FIELD_NAMES)
def variant_mask(
pack: GenrePack, field: str, pool: "list[str]", scope: Mapping[str, str | None]
) -> "list[str]":
"""``pool`` narrowed to what the entity's variant allows.
``scope`` carries the entity's resolved values, its variant among them.
Ownership is judged against the variants *this* subject is offered, so a
look owned only by another type's variant is neutral here. With a variant
drawn, the values it owns are the pool, else the neutral ones; with none,
the neutral ones. A mask that would empty the pool returns it whole --
re-drawn, never nulled.
"""
owners = pack.value_variants.get(field)
if not owners or VARIANT_FIELD not in pack.entity_fields:
return pool
offered = set(pool_for(pack, VARIANT_FIELD, scope))
if not offered:
return pool
claimed = {value: owners.get(value, frozenset()) & offered for value in pool}
variant = scope.get(VARIANT_FIELD)
if variant is not None:
owned = [value for value in pool if variant in claimed[value]]
if owned:
return owned
return [value for value in pool if not claimed[value]] or pool
def subject_scope(pack: GenrePack, kind: str, value: str | None) -> dict[str, str]:
"""The scope a ``(kind, type)`` subject resolves its pools under."""
scope = {KIND_FIELD: kind}
name = type_field(pack)
if name and value is not None:
scope[name] = value
return scope
def value_reach(
pack: GenrePack, field_name: str, honour_omits: bool = False
) -> "dict[str, list[tuple[str, str | None]]]":
"""``{value: [(kind, type), ...]}`` -- every subject whose resolved pool holds the value.
With ``honour_omits``, a subject whose archetype omits the field reaches
nothing there: it never draws the field, so a part it would fall through to
cannot misfit its body. A wreck's archetype omits ``emitters``, and the
default emitter pool is not its vocabulary. The shadowed-value check keeps
the plain reach, because an omitted pool is still authored vocabulary."""
reach: dict[str, list[tuple[str, str | None]]] = {}
for kind, value in subjects(pack):
scope = subject_scope(pack, kind, value)
if honour_omits:
archetype = archetype_for(pack, scope)
if archetype is not None and field_name in archetype.omits:
continue
for option in pool_for(pack, field_name, scope):
reach.setdefault(option, []).append((kind, value))
return reach
def own_values(pack: GenrePack, field_name: str) -> "dict[str, set[str]]":
"""``{value: owners}`` for every value some group or type owns.
An owner is a type's group, or the type (or kind) itself when ungrouped. A
value is owned when at most three subjects hold it, or when every holder is
in one group: a group of eleven heavy mechs owns the acts all eleven share
and nobody else draws."""
group_of = {
member: group
for group, members in (pack.pool_groups.get(type_field(pack) or "") or {}).items()
for member in members
}
owned: dict[str, set[str]] = {}
for option, holders in value_reach(pack, field_name).items():
keys = {group_of.get(value, value) if value else kind for kind, value in holders}
if len(holders) <= 3 or len(keys) == 1:
owned[option] = keys
return owned
def _stance_scope(pack: GenrePack, kind: str, value: str | None) -> dict[str, str]:
scope = {KIND_FIELD: kind}
name = type_field(pack)
@@ -2723,17 +2979,18 @@ def _values_with_trait(pack: GenrePack, field: str, trait: str) -> tuple[str, ..
value for value, traits in pack.value_traits[field].items() if trait in traits
)
def _trait_address(pack: GenrePack, field_name: str) -> str:
def _trait_address(pack: GenrePack, field_name: str, hero: bool = False) -> str:
"""Where a trait's field sits in a rule: bare for a scene-global field, per slot otherwise.
``context`` is drawn once per scene, so ``entity*.context`` is no address at all; the
situation and the relations are scene fields that still belong to a slot or a pair.
``hero`` binds a per-slot field to slot 1 instead of every slot.
"""
if field_name in pack.scene_fields and field_name not in (
SITUATION_FIELD, RELATION_FIELD, RELATION_POSITION_FIELD,
):
return field_name
return f"entity*.{field_name}"
return slot_path(LONE_ENTITY_SLOT, field_name) if hero else f"entity*.{field_name}"
def _expand_traits(pack: GenrePack) -> tuple[ConstraintRule, ...]:
"""Expand ``trait_conflicts`` into ordinary multi-value exclusion rules.
@@ -2756,12 +3013,18 @@ def _expand_traits(pack: GenrePack) -> tuple[ConstraintRule, ...]:
targets = _values_with_trait(pack, target_field, target_trait)
if not targets:
continue
# Placement says where the *hero* stands, so its conflicts bind
# to slot 1 rather than to every slot.
hero = any(
pack.prose.scene_field_moves.get(name) == MOVE_LEAD
for name in (trigger_field, target_field)
)
rules.append(
ConstraintRule(
type=RULE_EXCLUDE,
field=_trait_address(pack, trigger_field),
field=_trait_address(pack, trigger_field, hero),
values=triggers,
excludes_field=_trait_address(pack, target_field),
excludes_field=_trait_address(pack, target_field, hero),
excludes_values=targets,
reason=pack.trait_reasons.get(
f"{trigger_trait}|{target_trait}",
@@ -3267,6 +3530,11 @@ def _definition(
)
def widget_fields(pack: GenrePack) -> tuple[str, ...]:
"""The entity fields a node shows as widgets: every one but the hidden draws."""
return tuple(n for n, s in pack.entity_fields.items() if s.widget != "hidden")
def _brief_field_names(pack: GenrePack) -> tuple[str, ...]:
"""What a supporting slot carries when nothing is wired into it.
@@ -3323,12 +3591,12 @@ def build_field_definitions(pack: GenrePack, slots: int) -> "OrderedDict[str, Fi
)
if slots == ENTITY_NODE_SLOTS:
for name, spec in pack.entity_fields.items():
for name in widget_fields(pack):
definitions[name] = _definition(
key=name,
path=slot_path(LONE_ENTITY_SLOT, name),
base=name,
spec=spec,
spec=pack.entity_fields[name],
options=pool_options(pack, name),
slot=LONE_ENTITY_SLOT,
)
@@ -3348,7 +3616,7 @@ def build_field_definitions(pack: GenrePack, slots: int) -> "OrderedDict[str, Fi
for slot in range(1, slots + 1):
# Slot 1 carries the whole morphology so the core node is never a stub;
# supporting slots stay brief until a Scene Entity is wired into them.
names = tuple(pack.entity_fields) if slot == 1 else brief
names = widget_fields(pack) if slot == 1 else brief
for name in names:
# Every slot's kind defaults to "Random". An untouched node is still
# one entity, because ``entity_count`` defaults to 1 and slots past
@@ -3401,14 +3669,15 @@ def build_field_definitions(pack: GenrePack, slots: int) -> "OrderedDict[str, Fi
endpoints=(first, second),
)
context_spec = pack.scene_fields.get(CONTEXT_FIELD)
if context_spec is not None:
definitions[CONTEXT_FIELD] = _definition(
key=CONTEXT_FIELD,
path=CONTEXT_FIELD,
base=CONTEXT_FIELD,
spec=context_spec,
options=pool_options(pack, CONTEXT_FIELD),
# The context, then every later scene global, appended after the relations
# so a saved workflow's widget positions never move.
for name in scene_globals(pack):
definitions[name] = _definition(
key=name,
path=name,
base=name,
spec=pack.scene_fields[name],
options=pool_options(pack, name),
)
return definitions
@@ -3441,6 +3710,19 @@ def build_resolution_definitions(
"""
definitions = build_field_definitions(pack, slots)
if slots == ENTITY_NODE_SLOTS:
# A hidden field has no widget on this node either, and is keyed bare
# like the rest so the engine's keyer finds it.
for name, spec in pack.entity_fields.items():
if name not in definitions:
definitions[name] = _definition(
key=name,
path=slot_path(LONE_ENTITY_SLOT, name),
base=name,
spec=spec,
options=pool_options(pack, name),
slot=LONE_ENTITY_SLOT,
default=RANDOM,
)
return definitions
for slot in range(1, slots + 1):
for name, spec in pack.entity_fields.items():
+1022 -153
View File
File diff suppressed because it is too large Load Diff
+1788 -143
View File
File diff suppressed because it is too large Load Diff
+221
View File
@@ -2836,3 +2836,224 @@ the report's failure pattern is a subject that sits in frame doing nothing.
pins each card. A "says clock" row in `tests/test_concern_regressions.py`
locks each construct subkind in turn; a planted "clockwork brass hound" proved
it fails.
## Round XXX: variety (0.8.0)
The maintainer's report: output read like a premade scene picked from a list.
Orcs, mechs and elementals always looked alike, acts and settings repeated,
and the subject always stood centred and faced the viewer. Every earlier round
had only removed values, and nothing measured look variety per type. Four
causes: look pools were shallow and a subkind pool hid its kind pool; acts were
drawn from shared cores weighted like a type's own acts; a place had no state;
and nothing placed the subject, while face fields were spoken in most fantasy
and horror prompts.
### Mechanisms
- **Variant, a hidden draw** (`VARIANT_FIELD`, `FieldSpec.widget="hidden"`). It
has no widget, is written to `prompt_json` and is spoken as a head modifier.
**A variant is a mask, not a scope.** The values it owns are authored into the
type's own pool literals and marked in `GenrePack.value_variants`;
`variant_mask` in `data/genre.py` keeps only the drawn variant's values, or
only neutral values when none is drawn. "Neutral" is judged against the
variants this subject is offered. If the bans empty the masked pool, the draw
falls back to the unmasked pool. A locked owned value forces its variant.
`variant` is a control field, so a re-drawn variant re-scopes its looks. An
archetype that offers variants gets one more detail slot; every other
archetype omits the field.
- **Owned acts outweigh shared ones.** `own_values` names the values held by 3
types or fewer, or by one group only. `_derive_weights` leaves owned acts at
full weight and multiplies a shared act by `reach ** -specificity_exponent`
(0.5 in every pack). An exponent of 1.0 was tried and rejected: one bard act
took 63% of the bard's draws.
- **Scene globals.** `scene_globals(pack)` covers every scene field that is not
a core field, in declaration order (context, staging, aspect). It replaces
context's six hard-wired paths.
- **Placement** (`staging`) is a lead move: "At the far end of the hall, a
...". **Placement is relative to the place, never the camera:** how far off
the subject is and what it stands beside, never the frame, an angle or "the
viewer". Pose and heading stay the act's job.
- **Place state** (`aspect`) is an environment move: "set in a village green,
under a fresh fall of snow". It covers weather, season and what has
happened to the place, never the time of day or the light. Values need,
never grant.
- Both are widgets after Context, so the JS order still equals the schema.
- **Foreground framings.** "In the foreground is {a_context}." is eligible only
when its `Sentence.traits` are a subset of the drawn context's traits. Only
human-scale context values carry `near-prop`. The framings sit at the end of
`context_sentences`, so saved indices keep their meaning.
### Floors (`check_variety_floors`, check 35)
Each fails by name: FORMFLOOR (4 forms per bodied type), VARIANTFLOOR (3
variants where an archetype speaks them), ACTSPEC (6 owned acts per group or
ungrouped type), CONTEXTFLOOR (4 contexts per place), STAGEFLOOR (4 placements),
ASPECTFLOOR (6 outdoor, 4 interior), VIEWER (no act says "the viewer") and
FRAMING (no framing gated on a trait no context carries). The sweep rates come
from `scripts/reach_audit.py --variety`.
### Measured
Default node, slot 1. Main is v0.7.0. The branch was measured at 4000 scenes on
two seeds, wired and unwired.
| Measure | main | branch: sci-fi / fantasy / horror |
| --- | --- | --- |
| context absent | 50% / 55% / 62% | 26-28% / 21-22% / 21-22% |
| own-act share | about 17% | 44% / 40-41% / 49% |
| (variant, form) silhouettes per type, median | not measured (types with 2 forms or fewer: 45 / 114 / 54) | 14 / 11-12 / 15-16 |
| top first verb | not measured | 2.6-2.9% / 2.5-2.7% / 3.4-3.9% |
The types under 8 silhouettes are the worlds and phenomena that omit the
variant (black hole, rogue planet, star, energy beings and drifters). No type's
most common act exceeds 35% of its draws.
### Render test
A seeded batch, 12 scenes per pack (4 of them through Stylebook), was rendered
through the Krea2 graph. Prompts came from the branch engine as plain text,
because the live ComfyUI still ran 0.7.0. Placement, Place state and the
foreground framings all drew as written. Two shared pools reached the wrong
place: "half-hidden in the long grass" in snowbound pine woods, and
"half-flooded" in an attic. The room pools in horror and fantasy now say "with
rainwater pooled across the floor", and the wilds placement says "beside a
fallen trunk". A regression row for each is in
`tests/test_concern_regressions.py`; both were proved to fail on the old data.
The maintainer's review of the same batch found eight more. Each fix covers the
whole class, not only the drawn value, and has a regression row proved to fail
on the old data:
| Rendered | Cause | Fix |
| --- | --- | --- |
| A merfolk held a spear and a second weapon | "brandishing a weapon high" names a weapon apart from the one carried | Every generic weapon act is possessive: "their weapon", "its massive weapon" |
| A resting revenant's axe floated beside it | A dormant act with a held weapon | `dormant-act` conflicts with `held-weapon` (fantasy, horror) |
| A standing doll sat with a knife in its lap | The form names a posture the act contradicts | `POSTURE_VERBS` in `data/genre.py`; a posture form gives way to an act naming another |
| Netting on a revenant's back | "net-tangled rags" | "kelp-wound rags" |
| A campfire inside a church | "fire-gutted", "fire-blackened stone" render as live fire | No horror look says "fire-": soot-blackened, heat-scarred, gutted |
| Cloth on a highway fence | "hung with torn plastic sheeting" | "topped with coiled razor wire" |
| A giant tube out of a wreck | "trailing a torn length of ducting" | "venting a thin spray of frozen coolant" |
| A wreck drawn as a sailing ship; drones as one walker | "bow section", "snapped spar", "by salvage drones" | Wreck looks say girder and forward hull; "the cutting beams of small drones" |
Two more were the model or a Stylebook style (a wire sculpture style drew wire
and cable) and were left alone.
A second batch, two subtypes of every kind in each pack, found eight more:
| Rendered | Cause | Fix |
| --- | --- | --- |
| A faun drawn as a goat | "lowering its head" for a subject the prose calls "they" | Every act speaks its subject's pronoun; `PronounTests` sweeps all three packs |
| Coins among spiders | "coin-sized spiders" | "little spiders" |
| A hall clock in a supermarket | Furnishings needed only a room | A grandfather clock and a family picture need `domestic` |
| A bone revenant with a third arm | Horror's undead weapons were not `carried-weapon`, so clawing acts kept them | Tagged; clawing, dragging and prying acts are `both-hands-act` (fantasy too) |
| A skeleton eating raw meat | Feeding acts had no flesh need | Tagged `flesh-intact` |
| A scythe on a chariot | "scythe-wheeled frame" | "frame with bladed wheel hubs" |
| A green flame on a chain | A bare "spectral flame" emitter | "spectral flame burning in its chest" |
| A flyer pushing a dumpster | "sweeping a sampling scoop" | "skimming through an ash plume to take samples" |
A sky galleon drawn on the forest floor was the model: its act says it glides
over the treetops.
### Lessons
- Judge `tests/validate_data.py` by its exit code. Its last line is horror's
OK and hides a sci-fi failure above it.
- A wreck act must also be listed in sci-fi's `DORMANT_ACTS`.
- Needs are all-of. A sky-weather Place state needs `air` as well as its own
needs.
- A shared Place state or Placement pool must fit every storey and season of
every place that draws it. If it doesn't, key the value to the place.
- New looks count toward the motif ceilings. CI caught the sci-fi "ring" motif
at 23% (ceiling 15%), from "ring-shaped drone body", a "ringed" variant and a
quarantine state "ringed by" beacons. They now say "hoop-framed", "segment-banded"
and "cordoned off". Run every `ci.yml` step locally, including
`sample_distribution.py`, before pushing.
- A word that names a thing renders the thing. "Fire-gutted" draws a fire,
"net-tangled" draws a net, "spar" and "bow" draw a sailing ship, and "a
weapon" next to a carried spear draws two weapons. Say the damage or the
owner, not the object.
## Round XXXI: the audits take `--pack`
`coherence_audit.py` and `coherence_sweep.py` measured sci-fi only. The audit
reads pack declarations throughout, so `--pack` was enough there. The sweep's
classes are sci-fi word lists and kind names, so under `--pack fantasy|horror`
it runs two other sets: the pack's own classes from `tests/test_<pack>_pack.py`
(ceiling 0) and `shape_classes`, the sweep classes that read only a pack's
bands, affordances and traits. `concern_audit.py` stays sci-fi only: it
replays frozen flags from reported sci-fi batches, and the other packs have
none to replay.
The test files sweep 400 to 500 seeds. At 3000 to 4000 seeds the same classes
found what those runs never drew:
| Found | Cause | Fix |
| --- | --- | --- |
| A dormant revenant on the seabed with no act (`no-situation`, `dead-but-live`, 0.2%) | Undead dormant acts needed air (dust) or a wall | Two seabed dormant acts, shared with the artifacts |
| An abandoned airship, sky galleon or skiff with no act in the sky, a courtyard or a quay | Its dormant acts needed `ground` | A dead ship in the sky drifts if intact and falls if wrecked; the wreck act needs `floor` |
| "with its gasbag torn" on a sky galleon and a cloud skiff | The act was in the shared flying-ship pool | "lying wrecked in a tangle of torn rigging" |
| A huge golem in the blacksmith's forge (`huge-indoors`) | A later literal key `"blacksmith's forge": ("hot-place",)` replaced its `interior-place` | Both traits on the one key |
| Merfolk "raising an arm against a gust of grit" on the seabed (`weather-in-wrong-medium`) | The act needed nothing | It needs `air` |
The maintainer also reported a spear drawn leaving a sea serpent's mouth for
"snapping at a hurled spear". An object thrown by someone off-frame now says
its direction, and `TRAP_PHRASES` rejects the undirected form ("hurled",
"thrown", "flung", "raised" or "levelled" before a spear, dagger, torch and
the like). Renamed values, which a saved workflow that locked them will report
as "value not in list":
| Pack | Old | New |
| --- | --- | --- |
| fantasy | snapping at a hurled spear | snapping at a spear hurled straight at it |
| fantasy | snatching a thrown dagger from the air | snatching a dagger thrown at them out of the air |
| fantasy | lying wrecked across the ground with its gasbag torn | lying wrecked in a tangle of torn rigging |
| horror | lurching away from a raised torch | lurching away from a torch thrust toward them |
The shape ceilings are what 3000 seeds measured on both paths after the fixes;
`PACK_CEILINGS` in the script says what each remaining hit looked like. Each
fix has a regression row in `tests/test_concern_regressions.py`, and every row
failed on the old data first. CI now runs the fantasy and horror sweeps on both
paths (about 10 to 25 seconds each locally).
### A drawn field gives way to a lock
When a rule forbade a locked value, `_apply_constraints` kept the lock, warned,
and changed nothing else. An airship locked "wrecked" in the sea of clouds
kept its drawn intact gasbag, which forbids a wreck act, so it had no act in
150 of 150 seeds. `_redraw_triggers` now re-draws each unlocked field whose
value fired the rule, away from every value that fires it, and warns only when
no such field can move. A trigger with nothing else to draw keeps its value,
so a lock never empties another field. The torn-gasbag form also gained the
`falls` stance, and "plunging out of the sky trailing torn rigging" requires
it, as sci-fi's falling wrecks do; without that the torn form could not be in
the sky at all and there was nothing to re-draw to.
Measured against the previous engine on 400 seeds per pack: 0 of 1200 scenes
without locks changed. Of 1200 scenes with two or three fields locked from an
earlier draw, 66 changed, all of them scenes that had a conflict warning
before. Scenes with any conflict warning went from 78 to 16, and none failed
to settle.
## 0.8.2: the input cache is ComfyUI's
Both node classes used to return `NaN` from `fingerprint_inputs`, citing
ComfyUI #11905 (a randomised seed served a cached result). That could never
produce a new scene: a changed seed is a changed input and already misses the
cache, and an unchanged one re-runs to the same text, because a scene is a pure
function of its inputs (the same seed hashed identically under three
`PYTHONHASHSEED` values). What the `NaN` did do is enter the cache signature of
every node downstream. On a live ComfyUI, Scene Weaver at a fixed seed into
Concatenate Text into Preview as Text cached nothing on an identical second
queue; the same two nodes without Scene Weaver upstream were both cached. In a
real graph that re-ran the encoder and the sampler on every queue. The override
is gone and `tests/test_registration.py` pins its absence.
The same release clears the sci-fi `ring` motif, which sat at 15.90% over
1000 seeds (ceiling 15%) on 0.8.1: CI sampled 500 seeds, where it passed, while
`AGENTS.md` lists the 1000-seed run. Three values used the word for decoration
rather than for a ring subject and are reworded in place, so every other scene
is byte-identical: "spine-ringed shell" is "spine-fringed shell",
"concentric-ring rosettes" is "concentric-banded rosettes", and "coiling itself
into a defensive ring" is "looping itself into a defensive circle". The motif
measures 14.70%. CI now samples 1000 seeds per pack, as `AGENTS.md` does. A
workflow that locked one of the three old values reports "value not in list".
+47
View File
@@ -0,0 +1,47 @@
# Registry release checks
## After publishing
- Check the publish workflow, then inspect the exact published version in
`https://api.comfy.org/nodes/comfyui-sceneweaver/versions?include_status_reason=true`.
A green workflow alone does not prove Manager can offer the release.
- Confirm the version is Active. Pending is not a completed review;
`NodeVersionStatusFlagged` needs investigation. Inspect `status_reason`
rather than inferring a cause from the status alone.
- For a repeated finding, compare its file, issue type, and matched code with
previously cleared releases. When authorized, request maintainer review,
updating the existing review request when appropriate.
- Verify Manager offers the expected Registry version. A nightly Git install
uses commit-based update checks instead of a numbered Registry installation.
## Known scanner false positive
The October 22, 2026 investigation found SceneWeaver 0.8.1 flagged on
`link.origin.connect(link.originSlot, fresh, slot)` in `js/sceneweaver.js`.
This restores LiteGraph graph links during node recreation; it does not open
a network connection.
The finding was identical to one cleared on 0.8.0, whose public reason recorded
`policy-v0.6: reviewed-safe`. Do not rename legitimate APIs, remove features,
or disable scanning merely to silence this signature. Fix actual unsafe
behavior if found; otherwise seek review. Previous clearance does not
guarantee the next release avoids a flag.
Review request: https://github.com/Comfy-Org/registry-backend/issues/296
## Manager metadata is a separate path
Manager's stars and Last Update come from its GitHub statistics database, not
the Registry publish timestamp. The scanner discovers repositories through
`custom-node-list.json`; catalog-backed Registry rows retain the GitHub
reference used to look up those statistics.
Catalog registration: https://github.com/Comfy-Org/ComfyUI-Manager/pull/3403
The investigation also found Registry-only rows missing the UI's
`update-state` field. An existing fix addresses that general defect:
https://github.com/Comfy-Org/ComfyUI-Manager/pull/3261
Check those upstream records for current outcomes. Catalog merge and database
refresh do not clear Registry security flags, and missing metadata alone does
not prove a release or Git update failed.
+9 -3
View File
@@ -58,9 +58,13 @@ import re
from typing import Iterable, Mapping
try:
from ..data.genre import KIND_FIELD, POOL_DEFAULT_KEY, Archetype, GenrePack, HeadPhrase
from ..data.genre import (
KIND_FIELD, POOL_DEFAULT_KEY, VARIANT_FIELD, Archetype, GenrePack, HeadPhrase,
)
except ImportError: # pragma: no cover -- standalone/test context
from data.genre import KIND_FIELD, POOL_DEFAULT_KEY, Archetype, GenrePack, HeadPhrase
from data.genre import (
KIND_FIELD, POOL_DEFAULT_KEY, VARIANT_FIELD, Archetype, GenrePack, HeadPhrase,
)
__all__ = [
"ALLOWANCE_BY_COUNT",
@@ -293,7 +297,9 @@ def apply_budget(
# the total clause count where it was.
head = _head_phrase_for(pack, result.get(KIND_FIELD), archetype)
modifiers = set(head.modifiers) if head is not None else set()
exempted = modifiers - set(omits)
# The variant is the one modifier the authored caps never counted: a design
# word added on top, so it does not cost a clause.
exempted = modifiers - set(omits) - {VARIANT_FIELD}
# An archetype's cap is a floor on the caller's allowance, applied after the
# orphan pass and before the early exit so that ``budget=None`` still means
+45 -9
View File
@@ -37,6 +37,8 @@ try:
CONTEXT_FIELD,
ENVIRONMENT_FIELD,
GRAMMAR_SLOTS,
MOVE_ENVIRONMENT,
MOVE_LEAD,
POOL_DEFAULT_KEY,
RELATION_FIELD,
RELATION_POSITION_FIELD,
@@ -56,6 +58,8 @@ except ImportError: # pragma: no cover -- standalone/test context
CONTEXT_FIELD,
ENVIRONMENT_FIELD,
GRAMMAR_SLOTS,
MOVE_ENVIRONMENT,
MOVE_LEAD,
POOL_DEFAULT_KEY,
RELATION_FIELD,
RELATION_POSITION_FIELD,
@@ -522,14 +526,35 @@ def _entity_parts(
SKYBORNE_LEAD = "High in the sky above, "
def _staged(entity: ResolvedEntity, host: GenrePack, environment: "str | None",
def _scene_moves(scene: ResolvedScene, pack: GenrePack, move: str) -> "list[str]":
"""The spoken scene globals that take ``move``, in declaration order."""
return [
spoken_value(pack, name, value)
for name, value in scene.scene_values.items()
if value and pack.prose.scene_field_moves.get(name) == move
]
def _staged(entity: ResolvedEntity, host: GenrePack, scene: ResolvedScene,
sentences: "list[str]") -> "list[str]":
"""Lead a skyborne guest's first sentence with where it hangs."""
"""Lead the first sentence with where the subject is.
A skyborne guest leads with where it hangs. The hero (slot 1) otherwise
leads with its placement in the place -- "At the far end of the hall, a
banshee is ..." -- which says where it stands in the world, never where it
sits in the picture.
"""
if not sentences:
return sentences
guest = guest_pack(host, {"genre": entity.genre})
if not sentences or guest is None or not skyborne(guest, host, entity.fields, environment):
if guest is not None and skyborne(guest, host, entity.fields, scene.environment):
lead = SKYBORNE_LEAD
elif entity.index == 1 and (leads := _scene_moves(scene, host, MOVE_LEAD)):
lead = leads[0][:1].upper() + leads[0][1:] + ", "
else:
return sentences
first = sentences[0]
return [SKYBORNE_LEAD + first[:1].lower() + first[1:], *sentences[1:]]
return [lead + first[:1].lower() + first[1:], *sentences[1:]]
def _render_entity_sentences(entity: ResolvedEntity, pack: GenrePack) -> "list[str]":
@@ -585,7 +610,9 @@ def _sentence(text: str) -> str:
return _tidy(body if body.endswith(".") else f"{body}.")
def _environment_sentence(pack: GenrePack, environment: str) -> str:
def _environment_sentence(
pack: GenrePack, environment: str, states: "list[str] | tuple[str, ...]" = ()
) -> str:
"""The setting sentence, staged with the first affordance suffix that applies.
A text-to-image model grounds anything it is not told floats: a station in a
@@ -594,6 +621,11 @@ def _environment_sentence(pack: GenrePack, environment: str) -> str:
"""
template = pack.prose.environment_sentence or _template(pack, ENVIRONMENT_FIELD)
text = _format(template, spoken_value(pack, ENVIRONMENT_FIELD, environment))
# The place's state -- weather, season, what has happened to it -- is part
# of the place, so it is said with it: "set in a village green, under a
# fresh fall of snow".
for state in states:
text += f", {state}"
afforded = affordances_of(pack, environment)
for affordance, suffix in pack.prose.environment_staging:
if affordance in afforded:
@@ -720,14 +752,16 @@ def compose_scene(
sentences: list[str] = []
for entity in scene.entities:
sentences.extend(_staged(
entity, pack, scene.environment, _render_entity_sentences(entity, pack)
entity, pack, scene, _render_entity_sentences(entity, pack)
))
context = _context_sentence(scene, pack)
if context:
sentences.append(context)
if scene.environment:
sentences.insert(0, _environment_sentence(pack, scene.environment))
sentences.insert(0, _environment_sentence(
pack, scene.environment, _scene_moves(scene, pack, MOVE_ENVIRONMENT)
))
elif pack.prose.scene_frame and sentences:
# No environment to carry the genre, so it is stated on its own. A
# prompt that never names its genre gets drawn as whatever its nouns
@@ -766,11 +800,13 @@ def render_prose(scene: ResolvedScene, pack: GenrePack) -> str:
for section in pack.prose.scene_order:
if section == ENVIRONMENT_FIELD:
if scene.environment:
sections.append(_environment_sentence(pack, scene.environment))
sections.append(_environment_sentence(
pack, scene.environment, _scene_moves(scene, pack, MOVE_ENVIRONMENT)
))
elif section == _ENTITIES_SECTION:
for entity in scene.entities:
sections.extend(_staged(
entity, pack, scene.environment, _render_entity_sentences(entity, pack)
entity, pack, scene, _render_entity_sentences(entity, pack)
))
context = _context_sentence(scene, pack)
if context:
+4
View File
@@ -101,11 +101,15 @@ class ResolvedScene:
#: is what keeps a constraint's ``reason`` string (the pack's one deliberate
#: exemption from never-negate) out of the prompt.
meta: Mapping[str, Any] = field(default_factory=dict)
#: Every other scene-wide value -- placement, place state -- keyed by field.
#: Spoken where ``ProseSpec.scene_field_moves`` says; ``None`` emits nothing.
scene_values: Mapping[str, "str | None"] = field(default_factory=dict)
def __post_init__(self) -> None:
object.__setattr__(self, "entities", tuple(self.entities))
object.__setattr__(self, "relations", tuple(self.relations))
object.__setattr__(self, "meta", MappingProxyType(dict(self.meta)))
object.__setattr__(self, "scene_values", MappingProxyType(dict(self.scene_values)))
def entity(self, index: int) -> ResolvedEntity | None:
"""The entity in slot ``index``, or ``None`` if the slot is empty."""
+214 -28
View File
@@ -77,6 +77,8 @@ try:
SET_ALL_OPTIONS,
SITUATION_FIELD,
STANCE_FIELD,
VARIANT_FIELD,
MOVE_LEAD,
Archetype,
FieldDef,
GenrePack,
@@ -104,6 +106,8 @@ try:
resolved_needs,
type_feasible,
type_field,
scene_globals,
variant_mask,
)
except ImportError: # pragma: no cover -- standalone/test context
from data.genre import (
@@ -125,6 +129,8 @@ except ImportError: # pragma: no cover -- standalone/test context
SET_ALL_OPTIONS,
SITUATION_FIELD,
STANCE_FIELD,
VARIANT_FIELD,
MOVE_LEAD,
Archetype,
FieldDef,
GenrePack,
@@ -152,6 +158,8 @@ except ImportError: # pragma: no cover -- standalone/test context
resolved_needs,
type_feasible,
type_field,
scene_globals,
variant_mask,
)
from .budget import allowance_for, apply_budget
@@ -337,6 +345,9 @@ def _draw(
]
if not pool:
return None
# After the bans, so a mask that would leave nothing falls back to what the
# rules allow rather than to a value they forbid.
pool = variant_mask(pack, definition.base, pool, scope)
weights = pack.weights_for(definition.base)
# ``omission_weight`` lets a head-phrase modifier -- a word spoken on every
# entity -- say nothing at all, because a describing word on every entity is
@@ -421,10 +432,15 @@ def _resolve_entity_fields(
widget = _widget_value(definition, widgets)
banned = (
_control_values_ruled_out_by_locks(pack, name, definitions, widgets, keyer)
if name in controls
if name in controls and name != VARIANT_FIELD
else frozenset()
)
scope = {**scene_scope, **values}
if name == VARIANT_FIELD:
banned = _variants_ruled_out_by_locks(pack, definitions, widgets, keyer, scope)
if banned:
# A locked look its variant owns: the variant must be drawn.
definition = dataclasses.replace(definition, omission_weight=0.0)
values[name] = _resolve_one(
rng, pack, definition, widget, scope, scene_filter, locked_paths, banned
)
@@ -505,8 +521,57 @@ def _visible_fields(
def _control_fields(pack: GenrePack) -> "frozenset[str]":
"""Every entity control field -- a field that appears in some field's scope."""
return frozenset(control for spec in pack.entity_fields.values() for control in spec.scope)
"""Every entity control field -- a field that appears in some field's scope.
The variant counts too: it keys no pool, but a re-drawn variant leaves the
looks it owned standing, so they must be re-drawn with it.
"""
controls = {control for spec in pack.entity_fields.values() for control in spec.scope}
if pack.value_variants:
controls.add(VARIANT_FIELD)
return frozenset(controls)
def _draw_scope(pack: GenrePack, name: str) -> "tuple[str, ...]":
"""The controls a field's draw reads: its scope, plus the variant that masks it."""
spec = pack.entity_fields.get(name) or pack.scene_fields.get(name)
scope = tuple(spec.scope) if spec is not None else ()
if name in pack.value_variants:
variant_spec = pack.entity_fields[VARIANT_FIELD]
scope += (VARIANT_FIELD, *variant_spec.scope)
return scope
def _variants_ruled_out_by_locks(
pack: GenrePack,
definitions: Mapping[str, FieldDef],
widgets: Mapping[str, Any],
keyer: "Callable[[str], str]",
scope: "Mapping[str, str | None]",
) -> "frozenset[str]":
"""Variants that cannot be drawn because a look one of them owns is locked.
Lock "war-painted hide" and the entity has to be the war-band that owns it,
or the mask would hand every other look to a design line that never wears
it. Only narrows, like ``_control_values_ruled_out_by_locks``: a lock no
offered variant owns, and contradictory locks, ban nothing.
"""
offered = set(pool_for(pack, VARIANT_FIELD, scope))
allowed: "set[str] | None" = None
for name, owners in pack.value_variants.items():
definition = definitions.get(keyer(name))
if definition is None:
continue
value = _widget_value(definition, widgets)
if not _is_locked(value):
continue
holders = set(owners.get(value, ())) & offered
if not holders:
continue
allowed = holders if allowed is None else (allowed & holders)
if not allowed:
return frozenset()
return frozenset(offered - allowed)
def _control_values_ruled_out_by_locks(
@@ -667,6 +732,33 @@ def _locked_widget(
return value if _is_locked(value) else None
def _environments_ruled_out_by_scene_locks(
pack: GenrePack, definitions: Mapping[str, FieldDef], widgets: Mapping[str, Any]
) -> "frozenset[str]":
"""Places a locked scene global cannot be true of.
Read from the pools and needs alone: a place holds a locked value when its
scoped pool offers it and it affords everything the value needs.
"""
legal = pool_options(pack, ENVIRONMENT_FIELD)
allowed = set(legal)
for name in scene_globals(pack):
definition = definitions.get(name)
if definition is None:
continue
value = _widget_value(definition, widgets)
if not _is_locked(value):
continue
holders = {
environment for environment in allowed
if value in pool_for(pack, name, {ENVIRONMENT_FIELD: environment})
and resolved_needs(pack, name, value) <= affordances_of(pack, environment)
}
if holders:
allowed = holders
return frozenset(set(legal) - allowed)
def _environments_ruled_out_by_state(
pack: GenrePack, state: Mapping[str, "str | None"], slots: int
) -> "frozenset[str]":
@@ -1070,7 +1162,7 @@ def _rescope_slot(
scene_filter: str,
slot: int,
changed: "frozenset[str] | set[str]",
revive: "set[str] | frozenset[str]" = frozenset(),
revive: "set[str]",
) -> None:
"""Re-draw the fields a changed control scopes, in declaration order.
@@ -1086,15 +1178,19 @@ def _rescope_slot(
A field that is ``None`` is also left alone, because a field with an empty
pool is legitimately silent -- except for a path in ``revive``, which a rule
nulled and which the new control value may make drawable again.
nulled and which the new control value may make drawable again. A revived
path is removed from ``revive`` in place, which is why it is a required,
mutable set: a frozenset default raised on the first re-draw.
"""
changed = set(changed)
controls = _control_fields(pack)
for name, spec in pack.entity_fields.items():
if name in changed or not (set(spec.scope) & changed):
for name in pack.entity_fields:
if name in changed or not (set(_draw_scope(pack, name)) & changed):
continue
path = slot_path(slot, name)
if path in locked_paths or (state.get(path) is None and path not in revive):
if path in locked_paths or (
state.get(path) is None and path not in revive and name != VARIANT_FIELD
):
continue
definition = address_of.get(path)
if definition is None:
@@ -1114,7 +1210,7 @@ def _rescope_slot(
definition is not None
and situation_path not in locked_paths
and (state.get(situation_path) is not None or situation_path in revive)
and set(pack.scene_fields[SITUATION_FIELD].scope) & changed
and set(_draw_scope(pack, SITUATION_FIELD)) & changed
):
state[situation_path] = _draw(
rng, pack, definition, _scope_for(pack, state, situation_path), scene_filter
@@ -1180,6 +1276,65 @@ def _required_targets(
return required
def _redraw_triggers(
rng: random.Random,
pack: GenrePack,
state: dict[str, str | None],
address_of: Mapping[str, FieldDef],
locked_paths: "set[str]",
scene_filter: str,
slots: int,
target: str,
banned: "Mapping[str, set[str]]",
sticky_bans: "Mapping[str, frozenset[str]]",
nulled: "set[str]",
) -> bool:
"""Re-draw each unlocked field whose value makes a rule forbid locked ``target``.
The trigger is drawn away from every value that fires the rule. A trigger
with nothing else to draw keeps its value, so a lock never empties another
field; the caller then reports the conflict. True when anything moved.
"""
current = state.get(target)
moved = False
for rule, trigger, bound_target, triggers in _bound_rules(pack, slots):
if bound_target != target or trigger in locked_paths:
continue
if state.get(trigger) not in triggers:
continue
if rule.type == RULE_EXCLUDE:
if current not in rule.excludes_values:
continue
elif current in (set(rule.requires_values) if rule.requires_values else {rule.requires_value}):
continue
definition = address_of.get(trigger)
if definition is None:
continue
forbidden = set(triggers) | banned.get(trigger, set())
is_control = definition.base in _control_fields(pack) and definition.slot is not None
if is_control:
forbidden |= _control_values_ruled_out_by_state(
pack, definition.base, state, locked_paths, definition.slot
)
sticky = set(sticky_bans.get(trigger, ()))
if trigger == ENVIRONMENT_FIELD:
sticky |= _environments_ruled_out_by_state(pack, state, slots)
scope = _scope_for(pack, state, trigger)
replacement = _draw(rng, pack, definition, scope, scene_filter, forbidden | sticky)
if replacement is None and sticky:
replacement = _draw(rng, pack, definition, scope, scene_filter, forbidden)
if replacement is None:
continue
state[trigger] = replacement
moved = True
if is_control:
_rescope_slot(
rng, pack, state, address_of, locked_paths,
scene_filter, definition.slot, {definition.base}, nulled,
)
return moved
def _apply_constraints(
rng: random.Random,
pack: GenrePack,
@@ -1236,8 +1391,18 @@ def _apply_constraints(
elif current not in forbidden:
continue
if target in locked_paths:
# The user named this value. It wins, and the rule's reason
# is reported -- to _meta.warnings, never to prompt_text.
# The user named this value, so it wins. The unlocked field
# whose value fired the rule is re-drawn instead: a ship
# locked "wrecked" in the sky gets a torn gasbag, not an
# intact one that leaves no act it may do.
if _redraw_triggers(
rng, pack, state, address_of, locked_paths, scene_filter,
slots, target, banned, sticky_bans, nulled,
):
changed = True
continue
# Nothing else could move. The rule's reason is reported --
# to _meta.warnings, never to prompt_text.
for reason in reasons.get(target, ()):
message = f"{target}: kept the locked value {current!r} ({reason})"
if message not in warnings:
@@ -1518,11 +1683,11 @@ def _scope_for(
entity, dot, name = address.partition(".")
if not dot:
name, entity = address, ""
spec = pack.entity_fields.get(name) or pack.scene_fields.get(name)
if spec is None or not spec.scope:
controls = _draw_scope(pack, name)
if not controls:
return {}
scope: dict[str, str | None] = {}
for control in spec.scope:
for control in controls:
if control in pack.scene_fields or not entity:
scope[control] = state.get(control)
else:
@@ -1556,14 +1721,14 @@ def generate_scene(
``wired_entities`` maps a 1-based slot to a ``SCENE_ENTITY`` payload.
``entity_count`` is how many slots the scene occupies, and it is the
**authority** on that: slots past it are left out even if their kind widget
holds a value, and slots within it are filled even if their kind widget
still says "None". Anything else makes the control a lie -- a user who sets
it to 3 and gets one entity because two hidden widgets defaulted to "None"
has been told something untrue by the node face. A wired slot is occupied
whatever the count says, because connecting a node is the more explicit
statement; the count is raised to match and reported in ``_meta``.
``entity_count`` is how many slots the scene occupies: slots past it are
emptied, and a slot within it is whatever its own kind widget says -- the
kind widgets default to "Random", so the count is what the user gets, and a
slot deliberately set to "None" stays empty. Two things outrank the count,
as ``_occupied_slots`` records: a wired slot, because connecting a node is
the more explicit statement, and a slot whose kind widget holds a literal,
because naming a subject is a lock. Either raises the count, and the widened
count is what the budget divides the scene's detail between.
It defaults to ``DEFAULT_ENTITY_COUNT`` rather than to ``None`` so that a
bare call behaves like a freshly-dropped node: one subject. Pass ``None``
@@ -1647,15 +1812,22 @@ def generate_scene(
subject_bans = _environments_ruled_out_by_fixed_subjects(
pack, definitions, widgets, promoted,
)
# A locked placement or place state narrows the place the same way: snow
# on the ground is not a promise a sealed vault can keep.
scene_lock_bans = _environments_ruled_out_by_scene_locks(pack, definitions, widgets)
if scene_lock_bans and len(subject_bans | scene_lock_bans) < len(
pool_options(pack, ENVIRONMENT_FIELD)
):
subject_bans = subject_bans | scene_lock_bans
state[ENVIRONMENT_FIELD] = _resolve_one(
rng, pack, environment_def, environment_widget, {}, scene_filter, locked_paths,
banned=subject_bans,
)
scene_scope: dict[str, str | None] = {ENVIRONMENT_FIELD: state[ENVIRONMENT_FIELD]}
context_def = definitions.get(CONTEXT_FIELD)
if context_def is not None:
state[CONTEXT_FIELD] = _resolve_one(
rng, pack, context_def, _widget_value(context_def, widgets),
for name in scene_globals(pack):
definition = definitions[name]
state[name] = _resolve_one(
rng, pack, definition, _widget_value(definition, widgets),
{ENVIRONMENT_FIELD: state[ENVIRONMENT_FIELD]}, scene_filter, locked_paths,
)
@@ -1884,10 +2056,15 @@ def generate_scene(
# pack's own list and the document still round-trips.
context_patterns = pack.prose.context_sentences
here = affordances_of(pack, state.get(ENVIRONMENT_FIELD) or "")
# A foreground framing also needs a context that can sit near: "In the
# foreground is a ringed moon" puts the sky in front of the subject.
context_traits = pack.value_traits.get(CONTEXT_FIELD, {}).get(
state.get(CONTEXT_FIELD) or "", frozenset()
)
eligible = [
index
for index, pattern in enumerate(context_patterns)
if pattern.needs <= here
if pattern.needs <= here and pattern.traits <= context_traits
]
context_index = (
rng.choice(eligible) if eligible and state.get(CONTEXT_FIELD) else None
@@ -1913,6 +2090,14 @@ def generate_scene(
entities=tuple(entities),
relations=tuple(relations),
meta=meta,
# A placement places the hero; with slot 1 empty it places nothing.
scene_values={
name: state.get(name)
if 1 in occupied or pack.prose.scene_field_moves.get(name) != MOVE_LEAD
else None
for name in scene_globals(pack)
if name != CONTEXT_FIELD
},
)
return render_prose(scene, pack), _to_json(pack, scene)
@@ -1942,7 +2127,7 @@ def generate_entity(
widgets = dict(widgets or {})
warnings: list[str] = []
definitions = build_field_definitions(pack, ENTITY_NODE_SLOTS)
definitions = build_resolution_definitions(pack, ENTITY_NODE_SLOTS)
address_of = {d.path: d for d in definitions.values() if not d.control}
locked_paths: set[str] = set()
@@ -2047,6 +2232,7 @@ def _to_json(pack: GenrePack, scene: ResolvedScene) -> dict[str, Any]:
return {
ENVIRONMENT_FIELD: scene.environment,
CONTEXT_FIELD: scene.context,
**{name: scene.scene_values.get(name) for name in scene_globals(pack) if name != CONTEXT_FIELD},
"entities": entities,
RELATION_FIELD + "s": [
{
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -8
View File
@@ -71,14 +71,9 @@ def build_entity_node(pack: GenrePack) -> type:
],
)
@classmethod
def fingerprint_inputs(cls, **kwargs: Any) -> float:
# Force a fresh roll on every queue. ComfyUI can serve a stale cached
# result when control_after_generate auto-advances the seed (ComfyUI
# #11905); a never-equal value makes this node's cache signature always
# differ, so it re-executes and reads the new seed. Pure cache control --
# no RNG here, so a fixed seed still reproduces exactly.
return float("nan")
# No fingerprint_inputs: the output is a pure function of the inputs, so
# ComfyUI's own input cache is correct. A NaN fingerprint (0.8.1 and
# earlier) re-ran every downstream node, sampler included, on each queue.
@classmethod
def execute(cls, **kwargs: Any) -> "io.NodeOutput":
+1 -4
View File
@@ -115,10 +115,7 @@ def build_scene_node(pack: GenrePack) -> type:
],
)
@classmethod
def fingerprint_inputs(cls, **kwargs: Any) -> float:
# See the identical note on the Scene Entity node: ComfyUI #11905.
return float("nan")
# No fingerprint_inputs; see the note on the Scene Entity node.
@classmethod
def execute(cls, **kwargs: Any) -> "io.NodeOutput":
+6 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "comfyui-sceneweaver"
version = "0.7.0"
version = "0.8.2"
description = "One click, one whole coherent scene: the place, what is standing in it, and what it is doing - written as prose a text encoder can follow, where every detail agrees with every other one. A multi-genre scene engine: sci-fi (alien creatures, spacefarers, mechs, starships, stations, wrecks, worlds) fantasy (dragons, mythic beasts, giants, goblins, centaurs, elves, undead, golems, castles, airships) and horror (ghouls, vampires, banshees, cryptids, eldritch horrors, cultists, cursed objects, haunted houses, with a gore filter that starts on No gore), each drawn across a full morphology, with entities that wire across genres. Every field independently lockable."
license = { text = "MIT" }
readme = "README.md"
@@ -24,6 +24,11 @@ Icon = "https://raw.githubusercontent.com/EnragedAntelope/comfyui-sceneweaver/ma
[tool.ruff]
line-length = 100
[tool.ruff.lint]
# The rule set CI's pinned ruff applies by default, stated so a newer local ruff
# (0.17 widened its defaults to import sorting and naming) agrees with CI.
select = ["E4", "E7", "E9", "F"]
[tool.ruff.lint.per-file-ignores]
# The test modules prepend the repo root onto sys.path so they can be run
# standalone (``python tests/...``); those imports necessarily follow the shim,
+6 -4
View File
@@ -2,6 +2,7 @@
python scripts/coherence_audit.py # 1000 seeds
python scripts/coherence_audit.py --seeds 2000
python scripts/coherence_audit.py --pack fantasy # or horror
**Why this exists.** ``tests/test_coherence.py`` sweeps and asserts invariants;
this is the maintainer's instrument that *names* a defect instead of failing a
@@ -28,7 +29,7 @@ coil of gas" came from?
* buckets of the reference corpus, and it should sit near zero for the built and
* inert archetypes. A report, not a gate.
Zero dependencies and no ComfyUI; imports ``data.scifi`` directly (never the
Zero dependencies and no ComfyUI; imports ``data.<pack>`` directly (never the
entrypoint) so ``user_options.json`` can never reach a committed number.
"""
from __future__ import annotations
@@ -43,12 +44,12 @@ if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from data.genre import KIND_FIELD, archetype_name_for, scope_keys # noqa: E402
from data.scifi import SCIFI_PACK # noqa: E402
from engine.budget import count_tokens # noqa: E402
from engine.grammar import head_noun # noqa: E402
from engine.prose import render_entity # noqa: E402
from engine.resolution import ResolvedEntity # noqa: E402
from engine.scene import generate_scene # noqa: E402
from sample_distribution import PACK_SLUGS, load_pack # noqa: E402
def _normalized_head(value: str) -> str:
@@ -138,9 +139,10 @@ def _component_clauses(pack, record) -> int:
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--seeds", type=int, default=1000, help="seeds to sweep")
parser.add_argument("--pack", choices=PACK_SLUGS, default="scifi")
args = parser.parse_args(argv)
pack = SCIFI_PACK
pack = load_pack(args.pack)
by_kind_routes: dict[str, Counter] = defaultdict(Counter)
fallthrough_subkinds: dict[str, Counter] = defaultdict(Counter)
archetype_shape: dict[str, dict[str, list[int] | int]] = defaultdict(
@@ -185,7 +187,7 @@ def main(argv: list[str] | None = None) -> int:
if _component_clauses(pack, record) >= 4:
stats["heavy"] += 1
print(f"seeds {args.seeds} -- {entities} entities")
print(f"{args.pack}: seeds {args.seeds} -- {entities} entities")
print()
print("form resolution, per kind (share through a group/raw key):")
for kind in pack.kinds:
+94 -9
View File
@@ -4,6 +4,7 @@
python scripts/coherence_sweep.py --path unwired
python scripts/coherence_sweep.py --gate # exit 1 over a ceiling
python scripts/coherence_sweep.py --examples 3 # print real prompts
python scripts/coherence_sweep.py --pack fantasy # or horror
**Why this exists, and why it is not another concern_flags file.**
@@ -31,7 +32,15 @@ ceilings in ``CEILINGS`` are what the round left them at, so a change that puts
one back up is visible. Raise a ceiling only with a measured reason written next
to it.
An instrument, not a test: ``tests/`` owns the gates. Imports ``data.scifi``
**Fantasy and horror.** The sci-fi classes below are sci-fi word lists and kind
names, so ``--pack fantasy|horror`` runs two other sets instead: the pack's own
classes from ``tests/test_<pack>_pack.py`` (gated at zero there, over a few
hundred seeds; a ceiling of 0 here, over thousands), and ``shape_classes``,
which read only the pack's own declarations (bands, affordances, traits). At
4000 seeds the first set found dead subjects with no act and a forge holding a
huge golem that the 500-seed test sweep had never drawn.
An instrument, not a test: ``tests/`` owns the gates. Imports ``data.<pack>``
directly, never the entrypoint, so ``user_options.json`` can never reach a number.
"""
from __future__ import annotations
@@ -54,6 +63,7 @@ from data.genre import ( # noqa: E402
)
from data.scifi import SCIFI_PACK as PACK # noqa: E402
from engine.scene import generate_entity, generate_scene # noqa: E402
from sample_distribution import PACK_SLUGS, load_pack # noqa: E402
def _words(*terms: str) -> "re.Pattern[str]":
@@ -299,8 +309,80 @@ def classes(text: str, document: dict) -> "list[str]":
return out
def sweep(seeds: int, path: str, examples: int):
def shape_classes(pack, text: str, document: dict) -> "list[str]":
"""The classes above that need no sci-fi word: each reads ``pack``'s own bands,
affordances and traits, over every entity."""
out: set[str] = set()
place = document.get(ENVIRONMENT_FIELD) or ""
affords = affordances_of(pack, place)
context = (document.get(CONTEXT_FIELD) or "").lower()
low = text.lower()
pristine = {v for v, t in (pack.value_traits.get("condition") or {}).items() if "pristine-state" in t}
for entity in document["entities"]:
situation = (entity.get(SITUATION_FIELD) or "").lower()
substance = " ".join((entity.get(f) or "") for f in SUBSTANCE_FIELDS).lower()
if HOT.search(substance) and COLD.search(substance):
out.add("thermal-conflict")
if entity.get("condition") in pristine and BREAKING_GERUND.search(situation):
out.add("pristine-but-destroyed")
if "submerged" in affords and FIRE.search(situation):
out.add("fire-in-wrong-medium")
if "submerged" in affords and WEATHER.search(situation + " " + context):
out.add("weather-in-wrong-medium")
if place in (pack.environment_bands.get("interior") or ()) and context and DISTANCE.search(low):
out.add("interior-distance-context")
context_sentence = next((s for s in low.split(". ") if context and context in s), "")
if STANCE_VERB.search(context_sentence.replace(context, "")):
out.add("context-stance-verb")
return sorted(out)
#: Fantasy and horror. A class not listed is a test file's class, zero-gated there,
#: so any hit here is a rare draw the test sweep never reached. Shape ceilings were
#: measured at 3000 seeds on both paths when added (2026-10-17), after fixing merfolk
#: bracing against "a gust of grit" on the seabed (weather 0.13% -> 0).
PACK_CEILINGS: dict[str, dict[str, float]] = {
"fantasy": {
# 0.67 / 0.57: wide on purpose. A gleaming golem "splitting along a fresh crack",
# a pristine crown "bursting into a halo of cold blue flame", and plain misses
# ("crumbling a stone block in its grip", "breaking the surface").
"pristine-but-destroyed": 1.0,
# 0.07 / 0.17: a frost-grown crystal golem or a frost giant with a hot word.
"thermal-conflict": 0.3,
"fire-in-wrong-medium": 0.0,
"weather-in-wrong-medium": 0.0,
"interior-distance-context": 0.0,
"context-stance-verb": 0.0,
},
"horror": {
"pristine-but-destroyed": 0.0,
"thermal-conflict": 0.0,
"fire-in-wrong-medium": 0.0,
"weather-in-wrong-medium": 0.0,
# 0.90 / 0.83: the chapel and the ballroom afford ``vast``, so "In the distance"
# is the pack's own choice there.
"interior-distance-context": 1.0,
"context-stance-verb": 0.0,
},
}
def _classifier(slug: str):
"""``(pack, classify, ceilings)`` for one pack."""
if slug == "scifi":
return PACK, classes, CEILINGS
pack = load_pack(slug)
module = __import__(f"tests.test_{slug}_pack", fromlist=["_classes"])
def classify(text: str, document: dict) -> "list[str]":
return sorted(set(module._classes(text, document)) | set(shape_classes(pack, text, document)))
return pack, classify, PACK_CEILINGS[slug]
def sweep(seeds: int, path: str, examples: int, slug: str = "scifi"):
"""``(counts, scenes with any class, examples)`` over ``seeds`` scenes."""
pack, classify, _ceilings = _classifier(slug)
rng = random.Random(777)
tally: Counter = Counter()
shown: dict[str, list[str]] = defaultdict(list)
@@ -309,12 +391,12 @@ def sweep(seeds: int, path: str, examples: int):
entity_seed, scene_seed = rng.randrange(2**48), rng.randrange(2**48)
wired = {}
if path == "wired":
_text, payload = generate_entity(entity_seed, PACK)
_text, payload = generate_entity(entity_seed, pack)
wired = {1: payload}
text, document = generate_scene(
scene_seed, PACK, wired_entities=wired, entity_count=1
scene_seed, pack, wired_entities=wired, entity_count=1
)
found = classes(text, document)
found = classify(text, document)
tally.update(found)
flagged += bool(found)
for name in found:
@@ -329,18 +411,21 @@ def main(argv: "list[str] | None" = None) -> int:
parser.add_argument("--path", choices=("wired", "unwired"), default="wired")
parser.add_argument("--examples", type=int, default=0)
parser.add_argument("--gate", action="store_true")
parser.add_argument("--pack", choices=PACK_SLUGS, default="scifi")
args = parser.parse_args(argv)
logging.getLogger("sceneweaver").setLevel(logging.ERROR)
tally, flagged, shown = sweep(args.seeds, args.path, args.examples)
ceilings = _classifier(args.pack)[2]
tally, flagged, shown = sweep(args.seeds, args.path, args.examples, args.pack)
share = 100.0 * flagged / args.seeds
print(f"coherence_sweep -- {args.path} path, {args.seeds} scenes, "
print(f"coherence_sweep -- {args.pack}, {args.path} path, {args.seeds} scenes, "
f"{share:.1f}% carry at least one class")
over: list[str] = []
for name in sorted(CEILINGS):
# A class with no ceiling is a test file's zero-gated class: any hit is over.
for name in sorted(set(ceilings) | set(tally)):
count = tally.get(name, 0)
pct = 100.0 * count / args.seeds
ceiling = CEILINGS[name]
ceiling = ceilings.get(name, 0.0)
mark = ""
if pct > ceiling:
mark = f" <-- over ceiling {ceiling:.1f}%"
+1 -1
View File
@@ -110,7 +110,7 @@ def flags_0914(pack, doc, text):
" ".join([sit, ctx, field(e, "extras").lower(),
field(e, "appendages").lower()])):
out.append("tether-cable-chain")
if (re.search(r"\b(dragg\w*|haul\w*|tow\w*|tugg\w*)\b", sit)
if (re.search(r"\b(dragg\w*|haul\w*|tow(?!ards?\b)\w*|tugg\w*)\b", sit)
and (kind == "wreck"
or (kind == "robot or mech" and grp != "humanoid unit")
or (kind == "alien creature" and grp in _DRAG_CREATURE_GROUPS))):
+84 -36
View File
@@ -1,6 +1,6 @@
"""Reach audit -- a value nobody draws is dead.
python scripts/reach_audit.py --seeds 12000 [--path wired|unwired|both] [--gate]
python scripts/reach_audit.py --seeds 12000 [--path wired|unwired|locked|both] [--gate]
python scripts/reach_audit.py --explain "luminous flank slit"
``check_shadowed_values`` in ``tests/validate_data.py`` proves a value is *reachable*: some
@@ -53,28 +53,6 @@ FIELDS = tuple(sorted(
))
def _subjects(pack):
"""Every ``(kind, type)`` a scene can hold; ``(kind, None)`` for a kind with no types."""
name = G.type_field(pack)
for kind in pack.kinds:
values = G.pool_for(pack, name, {G.KIND_FIELD: kind}) if name else ()
for value in values or (None,):
yield kind, value
def _reach(pack, field_name):
"""``{value: [(kind, type), ...]}`` -- every subject whose resolved pool holds the value."""
name = G.type_field(pack)
reach: dict[str, list[tuple[str, str | None]]] = {}
for kind, value in _subjects(pack):
scope = {G.KIND_FIELD: kind}
if name and value is not None:
scope[name] = value
for option in G.pool_for(pack, field_name, scope):
reach.setdefault(option, []).append((kind, value))
return reach
def _exempt(field, value, reach):
"""Whether a never-drawn value is excused rather than dead."""
if G.pool_keys_for_value(P, field, value) == (G.POOL_DEFAULT_KEY,):
@@ -90,29 +68,92 @@ def _exempt(field, value, reach):
return True
def _sweep(path, seeds):
"""Count every non-None value of every field over ``seeds`` scenes on ``path``."""
def _scenes(path, seeds):
"""Yield ``(text, document)`` for ``seeds`` one-entity scenes on ``path``."""
rng = random.Random(_SEED)
counts = {field: Counter() for field in FIELDS}
# 0.8.0: the locked path gives every subject the same share of scenes, so a
# one-type value is not left to how often a random scene happens to pick its type.
subjects = list(G.subjects(P))
type_widget = f"entity1_{G.type_field(P)}"
for index in range(seeds):
if path == "wired":
if path == "locked":
kind, value = subjects[index % len(subjects)]
widgets = {"entity1_kind": kind} | ({type_widget: value} if value else {})
yield generate_scene(rng.randrange(2**48), P, widgets=widgets, entity_count=1)
elif path == "wired":
_text, payload = generate_entity(rng.randrange(2**48), P)
_text, document = generate_scene(
yield generate_scene(
rng.randrange(2**48), P, wired_entities={1: payload}, entity_count=1
)
else:
_text, document = generate_scene(rng.randrange(2**48), P, entity_count=1)
yield generate_scene(rng.randrange(2**48), P, entity_count=1)
done = index + 1
if done % _PROGRESS == 0:
print(f" {path}: {done}/{seeds} scenes", flush=True)
def _sweep(path, seeds):
"""Count every non-None value of every field over ``seeds`` scenes on ``path``."""
counts = {field: Counter() for field in FIELDS}
for _text, document in _scenes(path, seeds):
record = document["entities"][0] if document["entities"] else {}
for field in FIELDS:
value = document.get(field) if field in _SCENE_FIELDS else record.get(field)
if value is not None:
counts[field][value] += 1
done = index + 1
if done % _PROGRESS == 0:
print(f" {path}: {done}/{seeds} scenes", flush=True)
return counts
#: The fields that put a face on the subject; their share is reported, not gated.
_FACE_FIELDS = ("sensors", "aperture")
def _variety(path, seeds):
"""Print the look and act variety a user actually sees, per pack.
The numbers the 0.8.0 floors are judged by: distinct ``(variant, form)``
silhouettes per type, the share of drawn acts that are the subject's own,
the most common opening verb, how often the context goes unsaid, and how
often a face is named.
"""
name = G.type_field(P)
owned = G.own_values(P, G.SITUATION_FIELD)
looks: dict[str, set] = {}
draws: Counter = Counter()
verbs: Counter = Counter()
acts = own = no_context = faces = 0
for _text, document in _scenes(path, seeds):
if document.get(G.CONTEXT_FIELD) is None:
no_context += 1
if not document["entities"]:
continue
record = document["entities"][0]
subject = record.get(name) or record.get(G.KIND_FIELD)
draws[subject] += 1
looks.setdefault(subject, set()).add((record.get("variant"), record.get(G.STANCE_FIELD)))
if any(record.get(field) for field in _FACE_FIELDS):
faces += 1
act = record.get(G.SITUATION_FIELD)
if act:
acts += 1
own += act in owned
verbs[act.split()[0]] += 1
top_verb, top_count = verbs.most_common(1)[0] if verbs else ("-", 0)
silhouettes = sorted((len(v), k) for k, v in looks.items())
thin = [k for n, k in silhouettes if n < 8 and draws[k] >= 30]
print(f"\nvariety -- {path} path, {seeds} scenes")
print(f" own-act share {own / max(acts, 1):6.1%} (held by <= 3 types or one group)")
print(f" top first verb {top_count / max(acts, 1):6.1%} ({top_verb!r})")
print(f" context absent {no_context / seeds:6.1%}")
print(f" face named {faces / seeds:6.1%}")
median = silhouettes[len(silhouettes) // 2][0] if silhouettes else 0
print(f" silhouettes / type median {median}, types drawn {len(silhouettes)}")
print(f" under 8 silhouettes {len(thin)} types drawn 30+ times")
if thin:
print(" " + ", ".join(thin[:40]) + (" ..." if len(thin) > 40 else ""))
return thin
def _report(label, counts):
"""Print the per-field table and the never/exempt lists; return ``{field: dead}``."""
print(f"\nreach_audit -- {label}")
@@ -123,7 +164,7 @@ def _report(label, counts):
options = G.pool_options(P, field)
seen = counts[field]
never = [value for value in options if value not in seen]
reach = _reach(P, field)
reach = G.value_reach(P, field)
exempt = {value for value in never if _exempt(field, value, reach)}
dead = [value for value in never if value not in exempt]
dead_by_field[field] = dead
@@ -148,7 +189,7 @@ def _explain(value):
if value not in G.pool_options(P, field):
continue
found = True
reach = _reach(P, field)
reach = G.value_reach(P, field)
print(f"{field}: {value!r}")
print(f" pool keys: {G.pool_keys_for_value(P, field, value)}")
print(f" subjects: {reach.get(value, [])}")
@@ -164,9 +205,11 @@ def _explain(value):
def main(argv: "list[str] | None" = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--seeds", type=int, default=12000)
parser.add_argument("--path", choices=("wired", "unwired", "both"), default="both")
parser.add_argument("--path", choices=("wired", "unwired", "locked", "both"), default="both")
parser.add_argument("--gate", action="store_true")
parser.add_argument("--explain", default="", metavar="VALUE")
parser.add_argument("--variety", action="store_true", help="report look and act variety")
parser.add_argument("--seed", type=int, default=4242, help="sweep seed (--variety)")
parser.add_argument("--pack", choices=("scifi", "fantasy", "horror"), default="scifi")
args = parser.parse_args(argv)
if args.pack == "fantasy":
@@ -177,7 +220,12 @@ def main(argv: "list[str] | None" = None) -> int:
logging.getLogger("sceneweaver").setLevel(logging.ERROR)
if args.explain:
return _explain(args.explain)
paths = ("wired", "unwired") if args.path == "both" else (args.path,)
paths = ("wired", "unwired", "locked") if args.path == "both" else (args.path,)
if args.variety:
global _SEED
_SEED = args.seed
thin = [_variety(path, args.seeds) for path in paths if path != "locked"]
return 1 if args.gate and any(thin) else 0
merged = {field: Counter() for field in FIELDS}
dead_by_field: dict[str, list[str]] = {}
for path in paths:
+4 -3
View File
@@ -36,7 +36,7 @@ from engine.budget import (
HERO = ALLOWANCE_BY_COUNT[1][0]
#: The head-phrase modifier fields. They are two words in front of the noun,
#: not clauses, so they never spend the allowance and are always spoken.
HEAD_MODIFIERS = frozenset({"scale", "condition"})
HEAD_MODIFIERS = frozenset({"scale", "condition", "variant"})
from engine.prose import render_entity
from engine.resolution import ResolvedEntity
@@ -45,6 +45,7 @@ FULL = {
"subkind": "heavy freighter",
"scale": "large",
"condition": "battle-scarred",
"variant": "military-pattern",
"form": "needle hull",
"material": "titanium alloy",
"primary_color": "gunmetal grey",
@@ -335,7 +336,7 @@ class ArchetypeBudgetTests(unittest.TestCase):
def test_a_cap_lowers_a_callers_allowance(self) -> None:
values = apply_budget(SCIFI_PACK, FULL, budget=HERO, archetype=self._capped(4))
self.assertLessEqual(len(spoken(values) - {"kind"}), 4)
self.assertLessEqual(len(spoken(values) - {"kind", "variant"}), 4)
def test_a_cap_never_raises_a_callers_allowance(self) -> None:
values = apply_budget(SCIFI_PACK, FULL, budget=3, archetype=self._capped(9))
@@ -345,7 +346,7 @@ class ArchetypeBudgetTests(unittest.TestCase):
"""``budget=None`` means \"whatever this kind of thing speaks\", not
\"everything\" -- which is what keeps the Scene Entity node honest."""
values = apply_budget(SCIFI_PACK, FULL, budget=None, archetype=self._capped(5))
self.assertLessEqual(len(spoken(values) - {"kind"}), 5)
self.assertLessEqual(len(spoken(values) - {"kind", "variant"}), 5)
def test_an_archetypes_priority_is_spent_first(self) -> None:
archetype = Archetype(head_phrase=None, detail_priority=("markings", "extras"))
+5 -1
View File
@@ -47,6 +47,7 @@ from data.genre import (
is_classified,
pool_for,
pool_options,
scene_globals,
spoken_value,
)
from data.scifi import SCIFI_PACK, _FLOOR_BOUND
@@ -123,6 +124,7 @@ def _scene(document) -> ResolvedScene:
environment=document["environment"],
context=document.get("context"),
context_sentence_index=document["_meta"].get("context_sentence_index"),
scene_values={name: document.get(name) for name in scene_globals(SCIFI_PACK) if name != "context"},
entities=tuple(_entities(document)),
relations=tuple(
ResolvedRelation(endpoints=tuple(record["endpoints"]), value=record["value"], position=record.get("position"))
@@ -742,10 +744,12 @@ class ArchetypeShapeTests(unittest.TestCase):
archetype = SCIFI_PACK.archetypes.get(name) if name else None
if archetype is None or archetype.detail_cap is None:
continue
# The variant is a design word on top of the cap, never a
# clause the cap counts (engine/budget.py).
spoken = [
n
for n in self._HEADS
if n != KIND_FIELD and record.get(n) is not None
if n not in (KIND_FIELD, "variant") and record.get(n) is not None
]
with self.subTest(seed=seed, archetype=name):
self.assertLessEqual(len(spoken), archetype.detail_cap)
+135 -2
View File
@@ -12,7 +12,8 @@ from dataclasses import dataclass, field
from typing import Callable, Mapping
from data import fantasy as FANTASY
from data.genre import GenrePack, affordances_of, group_of, pool_for, resolved_needs
from data import horror as HORROR
from data.genre import POSTURE_VERBS, GenrePack, archetype_for, subjects, type_field, affordances_of, group_of, pool_for, resolved_needs
from data.fantasy import FANTASY_PACK
from data.horror import HORROR_PACK
from data.scifi import SCIFI_PACK
@@ -51,6 +52,21 @@ def scenes(concern: Concern):
yield seed, document["entities"][0], document, text
_FORM_WORDS = {"stand": {"standing", "upright"}, "sit": {"seated", "slumped"}}
def _posture(text: str, table: Mapping) -> "str | None":
"""The posture a form's or an act's first word names, if any."""
first = text.split(" ")[0] if text else ""
return next((p for p, words in table.items() if first in words), None)
def _posture_clash(record: dict) -> bool:
form = _posture(said(record, "form"), _FORM_WORDS)
act = _posture(said(record, "situation"), POSTURE_VERBS)
return None not in (form, act) and form != act
def said(record: dict, name: str) -> str:
return (record.get(name) or "").lower()
@@ -540,7 +556,9 @@ CONCERNS: tuple[Concern, ...] = (
),
Concern(
"a sealed helmet is drawn with an open face",
lambda r, d, t: "helmet" in t.lower() and said(r, "aperture") in (
# A helmet the act names belongs to someone else ("anointing a kneeling
# marine's helmet"), not to this subject's face.
lambda r, d, t: "helmet" in t.lower().replace(said(r, "situation"), "") and said(r, "aperture") in (
"open visor", "hood opening", "respirator grille", "breathing mask vent"
),
widgets={"entity1_kind": "spacefarer"},
@@ -1364,6 +1382,100 @@ CONCERNS = CONCERNS + (
)
for subkind in FANTASY.SUBKIND_POOLS["construct"]
),
# 0.8.0 render test: shared placement and place-state pools reached the wrong place.
Concern(
"long grass in snowbound woods",
lambda r, d, t: "long grass" in t,
widgets={"environment": "snowbound pine woods"},
pack=HORROR_PACK,
),
Concern(
"an attic is flooded",
lambda r, d, t: "flood" in t,
widgets={"environment": "attic crawlspace"},
pack=HORROR_PACK,
),
# 0.8.0 render test, second look: a merfolk "brandishing a weapon high" with a
# bone spear held two weapons; a resting revenant's axe floated beside it.
Concern("an act names a second weapon", lambda r, d, t: bool(r.get("armament")) and bool(
re.search(r"\ba (raised |lowered |massive |heavy )?weapon\b", said(r, "situation"))),
widgets={"entity1_subkind": "merfolk"}, pack=FANTASY_PACK),
Concern("a resting revenant carries a weapon",
lambda r, d, t: bool(r.get("armament")) and r.get("situation") in FANTASY.DORMANT_ACTS,
widgets={"entity1_subkind": "drowned revenant"}, pack=FANTASY_PACK),
Concern("the resting dead carry a weapon",
lambda r, d, t: bool(r.get("armament")) and r.get("situation") in HORROR.DORMANT_ACTS,
widgets={"entity1_kind": "undead"}, pack=HORROR_PACK),
Concern("a standing doll is sitting", lambda r, d, t: _posture_clash(r),
widgets={"entity1_subkind": "porcelain doll"}, pack=HORROR_PACK),
Concern("a drowned revenant wears netting", lambda r, d, t: "net" in said(r, "material").split("-"),
widgets={"entity1_subkind": "drowned revenant"}, pack=FANTASY_PACK),
Concern("a fire-damaged look renders as live fire", lambda r, d, t: "fire-" in " ".join(
str(v) for k, v in r.items() if k in ("variant", "material", "condition", "form", "surface_detail")),
widgets={"entity1_subkind": "boarded-up church"}, pack=HORROR_PACK),
Concern("a roadblock fence hung with sheeting", lambda r, d, t: "sheeting" in t,
widgets={"environment": "military roadblock on an empty highway"}, pack=HORROR_PACK),
Concern("a wreck reads as a sailing ship or trails a giant tube",
lambda r, d, t: bool(re.search(r"bow section|snapped spar|ducting|by salvage drones", t)),
widgets={"entity1_kind": "wreck"}, pack=SCIFI_PACK),
# 0.8.0 per-kind render batch.
Concern("coin-sized spiders render as coins", lambda r, d, t: "coin" in t,
widgets={"entity1_subkind": "swarm of spiders"}, pack=HORROR_PACK),
Concern("a hall clock in a supermarket", lambda r, d, t: r.get("subkind") in (
"grandfather clock", "haunted family picture"),
widgets={"environment": "looted supermarket aisle", "entity1_kind": "cursed object"}, pack=HORROR_PACK),
Concern("the dead claw with both hands and hold a sword", lambda r, d, t: bool(r.get("armament")) and said(
r, "situation").startswith(("clawing", "scratching", "cracking open", "dragging a bloodied", "pushing aside")),
widgets={"environment": "dusty manor ballroom", "entity1_subkind": "bone revenant"}, pack=HORROR_PACK),
Concern("a skeleton eats", lambda r, d, t: bool(re.search(r"raw meat|fresh kill|strip of flesh", t)),
widgets={"entity1_subkind": "walking skeleton"}, pack=HORROR_PACK),
Concern("a chariot grows a scythe", lambda r, d, t: "scythe" in t,
widgets={"entity1_subkind": "war chariot"}, pack=FANTASY_PACK),
Concern("a spectral flame floats free", lambda r, d, t: bool(re.search(r"spectral flame(?! burning)", t)),
widgets={"entity1_kind": "undead"}, pack=FANTASY_PACK),
Concern("a survey glider pushes a scoop", lambda r, d, t: "scoop through" in t,
widgets={"entity1_subkind": "survey glider"}, pack=SCIFI_PACK),
# A faun "lowering their horned head in challenge" rendered as a whole goat,
# its spear floating beside it: a beast's act makes a half-person a beast.
Concern("a faun acts like a goat", lambda r, d, t: bool(re.search(r"head in challenge|with a snort", t)),
widgets={"entity1_subkind": "faun"}, pack=FANTASY_PACK),
Concern("a centaur turns into a horse", lambda r, d, t: bool(re.search(r"small (?:[\w-]+ )*centaur|war harness|pony|horse tail", t)),
widgets={"entity1_subkind": "centaur"}, pack=FANTASY_PACK),
# --- coherence_sweep --pack fantasy at 4000 seeds: what the 500-seed test sweep missed ---
*(
Concern(f"a dormant undead has no act in {place}", lambda r, d, t: not r.get("situation"),
widgets={"environment": place, "entity1_kind": "undead", "entity1_condition": "dormant"},
pack=FANTASY_PACK)
for place in ("abyssal sea trench", "sunken temple ruins")
),
*(
Concern(f"an abandoned {subkind} has no act in {place}", lambda r, d, t: not r.get("situation"),
widgets={"environment": place, "entity1_kind": "vessel", "entity1_subkind": subkind,
"entity1_condition": "abandoned"}, pack=FANTASY_PACK)
for subkind in ("airship", "sky galleon", "cloud skiff")
for place in ("sea of clouds", "castle courtyard", "harbour town quay")
),
Concern("a wrecked airship has no act in the sky", lambda r, d, t: not r.get("situation"),
widgets={"environment": "stormy sky above a mountain range", "entity1_subkind": "airship",
"entity1_form": "torn gasbag sagging over a broken hull"}, pack=FANTASY_PACK),
# A lock a drawn field contradicts: the drawn field moves, the lock stays.
Concern("a locked-wrecked airship has no act in the sky", lambda r, d, t: not r.get("situation"),
widgets={"environment": "sea of clouds", "entity1_subkind": "airship",
"entity1_condition": "wrecked"}, pack=FANTASY_PACK),
Concern("a torn gasbag drifts on the wind",
lambda r, d, t: said(r, "situation") == "drifting crewless on the wind",
widgets={"environment": "windswept moorland", "entity1_subkind": "airship",
"entity1_form": "torn gasbag sagging over a broken hull"}, pack=FANTASY_PACK),
Concern("a sky galleon or a cloud skiff has a gasbag",
lambda r, d, t: "gasbag" in said(r, "situation") and said(r, "subkind") != "airship",
widgets={"environment": "windswept moorland", "entity1_kind": "vessel"}, pack=FANTASY_PACK),
Concern("a sea folk braces against a gust underwater",
lambda r, d, t: "gust" in said(r, "situation"),
widgets={"environment": "kelp forest depths", "entity1_kind": "hybrid folk",
"entity1_subkind": "merfolk"}, pack=FANTASY_PACK),
Concern("a huge subject fits in a forge",
lambda r, d, t: said(r, "scale") in ("huge", "colossal", "titanic"),
widgets={"environment": "blacksmith's forge"}, pack=FANTASY_PACK),
)
@@ -1394,6 +1506,27 @@ def hands_used(pack: GenrePack, record: dict) -> int:
return total
#: An act whose "its" or "their" names something other than the subject.
_PRONOUN_FREE = {"unfurling its wings to their full span", "dragging a disembowelled body by its ankles"}
class PronounTests(unittest.TestCase):
def test_an_act_speaks_its_subjects_pronoun(self) -> None:
"""A faun "lowering its head" rendered as a goat: "its" makes a person a beast."""
for pack in (SCIFI_PACK, FANTASY_PACK, HORROR_PACK):
name = type_field(pack)
wrong: dict[str, str] = {}
for kind, sub in subjects(pack):
scope = {"kind": kind, **({name: sub} if name and sub else {})}
pronoun = archetype_for(pack, scope).pronoun or pack.prose.pronoun
other = r"\b(their|themselves)\b" if pronoun == "it" else r"\b(its|itself)\b"
for act in pool_for(pack, "situation", scope):
if act not in _PRONOUN_FREE and re.search(other, act):
wrong.setdefault(act, sub or kind)
with self.subTest(pack=pack.slug):
self.assertEqual(wrong, {}, f"{pack.slug}: an act speaks the wrong pronoun")
class HandBudgetTests(unittest.TestCase):
def test_a_person_never_holds_more_than_two_hands_can(self) -> None:
for pack in (SCIFI_PACK, FANTASY_PACK, HORROR_PACK):
+4 -2
View File
@@ -130,10 +130,12 @@ class AddressResolutionTests(unittest.TestCase):
def test_every_trigger_value_is_a_real_option(self) -> None:
for rule in SCIFI_PACK.all_constraints:
field = PATH_TO_FIELD[_resolved_paths(rule.field)[0]]
# Every keyed pool, not pool_for: a bare-string scope reads as a
# kind, so place-keyed scene pools (context) would look empty.
reachable = {
option
for key in (None, *SCIFI_PACK.pools.get(field, {}))
for option in pool_for(SCIFI_PACK, field, key)
for values in SCIFI_PACK.pools.get(field, {}).values()
for option in values
}
for trigger in rule.triggers:
with self.subTest(rule=rule.reason, field=field, value=trigger):
+1 -1
View File
@@ -368,7 +368,7 @@ class RoundXXIXTests(unittest.TestCase):
SCIFI_PLACES = ("genetics laboratory", "living bioship corridor", "terraced arboretum dome")
NEW_SITUATIONS = (
(HORROR_PACK, H._S_DEAD_EV_WRECK + H._S_SPIRIT_EV_WRECK + H._S_ELDRITCH_EV_WRECK
+ H._S_BEAST_EV_WRECK + H._S_SURVIVOR_EV_WRECK + H._S_SWARM_EV_WRECK),
+ H._S_BEAST_EV_WRECK + H._S_SWARM_EV_WRECK),
(SCIFI_PACK, S._SITUATION_VOID_RITES + (
"smashing out of a cracked specimen tank in a flood of green fluid",
"clamping a cracked specimen tank shut as green fluid sprays out",
+2 -1
View File
@@ -86,7 +86,8 @@ class JsonSchemaTests(unittest.TestCase):
def test_the_top_level_shape(self) -> None:
self.assertEqual(
set(self.document), {"environment", "context", "entities", "relations", "_meta"}
set(self.document),
{"environment", "context", "staging", "aspect", "entities", "relations", "_meta"},
)
def test_the_meta_block(self) -> None:
+7 -5
View File
@@ -41,6 +41,7 @@ from data.genre import (
pool_options,
relation_pairs,
widget_choices,
widget_fields,
widget_order,
)
from data.scifi import SCIFI_PACK
@@ -52,9 +53,9 @@ from tests._loader import REPO_ROOT
#: which is not a field -- see genre.py -- + environment + slot 1's 21
#: morphology fields and its situation + three brief slots of five + six
#: relations + six positions.
EXPECTED_SCENE_KEYS = 54
EXPECTED_SCENE_KEYS = 56
EXPECTED_ENTITY_KEYS = 22
EXPECTED_ENTITY_FIELDS = 21
EXPECTED_ENTITY_FIELDS = 22
#: Directories that must never name a genre.
GENRE_FREE_DIRS = ("nodes", "engine")
@@ -230,11 +231,11 @@ class BuildFieldDefinitionsTests(unittest.TestCase):
)
def test_entity_node_is_a_seed_plus_the_morphology(self) -> None:
self.assertEqual(list(self.entity), ["seed", *SCIFI_PACK.entity_fields])
self.assertEqual(list(self.entity), ["seed", *widget_fields(SCIFI_PACK)])
def test_slot_one_is_full_depth_and_the_rest_are_brief(self) -> None:
slot_one = [d.base for d in self.scene.values() if d.slot == 1]
self.assertEqual(slot_one, [*SCIFI_PACK.entity_fields, "situation"])
self.assertEqual(slot_one, [*widget_fields(SCIFI_PACK), "situation"])
brief = [name for name, s in SCIFI_PACK.entity_fields.items() if s.brief]
for slot in (2, 3, 4):
with self.subTest(slot=slot):
@@ -362,7 +363,8 @@ class PackStructureTests(unittest.TestCase):
def test_scene_fields_are_declared(self) -> None:
self.assertEqual(
list(SCIFI_PACK.scene_fields),
["environment", "situation", "relation", "relation_position", "context"],
["environment", "situation", "relation", "relation_position", "context",
"staging", "aspect"],
)
#: Pool fields no todo has authored yet, and the todo that owns each. Todo 3
+22
View File
@@ -1022,5 +1022,27 @@ class FeasibilitySeamTests(unittest.TestCase):
self.assertNotEqual(record["kind"], BEAST)
class SpecificityTests(unittest.TestCase):
"""An owned act keeps its weight; a shared act is discounted by its reach."""
def test_owned_acts_are_not_discounted_and_shared_ones_are(self) -> None:
from data.genre import SITUATION_FIELD, own_values, value_reach
from data.scifi import SCIFI_PACK as pack
weights = pack.weights_for(SITUATION_FIELD)
owned = own_values(pack, SITUATION_FIELD)
reach = value_reach(pack, SITUATION_FIELD)
tiers = pack.value_tiers.get(SITUATION_FIELD, {})
base = lambda v: pack.tier_weights.get(tiers.get(v, ""), 1.0) # noqa: E731
solo = next(v for v in owned if len(reach[v]) == 1)
group = next(v for v in owned if len(reach[v]) > 3)
shared = max((v for v in reach if v not in owned), key=lambda v: len(reach[v]))
self.assertAlmostEqual(weights[solo] / base(solo), 1.0)
self.assertAlmostEqual(weights[group] / base(group), 1.0)
self.assertAlmostEqual(
weights[shared] / base(shared), len(reach[shared]) ** -pack.specificity_exponent
)
if __name__ == "__main__":
unittest.main()
+8 -6
View File
@@ -100,14 +100,16 @@ class NodeIdentityTests(unittest.TestCase):
self.assertEqual([o.display_name for o in entity_outputs], ["entity_text", "entity"])
self.assertEqual(entity_outputs[1].io_type, "SCENE_ENTITY")
def test_both_force_a_fresh_roll_every_queue(self) -> None:
"""ComfyUI #11905: with ``control_after_generate`` advancing the seed, a
cached result can be served for the new seed. ``vars(cls)`` rather than
``hasattr`` -- the base class declares the hook either way."""
def test_neither_overrides_the_input_cache(self) -> None:
"""The output is a pure function of the inputs (a changed seed is a
changed input), so ComfyUI's input cache is correct. A never-equal
fingerprint cannot produce a new scene -- an unchanged seed re-runs to the
same text -- but it enters every downstream node's cache signature, so a
re-queue re-ran the sampler. Measured on a live ComfyUI before removing it.
``vars(cls)`` rather than ``hasattr`` -- the base class declares the hook."""
for name, node in self.nodes.items():
with self.subTest(node=name):
self.assertIn("fingerprint_inputs", vars(node))
self.assertNotEqual(node.fingerprint_inputs(), node.fingerprint_inputs())
self.assertNotIn("fingerprint_inputs", vars(node))
def test_neither_node_is_a_shell_any_more(self) -> None:
"""Replaces the placeholder assertions Todos 17 and 18 retired. The
+10 -10
View File
@@ -36,7 +36,7 @@ class SchemaShapeTests(unittest.TestCase):
def test_input_count_is_the_seed_plus_the_whole_morphology(self) -> None:
"""22 = one seed + the pack's entity fields. Derived from the pack, not
typed in, so a genre with a different field count still passes."""
self.assertEqual(len(self.schema.inputs), 1 + len(SCIFI_PACK.entity_fields))
self.assertEqual(len(self.schema.inputs), 1 + len(genre.widget_fields(SCIFI_PACK)))
self.assertEqual(len(self.schema.inputs), 22)
def test_widget_order_matches_the_contract_exactly(self) -> None:
@@ -62,7 +62,7 @@ class SchemaShapeTests(unittest.TestCase):
self.assertEqual((seed.min, seed.max), (genre.SEED_MIN, genre.SEED_MAX))
def test_every_field_offers_random_then_options_then_none(self) -> None:
for name in SCIFI_PACK.entity_fields:
for name in genre.widget_fields(SCIFI_PACK):
with self.subTest(field=name):
options = self.by_id[name].options
self.assertEqual(options[0], RANDOM)
@@ -73,12 +73,12 @@ class SchemaShapeTests(unittest.TestCase):
def test_every_field_defaults_to_random(self) -> None:
"""Full random with no configuration is the pack's headline behaviour."""
for name in SCIFI_PACK.entity_fields:
for name in genre.widget_fields(SCIFI_PACK):
with self.subTest(field=name):
self.assertEqual(self.by_id[name].default, RANDOM)
def test_every_field_tooltip_states_the_three_choices(self) -> None:
for name in SCIFI_PACK.entity_fields:
for name in genre.widget_fields(SCIFI_PACK):
with self.subTest(field=name):
# Help sentence first, then one shared mechanic line last, so
# the three choices always read in the same place on every
@@ -94,7 +94,8 @@ class SchemaShapeTests(unittest.TestCase):
"""Per-kind labels are the frontend's job: a widget's label is fixed at
registration and the kind is not, so the schema carries the generic
name and ``js/sceneweaver.js`` rewrites it."""
for name, spec in SCIFI_PACK.entity_fields.items():
for name in genre.widget_fields(SCIFI_PACK):
spec = SCIFI_PACK.entity_fields[name]
with self.subTest(field=name):
self.assertEqual(self.by_id[name].display_name, spec.label)
@@ -213,11 +214,10 @@ class ExecuteTests(unittest.TestCase):
for seed in range(6):
with self.subTest(seed=seed):
_, payload = NODE.execute(seed=seed, kind="alien creature").args
form = payload["fields"]["form"]
if form is not None:
self.assertIn(
form, genre.pool_for(SCIFI_PACK, "form", "alien creature")
)
fields = payload["fields"]
if fields["form"] is not None:
scope = genre.subject_scope(SCIFI_PACK, "alien creature", fields["subkind"])
self.assertIn(fields["form"], genre.pool_for(SCIFI_PACK, "form", scope))
def test_a_count_never_survives_the_noun_it_counts(self) -> None:
"""A quantity of nothing in the payload would be believed by every
+21 -6
View File
@@ -45,12 +45,13 @@ class SchemaShapeTests(unittest.TestCase):
self.by_id = {i.id: i for i in self.schema.inputs}
def test_input_counts(self) -> None:
"""55 widgets: 4 controls (seed, entity count, scene filter, bulk edit)
"""57 widgets: 4 controls (seed, entity count, scene filter, bulk edit)
+ environment + slot 1's 21 + 3 brief slots of 5 + 4 situations
+ 6 relations + 6 positions + context. Plus four optional sockets."""
self.assertEqual(len(self.widgets), 55)
+ 6 relations + 6 positions + context, placement and place state. Plus
four optional sockets."""
self.assertEqual(len(self.widgets), 57)
self.assertEqual(len(self.sockets), SCENE_NODE_SLOTS)
self.assertEqual(len(self.schema.inputs), 59)
self.assertEqual(len(self.schema.inputs), 61)
def test_widget_order_matches_the_contract_exactly(self) -> None:
self.assertEqual(
@@ -72,7 +73,7 @@ class SchemaShapeTests(unittest.TestCase):
def test_slot_one_is_full_depth_and_the_others_are_brief(self) -> None:
"""The core node is never a stub, and supporting slots stay brief until
something is wired into them."""
for name in SCIFI_PACK.entity_fields:
for name in genre.widget_fields(SCIFI_PACK):
with self.subTest(field=name):
self.assertIn(f"entity1_{name}", self.by_id)
brief = {"kind", "subkind", "scale", "condition"}
@@ -132,7 +133,8 @@ class PromptJsonSchemaTests(unittest.TestCase):
def test_top_level_keys_exactly(self) -> None:
self.assertEqual(
set(self.document), {"environment", "context", "entities", "relations", "_meta"}
set(self.document),
{"environment", "context", "staging", "aspect", "entities", "relations", "_meta"},
)
def test_meta_keys_exactly_and_carries_the_seed(self) -> None:
@@ -341,6 +343,19 @@ class WiredEntityTests(unittest.TestCase):
with self.assertRaises(ValueError):
NODE.execute(seed=8, entity_1_in="not a payload")
def test_a_cached_payload_is_reused_unchanged(self) -> None:
"""ComfyUI caches the Entity node and hands the same payload object to
every later run, so the scene must neither mutate it nor read it
differently the second time."""
for seed in range(25):
with self.subTest(seed=seed):
_, payload = ENTITY_NODE.execute(seed=seed).args
before = json.dumps(payload, sort_keys=True)
first = _run(seed=seed, entity_count="2", **{entity_socket_key(2): payload})
self.assertEqual(json.dumps(payload, sort_keys=True), before)
second = _run(seed=seed, entity_count="2", **{entity_socket_key(2): payload})
self.assertEqual(first, second)
if __name__ == "__main__": # pragma: no cover
unittest.main()
+12 -9
View File
@@ -48,6 +48,9 @@ from tests._loader import REPO_ROOT, load_entrypoint
#: unambiguous.
CUSTOM_COLOUR = "zzz-test-hunter-green"
CUSTOM_SITUATION = "zzz-test drifting past a survey buoy"
#: Every starship subkind reads a situation pool of its own, so a value keyed by
#: the kind is read through one of them.
SCOUT = {"kind": "starship", "subkind": "scout ship"}
DOCUMENT = {
"pools": {
@@ -64,13 +67,13 @@ class MergeTests(unittest.TestCase):
def test_a_custom_value_joins_its_pool(self) -> None:
self.assertIn(CUSTOM_COLOUR, pool_for(self.merged, "primary_color"))
self.assertIn(CUSTOM_SITUATION, pool_for(self.merged, "situation", "starship"))
self.assertIn(CUSTOM_SITUATION, pool_for(self.merged, "situation", SCOUT))
def test_the_built_in_pack_is_left_alone(self) -> None:
"""A pack is frozen and shared process-wide; a merge that appended in
place would leak one caller's additions into every other reader."""
self.assertNotIn(CUSTOM_COLOUR, pool_for(SCIFI_PACK, "primary_color"))
self.assertNotIn(CUSTOM_SITUATION, pool_for(SCIFI_PACK, "situation", "starship"))
self.assertNotIn(CUSTOM_SITUATION, pool_for(SCIFI_PACK, "situation", SCOUT))
def test_a_custom_value_becomes_a_widget_option(self) -> None:
"""Pools are not enough: a value a user cannot select is not an option."""
@@ -86,8 +89,8 @@ class MergeTests(unittest.TestCase):
self.assertEqual(document["entities"][0]["primary_color"], CUSTOM_COLOUR)
def test_a_custom_tag_is_read_by_the_content_filter(self) -> None:
peaceful = filtered_pool(self.merged, "situation", "starship", "Peaceful")
conflict = filtered_pool(self.merged, "situation", "starship", "Conflict")
peaceful = filtered_pool(self.merged, "situation", SCOUT, "Peaceful")
conflict = filtered_pool(self.merged, "situation", SCOUT, "Conflict")
self.assertIn(CUSTOM_SITUATION, peaceful)
self.assertNotIn(CUSTOM_SITUATION, conflict)
@@ -97,7 +100,7 @@ class MergeTests(unittest.TestCase):
with self.subTest(scene_filter=scene_filter):
self.assertIn(
CUSTOM_SITUATION,
filtered_pool(merged, "situation", "starship", scene_filter),
filtered_pool(merged, "situation", SCOUT, scene_filter),
)
def test_the_merge_is_idempotent(self) -> None:
@@ -173,7 +176,7 @@ class BadFileTests(unittest.TestCase):
merged = merge_user_options(SCIFI_PACK, document, sections=("fantasy", "horror"))
self.assertIn("hunter green", pool_for(merged, "primary_color"))
self.assertIn("running dark past a picket line",
merged.pools["situation"]["starship"])
pool_for(merged, "situation", SCOUT))
ALL_PACKS = (SCIFI_PACK, FANTASY_PACK, HORROR_PACK)
@@ -205,10 +208,10 @@ class KeyedByWhereItIsReadTests(unittest.TestCase):
def test_a_kind_keyed_value_still_works_where_the_kind_key_is_read(self) -> None:
merged = merge_user_options(
SCIFI_PACK, {"pools": {"situation": {"starship": [CUSTOM]}}}
FANTASY_PACK, {"pools": {"situation": {"folk": [CUSTOM]}}}
)
self.assertIn(CUSTOM, merged.pools["situation"]["starship"])
self.assertGreater(_drawn(merged, {"entity1_kind": "starship"}), 0)
self.assertIn(CUSTOM, merged.pools["situation"]["folk"])
self.assertGreater(_drawn(merged, {"entity1_kind": "folk", "entity1_subkind": "knight"}), 0)
def test_an_environment_keyed_by_its_band_is_drawable_in_every_pack(self) -> None:
for pack in ALL_PACKS:
+19
View File
@@ -149,6 +149,18 @@ class EveryCheckFiresTests(unittest.TestCase):
def test_an_untagged_value_in_a_tagged_pool_is_caught(self) -> None:
self.assertCode(_plus("armament", "improvised spar", "starship"), "TAG")
def test_a_variant_that_owns_nothing_is_caught(self) -> None:
self.assertCode(_plus("variant", "rust-eaten", "small drone"), "VARIANT")
def test_a_variant_echoing_the_head_noun_is_caught(self) -> None:
"""A segmented alien's head noun is its form, "squat dome-backed frame"."""
self.assertCode(_plus("variant", "dome-backed", "segmented"), "ECHO")
def test_a_pool_with_no_neutral_look_is_caught(self) -> None:
owned = tuple(SCIFI_PACK.value_variants["material"])
drone = tuple(v for v in SCIFI_PACK.pools["material"]["small drone"] if v in owned)
self.assertCode(_with_pools(material=("small drone", drone)), "NEUTRAL")
def test_a_rule_naming_a_fifth_slot_is_caught(self) -> None:
rule = ConstraintRule(
type="exclude",
@@ -210,6 +222,13 @@ class EveryCheckFiresTests(unittest.TestCase):
short = SCIFI_PACK.pools["situation"]["starship"][: MIN_SITUATIONS_PER_KIND - 1]
self.assertCode(_with_pools(situation=("starship", short)), "SITUATION")
def test_a_place_below_the_context_floor_is_caught(self) -> None:
place = G.pool_options(SCIFI_PACK, G.ENVIRONMENT_FIELD)[0]
spec = SCIFI_PACK.scene_fields[G.CONTEXT_FIELD]
pools = SCIFI_PACK.pools[G.CONTEXT_FIELD]
key = next(k for k in G.scope_keys(SCIFI_PACK, spec, {G.ENVIRONMENT_FIELD: place}) if k in pools)
self.assertCode(_with_pools(context=(key, pools[key][:1])), "CONTEXTFLOOR")
def test_an_unclassified_tiered_value_is_caught(self) -> None:
"""A value with no tier would silently draw at neutral weight."""
self.assertCode(
+200 -41
View File
@@ -258,7 +258,11 @@ SUBSTANCE_COLOUR_HOMES: dict[str, tuple[str, ...]] = {
#: in sci-fi and horror; fantasy's torch is a real one, so it is not listed.
TRAP_PHRASES = re.compile(
r"\b(fork of|heart in its|iris of|iris valve|rolling body|winding key|bone charms?|bottle|"
r"handheld torch|with a torch)\b"
r"handheld torch|with a torch|"
# An object aimed by someone off-frame, with no direction: "snapping at a hurled spear"
# drew the spear leaving the subject's mouth. Say it comes "at it" / "toward them".
r"(?:hurled|thrown|flung|raised|levelled) (?:spears?|daggers?|knives|knife|axes?|stones?|rocks?|"
r"torch(?:es)?|javelins?|lances?))\b"
)
@@ -777,40 +781,6 @@ def check_empty_defaults(pack: G.GenrePack, report: Report) -> None:
)
def _subjects(pack: G.GenrePack):
"""Every ``(kind, type)`` a scene can hold; ``(kind, None)`` for a kind with no types."""
name = G.type_field(pack)
for kind in pack.kinds:
values = G.pool_for(pack, name, {G.KIND_FIELD: kind}) if name else ()
for value in values or (None,):
yield kind, value
def _reach(
pack: G.GenrePack, field_name: str, honour_omits: bool = False
) -> "dict[str, list[tuple[str, str | None]]]":
"""``{value: [(kind, type), ...]}`` -- every subject whose resolved pool holds the value.
With ``honour_omits``, a subject whose archetype omits the field reaches
nothing there: it never draws the field, so a part it would fall through to
cannot misfit its body. A wreck's archetype omits ``emitters``, and the
default emitter pool is not its vocabulary. The shadowed-value check keeps
the plain reach, because an omitted pool is still authored vocabulary."""
name = G.type_field(pack)
reach: dict[str, list[tuple[str, str | None]]] = {}
for kind, value in _subjects(pack):
scope = {G.KIND_FIELD: kind}
if name and value is not None:
scope[name] = value
if honour_omits:
archetype = G.archetype_for(pack, scope)
if archetype is not None and field_name in archetype.omits:
continue
for option in G.pool_for(pack, field_name, scope):
reach.setdefault(option, []).append((kind, value))
return reach
def _named(words_by_key, text: str) -> set[str]:
low = text.lower()
return {
@@ -837,7 +807,7 @@ def check_body_keywords(pack: G.GenrePack, report: Report) -> None:
if not pack.body_keywords:
return
for field_name in pack.body_lint_fields:
for option, subjects in sorted(_reach(pack, field_name, honour_omits=True).items()):
for option, subjects in sorted(G.value_reach(pack, field_name, honour_omits=True).items()):
named = _named(pack.body_keywords, option)
if not named:
continue
@@ -858,7 +828,7 @@ def check_body_coverage(pack: G.GenrePack, report: Report) -> None:
"""27. Every subject resolves to a declared body, even an empty one."""
if not pack.body_keywords:
return
for kind, value in _subjects(pack):
for kind, value in G.subjects(pack):
if not G.has_body_declaration(pack, kind, value):
report.fail("BODYCOVER", f"{value or kind!r} ({kind}) declares no body at any level")
@@ -868,7 +838,7 @@ def check_part_keywords(pack: G.GenrePack, report: Report) -> None:
if not pack.part_keywords:
return
for field_name in pack.part_lint_fields:
for option, subjects in sorted(_reach(pack, field_name, honour_omits=True).items()):
for option, subjects in sorted(G.value_reach(pack, field_name, honour_omits=True).items()):
named = _named(pack.part_keywords, option)
if not named:
continue
@@ -951,7 +921,7 @@ def check_shadowed_values(pack: G.GenrePack, report: Report) -> None:
if G.SITUATION_FIELD not in fields:
fields.append(G.SITUATION_FIELD)
for field_name in fields:
reach = _reach(pack, field_name)
reach = G.value_reach(pack, field_name)
for value in G.pool_options(pack, field_name):
if value in reach:
continue
@@ -989,7 +959,7 @@ def check_stranger_fallthrough(pack: G.GenrePack, report: Report) -> None:
continue
fallen: list[str] = []
subjects = 0
for kind, value in _subjects(pack):
for kind, value in G.subjects(pack):
scope = {G.KIND_FIELD: kind}
if type_name and value is not None:
scope[type_name] = value
@@ -1030,7 +1000,7 @@ def check_carried_body_parts(pack: G.GenrePack, report: Report) -> None:
"""
type_name = G.type_field(pack)
seen: set[tuple[str, str]] = set()
for kind, value in _subjects(pack):
for kind, value in G.subjects(pack):
scope = {G.KIND_FIELD: kind}
if type_name and value is not None:
scope[type_name] = value
@@ -1095,6 +1065,192 @@ def check_tier_coverage(pack: G.GenrePack, report: Report) -> None:
)
def _words(value: str) -> set[str]:
"""Content words, hyphenated parts counted apart -- the engine's echo guard's split."""
return set(value.replace("-", " ").split()) - {"a", "an", "the", "of", "and", "in", "on", "with"}
def _variant_subjects(pack: G.GenrePack):
"""``(kind, type, scope, offered variants)`` for every subject offered a variant."""
if G.VARIANT_FIELD not in pack.entity_fields:
return
for kind, value in G.subjects(pack):
scope = G.subject_scope(pack, kind, value)
offered = G.pool_for(pack, G.VARIANT_FIELD, scope)
if offered:
yield kind, value, scope, offered
def check_variants(pack: G.GenrePack, report: Report) -> None:
"""34. A variant owns a look its subject can draw, and never echoes the head noun.
A variant that owns nothing in its subject's pools is a bare word with no look
behind it. One that shares a word with the head noun ("jewel-backed" on a
"dome-backed frame") is silenced by the engine's echo guard after its owned
look was drawn, so the look is spoken without the word that explains it. And a
masked field whose every value is owned leaves a variant-less draw nothing
neutral, so it falls back to some variant's look."""
from engine.prose import head_phrase_spec
from engine.scene import _normalized_head, _share_vocabulary
heads_in_order = [
n for n, s in pack.entity_fields.items() if n != G.KIND_FIELD and s.renders_with is None
]
for kind, value, scope, offered in _variant_subjects(pack):
who = value or kind
pools = {field_name: G.pool_for(pack, field_name, scope) for field_name in pack.value_variants}
# The head-noun repeat guard re-draws a later field whose head word an
# earlier field already said, so an owned look ending in "hull" beside a
# "...hull" form is silenced as often as the form is drawn.
for field_name, pool in pools.items():
earlier = heads_in_order[: heads_in_order.index(field_name)]
taken = {
_normalized_head(v): other
for other in earlier if not _share_vocabulary(pack, field_name, other)
for v in G.pool_for(pack, other, scope)
}
for owned in pool:
if pack.value_variants[field_name].get(owned, frozenset()) & set(offered):
other = taken.get(_normalized_head(owned))
if other:
report.fail(
"REPEAT",
f"{who!r}: owned {field_name} {owned!r} ends on a word its {other} can say",
)
for variant in offered:
if not any(
variant in pack.value_variants[f].get(v, frozenset())
for f, pool in pools.items() for v in pool
):
report.fail("VARIANT", f"{who!r}: variant {variant!r} owns no look this subject can draw")
for field_name, pool in pools.items():
owners = pack.value_variants[field_name]
claimed = [v for v in pool if owners.get(v, frozenset()) & set(offered)]
if claimed and len(claimed) == len(pool):
report.fail(
"NEUTRAL", f"{who!r}: every {field_name} is owned by a variant, so none is neutral"
)
values = {G.KIND_FIELD: kind, **({G.type_field(pack): value} if value else {})}
head = head_phrase_spec(pack, kind, G.archetype_for(pack, values))
if head is None:
continue
noun = next((n for n in ((head.subject,) if head.subject else ()) + tuple(head.noun)
if n == G.KIND_FIELD or G.pool_for(pack, n, scope) or (n == G.type_field(pack) and value)),
None)
if noun == G.KIND_FIELD:
heads = [kind]
elif noun == G.type_field(pack):
heads = [value] if value else []
else:
heads = list(G.pool_for(pack, noun, scope)) if noun else []
for variant in offered:
for spoken in heads:
shared = _words(variant) & _words(spoken)
if shared:
report.fail(
"ECHO",
f"{who!r}: variant {variant!r} shares {sorted(shared)} with head noun {spoken!r}",
)
#: Report-only until the content rounds meet them; each then becomes a failure.
FORM_FLOOR = 4
VARIANT_FLOOR = 3
ACT_FLOOR = 6
CONTEXT_FLOOR = 4
STAGE_FLOOR = 4
ASPECT_FLOOR_OUTDOOR = 6
ASPECT_FLOOR_INDOOR = 4
def check_type_echo(pack: G.GenrePack, report: Report) -> None:
"""36. No look is dead because it ends on its own type's noun.
The head-noun repeat guard re-draws a field whose head word the type already
said, so "bow-topped wagon" on a "painted travelling wagon" is never spoken. A
value whose every holder is such a type is authored and unreachable; the reach
audit finds it only after a long sweep, this finds it at once."""
from engine.scene import _normalized_head, _share_vocabulary
name = G.type_field(pack)
if name is None:
return
fields = [
n for n, s in pack.entity_fields.items()
if n not in (G.KIND_FIELD, name) and s.renders_with is None and not _share_vocabulary(pack, n, name)
]
live: dict[tuple[str, str], bool] = {}
for kind, value in G.subjects(pack):
scope = G.subject_scope(pack, kind, value)
own = _normalized_head(value) if value else None
for field_name in fields:
for option in G.pool_for(pack, field_name, scope) or ():
key = (field_name, option)
live[key] = live.get(key, False) or _normalized_head(option) != own
for (field_name, option), alive in sorted(live.items()):
if not alive:
report.fail("TYPEECHO", f"{field_name}: {option!r} ends on its every holder's own noun")
def check_variety_floors(pack: G.GenrePack, report: Report) -> None:
"""35. The variety floors (0.8.0): every offender is a failure, by name."""
def note(code: str, short: "list[str]") -> None:
for name in short:
report.fail(code, f"{name!r} is below the floor")
forms, variants = [], []
for kind, value in G.subjects(pack):
scope = G.subject_scope(pack, kind, value)
pool = G.pool_for(pack, "form", scope)
if pool and len(pool) < FORM_FLOOR:
forms.append(value or kind)
archetype = G.archetype_for(pack, scope)
if G.VARIANT_FIELD in pack.entity_fields and not (
archetype and G.VARIANT_FIELD in archetype.omits
):
offered = G.pool_for(pack, G.VARIANT_FIELD, scope)
if len(offered) < VARIANT_FLOOR:
variants.append(value or kind)
note("FORMFLOOR", forms)
note("VARIANTFLOOR", variants)
own: dict[str, int] = {}
group_of = {
member: group
for group, members in (pack.pool_groups.get(G.type_field(pack)) or {}).items()
for member in members
}
size: dict[str, int] = {}
for kind, value in G.subjects(pack):
key = group_of.get(value, value) if value else kind
size[key] = size.get(key, 0) + 1
for owners in G.own_values(pack, G.SITUATION_FIELD).values():
for key in owners:
own[key] = own.get(key, 0) + 1
groups = set(size)
note("ACTSPEC", sorted(g for g in groups if own.get(g, 0) < ACT_FLOOR))
traits = pack.value_traits.get(G.ENVIRONMENT_FIELD, {})
contexts, stagings, aspects = [], [], []
for place in G.pool_options(pack, G.ENVIRONMENT_FIELD):
scope = {G.ENVIRONMENT_FIELD: place}
if len(G.filtered_pool(pack, G.CONTEXT_FIELD, scope, "Any")) < CONTEXT_FLOOR:
contexts.append(place)
if "staging" in pack.scene_fields and len(G.filtered_pool(pack, "staging", scope, "Any")) < STAGE_FLOOR:
stagings.append(place)
if "aspect" in pack.scene_fields:
floor = ASPECT_FLOOR_INDOOR if "interior-place" in traits.get(place, ()) else ASPECT_FLOOR_OUTDOOR
if len(G.filtered_pool(pack, "aspect", scope, "Any")) < floor:
aspects.append(place)
note("CONTEXTFLOOR", contexts)
note("STAGEFLOOR", stagings)
note("ASPECTFLOOR", aspects)
note("VIEWER", [v for v in G.pool_options(pack, G.SITUATION_FIELD) if "viewer" in v])
# A framing gated on a trait no context carries is never drawn.
carried = set().union(*map(set, pack.value_traits.get(G.CONTEXT_FIELD, {}).values()))
note("FRAMING", [s.text for s in pack.prose.context_sentences if not s.traits <= carried])
CHECKS = (
check_tags,
check_constraints,
@@ -1126,6 +1282,9 @@ CHECKS = (
check_shadowed_values,
check_stranger_fallthrough,
check_carried_body_parts,
check_variants,
check_type_echo,
check_variety_floors,
)