diff --git a/AGENTS.md b/AGENTS.md index 5679c8c68..b29d1484c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,8 @@ dimension-intent and oriented-slot geometry validation (ADR 1) → **1** `linting/`, `reporting` and peers → **3** `analysis` → **4** `annotations/` (the render passes; `orchestrator._PASS_SEQUENCE` is the one stage order) → **5** `drawing` and `intent_drain` (the deferred stages, with transaction state owned by `Drawing`) → **6** -`builder` and guarded layout selection → **7** facades (`sheet`, `document`, `sheet_emit`, +`builder` and guarded layout selection → **7** facades (`sheet` and its private +identity/layout-control owners, `document`, `sheet_emit`, `sheet_object_source`, `inspection`, `evaluation/`, `cli`, the recogniser/inspection contract joins). `make_drawing` / `annotate` diff --git a/docs/architecture.md b/docs/architecture.md index ad0a5f2f4..90747c735 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -404,6 +404,10 @@ observer registry and re-exports its existing private helper names. `model/declare.py` and calls `build_drawing(model=…)`. Née `sheet_dsl.py` (renamed #640 — it's a fluent facade, not a DSL, per ADR 4 (was 0001); the `sheet_dsl` alias shim was deleted at 0.4.0, #720). +- **`sheet_features.py`** — the facade's private token-preserving feature-list view; + `sheet.py` re-exports `_FeatureView` for existing private imports and pickles. +- **`sheet_layout_controls.py`** — declaration ID lookup and bounded side/lane layout + control policy behind `Sheet`'s stable query, validation and override methods. - **`sheet_object_source.py`** — live-object import seams and mutual one-to-one geometry correspondence for script generation. This facade-rank owner keeps the existing private `sheet_emit` import paths available to callers. diff --git a/src/draftwright/sheet.py b/src/draftwright/sheet.py index 9389aca40..f50b5cef2 100644 --- a/src/draftwright/sheet.py +++ b/src/draftwright/sheet.py @@ -53,7 +53,7 @@ import inspect import math import warnings -from collections.abc import Callable, MutableSequence, Sequence +from collections.abc import MutableSequence from dataclasses import replace from typing import TYPE_CHECKING, Literal, cast @@ -120,8 +120,8 @@ ) from draftwright.model.declare import read_bore_step as _read_bore_step from draftwright.model.declare import read_countersink as _read_countersink +from draftwright.model.ir import PLACEMENT_SIDES as PLACEMENT_SIDES from draftwright.model.ir import ( - PLACEMENT_SIDES, ControlFrame, DatumRef, DeclarationIdentity, @@ -142,6 +142,19 @@ validate_dimension_placement, ) from draftwright.model.planner import location_role as _location_role +from draftwright.sheet_features import _FeatureView +from draftwright.sheet_layout_controls import ( + _declaration_token as _layout_declaration_token, +) +from draftwright.sheet_layout_controls import ( + _dimension_entry_for_layout as _layout_dimension_entry_for_layout, +) +from draftwright.sheet_layout_controls import _identify as _layout_identify +from draftwright.sheet_layout_controls import layout_options as _layout_options +from draftwright.sheet_layout_controls import layout_override as _layout_apply_layout_override +from draftwright.sheet_layout_controls import ( + validate_layout_override as _layout_validate_layout_override, +) from draftwright.view_plan import ( PRINCIPAL_VIEW_NAMES, ConstraintSource, @@ -261,139 +274,6 @@ def _requirement_parameter(feature, target: str): return parameter -class _FeatureView(MutableSequence): - """The public ``Sheet.features`` list — a view over ``(token, feature)`` entries. - - Handles address their feature by **token**, not position (#908), and this view is - what keeps the two in step. Every mutation moves entries, so the token travels with - the feature it names: - - - ``append`` mints a new token — a declaration; - - ``features[i] = f`` mints a **new** token: assignment cannot express "move this - feature here", so inheriting the slot's identity would silently hand every - reference to whatever was assigned. Stale references fail loudly instead. The - identity-preserving rebuild a size verb needs is :meth:`_rebind`; - - ``reverse`` / ``sort`` / ``insert`` reorder entries, so a handle simply finds its - feature at the new position rather than silently naming a neighbour; - - ``del`` drops the token, so a handle for a removed feature raises when used. - - Before this, everything addressed by index into a plain list, and #872 found ways - for a long-lived reference — a tolerance, a GD&T origin, a - section, a dimension intent — to end up pointing at the wrong feature. Each fix - detected one route and opened another. Carrying identity makes the class impossible - instead of detectable. - """ - - __slots__ = ("_entries", "_next_token", "validate_change") - - def __init__(self, entries: list) -> None: - self._entries = entries - # A plain int, not `itertools.count`: counters lose pickle/copy support in - # Python 3.14 and this package supports >=3.11, so a Sheet carrying one would - # stop being copyable. Per-sheet rather than global because tokens appear in - # internal keys and this project holds output to be deterministic — a - # process-wide counter would make those keys depend on how many other sheets - # happened to be built first. - self._next_token = 0 - self.validate_change: Callable[[Sequence], None] | None = None - - def _validate(self, values): - if self.validate_change is not None: - self.validate_change(values) - - def _mint(self) -> int: - token = self._next_token - self._next_token += 1 - return token - - def __getitem__(self, i): - if isinstance(i, slice): - return [e[1] for e in self._entries[i]] - return self._entries[i][1] - - def __setitem__(self, i, value) -> None: - # Public assignment always mints a NEW token, scalar or slice. - # - # This is the distinction an earlier draft got wrong. Keeping the destination - # slot's token is right for the INTERNAL rebuild a size verb does — `.depth()` - # replaces the frozen dataclass with an updated copy of the same feature — but on - # the public view, assignment cannot tell "move this feature here" from "put a - # different feature here". Preserving identity across it silently transferred - # every reference (handles, tolerances, GD&T origins, sections, intents) onto - # whatever was assigned, which is the exact bug this class exists to remove: - # - # features[0], features[1] = features[1], features[0] # a tuple swap - # features[:] = features[::-1] # a slice reversal - # - # both of which move VALUES between slots. Minting fresh tokens makes those - # references fail loudly instead. To reorder while keeping identity, use - # `reverse()` / `sort()`, which move whole entries. Internal rebuilding goes - # through `_rebind`, which is the only path that preserves a token. - current = list(self) - if isinstance(i, slice): - value = list(value) - current[i] = value - self._validate(current) - if isinstance(i, slice): - self._entries[i] = [(self._mint(), f) for f in value] - return - self._entries[i] = (self._mint(), value) - - def _rebind(self, index: int, feature) -> None: - """Replace the feature at *index* KEEPING its token — the same feature, rebuilt. - - The only identity-preserving write. Used by the size verbs, whose frozen - dataclasses are replaced wholesale on every `.depth()` / `.cbore()` / `.thread()`. - """ - current = list(self) - current[index] = feature - self._validate(current) - self._entries[index] = (self._entries[index][0], feature) - - def __delitem__(self, i) -> None: - current = list(self) - del current[i] - self._validate(current) - del self._entries[i] - - def clear(self) -> None: - self._validate([]) - self._entries.clear() - - def __len__(self) -> int: - return len(self._entries) - - def insert(self, i, value) -> None: - current = list(self) - current.insert(i, value) - self._validate(current) - self._entries.insert(i, (self._mint(), value)) - - def extend(self, values) -> None: - values = list(values) - self._validate([*self, *values]) - self._entries.extend((self._mint(), value) for value in values) - - # Reordering must move ENTRIES, not values. `MutableSequence` implements `reverse` - # in terms of `__setitem__`, which here keeps each slot's token — right for a size - # verb replacing a feature in place, wrong for a reorder, where it would swap the - # features and leave every token pointing at its old position. Overriding both is - # what makes a reorder transparent to handles rather than silently retargeting them. - def reverse(self) -> None: - self._entries.reverse() - - def sort(self, *, key=None, reverse: bool = False) -> None: - self._entries.sort( - key=(lambda e: e[1]) if key is None else (lambda e: key(e[1])), reverse=reverse - ) - - def __repr__(self) -> str: - return repr([e[1] for e in self._entries]) - - def __eq__(self, other) -> bool: - return [e[1] for e in self._entries] == list(other) - - class _Nameable: """`dimension_ids()` for a declared-feature handle — the measurements it can be asked for. @@ -1817,16 +1697,7 @@ def of(self, ref) -> _Hole | _Dim: def _identify(self, token: int, identity: DeclarationIdentity) -> None: """Bind one validated identity to a live declaration token.""" - self._index_of_token(token) - live_tokens = {live_token for live_token, _feature in self._entries} - for other_token, existing in self._declaration_identities.items(): - if ( - other_token != token - and existing.declaration_id == identity.declaration_id - and other_token in live_tokens - ): - raise ValueError(f"duplicate declaration_id {identity.declaration_id!r}") - self._declaration_identities[token] = identity + _layout_identify(self, token, identity) def by_declaration(self, declaration_id: str) -> _Params: """Return the live handle carrying *declaration_id*, or fail if it was withdrawn.""" @@ -1836,38 +1707,14 @@ def by_declaration(self, declaration_id: str) -> _Params: def _declaration_token(self, declaration_id: str) -> int: """Resolve one build-scoped declaration ID to its live token.""" - live_tokens = {token for token, _feature in self._entries} - matches = [ - token - for token, identity in self._declaration_identities.items() - if identity.declaration_id == declaration_id and token in live_tokens - ] - if len(matches) != 1: - raise ValueError( - f"by_declaration({declaration_id!r}) requires one live declaration; " - f"found {len(matches)}" - ) - return matches[0] + return _layout_declaration_token(self, declaration_id) def _dimension_entry_for_layout( self, token: int, parameter_id: str ) -> tuple[dict, str] | None: """Return the one declared dimension entry addressed by a lane override.""" - for entries in (self._authored, self._added_dimensions): - matches = [ - entry - for entry in entries - if entry["token"] == token and entry["role"] == parameter_id - ] - if len(matches) > 1: - raise ValueError( - f"dimension {parameter_id!r} is declared more than once; " - "remove the conflicting intent before overriding its lane" - ) - if matches: - return matches[0], parameter_id - return None + return _layout_dimension_entry_for_layout(self, token, parameter_id) def layout_options( self, declaration_id: str, *, parameter: DimensionParameterId | None = None @@ -1878,68 +1725,7 @@ def layout_options( solve still decides whether the requested corridor can be used on the final sheet. """ - token = self._declaration_token(declaration_id) - feature = self._features[self._index_of_token(token)] - if parameter is not None: - handle = _Params(self, self._index_of_token(token)) - _resolved_token, target, discriminator, canonical = self._resolve_measurement( - handle, parameter, None, "layout_options" - ) - parameter_id = next( - ( - item.parameter_id - for item in target.parameters() - if canonical in (item.role, item.parameter_id) - and item.discriminator == discriminator - ), - canonical, - ) - entry = self._dimension_entry_for_layout(token, parameter_id) - if entry is None: - raise ValueError( - f"declaration {declaration_id!r} has no declared dimension " - f"{parameter_id!r} to override" - ) - if not dimension_lane_supported(feature, parameter_id): - raise ValueError( - f"dimension {parameter_id!r} on {feature.kind} does not expose a lane control" - ) - return { - "schema": "draftwright.layout-options", - "schema_version": 1, - "scope": "single-dimension-layout-controls", - "requires_build_validation": True, - "declaration_id": declaration_id, - "feature_kind": feature.kind, - "parameter_id": parameter_id, - "controls": { - "lane": { - "current": entry[0].get("lane"), - "minimum": 1, - "maximum": 8, - "meaning": "one-based drafting-spaced lane from the feature witness", - } - }, - } - side = getattr(feature, "side", None) - if side not in PLACEMENT_SIDES: - raise ValueError( - f"declaration {declaration_id!r} does not expose a supported side control" - ) - return { - "schema": "draftwright.layout-options", - "schema_version": 1, - "scope": "single-declaration-layout-controls", - "requires_build_validation": True, - "declaration_id": declaration_id, - "feature_kind": feature.kind, - "controls": { - "side": { - "current": side, - "supported_values": sorted(PLACEMENT_SIDES), - } - }, - } + return _layout_options(self, declaration_id, parameter=parameter, handle_factory=_Params) def validate_layout_override( self, @@ -1956,101 +1742,9 @@ def validate_layout_override( requires :meth:`build` to establish geometric feasibility on the composed sheet. """ - result: dict[str, object] = { - "schema": "draftwright.layout-validation", - "schema_version": 1, - "scope": "single-declaration-layout-controls", - "requires_build_validation": True, - "declaration_id": declaration_id, - "supported": False, - "issues": [], - "options": None, - } - try: - token = self._declaration_token(declaration_id) - except ValueError as error: - result["issues"] = [ - { - "code": "invalid_declaration", - "message": str(error), - } - ] - return result - if unsupported_controls: - result["issues"] = [ - { - "code": "unsupported_control", - "controls": sorted(unsupported_controls), - "message": "layout_override accepts only side, or parameter with lane", - } - ] - return result - if (side is None) == (lane is None): - result["issues"] = [ - { - "code": "invalid_control_combination", - "message": "specify exactly one of side or lane", - } - ] - return result - if lane is not None and parameter is None: - result["issues"] = [ - { - "code": "invalid_control_combination", - "message": "lane requires an exact parameter selector", - } - ] - return result - if side is not None and parameter is not None: - result["issues"] = [ - { - "code": "invalid_control_combination", - "message": "parameter selects a dimension lane and cannot accompany side", - } - ] - return result - feature = self._features[self._index_of_token(token)] - try: - options = self.layout_options(declaration_id, parameter=parameter) - except (TypeError, ValueError, IndexError) as error: - result["issues"] = [ - { - "code": "unsupported_declaration", - "feature_kind": feature.kind, - "message": str(error), - } - ] - return result - result["options"] = options - if side is not None: - supported = options["controls"]["side"]["supported_values"] # type: ignore[index] - if side not in supported: - result["issues"] = [ - { - "code": "unsupported_value", - "control": "side", - "value": side, - "supported_values": supported, - "message": f"side must be a supported side: {supported} (got {side!r})", - } - ] - return result - else: - assert parameter is not None - if isinstance(lane, bool) or not isinstance(lane, int) or not 1 <= lane <= 8: - result["issues"] = [ - { - "code": "unsupported_value", - "control": "lane", - "value": lane, - "minimum": 1, - "maximum": 8, - "message": f"lane must be an integer from 1 to 8 (got {lane!r})", - } - ] - return result - result["supported"] = True - return result + return _layout_validate_layout_override( + self, declaration_id, side=side, parameter=parameter, lane=lane, **unsupported_controls + ) def layout_override( self, @@ -2067,30 +1761,9 @@ def layout_override( coordinates; the shared placement solve resolves and validates the physical offset. """ - key = (declaration_id, parameter) - if any((row.declaration_id, row.parameter_id) == key for row in self._layout_overrides): - raise ValueError(f"layout target {key!r} already has a layout override") - validation = self.validate_layout_override( - declaration_id, side=side, parameter=parameter, lane=lane + return _layout_apply_layout_override( + self, declaration_id, side=side, parameter=parameter, lane=lane ) - if not validation["supported"]: - issues = cast(list[dict[str, object]], validation["issues"]) - raise ValueError(str(issues[0]["message"])) - token = self._declaration_token(declaration_id) - if side is not None: - index = self._index_of_token(token) - self._replace_feature(index, replace(self._features[index], side=side)) - self._layout_overrides.append(LayoutOverride(declaration_id, side)) - else: - options = cast(dict[str, object], validation["options"]) - parameter_id = cast(str, options["parameter_id"]) - entry = self._dimension_entry_for_layout(token, parameter_id) - assert entry is not None and lane is not None - entry[0]["lane"] = lane - self._layout_overrides.append( - LayoutOverride(declaration_id, parameter_id=parameter_id, lane=lane) - ) - return self def _declared_token(self, ref, *, verb: str) -> int | None: """The token of the declared feature *ref* names, or ``None`` if it names none. diff --git a/src/draftwright/sheet_features.py b/src/draftwright/sheet_features.py new file mode 100644 index 000000000..dcd300015 --- /dev/null +++ b/src/draftwright/sheet_features.py @@ -0,0 +1,138 @@ +"""Token-preserving mutable feature list for the declarative Sheet facade.""" + +from __future__ import annotations + +from collections.abc import Callable, MutableSequence, Sequence + + +class _FeatureView(MutableSequence): + """The public ``Sheet.features`` list — a view over ``(token, feature)`` entries. + + Handles address their feature by **token**, not position (#908), and this view is + what keeps the two in step. Every mutation moves entries, so the token travels with + the feature it names: + + - ``append`` mints a new token — a declaration; + - ``features[i] = f`` mints a **new** token: assignment cannot express "move this + feature here", so inheriting the slot's identity would silently hand every + reference to whatever was assigned. Stale references fail loudly instead. The + identity-preserving rebuild a size verb needs is :meth:`_rebind`; + - ``reverse`` / ``sort`` / ``insert`` reorder entries, so a handle simply finds its + feature at the new position rather than silently naming a neighbour; + - ``del`` drops the token, so a handle for a removed feature raises when used. + + Before this, everything addressed by index into a plain list, and #872 found ways + for a long-lived reference — a tolerance, a GD&T origin, a + section, a dimension intent — to end up pointing at the wrong feature. Each fix + detected one route and opened another. Carrying identity makes the class impossible + instead of detectable. + """ + + __slots__ = ("_entries", "_next_token", "validate_change") + + def __init__(self, entries: list) -> None: + self._entries = entries + # A plain int, not `itertools.count`: counters lose pickle/copy support in + # Python 3.14 and this package supports >=3.11, so a Sheet carrying one would + # stop being copyable. Per-sheet rather than global because tokens appear in + # internal keys and this project holds output to be deterministic — a + # process-wide counter would make those keys depend on how many other sheets + # happened to be built first. + self._next_token = 0 + self.validate_change: Callable[[Sequence], None] | None = None + + def _validate(self, values): + if self.validate_change is not None: + self.validate_change(values) + + def _mint(self) -> int: + token = self._next_token + self._next_token += 1 + return token + + def __getitem__(self, i): + if isinstance(i, slice): + return [e[1] for e in self._entries[i]] + return self._entries[i][1] + + def __setitem__(self, i, value) -> None: + # Public assignment always mints a NEW token, scalar or slice. + # + # This is the distinction an earlier draft got wrong. Keeping the destination + # slot's token is right for the INTERNAL rebuild a size verb does — `.depth()` + # replaces the frozen dataclass with an updated copy of the same feature — but on + # the public view, assignment cannot tell "move this feature here" from "put a + # different feature here". Preserving identity across it silently transferred + # every reference (handles, tolerances, GD&T origins, sections, intents) onto + # whatever was assigned, which is the exact bug this class exists to remove: + # + # features[0], features[1] = features[1], features[0] # a tuple swap + # features[:] = features[::-1] # a slice reversal + # + # both of which move VALUES between slots. Minting fresh tokens makes those + # references fail loudly instead. To reorder while keeping identity, use + # `reverse()` / `sort()`, which move whole entries. Internal rebuilding goes + # through `_rebind`, which is the only path that preserves a token. + current = list(self) + if isinstance(i, slice): + value = list(value) + current[i] = value + self._validate(current) + if isinstance(i, slice): + self._entries[i] = [(self._mint(), f) for f in value] + return + self._entries[i] = (self._mint(), value) + + def _rebind(self, index: int, feature) -> None: + """Replace the feature at *index* KEEPING its token — the same feature, rebuilt. + + The only identity-preserving write. Used by the size verbs, whose frozen + dataclasses are replaced wholesale on every `.depth()` / `.cbore()` / `.thread()`. + """ + current = list(self) + current[index] = feature + self._validate(current) + self._entries[index] = (self._entries[index][0], feature) + + def __delitem__(self, i) -> None: + current = list(self) + del current[i] + self._validate(current) + del self._entries[i] + + def clear(self) -> None: + self._validate([]) + self._entries.clear() + + def __len__(self) -> int: + return len(self._entries) + + def insert(self, i, value) -> None: + current = list(self) + current.insert(i, value) + self._validate(current) + self._entries.insert(i, (self._mint(), value)) + + def extend(self, values) -> None: + values = list(values) + self._validate([*self, *values]) + self._entries.extend((self._mint(), value) for value in values) + + # Reordering must move ENTRIES, not values. `MutableSequence` implements `reverse` + # in terms of `__setitem__`, which here keeps each slot's token — right for a size + # verb replacing a feature in place, wrong for a reorder, where it would swap the + # features and leave every token pointing at its old position. Overriding both is + # what makes a reorder transparent to handles rather than silently retargeting them. + def reverse(self) -> None: + self._entries.reverse() + + def sort(self, *, key=None, reverse: bool = False) -> None: + self._entries.sort( + key=(lambda e: e[1]) if key is None else (lambda e: key(e[1])), reverse=reverse + ) + + def __repr__(self) -> str: + return repr([e[1] for e in self._entries]) + + def __eq__(self, other) -> bool: + return [e[1] for e in self._entries] == list(other) diff --git a/src/draftwright/sheet_layout_controls.py b/src/draftwright/sheet_layout_controls.py new file mode 100644 index 000000000..cab1d3539 --- /dev/null +++ b/src/draftwright/sheet_layout_controls.py @@ -0,0 +1,299 @@ +"""Declaration-scoped layout controls for the Sheet facade (ADR 4).""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import replace +from typing import TYPE_CHECKING, cast + +from draftwright.model.ir import ( + PLACEMENT_SIDES, + DeclarationIdentity, + DimensionParameterId, + LayoutOverride, +) +from draftwright.model.planner import dimension_lane_supported + +if TYPE_CHECKING: + from draftwright.sheet import Sheet + + +def _identify(sheet: Sheet, token: int, identity: DeclarationIdentity) -> None: + """Bind one validated identity to a live declaration token.""" + + sheet._index_of_token(token) + live_tokens = {live_token for live_token, _feature in sheet._entries} + for other_token, existing in sheet._declaration_identities.items(): + if ( + other_token != token + and existing.declaration_id == identity.declaration_id + and other_token in live_tokens + ): + raise ValueError(f"duplicate declaration_id {identity.declaration_id!r}") + sheet._declaration_identities[token] = identity + + +def _declaration_token(sheet: Sheet, declaration_id: str) -> int: + """Resolve one build-scoped declaration ID to its live token.""" + + live_tokens = {token for token, _feature in sheet._entries} + matches = [ + token + for token, identity in sheet._declaration_identities.items() + if identity.declaration_id == declaration_id and token in live_tokens + ] + if len(matches) != 1: + raise ValueError( + f"by_declaration({declaration_id!r}) requires one live declaration; " + f"found {len(matches)}" + ) + return matches[0] + + +def _dimension_entry_for_layout( + sheet: Sheet, token: int, parameter_id: str +) -> tuple[dict, str] | None: + """Return the one declared dimension entry addressed by a lane override.""" + + for entries in (sheet._authored, sheet._added_dimensions): + matches = [ + entry for entry in entries if entry["token"] == token and entry["role"] == parameter_id + ] + if len(matches) > 1: + raise ValueError( + f"dimension {parameter_id!r} is declared more than once; " + "remove the conflicting intent before overriding its lane" + ) + if matches: + return matches[0], parameter_id + return None + + +def layout_options( + sheet: Sheet, + declaration_id: str, + *, + parameter: DimensionParameterId | None = None, + handle_factory: Callable[[Sheet, int], object], +) -> dict[str, object]: + """Describe the bounded layout-only controls supported by one declaration. + + This is a pre-build capability query, not a feasibility promise: the shared layout + solve still decides whether the requested corridor can be used on the final sheet. + """ + + token = sheet._declaration_token(declaration_id) + feature = sheet._features[sheet._index_of_token(token)] + if parameter is not None: + handle = handle_factory(sheet, sheet._index_of_token(token)) + _resolved_token, target, discriminator, canonical = sheet._resolve_measurement( + handle, parameter, None, "layout_options" + ) + parameter_id = next( + ( + item.parameter_id + for item in target.parameters() + if canonical in (item.role, item.parameter_id) + and item.discriminator == discriminator + ), + canonical, + ) + entry = sheet._dimension_entry_for_layout(token, parameter_id) + if entry is None: + raise ValueError( + f"declaration {declaration_id!r} has no declared dimension " + f"{parameter_id!r} to override" + ) + if not dimension_lane_supported(feature, parameter_id): + raise ValueError( + f"dimension {parameter_id!r} on {feature.kind} does not expose a lane control" + ) + return { + "schema": "draftwright.layout-options", + "schema_version": 1, + "scope": "single-dimension-layout-controls", + "requires_build_validation": True, + "declaration_id": declaration_id, + "feature_kind": feature.kind, + "parameter_id": parameter_id, + "controls": { + "lane": { + "current": entry[0].get("lane"), + "minimum": 1, + "maximum": 8, + "meaning": "one-based drafting-spaced lane from the feature witness", + } + }, + } + side = getattr(feature, "side", None) + if side not in PLACEMENT_SIDES: + raise ValueError( + f"declaration {declaration_id!r} does not expose a supported side control" + ) + return { + "schema": "draftwright.layout-options", + "schema_version": 1, + "scope": "single-declaration-layout-controls", + "requires_build_validation": True, + "declaration_id": declaration_id, + "feature_kind": feature.kind, + "controls": { + "side": { + "current": side, + "supported_values": sorted(PLACEMENT_SIDES), + } + }, + } + + +def validate_layout_override( + sheet: Sheet, + declaration_id: str, + *, + side: str | None = None, + parameter: DimensionParameterId | None = None, + lane: int | None = None, + **unsupported_controls, +) -> dict[str, object]: + """Preflight a layout override without mutating the sheet. + + A supported result means the declaration and bounded vocabulary are valid. It still + requires :meth:`build` to establish geometric feasibility on the composed sheet. + """ + + result: dict[str, object] = { + "schema": "draftwright.layout-validation", + "schema_version": 1, + "scope": "single-declaration-layout-controls", + "requires_build_validation": True, + "declaration_id": declaration_id, + "supported": False, + "issues": [], + "options": None, + } + try: + token = sheet._declaration_token(declaration_id) + except ValueError as error: + result["issues"] = [ + { + "code": "invalid_declaration", + "message": str(error), + } + ] + return result + if unsupported_controls: + result["issues"] = [ + { + "code": "unsupported_control", + "controls": sorted(unsupported_controls), + "message": "layout_override accepts only side, or parameter with lane", + } + ] + return result + if (side is None) == (lane is None): + result["issues"] = [ + { + "code": "invalid_control_combination", + "message": "specify exactly one of side or lane", + } + ] + return result + if lane is not None and parameter is None: + result["issues"] = [ + { + "code": "invalid_control_combination", + "message": "lane requires an exact parameter selector", + } + ] + return result + if side is not None and parameter is not None: + result["issues"] = [ + { + "code": "invalid_control_combination", + "message": "parameter selects a dimension lane and cannot accompany side", + } + ] + return result + feature = sheet._features[sheet._index_of_token(token)] + try: + options = sheet.layout_options(declaration_id, parameter=parameter) + except (TypeError, ValueError, IndexError) as error: + result["issues"] = [ + { + "code": "unsupported_declaration", + "feature_kind": feature.kind, + "message": str(error), + } + ] + return result + result["options"] = options + if side is not None: + supported = options["controls"]["side"]["supported_values"] # type: ignore[index] + if side not in supported: + result["issues"] = [ + { + "code": "unsupported_value", + "control": "side", + "value": side, + "supported_values": supported, + "message": f"side must be a supported side: {supported} (got {side!r})", + } + ] + return result + else: + assert parameter is not None + if isinstance(lane, bool) or not isinstance(lane, int) or not 1 <= lane <= 8: + result["issues"] = [ + { + "code": "unsupported_value", + "control": "lane", + "value": lane, + "minimum": 1, + "maximum": 8, + "message": f"lane must be an integer from 1 to 8 (got {lane!r})", + } + ] + return result + result["supported"] = True + return result + + +def layout_override( + sheet: Sheet, + declaration_id: str, + *, + side: str | None = None, + parameter: DimensionParameterId | None = None, + lane: int | None = None, +) -> Sheet: + """Append one bounded declaration-scoped layout override. + + ``side`` selects a feature corridor. ``parameter`` + ``lane`` selects a one-based + parallel lane for one declared referential dimension. Neither form accepts page + coordinates; the shared placement solve resolves and validates the physical offset. + """ + + key = (declaration_id, parameter) + if any((row.declaration_id, row.parameter_id) == key for row in sheet._layout_overrides): + raise ValueError(f"layout target {key!r} already has a layout override") + validation = sheet.validate_layout_override( + declaration_id, side=side, parameter=parameter, lane=lane + ) + if not validation["supported"]: + issues = cast(list[dict[str, object]], validation["issues"]) + raise ValueError(str(issues[0]["message"])) + token = sheet._declaration_token(declaration_id) + if side is not None: + index = sheet._index_of_token(token) + sheet._replace_feature(index, replace(sheet._features[index], side=side)) + sheet._layout_overrides.append(LayoutOverride(declaration_id, side)) + else: + options = cast(dict[str, object], validation["options"]) + parameter_id = cast(str, options["parameter_id"]) + entry = sheet._dimension_entry_for_layout(token, parameter_id) + assert entry is not None and lane is not None + entry[0]["lane"] = lane + sheet._layout_overrides.append( + LayoutOverride(declaration_id, parameter_id=parameter_id, lane=lane) + ) + return sheet diff --git a/tests/_tier_manifest.py b/tests/_tier_manifest.py index 735a91f09..df367d939 100644 --- a/tests/_tier_manifest.py +++ b/tests/_tier_manifest.py @@ -38,6 +38,15 @@ class ContractGroup: ("src/draftwright/model/oriented_slot_geometry.py",), ("test_issue_1432_oriented_slot_semantics.py",), ), + "sheet_layout_controls": ContractGroup( + ("src/draftwright/sheet_layout_controls.py",), + ( + "test_layout_override_lane_issue_1757.py", + "test_layout_override_side_issue_1757.py", + "test_sheet_identity_invariant.py", + "test_declare.py", + ), + ), "recognition": ContractGroup( ( "src/draftwright/recogn*", @@ -65,6 +74,7 @@ class ContractGroup: "src/draftwright/intents.py", "src/draftwright/measurement_support.py", "src/draftwright/sheet.py", + "src/draftwright/sheet_features.py", "src/draftwright/sheet_emit.py", ), ( @@ -79,6 +89,7 @@ class ContractGroup: "test_measurement_support.py", "test_model_ir.py", "test_sheet_emit.py", + "test_sheet_identity_invariant.py", ), ), "placement": ContractGroup( diff --git a/tests/test_import_boundaries.py b/tests/test_import_boundaries.py index 2a0cd243e..5042758b1 100644 --- a/tests/test_import_boundaries.py +++ b/tests/test_import_boundaries.py @@ -167,6 +167,8 @@ def _tree(path: Path) -> ast.Module: # 7 — the user-facing surfaces "make_drawing": 7, "sheet": 7, + "sheet_features": 7, + "sheet_layout_controls": 7, "document": 7, "sheet_emit": 7, "sheet_object_source": 7, diff --git a/tests/test_layout_override_side_issue_1757.py b/tests/test_layout_override_side_issue_1757.py index 5029006cc..27fefeded 100644 --- a/tests/test_layout_override_side_issue_1757.py +++ b/tests/test_layout_override_side_issue_1757.py @@ -11,9 +11,15 @@ from draftwright import Sheet from draftwright.model import ControlFrame, DatumRef, Frame, LayoutOverride +from draftwright.model.ir import PLACEMENT_SIDES as IR_PLACEMENT_SIDES +from draftwright.sheet import PLACEMENT_SIDES as SHEET_PLACEMENT_SIDES from draftwright.sheet_emit import emit_sheet_script, mirror_model +def test_sheet_placement_sides_import_path_stays_available() -> None: + assert SHEET_PLACEMENT_SIDES is IR_PLACEMENT_SIDES + + def _sheet() -> Sheet: sheet = Sheet(Box(80, 60, 10), title="override").authored_dimensions() sheet.add( @@ -70,6 +76,46 @@ def test_options_and_validation_are_available_before_build() -> None: } +def test_duplicate_live_identity_is_refused_but_withdrawn_identity_can_be_reused() -> None: + sheet = _sheet() + replacement = sheet.add(DatumRef(Frame((-20, 0, 5), "z"), "B", "plan", "above")) + + with pytest.raises(ValueError, match="duplicate declaration_id 'declaration:57'"): + replacement.identify("declaration:57") + + sheet.features.pop(0) + with pytest.raises(ValueError, match="requires one live declaration; found 0"): + sheet.by_declaration("declaration:57") + replacement.identify("declaration:57") + sheet.layout_override("declaration:57", side="below") + assert sheet.model().features[-1].side == "below" + + +def test_validation_rejects_unknown_and_ambiguous_controls_without_changing_intent() -> None: + sheet = _sheet() + before = sheet.model().features + + unknown = sheet.validate_layout_override("declaration:57", side="above", x=10, y=20) + assert unknown["supported"] is False + assert unknown["issues"] == [ + { + "code": "unsupported_control", + "controls": ["x", "y"], + "message": "layout_override accepts only side, or parameter with lane", + } + ] + for controls in ({}, {"side": "above", "lane": 2}): + invalid = sheet.validate_layout_override("declaration:57", **controls) + assert invalid["issues"] == [ + { + "code": "invalid_control_combination", + "message": "specify exactly one of side or lane", + } + ] + assert sheet.model().features == before + assert sheet.model().layout_overrides == () + + def test_two_overrides_change_only_side_and_are_retained_as_layout_intent() -> None: sheet = _sheet() sheet.layout_override("declaration:57", side="above") diff --git a/tests/test_tier_manifest.py b/tests/test_tier_manifest.py index b68ebcdc1..fe712636f 100644 --- a/tests/test_tier_manifest.py +++ b/tests/test_tier_manifest.py @@ -32,6 +32,7 @@ def test_each_named_contract_group_resolves_to_existing_modules(): "through_step_placement": "src/draftwright/annotations/from_model.py", "hole_locations": "src/draftwright/annotations/hole_locations.py", "oriented_slot_geometry": "src/draftwright/model/oriented_slot_geometry.py", + "sheet_layout_controls": "src/draftwright/sheet_layout_controls.py", "recognition": "src/draftwright/recognition_frame.py", "compilation": "src/draftwright/intents.py", "placement": "src/draftwright/layout.py", @@ -79,6 +80,22 @@ def test_unknown_production_module_selects_every_contract_group(): assert selected_groups([pattern]) == frozenset(CONTRACT_GROUPS) +def test_sheet_feature_view_changes_run_the_sheet_identity_contract(): + changed = ["src/draftwright/sheet_features.py"] + assert selected_groups(changed) == {"compilation"} + assert "test_sheet_identity_invariant.py" in pr_modules(_TESTS, changed) + + +def test_sheet_layout_control_changes_run_the_declaration_contract(): + changed = ["src/draftwright/sheet_layout_controls.py"] + assert selected_groups(changed) == {"sheet_layout_controls"} + modules = pr_modules(_TESTS, changed) + assert "test_layout_override_lane_issue_1757.py" in modules + assert "test_layout_override_side_issue_1757.py" in modules + assert "test_sheet_identity_invariant.py" in modules + assert "test_dimension_lane_canary_issue_1757.py" not in modules + + def test_nonproduction_changes_do_not_expand_the_core(): assert set(pr_modules(_TESTS, ["docs/guide.md"])) == ( set(PR_CORE_MODULES) | set(PR_POLICY_MODULES) | set(UNIT_MODULES)