Skip to content

Latest commit

 

History

History
733 lines (720 loc) · 55 KB

architecture.md

File metadata and controls

733 lines (720 loc) · 55 KB

Architecture — the detailed module map

The module-by-module map of the draftwright engine (AGENTS.md keeps only the working rules and a one-paragraph summary). The machine-enforced authority for the layering is tests/test_import_boundaries.py (_LAYERS); keep that table and this document in step. The why behind every shape here lives in docs/adr/.

The module map

The dependency graph is a DAG (the #138 / ADR 1 (was 0005) split is complete). Bottom to top: strict rank-0 package leaves: progress.py, layout.py (including semantic survival order), registry.py, fonts/, _geometry.py, fixed_ink_cache.py, fits.py, contract_values.py, measurement_support.py, sheet_metadata.py, angular_geometry.py, family_table.py, recogniser_policy.py, recogniser_schema.py, feature_identity.py, and the strict blend_contract.py provider-record boundary → the rank-1 model/ IR waist, recognition_ownership.py, profile_angles.py, oriented_slot_contract.py, plate_correspondence.py, recognition_frame.py, and _core.py (beside rank-1 annotation_layout_profile.py and the stable obligations.py and leader_policy.py import paths) → stage modules (export.py, drawing_export.py, pdf_text.py, repair.py, projection.py, compose.py, layout_scheme.py, analysis.py, recognition_cache.py, drawing.py, intent_drain.py, intent_routing.py, intents.py (stable import path), reporting.py, the linting/ subpackage and the annotations/ subpackage) → builder.py → the user-facing surfaces: the make_drawing.py / annotate.py compat facades, the fluent Sheet facade (sheet.py), the Sheet-script emitter (sheet_emit.py), its post-build evidence writer (replay_assessment.py), the read-only STEP inspection surface (inspection.py), the recognition-evaluation package (evaluation/), and the cli.py entry point. Developer-only _build_profile.py sits at the same top layer: it patches the public builder and Sheet bindings lazily for pytest measurement, and no engine module depends on it. The package root __init__.py sits above these facades at rank 8 and resolves its public API lazily. No lower module imports an upper one. location_contract.py remains a stable rank-1 import path for the location predicates in measurement_support.py; the compiler and lint import their owner directly. progress.py holds a context-scoped observer and cooperative cancellation; stage modules publish activity at their existing seams, while the CLI alone renders it. It does not own placement decisions or a recognition inventory. (All surfaces are front doors onto the one engine, build_drawing → _auto_annotate — there is no second engine.)

A leading underscore on an engine name means package-internal, not local to one file. Sibling modules may import it along the ranked DAG; callers should use the published surfaces instead. The package root publishes exactly the non-underscored names in __all__ through its lazy binding map. A module with a separate published contract, such as reporting.py, states and guards that contract at its own seam.

layout_scheme.py sits beside compose.py at rank 2: it derives typed, render-free corridor demand from approved model groups, and compose consumes that topology. recognition_cache.py sits beside analysis.py at rank 3: both consume bottom-layer recognition contracts, while drawing_state.py and builder.py consume the cache. fixed_ink_cache.py is a rank-0 package leaf: its caller-owned, bounded face-mesh cache uses exact located B-rep bytes and tessellation tolerance as the key. Annotation fixed-ink validation and Sheet.build() consume it; it never owns placement or model state. test_rank_zero_modules_are_package_leaves enforces that every rank-0 file has no package import across runtime, type-only and lazy paths. model/ shares a numerical rank with _core but its separate fail-closed import allowlist still prohibits any model-to-core edge while permitting approved shared rank-1 modules.

This DAG is machine-enforced by tests/test_import_boundaries.py (#640): the _LAYERS table there is the precise, ranked form of this section — a module-level import that points up a layer fails CI, as does an explicit import cycle through files or package initializers even when one edge is inside a function. Implicit parent-package initialization edges are checked across top-level submodules. The precise placement refines the coarse grouping above (e.g. linting/pmi/export/repair/ projection/compose sit above _core since they depend on it; model/ is the IR waist with a stricter import allowlist than its numerical rank). The _LAZY_UPWARD_EXEMPT mechanism is empty (#523 removed its last occupant, the builder→cli edge — see below); a new upward lazy import must earn an entry with a rationale and cannot close a cycle. In-function imports remain in several layers, including the cli→builder/sheet_emit imports that preserve the #313 build123d lazy-load. Their statement count has a shrinking test budget. Two type-only upward references (_core→compose.StripDepths and annotation_layout_profile→compose.StripDepths, both under TYPE_CHECKING) are explicit allowlist entries. Rank-0 modules cannot use this exemption. Keep _LAYERS and this section in step.

evaluation/ owns the versioned, independently-authored STEP-analysis benchmark and its scoring model. It is a top-layer consumer of the recognition contract; production recognition, IR, generation, and drawing code must not depend on benchmark expectations or scores. evaluation/_double_d_evidence.py owns the Double-D physical correspondence, public declaration, and drawing-evidence checks. evaluation/_turned_step_evidence.py owns turned-step IR correspondence and finished-drawing evidence. evaluation/_pocket_evidence.py owns lone-pocket and pocket-pattern correspondence, public declaration, and drawing evidence. evaluation/_prismatic_evidence.py owns rectangular-pad and plate correspondence, public declaration, and drawing evidence. evaluation/_groove_evidence.py owns groove correspondence, public declaration, and finished-drawing evidence, including an oracle independent of production callout formatting. evaluation/_edge_profile_evidence.py owns chamfer and fillet physical correspondence, public declaration, and finished-drawing evidence. evaluation/_flat_polygonal_evidence.py owns flat, polygonal-boss, and polygonal-stock correspondence, public declaration, and finished-drawing evidence. evaluation/_hole_family_evidence.py owns hole, countersink, and hole-pattern declaration and finished-drawing evidence. evaluation/step_analysis.py retains the observer registry and re-exports the existing private helper names.

  • make_drawing.py — thin compat facade (~20 lines) re-exporting the public surface (Drawing, build_drawing, make_drawing, _cli, FeatureInfo, fix_svg_page_size, lint_feature_coverage) so existing imports and the draftwright CLI entry point keep working. The engine lives in:

    • builder.py — build orchestration: build_drawing (analyse → assemble → measure-and-repack → Drawing) and make_drawing (+ export). Imports drawing/analysis/the annotation orchestrator/the stage modules — never make_drawing (a DAG). (generate_script, the imperative editable-script generator, was retired by #940 — ADR 4 (was 0016) phase 6 / ADR 4 (was 0001 Amdt 2) — and deleted at its 0.4.0 date (#720), along with the raising stub that stood in for it and the bespoke --style imperative message. --style itself survives with the single value sheet so existing invocations keep working.) (The CLI moved out to cli.py; the _cli compat shim lives there too (#523), so builder no longer imports cli.)
    • build_policy.py — rank-6 finished-drawing scale and arrangement decisions: required-outcome blockers, structural validity, candidate quality, and stable decision records. builder.py keeps the automatic retry ladder and its constants.
    • section_scale_recovery.py — rank-6 bounded same-sheet scale recovery after an optional section drops, including a finished requirement comparison.
    • explicit_scale.py — rank-6 resolution of a caller-requested scale: automatic-view veto, strict and permissive decisions, and bounded standard-scale fallback. The builder supplies its build and critique seams and current scale ladder.
    • build_once.py — rank-6 owner of one compile attempt: analysis, view preflight, pre-render profile choice, assembly, measured repack, repair, and the returned view decision. builder._build_drawing_once passes its stage bindings through so the outer policy ladder and instrumentation keep one seam.
    • layout_safety.py — rank-6 observational safety evidence for a finished candidate, using reporting and settled view geometry without a baseline drawing.
    • layout_selection.py — rank-6 finished-drawing annotation layout evidence and safe semantic comparison between the default and alternative layouts (guarded layout selection). Its manifest gets raw witnesses and their summary in one lint_snapshot(drawing) call from drawing.py, so it critiques one finished state once without exposing a reusable scope to callers. A persistent cache remains a follow-on for #1945: live annotation, view and registry mutations need a complete generation contract before a cached result can be trusted.
    • cli.py — the Typer command-line interface (#289): argument parsing, --version, shell completion, --format, rich help. The engine (build123d) is imported lazily inside the command body so completion/--help/ --version stay sub-second (#313). Entry point: draftwright.cli:app.
    • drawing.py — the Drawing result object (.lint()/.dimension()/.place_dim()/ .repair()/.export()). It owns feature edit decisions and solver-bound intent preparation with its private mutable state, and delegates identity to registry and ordered lint critique to linting/orchestration.py. It also defines FeatureInfo (_build_table moved beside _table_metrics in _core, #699). Sits below builder (which constructs it). (The build context lives in ONE typed BuildState on Drawing (_build: analysis, part model, lint's geometry caches) — filled at a single site in builder._assemble, read through compat properties, single-writer-guarded by test_drawing_encapsulation. ADR 1 (was 0005 §2) / #639 closed: annotations/ has zero private Drawing reads (empty allowlist ratchet) — and since #699 slice d the state-bus guard covers the WHOLE engine: no module but drawing.py touches dwg._* (rationale-carrying allowlist, builder's fill site only).)
    • drawing_evidence.py — rank-2 read-only suppression, measurement-claim, page-use and lint-summary projections. Drawing supplies explicit model, registry, annotation and build evidence; this module neither owns build state nor reaches into private drawing fields.
    • drawing_diagnostics.py — rank-5 finished-drawing lint and report coordination. Drawing supplies explicit build state and public dispatch callbacks; task-local scopes retain pair and requirement evidence without a persistent result cache.
    • drawing_export.py — rank-2 export orchestration and shape serialization. Drawing retains the observed public operation and supplies explicit writer, lint and text callbacks; the export owner reads only public result state.
    • drawing_state.py — rank-5 typed BuildState owner; drawing.py re-exports the type and remains its sole construction site.
    • drawing_tables.py — rank-5 note, data-table, hole-table, and balloon operations over an explicit snapshot of Drawing-owned state. Drawing retains the public verbs and the private-state reads.
    • intent_drain.py — rank-5 deferred intent stage execution. Drawing.finalize() owns the snapshot, rollback and trace commit; its thin _drain_intents facade supplies an explicit intent list, detail setting and callbacks. The drain uses the public drawing surface and the shared PlacementContext to execute the orchestrator's canonical stage order without importing Drawing.
    • intent_routing.py — rank-5 classification of recorded edits into the canonical stage routes. Drawing supplies its intent list and span-validation callback; the classifier returns route identities and feature sets without modifying drawing state or placing annotations.
  • annotate.py — thin compat facade re-exporting _auto_annotate (the orchestrator) from annotations/. The annotation passes were split into the annotations/ subpackage (#164 / ADR 1 (was 0005), P5):

    • annotations/drawing_port.py — the structural rank-4 Drawing interface used by annotation stage entry points. The real rank-5 Drawing satisfies it through the builder call without an upward annotation import.
    • annotations/orchestrator.py — _auto_annotate, the single entry point (called by build_drawing); classifies the part and drives the render passes
      • title block. Owns _PASS_SEQUENCE — the ONE canonical stage order (#699 slice b): _auto_annotate and intent_drain.drain_intents (the finalize drain) both hand name→thunk dicts to the shared run_stages, so the two build paths cannot diverge in sequencing (the drain step itself is the shared drain_and_reconcile). The current ADR 1 (was 0015) shape is build model → plan/model-routed intents → render; some inline engine code remains — chiefly _maybe_tabulate_holes (the hole-table/balloon escalation resolver) and the iso right-strip outer-limit tightening — pending the last convergence steps.
    • annotations/_sheet_furniture.py — the shared title-block cache, page frame, zone ruler, projection glyph, scale note, and document-wide finish renderers called by both the builder and annotation orchestrator.
    • annotations/from_model.py — the IR render facade and remaining feature passes: turns the planner's DimensionGroup/render intents into placed dimensions, callouts, centre marks, and section triggers. It keeps the orchestrator's pass bindings while family owners implement extracted passes.
    • annotations/_axial_render.py — compiled step-chain, height-ladder, step-position and rotational rendering. from_model re-exports the public passes and injects its current chain placer into step-length and authored detail calls, preserving the shared immediate/deferred route.
    • annotations/_machined_leaders.py — expands compiler-approved feature leader jobs into analytical interior/exterior candidates and submits them to immediate or late shared placement. from_model.place_machined_leader_jobs remains the pass seam and supplies live rendering and test bindings.
    • annotations/_step_lengths.py — owns compiler-approved turned axial profile grouping, X/Y crowded-chain detail requests, and step-length placement. from_model.render_step_lengths remains the public pass; the shared chain placer lives in _axial_render and is injected through from_model for immediate/deferred detail recovery.
    • annotations/_height_ladder.py — owns compiled prismatic step-height and overall-height corridor candidates, including chained witnesses and short-rung left-strip escape. from_model.render_height_ladder retains view routing and compiled-rung selection; candidates enter the shared corridor solve.
    • annotations/_envelope.py — owns compiler-approved overall width/depth routing, mandatory corridor candidates, and deferred above/interior retry with measurement-specific refusal evidence. from_model.render_envelope retains the public pass and supplies its live placement bindings.
    • annotations/_circular_recesses.py — owns compiler-approved blind-step and channel callout grouping and the bounded circular-wall leader candidates. The public passes in from_model supply live radial and leader placement bindings.
    • annotations/_pocket_pad.py — owns compiler-approved pocket and pad-height labels, projected rim bounds, direction policy, and leader job construction. The public passes in from_model submit those jobs to the existing late feature-leader assignment.
    • annotations/_polygonal_prisms.py — owns compiler-approved hex-pocket, polygonal-boss, and polygonal-stock labels and physical wall-anchor jobs. The public passes in from_model supply the shared leader reach and submit those jobs to the established late leader assignment.
    • annotations/_edge_callouts.py — owns compiler-approved chamfer, fillet, and Blend labels, physical attachment sites, and leader candidate jobs. The public passes in from_model retain the shared late assignment and outcomes.
    • annotations/_thin_profiles.py — owns compiler-approved plate thickness and open-channel width corridor candidates. from_model.render_plates retains the public pass and registers them in the established order.
    • annotations/_diameters.py — owns compiler-approved step and boss diameter grouping, row/column placement, radial leader jobs, and physical rerouting. from_model.render_diameters keeps the public pass and supplies the shared leader solve and live material predicate.
    • annotations/_locations.py — owns compiler-approved hole and circular-seat datum locations, axis furniture, and X/Y corridor candidates. The public from_model passes retain their signatures and supply live dimension, corridor-registration, and iso-boundary bindings.
    • annotations/_gdt.py — owns declared GD&T glyphs, source provenance, and shared-corridor candidates with deferred side and sheet fallback. from_model.render_gdt keeps the public pass and supplies live leader, carving, and sheet-fallback bindings.
    • annotations/_pmi_dimensions.py — owns imported authored PMI dimension selection and compiled included-angle rendering, proven witnesses, angle/linear/cylinder candidates, source outcomes, and shared-corridor fallback. from_model.render_pmi and render_angular_dimensions keep their public pass signatures and supply live selection and placement bindings.
    • annotations/_slots.py — owns compiler-approved slot, pad, and pocket in-plane dimension witnesses, corridor candidates, and obround-radius candidates. from_model.render_slots retains the public pass and submits radius jobs to the shared late leader assignment.
    • annotations/angular.py — angular arc/arrow/extension ink and analytic radius-dependent footprints, consumed through the shared corridor solve.
    • annotations/holes.py — hole callouts, balloons, planar location, pitch placement, table furniture transactions, and the pattern pass entry points.
    • annotations/_patterns.py — grouped pocket and slot pattern callouts, compiled pitch labels, grid-axis selection, and aligned-pitch coalescing. The hole pass supplies its live strip-placement and furniture bindings.
    • annotations/hole_locations.py — compiler-approved off-axis hole locations (incl. side-drilled #133) placed through the shared corridor solve.
    • annotations/hole_leader_candidates.py — ordered physical candidates for sparse plan and side hole leaders in the shared late leader assignment, plus front/rear rim-tip construction consumed by the current vertical strip solve. The hole pass retains strip selection, table eligibility, and furniture transactions.
    • annotations/_hole_leader_placement.py — shared physical hole-leader construction, callout claim forwarding, and bounded sheet recovery; the hole pass owns the queue and survivor commit. Sparse plan and side holes enter the late feature-leader inventory after a PAVA seed. Front and rear callouts use a below-view vertical strip with a compiled location witness and the shared strip survivor commit. Dense and profiled plan/side callouts retain an immediate, diameter-ranked PAVA row solve with keep-out bands and bounded Policy B relocation; only surviving rows receive their names, measurement owners, and pattern furniture. Dense scattered holes can instead become a table and balloons. Immediate and late jobs share physical leader construction and leaders.commit_feature_leader; front/rear callouts use place_strip_candidates and the strip commit. #1937 tracks convergence of these placement and transaction paths while preserving authored-side routing, owner and measurement identity, furniture rollback, callout indexing, and trace order.
    • annotations/_leader_fixed_ink.py — exact fixed-annotation component lowering for the shared leader solve: metadata strokes, label boxes, and residual rendered faces retain bounded work and stable component identities.
    • annotations/_leader_candidates.py — typed feature-leader regions and bounded, deterministic interior/exterior expansion of physical anchors before the shared late solve. The established leaders imports remain available to feature renderers.
    • annotations/_leader_commit.py — settled joint candidate inventory, trace recording, and survivor commit for the shared late leader solve. It receives typed outcomes and callbacks from leaders, without owning the producer streams or assignment policy.
    • annotations/leaders.py — the one bounded late inventory for compatible automatic/deferred same-view feature leaders (#1166). Its typed phase handoffs keep the producer streams, lazy greedy floor, primary per-view assignment, budget replay, and OCC survivor validation in this rank-four owner; the public placement entry point hands settled outcomes to _leader_commit in order. Sparse ordinary side/plan hole jobs and the five post-drain machined-feature families lower exact committed component ink conflicts (including component-local curved centre furniture and rendered shifted-dimension arrows), retaining any rendered residual triangle not covered by one same known component and any curved residual area between tessellation stations, including filled datum/GD&T faces without segment metadata; candidate construction fails closed per alternative, while a selected-survivor construction exception or mismatch replays the canonical lazy producer tail rather than silently reducing cardinality, with validation-stage diagnostics and without swallowing compiler invariant errors; fixed components are lowered once under the same resource discipline and reused; the complete title band stays hard after rendering; only explicitly marked global turning axes exempt only the arrow-local tip attachment (not near-collinear shaft travel), priorities, Policy-B penalties, and numeric costs into layout.py; optional sections enter only a separately bounded no-worse refinement, then validate their final ink against landed leaders, repair one end-symbol extent, and yield on conflict, then validate the selected OCC ink and emit it with its original provenance; any retained fixed-ink Policy-B crossing persists as feature_leader_crossing, independently of opt-in tracing, while a producer replay beyond the exact fixed-probe budget persists as feature_leader_fixed_ink_unverified without exceeding that bound and cannot report a perfect legibility quality score. ADR 2 (was 0014 Amendment 3) (#798) adds material re-entry to that Policy-B penalty at a stated exchange rate (one unit per visible stroke width of buried shaft) — a cost, never an eligibility gate and never an acceptance test, so no callout is dropped because its route cuts. The resource-cap floor, which is what actually runs on dense parts, gained a bounded lookahead past a first acceptable-but-cutting route; a job whose first acceptable route already clears the body selects it exactly where it always did.
    • annotations/sections.py — section A–A + detail views (cut-plane arrows, hatched cut faces; supported conventions and limits in the detail/section comparison).
    • annotations/balloons.py — the leadered hole-balloon pass (#111/#516; moved down from Drawing, #699). Drawing.add_balloons is the public verb threading build state in; the band-assignment flow solver lives in layout.py.
    • annotations/gears.py — standards-backed data-table presentation for the declaration-only metric external spur gear; the table flows through the generic solver-owned late-furniture path (#1086).
    • annotations/_dimension_ink.py — analytical dimension label sizes, candidate footprints, and straight-stroke probes used by the corridor solve before selected annotations are built. It uses lower-layer typography and arrow bounds; _common.py retains the existing helper import paths.
    • annotations/_dimension_ink_repair.py — bounded same-batch label conflict arithmetic and deterministic candidate search. _common.py supplies its dimension builder at call time and keeps the established import path.
    • annotations/_placement_geometry.py — analytical leader footprints, decomposed occupancy boxes, centerline label clearance, and the shared 1D obstacle carve. It owns _box_hits; _common.py retains the established helper import paths.
    • annotations/_placement_occupancy.py — placed annotation occupancy, late-furniture obstacles, pending title-block keep-out, and exact ink-clearance predicates. It also places the ISO NTS caption against the finished sheet; _common.py keeps the existing imports and supplies its live caption box probe.
    • annotations/_strip_postsolve.py — required exact-ink resolution after the shared strip solve and final survivor commit with provenance and trace closure. _common.py supplies its live placement helpers at call time and retains the established private helper paths.
    • annotations/_common.py — the ADR 2 (was 0014) corridor-solve engine (CorridorCandidate, solve_corridor, register_corridor/drain_corridors, place_strip_candidates, PlacementContext), at the bottom of the annotations DAG. Bbox and segment helpers live in _core, _geometry, and _placement_geometry. The post-fit late-furniture seam (#1197) lives in _placement_occupancy: late_furniture_obstacles includes views and decomposed annotation ink, excludes page-spanning riders, and includes the title block as one hull. Drawing.add_table and the ISO NTS caption share that policy through the stable _common imports.
    • annotations/solve_trace.py — the optional, recording-only corridor and pass event recorder. _common.SolveTrace remains the same class for existing callers and trace pickle identities; its JSON schema and failure isolation stay owned here, below Drawing and builder. Submodules import only down or sideways — _core/layout/analysis/ projection/the model/ IR/linting.structural/third-party, never annotate/make_drawing/drawing (the drawing is duck-typed as dwg) — so the orchestrator calls down with no cycle.
  • _core.py — shared primitives below both make_drawing.py and annotate.py: the Analysis namespace and its field types (_Projector, Strip, ViewZones), the dimension/format helpers (_dim, _fmt, …), and the page/slot/margin layout constants.

  • layout.py — the deterministic placement primitives used by ADR 2: the deterministic 1D PAVA strip solve (_solve_strip_1d_pava, plus plan_strip/StripCandidate, the ADR 2 (was 0014) collect-then-solve entry point), the 2D free-rectangle placer (fit_box) and compressed-coordinate largest-empty-rectangle sweep (_largest_empty_rect, still importable through _core), and the balloon band-assignment min-cost max-flow solve (_assign_balloon_bands, #516; here since #699 — solvers live in the solver layer), and the required/unknown/optional survival order shared by pre-render demand and placement solvers. It has no IR or rendering dependency; source and measurement authority stay with the compiler. Sits below the domain API.

  • obligations.py — stable rank-1 import path for layout.py's semantic survival order. Engine consumers import the owner directly.

  • leader_policy.py — stable rank-1 import path for the feature-leader region policy owned by annotation_layout_profile.py.

  • _geometry.py — model-neutral geometry primitives (_xyz, HoleRef, _axis_letter, _END_ON) plus the #700 shared page-plane maths (_fmt, _boxes_overlap, the two segment/box tests) and plane_axes — the one in-plane (u, v) basis per axis, shared by recognition._features._plane_uv and model.declare._plane_axes so a pattern's angle means the same thing detected as declared (#969); the DAG's bottom leaf (guarded by test_geometry_is_a_leaf) so the IR waist uses them without importing _core. Also the ADR 2 (was 0014 Amendment 3) filled material field (#798): MaterialField/material_field (page-plane triangles + a uniform grid index), material_span, material_intervals, and material_reentry_span — exact half-plane clipping with a fixed-point interval union and an incremental cell walk, no sampling. Re-entry, not traversal, is the routing defect: a leader's first passage out of the body is the legitimate exit every callout makes.

  • _pmi_part21.py — the rank-0 structured ISO 10303-21 adapter for AP242 geometric-tolerance facts that OCCT's XCAF transfer drops. It resolves explicit Part21 references and SI length units, and requires unique semantic-name + kind correspondence; it knows nothing about XCAF, drafting IR, or placement.

  • _warnings.py — the public warning categories (SoftDeprecationWarning), a dependency-free leaf. Separate from _core on purpose: _core imports build123d, so a category defined there costs the CAD kernel (~6 s) to reach, and the pytest filterwarnings entry naming it pays that on every invocation (#1043).

  • fits.py — the ISO 286 fit tables (fit_deviation, FitClass; ADR 4 (was 0011) P2a.2): a rank-0 leaf consumed by _core, model/ir and sheet.

  • intent_routing.py / intents.py — the deferred-placement "low IR" behind Drawing.finalize() (#426): the rank-5 routing owner defines the edit-verb Intent record; intents.py reexports the same class for existing imports. The deliberately stringly-typed record feeds the recompose path.

  • registry.py — AnnotationRegistry: the single owner of annotation identity/ownership/pins/build-issues (#138 / ADR 1 (was 0005), Step 2). It also owns typed candidate-region provenance, per-annotation detail scale, the immutable cut/view mark on each live section cutting-plane line, and each committed engine dimension's immutable point/spec snapshot with an explicit live Draft style source for PDF text (#1931). Drawing delegates here and keeps the render list. The _named/_anno_view/_pinned/ _build_issues aliases on Drawing (and coverage's three) were deleted at their §4 date (#720): reach the state through dwg.registry (in reg, names(), issues, restore_issues()) and dwg.coverage. Their absence is asserted by test_the_expired_compat_aliases_stay_deleted.

  • linting/ — the lint subpackage (#138 / ADR 1 (was 0005); ADR 3 (was 0007): draftwright owns linting): orchestration.py (ordered structural, physical, PMI, and build-issue critique over an explicit drawing context), coverage.py (lint_feature_coverage + CoverageState), _coverage_common.py (stable import of _registry's exact measurement-outcome index, shared outcome checks, exact three-coordinate point rounding, blind-slot value validation, and section-recess source selection), _parameter_coverage.py (the shared physical-key, exact-parameter and outcome driver for chamfer, fillet, paired-ramp-step, circular-blind-step, rectangular-blind-slot, and round-bottom-blind-slot coverage), structural.py (geometry/standards checks), issues.py (the LintIssue type), angular.py (degree claims and actual angular ink), requirements.py (the physical requirement join), schedule_evidence.py (verified table-cell carriers), ink_overlap.py (line-work against annotation labels), and suggest.py (_suggest_fix, #29 snippets). The family owners are the *_coverage.py modules: angled_step, blend, boss, chamfer, channel, circular_blind_step, envelope, fillet, flat, gear, groove, gusset_rib, hole, oriented_slot, pad, paired_ramp_step, passage, plate, pmi, pocket, pocket_pattern, polygonal_boss, polygonal_stock, prismatic_pocket, profiled_bore, rectangular_blind_slot, round_bottom_blind_slot, section_recess, slot, through_step, and turned_step. Lint reads lower-layer geometry, registry, measurement and recognition contracts, as well as rank-2 projection and PMI helpers; it never imports draftwright.model. _QUOTED_RE (a lint-message label regex shared with the repair loop) lives in _core.

  • recognition_cache.py — rank-3 Draftwright ADR 3 (was 0017) one-result lifecycle owner. Raw automatic analysis seeds it with one external build_recognition_evidence(part) acquisition; on a lazy declared critique the empty cache makes that call itself. It retains the exact RecognitionResult projection and evidence authority together. The package owns recognition, while Draftwright owns when the pair is computed and reused. A bare or explicit framed result remains valid without evidence; the cache never rescans to backfill it.

  • recognition_ownership.py — the run-local consumer ledger below/beside the ADR 1 (was 0015) IR waist. During record→IR conversion it binds opaque provider occurrences to the exact IR feature objects that represent or absorb them, by same-run record identity and explicit aggregate membership. Ownerless outcomes are projected from the existing consumer capability declaration, not a second policy table. It exposes no persistent topology/order/address ID. Bolt-circle corroboration is shared with declared critique: an uncorroborated proposal may be drawn as ordinary holes, while an exact authored pattern retains its independent join. Unconditional 1:1 adapters, singleton/grouped/pattern hole/slot/pocket members, nested countersinks, conditional channel/turned-step owners, direct or multi-feature through-step owners, and settled unsupported/deferred/evidence-only occurrences are classified; remaining conditional cross-family records stay unclassified.

  • measurement_support.py — a strict package leaf for run-local producer-issued measurement, interval and member witnesses, plus the shared pocket/pad datum reference and coincidence predicates and the exact same-run four-flat boss/pad owner check. Lint's named annotation carrier belongs to linting/_registry.py, beside the registry evidence that creates it.

  • location_contract.py — stable rank-1 import path for those predicates; the implementation is owned by measurement_support.py and this path is not deprecated.

  • plate_correspondence.py — pure shared Plate-record/final-IR correspondence predicates.

  • contract_values.py — shared three-decimal correspondence rounding, exact built-in finite-real validation, and the common compensated dot product and 3D cross product used by profile and frame checks.

  • sheet_metadata.py — the frozen, dependency-free carrier for the title, display, border, and title-block inputs forwarded through analysis. Public defaults and the existing validation paths remain at their current entry and layout owners.

  • section_recess_contract.py — the published SectionRecess grammar interpreted in Draftwright's drafting vocabulary (pocket, channel and hex fields) and the exact inventory pattern joins, shared by detection and independent completeness lint.

  • annotation_layout_profile.py — rank-1 build-scoped options for the alternative annotation layout (candidate options and corridor caps), so a candidate is built without mutating process state. It also owns the typed, coordinate-free document policy that filters feature-leader candidate regions without granting coordinates or inventing eligibility.

  • view_plan.py — the ADR 2 planning vocabulary for which views a drawing requests and resolves; a drawing-independent leaf.

  • audit.py — compares finished drawings and captured measurement claims (diff_builds: named annotation losses, gains, changed labels and substitutions).

  • profile_angles.py — bounded face-profile angle requirements projected from Quiddity's ordered supports, with issued body/profile identity retained outside the IR. The detection adapter creates the ordinary declared angle feature and records its owner in RecognitionOwnership.profile_angles; these are drafting requirements, not additional accepted recognition occurrences.

  • angular_geometry.py — analytic angular boxes from support rays, fixed typography and paper-space drafting clearances. Composition and rendering share this geometry; page/scale trials consume numeric boxes without constructing CAD annotation objects. Model assembly uses their feature dependency sets only while recording exact same-run occurrence ownership; completeness lint uses the same predicates for requirement ownership. The leaf imports neither consumer, recogniser implementation, nor drawing state.

  • recogniser_policy.py — the rank-0 Draftwright-owned source for reviewed unsupported, deferred, and geometry-only family policy. Both the cross-repository capability declaration and the run-local occurrence ledger project this same immutable data; recognition remains geometry-only and no engine leaf imports the rank-7 contract validator.

  • family_table.py — rank-0 consumer metadata for provider and local drafting families. It spells out provider, issued evidence, aggregate, requirement, and quality names where they differ. The four static ownership categories are derived from it; record-dependent ownership exceptions remain with recognition_ownership.py.

  • recogniser_schema.py — the rank-0 Draftwright-owned table of public provider record schema versions consumed by adapters. The report projector and rank-7 cross-repository validator share this leaf, so the engine never imports the validator to learn schema metadata.

  • document_evidence.py — rank-2 binding of confirmed member claims to exact interval/member witnesses, engineering agreement and producer-issued dependency proof evaluation.

  • reporting.py — the rank-2 pure schema-v1 report projector, and the named seam (project_occurrences, json_value, producer, write_json_document) that the drawing report and the STEP-inspection document are both built from (#1461). The generation snapshot it also used to project was removed in #1460. Drawing owns all report reads from its BuildState, while generated Python passes the exact retained evidence, ownership, detected model, and source digest explicitly. Reporting never reaches through Drawing private state or triggers recognition, placement, or export.

  • recognition_frame.py — the ADR 3 (was 0020) prepared local-frame boundary. It calls the public provider preparation seam, classifies the exact normalized solid from its already-scanned cylinders, runs one paired aggregate, propagates typed refusal without fallback, and exposes conservative FULL/ORTHOGONAL/AXIAL semantic policy. Analysis calls it only for the explicit framed_recognition=True rollout path and owns any visible raw fallback above this module.

  • blend_contract.py — the strict leaf boundary for released schema-v3 straight/circular Blend path records. It rejects widened, mutable, non-finite, non-canonical, and unreleased values and owns the exact occurrence key shared by conversion and completeness lint.

  • oriented_slot_contract.py / feature_identity.py — the #1432 shared trust boundaries. The rank-0 identity leaf also registers the exact envelope type for independent consolidated seat-run coverage. The former shares exact released schema validation between detection and independent completeness, with geometric correspondence keys separate from same-run occurrence identity. The latter registers exact compiler feature, passage and frame classes so lint can reject same-named ducks without the ADR 1 (was 0015)-forbidden linting → model import.

  • recogniser_contract.py — the fail-closed cross-repository capability join. It consumes only the installed quiddity public manifest and rank-0 consumer policy, then validates Draftwright-owned IR, Sheet, generated-code, drawing, completeness, and documentation declarations. It is rank 7 because validation dynamically resolves implementation references across every lower layer; package geometry policy never imports or owns this consumer overlay.

  • inspection_contract.py — the separate fail-closed join for declared-feature geometry reads. It validates inspection manifest format 1/API major 1, the exact installed recogniser release, and only the stable quiddity.inspection symbols and value schemas consumed by model/declare.py. It deliberately does not declare recognition-family semantics.

  • build_options.py — rank-1 frozen build inputs shared by the builder and script emitter. It owns defaults and context-free policy validation; retry-specific scale, page, and analysis state remain explicit in build orchestration.

  • document_input.py — rank-1 common intake authority: exact raw recognition/ownership, sealed physical membership and copies of member authoring containers. It retains source bytes and the original analysis for reuse through the existing builder.

  • document.py — rank-7 explicit document facade. It takes one STEP snapshot, binds member Sheets to the common source, and builds them through the existing pipeline with named failures. Live member snapshots reach reporting.py for document coverage, carrier attribution and engineering conflict assessment; ordinary Drawing reports retain schema v3.

  • inspection.py — the rank-7 public read-only STEP inspection surface (inspect_step). It hashes one immutable source-byte snapshot, drives the shared one-run _detect_part_model_analysis seam over a private copy of those bytes, and projects the resulting evidence, ownership and association accounting through the rank-2 reporting.py occurrence projector. It builds no drawing: no projection, placement, render, export, or physical lint path runs. The engine imports the builder lazily inside the function so from draftwright import inspect_step stays sub-second (#313). sheet_emit imports it at the same rank to write its sidecar; nothing below rank 7 depends on it.

  • model/ — the ADR 1 (was 0015) IR waist: ir_foundation.py owns the foundational values, protocol and common feature records; ir.py re-exports those records at their historical qualified names and owns PartModel and the remaining feature records (the one inventory); oriented_slot_geometry.py holds private passage and feature geometry validation, with the public dataclasses retained in ir.py; dimension_intent.py holds the authored measurement selector vocabulary and semantic view/strip validation, with stable forwarding functions in ir.py; detect.py (detectors → Feature objects, adapting quiddity records through a typed ordered-run context; section-recess record conversion stays in this adapter), detect_inventory.py (supplied-input validation and one aggregate inventory projection), and detect_ownership.py stages (aggregate radius partition, prismatic owner preparation and exact through-step legacy ownership), planner.py (plan_dimensions — one rule set → a DimensionGroup per feature, + plan_sections; and, since #1154, the one cross-feature reconciliation: two features measuring between the same two support planes state one fact, so the overall extent keeps it and the feature-local one records where it went), pmi_lowering.py (geometry-correlated AP242 dimensional and manufacturing requirement lowering), manufacturing_schedule.py (source-owned table presentation for long imported requirements), and declare.py (ADR 4 (was 0011) object→feature constructors: hole/boss/step/… read a feature's size off the build123d object — a second, declared front-end into the same IR the detectors fill). The narrow middle of the compiler hourglass; consumed by annotations/from_model.py.

  • auxiliary_layout.py — measured note rows and discretionary page-block gutters shared by sheet selection and late placement. It retries the hard fit whenever preferred whitespace is infeasible; it never weakens content survival.

  • compose.py — the ADR 2 (was 0004) outer compose-then-pack layout engine (choose_scale, ViewBlock, zone/strip depths). Née sheet.py; renamed (#640) so the layout engine stops shadowing the user-facing Sheet facade (which now owns the sheet.py name).

  • analysis.py — the _analyse stage: solid classification, the one-shot feature-inventory detection (ADR 1 (was 0015)), view sizing, and the strip/zone model (fv_zones/pv_zones/sv_zones) that ADR 2 (was 0014) placement reads. Its internal request carries one SheetMetadata record and flattens those values back into the established Analysis fields after sizing and validation.

  • projection.py — HLR projection and view-coordinate transforms (_assemble's geometry half; #161). Also the #798 material lowering: part_material_mesh tessellates the part once per build and view_material_field projects that one mesh per view, so every view measures the same material. The mesh is taken under explicit control (copy → BRepTools.Clean_s → BRepMesh_IncrementalMesh) because OCC caches a triangulation on the shape and returns it for any later request — even a finer one — which would make the field a function of build history (the ADR 5 (was 0006) hazard). Drawing.material_fields() holds the result on BuildState. _fit_iso_view returns the iso bbox when the fitted iso is off sheet scale and therefore needs an NTS caption, else None; it does not place that caption. builder does, at the common post-fit point before render_gear_tables — the caption is tied to the block it labels while a table may sit anywhere, so the constrained furniture claims space first (#1197).

  • sheet.py — the fluent declarative Sheet facade (ADR 4 (was 0011)): feature verbs (hole/boss/slot/…), aspect verbs (.tolerance/.fit/ .finish), GD&T (datum/control). Facade tier: builds a PartModel via 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_views.py — private Sheet view declaration, relation and constraint materialisation methods. Sheet inherits these methods and sheet.py re-exports _View for existing private imports and pickles. Caller locations skip both facade files so a declared constraint still points to its author.

  • 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.

  • sheet_feature_lines.py — private feature-declaration formatting for generated scripts: numeric spelling, source-record expressions, and feature-family calls. sheet_emit.py keeps the dispatch and existing private import paths.

  • sheet_emit.py — the script emitter, behind --script (#940 retired the imperative alternative): generates an editable Sheet script from a detected model — one named binding per feature, an explicit dimension source, and a bounded generation-time recognition-gap snapshot. Facade tier; imports builder, the pure reporting projector, sheet_feature_lines, and replay_assessment downward at module level. The latter prepares exact source/script identity before replay and atomically wraps the same Drawing's strict report plus export-result hashes afterward; it never builds or recognizes (#1715). The old builder→cli→sheet_emit lazy cycle is gone (#523): the _cli compat shim moved from builder to cli.py (beside the Typer app), so builder no longer imports cli and _LAZY_UPWARD_EXEMPT is now empty. The graph is a plain DAG — cli → {builder, sheet_emit}, sheet_emit → {builder, reporting, replay_assessment, sheet_feature_lines}, replay_assessment → reporting, builder → ∅. The rank-0 audit module compares serialized v2 replay assessments without importing the engine: exact declaration/occurrence ownership, compiled meanings, representation carriers, lint, layout and independent quality components stay as a vector. A fixed expected-requirement list is caller authority, never inferred from geometry, and no composite quality score is formed.

  • score.py / recognition/ — temporary public compatibility re-exports of quiddity, identity-preserving and scheduled for removal in 0.6.0. There are no embedded recogniser modules. Engine code imports the external package directly; private historical draftwright.recognition.* paths are intentionally unsupported.

  • quiddity (external) — the ADR 3 (was 0013) geometry-only bottom layer: uniform deterministic recognise_* functions, frozen serialisable records, shared substrates, RecognitionResult orchestration/manifest, repeating-profile correspondence, and feature_census. It imports build123d/OCP and never imports Draftwright.

  • fonts/ — vendored, path-pinned IBM Plex fonts for deterministic cross-platform layout (ADR 5 (was 0006)).

  • pdf_text.py — rank-2 PDF semantic text assembly from the drawing's explicitly supplied draft, named annotations, and registry dimension specs. It preserves label recovery, text placement, and page reading order; Drawing._pdf_text_runs() delegates here, and export.py renders the returned runs over vector glyph paths.

  • export.py — SVG/DXF/PDF/PNG export + post-processing (page-size fix, attribution hyperlink/metadata, DXF metadata, arc sanitisation, element-wise shape-export degradation). The render chain is SVG → PDF → PNG: PDF via svglib + reportlab (_render_pdf, #288), PNG via pypdfium2 + Pillow (_render_png) — both pure-wheel, no native cairo and permissively licensed (BSD/Apache/HPND, dual-license-clean). The unified Drawing.export(out, *, formats) → {format: path} is the front door; the legacy svg=/dxf= tuple form and export_pdf were removed in 0.5.0. This module sits below make_drawing.py, above _core.py.

    reproducible= — byte-identical exports by default. On, two exports of one drawing are identical, so a checked-in drawing diffs cleanly and a caller can see when its output really changed. Three things are settled to get there: the clock and GUIDs an exporter stamps (a per-document fixed metadata updater, avoiding ezdxf's concurrency-unsafe process-global testing option, plus reportlab's invariant), ezdxf's CLASSES section (built by iterating a set[str], so it is pre-seeded sorted), and the order the kernel hands parts over, which is not stable between runs and does not reduce to PYTHONHASHSEED.

    The two formats reach that by different routes, and the asymmetry is deliberate. A DXF must be ordered going in — ExportDXF writes an entity per element as it converts and the handles follow — so _elements(ordered=True) sorts the emitted boundary entities by geometry, keyed on where an edge sits and which way it runs (hidden-line removal emits reversed duplicate pairs that agree on everything else); faces are flattened before sorting so their cyclic wire start cannot leak into entity order, and cheap-key ties use exact B-rep bytes. An SVG is settled coming out, by canonicalize_svg sorting each all-leaf layer group in the written file, so it is handed its shapes unordered even when the flag is on.

    Canonical DXF ordering costs work; pass reproducible=False at build or export time when stable file bytes are unnecessary. The flag controls both ordering and metadata pinning. Weigh any change here against #602, which removed a zoom.extents walk from the same path.

  • repair.py — the deterministic lint→repair loop (#30 / ADR 5 (was 0002)): the re-place helpers (_find_dim/_replace_dim/_repair_*/repair_drawing) take the drawing duck-typed as dwg; Drawing.repair() stays a thin wrapper. Imports _core, audit, and registry.

  • _pmi_schema.py — OCCT dimension and geometric-tolerance type-code tables used by the AP242 extractor.

  • _pmi_datum_geometry.py — exact imported datum face attachment sites and oriented normals in the source or recognition frame.

  • _pmi_linear_geometry.py — proves authored linear reference stations and their principal projection before the PMI extractor lowers dimensions, including thickness wording.

  • _pmi_support_blockers.py — pure XCAF source-support and geometric-tolerance blocker policy, with direct-support completeness and exact Part21-overlay filters.

  • _pmi_topology.py — exact Part21 support resolvers that verify transferred faces and edges belong to the imported topology before PMI correlation, and planar-face normal and projected-witness evidence for linear PMI.

  • pmi.py — PMI (product manufacturing information) extraction from STEP AP242. Defines the public record and source-census types at their established import path, owns the XCAF source census, and overlays _pmi_part21 facts only after exact correspondence. It inventories the complete OCCT geometric-tolerance modifier vocabulary, preserves unsupported facts in the raw IR fallback, and exposes explicit blockers to typed lowering; XCAF and Part21 source identities survive both paths.

Architecture decisions

The five live records in docs/adr/ own every decision this map implements; each names the tests that guard it. This document is the module map only — where things live and what imports what, kept in step with tests/test_import_boundaries.py. It does not restate the decisions.