From f45a9ad34468691f46436eb17b7f9325342d5783 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 3 Sep 2026 07:31:52 +1200 Subject: [PATCH 01/38] Record owned root assembly successor --- docs/project/current-handover.md | 8 +- docs/project/status.md | 78 +-- docs/research/README.md | 4 + .../owned-root-assembly-investigation.md | 207 ++++++++ experiments/README.md | 6 + .../owned-root-assembly-successor/README.md | 452 ++++++++++++++++++ 6 files changed, 715 insertions(+), 40 deletions(-) create mode 100644 docs/research/owned-root-assembly-investigation.md create mode 100644 experiments/owned-root-assembly-successor/README.md diff --git a/docs/project/current-handover.md b/docs/project/current-handover.md index 82f9652..d42bc29 100644 --- a/docs/project/current-handover.md +++ b/docs/project/current-handover.md @@ -9,10 +9,10 @@ with live verification and navigation. The following values are expected last-known context and are explicitly untrusted until verified live: -- Checkout: `/home/ben/src/creature-kernel-worktrees/programmatic-root-complex-surface` -- Worktree: `/home/ben/src/creature-kernel-worktrees/programmatic-root-complex-surface` -- Branch: `codex/programmatic-root-complex-surface` -- Pull request: draft implementation PR #125 +- Checkout: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` +- Worktree: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` +- Branch: `codex/owned-root-assembly-successor` +- Pull request: none yet; successor-plan worktree is not a PR ## Live verification checklist diff --git a/docs/project/status.md b/docs/project/status.md index 28c44a6..3186289 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -18,42 +18,48 @@ This section is the sole current continuation source for the repository. Later status sections are reference history or task-specific state only; they may preserve evidence but do not redefine current continuation. -### Terminal investigation outcome - -The Ben-authorized, experiment-local, pre-Readiness-4 investigation of a -programmatic surface-domain/subdivision-cage representation is terminal for -its seven-ring candidate. Its bounded question was whether that -representation could produce a credible ribcage-waist-pelvis assembly with -readable neck, axilla, and hip/thigh-root boundaries, sufficient to justify -extending the representation. The recorded plan and outcome are in the -[programmatic root-complex surface investigation](../research/programmatic-root-complex-surface-investigation.md). - -The investigation consumes explicitly identified authored/prepared input only. -It introduces no production `GeometryRequest`/`GeometryResult` contract, no -production-core dependency, no claimed resolved graph, and no durable -domain/chart/cage identity. It cannot satisfy or replace the DR-0013 Stage 1 -proof. DR-0009 and DR-0010 remain parked; any promotion stops for the -appropriate decision record/canonical architecture work and Ben's approval. - -The scoped standard-neutral evidence exhausted exactly three frozen shared -correction rounds: round 1 fixed measured shoulder intersections, round 2 -improved axial taper and thigh seating, and round 3 applied a superior axial -saddle. Main-thread direct vision of the fixed front, side, and three-quarter -round-3 evidence found neck emergence and downward shoulder departure still -too weak; the arm ports continued to read in a broad superior shelf. Neutral -credibility failed, so exact-five, tail, and gallery expansion are blocked and -no fourth correction is allowed. - -Structural evidence nevertheless passed: 72 cage vertices and 63 quads, -1,053 level-2 vertices and 1,008 level-2 quads, level-1/level-2 intersection -counts `0/0`, and all five clearance ratios passing. This is a scoped rejection -of the seven-ring candidate, not formal Stage 1, not a global rejection of -programmatic or hybrid surfaces, and not authority to reactivate DR-0009, -DR-0010, or another parked workstream. - -The next retained-human action is Ben's disposition or a newly authorized -direction. There is no autonomous substitute checkpoint, exact-five -continuation, or parked-work reactivation under this runway. +### Owned root assembly successor + +The Ben-authorized, experiment-local successor is the bounded [owned root +assembly investigation](../research/owned-root-assembly-investigation.md). +It tests one welded standard-neutral root surface using exactly eight named, +nonempty domain interiors under the hard `<=8` cap, five open ports, at most +128 controls and 120 base quads, two subdivision levels, and at most two shared +correction rounds. Construction ownership, semantic causality, and +evaluated-surface contributor/chart lineage remain separate; every output must +be owned or have a declared junction or contributor record. + +The successor must use the authored `neck_upper` and `upper_abdomen` controls +and freeze its oriented interfaces, patch layout, port orientation, +extraordinary placement/valence, continuity, normal/fold bounds, subdivision +support, causality matrix, and locality perturbations before rendering. It +replaces the old port-span anatomy gates with candidate-specific checks for +neck exposure, shoulder descent, axillary concavity, pelvic wrap, and +downward thigh-root orientation. Direct skin and ownership diagnostics must +be renders of the same evaluated surface, and categorical colour cannot stand +in for causality. + +The plan remains non-executable until the required +`experiments/owned-root-assembly-successor/design-contract.md` freeze artifact +exists, has a recorded SHA-256 identity, and supplies all pre-build finite +complexity caps and candidate details required by the investigation. The +future builder must reject a missing or mismatched design-contract identity. + +Advance only through the documented bounded implementation and internal gates. +Do not add profile branches, hidden skin, render corrections, solvers, distal +body, tail, runtime/deformation, gallery, or exact-five work before credible +standard-neutral evidence. If the required cues remain unclear after the +initial implementation and two shared corrections, reject this candidate; +another representation requires a newly recorded runway rather than an +automatic fallback. + +The named human checkpoint is Ben's appraisal of the exact-five owned-root +assembly, but only after standard neutral passes the unchanged internal gates +and the exact-five evidence is generated. The checkpoint uses fixed front, +side, and three-quarter final-surface renders. Internal metrics and model +reviews do not substitute for Ben's visual judgment. The [terminal seven-ring +outcome](../research/programmatic-root-complex-surface-investigation.md#terminal-outcome-2026-09-03) +remains historical evidence and is not reactivated. ## Historical failed-candidate runway (2026-09-01) diff --git a/docs/research/README.md b/docs/research/README.md index 10a7310..50dd78c 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -25,6 +25,10 @@ hypotheses, references, and research context. Ben-authorized, experiment-local, pre-Readiness-4 terminal candidate outcome; it is non-normative, blocks exact-five continuation, and does not activate DR-0009/0010 or replace DR-0013 Stage 1 proof. +- [Owned root assembly investigation](owned-root-assembly-investigation.md) — a + planned, Ben-authorized, experiment-local successor direction using explicit + domain/junction ownership; it is non-normative and remains bounded by the + Active runway and the later exact-five human checkpoint. - [Numeric and frame profile experiment design](numeric-frame-profile-experiment.md) — planned and unregistered evidence for numeric admission, exact dyadic/ULP boundaries, deterministic normalization and offline half-chord derivation, diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md new file mode 100644 index 0000000..b20947f --- /dev/null +++ b/docs/research/owned-root-assembly-investigation.md @@ -0,0 +1,207 @@ +# Owned root assembly investigation + +Status: Settled candidate plan; Ben-authorized bounded investigation; +experiment-local and non-normative + +This is the settled successor plan after the terminal seven-ring candidate in +the [programmatic root-complex investigation](programmatic-root-complex-surface-investigation.md). +It does not define product behaviour, a production surface contract, canonical +Regions or Sockets, a permanent topology, or a backend. It cannot satisfy or +replace the DR-0013 Stage 1 proof. DR-0009 and DR-0010 remain parked. + +## Research-question mapping + +This unregistered exploratory experiment targets four canonical questions: + +- `RQ-002`: whether the result reads as an intentional stylized creature + character rather than an articulated blob; +- `RQ-012`: whether semantic fields, local coordinates, and part identity can + remain explicit through construction and evaluation; +- `RQ-020`: whether an owned multi-chart welded surface is useful evidence for + the still-open initial-surface representation choice; and +- `RQ-021`: whether the method can produce useful shoulder, hip, and branch + junctions without a base mesh. + +All four questions remain `Open` in the canonical [open-questions +registry](open-questions.md). This plan and any resulting evidence do not +change their lifecycle automatically. + +## Question and bounded outcome + +Can a single welded standard-neutral root surface make anatomical ownership +visible enough that the neck, shoulder/axilla, pelvis, and hip/thigh-root +transitions read as one intentionally constructed simplified humanoid form? + +The candidate is successful only if fixed front, side, and three-quarter views +show all of these cues: + +- a clear neck stem emerging from the thorax; +- shoulders departing below the neck rather than forming a superior shelf; +- readable axillary hollows and arm ports; +- a pelvis that wraps over each hip/thigh root; and +- thighs descending from beneath the pelvis rather than appearing as external + bulbs. + +These are bounded visual criteria for this investigation, not a product anatomy +promise. Structural metrics can reject a broken artifact, but they cannot +accept anatomical readability; direct main-thread vision remains authoritative. + +## Settled candidate + +Build one welded subdivision cage for the ribcage, neck root, +abdomen/lumbar bridge, pelvis, bilateral shoulder/axilla roots, and bilateral +hip roots. This candidate uses exactly eight named, nonempty experiment-local +domain interiors while retaining a hard cap of no more than eight: + +1. thorax; +2. neck root; +3. abdomen/lumbar bridge; +4. pelvis; +5. left shoulder/axilla root; +6. right shoulder/axilla root; +7. left hip root; and +8. right hip root. + +The candidate has five open ports: neck, left arm, right arm, left thigh, and +right thigh. Freeze one profile-independent topology with at most 128 controls +and 120 base quads, two subdivision levels, oriented port boundaries, and +declared interface cardinality before rendering. Use existing authored +`neck_upper` and `upper_abdomen` controls. The exact topology, chart degrees, +port orientations, extraordinary placement and valence, continuity tolerances, +normal/fold bounds, and subdivision support are candidate inputs to freeze +before coordinates or images are judged. + +Each domain owns its interior faces and controls. Each shared boundary is +represented once by a named junction owned by its incident domains; there are +no overlapping skins that merely happen to coincide. Domains, charts, ports, +and junctions are ephemeral experiment records, not canonical anatomy IDs. +The frozen design must enumerate every base face and control owner, every +junction adjacency and its incident domains, and every domain's nonempty +interior. It rejects any domain interior that crosses a required neck, +shoulder/axilla, abdomen/thorax, abdomen/pelvis, or pelvis/hip anatomical +boundary instead of representing that boundary through a declared junction. + +## Three distinct layers + +Keep these responsibilities separate and test them separately: + +1. **Construction ownership** assigns every base face, interior control, and + shared junction boundary to exactly one domain or declared junction. +2. **Semantic causality** carries authored addresses and roles through derived + parameters, bindings, and subdivision stencils to the generated controls + and evaluated vertices. +3. **Evaluated-surface lineage** records the domain/chart contributors and + local coordinates of the actual evaluated surface, including legitimate + multi-domain junction contribution. + +Every output control and evaluated vertex must be owned or have a declared +junction/contributor record. A categorical ownership-colour view may help a +human inspect lineage, but colour must never stand in for causality, +ownership, or geometry evidence. Direct skin and ownership diagnostics must +render the same evaluated surface; there is no hidden second skin or +render-only correction. + +## Required design contract + +Before any executable build exists, create +`experiments/owned-root-assembly-successor/design-contract.md` as the sole +freeze artifact for the candidate design. It is intentionally not created by +this plan-writing change. Once created, its exact raw bytes receive a recorded +SHA-256 identity, and the future builder must require that identity and reject +a missing file or any mismatch before admitting inputs or producing output. +This investigation remains explicitly non-executable until that record and its +identity exist. + +The design contract must freeze every item in the preflight below. It must also +set finite caps for total junction count and interface cardinality; chart, +formula, and dependency counts; candidate special cases; and non-test +implementation and test LOC. This plan intentionally does not invent those +numeric values. + +## Frozen preflight and evidence gates + +Before geometry rendering, freeze the standard-neutral inputs, oriented +interface curves and cardinality, patch layout and degree, port orientation, +extraordinary placement/valence, positional continuity, evaluated normal/fold +bounds, declared subdivision rule/support, causality matrix, and locality +perturbations. The candidate-specific anatomy measurements replace the old +misleading port-span gates: + +- neck exposure and neck-stem emergence; +- shoulder descent below the neck; +- axillary concavity; +- pelvic wrap over each hip root; and +- downward thigh-root orientation. + +The implementation must then prove, on the same evaluated surface: + +- no unowned controls or faces and no duplicate hidden surface; +- every declared geometry-driving input has a downstream binding; +- each must-affect baseline-versus-perturbed run moves actual in-target + evaluated vertex coordinates by at least its frozen scale-relative minimum, + and the final mesh bytes serialize those changed coordinates; +- off-target evaluated coordinates remain within their frozen locality bound; +- metadata, provenance, dependency, or manifest movement without the required + evaluated-coordinate and final-mesh movement fails the must-affect gate; +- shared boundaries are welded with bounded positional and normal/fold + behaviour; +- ports, manifold topology, winding, degeneracy, clearances, and bounded + self-intersection checks pass at the cage and both subdivision levels; and +- fresh-process output is byte-identical under the pinned launcher and two + hash seeds. + +The structural checks are necessary gates and evidence, not an aggregate visual +score. The fixed neutral views are inspected by the main thread before any +profile expansion. + +## Execution order and stop rule + +The next implementation work proceeds in this order: + +1. audit the terminal candidate's utilities for representation-independent + reuse; +2. create and SHA-256-bind the required design contract, freezing the + successor's neutral topology, interfaces, dependencies, finite complexity + caps, tolerances, and evidence views; +3. implement the bounded owned-domain/junction cage and the three-layer + records; +4. run ownership, causality, locality, topology, geometry, determinism, and + same-surface rendering checks; +5. inspect the fixed standard-neutral views in the main thread; and +6. only if neutral credibility passes, apply the unchanged candidate to the + exact-five profile order and complete the required evidence. + +The exact-five order is `standard_neutral_reference`, +`compact_broad_short_limb_large_head`, `tall_narrow_long_legged`, +`slender_long_limb`, and `stocky_broad_chested`. This order is an evidence +fixture, not a supported morphology promise. + +Allow the initial implementation plus at most two shared correction rounds. +If the visual cues remain unclear, a gate fails, ownership is ambiguous, or a +correction requires a profile branch, hidden surface, render offset, solver, +global remeshing, or unclear junction ownership, reject this candidate. Do not +fall back automatically to another representation; a different representation +requires a newly recorded runway and human authorization. + +The named human checkpoint is Ben's appraisal of the exact-five owned-root +assembly, using fixed front, side, and three-quarter final-surface renders, +only after the standard neutral passes the unchanged internal gates and the +exact-five evidence is generated. No internal metric, model review, or +standard-neutral result substitutes for that checkpoint. + +## Reuse, exclusions, and authority + +Reuse only representation-independent utilities after a focused audit and +independent tests. Archive or reimplement the seven-ring topology, ring and +branch formulas, correction macros, candidate IDs and thresholds, and +anatomy-specific tests by default. Do not transplant its ownership model just +because its mesh checks passed. + +This plan excludes distal anatomy, tail work, exact-five generation before +neutral credibility, gallery work before viable evidence, rigging, weights, +shared pose, deformation, simulation, packaging, Godot or other engine work, +production dependencies, and activation of parked decision records. Generated +meshes, captures, caches, and other large binaries remain outside Git under the +existing artifact policy. The implementation, if authorized by this runway, +stays under `experiments/`; this research record remains evidence and +direction context only. diff --git a/experiments/README.md b/experiments/README.md index d865425..dd3dcf8 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -111,6 +111,12 @@ candidate-local frozen contract, neutral-first visual checkpoint, and experiment-local launcher are not product, Stage 1, production, or formal surface-comparison authority. +The [owned root assembly successor](owned-root-assembly-successor/README.md) +is the unregistered exploratory successor targeting open `RQ-002`, `RQ-012`, +`RQ-020`, and `RQ-021`. It is not `EXP-0001`, remains non-executable until its +required SHA-256-bound design contract exists, and cannot establish a formal +technology outcome, production surface contract, or Stage 1 result. + ## Artifact policy Large meshes, caches, videos, captures, and datasets must not be committed until diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md new file mode 100644 index 0000000..7d55000 --- /dev/null +++ b/experiments/owned-root-assembly-successor/README.md @@ -0,0 +1,452 @@ +# Owned root assembly successor + +Status: bounded experiment-local successor plan; non-normative + +Experiment lifecycle: planned + +Evidence closure: open + +Technology outcome: none + +Owner: Creature Kernel main Sol thread; Ben retains direction and acceptance + +Date started: 2026-09-03 + +Date completed: — + +Research questions: canonical open `RQ-002`, `RQ-012`, `RQ-020`, and `RQ-021` +in the [open-questions registry](../../docs/research/open-questions.md). This +experiment does not change their lifecycle. + +Related DRs: DR-0013 context only; DR-0009 and DR-0010 remain parked + +## Status and authority + +This is a draft contract for one new, bounded, standard-neutral experiment. It +is the successor direction authorized after the seven-ring candidate in PR +#125 reached its three-round stop rule. It does not accept a production +schema, architecture, topology, supported morphology promise, or technology +outcome. It does not reactivate a parked workstream or satisfy the DR-0013 +Stage 1 proof. + +The previous candidate is evidence, not a foundation to transplant. Its +seven-ring topology, projection, formulas, macros, IDs, thresholds, and +anatomy-specific tests are archive/reimplementation candidates under the +ledger below. Representation-independent utilities may be reused only after +the focused audit required here. + +## Protocol + +This is an unregistered exploratory experiment. No comparative, accounting, +or external-review protocol is activated. The generic experiment workflow +still applies: provenance, a falsifiable question, reproducible inputs and +commands, evidence, limitations, and decision impact must be recorded. +It is not `EXP-0001`. + +## Question + +Can a single welded surface assembled from explicit, interacting anatomical +domains produce a credible standard-neutral ribcage-to-pelvis root complex +with a readable neck, shoulder/axilla junctions, and hip/thigh roots, without +any layer silently bypassing or rewriting another? + +This is a representation-direction question. It is not a claim that the +result is a complete humanoid, an animation-ready body, a runtime skeleton, +or a production geometry backend. + +## Hypothesis + +Giving thorax, neck root, abdomen/lumbar bridge, pelvis, bilateral +shoulder/axilla roots, and bilateral hip roots explicit surface ownership, +local charts, and shared welded junctions will make the causal path from +authored anatomy to evaluated skin inspectable and will produce clearer root +anatomy than the failed single axial ring grammar. + +The hypothesis fails if the candidate needs unowned geometry, duplicated or +hidden skin, render-only corrections, profile-specific geometry, a solver, or +more than the allowed shared correction rounds to make the neutral result +credible. + +## Decision impact + +A credible neutral result, after all technical gates, permits an unchanged +exact-five profile run and a later human checkpoint about whether this +representation is worth extending. It does not approve production use. + +An uncured neutral failure rejects this candidate. It does not reject +programmatic or hybrid surfaces globally. A materially different +representation then requires a new recorded runway and direction; this +experiment does not silently fall back to another approach. + +## Inputs and source authority + +The first and only execution target in this plan is the standard-neutral +profile. The exact source inputs are: + +1. `examples/body-documents/stylized-digitigrade-biped-authored-form.json` + — authoritative authored anatomy source at frozen-plan hash + `d4f0dad6f936d62f9ee8c0fa24701898ee4ae6e48bcdeaf44641bd4dc3b549de`. +2. `experiments/current-form-surface-preview/structural_profile_candidates.json` + — supporting source for the existing profile identity and its + standard-neutral selection, at frozen-plan hash + `6794c7ec273cdbdc66e5bbe1f4816237a45f60a086315e40e0ef4ce6d18ddc0a`. + +The authored document owns the source addresses, roles, frames, landmarks, +section measurements, module state, and provenance. The profile table may +identify the standard-neutral source selection and later the existing ordered +five-profile comparison; it must never select topology or geometry code. +Before execution, the launcher records both source hashes and stops on source +drift rather than silently using a new input. + +The prepared input may contain only source-derived frames, named landmarks, +section measurements, derived scalar parameters, module state, and provenance. +It must include the existing authored `neck_upper` and `upper_abdomen` controls +where their source roles are relevant. It must not contain finished vertices, +faces, edges, connectivity, a perimeter, point cloud, field, mask, silhouette, +corrective offset, serialized prior output, or anything trivially reindexed +into the candidate cage. + +There is no random seed: randomness is forbidden. No profile ID may reach +geometry logic. No tail, distal body, exact-five expansion, deformation, +runtime, engine, or gallery input is part of the initial neutral run. + +## Ephemeral experiment interfaces + +The following are conceptual boundaries for this experiment only. They are not +serialized production schemas, canonical identifiers, or additions to +`spec/`: + +- **Prepared intent**: admitted source addresses and roles, frames, landmarks, + section measurements, module state, and provenance. +- **Domain plan**: one owner for each domain interior and its local chart, + including declared boundary participation. +- **Junction plan**: the shared boundary between incident domains, its ordered + interface curve, port relationship, and continuity obligations. +- **Causal binding**: source address/role to derived parameter, control, + subdivision stencil, and evaluated-surface lineage. +- **Surface artifact**: one welded control/evaluated surface with ephemeral + domain, junction, port, chart, contributor, and diagnostic metadata. + +The construction layer owns base faces, domain interiors, and junction +construction. The semantic layer carries causality from authored addresses and +roles through derived parameters and subdivision stencils. The evaluated +surface carries contributor and chart lineage, which may name multiple +domains. These layers may reference one another through explicit bindings but +may not silently replace one another. + +Every base face and control has exactly one construction owner: a domain +interior or a declared junction. Every shared junction boundary is represented +once in the welded surface and records all incident domains. Every evaluated +surface element has valid contributor/chart lineage. There is no unowned +output. A categorical colour or legend may expose lineage in a diagnostic, +but it is never evidence of causality by itself. + +## Fixed scope and hard caps + +The standard-neutral root surface contains five open anatomy ports: neck, +left arm, right arm, left thigh, and right thigh. This candidate uses exactly +eight named, nonempty domain interiors while retaining the hard `<=8` cap: + +- thorax; +- neck root; +- abdomen/lumbar bridge; +- pelvis; +- left shoulder/axilla root; +- right shoulder/axilla root; +- left hip root; and +- right hip root. + +The hard experiment caps are fixed before the design pass: + +- at most 8 explicit domains; +- exactly 5 declared open ports for the neutral root surface; +- at most 128 base controls and 120 base quads; +- exactly 2 declared subdivision levels; +- at most 2 shared correction rounds after the initial build. + +These are caps, not a chosen topology. The experiment must not claim an exact +control count, boundary cardinality, patch degree, extraordinary-vertex +placement, or coordinate layout until the bounded design pass below freezes +those details. All eight named domain interiors must be nonempty. If the +design cannot satisfy the caps and ownership rules, it stops before +coordinates are authored. + +## Freeze-before-build obligations + +One bounded design pass must create +`experiments/owned-root-assembly-successor/design-contract.md`. That required +freeze artifact does not exist yet and must not be created as part of this +plan-review correction. Its exact raw bytes must receive a recorded SHA-256 +identity. The future builder must require the expected identity, hash the file +before admitting source inputs, and reject a missing file or mismatch without +producing an artifact. This plan is non-executable until the file and recorded +identity exist. + +The design contract must freeze all details needed to make the candidate +reproducible without inventing them during coding: + +- all eight named, nonempty domain interiors and their required anatomical + boundaries; +- the owner of every base face and control; +- every junction adjacency and the complete set of incident domains; +- the oriented ordered interface curves and their cardinalities; +- the patch layout, degree, and welded shared-boundary representation; +- the orientation and semantic role of each of the five ports; +- extraordinary-vertex locations and permitted valences, with extraordinary + points kept away from critical silhouettes where the design allows; +- positional continuity at every shared boundary and port; +- evaluated normal-angle and fold bounds; +- the fixed subdivision rule and its declared support/stencil behaviour; +- candidate-specific measures for neck exposure, shoulder descent, axillary + concavity, pelvic wrap, and downward thigh-root orientation; +- the must-affect perturbations and off-target locality expectations; and +- the exact preflight, build, artifact, and comparison commands. + +It must reject any domain interior that crosses a required anatomical boundary +instead of meeting another domain through a declared junction. It must also +set finite caps for total junction count and interface cardinality; chart, +formula, and dependency counts; candidate special cases; and non-test +implementation and test LOC. Numeric values are deliberately not selected in +this README; the design contract must freeze them before build. + +This pass freezes obligations and measurable tolerances before geometry +coordinates or visual tuning. It must not smuggle in arbitrary anatomy +thresholds, profile-shaped coordinates, or a production contract. The failed +candidate's old port-span anatomy gates are not reused as a substitute for the +new candidate-specific measures. Numeric tolerances are recorded with their +units and rationale before the build; human visual criteria remain +authoritative for anatomical readability. + +## Topology and junction requirements + +The candidate is one connected, orientable, welded surface with the five +declared open ports. It must have no duplicate overlapping skin pieces, +unowned faces, seam-only contacts, accidental holes, or topology selected by a +profile. Every boundary and junction is explicit in the design record. + +The junction network must make these relationships inspectable: + +- a neck-root junction that exposes a neck stem rather than a mound in the + thorax; +- shoulder/axilla junctions whose shoulders depart below the neck and leave a + readable axillary hollow around each arm port; +- an abdomen/lumbar bridge between thorax and pelvis rather than one universal + torso ring progression; and +- hip-root junctions where each pelvis wraps over and seats the thigh root, + with the thighs descending from beneath the pelvis. + +Shared boundaries use the same control curve, not two surfaces made to +coincide. The candidate must report positional continuity and the frozen +normal/fold measures. It must not claim mathematical C1 or G1 continuity at +extraordinary vertices or open ports without a separate proof. + +## Causality and ownership requirements + +Before rendering, a preflight must prove: + +1. Every admitted geometry-driving source address, role, landmark, frame, + section measure, module-state input, and shared scalar has a downstream + causal consumer or is explicitly classified as non-geometric. +2. Every domain interior, junction, port, base face, and control has exactly + one construction owner. +3. Every evaluated element carries contributor/chart lineage, including + multi-domain junction contributions where applicable. +4. Each must-affect definition names a baseline, perturbation, in-target + evaluated-vertex set, scale `S`, frozen minimum movement relative to `S`, + off-target set, and frozen locality tolerance. +5. A fresh baseline-versus-perturbed build must move actual in-target evaluated + vertex coordinates by at least that scale-relative minimum, and the final + mesh bytes must differ by serializing those changed coordinates. +6. Off-target evaluated vertex coordinates remain within their frozen locality + tolerance. +7. Metadata, provenance, dependency, manifest, or ownership-label movement + without the required evaluated-coordinate and final-mesh movement fails. +8. Topology, IDs, formulas, and ownership remain unchanged under admitted + perturbations. +9. The renderer consumes the evaluated surface and its lineage; it cannot + add geometry, alter vertices, or use a second hidden skin. + +Provenance is not proof of effect. A listed dependency with no geometric +effect fails the must-affect gate. Conversely, a contributor label without a +causal binding is not accepted as an explanation. + +## Preflight and build order + +The eventual implementation must follow this order and stop at the first +failed gate: + +1. Verify worktree, source paths, source hashes, pinned launcher, and the + standard-neutral-only scope. +2. Create and SHA-256-bind the required design contract; no later build may + choose an omitted topology, ownership, cap, tolerance, or evidence rule. +3. Admit and validate the prepared intent, including provenance and the + required `neck_upper` and `upper_abdomen` source controls. +4. Build the domain, junction, port, and chart ownership plan; prove complete + coverage and a single shared boundary representation. +5. Build the causal binding plan from source roles through derived parameters, + controls, subdivision support, and evaluated lineage. +6. Run symbolic topology and ownership preflight before admitting anatomy + coordinates; reject profile-selected layout, duplicated boundaries, or + unowned output. +7. Derive one welded control surface from the admitted intent using shared + rules. No render correction, solver, optimizer, remesher, or post-generation + edit is permitted. +8. Evaluate exactly the frozen subdivision support for two levels, retaining + the base and intermediate diagnostics. +9. Run structural, geometric, causality, locality, and determinism gates; + produce the direct-skin and same-surface ownership evidence. +10. Run the fixed neutral visual appraisal. Only a credible neutral result + unlocks the exact-five gate. + +## Structural and geometric gates + +The following gates apply to the actual welded evaluated surface and its base +construction, not to a synthetic diagnostic object: + +- all values are finite and the surface is connected, orientable, and a valid + welded quad surface with exactly the five declared ports; +- control/quadrilateral counts remain within the fixed caps and all topology, + junction, port, and extraordinary rules match the frozen design; +- no face, edge, boundary, or control is unowned or duplicated; +- shared junctions satisfy the frozen positional continuity and normal/fold + bounds; +- no degenerate edges/faces, invalid winding, accidental holes, or + non-adjacent self-intersections exist at either evaluated level; +- the five ports preserve their frozen orientation and remain usable after + subdivision; +- neck, both axillae, groin, and both medial-thigh clearances remain positive + under the candidate-specific geometric measures; +- candidate-specific measures report neck exposure, shoulder descent, + axillary concavity, pelvic wrap, and downward thigh-root orientation + independently; and +- all must-affect/locality, forbidden-input, profile-neutrality, and + deterministic-artifact checks pass. + +Clearance and continuity thresholds are not invented in this plan. The design +pass must freeze them before coordinates and record each independently; one +aggregate score is forbidden. Human vision decides whether positive geometry +actually reads as anatomy. + +## Visual evidence and checkpoint + +Render the direct skin from the same evaluated surface for fixed front, side, +and three-quarter views. The ownership/contributor diagnostic must reuse those +same evaluated positions and topology; it may add a transparent legend or +lineage overlay but may not render a hidden structural substitute. + +The neutral internal visual gate looks for a clear neck stem, shoulders +departing below it, arm ports below that departure, visible axillary hollows, +pelvis wrapping over the hip roots, and thighs descending from beneath the +pelvis. It also records whether the thorax, abdomen/lumbar bridge, and pelvis +read as deliberate connected regions rather than primitive blobs or a single +ring-shaped mass. This is scoped evidence, not an aggregate aesthetic score. + +No gallery or human-facing checkpoint is created before the neutral result is +credible and the required technical evidence exists. A later exact-five +gallery, if unlocked, must show direct final skin and the same-surface lineage +diagnostic; an x-ray-like picture must not imply an underlying structure that +was not rendered. + +## Deterministic artifact policy + +The implementation must use the repository's pinned experiment launcher and a +fresh temporary output directory for every run. It must record the exact +interpreter/environment identity, source hashes, design-contract identity, +and artifact hashes. Generated meshes, captures, caches, and renders remain +outside Git unless a storage decision is accepted. + +Two fresh launcher processes with different `PYTHONHASHSEED` values must +produce byte-identical prepared input, base and evaluated mesh artifacts, +lineage/dependency and metrics manifests, and metadata-free visual evidence. +Paths, timestamps, host-specific display data, and temporary-directory names +must not affect identity. A failed or partial publication must not be mistaken +for evidence. + +The eventual README revision that activates execution must provide the exact +copy-paste reproduction command and list all raw outputs. This plan remains +non-executable until that command and the freeze-before-build record exist. + +## Correction stop + +The initial implementation is followed by at most two shared correction +rounds. A round is one coherent, review-triggered change to already-frozen +shared construction formulas or tunables, applied consistently to both sides +and all relevant domains, followed by full regeneration and inspection. + +A correction may not change the patch layout, port cardinality, topology, +ownership model, source admission, subdivision rule, gates, or scope. Such a +change is a new candidate and requires a new runway; it cannot be hidden as a +third correction. Render-only offsets, profile branches, duplicated skin, +solver behaviour, and threshold relaxation are immediate stop conditions. + +If the neck, shoulder/axilla, and hip/thigh-root visual criteria are not +credible after the initial build plus two shared corrections, mark this +candidate rejected/inconclusive in its eventual evidence record, archive it, +and stop. Do not run exact-five, add a tail, build distal anatomy, or continue +parameter tuning. + +## Exact-five gate + +Exact-five is a later unchanged-rule gate, not part of the initial neutral +implementation. It may run only when: + +1. the neutral design and all structural, geometric, causality, locality, and + deterministic gates pass; +2. main-thread vision finds the required neck, shoulder/axilla, pelvic-wrap, + and thigh-root cues credible; and +3. the exact five existing profile identities are selected only as admitted + data, in this order, with the standard reference first: + `standard_neutral_reference`, + `compact_broad_short_limb_large_head`, + `tall_narrow_long_legged`, `slender_long_limb`, and + `stocky_broad_chested`. + +The five profiles use the same domain plan, topology, junction rules, +causality rules, subdivision support, gates, and renderer. No profile-specific +geometry or topology is permitted. A tail-present/tail-absent case is not +part of this gate; optional-module absence requires a separately derived, +explicitly authorized input and must not create phantom identities. + +## Reuse and archive ledger + +Reuse is conditional, not inherited from PR #125. The main thread audits each +candidate against representation-independent inputs, consumers, assumptions, +independent tests, and maintenance cost before retaining it. + +| Candidate asset or idea | Starting disposition | Reuse condition or archive reason | +| --- | --- | --- | +| Authored body document, source provenance, frames, landmarks, and existing profile identities | Adapt | Keep as input evidence only; preserve source ownership and prevent profile ID from entering geometry. | +| Non-adjacent triangle intersection validator | Reuse after audit | Keep only if its interface is mesh-representation-independent, fail-closed, bounded, and independently tested. | +| Generic subdivision evaluator | Reuse after audit | Keep only the rule-independent evaluator pieces whose support and boundary behaviour can be tested without seven-ring IDs or formulas. | +| Generic mesh export, metadata-free rendering, hashing, and temporary-output utilities | Reuse after audit | Retain only generic functions with independent tests; no candidate-specific anatomy or hidden geometry. | +| Launcher and pinned-environment plumbing | Adapt | Reuse the required sibling-launcher contract and explicit failure behaviour; do not add interpreter fallbacks. | +| Prepared-input admission and provenance helpers | Adapt or reimplement | Retain only after rejecting unknown/empty provenance and forbidden final-geometry inputs; test the successor's admitted fields directly. | +| Seven-ring topology, axial projection, shoulder/seat/envelope/saddle formulas, pelvic macro, control IDs, and thresholds | Archive/reimplement | They encode the failed candidate's ownership and layout; they are not a successor foundation. | +| Seven-ring anatomy-specific tests and candidate-specific clearance loops | Archive/reimplement | Replace with representation-independent invariants plus successor-owned junction, causality, and candidate-specific measures. | +| Prior candidate publisher/gallery and x-ray-style diagnostics | Archive | No gallery before credible neutral; diagnostics must render the same evaluated surface. Reimplement only small generic UI behaviour later. | +| Prior generated meshes, captures, caches, manifests, and profile fixtures | Archive as evidence | Keep hashes and provenance in the failed-candidate record; do not treat outputs as successor inputs or commit large binaries. | + +An item may be retained only when it has no seven-ring/profile assumptions, +has an isolated interface, has independent tests for the successor use, and +has lower maintenance risk than a small reimplementation. The ledger itself +does not authorize promotion into production code or canonical architecture. + +## Results, limitations, and conclusion + +No result exists yet. Until execution, lifecycle remains `planned`, evidence +closure remains `open`, and technology outcome remains `none`. + +The trial is limited to one standard-neutral root assembly. It does not test +the exact-five profiles, optional modules, tails, hands, feet, faces, distal +anatomy, posing, skeleton runtime, deformation, simulation, engine adapters, +or production packaging. A positive result would only justify the next +recorded investigation and human checkpoint. + +## Recommended follow-up + +Complete the one bounded design pass and record its frozen interface curves, +patch/junction layout, port orientations, subdivision support, continuity and +fold measures, candidate-specific geometric measures, causal perturbations, +and exact reproduction command. Then implement only the standard-neutral +candidate within this contract. Do not edit canonical specifications or +production architecture as part of this experiment. From aa7e66ed4385104b92705472ad76d34d3d37b614 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 3 Sep 2026 08:20:34 +1200 Subject: [PATCH 02/38] Resolve root-complex review correctness gaps --- .../README.md | 4 +- .../build_root_complex.py | 8 +-- .../prepared_projection.py | 2 +- .../render_export.py | 4 +- .../root_complex_surface.py | 2 +- .../tests/test_prepared_projection.py | 9 +-- .../tests/test_render_export.py | 58 ++++++++++--------- .../tests/test_root_complex_surface.py | 8 ++- 8 files changed, 47 insertions(+), 48 deletions(-) diff --git a/experiments/programmatic-root-complex-surface/README.md b/experiments/programmatic-root-complex-surface/README.md index 6bf62cd..ff78c9f 100644 --- a/experiments/programmatic-root-complex-surface/README.md +++ b/experiments/programmatic-root-complex-surface/README.md @@ -289,8 +289,8 @@ the listed scale-relative thresholds: - neck: `min(span_L(neck), span_F(neck)) >= 0.030 S`; - each axilla: `min(span_U(arm), span_F(arm)) >= 0.025 S`; -- groin: signed `L` separation of the first right and left thigh samples - `>= 0.020 S`; and +- groin: signed `L` separation of the right thigh loop's minimum and the left + thigh loop's maximum `L` projections (`min(right) - max(left)`) `>= 0.020 S`; and - medial thigh: minimum signed `L` separation across right-versus-left thigh loop samples `>= 0.025 S`. diff --git a/experiments/programmatic-root-complex-surface/build_root_complex.py b/experiments/programmatic-root-complex-surface/build_root_complex.py index df15bcc..234fbcb 100644 --- a/experiments/programmatic-root-complex-surface/build_root_complex.py +++ b/experiments/programmatic-root-complex-surface/build_root_complex.py @@ -30,8 +30,8 @@ def build(source: str | Path, output_dir: str | Path) -> Path: raise FileExistsError(f"output directory must be new and have an existing parent: {target}") stage = Path(tempfile.mkdtemp(prefix=f".{target.name}.staging-", dir=target.parent)) try: - prepared = prepare_standard_neutral(source) - evaluated = surface.evaluate(prepared, levels=2) + prepared = prepare_standard_neutral(source); evaluated = surface.evaluate(prepared, levels=2); intersection_counts = tuple(evaluated.intersection_counts) + if any(intersection_counts): raise ValueError("refusing publication with nonzero evaluated intersections") final, cage = evaluated.levels[-1], evaluated.cage (stage / "prepared.json").write_bytes(canonical_json_bytes(prepared)) render_export.write_skin_ply(stage / "skin.ply", final.vertices, final.quads) @@ -39,14 +39,12 @@ def build(source: str | Path, output_dir: str | Path) -> Path: render_export.render_cage_png(stage / "cage.png", cage.vertices, cage.quads) files = {name: _sha256(stage / name) for name in ("prepared.json", "skin.ply", "skin.png", "cage.png")} scale = surface.validate_geometry(final, evaluated=True) - intersection_counts = tuple(evaluated.intersection_counts) metrics = {"schema": "programmatic-root-complex.metrics.v1", "level": 2, "scale": scale, "cage_vertices": len(cage.vertices), "cage_quads": len(cage.quads), "skin_vertices": len(final.vertices), "skin_quads": len(final.quads), "intersection_status": "zero" if not any(intersection_counts) else "nonzero", "intersection_count": sum(intersection_counts), "intersection_counts_by_level": intersection_counts, - "clearance_ratios": dict(evaluated.clearance_ratios), "files": files} - (stage / "metrics.json").write_bytes(canonical_json_bytes(metrics)) + "clearance_ratios": dict(evaluated.clearance_ratios), "files": files}; (stage / "metrics.json").write_bytes(canonical_json_bytes(metrics)) files["metrics.json"] = _sha256(stage / "metrics.json") manifest = {"schema": "programmatic-root-complex.manifest.v1", "source_sha256": prepared["source"]["sha256"], "files": files} (stage / "manifest.json").write_bytes(canonical_json_bytes(manifest)) diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index 46611ef..1b2f018 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -46,7 +46,7 @@ def _addr(value, where): def _pick(rows, owner, role, fields, name): hits = [] for i, raw in enumerate(rows): - where, row = f"body.{name}[{i}]", _dict(raw, f"body.{name}[{i}]"); key = "owner" if "owner" in row else "address" + where, row = f"body.{name}[{i}]", _dict(raw, f"body.{name}[{i}]"); key = "owner" if "owner" in row else "address"; _ok(key in row, where, "missing record selector") if _addr(row[key], f"{where}.{key}") == owner and row.get("role", owner[3]) == role: hits.append((row, where)) _ok(len(hits) == 1, f"body.{name}.{role}", "missing or duplicate required record"); row, where = hits[0] _ok(set(row) == fields, where, "unknown or missing required field"); return row, where diff --git a/experiments/programmatic-root-complex-surface/render_export.py b/experiments/programmatic-root-complex-surface/render_export.py index 6c1bd4d..72fcf45 100644 --- a/experiments/programmatic-root-complex-surface/render_export.py +++ b/experiments/programmatic-root-complex-surface/render_export.py @@ -80,6 +80,7 @@ def write_skin_ply(path: str | Path, vertices: object, quads: object) -> None: def _frames(points: np.ndarray) -> tuple[list[np.ndarray], list[np.ndarray], float]: + coordinate_bound = float(np.max(np.abs(points))); points = points / coordinate_bound if coordinate_bound > np.finfo(np.float64).max / 4.0 else points cameras = [points @ basis.T for basis in _VIEW_BASES] if not all(np.isfinite(camera).all() for camera in cameras): raise ValueError("projected coordinates must be finite") @@ -120,11 +121,12 @@ def _rasterize_triangle(pixels: np.ndarray, depth: np.ndarray, camera: np.ndarra def _skin_png_bytes(points: np.ndarray, triangles: np.ndarray) -> bytes: cameras, centres, scale = _frames(points) + coordinate_bound = float(np.max(np.abs(points))); lighting_points = points / coordinate_bound if coordinate_bound > np.finfo(np.float64).max / 4.0 else points pixels = np.full((CANVAS_SIZE[1], CANVAS_SIZE[0], 3), _BACKGROUND, dtype=np.uint8) for panel, camera in enumerate(cameras): depth = np.full((CANVAS_SIZE[1], CANVAS_SIZE[0]), -np.inf, dtype=np.float64) for triangle in triangles: - normal = np.cross(points[triangle[1]] - points[triangle[0]], points[triangle[2]] - points[triangle[0]]) + normal = np.cross(lighting_points[triangle[1]] - lighting_points[triangle[0]], lighting_points[triangle[2]] - lighting_points[triangle[0]]) length = float(np.linalg.norm(normal)) brightness = 0.38 if length == 0.0 else 0.38 + 0.62 * max(0.0, float(np.dot(normal / length, _LIGHT))) colour = tuple(int(round(channel * brightness)) for channel in _BASE_COLOUR) diff --git a/experiments/programmatic-root-complex-surface/root_complex_surface.py b/experiments/programmatic-root-complex-surface/root_complex_surface.py index eff0576..82a9457 100644 --- a/experiments/programmatic-root-complex-surface/root_complex_surface.py +++ b/experiments/programmatic-root-complex-surface/root_complex_surface.py @@ -567,7 +567,7 @@ def evaluate(prepared, levels=2): pairs = mesh_correctness.validate_triangle_intersections( current.vertices, current.triangles, scale) intersection_counts.append(len(pairs)) - if level == 2: + if level == levels: values = mesh_correctness.validate_boundary_clearances( current.vertices, dict(current.boundary_loops), {"L": lateral, "U": up, "F": forward}, scale) diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index 4345163..d0fbc00 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -73,17 +73,12 @@ def test_required_source_shape_and_routes_fail_closed(self): self.assert_rejected(lambda source: source["body"]["dimensions"][6].__setitem__("value", 0)) self.assert_rejected(lambda source: source["body"]["landmarks"][15].__setitem__("position", [0, 0, 0])) self.assert_rejected(lambda source: source["body"]["landmarks"].__setitem__(42, copy.deepcopy(source["body"]["landmarks"][24]))) + self.assert_rejected(lambda source: source["body"]["landmarks"].__setitem__(0, {})) self.assert_rejected(lambda source: source["body"].__setitem__("unknown", [])) def duplicate_pelvis_frame(source): frames = source["body"]["frames"] frames[1] = copy.deepcopy(frames[0]) - self.assertEqual(len(frames), 16) - self.assertEqual(frames[1]["owner"], frames[0]["owner"]) - self.assertEqual(frames[1]["role"], frames[0]["role"]) + self.assertEqual((frames[1]["owner"], frames[1]["role"]), (frames[0]["owner"], frames[0]["role"])) self.assert_rejected(duplicate_pelvis_frame) - - -if __name__ == "__main__": - unittest.main() diff --git a/experiments/programmatic-root-complex-surface/tests/test_render_export.py b/experiments/programmatic-root-complex-surface/tests/test_render_export.py index 3d45683..d952f65 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_render_export.py +++ b/experiments/programmatic-root-complex-surface/tests/test_render_export.py @@ -1,29 +1,24 @@ from __future__ import annotations -import json, os, struct, subprocess, sys, tempfile, unittest +import hashlib, json, os, struct, subprocess, sys, tempfile, unittest from pathlib import Path +from types import SimpleNamespace; from unittest.mock import patch import numpy as np from PIL import Image -ROOT = Path(__file__).resolve().parents[1] -REPOSITORY = ROOT.parents[1] -SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" -LAUNCHER = ROOT / "root_complex_launcher.sh" -BUILD_SCRIPT = ROOT / "build_root_complex.py" -ARTIFACTS = ("prepared.json", "skin.ply", "skin.png", "cage.png", "metrics.json", "manifest.json") +ROOT = Path(__file__).resolve().parents[1]; REPOSITORY = ROOT.parents[1] +SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json"; LAUNCHER = ROOT / "root_complex_launcher.sh"; BUILD_SCRIPT = ROOT / "build_root_complex.py"; ARTIFACTS = ("prepared.json", "skin.ply", "skin.png", "cage.png", "metrics.json", "manifest.json") sys.path.insert(0, str(ROOT)) import build_root_complex as builder # noqa: E402 import render_export # noqa: E402 -VERTICES = np.asarray( - ((-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, 1.0, -1.0), - (-1.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0)), dtype=np.float64) +VERTICES = np.asarray(((-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0)), dtype=np.float64) QUADS = np.asarray(((0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (4, 0, 3, 7)), dtype=np.int64) DEPTH_VERTICES = np.asarray(((-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (1.0, 1.0, 3.0), (-1.0, 1.0, 3.0), (-1.0, -1.0, 1.6), (1.0, -1.0, 1.6), (1.0, 1.0, 1.6), (-1.0, 1.0, 1.6)), dtype=np.float64) -DEPTH_QUADS = np.asarray(((0, 1, 2, 3), (4, 5, 6, 7)), dtype=np.int64) +DEPTH_QUADS = np.asarray(((0, 1, 2, 3), (4, 5, 6, 7)), dtype=np.int64); EXTREME_VERTICES = VERTICES * (np.finfo(np.float64).max / 2.0) def png_chunk_types(data: bytes) -> list[bytes]: @@ -57,22 +52,18 @@ def test_skin_z_buffer_chooses_local_near_depth_independent_of_triangle_order(se def test_png_is_rgb_fixed_size_and_has_no_metadata_chunks(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: path = Path(d) / "skin.png"; render_export.render_skin_png(path, VERTICES, QUADS); data = path.read_bytes() - with Image.open(path) as image: self.assertEqual((image.mode, image.size, image.info), ("RGB", render_export.CANVAS_SIZE, {})) - self.assertEqual(png_chunk_types(data), [b"IHDR", b"IDAT", b"IEND"]) + with Image.open(path) as image: self.assertEqual((image.mode, image.size, image.info), ("RGB", render_export.CANVAS_SIZE, {})); self.assertEqual(png_chunk_types(data), [b"IHDR", b"IDAT", b"IEND"]) def test_cage_diagnostic_is_rgb_and_has_visible_edges(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: path = Path(d) / "cage.png"; render_export.render_cage_png(path, VERTICES, QUADS); data = path.read_bytes() - with Image.open(path) as image: self.assertEqual((image.mode, image.size), ("RGB", render_export.CANVAS_SIZE)); self.assertIn((237, 188, 86), set(image.getdata())) - self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n")) + with Image.open(path) as image: self.assertEqual((image.mode, image.size), ("RGB", render_export.CANVAS_SIZE)); self.assertIn((237, 188, 86), set(image.getdata())); self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n")) def test_existing_outputs_are_not_replaced(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: root = Path(d) for name, writer in (("skin.ply", render_export.write_skin_ply), ("skin.png", render_export.render_skin_png), ("cage.png", render_export.render_cage_png)): - path = root / name; path.write_bytes(b"keep me") - with self.assertRaises(FileExistsError): writer(path, VERTICES, QUADS) - self.assertEqual(path.read_bytes(), b"keep me") + path = root / name; path.write_bytes(b"keep me"); self.assertRaises(FileExistsError, writer, path, VERTICES, QUADS); self.assertEqual(path.read_bytes(), b"keep me") def test_changing_a_supplied_vertex_changes_ply_and_skin_png(self) -> None: changed = VERTICES.copy(); changed[6, 0] += 0.35 @@ -82,28 +73,39 @@ def test_changing_a_supplied_vertex_changes_ply_and_skin_png(self) -> None: writer(root / f"original.{suffix}", VERTICES, QUADS); writer(root / f"changed.{suffix}", changed, QUADS); self.assertNotEqual((root / f"original.{suffix}").read_bytes(), (root / f"changed.{suffix}").read_bytes()) def test_nonfinite_and_invalid_indices_are_rejected(self) -> None: - bad_vertices = VERTICES.copy(); bad_vertices[0, 0] = np.nan - with self.assertRaises(ValueError): render_export.triangulate_quads(bad_vertices, QUADS) + bad_vertices = VERTICES.copy(); bad_vertices[0, 0] = np.nan; self.assertRaises(ValueError, render_export.triangulate_quads, bad_vertices, QUADS) for value, dtype in ((np.inf, np.float64), (0.5, np.float64), (-1, np.int64), (len(VERTICES), np.int64)): - bad_indices = QUADS.astype(dtype); bad_indices[0, 0] = value - with self.assertRaises(ValueError): render_export.triangulate_quads(VERTICES, bad_indices) + bad_indices = QUADS.astype(dtype); bad_indices[0, 0] = value; self.assertRaises(ValueError, render_export.triangulate_quads, VERTICES, bad_indices) + + def test_extreme_finite_coordinates_keep_frame_projection_finite(self) -> None: + cameras, centres, scale = render_export._frames(EXTREME_VERTICES) + self.assertTrue(np.isfinite(np.asarray(cameras)).all()); self.assertTrue(np.isfinite(np.asarray(centres)).all()); self.assertTrue(np.isfinite(scale) and scale > 0.0) + with tempfile.TemporaryDirectory(prefix="root-complex-render-extreme-") as d: + path = Path(d) / "skin.png"; render_export.render_skin_png(path, EXTREME_VERTICES, QUADS) + with Image.open(path) as image: self.assertEqual((image.mode, image.size), ("RGB", render_export.CANVAS_SIZE)) + + def test_builder_rejects_nonzero_intersections_before_publication(self) -> None: + with tempfile.TemporaryDirectory(prefix="root-complex-intersection-") as d: + root = Path(d); target = root / "standard-neutral"; evaluated = SimpleNamespace(intersection_counts=(0, 1)) + with patch.object(builder, "prepare_standard_neutral", return_value={}), patch.object(builder.surface, "evaluate", return_value=evaluated), patch.object(builder, "_publish_no_replace") as publish: + with self.assertRaisesRegex(ValueError, "nonzero evaluated intersections"): builder.build(SOURCE, target) + publish.assert_not_called() + self.assertFalse(target.exists()) + self.assertEqual(list(root.glob(f".{target.name}.staging-*")), []) def test_builder_publishes_complete_metrics_and_manifest(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-build-") as d: target = Path(d) / "standard-neutral"; self.assertEqual(builder.build(SOURCE, target), target); self.assertEqual({p.name for p in target.iterdir()}, set(ARTIFACTS)) - metrics = json.loads((target / "metrics.json").read_text(encoding="utf-8")); manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8")) - self.assertEqual(metrics["intersection_status"], "zero"); self.assertEqual(metrics["intersection_counts_by_level"], [0, 0]); self.assertEqual(set(manifest["files"]), set(ARTIFACTS[:-1])); self.assertEqual(manifest["files"]["metrics.json"], builder._sha256(target / "metrics.json")) + metrics = json.loads((target / "metrics.json").read_text(encoding="utf-8")); manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8")); self.assertEqual(metrics["intersection_status"], "zero"); self.assertEqual(metrics["intersection_counts_by_level"], [0, 0]); self.assertEqual(set(manifest["files"]), set(ARTIFACTS[:-1])); self.assertEqual(manifest["files"]["metrics.json"], hashlib.sha256((target / "metrics.json").read_bytes()).hexdigest()) def test_atomic_publication_refuses_existing_target_without_overwrite(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-publish-") as d: - root = Path(d); stage, target = root / "stage", root / "target"; stage.mkdir(); (stage / "payload").write_bytes(b"new"); target.mkdir(); (target / "payload").write_bytes(b"keep") - with self.assertRaises(FileExistsError): builder._publish_no_replace(stage, target) + root = Path(d); stage, target = root / "stage", root / "target"; stage.mkdir(); (stage / "payload").write_bytes(b"new"); target.mkdir(); (target / "payload").write_bytes(b"keep"); self.assertRaises(FileExistsError, builder._publish_no_replace, stage, target) self.assertEqual((stage / "payload").read_bytes(), b"new"); self.assertEqual((target / "payload").read_bytes(), b"keep") def test_builder_cleans_staging_after_generation_failure(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-failure-") as d: - root = Path(d); target = root / "standard-neutral" - with self.assertRaises(ValueError): builder.build(root / "missing-source.json", target) + root = Path(d); target = root / "standard-neutral"; self.assertRaises(ValueError, builder.build, root / "missing-source.json", target) self.assertFalse(target.exists()); self.assertEqual(list(root.glob(f".{target.name}.staging-*")), []) def test_launcher_fresh_processes_are_byte_identical(self) -> None: diff --git a/experiments/programmatic-root-complex-surface/tests/test_root_complex_surface.py b/experiments/programmatic-root-complex-surface/tests/test_root_complex_surface.py index 6a7c9fb..2be6761 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_root_complex_surface.py +++ b/experiments/programmatic-root-complex-surface/tests/test_root_complex_surface.py @@ -190,8 +190,7 @@ def test_symmetric_pair_of_pants_routes_are_exact(self): expected.extend((path[i], path[i + 1], cuff[i + 1], cuff[i]) for i in range(4)) expected.append((50, 64, 54, 68)) - self.assertEqual({frozenset(face) for face in faces[-9:]}, - {frozenset(face) for face in expected}) + self.assertEqual(faces[-9:], tuple(expected[:4]) + tuple(tuple(reversed(face)) for face in expected[4:8]) + (expected[8],)) def test_pelvic_routes_have_no_proper_front_projection_crossings(self): cage = surface.build_cage(synthetic_prepared()) @@ -325,7 +324,7 @@ def test_shoulder_bridges_are_outward_and_each_quad_is_unfolded(self): for a, b in cross_edges: point = vertices[a] if a in collar else vertices[b] other = vertices[b] if a in collar else vertices[a] - self.assertNotEqual(sign * (other[0] - point[0]), 0.0) + self.assertGreater(sign * (point[0] - other[0]), 0.0) def orientation(a, b, c): return ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) @@ -567,6 +566,9 @@ def test_open_boundaries_subdivide_and_euler_is_preserved(self): self.assertTrue(all(value > threshold for (_, value), threshold in zip( self.result.clearance_ratios, (0.030, 0.025, 0.025, 0.020, 0.025)))) + def test_final_level_clearance_gate_runs_at_requested_level(self): + self.assertEqual(tuple(name for name, _ in surface.evaluate(self.prepared, levels=1).clearance_ratios), ("neck", "axilla_left", "axilla_right", "groin", "medial_thigh")) + def test_correspondence_order_and_results_are_deterministic(self): repeated = surface.evaluate(synthetic_prepared(), levels=2) self.assertEqual(self.result, repeated) From e5f33f1a40125c82a1baa285f529da17cac41538 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 3 Sep 2026 09:45:02 +1200 Subject: [PATCH 03/38] Repair canonical metre source handling --- .../src/provisional_form_inspection.rs | 244 +++++++++----- dev-tools/repo_search.sh | 24 ++ dev-tools/validation/test_repo_search.sh | 53 +++ .../publish_successor_anatomy_gallery.py | 20 +- .../tests/test_successor_anatomy_gallery.py | 32 ++ .../tests/test_surface_preview_publication.py | 4 +- .../owned-root-assembly-investigation.md | 22 ++ ...lized-digitigrade-biped-authored-form.json | 306 +++++++++--------- .../current-form-surface-preview/README.md | 34 +- .../generate_structural_profile_sources.py | 132 +++++++- .../structural_profile_candidates.json | 4 +- .../tests/test_structural_profile_sources.py | 217 ++++++++++++- .../owned-root-assembly-successor/README.md | 36 ++- .../README.md | 17 + .../prepared_projection.py | 17 +- .../tests/test_prepared_projection.py | 38 ++- .../tests/test_render_export.py | 2 + 17 files changed, 907 insertions(+), 295 deletions(-) create mode 100755 dev-tools/repo_search.sh create mode 100755 dev-tools/validation/test_repo_search.sh diff --git a/crates/creature-kernel-cli/src/provisional_form_inspection.rs b/crates/creature-kernel-cli/src/provisional_form_inspection.rs index b86d54d..5867173 100644 --- a/crates/creature-kernel-cli/src/provisional_form_inspection.rs +++ b/crates/creature-kernel-cli/src/provisional_form_inspection.rs @@ -9,6 +9,7 @@ use creature_kernel_core::body_document::{ResourceProfile, Status as AdmissionStatus}; use creature_kernel_core::frame::RigidTransform; +use creature_kernel_core::numeric::{NormalizedBinary64, decimal_to_binary64}; use creature_kernel_core::provisional_form_preview::{ MAX_PROVISIONAL_PERMILLE, ProvisionalFormPreview, ProvisionalFormPreviewError, ProvisionalPlacementFailureKind, ProvisionalShape, ProvisionalSourceFailureKind, @@ -140,13 +141,13 @@ const LIMITATIONS: &str = "Provisional display-only filled-form descriptors from struct PreparedAuthoredDimensions { inventory: Vec, - values: BTreeMap<(AddressKey, String), u32>, + display_values: BTreeMap<(AddressKey, String), u32>, } struct AuthoredDimension { owner: AddressKey, role: String, - value_permille: u32, + display_value_permille: u32, document: String, namespace: String, } @@ -160,8 +161,8 @@ impl AuthoredDimension { &self.role } - const fn value_permille(&self) -> u32 { - self.value_permille + const fn display_value_permille(&self) -> u32 { + self.display_value_permille } fn provenance(&self) -> AuthoredDimensionProvenance<'_> { @@ -350,7 +351,7 @@ impl fmt::Display for InspectionError { value, } => write!( formatter, - "source-authored dimension {role:?} at {address} has invalid positive permille value {value}" + "source-authored dimension {role:?} at {address} has invalid canonical metre value {value}" ), Self::MissingAuthoredControl { owner, role } => write!( formatter, @@ -580,7 +581,7 @@ fn authored_dimension_value(dimension: &AuthoredDimension) -> Value { json!({ "owner": crate::structural_inspection::address_key_value(dimension.owner()), "role": dimension.role(), - "value_permille": dimension.value_permille(), + "value_permille": dimension.display_value_permille(), "provenance": { "source": dimension.provenance().source(), "document": dimension.provenance().document(), @@ -1013,6 +1014,33 @@ fn authored_dimension_index( .expect("validated torso profile dimension was not retained") } +fn canonical_metres_to_display_permille(value: NormalizedBinary64) -> Result { + let metres = value.as_f64(); + if !metres.is_finite() { + return Err("value must be finite"); + } + if metres <= 0.0 { + return Err("value must be strictly positive"); + } + + let maximum_metres = f64::from(MAX_PROVISIONAL_PERMILLE) / 1_000.0; + if metres > maximum_metres { + return Err("value is outside the provisional display range"); + } + + // The source remains a canonical metre value. Compare its admitted + // binary64 identity with each exact decimal thousandth encoding instead + // of rounding an arbitrary source value onto the display grid. + for display_value_permille in 1..=MAX_PROVISIONAL_PERMILLE { + let grid_metres = f64::from(display_value_permille) / 1_000.0; + if value.to_bits() == grid_metres.to_bits() { + return Ok(display_value_permille); + } + } + + Err("value is not exactly representable on the provisional thousandth grid") +} + fn torso_profile_factors(profile_id: &'static str, owner_role: &str) -> (u32, u32) { match profile_id { "neutral-v0" => (1_000, 1_000), @@ -1080,7 +1108,7 @@ fn validate_head_neck_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} cannot be checked-scaled for variant {:?} with factor {factor}", + "display-grid={value} cannot be checked-scaled for variant {:?} with factor {factor}", variant.id() ), }); @@ -1090,7 +1118,7 @@ fn validate_head_neck_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", + "display-grid={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", variant.id() ), }); @@ -1152,7 +1180,7 @@ fn validate_arm_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} cannot be checked-scaled for variant {:?} with factor {factor}", + "display-grid={value} cannot be checked-scaled for variant {:?} with factor {factor}", variant.id() ), }); @@ -1162,7 +1190,7 @@ fn validate_arm_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", + "display-grid={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", variant.id() ), }); @@ -1207,7 +1235,7 @@ fn validate_leg_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} cannot be checked-scaled for variant {:?} with factor {factor}", + "display-grid={value} cannot be checked-scaled for variant {:?} with factor {factor}", variant.id() ), }); @@ -1217,7 +1245,7 @@ fn validate_leg_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", + "display-grid={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", variant.id() ), }); @@ -1252,7 +1280,7 @@ fn validate_foot_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} cannot be checked-scaled for variant {:?} with factor {factor}", + "display-grid={value} cannot be checked-scaled for variant {:?} with factor {factor}", variant.id() ), }); @@ -1262,7 +1290,7 @@ fn validate_foot_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", + "display-grid={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", variant.id() ), }); @@ -1274,7 +1302,7 @@ fn validate_foot_profile_radius( fn validate_foot_profile_geometry( preview: &ProvisionalFormPreview, profile: &PreparedFootProfile, - dimensions: &BTreeMap<(AddressKey, String), u32>, + display_values: &BTreeMap<(AddressKey, String), u32>, ) -> Result<(), InspectionError> { let reference_length = (preview.reference_scale().squared_length() as f64).sqrt(); if !reference_length.is_finite() || reference_length <= 0.0 { @@ -1284,7 +1312,7 @@ fn validate_foot_profile_geometry( } let dimension_value = |address: &AddressKey, role: &str| { - *dimensions + *display_values .get(&(address.clone(), role.to_owned())) .expect("validated foot profile dimension") }; @@ -1415,7 +1443,7 @@ fn validate_torso_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} cannot be checked-scaled for variant {:?} with factor {factor}", + "display-grid={value} cannot be checked-scaled for variant {:?} with factor {factor}", variant.id() ), }); @@ -1425,7 +1453,7 @@ fn validate_torso_profile_radius( address: address.clone(), role: role.to_owned(), value: format!( - "integer={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", + "display-grid={value} projects to {scaled} for variant {:?} with factor {factor}; expected 1..={MAX_PROVISIONAL_PERMILLE}", variant.id() ), }); @@ -2649,7 +2677,7 @@ fn prepare_authored_dimensions( } } - let mut values = BTreeMap::new(); + let mut display_values = BTreeMap::new(); for (owner_role, value) in prepared.dimensions() { let key = (owner_role.owner().clone(), owner_role.role().to_owned()); if owner_role @@ -2707,38 +2735,30 @@ fn prepare_authored_dimensions( if !required.contains(&key) { continue; } - let exact = match value.to_exact_i64() { - Ok(exact) => exact, + let display_value_permille = match canonical_metres_to_display_permille(*value) { + Ok(display_value_permille) => display_value_permille, Err(cause) => { return Err(InspectionError::InvalidAuthoredDimension { address: key.0, role: key.1, - value: format!("bits=0x{:016x} ({cause})", value.to_bits()), - }); - } - }; - let value_permille = match u32::try_from(exact) { - Ok(value_permille) if (1..=i64::from(MAX_PROVISIONAL_PERMILLE)).contains(&exact) => { - value_permille - } - _ => { - return Err(InspectionError::InvalidAuthoredDimension { - address: key.0, - role: key.1, - value: format!("integer={exact} bits=0x{:016x}", value.to_bits()), + value: format!( + "metres={} bits=0x{:016x} ({cause})", + value.as_f64(), + value.to_bits() + ), }); } }; - validate_torso_profile_radius(preview, &key.0, &key.1, value_permille)?; - validate_head_neck_profile_radius(preview, &key.0, &key.1, value_permille)?; - validate_arm_profile_radius(preview, &key.0, &key.1, value_permille)?; - validate_leg_profile_radius(preview, &key.0, &key.1, value_permille)?; - validate_foot_profile_radius(preview, &key.0, &key.1, value_permille)?; - values.insert(key, value_permille); + validate_torso_profile_radius(preview, &key.0, &key.1, display_value_permille)?; + validate_head_neck_profile_radius(preview, &key.0, &key.1, display_value_permille)?; + validate_arm_profile_radius(preview, &key.0, &key.1, display_value_permille)?; + validate_leg_profile_radius(preview, &key.0, &key.1, display_value_permille)?; + validate_foot_profile_radius(preview, &key.0, &key.1, display_value_permille)?; + display_values.insert(key, display_value_permille); } for (address, role) in &required { - if !values.contains_key(&(address.clone(), role.clone())) { + if !display_values.contains_key(&(address.clone(), role.clone())) { return Err(InspectionError::MissingAuthoredDimension { address: address.clone(), role: role.clone(), @@ -2746,20 +2766,25 @@ fn prepare_authored_dimensions( } } - validate_foot_profile_geometry(preview, foot_profile, &values)?; + validate_foot_profile_geometry(preview, foot_profile, &display_values)?; let source = prepared.graph().source(); - let inventory = values + let inventory = display_values .iter() - .map(|((owner, role), value_permille)| AuthoredDimension { - owner: owner.clone(), - role: role.clone(), - value_permille: *value_permille, - document: source.document.clone(), - namespace: source.namespace.clone(), - }) + .map( + |((owner, role), display_value_permille)| AuthoredDimension { + owner: owner.clone(), + role: role.clone(), + display_value_permille: *display_value_permille, + document: source.document.clone(), + namespace: source.namespace.clone(), + }, + ) .collect(); - Ok(PreparedAuthoredDimensions { inventory, values }) + Ok(PreparedAuthoredDimensions { + inventory, + display_values, + }) } fn authored_dimension_roles(role: &str) -> Option<&'static [&'static str]> { @@ -2780,7 +2805,7 @@ fn dimension_value( role: &str, ) -> u32 { *dimensions - .values + .display_values .get(&(address.clone(), role.to_owned())) .expect("required authored dimension was validated before shape construction") } @@ -3267,11 +3292,15 @@ mod tests { creature_kernel_core::provisional_json::to_vec(&value).expect("JSON bytes") } + fn grid_metres(display_value_permille: u32) -> Value { + json!(f64::from(display_value_permille) / 1_000.0) + } + fn set_torso_profile_radii( source: &mut Value, owner_role: Option<&str>, axis_suffix: Option<&str>, - value: u32, + value: Value, ) { for dimension in source["body"]["dimensions"].as_array_mut().unwrap() { let role = dimension["role"].as_str().unwrap(); @@ -3279,7 +3308,7 @@ mod tests { && owner_role.is_none_or(|owner| dimension["owner"]["role"] == json!(owner)) && axis_suffix.is_none_or(|suffix| role.ends_with(suffix)) { - dimension["value"] = json!(value); + dimension["value"] = value.clone(); } } } @@ -3396,6 +3425,33 @@ mod tests { ); } + #[test] + fn canonical_metre_dimensions_use_only_exact_display_grid_values() { + for (token, expected_display_value_permille) in + [("0.001", 1), ("0.34", 340), ("1.5", 1_500), ("5", 5_000)] + { + let value = decimal_to_binary64(token).expect("finite decimal source value"); + assert_eq!( + canonical_metres_to_display_permille(value), + Ok(expected_display_value_permille) + ); + } + + for token in ["0.0005", "0.3505", "1.5005", "5.001", "0", "-1"] { + let value = decimal_to_binary64(token).expect("finite decimal source value"); + assert!( + canonical_metres_to_display_permille(value).is_err(), + "{token}" + ); + } + + // JSON numeric admission rejects overflow/non-finite spellings before + // this adapter boundary; there is no non-finite source value to pass + // into NormalizedBinary64. + assert!(decimal_to_binary64("1e999").is_err()); + assert!(decimal_to_binary64("NaN").is_err()); + } + fn authored_control_failure(value: Value) -> Value { let result = parsed(&inspect_source(&bytes(value))); assert_eq!(result["status"], "invalid-source"); @@ -4326,7 +4382,7 @@ mod tests { dimension["role"] == "form_leg_profile_hock_endpoint_forward_radius" && dimension["owner"]["anchors"] == json!(["right"]) }) - .unwrap()["value"] = json!(180); + .unwrap()["value"] = grid_metres(180); let changed_radius = parsed(&inspect_source(&bytes(changed_radius_source))); assert_eq!(changed_radius["status"], "success"); @@ -4514,7 +4570,7 @@ mod tests { assert_eq!(result["status"], "invalid-source"); assert_eq!(result["stage"], "dimensions"); - for invalid in [json!(0), json!(-1), json!(5_001), json!(350.5)] { + for invalid in [json!(0.0), json!(-1.0), json!(5.001), json!(0.3505)] { let mut invalid_source = document(); invalid_source["body"]["dimensions"] .as_array_mut() @@ -4568,7 +4624,7 @@ mod tests { &mut all_axes_at_projectable_lower_bound, None, None, - json!(2), + grid_metres(2), ); let all_axes_at_projectable_lower_bound = parsed(&inspect_source(&bytes(all_axes_at_projectable_lower_bound))); @@ -4576,7 +4632,12 @@ mod tests { assert_emitted_variant_radii_are_bounded(&all_axes_at_projectable_lower_bound); let mut up_at_source_minimum = document(); - set_leg_profile_radii(&mut up_at_source_minimum, None, Some("up_radius"), json!(1)); + set_leg_profile_radii( + &mut up_at_source_minimum, + None, + Some("up_radius"), + grid_metres(1), + ); let up_at_source_minimum = parsed(&inspect_source(&bytes(up_at_source_minimum))); assert_eq!(up_at_source_minimum["status"], "success"); assert_emitted_variant_radii_are_bounded(&up_at_source_minimum); @@ -4587,7 +4648,7 @@ mod tests { &mut below_projectable_lower_bound, None, Some(axis_suffix), - json!(1), + grid_metres(1), ); let below_projectable_lower_bound = parsed(&inspect_source(&bytes(below_projectable_lower_bound))); @@ -4606,13 +4667,18 @@ mod tests { ]; for (axis_suffix, boundary) in boundaries { let mut valid = document(); - set_leg_profile_radii(&mut valid, None, Some(axis_suffix), json!(boundary)); + set_leg_profile_radii(&mut valid, None, Some(axis_suffix), grid_metres(boundary)); let valid = parsed(&inspect_source(&bytes(valid))); assert_eq!(valid["status"], "success"); assert_emitted_variant_radii_are_bounded(&valid); let mut invalid = document(); - set_leg_profile_radii(&mut invalid, None, Some(axis_suffix), json!(boundary + 1)); + set_leg_profile_radii( + &mut invalid, + None, + Some(axis_suffix), + grid_metres(boundary + 1), + ); let invalid = parsed(&inspect_source(&bytes(invalid))); assert_eq!(invalid["status"], "invalid-source"); assert_eq!(invalid["stage"], "dimensions"); @@ -4719,7 +4785,7 @@ mod tests { dimension["role"] == "form_arm_profile_forearm_midpoint_forward_radius" && dimension["owner"]["anchors"] == json!(["right"]) }) - .unwrap()["value"] = json!(200); + .unwrap()["value"] = grid_metres(200); let changed_radius = parsed(&inspect_source(&bytes(changed_radius_source))); assert_eq!(changed_radius["status"], "success"); @@ -4917,7 +4983,7 @@ mod tests { assert_eq!(result["status"], "invalid-source"); assert_eq!(result["stage"], "dimensions"); - for invalid in [json!(0), json!(-1), json!(5_001), json!(350.5)] { + for invalid in [json!(0.0), json!(-1.0), json!(5.001), json!(0.3505)] { let mut invalid_source = document(); invalid_source["body"]["dimensions"] .as_array_mut() @@ -4971,7 +5037,7 @@ mod tests { &mut all_axes_at_projectable_lower_bound, None, None, - json!(2), + grid_metres(2), ); let all_axes_at_projectable_lower_bound = parsed(&inspect_source(&bytes(all_axes_at_projectable_lower_bound))); @@ -4979,7 +5045,12 @@ mod tests { assert_emitted_variant_radii_are_bounded(&all_axes_at_projectable_lower_bound); let mut up_at_source_minimum = document(); - set_arm_profile_radii(&mut up_at_source_minimum, None, Some("up_radius"), json!(1)); + set_arm_profile_radii( + &mut up_at_source_minimum, + None, + Some("up_radius"), + grid_metres(1), + ); let up_at_source_minimum = parsed(&inspect_source(&bytes(up_at_source_minimum))); assert_eq!(up_at_source_minimum["status"], "success"); assert_emitted_variant_radii_are_bounded(&up_at_source_minimum); @@ -4990,7 +5061,7 @@ mod tests { &mut below_projectable_lower_bound, None, Some(axis_suffix), - json!(1), + grid_metres(1), ); let below_projectable_lower_bound = parsed(&inspect_source(&bytes(below_projectable_lower_bound))); @@ -5009,13 +5080,18 @@ mod tests { ]; for (axis_suffix, boundary) in boundaries { let mut valid = document(); - set_arm_profile_radii(&mut valid, None, Some(axis_suffix), json!(boundary)); + set_arm_profile_radii(&mut valid, None, Some(axis_suffix), grid_metres(boundary)); let valid = parsed(&inspect_source(&bytes(valid))); assert_eq!(valid["status"], "success"); assert_emitted_variant_radii_are_bounded(&valid); let mut invalid = document(); - set_arm_profile_radii(&mut invalid, None, Some(axis_suffix), json!(boundary + 1)); + set_arm_profile_radii( + &mut invalid, + None, + Some(axis_suffix), + grid_metres(boundary + 1), + ); let invalid = parsed(&inspect_source(&bytes(invalid))); assert_eq!(invalid["status"], "invalid-source"); assert_eq!(invalid["stage"], "dimensions"); @@ -5140,7 +5216,7 @@ mod tests { .find(|dimension| { dimension["role"] == "form_head_neck_profile_muzzle_mid_forward_radius" }) - .unwrap()["value"] = json!(550); + .unwrap()["value"] = grid_metres(550); let changed_dimension = parsed(&inspect_source(&bytes(changed_dimension_source))); assert_eq!( original["authored_landmarks"], @@ -5334,7 +5410,7 @@ mod tests { "ck.cli.provisional-form.authored-dimension" ); - for invalid in [json!(1.5), json!(0), json!(-1), json!(5_001)] { + for invalid in [json!(1.5005), json!(0.0), json!(-1.0), json!(5.001)] { let mut document = document(); document["body"]["dimensions"].as_array_mut().unwrap()[0]["value"] = invalid; let result = parsed(&inspect_source(&bytes(document))); @@ -5353,7 +5429,7 @@ mod tests { .iter_mut() .find(|dimension| dimension["role"] == "form_shoulder_depth_radius") .expect("shoulder depth control"); - dimension["value"] = json!(350.5); + dimension["value"] = json!(0.3505); let fractional_profile = parsed(&inspect_source(&bytes(fractional_profile))); assert_eq!(fractional_profile["status"], "invalid-source"); assert_eq!(fractional_profile["stage"], "dimensions"); @@ -5569,7 +5645,7 @@ mod tests { }); assert_invalid_head_neck_dimension_source(missing); - for invalid in [json!(0), json!(-1), json!(5_001), json!(350.5)] { + for invalid in [json!(0.0), json!(-1.0), json!(5.001), json!(0.3505)] { let mut invalid_source = document(); invalid_source["body"]["dimensions"] .as_array_mut() @@ -5631,7 +5707,7 @@ mod tests { &mut valid, Some(owner_role), Some(axis_suffix), - json!(boundary), + grid_metres(boundary), ); let valid = parsed(&inspect_source(&bytes(valid))); assert_eq!(valid["status"], "success"); @@ -5642,7 +5718,7 @@ mod tests { &mut invalid, Some(owner_role), Some(axis_suffix), - json!(boundary + 1), + grid_metres(boundary + 1), ); assert_invalid_head_neck_dimension_source(invalid); } @@ -5817,7 +5893,7 @@ mod tests { assert_eq!(result["status"], "invalid-source"); assert_eq!(result["stage"], "dimensions"); - for invalid in [json!(0), json!(-1), json!(5_001), json!(350.5)] { + for invalid in [json!(0.0), json!(-1.0), json!(5.001), json!(0.3505)] { let mut invalid_source = document(); invalid_source["body"]["dimensions"] .as_array_mut() @@ -5855,7 +5931,7 @@ mod tests { for owner_role in ["pelvis", "torso"] { for invalid in [1, MAX_PROVISIONAL_PERMILLE] { let mut source = document(); - set_torso_profile_radii(&mut source, Some(owner_role), None, invalid); + set_torso_profile_radii(&mut source, Some(owner_role), None, grid_metres(invalid)); assert_invalid_torso_radius_source(source); } } @@ -5871,12 +5947,12 @@ mod tests { for (owner_role, axis_suffix, high_boundary) in high_boundaries { for source_radius in [2, high_boundary] { let mut source = document(); - set_torso_profile_radii(&mut source, None, None, 2); + set_torso_profile_radii(&mut source, None, None, grid_metres(2)); set_torso_profile_radii( &mut source, Some(owner_role), Some(axis_suffix), - source_radius, + grid_metres(source_radius), ); let result = parsed(&inspect_source(&bytes(source))); assert_eq!(result["status"], "success"); @@ -5884,12 +5960,12 @@ mod tests { } let mut just_over_high = document(); - set_torso_profile_radii(&mut just_over_high, None, None, 2); + set_torso_profile_radii(&mut just_over_high, None, None, grid_metres(2)); set_torso_profile_radii( &mut just_over_high, Some(owner_role), Some(axis_suffix), - high_boundary + 1, + grid_metres(high_boundary + 1), ); assert_invalid_torso_radius_source(just_over_high); } @@ -5906,7 +5982,7 @@ mod tests { dimension["owner"]["role"] == "pelvis" && dimension["role"] == "form_extent_y" }) .expect("pelvis y extent"); - dimension["value"] = json!(MAX_PROVISIONAL_PERMILLE); + dimension["value"] = grid_metres(MAX_PROVISIONAL_PERMILLE); let result = parsed(&inspect_source(&bytes(source))); assert_eq!(result["status"], "success"); @@ -6117,7 +6193,7 @@ mod tests { Some("right"), Some("toe"), Some("forward_radius"), - json!(260), + grid_metres(260), ); let changed_radius = parsed(&inspect_source(&bytes(changed_radius_source))); assert_eq!(changed_radius["status"], "success"); @@ -6261,7 +6337,7 @@ mod tests { .unwrap()["position"][1] = json!(-0.21); authored_control_failure(contact_gap); - for invalid in [json!(0), json!(-1), json!(5_001), json!(4_349)] { + for invalid in [json!(0.0), json!(-1.0), json!(5.001), json!(4.349)] { let mut invalid_source = document(); set_foot_profile_radii( &mut invalid_source, @@ -6377,7 +6453,7 @@ mod tests { dimension["owner"]["role"] == "torso" && dimension["role"] == "form_extent_x" }) .expect("torso x control"); - torso_x["value"] = json!(1_750); + torso_x["value"] = grid_metres(1_750); let changed = parsed(&inspect_source(&bytes(changed_source))); for (original_variant, changed_variant) in original["variants"] diff --git a/dev-tools/repo_search.sh b/dev-tools/repo_search.sh new file mode 100755 index 0000000..6728f43 --- /dev/null +++ b/dev-tools/repo_search.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if (( $# == 0 )); then + printf 'usage: %s PATTERN [PATH ...]\n' "$0" >&2 + exit 64 +fi + +pattern=$1 +shift + +if (( $# == 0 )); then + set -- . +fi + +for path in "$@"; do + if [[ $path == -* ]]; then + printf '%s: option-shaped path is not allowed after the pattern: %q\n' "$0" "$path" >&2 + exit 64 + fi +done + +exec rg -n -C 2 -- "$pattern" "$@" diff --git a/dev-tools/validation/test_repo_search.sh b/dev-tools/validation/test_repo_search.sh new file mode 100755 index 0000000..b50e9ea --- /dev/null +++ b/dev-tools/validation/test_repo_search.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root=$(cd -- "$(dirname -- "$0")/../.." && pwd) +search_script=$repo_root/dev-tools/repo_search.sh + +bash -n "$search_script" "$0" + +tmp_dir=$(mktemp -d -t repo-search-test.XXXXXX) +trap 'rm -rf -- "$tmp_dir"' EXIT + +test_root=$tmp_dir/repository +mkdir -p "$test_root/space dir" +printf 'before\n-dash-leading\nafter\n' >"$test_root/dash.txt" +printf 'before\nnormal needle\nafter\n' >"$test_root/normal.txt" +printf 'needle with spaces\n' >"$test_root/space dir/result.txt" +printf 'default-marker\n' >"$test_root/default.txt" + +dash_output=$(cd -- "$test_root" && "$search_script" '-dash-leading') +[[ $dash_output == *'dash.txt:2:-dash-leading'* ]] + +normal_output=$("$search_script" 'normal needle' "$test_root/normal.txt") +[[ $normal_output == *'2:normal needle'* ]] + +default_output=$(cd -- "$test_root" && "$search_script" 'default-marker') +[[ $default_output == *'default.txt:1:default-marker'* ]] + +spaces_output=$("$search_script" 'needle with spaces' "$test_root/space dir") +[[ $spaces_output == *"$test_root/space dir/result.txt:1:needle with spaces"* ]] + +fake_bin=$tmp_dir/fake-bin +rg_called=$tmp_dir/rg-called +mkdir -p "$fake_bin" +printf '#!/usr/bin/env bash\n: >"%s"\nexit 99\n' "$rg_called" >"$fake_bin/rg" +chmod +x "$fake_bin/rg" + +option_error=$tmp_dir/option-error +set +e +PATH="$fake_bin:$PATH" "$search_script" needle '--glob=*.txt' 2>"$option_error" +option_status=$? +set -e +[[ $option_status -eq 64 ]] +[[ ! -e $rg_called ]] +rg -F -- 'option-shaped path is not allowed' "$option_error" >/dev/null + +set +e +"$search_script" 'does-not-match' "$test_root/normal.txt" >/dev/null +no_match_status=$? +set -e +[[ $no_match_status -eq 1 ]] + +printf '%s\n' 'repo_search.sh tests passed' diff --git a/dev-tools/visual-review/publish_successor_anatomy_gallery.py b/dev-tools/visual-review/publish_successor_anatomy_gallery.py index 5ff16e8..b7c8e40 100644 --- a/dev-tools/visual-review/publish_successor_anatomy_gallery.py +++ b/dev-tools/visual-review/publish_successor_anatomy_gallery.py @@ -295,6 +295,19 @@ def _text(value: Any, where: str) -> str: return value +def _validate_tail_signature(value: Any, where: str) -> None: + if not isinstance(value, list) or len(value) != 5: + _fail(f"{where} is invalid") + if any( + type(number) not in (int, float) + or (type(number) is float and not math.isfinite(number)) + or number <= 0 + or number > profile_source_generator.MAX_SAFE_INTEGER + for number in value + ): + _fail(f"{where} is invalid") + + def _read_reference_bytes(reference: common.SourceReference, maximum: int, where: str) -> bytes: try: with common.open_source_reference(reference, where) as stream: @@ -658,12 +671,7 @@ def _validate_source_manifest(manifest_path: Path) -> tuple[dict[str, Any], byte _fail(f"{where}.bytes exceeds the inspect-provisional-form source bound") expected_hash = _hash(profile["sha256"], f"{where}.sha256") tail_signature = profile["tail_signature"] - if ( - not isinstance(tail_signature, list) - or len(tail_signature) != 5 - or any(type(value) is not int for value in tail_signature) - ): - _fail(f"{where}.tail_signature is invalid") + _validate_tail_signature(tail_signature, f"{where}.tail_signature") source_ref = _resolve_file(manifest_ref.path.parent / file_name, f"{where}.file") source_value, source_bytes = _read_canonical_json(source_ref, f"{where}.file", source=True) if source_bytes != generated_source_bytes[index]: diff --git a/dev-tools/visual-review/tests/test_successor_anatomy_gallery.py b/dev-tools/visual-review/tests/test_successor_anatomy_gallery.py index a016e2d..b735ab0 100644 --- a/dev-tools/visual-review/tests/test_successor_anatomy_gallery.py +++ b/dev-tools/visual-review/tests/test_successor_anatomy_gallery.py @@ -462,6 +462,38 @@ def test_active_generation_mode_is_forwarded_explicitly(self) -> None: profile_generator.DEFAULT_GENERATION_MODE, ) + def test_active_generated_manifest_with_decimal_metre_signatures_validates(self) -> None: + manifest, _manifest_bytes, records = adapter._validate_source_manifest(self.source_manifest) + signatures = [profile["tail_signature"] for profile in manifest["profiles"]] + self.assertTrue(any(type(number) is float for signature in signatures for number in signature)) + self.assertEqual(len(records), 5) + + def test_malformed_tail_signatures_are_rejected_fail_closed(self) -> None: + manifest = json.loads(self.source_manifest.read_text(encoding="utf-8")) + original_signature = manifest["profiles"][0]["tail_signature"] + malformed_signatures = ( + ("bool", [True, *original_signature[1:]], "tail_signature is invalid", False), + ("zero", [0, *original_signature[1:]], "tail_signature is invalid", False), + ("negative", [-0.1, *original_signature[1:]], "tail_signature is invalid", False), + ("wrong-length", original_signature[:-1], "tail_signature is invalid", False), + ("mismatch", [original_signature[0] + 1, *original_signature[1:]], "does not match", False), + ("nan", [float("nan"), *original_signature[1:]], "not finite UTF-8 JSON", True), + ("infinity", [float("inf"), *original_signature[1:]], "not finite UTF-8 JSON", True), + ) + for name, signature, expected_error, noncanonical in malformed_signatures: + with self.subTest(name=name): + malformed = copy.deepcopy(manifest) + malformed["profiles"][0]["tail_signature"] = signature + if noncanonical: + self.source_manifest.write_text( + json.dumps(malformed, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=True) + "\n", + encoding="utf-8", + ) + else: + self.source_manifest.write_bytes(profile_generator.canonical_bytes(malformed)) + with self.assertRaisesRegex(adapter.SuccessorAnatomyGalleryError, expected_error): + adapter._validate_source_manifest(self.source_manifest) + def test_profile_source_constant_reader_does_not_execute_source(self) -> None: marker = self.root / "executed" source_path = self.root / "generator.py" diff --git a/dev-tools/visual-review/tests/test_surface_preview_publication.py b/dev-tools/visual-review/tests/test_surface_preview_publication.py index 1a73784..7674c05 100644 --- a/dev-tools/visual-review/tests/test_surface_preview_publication.py +++ b/dev-tools/visual-review/tests/test_surface_preview_publication.py @@ -3182,10 +3182,10 @@ def test_checked_in_authored_source_identity_fits_inside_context_bound(self) -> / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" ) raw = source.read_bytes() - self.assertEqual(len(raw), 56_863) + self.assertEqual(len(raw), 56_984) self.assertEqual( hashlib.sha256(raw).hexdigest(), - "d4f0dad6f936d62f9ee8c0fa24701898ee4ae6e48bcdeaf44641bd4dc3b549de", + "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14", ) evidence = publisher._validate_input_evidence( publisher._read_input_evidence(source), "checked-in source" diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index b20947f..6680355 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -9,6 +9,28 @@ It does not define product behaviour, a production surface contract, canonical Regions or Sockets, a permanent topology, or a backend. It cannot satisfy or replace the DR-0013 Stage 1 proof. DR-0009 and DR-0010 remain parked. +## Canonical metre repair evidence and boundary + +The active authored input has been rebaselined to the repaired canonical metre +source. `examples/body-documents/stylized-digitigrade-biped-authored-form.json` +is 56,984 bytes with SHA-256 +`82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14`. All 153 +canonical dimensions are metres. Non-dimension transforms and landmarks are +unchanged. The provisional display adapter derives retained descriptor-local +integer `*_permille` fields explicitly; those fields are not authored dimension +units. Profile factors remain separate integer-permille display/profile inputs; +active generated-profile output applies them with exact decimal arithmetic, +quantizes to the nearest millimetre using ties-to-even, and emits canonical +metres. + +The active candidate-table binding is +`experiments/current-form-surface-preview/structural_profile_candidates.json` +with SHA-256 +`a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. This is +a source/hash metadata rebaseline only: standard-neutral geometry is expected +to remain unchanged. Historical source and evidence remain untouched; this +record does not claim that the successor contract is implemented. + ## Research-question mapping This unregistered exploratory experiment targets four canonical questions: diff --git a/examples/body-documents/stylized-digitigrade-biped-authored-form.json b/examples/body-documents/stylized-digitigrade-biped-authored-form.json index 7dc7489..e188971 100644 --- a/examples/body-documents/stylized-digitigrade-biped-authored-form.json +++ b/examples/body-documents/stylized-digitigrade-biped-authored-form.json @@ -108,159 +108,159 @@ {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe", "frame": {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_control"}, "position": [0, -0.2, 0.72]} ], "dimensions": [ - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_x", "value": 1700}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_y", "value": 1200}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_z", "value": 900}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_x", "value": 1650}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_y", "value": 1200}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_z", "value": 900}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_lateral_radius", "value": 1500}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_anterior_radius", "value": 850}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_posterior_radius", "value": 600}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_lateral_radius", "value": 1350}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_anterior_radius", "value": 780}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_posterior_radius", "value": 560}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_lateral_radius", "value": 1125}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_anterior_radius", "value": 680}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_posterior_radius", "value": 540}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_lateral_radius", "value": 875}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_anterior_radius", "value": 500}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_posterior_radius", "value": 400}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_lateral_radius", "value": 1225}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_anterior_radius", "value": 725}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_posterior_radius", "value": 560}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_lateral_radius", "value": 1450}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_anterior_radius", "value": 875}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_posterior_radius", "value": 675}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_lateral_radius", "value": 1500}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_anterior_radius", "value": 900}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_posterior_radius", "value": 700}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_lateral_radius", "value": 420}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_up_radius", "value": 380}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_forward_radius", "value": 400}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_lateral_radius", "value": 340}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_up_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_forward_radius", "value": 330}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_lateral_radius", "value": 520}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_up_radius", "value": 400}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_forward_radius", "value": 480}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_lateral_radius", "value": 780}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_up_radius", "value": 560}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_forward_radius", "value": 720}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_lateral_radius", "value": 700}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_up_radius", "value": 520}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_forward_radius", "value": 650}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_lateral_radius", "value": 500}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_up_radius", "value": 360}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_forward_radius", "value": 520}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_lateral_radius", "value": 430}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_up_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_forward_radius", "value": 500}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_lateral_radius", "value": 340}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_up_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_forward_radius", "value": 360}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_radius", "value": 350}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_x", "value": 1000}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_y", "value": 600}, - {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_z", "value": 900}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_shoulder_depth_radius", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_radius", "value": 190}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_x", "value": 450}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_y", "value": 400}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_z", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_shoulder_depth_radius", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_radius", "value": 190}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_x", "value": 450}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_y", "value": 400}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_z", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_lateral_radius", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_up_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_forward_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_lateral_radius", "value": 250}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_up_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_forward_radius", "value": 230}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_lateral_radius", "value": 230}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_up_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_forward_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_lateral_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_up_radius", "value": 200}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_forward_radius", "value": 190}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_lateral_radius", "value": 180}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_up_radius", "value": 170}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_forward_radius", "value": 160}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_lateral_radius", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_up_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_forward_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_lateral_radius", "value": 250}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_up_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_forward_radius", "value": 230}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_lateral_radius", "value": 230}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_up_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_forward_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_lateral_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_up_radius", "value": 200}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_forward_radius", "value": 190}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_lateral_radius", "value": 180}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_up_radius", "value": 170}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_forward_radius", "value": 160}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_lateral_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_up_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_forward_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_lateral_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_up_radius", "value": 260}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_forward_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_lateral_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_up_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_forward_radius", "value": 225}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_lateral_radius", "value": 225}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_up_radius", "value": 195}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_forward_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_lateral_radius", "value": 185}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_up_radius", "value": 165}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_forward_radius", "value": 175}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_lateral_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_up_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_forward_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_lateral_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_up_radius", "value": 260}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_forward_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_lateral_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_up_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_forward_radius", "value": 225}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_lateral_radius", "value": 225}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_up_radius", "value": 195}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_forward_radius", "value": 210}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_lateral_radius", "value": 185}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_up_radius", "value": 165}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_forward_radius", "value": 175}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_x", "value": 500}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_y", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_z", "value": 700}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_radius", "value": 280}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_x", "value": 500}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_y", "value": 350}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_z", "value": 700}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_lateral_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_up_radius", "value": 150}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_forward_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_lateral_radius", "value": 260}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_up_radius", "value": 150}, - {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_forward_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_lateral_radius", "value": 320}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_up_radius", "value": 150}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_forward_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_lateral_radius", "value": 260}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_up_radius", "value": 150}, - {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_forward_radius", "value": 240}, - {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_root"}, "role": "form_start_radius", "value": 300}, - {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_root"}, "role": "form_end_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_tip"}, "role": "form_start_radius", "value": 220}, - {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_tip"}, "role": "form_end_radius", "value": 40} + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_x", "value": 1.7}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_y", "value": 1.2}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_extent_z", "value": 0.9}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_x", "value": 1.65}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_y", "value": 1.2}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_extent_z", "value": 0.9}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_lateral_radius", "value": 1.5}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_anterior_radius", "value": 0.85}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_lower_pelvis_posterior_radius", "value": 0.6}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_lateral_radius", "value": 1.35}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_anterior_radius", "value": 0.78}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_upper_pelvis_posterior_radius", "value": 0.56}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_lateral_radius", "value": 1.125}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_anterior_radius", "value": 0.68}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_abdomen_posterior_radius", "value": 0.54}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_lateral_radius", "value": 0.875}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_anterior_radius", "value": 0.5}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_waist_abdomen_posterior_radius", "value": 0.4}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_lateral_radius", "value": 1.225}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_anterior_radius", "value": 0.725}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_abdomen_posterior_radius", "value": 0.56}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_lateral_radius", "value": 1.45}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_anterior_radius", "value": 0.875}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_lower_ribcage_posterior_radius", "value": 0.675}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_lateral_radius", "value": 1.5}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_anterior_radius", "value": 0.9}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "torso"}, "role": "form_torso_profile_upper_ribcage_shoulder_posterior_radius", "value": 0.7}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_lateral_radius", "value": 0.42}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_up_radius", "value": 0.38}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_collar_forward_radius", "value": 0.4}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_lateral_radius", "value": 0.34}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_up_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_head_neck_profile_neck_upper_forward_radius", "value": 0.33}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_lateral_radius", "value": 0.52}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_up_radius", "value": 0.4}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_head_base_forward_radius", "value": 0.48}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_lateral_radius", "value": 0.78}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_up_radius", "value": 0.56}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_mid_forward_radius", "value": 0.72}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_lateral_radius", "value": 0.7}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_up_radius", "value": 0.52}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_cranium_crown_forward_radius", "value": 0.65}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_lateral_radius", "value": 0.5}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_up_radius", "value": 0.36}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_root_forward_radius", "value": 0.52}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_lateral_radius", "value": 0.43}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_up_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_mid_forward_radius", "value": 0.5}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_lateral_radius", "value": 0.34}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_up_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_head_neck_profile_muzzle_tip_forward_radius", "value": 0.36}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "neck"}, "role": "form_radius", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_x", "value": 1}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_y", "value": 0.6}, + {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "head"}, "role": "form_extent_z", "value": 0.9}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_shoulder_depth_radius", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_radius", "value": 0.19}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_x", "value": 0.45}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_y", "value": 0.4}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "hand"}, "role": "form_extent_z", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_shoulder_depth_radius", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_radius", "value": 0.19}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_x", "value": 0.45}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_y", "value": 0.4}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "hand"}, "role": "form_extent_z", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_lateral_radius", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_up_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_forward_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_lateral_radius", "value": 0.25}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_up_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_forward_radius", "value": 0.23}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_lateral_radius", "value": 0.23}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_up_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_forward_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_lateral_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_up_radius", "value": 0.2}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_forward_radius", "value": 0.19}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_lateral_radius", "value": 0.18}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_up_radius", "value": 0.17}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_forward_radius", "value": 0.16}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_lateral_radius", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_up_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_start_forward_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_lateral_radius", "value": 0.25}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_up_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_upper_arm_midpoint_forward_radius", "value": 0.23}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_lateral_radius", "value": 0.23}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_up_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "upper_arm"}, "role": "form_arm_profile_elbow_forward_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_lateral_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_up_radius", "value": 0.2}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_midpoint_forward_radius", "value": 0.19}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_lateral_radius", "value": 0.18}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_up_radius", "value": 0.17}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "forearm"}, "role": "form_arm_profile_forearm_distal_forward_radius", "value": 0.16}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_lateral_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_up_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_forward_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_lateral_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_up_radius", "value": 0.26}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_forward_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_lateral_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_up_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_forward_radius", "value": 0.225}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_lateral_radius", "value": 0.225}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_up_radius", "value": 0.195}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_forward_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_lateral_radius", "value": 0.185}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_up_radius", "value": 0.165}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_forward_radius", "value": 0.175}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_lateral_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_up_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_start_forward_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_lateral_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_up_radius", "value": 0.26}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_thigh_midpoint_forward_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_lateral_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_up_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_leg_profile_knee_forward_radius", "value": 0.225}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_lateral_radius", "value": 0.225}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_up_radius", "value": 0.195}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_shin_midpoint_forward_radius", "value": 0.21}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_lateral_radius", "value": 0.185}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_up_radius", "value": 0.165}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_leg_profile_hock_endpoint_forward_radius", "value": 0.175}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "thigh"}, "role": "form_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "shin"}, "role": "form_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_x", "value": 0.5}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_y", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_extent_z", "value": 0.7}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "thigh"}, "role": "form_radius", "value": 0.28}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "shin"}, "role": "form_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_x", "value": 0.5}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_y", "value": 0.35}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_extent_z", "value": 0.7}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_lateral_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_up_radius", "value": 0.15}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_forward_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_lateral_radius", "value": 0.26}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_up_radius", "value": 0.15}, + {"owner": {"namespace": "main", "anchors": ["left"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_forward_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_lateral_radius", "value": 0.32}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_up_radius", "value": 0.15}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_pad_forward_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_lateral_radius", "value": 0.26}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_up_radius", "value": 0.15}, + {"owner": {"namespace": "main", "anchors": ["right"], "kind": "part", "role": "foot"}, "role": "form_foot_profile_toe_forward_radius", "value": 0.24}, + {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_root"}, "role": "form_start_radius", "value": 0.3}, + {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_root"}, "role": "form_end_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_tip"}, "role": "form_start_radius", "value": 0.22}, + {"owner": {"namespace": "main", "anchors": ["tail"], "kind": "part", "role": "tail_tip"}, "role": "form_end_radius", "value": 0.04} ], "frames": [ {"owner": {"namespace": "main", "anchors": [], "kind": "part", "role": "pelvis"}, "role": "form_torso_profile_control", "transform": {"translation": [0, 0, 0], "rotation_xyzw": [0, 0, 0, 1]}}, diff --git a/experiments/current-form-surface-preview/README.md b/experiments/current-form-surface-preview/README.md index 3fa5cb3..095c47a 100644 --- a/experiments/current-form-surface-preview/README.md +++ b/experiments/current-form-surface-preview/README.md @@ -3,9 +3,16 @@ This is an exploratory visual workbench documenting the historical, closed four-variant `creature-kernel.provisional-form-preview.v11` envelope. It converts the -source-authored dimension-backed integer descriptors into analytic ellipsoid, capsule, and -linear-radius tapered-segment fields, folds them in stable full-AddressKey -order, and extracts a bounded continuous surface on a fixed uniform grid. +source-authored canonical metre-valued dimensions into analytic ellipsoid, +capsule, and linear-radius tapered-segment fields, folds them in stable full- +AddressKey order, and extracts a bounded continuous surface on a fixed uniform +grid. The source contains 153 canonical metre-valued dimensions. The +provisional display adapter explicitly derives retained descriptor-local integer +`*_permille` fields for its display controls; those fields are not authored +dimension units. Profile factors are separate integer-permille inputs applied at +the display/profile boundary. Active generated-profile output applies those +factors with exact decimal arithmetic, quantizes to the nearest millimetre +using ties-to-even, and emits canonical metres. It is not a production geometry system, SDF contract, collision system, animation topology, rig, skin, runtime, Readiness 3/4 proof, or DR-0009/0010 @@ -569,6 +576,10 @@ source candidate IDs for the closed regional candidate reproduction, with the standard neutral reference first: `standard_neutral_reference`, `compact_broad_short_limb_large_head`, `tall_narrow_long_legged`, `slender_long_limb`, and `stocky_broad_chested`. +Its active repaired-source binding is SHA-256 +`82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14`, and the +candidate-table bytes are bound by SHA-256 +`a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. Generate their compact canonical BodyDocuments through one shared data-driven transform: @@ -578,15 +589,20 @@ BodyDocuments through one shared data-driven transform: --output-dir /tmp/ck-structural-profile-sources ``` -The transform changes exact integer Part placements and source-authored -permille form dimensions, retains the stable unit neck-to-head reference edge, -preserves normalized route controls and identity rotations, and keeps one tail -module present in each of the five generated profiles while varying tail -length and taper. It fails closed on +The transform changes exact integer Part placements and canonical metre-valued +source dimensions by applying its integer-permille profile factors with exact +decimal arithmetic. Active generated-profile output quantizes each generated +dimension to the nearest millimetre using ties-to-even and emits canonical +metres; it does not reinterpret authored dimensions as permille. It retains the +stable unit neck-to-head reference edge, preserves normalized route controls and +identity rotations, and keeps one tail module present in each of the five +generated profiles while varying tail length and taper. It fails closed on incomplete targets, overlapping or uncovered dimension groups, broken bilateral/alignment/Attachment invariants, unsafe values, or non-atomic output. These are candidate source fixtures and lineage evidence, not public morphology -limits or a production parameter system. +limits or a production parameter system. This repair rebaselines active metadata +hashes only; standard-neutral geometry is expected unchanged, and the historical +source/evidence and its recorded outcome remain untouched. The five-profile source-generation command above is a historical closed-candidate reproduction command, not active runway work. The completed diff --git a/experiments/current-form-surface-preview/generate_structural_profile_sources.py b/experiments/current-form-surface-preview/generate_structural_profile_sources.py index 28c79aa..950872a 100644 --- a/experiments/current-form-surface-preview/generate_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/generate_structural_profile_sources.py @@ -19,6 +19,7 @@ import stat import sys import tempfile +from decimal import ROUND_HALF_EVEN, Decimal, InvalidOperation, localcontext from pathlib import Path, PurePosixPath from typing import Any, Iterable @@ -130,6 +131,36 @@ def _strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: return result +def _is_active_dimension_value_path(path: tuple[str | int, ...]) -> bool: + return ( + len(path) == 4 + and path[0] == "body" + and path[1] == "dimensions" + and isinstance(path[2], int) + and path[3] == "value" + ) + + +def _restore_json_number_types(value: Any, path: tuple[str | int, ...] = ()) -> Any: + """Keep authored dimension tokens exact while retaining ordinary JSON types elsewhere.""" + + if isinstance(value, Decimal): + if _is_active_dimension_value_path(path): + return value + try: + return float(value) + except (OverflowError, ValueError) as exc: + raise ProfileGenerationError("JSON number cannot be represented as a host float") from exc + if isinstance(value, list): + return [_restore_json_number_types(item, path + (index,)) for index, item in enumerate(value)] + if isinstance(value, dict): + return { + key: _restore_json_number_types(item, path + (key,)) + for key, item in value.items() + } + return value + + def load_json_with_bytes(path: Path, label: str) -> tuple[Any, bytes]: try: raw = path.read_bytes() @@ -138,12 +169,14 @@ def load_json_with_bytes(path: Path, label: str) -> tuple[Any, bytes]: if len(raw) > MAX_JSON_BYTES: raise ProfileGenerationError(f"{label} exceeds the bounded JSON size") try: - value = json.loads( + parsed = json.loads( raw.decode("utf-8"), object_pairs_hook=_strict_object, + parse_float=Decimal, parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token)), ) - except (UnicodeDecodeError, json.JSONDecodeError, RecursionError, ValueError) as exc: + value = _restore_json_number_types(parsed) + except (InvalidOperation, OverflowError, UnicodeDecodeError, json.JSONDecodeError, RecursionError, ValueError) as exc: raise ProfileGenerationError(f"{label} is not finite UTF-8 JSON") from exc _finite(value, label) return value, raw @@ -191,6 +224,10 @@ def _finite(value: Any, where: str, *, depth: int = 0, state: list[int] | None = if not math.isfinite(value): raise ProfileGenerationError(f"{where} contains a non-finite number") return + if isinstance(value, Decimal): + if not value.is_finite(): + raise ProfileGenerationError(f"{where} contains a non-finite number") + return if isinstance(value, int) and not isinstance(value, bool): if abs(value) > MAX_SAFE_INTEGER: raise ProfileGenerationError(f"{where} contains an unsafe integer") @@ -237,6 +274,50 @@ def _integer(value: Any, where: str, *, minimum: int = 0, maximum: int = MAX_SAF return value +def _positive_finite_metre(value: Any, where: str) -> Decimal: + """Validate a JSON number as a positive canonical metre value.""" + + if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): + raise ProfileGenerationError(f"{where} must be a positive finite metre number") + if isinstance(value, float) and not math.isfinite(value): + raise ProfileGenerationError(f"{where} must be a positive finite metre number") + try: + decimal = Decimal(str(value)) + except (InvalidOperation, ValueError, TypeError) as exc: + raise ProfileGenerationError(f"{where} must be a positive finite metre number") from exc + if not decimal.is_finite() or decimal <= 0 or decimal > Decimal(MAX_SAFE_INTEGER): + raise ProfileGenerationError(f"{where} must be a positive finite metre number") + return decimal + + +def _decimal_json_number(value: Decimal, where: str) -> int | float: + """Convert exact decimal arithmetic to a finite JSON number without silent rounding.""" + + if not value.is_finite() or value <= 0 or value > Decimal(MAX_SAFE_INTEGER): + raise ProfileGenerationError(f"{where} is outside the safe canonical metre range") + if value == value.to_integral_value(): + return int(value) + number = float(value) + if not math.isfinite(number) or Decimal(str(number)) != value: + raise ProfileGenerationError(f"{where} cannot be emitted without decimal rounding") + return number + + +def _quantize_profile_metres(value: Decimal, scale: int) -> Decimal: + """Apply an integer-permille profile factor and quantize to nearest millimetre.""" + + # The input is bounded by the JSON size limit, but a valid decimal token can + # still contain more digits than Decimal's default context precision. Use + # enough local precision for the source token and the integer scale so the + # only rounding performed here is the requested millimetre quantization. + precision = len(value.as_tuple().digits) + len(str(abs(scale))) + 2 + with localcontext() as context: + context.prec = max(context.prec, precision) + scaled_millimetres = value * Decimal(scale) + quantized_millimetres = scaled_millimetres.to_integral_value(rounding=ROUND_HALF_EVEN) + return quantized_millimetres / Decimal(1000) + + def _vector(value: Any, where: str, length: int = 3) -> list[int]: values = _list(value, where) if len(values) != length: @@ -431,10 +512,19 @@ def _check_attachment_equations(source: dict[str, Any], where: str) -> None: raise ProfileGenerationError(f"{where} Attachment equation failed: host_world + offset != mating_world") -def _validate_source_shape(source: dict[str, Any], candidate: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, Any]]]: +def _validate_source_shape( + source: dict[str, Any], + candidate: dict[str, Any], + *, + mode: str = DEFAULT_GENERATION_MODE, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, Any]]]: _require_keys(source, ("basis", "body", "contract", "extensions", "profiles", "source"), "source") source_metadata = _object(source["source"], "source.source") _require_keys(source_metadata, ("dependencies", "document", "namespace"), "source.source") + if mode == DEFAULT_GENERATION_MODE: + basis = _object(source["basis"], "source.basis") + if basis.get("length_unit") != "metre": + raise ProfileGenerationError("active authored source basis must use metre dimensions") base_source = _object(candidate["base_source"], "candidate.base_source") if source_metadata["document"] != base_source["document"] or source_metadata["namespace"] != base_source["namespace"]: raise ProfileGenerationError("source identity does not match candidate.base_source") @@ -487,7 +577,10 @@ def _validate_source_shape(source: dict[str, Any], candidate: dict[str, Any]) -> owner = _address(dimension["owner"], f"source.body.dimensions[{index}].owner", kind="part") dimension["owner"] = owner dimension["role"] = _text(dimension["role"], f"source.body.dimensions[{index}].role") - _integer(dimension["value"], f"source.body.dimensions[{index}].value", minimum=1, maximum=MAX_SAFE_INTEGER) + if mode == DEFAULT_GENERATION_MODE: + _positive_finite_metre(dimension["value"], f"source.body.dimensions[{index}].value") + else: + _integer(dimension["value"], f"source.body.dimensions[{index}].value", minimum=1, maximum=MAX_SAFE_INTEGER) matches: list[str] = [] for name, selector in normalized_groups.items(): if _matches_dimension(dimension, selector): @@ -518,7 +611,7 @@ def _validate_candidate( if len(base_source["sha256"]) != 64 or any(character not in "0123456789abcdef" for character in base_source["sha256"]): raise ProfileGenerationError("candidate.base_source.sha256 is invalid") _object(candidate["canonicalization"], "candidate.canonicalization") - parts, dimensions, groups = _validate_source_shape(source, candidate) + parts, dimensions, groups = _validate_source_shape(source, candidate, mode=mode) transform = _object(candidate["transform"], "candidate.transform") _require_keys(transform, ("dimension_groups", "placement_targets", "preserved_controls", "reference_edges", "rotation_policy"), "candidate.transform") targets = [_text(item, f"candidate.transform.placement_targets[{index}]") for index, item in enumerate(_list(transform["placement_targets"], "candidate.transform.placement_targets"))] @@ -689,7 +782,13 @@ def point(role: str, anchors: tuple[str, ...] = ()) -> tuple[int, int, int]: raise ProfileGenerationError(f"{where} moves an axial core Part off the shared centerline") -def _apply_profile(source: dict[str, Any], profile: dict[str, Any], groups: dict[str, dict[str, Any]]) -> dict[str, Any]: +def _apply_profile( + source: dict[str, Any], + profile: dict[str, Any], + groups: dict[str, dict[str, Any]], + *, + mode: str = DEFAULT_GENERATION_MODE, +) -> dict[str, Any]: output = copy.deepcopy(source) profile_id = profile["id"] output["source"]["document"] = f"{source['source']['document']}__{SOURCE_DOCUMENT_SUFFIX}__{profile_id}" @@ -712,11 +811,20 @@ def _apply_profile(source: dict[str, Any], profile: dict[str, Any], groups: dict scale = profile["dimension_scales"].get(matches[0]) if scale is None: raise ProfileGenerationError(f"profile {profile_id} is missing transform target group {matches[0]}") - value = _integer(dimension["value"], f"source.body.dimensions[{index}].value", minimum=1) - scaled = _round_permille(value, _integer(scale, f"profile {profile_id}.dimension_scales.{matches[0]}", minimum=1, maximum=10_000)) - if scaled < 1 or scaled > MAX_SAFE_INTEGER: - raise ProfileGenerationError(f"profile {profile_id} generated an unsafe permille value") - dimension["value"] = scaled + integer_scale = _integer(scale, f"profile {profile_id}.dimension_scales.{matches[0]}", minimum=1, maximum=10_000) + if mode == HISTORICAL_GENERATION_MODE: + value = _integer(dimension["value"], f"source.body.dimensions[{index}].value", minimum=1) + scaled = _round_permille(value, integer_scale) + if scaled < 1 or scaled > MAX_SAFE_INTEGER: + raise ProfileGenerationError(f"profile {profile_id} generated an unsafe permille value") + dimension["value"] = scaled + else: + value = _positive_finite_metre(dimension["value"], f"source.body.dimensions[{index}].value") + scaled = _quantize_profile_metres(value, integer_scale) + dimension["value"] = _decimal_json_number( + scaled, + f"profile {profile_id} generated dimension {index}", + ) return output @@ -744,7 +852,7 @@ def _generate_sources( outputs: list[dict[str, Any]] = [] tail_signatures: set[tuple[int, int, int, int, int]] = set() for profile in candidate["profiles"]: - output = _apply_profile(source, profile, groups) + output = _apply_profile(source, profile, groups, mode=mode) _assert_preserved(source, output, source_snapshot) _reference_edge_check(source, output, _object(candidate["transform"], "candidate.transform")) _check_attachment_equations(output, f"profile {profile['id']}") diff --git a/experiments/current-form-surface-preview/structural_profile_candidates.json b/experiments/current-form-surface-preview/structural_profile_candidates.json index 6fd492d..09f0a49 100644 --- a/experiments/current-form-surface-preview/structural_profile_candidates.json +++ b/experiments/current-form-surface-preview/structural_profile_candidates.json @@ -3,10 +3,10 @@ "document": "stylized_digitigrade_biped_authored_form", "namespace": "main", "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", - "sha256": "d4f0dad6f936d62f9ee8c0fa24701898ee4ae6e48bcdeaf44641bd4dc3b549de" + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" }, "canonicalization": { - "number_rule": "integer source placements and permille dimensions only; round-to-nearest ties-to-even for positive integer products", + "number_rule": "source placements remain integer metres and authored dimensions remain positive finite canonical metre numbers; active generated profiles apply integer-permille factors with exact decimal arithmetic, quantize to nearest millimetre ties-to-even, and emit canonical metres; no authored-source permille interpretation", "serialization": "candidate table uses sorted two-space JSON; generated BodyDocuments use compact sorted JSON to retain the existing CLI byte bound; both use UTF-8 and one trailing newline" }, "format": "creature-kernel.disposable-structural-profile-candidates.v1", diff --git a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py index 6b29186..ff236d2 100644 --- a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py @@ -7,12 +7,14 @@ import io import hashlib import json +import math import os import subprocess import sys import tempfile import unittest from contextlib import redirect_stdout +from decimal import Decimal from pathlib import Path from unittest.mock import patch @@ -33,6 +35,20 @@ "slender_long_limb", "stocky_broad_chested", ) +EXPECTED_AUTHORED_DIMENSIONS_PERMILLE = tuple( + int(value) + for value in """ + 1700 1200 900 1650 1200 900 1500 850 600 1350 780 560 1125 680 540 + 875 500 400 1225 725 560 1450 875 675 1500 900 700 420 380 400 340 + 320 330 520 400 480 780 560 720 700 520 650 500 360 520 430 300 500 + 340 240 360 350 1000 600 900 220 350 190 450 400 350 220 350 190 450 + 400 350 350 300 320 250 240 230 230 220 210 210 200 190 180 170 160 + 350 300 320 250 240 230 230 220 210 210 200 190 180 170 160 320 280 300 + 300 260 280 240 210 225 225 195 210 185 165 175 320 280 300 300 260 280 + 240 210 225 225 195 210 185 165 175 280 220 500 350 700 280 220 500 350 + 700 320 150 300 260 150 240 320 150 300 260 150 240 300 220 220 40 + """.split() +) def address(role: str, anchors: list[str] | None = None, kind: str = "part") -> dict[str, object]: @@ -101,13 +117,180 @@ def part(document: dict[str, object], role: str, anchors: list[str] | None = Non raise AssertionError(f"missing Part {wanted}") @classmethod - def dimension(cls, document: dict[str, object], owner_role: str, dimension_role: str, anchors: list[str] | None = None) -> int: + def dimension( + cls, + document: dict[str, object], + owner_role: str, + dimension_role: str, + anchors: list[str] | None = None, + ) -> int | float | Decimal: wanted = address(owner_role, anchors) for dimension in document["body"]["dimensions"]: # type: ignore[index] if dimension["owner"] == wanted and dimension["role"] == dimension_role: # type: ignore[index] return dimension["value"] # type: ignore[index,return-value] raise AssertionError(f"missing dimension {wanted} {dimension_role}") + def test_authored_dimensions_are_exactly_153_converted_canonical_metres(self) -> None: + dimensions = self.base["body"]["dimensions"] # type: ignore[index] + self.assertEqual(self.base["basis"]["length_unit"], "metre") # type: ignore[index] + self.assertEqual(len(dimensions), 153) + self.assertEqual(len(EXPECTED_AUTHORED_DIMENSIONS_PERMILLE), 153) + for index, (dimension, expected_permille) in enumerate( + zip(dimensions, EXPECTED_AUTHORED_DIMENSIONS_PERMILLE, strict=True) + ): + with self.subTest(index=index): + value = Decimal(str(dimension["value"])) # type: ignore[index] + self.assertGreater(value, 0) + self.assertEqual(value * 1000, Decimal(expected_permille)) + self.assertLess(value, 2) + + @staticmethod + def non_dimension_source_projection(document: dict[str, object]) -> dict[str, object]: + projection = copy.deepcopy(document) + projection["source"].pop("document") # type: ignore[index] + for module in projection["body"]["modules"]: # type: ignore[index] + module["declaration"].pop("document") # type: ignore[index] + projection["body"].pop("dimensions") # type: ignore[index] + return projection + + def test_active_generation_preserves_non_dimension_source_projection(self) -> None: + neutral = self.sources["standard_neutral_reference"] + self.assertEqual( + self.non_dimension_source_projection(neutral), + self.non_dimension_source_projection(self.base), + ) + + def test_source_hash_is_exactly_bound_to_the_canonical_authored_bytes(self) -> None: + source_hash = hashlib.sha256(self.source_path.read_bytes()).hexdigest() + self.assertEqual(self.candidate["base_source"]["sha256"], source_hash) # type: ignore[index] + manifest = json.loads((self.output_dir / "manifest.json").read_text(encoding="utf-8")) + self.assertEqual(manifest["source"]["source_sha256"], source_hash) + + def test_profile_scaling_preserves_prior_effective_millimetre_values(self) -> None: + _, _, groups, _ = generator._validate_candidate(copy.deepcopy(self.candidate), copy.deepcopy(self.base)) + for profile in self.candidate["profiles"]: # type: ignore[index] + profile_id = profile["id"] # type: ignore[index] + generated = self.sources[profile_id] + for index, (source_dimension, generated_dimension) in enumerate( + zip( + self.base["body"]["dimensions"], # type: ignore[index] + generated["body"]["dimensions"], # type: ignore[index] + strict=True, + ) + ): + with self.subTest(profile=profile_id, index=index): + matches = [ + name + for name, selector in groups.items() + if generator._matches_dimension(source_dimension, selector) + ] + self.assertEqual(len(matches), 1) + scale = profile["dimension_scales"][matches[0]] # type: ignore[index] + expected_permille = generator._round_permille( + EXPECTED_AUTHORED_DIMENSIONS_PERMILLE[index], + scale, + ) + actual_metres = Decimal(str(generated_dimension["value"])) # type: ignore[index] + self.assertEqual(actual_metres * 1000, Decimal(expected_permille)) + + def test_active_profile_quantization_uses_millimetre_ties_to_even(self) -> None: + self.assertEqual( + generator._quantize_profile_metres(Decimal("0.65"), 1250), + Decimal("0.812"), + ) + self.assertEqual( + generator._quantize_profile_metres(Decimal("0.65"), 1350), + Decimal("0.878"), + ) + compact = self.sources["compact_broad_short_limb_large_head"] + self.assertEqual( + self.dimension( + compact, + "head", + "form_head_neck_profile_cranium_crown_forward_radius", + ), + 0.812, + ) + + def test_active_profile_write_preserves_decimal_tokens_at_half_millimetre(self) -> None: + marker = b'"role": "form_head_neck_profile_cranium_crown_forward_radius", "value": 0.65' + expected_permille = { + "just_below": 812, + "tie": 812, + "just_above": 813, + } + for label, token in ( + ("just_below", "0.6499999999999999999"), + ("tie", "0.65"), + ("just_above", "0.6500000000000000001"), + ): + with self.subTest(token=label): + source_bytes = self.source_path.read_bytes() + self.assertEqual(source_bytes.count(marker), 1) + source_bytes = source_bytes.replace(marker, marker.replace(b"0.65", token.encode("ascii")), 1) + source_path = self.root / f"{label}-source.json" + source_path.write_bytes(source_bytes) + + loaded_source, loaded_bytes = generator.load_json_with_bytes(source_path, f"{label} source") + self.assertEqual( + self.dimension( + loaded_source, + "head", + "form_head_neck_profile_cranium_crown_forward_radius", + ), + Decimal(token), + ) + + candidate = copy.deepcopy(self.candidate) + candidate["base_source"]["sha256"] = hashlib.sha256(loaded_bytes).hexdigest() # type: ignore[index] + candidate_path = self.root / f"{label}-candidate.json" + candidate_path.write_bytes(generator.canonical_bytes(candidate)) + output_dir = self.root / f"{label}-sources" + manifest = generator.write_sources(candidate_path, source_path, output_dir) + generated = json.loads( + (output_dir / "compact_broad_short_limb_large_head.json").read_text(encoding="utf-8") + ) + actual_value = self.dimension( + generated, + "head", + "form_head_neck_profile_cranium_crown_forward_radius", + ) + self.assertEqual(Decimal(str(actual_value)) * 1000, Decimal(expected_permille[label])) + self.assertEqual(manifest["source"]["source_sha256"], hashlib.sha256(source_bytes).hexdigest()) # type: ignore[index] + values = [item["value"] for item in generated["body"]["dimensions"]] # type: ignore[index] + self.assertTrue( + all( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(float(value)) + for value in values + ) + ) + + def test_generated_dimensions_remain_positive_finite_canonical_metres(self) -> None: + for profile_id, document in self.sources.items(): + with self.subTest(profile=profile_id): + self.assertEqual(document["basis"]["length_unit"], "metre") # type: ignore[index] + values = [item["value"] for item in document["body"]["dimensions"]] # type: ignore[index] + self.assertEqual(len(values), 153) + self.assertTrue( + all( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(float(value)) + and Decimal(str(value)) > 0 + for value in values + ) + ) + self.assertTrue( + all( + Decimal(str(value)) * 1000 + == (Decimal(str(value)) * 1000).to_integral_value() + for value in values + ) + ) + self.assertTrue(any(isinstance(value, float) for value in values)) + def test_freezes_exactly_five_canonical_sources_with_lineage(self) -> None: self.assertEqual(len(PROFILE_IDS), 5) self.assertEqual([profile["id"] for profile in self.candidate["profiles"]], PROFILE_IDS) @@ -132,10 +315,22 @@ def test_freezes_exactly_five_canonical_sources_with_lineage(self) -> None: serialized = (self.output_dir / f"{profile_id}.json").read_bytes() self.assertEqual(serialized, generator.canonical_source_bytes(document)) self.assertLessEqual(len(serialized), generator.MAX_OUTPUT_JSON_BYTES) - self.assertTrue(all(isinstance(item["value"], int) and item["value"] > 0 for item in document["body"]["dimensions"])) # type: ignore[index] + self.assertTrue( + all( + isinstance(item["value"], (int, float)) + and not isinstance(item["value"], bool) + and math.isfinite(float(item["value"])) + and Decimal(str(item["value"])) > 0 + for item in document["body"]["dimensions"] # type: ignore[index] + ) + ) self.assertLessEqual((self.output_dir / "manifest.json").stat().st_size, generator.MAX_OUTPUT_JSON_BYTES) def test_historical_four_profile_mode_is_explicit_and_byte_bound(self) -> None: + historical_candidate_bytes = generator.HISTORICAL_CANDIDATE.read_bytes() + historical_source_bytes = generator.HISTORICAL_SOURCE.read_bytes() + self.assertEqual(hashlib.sha256(historical_candidate_bytes).hexdigest(), generator.HISTORICAL_CANDIDATE_SHA256) + self.assertEqual(hashlib.sha256(historical_source_bytes).hexdigest(), generator.HISTORICAL_SOURCE_SHA256) historical_candidate = json.loads(generator.HISTORICAL_CANDIDATE.read_bytes()) historical_source = json.loads(generator.HISTORICAL_SOURCE.read_bytes()) with self.assertRaisesRegex(generator.ProfileGenerationError, "exactly 5 profiles"): @@ -257,7 +452,7 @@ def test_thigh_roots_are_symmetric_and_inside_scaled_lower_pelvis(self) -> None: "pelvis", "form_torso_profile_lower_pelvis_lateral_radius", ) - self.assertLess(abs(left[0]) * 1000, lower_pelvis_radius) + self.assertLess(Decimal(str(abs(left[0]))), Decimal(str(lower_pelvis_radius))) expected_thigh_y = { "standard_neutral_reference": -1, "compact_broad_short_limb_large_head": -1, @@ -297,20 +492,20 @@ def test_shared_torso_profile_keeps_endpoints_and_moves_fullness_lower(self) -> [0, 0.95, 0], ) expected_radii = { - "form_torso_profile_lower_pelvis": (1500, 850, 600), - "form_torso_profile_upper_pelvis": (1350, 780, 560), - "form_torso_profile_lower_abdomen": (1125, 680, 540), - "form_torso_profile_waist_abdomen": (875, 500, 400), - "form_torso_profile_upper_abdomen": (1225, 725, 560), - "form_torso_profile_lower_ribcage": (1450, 875, 675), - "form_torso_profile_upper_ribcage_shoulder": (1500, 900, 700), + "form_torso_profile_lower_pelvis": (1.5, 0.85, 0.6), + "form_torso_profile_upper_pelvis": (1.35, 0.78, 0.56), + "form_torso_profile_lower_abdomen": (1.125, 0.68, 0.54), + "form_torso_profile_waist_abdomen": (0.875, 0.5, 0.4), + "form_torso_profile_upper_abdomen": (1.225, 0.725, 0.56), + "form_torso_profile_lower_ribcage": (1.45, 0.875, 0.675), + "form_torso_profile_upper_ribcage_shoulder": (1.5, 0.9, 0.7), } for role, (lateral, anterior, posterior) in expected_radii.items(): with self.subTest(role=role): self.assertEqual(self.dimension(neutral, "torso" if "pelvis" not in role else "pelvis", f"{role}_lateral_radius"), lateral) self.assertEqual(self.dimension(neutral, "torso" if "pelvis" not in role else "pelvis", f"{role}_anterior_radius"), anterior) self.assertEqual(self.dimension(neutral, "torso" if "pelvis" not in role else "pelvis", f"{role}_posterior_radius"), posterior) - self.assertEqual(self.dimension(neutral, "torso", "form_extent_y"), 1200) + self.assertEqual(self.dimension(neutral, "torso", "form_extent_y"), 1.2) def test_profile_inequalities_and_tail_style_contrast_are_real_source_differences(self) -> None: neutral = self.sources[PROFILE_IDS[0]] diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 7d55000..e786e70 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -22,12 +22,12 @@ Related DRs: DR-0013 context only; DR-0009 and DR-0010 remain parked ## Status and authority -This is a draft contract for one new, bounded, standard-neutral experiment. It -is the successor direction authorized after the seven-ring candidate in PR -#125 reached its three-round stop rule. It does not accept a production -schema, architecture, topology, supported morphology promise, or technology -outcome. It does not reactivate a parked workstream or satisfy the DR-0013 -Stage 1 proof. +This is the settled candidate plan for one new, bounded, standard-neutral +experiment. It is the successor direction authorized after the seven-ring +candidate in PR #125 reached its three-round stop rule. It does not accept a +production schema, architecture, topology, supported morphology promise, or +technology outcome. It does not reactivate a parked workstream or satisfy the +DR-0013 Stage 1 proof. The previous candidate is evidence, not a foundation to transplant. Its seven-ring topology, projection, formulas, macros, IDs, thresholds, and @@ -84,19 +84,31 @@ The first and only execution target in this plan is the standard-neutral profile. The exact source inputs are: 1. `examples/body-documents/stylized-digitigrade-biped-authored-form.json` - — authoritative authored anatomy source at frozen-plan hash - `d4f0dad6f936d62f9ee8c0fa24701898ee4ae6e48bcdeaf44641bd4dc3b549de`. + — authoritative repaired authored anatomy source and frozen input, 56,984 + bytes, at SHA-256 + `82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14`. 2. `experiments/current-form-surface-preview/structural_profile_candidates.json` — supporting source for the existing profile identity and its - standard-neutral selection, at frozen-plan hash - `6794c7ec273cdbdc66e5bbe1f4816237a45f60a086315e40e0ef4ce6d18ddc0a`. + standard-neutral selection, frozen as an input at SHA-256 + `a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. The authored document owns the source addresses, roles, frames, landmarks, section measurements, module state, and provenance. The profile table may identify the standard-neutral source selection and later the existing ordered five-profile comparison; it must never select topology or geometry code. -Before execution, the launcher records both source hashes and stops on source -drift rather than silently using a new input. +All 153 canonical dimensions in the repaired source are metre-valued; its +non-dimension transforms and landmarks remain unchanged. The provisional +display adapter derives any retained descriptor-local integer `*_permille` +fields explicitly, while profile factors remain separate integer-permille +inputs. Active generated-profile output applies those factors with exact +decimal arithmetic, quantizes to the nearest millimetre using ties-to-even, +and emits canonical metres. Before execution, the launcher records both active +source hashes and stops on source drift rather than silently using a new input. + +This is a metadata/hash rebaseline only. Standard-neutral geometry is expected +to remain unchanged, and the historical source/evidence is not rewritten. This +README does not claim that the successor contract is implemented or that +successor execution has begun. The prepared input may contain only source-derived frames, named landmarks, section measurements, derived scalar parameters, module state, and provenance. diff --git a/experiments/programmatic-root-complex-surface/README.md b/experiments/programmatic-root-complex-surface/README.md index ff78c9f..7e4edef 100644 --- a/experiments/programmatic-root-complex-surface/README.md +++ b/experiments/programmatic-root-complex-surface/README.md @@ -58,12 +58,29 @@ protocol](../../docs/research/visual-quality-evaluation.md). The admission gate accepts only source-derived scalar dimensions or measurements, rigid frames, individually named landmarks, section stations with scalar width/depth/offset/taper/squareness, module state, and provenance. +Dimension values are finite, strictly positive canonical metre values and are +admitted exactly as authored; this consumer does not interpret integers as +thousandths or apply a `/1000` scale. The prepared input is capped at 8 frames, 24 landmarks, 10 stations, and 6 scalars per station. Every numeric value carries source provenance or a deterministic derivation. The four scalar records emitted by the frozen projection and the seven declared shared formula-constant override names are the complete accepted scalar-name set. +### Standard-neutral regression provenance + +The standard-neutral geometry and render outputs have durable regression +identities at the actual builder boundary: `skin.ply` is +`bb1d19d8264c9df7575a978b523346477b7ac30e62d955736bfa7b68bf7ed6cf`, `skin.png` +is `695eec4a39742ecdda501ca84d930c7a28eca10f9a637e9dc0878647cf5d39ce`, and +`cage.png` is +`06e17b31d909936fbe1151ae3853bb8b52e7b8bb52112745e8d7e86604bde046`. These +three digests were cross-checked against the prior exact commit +`fc2d56555e063680b15c67f7d438c4eb375c498b`, built with the former +source/adapter. Metadata hashes intentionally rebaseline across the canonical +unit migration. This is regression provenance for unchanged geometry/rendering, +not acceptance of the historical experiment. + The following are forbidden inputs: cage or mesh vertices, faces, edges, rings, or connectivity; ordered perimeter samples; point clouds, fields, masks, or silhouettes; corrective offsets; serialized old output; and any data trivially diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index 1b2f018..b43bbc8 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -16,7 +16,8 @@ class PreparedProjectionError(ValueError): _BODY = {"attachments", "capabilities", "dimensions", "fields", "frames", "joints", "landmarks", "modules", "parts", "regions", "sockets"} _COUNT = {"parts": 18, "frames": 16, "landmarks": 43, "dimensions": 153} _I = (0, 0, 0, 1) -_D = "derivation=source_dimension_integer_as_thousandths_of_canonical_metre_v1" +_DIMENSION = {"owner", "role", "value"} +_D = "provenance=source_dimension_canonical_metre_value_v1" _P = "derivation=parent_local_part_translation_plus_landmark_position_v1" @@ -25,7 +26,9 @@ def _ok(condition, where, message): if not condition: _bad(where, message) def _dict(value, where): _ok(isinstance(value, dict), where, "expected object"); return value def _num(value, where, positive=False): - _ok(not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value), where, "expected finite number"); _ok(not positive or value > 0, where, "expected positive number"); return 0 if value == 0 else value + _ok(not isinstance(value, bool) and isinstance(value, (int, float)), where, "expected finite number") + _ok(not isinstance(value, float) or math.isfinite(value), where, "expected finite number") + _ok(not positive or value > 0, where, "expected positive number"); return 0 if value == 0 else value def _vec(value, where, size=3): _ok(isinstance(value, list) and len(value) == size, where, f"expected {size}-vector"); return tuple(_num(x, f"{where}[{i}]") for i, x in enumerate(value)) def _pairs(items): @@ -56,8 +59,15 @@ def _part(rows, owner, parent): _ok(containment == {"root": True} if parent is None else set(containment) == {"parent"} and _addr(containment["parent"], where) == parent, where, "invalid containment") return translation, where def _add(a, b): return tuple(x + y for x, y in zip(a, b)) +def _validate_dimensions(rows): + for i, raw in enumerate(rows): + where, row = f"body.dimensions[{i}]", _dict(raw, f"body.dimensions[{i}]") + _ok(set(row) == _DIMENSION, where, "unknown or missing required field") + _addr(row["owner"], f"{where}.owner") + _ok(isinstance(row["role"], str) and row["role"], f"{where}.role", "expected non-empty role") + _num(row["value"], f"{where}.value", positive=True) def _dimension(rows, owner, role): - row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions"); value = _num(row["value"], f"{where}.value", True) / 1000.0 + row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions"); value = _num(row["value"], f"{where}.value", True) return value, f"{where}.value; {_D}" def _landmark(rows, owner, role, frame): row, where = _pick(rows, owner, role, {"owner", "role", "frame", "position"}, "landmarks"); ref = _dict(row["frame"], f"{where}.frame"); _ok(set(ref) == {"owner", "role"} and (_addr(ref["owner"], where), ref["role"]) == frame, where, "invalid landmark frame"); return _vec(row["position"], f"{where}.position"), where @@ -76,6 +86,7 @@ def prepare_standard_neutral(path): _ok(source["profiles"] == {"semantic_numeric": "ck.numeric-frame.r1"} and source["extensions"] == [], "source", "unsupported profile or extension") body = _dict(source["body"], "source.body"); _ok(set(body) == _BODY, "source.body", "unknown or missing collection") for name, count in _COUNT.items(): _ok(isinstance(body[name], list) and len(body[name]) == count, f"body.{name}", f"expected {count} records") + _validate_dimensions(body["dimensions"]) ns = source["source"]["namespace"] def part(role, side=None): return ns, () if side is None else (side,), "part", role p = {part("pelvis"): _part(body["parts"], part("pelvis"), None), part("torso"): _part(body["parts"], part("torso"), part("pelvis")), part("neck"): _part(body["parts"], part("neck"), part("torso"))} diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index d0fbc00..3fa03ef 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -52,6 +52,35 @@ def test_source_identity_provenance_and_expected_controls(self): self.assertGreater(self.prepared["landmarks"]["shoulder_peak_right"]["point"][0], 0) self.assertEqual(self.prepared["scalars"]["arm_root_depth"]["value"], 0.32) self.assertEqual(self.prepared["scalars"]["thigh_lateral_radius"]["value"], 0.32) + dimension_records = list(self.prepared["stations"].values()) + list(self.prepared["scalars"].values()) + self.assertTrue(all("source_dimension_canonical_metre_value_v1" in record["provenance"] for record in dimension_records)) + + @staticmethod + def set_dimension_value(source, role, value): + matches = [row for row in source["body"]["dimensions"] if row.get("role") == role] + if not matches: + raise AssertionError(f"dimension role not found: {role}") + for row in matches: + row["value"] = value + + def prepared_from_mutated_source(self, mutate): + source = json.loads(SOURCE.read_text(encoding="utf-8")) + mutate(source) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "source.json"; path.write_text(json.dumps(source), encoding="utf-8") + return prepare_standard_neutral(path) + + def test_canonical_metre_dimensions_are_admitted_without_rescaling(self): + prepared = self.prepared_from_mutated_source(lambda source: (self.set_dimension_value(source, "form_torso_profile_lower_pelvis_lateral_radius", 1.5), self.set_dimension_value(source, "form_arm_profile_upper_arm_start_forward_radius", 0.32))) + self.assertEqual(prepared["stations"]["lower_pelvis"]["lateral_radius"], 1.5) + self.assertEqual(prepared["scalars"]["arm_root_depth"]["value"], 0.32) + + def test_non_dimension_routes_remain_unchanged_when_dimensions_change(self): + prepared = self.prepared_from_mutated_source(lambda source: (self.set_dimension_value(source, "form_torso_profile_lower_pelvis_lateral_radius", 1.25), self.set_dimension_value(source, "form_arm_profile_upper_arm_start_forward_radius", 0.28))) + self.assertEqual(prepared["basis"], self.prepared["basis"]) + self.assertEqual(prepared["frames"], self.prepared["frames"]) + self.assertEqual(prepared["landmarks"], self.prepared["landmarks"]) + self.assertEqual({name: station["center"] for name, station in prepared["stations"].items()}, {name: station["center"] for name, station in self.prepared["stations"].items()}) def test_canonical_bytes_and_forbidden_payloads(self): again = prepare_standard_neutral(SOURCE) @@ -67,10 +96,17 @@ def assert_rejected(self, mutate): path = Path(directory) / "source.json"; path.write_text(json.dumps(source), encoding="utf-8") with self.assertRaises(PreparedProjectionError): prepare_standard_neutral(path) + def test_dimension_values_fail_closed_for_booleans_nonfinite_and_nonpositive_values(self): + for value in (True, False, float("nan"), float("inf"), 0, -0.01): + with self.subTest(value=value): + self.assert_rejected(lambda source, value=value: self.set_dimension_value(source, "form_torso_profile_lower_pelvis_lateral_radius", value)) + + def test_unused_dimension_value_fails_closed(self): + self.assert_rejected(lambda source: source["body"]["dimensions"][0].__setitem__("value", 0)) + def test_required_source_shape_and_routes_fail_closed(self): self.assert_rejected(lambda source: source["basis"].__setitem__("forward", "-z")) self.assert_rejected(lambda source: source["source"].__setitem__("document", "other")) - self.assert_rejected(lambda source: source["body"]["dimensions"][6].__setitem__("value", 0)) self.assert_rejected(lambda source: source["body"]["landmarks"][15].__setitem__("position", [0, 0, 0])) self.assert_rejected(lambda source: source["body"]["landmarks"].__setitem__(42, copy.deepcopy(source["body"]["landmarks"][24]))) self.assert_rejected(lambda source: source["body"]["landmarks"].__setitem__(0, {})) diff --git a/experiments/programmatic-root-complex-surface/tests/test_render_export.py b/experiments/programmatic-root-complex-surface/tests/test_render_export.py index d952f65..aac4c41 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_render_export.py +++ b/experiments/programmatic-root-complex-surface/tests/test_render_export.py @@ -96,6 +96,8 @@ def test_builder_rejects_nonzero_intersections_before_publication(self) -> None: def test_builder_publishes_complete_metrics_and_manifest(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-build-") as d: target = Path(d) / "standard-neutral"; self.assertEqual(builder.build(SOURCE, target), target); self.assertEqual({p.name for p in target.iterdir()}, set(ARTIFACTS)) + expected = {"skin.ply": "bb1d19d8264c9df7575a978b523346477b7ac30e62d955736bfa7b68bf7ed6cf", "skin.png": "695eec4a39742ecdda501ca84d930c7a28eca10f9a637e9dc0878647cf5d39ce", "cage.png": "06e17b31d909936fbe1151ae3853bb8b52e7b8bb52112745e8d7e86604bde046"} + for name, digest in expected.items(): self.assertEqual(hashlib.sha256((target / name).read_bytes()).hexdigest(), digest, name) metrics = json.loads((target / "metrics.json").read_text(encoding="utf-8")); manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8")); self.assertEqual(metrics["intersection_status"], "zero"); self.assertEqual(metrics["intersection_counts_by_level"], [0, 0]); self.assertEqual(set(manifest["files"]), set(ARTIFACTS[:-1])); self.assertEqual(manifest["files"]["metrics.json"], hashlib.sha256((target / "metrics.json").read_bytes()).hexdigest()) def test_atomic_publication_refuses_existing_target_without_overwrite(self) -> None: From 6f69ef3966a9432ae164fb67a6fefef848a5e645 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 19:55:52 +1200 Subject: [PATCH 04/38] Freeze owned root assembly contract --- docs/project/status.md | 19 +- .../owned-root-assembly-investigation.md | 43 +- experiments/README.md | 7 +- .../owned-root-assembly-successor/README.md | 115 +- .../design-contract.md | 3302 +++++++++++++++++ .../design-contract.sha256 | 1 + 6 files changed, 3402 insertions(+), 85 deletions(-) create mode 100644 experiments/owned-root-assembly-successor/design-contract.md create mode 100644 experiments/owned-root-assembly-successor/design-contract.sha256 diff --git a/docs/project/status.md b/docs/project/status.md index 3186289..60eb640 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -29,21 +29,24 @@ correction rounds. Construction ownership, semantic causality, and evaluated-surface contributor/chart lineage remain separate; every output must be owned or have a declared junction or contributor record. -The successor must use the authored `neck_upper` and `upper_abdomen` controls -and freeze its oriented interfaces, patch layout, port orientation, -extraordinary placement/valence, continuity, normal/fold bounds, subdivision -support, causality matrix, and locality perturbations before rendering. It +The successor uses the authored `neck_upper` and `upper_abdomen` controls; its +oriented interfaces, patch layout, port orientation, extraordinary +placement/valence, continuity, normal/fold bounds, subdivision support, +causality matrix, and locality perturbations are frozen before rendering. It replaces the old port-span anatomy gates with candidate-specific checks for neck exposure, shoulder descent, axillary concavity, pelvic wrap, and downward thigh-root orientation. Direct skin and ownership diagnostics must be renders of the same evaluated surface, and categorical colour cannot stand in for causality. -The plan remains non-executable until the required +The required `experiments/owned-root-assembly-successor/design-contract.md` freeze artifact -exists, has a recorded SHA-256 identity, and supplies all pre-build finite -complexity caps and candidate details required by the investigation. The -future builder must reject a missing or mismatched design-contract identity. +is now frozen and SHA-256-bound at +`3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`, recorded +by its sidecar. Two independent Sol reviews returned `FREEZE` with zero +blockers. The bounded implementation phase is active at +`correction_round=0`; the builder must reject a missing or mismatched +design-contract identity. Advance only through the documented bounded implementation and internal gates. Do not add profile branches, hidden skin, render corrections, solvers, distal diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index 6680355..fbe8f42 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -1,7 +1,7 @@ # Owned root assembly investigation -Status: Settled candidate plan; Ben-authorized bounded investigation; -experiment-local and non-normative +Status: Frozen candidate implementation phase; Ben-authorized bounded +investigation; experiment-local and non-normative This is the settled successor plan after the terminal seven-ring candidate in the [programmatic root-complex investigation](programmatic-root-complex-surface-investigation.md). @@ -29,7 +29,7 @@ with SHA-256 `a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. This is a source/hash metadata rebaseline only: standard-neutral geometry is expected to remain unchanged. Historical source and evidence remain untouched; this -record does not claim that the successor contract is implemented. +record does not claim that the successor implementation is complete. ## Research-question mapping @@ -90,8 +90,8 @@ and 120 base quads, two subdivision levels, oriented port boundaries, and declared interface cardinality before rendering. Use existing authored `neck_upper` and `upper_abdomen` controls. The exact topology, chart degrees, port orientations, extraordinary placement and valence, continuity tolerances, -normal/fold bounds, and subdivision support are candidate inputs to freeze -before coordinates or images are judged. +normal/fold bounds, and subdivision support are frozen in the required design +contract before coordinates or images are judged. Each domain owns its interior faces and controls. Each shared boundary is represented once by a named junction owned by its incident domains; there are @@ -125,20 +125,19 @@ render-only correction. ## Required design contract -Before any executable build exists, create -`experiments/owned-root-assembly-successor/design-contract.md` as the sole -freeze artifact for the candidate design. It is intentionally not created by -this plan-writing change. Once created, its exact raw bytes receive a recorded -SHA-256 identity, and the future builder must require that identity and reject -a missing file or any mismatch before admitting inputs or producing output. -This investigation remains explicitly non-executable until that record and its -identity exist. - -The design contract must freeze every item in the preflight below. It must also -set finite caps for total junction count and interface cardinality; chart, -formula, and dependency counts; candidate special cases; and non-test -implementation and test LOC. This plan intentionally does not invent those -numeric values. +The required sole freeze artifact for the candidate design is +`experiments/owned-root-assembly-successor/design-contract.md`. Its exact raw +bytes are frozen and SHA-256-bound at +`3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`, recorded +by `experiments/owned-root-assembly-successor/design-contract.sha256`. The +builder must require that identity and reject a missing file or any mismatch +before admitting inputs or producing output. The bounded implementation is +next under this frozen contract; no implementation result is implied. + +The frozen design contract covers every item in the preflight below and sets +finite caps for total junction count and interface cardinality; chart, formula, +and dependency counts; candidate special cases; and non-test implementation +and test LOC. This plan intentionally does not invent those numeric values. ## Frozen preflight and evidence gates @@ -182,9 +181,9 @@ The next implementation work proceeds in this order: 1. audit the terminal candidate's utilities for representation-independent reuse; -2. create and SHA-256-bind the required design contract, freezing the - successor's neutral topology, interfaces, dependencies, finite complexity - caps, tolerances, and evidence views; +2. verify the frozen, SHA-256-bound design contract and its successor-neutral + topology, interfaces, dependencies, finite complexity caps, tolerances, and + evidence views; 3. implement the bounded owned-domain/junction cage and the three-layer records; 4. run ownership, causality, locality, topology, geometry, determinism, and diff --git a/experiments/README.md b/experiments/README.md index dd3dcf8..95d97a1 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -113,9 +113,10 @@ surface-comparison authority. The [owned root assembly successor](owned-root-assembly-successor/README.md) is the unregistered exploratory successor targeting open `RQ-002`, `RQ-012`, -`RQ-020`, and `RQ-021`. It is not `EXP-0001`, remains non-executable until its -required SHA-256-bound design contract exists, and cannot establish a formal -technology outcome, production surface contract, or Stage 1 result. +`RQ-020`, and `RQ-021`. It is not `EXP-0001`; its candidate-local design +contract is frozen and SHA-256-bound, and its bounded implementation phase is +active at `correction_round=0`. It cannot establish a formal technology +outcome, production surface contract, or Stage 1 result. ## Artifact policy diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index e786e70..09d5988 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -1,6 +1,7 @@ # Owned root assembly successor -Status: bounded experiment-local successor plan; non-normative +Status: bounded experiment-local successor implementation phase; frozen, +SHA-256-bound, non-normative Experiment lifecycle: planned @@ -20,11 +21,20 @@ experiment does not change their lifecycle. Related DRs: DR-0013 context only; DR-0009 and DR-0010 remain parked +Freeze state: double-FREEZE; two independent Sol reviews returned `FREEZE` +with zero blockers + +Design contract SHA-256: `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490` + +`correction_round=0`: initial implementation phase; at most two shared +correction rounds remain available after the initial build + ## Status and authority -This is the settled candidate plan for one new, bounded, standard-neutral -experiment. It is the successor direction authorized after the seven-ring -candidate in PR #125 reached its three-round stop rule. It does not accept a +This is the frozen candidate contract and bounded implementation phase for one +new, standard-neutral experiment. It is the successor direction authorized +after the seven-ring candidate in PR #125 reached its three-round stop rule. +It remains an unaccepted experiment-local candidate: it does not accept a production schema, architecture, topology, supported morphology promise, or technology outcome. It does not reactivate a parked workstream or satisfy the DR-0013 Stage 1 proof. @@ -106,9 +116,10 @@ and emits canonical metres. Before execution, the launcher records both active source hashes and stops on source drift rather than silently using a new input. This is a metadata/hash rebaseline only. Standard-neutral geometry is expected -to remain unchanged, and the historical source/evidence is not rewritten. This -README does not claim that the successor contract is implemented or that -successor execution has begun. +to remain unchanged, and the historical source/evidence is not rewritten. The +design contract is now frozen and SHA-256-bound; this README activates the +bounded implementation phase but does not claim that implementation evidence +or successor execution results exist. The prepared input may contain only source-derived frames, named landmarks, section measurements, derived scalar parameters, module state, and provenance. @@ -176,25 +187,24 @@ The hard experiment caps are fixed before the design pass: - exactly 2 declared subdivision levels; - at most 2 shared correction rounds after the initial build. -These are caps, not a chosen topology. The experiment must not claim an exact -control count, boundary cardinality, patch degree, extraordinary-vertex -placement, or coordinate layout until the bounded design pass below freezes -those details. All eight named domain interiors must be nonempty. If the -design cannot satisfy the caps and ownership rules, it stops before -coordinates are authored. - -## Freeze-before-build obligations - -One bounded design pass must create -`experiments/owned-root-assembly-successor/design-contract.md`. That required -freeze artifact does not exist yet and must not be created as part of this -plan-review correction. Its exact raw bytes must receive a recorded SHA-256 -identity. The future builder must require the expected identity, hash the file -before admitting source inputs, and reject a missing file or mismatch without -producing an artifact. This plan is non-executable until the file and recorded -identity exist. - -The design contract must freeze all details needed to make the candidate +These are caps, not a product contract. The frozen design contract records the +exact topology, boundary cardinality, patch degree, extraordinary-vertex +placement, and coordinate rules for this candidate. All eight named domain +interiors must be nonempty. If the implementation cannot satisfy the caps and +ownership rules, it stops before producing evidence. + +## Frozen design contract and implementation phase + +The bounded design pass created +`experiments/owned-root-assembly-successor/design-contract.md` as the sole +freeze artifact for the candidate design. Its exact raw bytes are recorded in +`experiments/owned-root-assembly-successor/design-contract.sha256` with +SHA-256 `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`. +The builder must require that identity, hash the file before admitting source +inputs, and reject a missing file or mismatch without producing an artifact. +The bounded implementation phase is active under this frozen contract. + +The frozen design contract fixes all details needed to make the candidate reproducible without inventing them during coding: - all eight named, nonempty domain interiors and their required anatomical @@ -215,14 +225,14 @@ reproducible without inventing them during coding: - the exact preflight, build, artifact, and comparison commands. It must reject any domain interior that crosses a required anatomical boundary -instead of meeting another domain through a declared junction. It must also -set finite caps for total junction count and interface cardinality; chart, -formula, and dependency counts; candidate special cases; and non-test -implementation and test LOC. Numeric values are deliberately not selected in -this README; the design contract must freeze them before build. - -This pass freezes obligations and measurable tolerances before geometry -coordinates or visual tuning. It must not smuggle in arbitrary anatomy +instead of meeting another domain through a declared junction. It also sets +finite caps for total junction count and interface cardinality; chart, formula, +and dependency counts; candidate special cases; and non-test implementation +and test LOC. The frozen design contract is authoritative for those numeric +values before build. + +The frozen contract fixes obligations and measurable tolerances before +geometry coordinates or visual tuning. It must not smuggle in arbitrary anatomy thresholds, profile-shaped coordinates, or a production contract. The failed candidate's old port-span anatomy gates are not reused as a substitute for the new candidate-specific measures. Numeric tolerances are recorded with their @@ -284,13 +294,13 @@ causal binding is not accepted as an explanation. ## Preflight and build order -The eventual implementation must follow this order and stop at the first +The implementation must follow this order and stop at the first failed gate: 1. Verify worktree, source paths, source hashes, pinned launcher, and the standard-neutral-only scope. -2. Create and SHA-256-bind the required design contract; no later build may - choose an omitted topology, ownership, cap, tolerance, or evidence rule. +2. Verify the SHA-256-bound design contract; no build may choose an omitted + topology, ownership, cap, tolerance, or evidence rule. 3. Admit and validate the prepared intent, including provenance and the required `neck_upper` and `upper_abdomen` source controls. 4. Build the domain, junction, port, and chart ownership plan; prove complete @@ -334,10 +344,10 @@ construction, not to a synthetic diagnostic object: - all must-affect/locality, forbidden-input, profile-neutrality, and deterministic-artifact checks pass. -Clearance and continuity thresholds are not invented in this plan. The design -pass must freeze them before coordinates and record each independently; one -aggregate score is forbidden. Human vision decides whether positive geometry -actually reads as anatomy. +Clearance and continuity thresholds are not invented in this plan. The frozen +design contract records them before coordinates and each is evaluated +independently; one aggregate score is forbidden. Human vision decides whether +positive geometry actually reads as anatomy. ## Visual evidence and checkpoint @@ -374,9 +384,9 @@ Paths, timestamps, host-specific display data, and temporary-directory names must not affect identity. A failed or partial publication must not be mistaken for evidence. -The eventual README revision that activates execution must provide the exact -copy-paste reproduction command and list all raw outputs. This plan remains -non-executable until that command and the freeze-before-build record exist. +This implementation-phase README provides the exact copy-paste reproduction +command and lists all raw outputs. Execution remains bounded by that command +and the frozen design-contract identity. ## Correction stop @@ -445,8 +455,9 @@ does not authorize promotion into production code or canonical architecture. ## Results, limitations, and conclusion -No result exists yet. Until execution, lifecycle remains `planned`, evidence -closure remains `open`, and technology outcome remains `none`. +No result exists yet. Execution is activated at `correction_round=0`; until a +run closes evidence, lifecycle remains `planned`, evidence closure remains +`open`, and technology outcome remains `none`. The trial is limited to one standard-neutral root assembly. It does not test the exact-five profiles, optional modules, tails, hands, feet, faces, distal @@ -456,9 +467,9 @@ recorded investigation and human checkpoint. ## Recommended follow-up -Complete the one bounded design pass and record its frozen interface curves, -patch/junction layout, port orientations, subdivision support, continuity and -fold measures, candidate-specific geometric measures, causal perturbations, -and exact reproduction command. Then implement only the standard-neutral -candidate within this contract. Do not edit canonical specifications or -production architecture as part of this experiment. +Implement only the standard-neutral candidate within the frozen contract, +using its recorded interface curves, patch/junction layout, port orientations, +subdivision support, continuity and fold measures, candidate-specific +geometric measures, causal perturbations, and exact reproduction command. Do +not edit canonical specifications or production architecture as part of this +experiment. diff --git a/experiments/owned-root-assembly-successor/design-contract.md b/experiments/owned-root-assembly-successor/design-contract.md new file mode 100644 index 0000000..1957131 --- /dev/null +++ b/experiments/owned-root-assembly-successor/design-contract.md @@ -0,0 +1,3302 @@ +# Owned-root assembly successor: candidate design contract + +Status: Candidate freeze contract v2; experiment-local and non-normative + +Experiment lifecycle: `planned` +Evidence closure: `open` +Technology outcome: `none` + +This document is a second freeze candidate for one standard-neutral, +Alternative C owned-root assembly. It is not a product contract, canonical +anatomy specification, production geometry backend, supported morphology +promise, runtime skeleton, Stage 1 result, or human acceptance. It does not +activate DR-0009, DR-0010, or DR-0013. The contract has no self-referential +hash. The sidecar and final digest anchors are deliberately absent until this +candidate has passed fresh independent review. + +The target is one welded surface for thorax, neck root, abdomen/lumbar bridge, +pelvis, bilateral shoulder/axilla roots, and bilateral hip roots. It excludes +the head, hands, feet, distal limbs, tail, posing, rigging, weights, +deformation, simulation, engine integration, packaging, and exact-five profile +expansion until this candidate clears its neutral gates. + +## 1. Evidence status, authority, and stop rule + +The preliminary disposable technical evidence passed all 39 implemented +harness gates for each of seeds 17 and 29. It is **not** a completed-contract +pass: it did not exercise the completed charts, all new anatomy gates, +structural floors, corrected tolerance `T`, corrected shared-index policy, or +human acceptance. It also did not produce the contract-bound 47-file output +inventory below. Harness invocation bugs consumed zero geometry-correction +rounds. The evidence is historical provenance, not an oracle or acceptance of +this candidate. + +The current disposable evidence identities are: + +```text +corrected runner: 5093de56ca1ecbacb1b59f9b6a95ca96808279d528ff7d5d7f01ae99c17a81e0 +bundle manifest: 8ce3f556c1b51f0145cdca1b581474ee780b6d0d0ed146bc281ce205682083e2 +threshold contract: efd7b3d6cf94bca75c1ae93f0a7ddeb08be39f5a0f66484a05b0ea859da1a75c +two-level smoke report: 763d285ebc88aa577d02f9e7ef9b56f0203bd809d4794f6e6eb73291596cec36 +seed-17 report: 370c4272e30678b4e07bbdd0bbf4501762813388737911f388fa0086a7c4db74 +seed-29 report: f88bc67c8db34b25a2b8c914bf1eb3540c48c0e147f21642153d5ab1f4e7e39 +stable manifest: f9c5422541911da2a0c5af901c18302f06ee31ee14307ea4416a2d9849bffd6a +coordinate manifest: 6c653300922f64454332a0c8888779d9fd90f1933edd35ccd110f738599ae974 +gate manifest: f8b406b0749ac94fd92cba7875adac294c85b298c68dcc12ed3e0f1537d0804d +causality manifest: 6885cf7ae4bb1eb05ca29c5dc92f358020ab36f3636470542a74fa9f3a9a817b +render manifest: 00288e0b1f7f7f5b298cc447c25f9c7b657f47f5b58fd5bbe436650b799311ba +level-2 PLY: b092fbca5e62735743290f260fd94b5d9b8db5924ec25f9a7ae49e35d9572250 +direct PNG: 066f0682135603fb3f250ffde73a0c8c39bcdffb6433eca441768267fd80490f +lineage PNG: 4f1ddafe67a8dee9eaf97f35e9b3095aba8cc1b71c8c690fc4b8966a164424cc +``` + +An exact geometry audit of the level-2 PLY identified above enumerated 17,832 +triangle pairs with exactly one shared vertex. The exact cone-feasibility +classifier frozen in section 7 classified all 17,832 as point-only. The +rejected incomplete finite-axis certificate falsely rejected 258 of those +pairs: 246 were ordinary noncoplanar incident-fan cases and 12 were +near-coplanar; the exact audit found zero genuine overlaps. This is local +pre-freeze audit evidence about those exact PLY bytes, not completed +implementation evidence and not a claim that the future checker passes. + +The pre-freeze quantitative hip-correction evidence is recorded against the +prospective `lambda_x=1.00` and lower-pelvis-z dependency. Pelvic lateral +ratios are `L0=1.5625`, `L1=1.339629214789240`, and +`L2=1.068201586498584`; the minimum thigh co-normal values are +`L0=0.8038497998`, `L1=0.8038497998`, and `L2=0.8027381422`. All unchanged +structural, continuity, anatomy, intersection, causality, locality, and +determinism gates pass these derived values. This is pre-freeze derived gate +evidence, not a result of a completed executable contract, and no gate is +loosened by it. + +The unchanged standard-neutral axillary samples have topology-ordered +`turn_depth` values from `0.151710 m` through `0.165612 m` and +`path_stretch` values from `1.898909` through `2.338761`; both ranges pass the +section-8 bounds. The prior finite-chord predicate was invalid for valid +level-1 and level-2 topology-ordered hollows, not evidence of a geometry +failure. These ranges are scoped pre-freeze audit evidence, not completed +implementation evidence or premature exact-five evidence. + +The historical bundle used an earlier tolerance literal and different output +names. It is not silently rewritten. The future builder MUST use the corrected +`T` below, the exact output names below, and rerun all evidence against this +contract. The future build MUST reject before source admission and before +creating output when contract identity, source identity, profile identity, +runtime identity, package allowlist, or any closed input rule fails. + +Authority is separated as follows: `AGENTS.md` and applicable workflows govern +operation; `docs/research/owned-root-assembly-investigation.md` owns the +Ben-authorized experiment direction; this file owns this candidate's exact +topology, formulas, gates, artifacts, and finite budgets; code and evidence can +demonstrate or falsify it but cannot alter it. + +The prospective initial freeze is `correction_round=0`. This present +pre-freeze candidate therefore records `correction_round=0` and the exactly +empty ledger `correction_ledger=[]`; no contract has frozen or built yet. +Resolving review findings before that first freeze does not consume a geometry +correction round. After the initial neutral build, at most two shared +correction rounds are available. The exact mutable formula-block registry is: + +```text +formula.axial.j1.edge section 4.2 executable E/u expression and d,n tunables +formula.axial.j1.interior section 4.2 executable virtual-C/E/u expression and d,n tunables +formula.axial.station section 4.2 executable midpoint/E/u expression and d,n tunables +formula.neck.stem section 4.3 executable E/u expression and n tunable +formula.shoulder.left section 4.4 executable inner/outer/depth/center/E expressions +formula.shoulder.right section 4.4 executable inner/outer/depth/center/E expressions +formula.hip.left section 4.5 executable B_s/D/M_x/H_c/H_s/J_x/J_f/J_b/J_s expressions +formula.hip.right section 4.5 executable B_s/D/M_x/H_c/H_s/J_x/J_f/J_b/J_s expressions +``` + +The exact named candidate tunables inside those blocks are +`axial.j1_d=2.5`, `axial.station_d=1.5`, `axial.n=2.6`, +`neck.lateral_multiplier=2.0`, `neck.n=2.2`, +`shoulder.inner_base_depth_factor=0.75`, +`shoulder.outer_vertical_factor=0.5`, `shoulder.n=2.2`, +`hip.kappa_s=0.70`, `hip.lambda_x=1.00`, `hip.lambda_y=0.25`, and +`hip.lambda_z=0.20`. A permitted correction's substantive change is limited +to an executable expression or named tunable in this registry and its +mechanically derived section-4.6 dependency records; the mandatory +round/ledger update and later derived identity anchors are mechanical +consequences, not an expanded correction scope. A shared helper correction +names every formula ID whose coordinates or derivatives it changes. + +The station-row assignments, side/index dispatch, source selectors, aliases, +prepared values, source/profile identities and hashes, and every +standard-neutral trial/source-derived literal printed in sections 2 and 4.5 +are immutable inputs, not formula tunables. A correction cannot change them or +topology, IDs, construction ownership, ports, subdivision, source admission, +the renderer, artifacts, gates, thresholds, scope, or any allowlist. + +Each permitted correction edits this contract, increments `correction_round` +by exactly one to 1 or 2, and appends exactly one record to +`correction_ledger`. A ledger record is a closed object with exactly these +keys and types: + +```text +round: integer, exactly the new correction_round +prior_contract_sha256: lowercase 64-hex string +trigger_evidence: nonempty array of file_record, sorted by role_path +changes: nonempty array sorted by (formula_id,symbol), each exactly + {formula_id: string, symbol: string, + prior_literal_or_formula: string, corrected_literal_or_formula: string} +applicability: exactly {bilateral: boolean, + domains: sorted nonempty unique domain_id array} +invalidation: exactly "all older implementation and evidence is invalidated" +``` + +`file_record` is defined in section 10. A bilateral formula correction MUST be +one shared correction applied to both sides and name both domains in +`applicability`; no implementation-only or one-sided tuning is permitted. +Every corrected contract requires two fresh, independent reviews of its exact +bytes. Only after both reviews resolve to a freeze recommendation may the new +sidecar, the two independent code literals, and the README anchor be +materialized for the new SHA. Implementation validation and all seed-local and +pair evidence then rerun from scratch; older output cannot be carried forward. +A third correction or any change outside this boundary rejects the candidate +and requires a new runway. Render-only offsets, hidden/duplicate skin, profile +branches, a solver, remeshing, or threshold relaxation likewise reject it. + +## 2. Source and prepared input + +### 2.1 Immutable source inputs and fixed paths + +The fixed repository-relative inputs are: + +```text +contract: experiments/owned-root-assembly-successor/design-contract.md +sidecar: experiments/owned-root-assembly-successor/design-contract.sha256 +source: examples/body-documents/stylized-digitigrade-biped-authored-form.json +profile_table: experiments/current-form-surface-preview/structural_profile_candidates.json +``` + +At this candidate state the contract is the only one of these four files +changed by this documentation pass; the source and profile files are existing +immutable inputs, and the future sidecar is not yet created. The source and +profile identities currently bound to the evidence are: + +```text +source bytes: 56984 +source sha256: 82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14 +profile bytes: 29970 +profile sha256: a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640 +``` + +The exact source basis is `length_unit=metre`, `handedness=right`, `up=+y`, +and `forward=+z`. Every admitted dimension is a canonical binary64 metre; no +`/1000` conversion is allowed. Non-dimension transforms and landmarks remain +unchanged by the metre repair. Source or profile byte drift rejects the build. + +The profile table is admitted only to select and validate the named profile. +The selected profile is exactly `standard_neutral_reference`; every numeric +field in its closed `dimension_scales` object MUST be exactly `1000`, and those +values MUST drive no geometry, formula, threshold, topology, or renderer +choice. Profile identity and the excluded optional-module state are +non-geometric. No profile branch is admitted in this neutral build. + +### 2.2 Closed prepared schema + +The prepared schema ID is `owned-root-assembly-successor-prepared.v1`. Its +UTF-8 JSON object MUST contain exactly these top-level keys and no others: + +```text +schema, contract, source, profile_selection, basis, parts, stations, +shoulders, hips, provenance +``` + +The exact nested shapes are: + +`vector3` is the reusable runtime numeric type: an array of exactly three +finite IEEE-754 binary64 values in x,y,z order. At runtime every field declared +`binary64` MUST have exact Python type `float` and be finite; `bool` and `int` +are not runtime binary64 values. Either signed-zero float is admitted in +memory. Section 10.1 freezes its distinct schema-aware wire encoding and +decoding rules. This is a type alias only and adds no schema member. + +```text +schema: string, exactly owned-root-assembly-successor-prepared.v1 +contract: {path: string, sha256: lowercase 64-hex string} +source: {path: string, sha256: lowercase 64-hex string} +profile_selection: { + profile_id: string, + profile_table_path: string, + profile_table_sha256: lowercase 64-hex string, + dimensions: object with exactly the selected profile's closed + dimension_scales key set, binary64 values, every value 1000 +} +basis: { + length_unit: exactly "metre", handedness: exactly "right", + up: exactly "+y", forward: exactly "+z" +} +``` + +`parts` is an array of exactly seven objects, in the address order below. +Each object contains exactly `address` and `placement`. `address` is the +normalized four-item array `[namespace, anchors, kind, role]`; `anchors` is an +array of strings. `placement` is exactly +`{translation: vector3, +rotation_xyzw: [binary64,binary64,binary64,binary64]}`. The rotation MUST be +the runtime float tuple `(+0.0,+0.0,+0.0,1.0)`, whose section-10.1 canonical +wire array is exactly `[0,0,0,1.0]`; scale and shear fields are forbidden. A +nonidentity rotation is rejected before any world sum. A missing, unknown, +duplicate, or extra part rejects: + +```text +["main",[],"part","pelvis"] +["main",[],"part","torso"] +["main",[],"part","neck"] +["main",["left"],"part","upper_arm"] +["main",["right"],"part","upper_arm"] +["main",["left"],"part","thigh"] +["main",["right"],"part","thigh"] +``` + +`stations` is an object with exactly the nine station keys listed in section +2.3. Each value is exactly `{owner: address_tuple, prefix: string, +C: vector3, rL: binary64, rA: binary64, rP: binary64}`. +`shoulders` has exactly `left` and `right`; each value is exactly +`{axilla: vector3, peak: vector3, arm_origin: vector3, start_lateral: +binary64, start_up: binary64, start_forward: binary64, shoulder_depth: +binary64}`. `hips` has exactly `left` and `right`; each value is exactly +`{P_s: vector3, r_x: binary64, r_y: binary64, r_z: binary64}`. +`provenance` is exactly `{source_files: array of exactly 2 objects}`. Each +source-file object is exactly `{path, sha256, bytes}`. No provenance records, +required-control aliases, non-geometric object, or other provenance member is +admitted. Unknown keys, empty provenance, or a source-file count other than +two reject. + +The immutable raw source JSON has its own section-2.1 admission path and is +not a contract-owned canonical artifact. After selecting a raw source numeric +value, prepared-input construction MUST explicitly convert it to finite Python +`float` before assigning it to a `binary64` field. The section-10.1 rejection +of nonzero integer tokens in contract-owned binary64 fields does not reject an +otherwise admitted integer spelling in the raw source. + +No prepared object may contain finished vertices, faces, edges, connectivity, +perimeters, point clouds, fields, masks, silhouettes, corrective offsets, +serialized prior output, or anything trivially reindexed into the candidate +cage. A derived scalar is admitted only when named below and bound to a source +selector. These rules prevent a skin or hidden geometry layer from bypassing +the owned root. + +### 2.3 Exact semantic selectors and aliases + +Before selecting any row, normalize its source address or owner with this +closed admission function: + +```text +normalize_source_address(raw): + require raw is an object with exactly the keys + {namespace, anchors, kind, role} + require namespace, kind, and role are nonempty strings + require anchors is an array of strings, with no other element type + return [namespace, anchors, kind, role] +``` + +The function rejects a missing key, an extra key, a wrong type, an empty +string, or a non-string anchor. It returns a new normalized JSON array and +never a source object or tuple. `A(role,side)` returns exactly that array: + +```text +A(role, side=None) = normalize_source_address({ + "namespace": "main", + "anchors": [] if side is None else [side], + "kind": "part", + "role": role +}) +``` + +Every source selector first normalizes each candidate row's `address` or +`owner`, then compares normalized arrays for equality. This applies to +`part(A)`, `landmark(A,role)`, `dimension(A,role)`, selected landmark frame +owners, prepared addresses, `source_binding_record.source_addresses`, and all +containment and address sorting. Raw object member order, source-row identity, +or a host tuple representation never participates in equality or sorting. +`address_tuple` elsewhere in this contract means this normalized JSON array. + +The source selectors are unique and fail closed. `part(A)` is the unique +`body.parts` row with address `A`; `landmark(A,r)` is the unique +`body.landmarks` row whose owner is `A` and role is `r`; and `dimension(A,r)` is +the unique `body.dimensions` row whose owner is `A` and role is `r`. Missing or +duplicate matches reject. Every dimension is finite, positive, and parsed +directly as binary64 metres. + +World translations and landmarks are: + +```text +W(pelvis) = part(A("pelvis")).placement.translation +W(torso) = W(pelvis) + part(A("torso")).placement.translation +W(neck) = W(torso) + part(A("neck")).placement.translation +W(upper_arm,side) = W(torso) + part(A("upper_arm",side)).placement.translation +W(thigh,side) = W(pelvis) + part(A("thigh",side)).placement.translation +L(A,role) = W(A) + landmark(A,role).position +``` + +`W(A)` means the world translation of the unique admitted part at address +`A`, using the exact containment-chain recurrence above; no other transform +composition is implied. + +The nine exact station mappings are: + +| station | owner | prefix | +| --- | --- | --- | +| `lower_pelvis` | `A("pelvis")` | `form_torso_profile_lower_pelvis` | +| `upper_pelvis` | `A("pelvis")` | `form_torso_profile_upper_pelvis` | +| `lower_abdomen` | `A("torso")` | `form_torso_profile_lower_abdomen` | +| `waist_abdomen` | `A("torso")` | `form_torso_profile_waist_abdomen` | +| `upper_abdomen` | `A("torso")` | `form_torso_profile_upper_abdomen` | +| `lower_ribcage` | `A("torso")` | `form_torso_profile_lower_ribcage` | +| `upper_ribcage_shoulder` | `A("torso")` | `form_torso_profile_upper_ribcage_shoulder` | +| `neck_collar` | `A("neck")` | `form_head_neck_profile_neck_collar` | +| `neck_upper` | `A("neck")` | `form_head_neck_profile_neck_upper` | + +`upper_abdomen` and `neck_upper` are mandatory ordinary stations, not aliases +or optional controls, and each has its ordinary `C` and radius +`source_binding_record`s. For every selected landmark, frame admission is +closed as follows: pelvis and torso station landmarks require +`frame.role="form_torso_profile_control"`; neck station landmarks require +`frame.role="form_head_neck_profile_control"`; upper-arm `form_axilla` and +`form_shoulder_peak` landmarks require `frame.role="form_shoulder_control"`; +and thigh `form_leg_profile_thigh_start` landmarks require +`frame.role="form_leg_profile_control"`. The selected frame owner MUST +normalize to the landmark owner. A missing frame, an additional matching +frame, or a different frame role or owner rejects. Dimension rows have no +invented or inferred frame. + +For each non-neck station, `C=L(owner,prefix)`, `rL=dimension(owner, +prefix+"_lateral_radius")`, `rA=dimension(owner,prefix+"_anterior_radius")`, +and `rP=dimension(owner,prefix+"_posterior_radius")`. For each neck station, +`C` and `rL` use the same rules while `rA=rP=dimension(owner, +prefix+"_forward_radius")`; the authored `*_up_radius` values remain +non-geometric. + +For each side, the exact shoulder aliases are: + +```text +axilla = L(A("upper_arm",side), "form_axilla") +peak = L(A("upper_arm",side), "form_shoulder_peak") +arm_origin = W(upper_arm,side) +start_lateral = dimension(A("upper_arm",side), + "form_arm_profile_upper_arm_start_lateral_radius") +start_up = dimension(A("upper_arm",side), + "form_arm_profile_upper_arm_start_up_radius") +start_forward = dimension(A("upper_arm",side), + "form_arm_profile_upper_arm_start_forward_radius") +shoulder_depth = dimension(A("upper_arm",side), "form_shoulder_depth_radius") +``` + +The exact hip aliases are: + +```text +P_s = L(A("thigh",side), "form_leg_profile_thigh_start") +r_x = dimension(A("thigh",side), + "form_leg_profile_thigh_start_lateral_radius") +r_y = dimension(A("thigh",side), + "form_leg_profile_thigh_start_up_radius") +r_z = dimension(A("thigh",side), + "form_leg_profile_thigh_start_forward_radius") +L_x = stations.lower_pelvis.C.x +L_y = stations.lower_pelvis.C.y +L_z = stations.lower_pelvis.C.z +R_x = stations.lower_pelvis.rL +R_f = stations.lower_pelvis.rA +R_b = stations.lower_pelvis.rP +``` + +`hip.origin`, `form_extent_y`, profile identity, basis labels, and excluded +module state are non-geometric source concepts and are not prepared fields. +The closed prepared component universe is the exact 92 scalar components in +section 2.4. The existing `<=96` complexity ceiling remains a cap, not +permission to admit an additional key. + +### 2.4 Closed geometry-component bindings + +The geometry-driving prepared-component universe contains exactly 92 canonical +component IDs and no others: + +```text +stations..C.x, stations..C.y, stations..C.z, +stations..rL, stations..rA, stations..rP + for station in the exact nine-station table order 9*6 = 54 + +shoulders..axilla.{x,y,z}, shoulders..peak.{x,y,z}, +shoulders..arm_origin.{x,y,z}, +shoulders..start_lateral, shoulders..start_up, +shoulders..start_forward, shoulders..shoulder_depth + for side in left,right 2*13 = 26 + +hips..P_s.{x,y,z}, hips..r_x, +hips..r_y, hips..r_z + for side in left,right 2*6 = 12 + total = 92 +``` + +Brace notation in this listing expands to separate dotted IDs. The nine +station names and their order are exactly those in section 2.3. Every +component has exactly one nonempty `source_binding_record`: + +```text +{prepared_component: string, + derivation_id: one of "source.dimension-value.v1", + "source.world-placement-axis-sum.v1", + "source.world-landmark-axis-sum.v1", + source_addresses: nonempty sorted unique array of address_tuple, + source_pointers: nonempty sorted unique array of canonical JSON-pointer string} +``` + +Arrays `body.parts`, `body.landmarks`, and `body.dimensions` are addressed by +their zero-based indices in the exact admitted raw source bytes. The decimal +index token is `0` or an unsigned base-10 integer without a leading zero. A +canonical pointer is an RFC 6901 pointer with `~` encoded as `~0`, `/` as +`~1`, no URI escaping, and no trailing slash. Let `p(A)`, `l(A,role)`, and +`d(A,role)` be the exact unique raw-array indices selected by `part`, +`landmark`, and `dimension` in section 2.3. Missing or duplicate selection +rejects before a pointer is emitted. Axis indices are exactly `x=0`, `y=1`, +and `z=2`. The pointer constructors are: + +```text +placement_pointer(A,axis) = + "/body/parts/" + decimal(p(A)) + "/placement/translation/" + axis_index +landmark_pointer(A,role,axis) = + "/body/landmarks/" + decimal(l(A,role)) + "/position/" + axis_index +dimension_pointer(A,role) = + "/body/dimensions/" + decimal(d(A,role)) + "/value" +``` + +The fixed containment chains, in summation order, are: + +```text +pelvis: [A("pelvis")] +torso: [A("pelvis"), A("torso")] +neck: [A("pelvis"), A("torso"), A("neck")] +upper_arm,side: [A("pelvis"), A("torso"), A("upper_arm",side)] +thigh,side: [A("pelvis"), A("thigh",side)] +``` + +For each station `C.axis`, use derivation +`source.world-landmark-axis-sum.v1`; its pointers are the same-axis placement +pointers for the station owner's complete containment chain followed by +`landmark_pointer(owner,prefix,axis)`. Shoulder `axilla.axis` and `peak.axis` +use the upper-arm chain followed by the corresponding landmark pointer. Hip +`P_s.axis` uses the thigh chain followed by the thigh-start landmark pointer. +For each shoulder `arm_origin.axis`, use +`source.world-placement-axis-sum.v1` and exactly the same-axis placement +pointers for the upper-arm chain, with no landmark pointer. + +Every station radius, shoulder scalar, and hip radius uses +`source.dimension-value.v1` and exactly its unique section-2.3 dimension +pointer. `source_addresses` is the sorted unique set of every part address +whose placement, landmark, or dimension row contributes to those pointers: +the complete containment-chain address set for a world sum and exactly the +dimension owner's address for a scalar. Address tuples sort by their canonical +section-10.1 JSON bytes; pointers sort by UTF-8 bytes. Pointer arrays preserve +no summation order--the `derivation_id`, fixed chain above, and axis-specific +formula define that order. + +Both input-manifest and causality-manifest contain the same 92 records, unique +by `prepared_component`, sorted by that string's UTF-8 bytes. Empty, +duplicate, missing, extra, differently derived, or pointer/address-inconsistent +records reject. Source/profile identities, exact indices, selectors, aliases, +and all 92 bindings are immutable across correction rounds. + +### 2.5 Scalar arithmetic and historical input + +Every scalar primitive uses binary64 round-to-nearest, ties-to-even after each +primitive operation, with no fused multiply-add. For noninteger `p`, +`sp(x,p)` computes `m=math.pow(abs(x),p)` using exactly CPython 3.10.12 under the identical +frozen runtime fingerprint, returns `+0.0` when `m==0.0`, otherwise returns +`m` when `x>=0.0` and `fl(-m)` when `x<0.0`. This is a same-runtime +determinism rule, not a universal libm claim. `lerp(a,b,t)=(1-t)*a+t*b` uses +the explicit primitive order in section 7. Signed powers MUST use `sp`; a zero +sign MUST never become negative zero by accident. + +The verified standalone evidence inventory and its bundled copy were each +52,282 bytes and byte-identical. Their mutable temporary paths are historical +provenance only. The historical level-0/1/2 coordinate hashes were: + +```text +level 0: add98870612d897648fd5db7fdb96939b943e844bfa97588772c418943ce45be +level 1: 4ff42e85144c287343687d91acdabc35c4e328ab0bfeca75d085428b43c654d9 +level 2: d15bbd8bb7cab281417a85aec0e3371302448f7cbad89a9dae5a7ec537e4af33 +``` + +Those hashes are historical disposable evidence, not a completed-contract +result. The contract-bound build may change them when scalar operation order, +three PLY serialization, or the shared-index policy is corrected. + +## 3. Fixed topology and ownership catalog + +### 3.1 Cells, domains, and counts + +The surface is the boundary of 58 selected unit cubical cells in an integer +lattice. A cell is `(domain_id,i,j,k)` with `k in {0,1}`. The exact closed +`domain_id` set and domain order are: + +```text +domain.pelvis, domain.abdomen, domain.thorax, domain.neck, +domain.left_shoulder, domain.right_shoulder, domain.left_hip, domain.right_hip +``` + +These eight strings are the only domain IDs. Short anatomical names remain +ordinary prose or source-role names only; no short alias is admitted in a +contract-owned serialized owner, contributor, incident-domain, or palette +field. Cells sort lexicographically within each domain in the order above. + +The complete selected-cell inventory is: + +```text +domain.pelvis: (0,0,0) (0,0,1) (1,0,0) (1,0,1) (2,0,0) (2,0,1) (3,0,0) (3,0,1) (4,0,0) (4,0,1) +domain.abdomen: (1,1,0) (1,1,1) (1,2,0) (1,2,1) (2,1,0) (2,1,1) (2,2,0) (2,2,1) (3,1,0) (3,1,1) (3,2,0) (3,2,1) +domain.thorax: (1,3,0) (1,3,1) (1,4,0) (1,4,1) (1,5,0) (1,5,1) (2,3,0) (2,3,1) (2,4,0) (2,4,1) (2,5,0) (2,5,1) (3,3,0) (3,3,1) (3,4,0) (3,4,1) (3,5,0) (3,5,1) +domain.neck: (2,6,0) (2,6,1) +domain.left_shoulder: (0,4,0) (0,4,1) (0,5,0) (0,5,1) +domain.right_shoulder: (4,4,0) (4,4,1) (4,5,0) (4,5,1) +domain.left_hip: (0,-1,0) (0,-1,1) (1,-1,0) (1,-1,1) +domain.right_hip: (3,-1,0) (3,-1,1) (4,-1,0) (4,-1,1) +``` + +Each selected cell contributes six outward-wound unit faces. Faces used by two +selected cells are internal and omitted. Remove the five named port-cap face +sets: + +```text +neck: 2 faces left_arm: 4 faces right_arm: 4 faces +left_thigh: 4 faces right_thigh: 4 faces +``` + +The un-capped exterior has 122 faces. The retained welded surface MUST have: + +```text +controls=120, quads=104, edges=227, boundary_edges=38, +boundary_components=5, connected_components=1, Euler_characteristic=-3, +non_manifold_edges=0, directed_orientation_conflicts=0 +``` + +All eight domains MUST be nonempty. Every retained base quad is one bilinear +`(1,1)` patch with four distinct control IDs in its listed outward-wound +cycle. A shared junction is represented once by indexed controls, not by +coincident duplicate surfaces. + +The explicit `q000` through `q103` sequence printed in section 3.3 is the sole +level-0 face-order authority. Recomputing retained exterior faces from the +selected cells MUST produce a bijection to that catalog, and every recomputed +face MUST match its printed canonical owner and exact four-control cycle in +place; cyclic rotation and reversal are both forbidden. There is no secondary +coordinate, direction, cell, or implementation-native face sort. A use count +above two fails closed. A retained control with one incident face domain is +owned by that canonical domain ID. A control with two incident face domains +MUST match one of the seven junctions; three or more domains, no matching +junction, or no owner fails closed. + +### 3.2 Control catalog + +IDs are assigned by lexicographic lattice coordinate `(i,j,k)`. The following +is the complete control/owner catalog; `c000` is first and `c119` is last: + +```text +c000@(0,-1,0):domain.left_hip c001@(0,-1,1):domain.left_hip c002@(0,-1,2):domain.left_hip +c003@(0,0,0):junction.pelvis__left_hip c004@(0,0,1):junction.pelvis__left_hip c005@(0,0,2):junction.pelvis__left_hip +c006@(0,1,0):domain.pelvis c007@(0,1,1):domain.pelvis c008@(0,1,2):domain.pelvis +c009@(0,4,0):domain.left_shoulder c010@(0,4,1):domain.left_shoulder c011@(0,4,2):domain.left_shoulder +c012@(0,5,0):domain.left_shoulder c013@(0,5,2):domain.left_shoulder c014@(0,6,0):domain.left_shoulder +c015@(0,6,1):domain.left_shoulder c016@(0,6,2):domain.left_shoulder +c017@(1,-1,0):domain.left_hip c018@(1,-1,2):domain.left_hip +c019@(1,0,0):junction.pelvis__left_hip c020@(1,0,2):junction.pelvis__left_hip +c021@(1,1,0):junction.pelvis__abdomen c022@(1,1,1):junction.pelvis__abdomen c023@(1,1,2):junction.pelvis__abdomen +c024@(1,2,0):domain.abdomen c025@(1,2,1):domain.abdomen c026@(1,2,2):domain.abdomen +c027@(1,3,0):junction.abdomen__thorax c028@(1,3,1):junction.abdomen__thorax c029@(1,3,2):junction.abdomen__thorax +c030@(1,4,0):junction.thorax__left_shoulder c031@(1,4,1):junction.thorax__left_shoulder c032@(1,4,2):junction.thorax__left_shoulder +c033@(1,5,0):junction.thorax__left_shoulder c034@(1,5,2):junction.thorax__left_shoulder +c035@(1,6,0):junction.thorax__left_shoulder c036@(1,6,1):junction.thorax__left_shoulder c037@(1,6,2):junction.thorax__left_shoulder +c038@(2,-1,0):domain.left_hip c039@(2,-1,1):domain.left_hip c040@(2,-1,2):domain.left_hip +c041@(2,0,0):junction.pelvis__left_hip c042@(2,0,1):junction.pelvis__left_hip c043@(2,0,2):junction.pelvis__left_hip +c044@(2,1,0):junction.pelvis__abdomen c045@(2,1,2):junction.pelvis__abdomen +c046@(2,2,0):domain.abdomen c047@(2,2,2):domain.abdomen +c048@(2,3,0):junction.abdomen__thorax c049@(2,3,2):junction.abdomen__thorax +c050@(2,4,0):domain.thorax c051@(2,4,2):domain.thorax +c052@(2,5,0):domain.thorax c053@(2,5,2):domain.thorax +c054@(2,6,0):junction.thorax__neck c055@(2,6,1):junction.thorax__neck c056@(2,6,2):junction.thorax__neck +c057@(2,7,0):domain.neck c058@(2,7,1):domain.neck c059@(2,7,2):domain.neck +c060@(3,-1,0):domain.right_hip c061@(3,-1,1):domain.right_hip c062@(3,-1,2):domain.right_hip +c063@(3,0,0):junction.pelvis__right_hip c064@(3,0,1):junction.pelvis__right_hip c065@(3,0,2):junction.pelvis__right_hip +c066@(3,1,0):junction.pelvis__abdomen c067@(3,1,2):junction.pelvis__abdomen +c068@(3,2,0):domain.abdomen c069@(3,2,2):domain.abdomen +c070@(3,3,0):junction.abdomen__thorax c071@(3,3,2):junction.abdomen__thorax +c072@(3,4,0):domain.thorax c073@(3,4,2):domain.thorax +c074@(3,5,0):domain.thorax c075@(3,5,2):domain.thorax +c076@(3,6,0):junction.thorax__neck c077@(3,6,1):junction.thorax__neck c078@(3,6,2):junction.thorax__neck +c079@(3,7,0):domain.neck c080@(3,7,1):domain.neck c081@(3,7,2):domain.neck +c082@(4,-1,0):domain.right_hip c083@(4,-1,2):domain.right_hip +c084@(4,0,0):junction.pelvis__right_hip c085@(4,0,2):junction.pelvis__right_hip +c086@(4,1,0):junction.pelvis__abdomen c087@(4,1,1):junction.pelvis__abdomen c088@(4,1,2):junction.pelvis__abdomen +c089@(4,2,0):domain.abdomen c090@(4,2,1):domain.abdomen c091@(4,2,2):domain.abdomen +c092@(4,3,0):junction.abdomen__thorax c093@(4,3,1):junction.abdomen__thorax c094@(4,3,2):junction.abdomen__thorax +c095@(4,4,0):junction.thorax__right_shoulder c096@(4,4,1):junction.thorax__right_shoulder c097@(4,4,2):junction.thorax__right_shoulder +c098@(4,5,0):junction.thorax__right_shoulder c099@(4,5,2):junction.thorax__right_shoulder +c100@(4,6,0):junction.thorax__right_shoulder c101@(4,6,1):junction.thorax__right_shoulder c102@(4,6,2):junction.thorax__right_shoulder +c103@(5,-1,0):domain.right_hip c104@(5,-1,1):domain.right_hip c105@(5,-1,2):domain.right_hip +c106@(5,0,0):junction.pelvis__right_hip c107@(5,0,1):junction.pelvis__right_hip c108@(5,0,2):junction.pelvis__right_hip +c109@(5,1,0):domain.pelvis c110@(5,1,1):domain.pelvis c111@(5,1,2):domain.pelvis +c112@(5,4,0):domain.right_shoulder c113@(5,4,1):domain.right_shoulder c114@(5,4,2):domain.right_shoulder +c115@(5,5,0):domain.right_shoulder c116@(5,5,2):domain.right_shoulder +c117@(5,6,0):domain.right_shoulder c118@(5,6,1):domain.right_shoulder c119@(5,6,2):domain.right_shoulder +``` + +### 3.3 Face catalog + +The complete retained face catalog is: + +```text +q000 domain.left_hip [c000,c001,c004,c003] q001 domain.left_hip [c000,c003,c019,c017] +q002 domain.left_hip [c001,c002,c005,c004] q003 domain.left_hip [c002,c018,c020,c005] +q004 domain.pelvis [c003,c004,c007,c006] q005 domain.pelvis [c003,c006,c021,c019] +q006 domain.pelvis [c004,c005,c008,c007] q007 domain.pelvis [c005,c020,c023,c008] +q008 domain.pelvis [c006,c007,c022,c021] q009 domain.pelvis [c007,c008,c023,c022] +q010 domain.left_shoulder [c009,c012,c033,c030] q011 domain.left_shoulder [c009,c030,c031,c010] +q012 domain.left_shoulder [c010,c031,c032,c011] q013 domain.left_shoulder [c011,c032,c034,c013] +q014 domain.left_shoulder [c012,c014,c035,c033] q015 domain.left_shoulder [c013,c034,c037,c016] +q016 domain.left_shoulder [c014,c015,c036,c035] q017 domain.left_shoulder [c015,c016,c037,c036] +q018 domain.left_hip [c017,c019,c041,c038] q019 domain.left_hip [c018,c040,c043,c020] +q020 domain.pelvis [c019,c021,c044,c041] q021 domain.pelvis [c020,c043,c045,c023] +q022 domain.abdomen [c021,c022,c025,c024] q023 domain.abdomen [c021,c024,c046,c044] +q024 domain.abdomen [c022,c023,c026,c025] q025 domain.abdomen [c023,c045,c047,c026] +q026 domain.abdomen [c024,c025,c028,c027] q027 domain.abdomen [c024,c027,c048,c046] +q028 domain.abdomen [c025,c026,c029,c028] q029 domain.abdomen [c026,c047,c049,c029] +q030 domain.thorax [c027,c028,c031,c030] q031 domain.thorax [c027,c030,c050,c048] +q032 domain.thorax [c028,c029,c032,c031] q033 domain.thorax [c029,c049,c051,c032] +q034 domain.thorax [c030,c033,c052,c050] q035 domain.thorax [c032,c051,c053,c034] +q036 domain.thorax [c033,c035,c054,c052] q037 domain.thorax [c034,c053,c056,c037] +q038 domain.thorax [c035,c036,c055,c054] q039 domain.thorax [c036,c037,c056,c055] +q040 domain.left_hip [c038,c041,c042,c039] q041 domain.left_hip [c039,c042,c043,c040] +q042 domain.pelvis [c041,c044,c066,c063] q043 domain.pelvis [c041,c063,c064,c042] +q044 domain.pelvis [c042,c064,c065,c043] q045 domain.pelvis [c043,c065,c067,c045] +q046 domain.abdomen [c044,c046,c068,c066] q047 domain.abdomen [c045,c067,c069,c047] +q048 domain.abdomen [c046,c048,c070,c068] q049 domain.abdomen [c047,c069,c071,c049] +q050 domain.thorax [c048,c050,c072,c070] q051 domain.thorax [c049,c071,c073,c051] +q052 domain.thorax [c050,c052,c074,c072] q053 domain.thorax [c051,c073,c075,c053] +q054 domain.thorax [c052,c054,c076,c074] q055 domain.thorax [c053,c075,c078,c056] +q056 domain.neck [c054,c055,c058,c057] q057 domain.neck [c054,c057,c079,c076] +q058 domain.neck [c055,c056,c059,c058] q059 domain.neck [c056,c078,c081,c059] +q060 domain.right_hip [c060,c061,c064,c063] q061 domain.right_hip [c060,c063,c084,c082] +q062 domain.right_hip [c061,c062,c065,c064] q063 domain.right_hip [c062,c083,c085,c065] +q064 domain.pelvis [c063,c066,c086,c084] q065 domain.pelvis [c065,c085,c088,c067] +q066 domain.abdomen [c066,c068,c089,c086] q067 domain.abdomen [c067,c088,c091,c069] +q068 domain.abdomen [c068,c070,c092,c089] q069 domain.abdomen [c069,c091,c094,c071] +q070 domain.thorax [c070,c072,c095,c092] q071 domain.thorax [c071,c094,c097,c073] +q072 domain.thorax [c072,c074,c098,c095] q073 domain.thorax [c073,c097,c099,c075] +q074 domain.thorax [c074,c076,c100,c098] q075 domain.thorax [c075,c099,c102,c078] +q076 domain.thorax [c076,c077,c101,c100] q077 domain.neck [c076,c079,c080,c077] +q078 domain.thorax [c077,c078,c102,c101] q079 domain.neck [c077,c080,c081,c078] +q080 domain.right_hip [c082,c084,c106,c103] q081 domain.right_hip [c083,c105,c108,c085] +q082 domain.pelvis [c084,c086,c109,c106] q083 domain.pelvis [c085,c108,c111,c088] +q084 domain.pelvis [c086,c087,c110,c109] q085 domain.abdomen [c086,c089,c090,c087] +q086 domain.pelvis [c087,c088,c111,c110] q087 domain.abdomen [c087,c090,c091,c088] +q088 domain.abdomen [c089,c092,c093,c090] q089 domain.abdomen [c090,c093,c094,c091] +q090 domain.thorax [c092,c095,c096,c093] q091 domain.thorax [c093,c096,c097,c094] +q092 domain.right_shoulder [c095,c098,c115,c112] q093 domain.right_shoulder [c095,c112,c113,c096] +q094 domain.right_shoulder [c096,c113,c114,c097] q095 domain.right_shoulder [c097,c114,c116,c099] +q096 domain.right_shoulder [c098,c100,c117,c115] q097 domain.right_shoulder [c099,c116,c119,c102] +q098 domain.right_shoulder [c100,c101,c118,c117] q099 domain.right_shoulder [c101,c102,c119,c118] +q100 domain.right_hip [c103,c106,c107,c104] q101 domain.right_hip [c104,c107,c108,c105] +q102 domain.pelvis [c106,c109,c110,c107] q103 domain.pelvis [c107,c110,c111,c108] +``` + +### 3.4 Junction and port catalog + +There are exactly seven two-domain junctions. Junction IDs use the fixed +domain order. Each line freezes its canonical incident-domain pair and control +trace. Storage starts at the lexicographically least lattice endpoint, then +takes the lexicographically lesser neighbor first. This is a storage order, +not an outward-direction claim: + +```text +junction.pelvis__left_hip [domain.pelvis,domain.left_hip]: [c003,c004,c005,c020,c043,c042,c041,c019] +junction.pelvis__abdomen [domain.pelvis,domain.abdomen]: [c021,c022,c023,c045,c067,c088,c087,c086,c066,c044] +junction.abdomen__thorax [domain.abdomen,domain.thorax]: [c027,c028,c029,c049,c071,c094,c093,c092,c070,c048] +junction.thorax__left_shoulder [domain.thorax,domain.left_shoulder]: [c030,c031,c032,c034,c037,c036,c035,c033] +junction.thorax__neck [domain.thorax,domain.neck]: [c054,c055,c056,c078,c077,c076] +junction.pelvis__right_hip [domain.pelvis,domain.right_hip]: [c063,c064,c065,c085,c108,c107,c106,c084] +junction.thorax__right_shoulder [domain.thorax,domain.right_shoulder]: [c095,c096,c097,c099,c102,c101,c100,c098] +``` + +The five open ports, their canonical construction-owner domains, declared +outward directions, and exact loops are: + +```text +port.neck owner=domain.neck outward=+Y loop=[c057,c079,c080,c081,c059,c058] length=6 +port.left_arm owner=domain.left_shoulder outward=-X loop=[c009,c012,c014,c015,c016,c013,c011,c010] length=8 +port.right_arm owner=domain.right_shoulder outward=+X loop=[c112,c113,c114,c116,c119,c118,c117,c115] length=8 +port.left_thigh owner=domain.left_hip outward=-Y loop=[c000,c001,c002,c018,c040,c039,c038,c017] length=8 +port.right_thigh owner=domain.right_hip outward=-Y loop=[c060,c061,c062,c083,c105,c104,c103,c082] length=8 +``` + +`junction_id` means exactly one of the seven IDs above. `construction_owner` +means exactly one of the eight section-3.1 `domain_id` values or one of those +seven `junction_id` values, as allowed by the owning catalog; no other string +is admitted. Every contract-owned serialized owner, face domain, +`contributor_domains`, and `incident_domains` value uses these canonical IDs. +A port owner is always the one canonical domain printed above and is never a +junction or a short alias. + +Port direction MUST be proven by the loop-area and induced co-normal gates in +section 7, never by a label alone. Exactly 20 interior controls are extraordinary: + +```text +valence 3: c006,c008,c109,c111 +valence 5: c021,c023,c030,c032,c041,c043,c054,c056,c063,c065,c076,c078, + c086,c088,c095,c097 +``` + +No C1 or G1 claim is made at extraordinary controls or open ports. + +## 4. Formula dispatch and source-derived coordinates + +### 4.1 Exact disjoint dispatch + +The dispatch is over the 120 retained control keys, never over an unretained +Cartesian lattice. Test each key in this order and reject a key that matches +zero or more than one rule: + +```text +1. if j in {6,7} and i in {2,3}: + family=neck; formula_id=formula.neck.stem +2. else if j in {4,5,6} and i in {0,1,4,5}: + family=shoulder; side=left iff i in {0,1}, right iff i in {4,5} + formula_id=formula.shoulder. +3. else if j in {-1,0}: + family=hip; side=left iff i in {0,1,2}, right iff i in {3,4,5} + formula_id=formula.hip. +4. else: + family=axial; j=1 edge iff i in {0,5} + j=1 interior iff i in {1,2,3,4} + formula_id=formula.axial.j1.edge, formula.axial.j1.interior, + or formula.axial.station for j>=2 +``` + +There is no axial j=0 or axial j=6 rule. The only axial rows are: + +```text +j=1 edge: 6 controls +j=1 interior: 10 controls +j=2: 10 controls +j=3: 10 controls +j=4: 4 controls +j=5: 4 controls +total: 44 controls +``` + +The family totals are neck 12, shoulder 32, hip 32, and axial 44. Each +control MUST have exactly one record with exactly these fields: + +```text +control_id, lattice_key, formula_id, construction_owner, +index_parameters, geometry_dependencies, coordinate +``` + +`construction_owner` is the exact section-3.4 canonical owner for that +control and has no short alias. `coordinate` and every binary64 member of +`index_parameters` obey the section-2.2 runtime and section-10.1 wire rule. +geometry_dependencies contains prepared component keys only when the analytic +coordinate derivative for that record is nonzero. The contract hash and +formula ID bind formulas, constants, preconditions, and intermediate values; +they MUST NOT be redundantly or variably serialized into a formula record. +`coordinate` is the final finite base-control `vector3` before subdivision. The +closed dependency universe has exactly the 92 possible prepared-component IDs +defined in section 2.4, of which no more than 96 were allowed by the original +cap, and each record has at most 12 dependencies. A dependency list is sorted +and duplicate-free. + +`index_parameters` is a closed object selected by formula family: + +```text +axial: {i: integer, j: integer, k: integer, + u: binary64, q: binary64, d: binary64, n: binary64, + station_selector: string} +neck: {i: integer, j: integer, k: integer, + u: binary64, q: binary64, n: binary64, + station_selector: string} +shoulder:{i: integer, j: integer, k: integer, side: "left"|"right", + a: binary64, v: binary64, q: binary64, sign: integer -1|+1} +hip: {i: integer, j: integer, k: integer, side: "left"|"right", + u: binary64, q: binary64} +``` + +The values are exactly those produced by sections 4.2 through 4.5 after every +stated binary64 rounding. Axial `station_selector` is exactly +`upper_pelvis`, `virtual.upper_pelvis_y__lower_abdomen`, `waist_abdomen`, +`upper_abdomen`, `lower_ribcage`, or +`virtual.lower_ribcage__upper_ribcage_shoulder` according to the frozen row +mapping. Neck `station_selector` is exactly `neck_collar` or `neck_upper`. +No other key, selector spelling, or family-specific payload is admitted. + +### 4.2 Axial family + +Define E componentwise with the binary64 operation rules in section 7: + +```text +E(C,u,q,rL,rA,rP,n) = + (fl(C.x + fl(rL * sp(u,2/n))), + C.y, + fl(C.z + fl((rA if q>=0 else rP) * sp(q,2/n)))) +``` + +For axial records, `q=k-1`, `n=2.6`, and `u=fl((i-2.5)/d)`. Use `d=2.5` for +both j=1 cases and `d=1.5` for j>=2. Station selection is exact: + +```text +j=1 edge: upper_pelvis +j=1 interior: virtual station: + C.x=lower_abdomen.C.x + C.y=fl((upper_pelvis.C.y+lower_abdomen.C.y)/2) + C.z=lower_abdomen.C.z + all radii=lower_abdomen radii +j=2: waist_abdomen +j=3: upper_abdomen +j=4: lower_ribcage +j=5: componentwise midpoint of lower_ribcage and + upper_ribcage_shoulder, each operation rounded +``` + +The j=1 edge record uses only upper-pelvis center and radii. The j=1 interior +record uses only lower-abdomen center and radii plus upper-pelvis center y. It +MUST NOT use unused upper-pelvis radii or center x/z. + +### 4.3 Neck family + +For `j=6` use `neck_collar`; for `j=7` use `neck_upper`: + +```text +E(station.C, 2*(i-2.5), k-1, + station.rL, station.rA, station.rP, 2.2) +``` + +Both neck depth values come from the authored `*_forward_radius` role. The +authored neck `*_up_radius` values, including the trial values 0.38 and 0.32, +are non-geometric and MUST NOT affect coordinates. + +### 4.4 Shoulder family + +For the left side use `i in {0,1}`, `a=1-i`, `sign=-1`; for the right use +`i in {4,5}`, `a=i-4`, `sign=+1`. Let `v=(j-4)/2` and `q=k-1`: + +```text +inner = lerp(axilla, peak, v) +joint = arm_origin +outer = joint + (sign*start_lateral, (2*v-1)*start_up*0.5, 0) +inner_depth = 0.75*start_forward if v=0 else shoulder_depth +depth = (1-a)*inner_depth + a*start_forward +center = lerp(inner, outer, a) +point = E(center, 0, q, 0, depth, depth, 2.2) +``` + +The family does not imply that distal arms are in scope. Its exact +zero-coefficient-aware dependency rules are in section 4.6; a record MUST NOT +declare every family input as a dependency merely because the family names it. + +### 4.5 Hip family + +#### 4.5.1 Mutable executable formula block + +For left use `u=i-1`; for right use `u=i-4`; in both cases `q=k-1`. + +```text +kappa_s=0.70 lambda_x=1.00 +lambda_y=0.25 lambda_z=0.20 + +B_s(u,q) = P_s + (u*r_x, 0, q*r_z) + +D = L_y - P_s.y +M_x = R_x - abs(P_s.x - L_x) +H_c = r_y + lambda_y*(D-r_y) +H_s = kappa_s*H_c +J_x = r_x + lambda_x*(M_x-r_x) +J_f = r_z + lambda_z*(R_f-r_z) +J_b = r_z + lambda_z*(R_b-r_z) +J_0z = lerp(P_s.z, L_z, lambda_z) +Q_z = fl(J_f*q) if q>=0 else fl(J_b*q) + +J_s(u,q) = (P_s.x + u*J_x, + P_s.y + H_s + (H_c-H_s)*(1-u*u), + fl(J_0z + Q_z)) +``` + +The port row depends only on `P_s`, `r_x`, and `r_z`. The junction row +depends only on `P_s`, `r_x`, `r_y`, `r_z`, lower-pelvis center x/y/z, +lower-pelvis lateral/anterior/posterior radii, and the four named constants. +It MUST NOT consume `hip.origin`, `form_extent_y`, profile identity, or a +basis value as a coordinate input. + +#### 4.5.2 Immutable source-derived trial records + +The standard-neutral trial source records are: + +```text +lower_pelvis C=(0,-0.45,0) rL=1.50 rA=0.85 rP=0.60 +upper_pelvis C=(0,-0.20,0) rL=1.35 rA=0.78 rP=0.56 +lower_abdomen C=(0, 0.25,0) rL=1.125 rA=0.68 rP=0.54 +waist_abdomen C=(0, 0.50,0) rL=0.875 rA=0.50 rP=0.40 +upper_abdomen C=(0, 0.80,0) rL=1.225 rA=0.725 rP=0.56 +lower_ribcage C=(0, 1.05,0) rL=1.45 rA=0.875 rP=0.675 +upper_ribcage_shoulder C=(0, 1.95,0) rL=1.50 rA=0.90 rP=0.70 +neck_collar C=(0, 2.15,0) rL=0.42 rA=0.40 rP=0.40 +neck_upper C=(0, 2.55,0) rL=0.34 rA=0.33 rP=0.33 +``` + +The trial hip values are `P_s=(-1,-1,0)/(1,-1,0)`, `r_x=0.32`, `r_y=0.28`, +`r_z=0.30`. The shoulder values are arm origins `(-1,2,0)/(1,2,0)`, axillae +`(-1.1,1.7,0)/(1.1,1.7,0)`, peaks `(-1.1,2.15,0)/(1.1,2.15,0)`, start +radii `(0.35,0.30,0.32)`, and `shoulder_depth=0.35`. + +### 4.6 Exhaustive derivative dependency rules + +The builder MUST publish the exact dependency list for every one of the 120 +records. The following rules are exhaustive. A component is absent when its +coefficient is zero at the exact discrete index; no blanket family dependency +is allowed. For the hip-junction exception below, the frozen +`lambda_x=1.00` value is in force. `direct station E` applies to axial j=1 +edge, axial j=2 through 4, and neck rows; j=1 interior and j=5 use their +explicit expansions below: + +```text +direct station E(C,u,q,rL,rA,rP,n): + always stations..C.x, + stations..C.y, + stations..C.z + include stations..rL iff u != 0 + include stations..rA iff q > 0 + include stations..rP iff q < 0 + +axial j=1 interior: + always stations.lower_abdomen.C.x, stations.lower_abdomen.C.y, + stations.lower_abdomen.C.z, stations.upper_pelvis.C.y + include stations.lower_abdomen.rL iff u != 0 + include stations.lower_abdomen.rA iff q > 0 + include stations.lower_abdomen.rP iff q < 0 + +axial j=5 virtual midpoint: + always stations.lower_ribcage.C.x, + stations.lower_ribcage.C.y, + stations.lower_ribcage.C.z, + stations.upper_ribcage_shoulder.C.x, + stations.upper_ribcage_shoulder.C.y, + stations.upper_ribcage_shoulder.C.z + include stations.lower_ribcage.rL and + stations.upper_ribcage_shoulder.rL iff u != 0 + include stations.lower_ribcage.rA and + stations.upper_ribcage_shoulder.rA iff q > 0 + include stations.lower_ribcage.rP and + stations.upper_ribcage_shoulder.rP iff q < 0 + +shoulder, a=0 (inner): + include shoulders..axilla.{x,y,z} iff v < 1 + include shoulders..peak.{x,y,z} iff v > 0 + include shoulders..start_forward iff q != 0 and v = 0 + include shoulders..shoulder_depth iff q != 0 and v > 0 + +shoulder, a=1 (outer): + always shoulders..arm_origin.{x,y,z}, + shoulders..start_lateral + include shoulders..start_up iff v != 0.5 + include shoulders..start_forward iff q != 0 + +hip port, j=-1: + always hips..P_s.{x,y,z} + include hips..r_x iff u != 0 + include hips..r_z iff q != 0 + +hip junction, j=0: + always hips..P_s.y, hips..P_s.z, hips..r_y, + stations.lower_pelvis.C.y, stations.lower_pelvis.C.z + include hips..P_s.x except when the complete x derivative cancels: + side=left and u=-1, or side=right and u=+1 + include stations.lower_pelvis.rL, stations.lower_pelvis.C.x iff u != 0 + include hips..r_z, stations.lower_pelvis.rA iff q > 0 + include hips..r_z, stations.lower_pelvis.rP iff q < 0 +``` + +Every j=5 virtual center or radius has exactly two nonzero `0.5` +source-component coefficients, one for `lower_ribcage` and one for +`upper_ribcage_shoulder`, before the usual `u`/`q` zero-coefficient rules for +radii are applied. No virtual center/radius or `station_selector` string may +appear in `geometry_dependencies`; only the canonical 92 section-2.4 IDs may +appear. Source placement components that fan out to several prepared +aliases are counted once as prepared component keys. This ledger is the sole +source of causality claims; metadata, labels, or observed movement cannot add +dependencies. + +## 5. Ownership, charts, and junction continuity + +Construction ownership, semantic causality, and evaluated-surface lineage are +three separate layers: + +1. construction owns every domain interior, junction, control, and face; +2. semantic causality binds authored roles through derived values, formulas, + and subdivision support; and +3. evaluated lineage records actual base-control contributors, source + dependencies, domain/chart contributors, and face lineage. + +Every control and face MUST have exactly one construction owner. Every +evaluated element MUST have lineage. A lineage colour or legend is a +diagnostic only and cannot prove causality. Direct and lineage renders MUST +consume the same evaluated arrays; lineage MUST NOT add, hide, or move skin. + +### 5.1 Chart contract + +There is one base chart per retained face: `chart.q000` through +`chart.q103`. For each face cycle `(U0,U1,U2,U3)`, its UVs are exactly: + +```text +(U0,(0,0)), (U1,(1,0)), (U2,(1,1)), (U3,(0,1)) +``` + +The chart owner is the face's canonical `domain_id`. Child corner order is +fixed by: + +```text +M01=(U0+U1)/2 M12=(U1+U2)/2 +M23=(U2+U3)/2 M30=(U3+U0)/2 +C=(U0+U1+U2+U3)/4 +s0=[U0,M01,C,M30] +s1=[U1,M12,C,M01] +s2=[U2,M23,C,M12] +s3=[U3,M30,C,M23] +``` + +Apply this rule recursively with exact reduced dyadic UVs. Child `sI` is +the child at parent corner `I`. IDs are: + +```text +level 0 vertex: c000 through c119 +level 1 vertex: vertex.L1.v0000 through vertex.L1.v0450 +level 2 vertex: vertex.L2.v0000 through vertex.L2.v1736 +level 0 face: q000 through q103 +level 1 face: face.L1.q0000 through face.L1.q0415 +level 2 face: face.L2.q0000 through face.L2.q1663 +level 0 chart: chart.qNNN +level 1 chart: chart.qNNN/L1.sI +level 2 chart: chart.qNNN/L2.sI.sJ +``` + +Level-0 vertex and face IDs are exactly the section-3 catalog IDs. At each +derived level, vertex numbering resets to zero and follows the already-frozen +numeric vertex order in section 6. Derived face numbering likewise resets to +zero and follows the frozen child-emission order. `NNN` is exactly three ASCII +decimal digits, `MMMM` is exactly four ASCII decimal digits, and `I` and `J` +are each one ASCII digit in `0..3`; a transition level is one ASCII digit in +`0..2`. All literal punctuation, case, prefixes, and zero padding are exactly +as printed above; no alternative spelling, padding, alias, or +implementation-native identifier is admitted. + +For base face `qNNN`, interpret `NNN` as its zero-based numeric face index. +Its level-1 child at corner `I` has numeric face index `4*NNN+I`, exact face ID +`face.L1.qMMMM`, and chart ID `chart.qNNN/L1.sI`. Its level-2 child at corner +`J` of that level-1 child has numeric face index `16*NNN+4*I+J`, exact face ID +`face.L2.qMMMM`, and chart ID `chart.qNNN/L2.sI.sJ`. `MMMM` is the four-digit +zero-padded spelling of the calculated index. This mapping is the executable +relation between child chart ancestry and numeric face IDs. + +For each interior edge at a level, use the undirected key +`(lower_endpoint_id,higher_endpoint_id)`, where lower and higher mean numeric +vertex order at that level, never implementation string comparison. Its exact +`min(endpoint_id)` and `max(endpoint_id)` notation anywhere in edge or +transition processing means these same lower and higher numeric-order +endpoints, not lexical minimum or maximum. The exact +ASCII transition ID is the concatenation +`"transition/L" + decimal(level) + "/e" + lower_endpoint_id + "-" + +higher_endpoint_id`, using the exact endpoint spellings frozen above, with no +escaping, whitespace, padding change, or alternative separator. The source +chart is the lower numeric incident-face index at that level, and the +destination chart the higher; chart-string comparison is forbidden. In each +face, edge slot `r` is the directed pair +`face[r]->face[(r+1)%4]`; the destination slot MUST have reverse endpoint +order. Store source/destination chart, edge slots, endpoint IDs in ascending +numeric vertex order, `t_destination=1-t_source`, and `junction_id`. +Same-domain transitions use `junction_id=null`; a cross-domain transition +stores exactly one catalog junction ID and both incident domains in catalog +order. + +At every level, each evaluated face has exactly one chart and base-face ancestor. +`chart_records` are authoritative face lineage: at level 0, +`base_face_id=face_id`; each child inherits its parent's `base_face_id` and +the construction-owner domain of that base face. No additional surface or +file lineage is permitted. Construction ownership, causal lineage, +contributor domains, and face/chart lineage remain distinct records and +claims. +Each evaluated vertex stores all incident `(chart_id,u,v)` records, sorted by +chart ID and then reduced dyadic `u,v`. Derived vertex IDs and numeric +order are the subdivision order in section 6. Child face IDs are emitted in +parent-face order and then parent corner order `0,1,2,3`. + +The exact chart/transition counts are: + +```text + level 0 level 1 level 2 total +charts 104 416 1664 2184 +interior transitions 189 794 3252 4235 +maximum chart samples/vertex: 5 at every level +``` + +### 5.2 Junction traces + +For every junction, traces MUST be derived independently from each incident +domain's face/chart incidence. The two derived directions MUST be opposite. +Pair samples by exact dyadic transverse tags and require equal tags and IDs +before comparing coordinates. A junction residual MUST be at most `T` per +coordinate at levels 0, 1, and 2. Stored control order is never used as a +substitute for independently derived incidence traces. + +The exhaustive junction map and transverse-tag rule are: + +```text +junction.pelvis__left_hip drop j; tag (i,k) +junction.pelvis__abdomen drop j; tag (i,k) +junction.abdomen__thorax drop j; tag (i,k) +junction.thorax__left_shoulder drop i; tag (j,k) +junction.thorax__neck drop j; tag (i,k) +junction.pelvis__right_hip drop j; tag (i,k) +junction.thorax__right_shoulder drop i; tag (j,k) +``` + +Initial tags are the indicated components of the exact section-3 lattice keys. +Subdivision propagates them as reduced dyadic values. Inherited boundary +vertices retain their tag; each inserted edge sample receives the exact +rational midpoint of its endpoint tags. The two incident canonical-domain +traces MUST be derived independently and produce equal tag/vertex sets in +opposite cyclic directions. Missing, duplicate, unequal, or differently +directed sets fail closed. + +### 5.3 Executable ownership and lineage counts + +The `unowned_elements` and `overowned_elements` invalid-count gates are +computed independently at every level from a closed, disjoint element +universe. Its keys are all expected vertices in that level's numeric order, +all expected faces in numeric face order, all topology-derived undirected +edges keyed by their lower and higher numeric vertex indices, and exactly one +boundary slot for each of the five catalog port IDs. At a conforming level its +cardinality is therefore: + +```text +level 0: 120 vertices/controls + 104 faces + 227 edges + 5 boundary slots = 456 +level 1: 451 vertices + 416 faces + 870 edges + 5 boundary slots = 1742 +level 2: 1737 vertices + 1664 faces + 3404 edges + 5 boundary slots = 6810 +``` + +The level-0 vertex keys are also the base-control keys, so a control is not +counted a second time. The level-0 face keys likewise represent the base +faces. This tagged union is the sole counting universe; an element can +contribute at most one to one of the two invalid counts at a level. +Any output identifier outside the exact section-5.1 level set is a hard +identifier/catalog failure and is never admitted as an alternate universe +element. + +Base controls and base faces each require exactly one catalog-valid +construction-owner record. A base-control owner is either its exact catalog +domain or its exact catalog junction, including that junction's complete +incident-domain set. A base-face owner is its exact section-3 face-catalog +domain. A level-0 vertex/control element has both this construction-owner +obligation and the evaluated-vertex lineage obligation below; a derived vertex +has the lineage obligation only. For a level-0 face, the unique +chart/base-face ancestry record MUST exist and agree with that catalog owner. +Every level-1 or level-2 face MUST +have exactly one chart record whose section-5.1 numeric face ID, unique +base-face ancestor, and inherited construction-owner domain agree. That one +ancestry path is the evaluated face's construction ownership; contributor +lineage does not create another face owner. + +Each topology-derived edge has exactly one derived classification record: + +```text +one incident face: boundary edge in exactly one propagated catalog port loop +two same-domain faces: interior edge belonging to that one domain +two cross-domain faces: edge in exactly one catalog junction and in that + junction's independently derived level trace +``` + +The three cases are mutually exclusive and are derived from face incidence, +face ancestry owners, propagated port loops, the junction catalog, and the two +independent junction traces rather than from a serialized edge-owner label. +Any other incidence or zero or multiple matching classifications is invalid. +For each boundary slot, its classification records are the actual one-face +boundary components whose canonically rotated, orientation-preserving numeric +vertex cycle exactly equals that propagated catalog port loop. Canonical +rotation starts at the cycle's lowest numeric vertex and does not reverse the +derived orientation. Requiring exactly one record in every port slot, together +with requiring every one-face edge to have exactly one port classification, +makes the actual boundary components and catalog ports bijective: a missing +port, duplicate component, unmatched component, or multiply matched component +cannot pass. + +Every evaluated vertex requires exactly one `vertex_record` under its exact +section-5.1 ID. Its incident chart samples, base-control contributors, +geometry-dependency union, and contributor domains MUST be nonempty, complete, +and equal to the independently recomputed section-6 lineage. Multiple entries +inside the one catalog-order-unique `contributor_domains` array are valid +multi-domain evaluated lineage and never count as construction +over-ownership. + +For each required obligation above, classify its candidate-record multiset as +`zero` when it is absent or its sole record is not catalog-valid, complete, and +equal to the independently derived value; `one` only when exactly one such +record exists and is valid; or `multiple` whenever more than one candidate +record exists, regardless of their contents. An element is counted once in +`overowned_elements` if any of its obligations is `multiple`; otherwise it is +counted once in `unowned_elements` if any obligation is `zero`; otherwise it +is valid. This precedence makes zero-versus-multiple handling deterministic +and prevents a face, edge, boundary slot, or vertex/control output from being +double-counted across the two aggregate invalid-count gates. + +## 6. Subdivision, lineage, and finite formula ledger + +Exactly two open-boundary Catmull–Clark levels are evaluated. The rules are: + +```text +face point = ordered mean of four face vertices in face-cycle order +boundary edge = ordered midpoint of endpoint IDs +interior edge = ordered sum of two endpoints and two face points, divided by 4 +boundary vertex = ordered (6*P + neighbor_1 + neighbor_2) / 8 +interior vertex = ordered (F + 2*R + (n-3)*P) / n +face emission = (vertex, next-edge-point, face-point, previous-edge-point) +``` + +Boundary vertices MUST have exactly two boundary neighbours. Boundary loops +expand as `(vertex,next-edge-point)` while retaining orientation. No alternative +boundary rule, smoothing kernel, remesher, solver, optimizer, or post-build +correction is permitted. + +```text +level 0: vertices=120, edges=227, quads=104, triangles=208, boundary_edges=38 +level 1: vertices=451, edges=870, quads=416, triangles=832, boundary_edges=76 +level 2: vertices=1737, edges=3404, quads=1664, triangles=3328, boundary_edges=152 +``` + +The recurrence is `V'=V+E+Q`, `E'=2E+4Q`, `Q'=4Q`, `B'=2B`. + +All displayed means and sums are componentwise. Every multiplication, +addition, subtraction, division, and square root is rounded binary64 after +the primitive, with no fused multiply-add. Face points use parent face order; +incident faces use ascending numeric face order; incident edges use ascending +numeric endpoint-index pairs. Numeric vertex order at each new level is: +updated parent vertices in parent order, edge points in sorted undirected-edge +order, then face points in parent-face order. Child faces are emitted in +parent-face order and corner order 0,1,2,3. Boundary-neighbor order is the +ascending numeric boundary-neighbor ID. + +For an interior vertex P with n incident faces, F is the ordered componentwise +mean of its incident face points in ascending numeric face order. R is the ordered +componentwise mean of the endpoint midpoints of its incident edges in ascending +undirected-edge order. The interior update operation order is: + +```text +t0 = fl(2*R) +t1 = fl(F+t0) +t2 = fl((n-3)*P) +P' = fl(fl(t1+t2)/n) +``` + +For a boundary vertex with ascending boundary neighbours N0 and N1: + +```text +t0 = fl(6*P) +t1 = fl(t0+N0) +t2 = fl(t1+N1) +P' = fl(t2/8) +``` + +For an edge with endpoint IDs `e0=0.10 m >=0.04 m >=0.02 m +minimum triangle area >=0.010 m2 >=0.002 m2 >=0.0005 m2 +minimum quad area >=0.010 m2 >=0.002 m2 >=0.0005 m2 +``` + +At every level all values, normals, areas, and metrics MUST be finite. The +surface MUST be connected, orientable, outward-wound, non-manifold-free, and +free of accidental holes other than the five declared ports. Duplicate +controls, duplicate faces, degenerate faces, zero-length edges, unowned or +over-owned elements, and failed caps are hard failures. + +`outward_wound` is the exact topological predicate: every level-0 face cycle +equals its section-3.3 printed cycle without rotation or reversal; every +two-face edge occurs in opposite directed order in its incident cycles; and +every one-face edge has the direction induced by its exact section-3.4 port +loop. At levels 1 and 2 every child cycle is the section-5.1 frozen emission +cycle from an outward-wound parent and every shared edge remains oppositely +directed. This predicate makes no subjective claim that a geometric normal +points away from a body centre. + +The independent triangle checker MUST reject before geometry output if a level +has more than 4096 triangles. Its production broad-phase candidate cap and the +matching generated threshold are both exactly `1000000`; the cap applies +separately at each level and is not caller-configurable. +Normalize the complete mesh once: + +```text +lo=componentwise mesh minimum +extent=componentwise(maximum-lo) +scale=norm(extent); reject unless finite and scale>0 +p_normalized=(p-lo)/scale +D=0x1.0000000000000p-46 +reject repeated IDs, non-finite coordinates, or normalized normal length <=D +``` + +The conservative shared-index intersection policy processes unordered triangle +pairs `(i,j)` with iI0`, use a gap magnitude, reassociate it, or +apply the tolerance twice. A zero-shared AABB is disjoint when this predicate +is true on any axis. Contact or equality is not disjoint and remains a hit. + +For each level, `broad_phase_candidate_count` is exactly the cardinality of +the unique unordered pairs of triangulated face records with `shared=0` for +which `interval_disjoint` is false on every normalized-AABB axis. Shared-one +pairs go +directly to the exact cone classifier and are not counted; shared-two and +shared-three pairs are also excluded. An acceleration structure is admitted +only if its deduplicated set equals the exhaustive `(i,j)` reference set with +`i= 0 for every i +lambda0+lambda1+lambda2+lambda3 = 1 +lambda0*X0+lambda1*X1+lambda2*X2+lambda3*X3 = (0,0,0) +lambda0+lambda1 > 0 +lambda2+lambda3 > 0 +``` + +If no such values exist, the pair is point-only. Determine feasibility by the +following closed active-set procedure. Enumerate all subsets of +`{0,1,2,3}` first by sizes 2, 3, and 4 and then by lexicographic index order. +For each subset, solve the exact augmented system whose column for index `i` +is `(Xi.x,Xi.y,Xi.z,1)` and whose right-hand side is `(0,0,0,1)`. Row-reduce +with arbitrary-precision rational arithmetic: process unknown columns from +left to right; for each, choose the lowest currently available row with a +nonzero entry as pivot, swap it into the next pivot row, divide that row by +the pivot, and eliminate the unknown from every other row. Skip the subset if +an unknown column has no pivot, or if a coefficient-zero row has a nonzero +right-hand side. Otherwise the full-column-rank system has one solution; set +lambdas for omitted indices to zero and test all nonnegativity and both strict +side-sum conditions exactly. Stop at the first satisfying subset and classify +the pair as a hit. If all subsets fail, classify it as point-only. + +The ordered inventory contains exactly +`C(4,2)+C(4,3)+C(4,4)=6+4+1=11` candidate subsets. Because evaluation stops +at the first satisfying subset, each shared-one pair evaluates at most 11 +subset attempts. Carathéodory's theorem makes the inventory complete: any +feasible convex combination in three dimensions has a representation with at +most four active points, while the two strict side sums and nonzero rays rule +out a one-point witness. `I0`, `D`, and any former projection tolerance `R` +do not decide the final shared-one Boolean classification. The classifier's +Boolean result MUST be invariant under swapping triangles A and B and under +independently swapping the two A rays or the two B rays. + +The production intersection fixture catalog is closed at exactly 105 +executions. Every coordinate literal below is an exact binary64 hexadecimal +value, with these aliases: + +```text +P0 = 0x0.0p+0 +N0 = -0x0.0p+0 +ONE = 0x1.0000000000000p+0 +HALF = 0x1.0000000000000p-1 +D50 = 0x1.0000000000000p-50 +MIN_SUBNORMAL = 0x0.0000000000001p-1022 +D = 0x1.0000000000000p-46 +I0 = 0x1.b7cdfd9d7bdbbp-34 +``` + +Unless a row overrides it, a shared-one base uses exact indexed triangles +`A=[(v0,s),(v1,A0),(v2,A1)]` and +`B=[(v0,s),(v3,B0),(v4,B1)]`, so the shared-index cardinality is one, with: + +```text +s = (P0,P0,P0) +A0 = (ONE,P0,P0) +A1 = (P0,ONE,P0) +``` + +The exact transform used by fixture rows is componentwise and ordered: + +```text +transform(p,scale,t).axis: + q0 = fl(scale*p.axis) + q1 = fl(q0+t.axis) + result = q1 +``` + +The eleven shared-one bases, in stable table order, are: + +| base fixture ID | exact override or construction | expected | required coverage | +| --- | --- | --- | --- | +| `shared1.offset-d50-point-only` | `B0=(ONE,P0,D50)`, `B1=(P0,ONE,D50)` | `point-only` | rejected finite-axis counterexample; near-coplanar point-only | +| `shared1.coplanar-duplicate-hit` | `B0=(ONE,P0,P0)`, `B1=(P0,ONE,P0)` | `hit` | `d=0`; ray/ray overlap; duplicate geometric rays; antipodal signed `Xi`; positive-zero representation | +| `shared1.offset-positive-minsub-point-only` | `B0=(ONE,P0,MIN_SUBNORMAL)`, `B1=(P0,ONE,MIN_SUBNORMAL)` | `point-only` | positive one-ULP side | +| `shared1.offset-negative-minsub-point-only` | `B0=(ONE,P0,-MIN_SUBNORMAL)`, `B1=(P0,ONE,-MIN_SUBNORMAL)` | `point-only` | negative one-ULP side | +| `shared1.coplanar-disjoint-fans` | `B0=(-ONE,P0,P0)`, `B1=(P0,-ONE,P0)` | `point-only` | coplanar disjoint fans; antipodal geometric rays; duplicate signed `Xi` | +| `shared1.ray-cone-hit` | `B0=(ONE,ONE,P0)`, `B1=(P0,P0,ONE)` | `hit` | one B ray strictly inside the A cone | +| `shared1.near-coplanar-full-rank-hit` | `B0=(ONE,P0,D50)`, `B1=(P0,ONE,-D50)` | `hit` | full-column-rank witness `lambda=(1/4,1/4,1/4,1/4)` | +| `shared1.transformed-point-only` | transform every point of `shared1.offset-d50-point-only` with `scale=0x1.0000000000000p+3`, `t=(0x1.0000000000000p+2,-0x1.0000000000000p+1,ONE)` | `point-only` | exactly representable translation and positive scale | +| `shared1.transformed-hit` | apply that same transform to `shared1.near-coplanar-full-rank-hit` | `hit` | exactly representable translation and positive scale | +| `shared1.negative-zero-hit` | start from `shared1.coplanar-duplicate-hit` and replace every zero-valued coordinate component with the exact `N0` bit pattern without arithmetic | `hit` | negative-zero representation; every decoded zero becomes `0/1` | +| `shared1.level2-ply-point-only` | exact PLY records and coordinates below | `point-only` | representative ordinary noncoplanar incident fan | + +The positive-zero and negative-zero rows exhaust the two zero bit patterns for +every zero occurrence. Mixed masks add no distinct predicate case because the +exact rational decoder canonicalizes every component independently. + +The level-2 PLY base uses `A=[(3,s),(1321,A0),(462,A1)]` and +`B=[(3,s),(1329,B0),(463,B1)]` from zero-based triangle pair `(1,65)` in PLY +SHA-256 `b092fbca5e62735743290f260fd94b5d9b8db5924ec25f9a7ae49e35d9572250`. +After section-7 mesh normalization its coordinates are exactly: + +```text +s = p3 = (0x1.8b59f7e4bf4dfp-7,0x1.0a35e0636f7c1p-4,0x1.264d28c7c3da4p-4) +A0 = p1321 = (0x1.37918e2798bb6p-8,0x1.61bcdab8dcc06p-4,0x1.43c9e5ce2aeb6p-4) +A1 = p462 = (0x1.7bc42ac7f04b0p-7,0x1.6cae8c4686bb2p-4,0x1.0be935f6a339ep-4) +B0 = p1329 = (0x1.7888e87a16156p-6,0x1.7eec0987f75cdp-4,0x1.d5d88ce274e30p-5) +B1 = p463 = (0x1.8b59f7e4bf4dfp-6,0x1.18982604f83a1p-4,0x1.07df2315527a3p-4) +``` + +Each base expands into exactly eight executions with suffixes in this order: + +```text +p000, p001, p010, p011, p100, p101, p110, p111 +``` + +For suffix `pABC`, apply bits left-to-right: if `A=1`, swap the complete +triangle A and B records; if `B=1`, swap the two nonshared records in the +resulting triangle A; if `C=1`, swap the two nonshared records in the resulting +triangle B. The shared record remains first in each triangle. Coordinates and +vertex IDs do not change. Every variant has ID `.` +and MUST produce its base result. Execution order is base-table order then the +suffix order above. Thus this matrix contributes exactly `11*8=88` +executions and tests all eight required swap combinations for every base. + +The remaining seventeen fixtures, in stable table order, are: + +| fixture ID | exact records or construction | expected result and stage | +| --- | --- | --- | +| `shared0.clear-hit-origin` | `A=[(0,(-ONE,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]`; `B=[(3,(P0,-ONE,P0)),(4,(HALF,HALF,P0)),(5,(-HALF,HALF,P0))]` | `hit` in zero-shared SAT narrow phase | +| `shared0.clear-hit-translated` | transform the preceding fixture with `scale=ONE`, `t=(0x1.0000000000000p+2,-0x1.0000000000000p+1,ONE)` | `hit` | +| `shared0.sub-I0-contact-origin` | `A=[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]`; B has IDs `3,4,5`, the same x/y values, and every z=`0x1.0000000000000p-34` | `hit` under `I0` although geometrically separated | +| `shared0.sub-I0-contact-translated` | transform the preceding fixture with `scale=ONE`, `t=(0x1.0000000000000p+2,-0x1.0000000000000p+1,ONE)` | `hit` under `I0` | +| `shared0.aabb-disjoint` | `A=[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]`; `B=[(3,(P0,P0,ONE)),(4,(ONE,P0,ONE)),(5,(P0,ONE,ONE))]` | `disjoint` at AABB stage | +| `shared0.sat-disjoint` | `A=[(0,(P0,P0,P0)),(1,(0x1.0000000000000p+1,P0,P0)),(2,(P0,0x1.0000000000000p+1,P0))]`; `B=[(3,(0x1.0000000000000p+1,0x1.0000000000000p+1,P0)),(4,(0x1.0000000000000p+1,0x1.8000000000000p+0,P0)),(5,(0x1.8000000000000p+0,0x1.0000000000000p+1,P0))]` | AABBs overlap; `disjoint` at SAT axis | +| `shared0.extreme-small-hit` | transform `shared0.clear-hit-origin` with `scale=0x1.0000000000000p-500`, `t=(P0,P0,P0)` | `hit` after normalization | +| `shared0.extreme-large-hit` | transform `shared0.clear-hit-origin` with `scale=0x1.0000000000000p+500`, `t=(P0,P0,P0)` | `hit` after normalization | +| `normal.boundary-D-reject` | one triangle `[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,D,P0))]` | hard failure at normalized-normal admission because norm `<=D` | +| `normal.successor-D-accept` | one triangle `[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,0x1.0000000000000p-45,P0))]` | normal admission passes; there are zero unordered pairs | +| `shared2.opposite-edge-valid` | `A=[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]`; `B=[(1,(ONE,P0,P0)),(0,(P0,P0,P0)),(3,(P0,-ONE,P0))]` | `excluded-adjacent`; opposite directed shared edge | +| `shared2.same-direction-reject` | `A=[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]`; `B=[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(3,(P0,-ONE,P0))]` | hard failure at shared-two incidence/direction check | +| `shared3.duplicate-triangle-reject` | two triangle records both equal `[(0,(P0,P0,P0)),(1,(ONE,P0,P0)),(2,(P0,ONE,P0))]` | hard failure at duplicate-triangle policy | +| `triangle-cap.boundary-4096` | for `r=0..4095`, IDs are `[3r,3r+1,3r+2]`; let binary64 `x=float(4*r)`, then coordinates are `(x,P0,P0)`, `(fl(x+ONE),P0,P0)`, `(x,ONE,P0)` | triangle cap admitted; no AABB candidates or hits | +| `triangle-cap.successor-4097` | preceding generator for `r=0..4096` | hard failure before normalization at triangle count 4097 | +| `candidate-cap.boundary-injected-3` | production helper with fixture-local cap 3 over the three exact triangles below | enumeration succeeds with exactly three candidates; narrow phase reports hits | +| `candidate-cap.successor-injected-3` | production helper with fixture-local cap 3 over the four exact triangles below | hard failure on the fourth candidate, before narrow phase | + +For each candidate-cap row, triangle `r` has distinct IDs +`[3r,3r+1,3r+2]` and identical valid geometry: + +```text +T_r = [(3r,(P0,P0,P0)), + (3r+1,(ONE,P0,P0)), + (3r+2,(P0,ONE,P0))] +boundary row: r=0..2 +successor row: r=0..3 +``` + +All inter-triangle pairs have `shared=0` and surviving identical AABBs. The +boundary row therefore yields exactly `C(3,2)=3` candidates. For the successor +row the first four candidates in reference order are `(0,1)`, `(0,2)`, +`(0,3)`, and `(1,2)`; the injected cap of 3 MUST fail on `(1,2)`. Both rows +also assert, without adding an execution, that the production constant equals +integer `1000000` and that the three exact threshold records +`threshold.intersection.L0.broad_phase_candidate_count`, +`threshold.intersection.L1.broad_phase_candidate_count`, and +`threshold.intersection.L2.broad_phase_candidate_count` each have relation +`le`, upper bound integer `1000000`, and no lower bound. A million-pair +materialized fixture is forbidden. + +The closed execution arithmetic is exactly: + +```text +11 shared-one bases * 8 permutations = 88 executions +17 general fixture rows 17 executions +total 105 executions +``` + +The 88 shared-one executions invoke the exact production shared-one classifier +with their coordinates treated as the already-normalized values its interface +requires. Each general row enters the production checker or named production +helper at the stage its construction specifies and follows production logic to +its frozen terminal result. Only the two candidate-cap rows use the +fixture-local helper cap. No fixture writes or publishes an artifact. The +complete 17,832-pair PLY audit remains bounded +pre-freeze evidence from section 1, not a committed mesh fixture, admitted +implementation input, output role, or completed-contract regression. The +artifact policy and closed 47-role inventory remain unchanged. + +For every port and every level, let the ordered loop points be `p_i`, centroid +`c`, declared outward direction `d_port`, and +`A=0.5*sum(cross(p_i-c,p_(i+1)-c))`. The port loop MUST satisfy: + +```text +-normalize(A) dot d_port >=0.99 +planarity residual <=T +||A||/S^2 >=0.0001 +``` + +Loop equality permits orientation-preserving cyclic rotation only; reversal +MUST fail. For each port boundary edge, calculate the full area-weighted +normal `nF` of its adjacent outward-wound quad, the outward-wound boundary +tangent `t`, and `cF=normalize(cross(t,nF))`. Require +`cF dot d_port >=0.80` at levels 0, 1, and 2. This induced co-normal gate is +independent of the loop-area gate and cannot be replaced by a label or colour. + +At every cross-domain shared edge, compare the full area-weighted normals of +the incident quads using the smaller angle in degrees. Reject at or above: + +```text +base: 90 degrees level 1: 60 degrees level 2: 30 degrees +``` + +The fold measure uses exactly CPython 3.10.12 `math.acos` under the identical frozen +runtime fingerprint. With +`pi=0x1.921fb54442d18p+1`, compute exactly: + +```text +c = clamp(dot(n0,n1),-1,+1) +a = math.acos(c) +t0 = fl(a*180.0) +degrees = fl(t0/pi) +``` + +The normals are the full area-weighted quad normals from the primitive above, +and the smaller angle in degrees is reported. No reassociation is permitted; +the determinism claim is same-runtime only. + +## 8. Candidate-specific anatomy gates + +All measures below use the same evaluated surface at levels 0, 1, and 2. +Trace-to-trace measures use exact dyadic tag pairing; the shoulder-surface gate +uses its explicitly defined face-incidence set. A missing or ambiguous selector +fails closed. These are mechanical readability guards, not a visual-quality +score. + +```text +neck exposure: min >=0.05 m at levels 0,1,2 +shoulder-surface descent: min >=0.05 m at levels 0,1,2 +arm-port descent: supporting min >=0.05 m at levels 0,1,2 +axillary turn depth: min >=0.05 m at levels 0,1,2 +axillary path stretch: max <=2.5 at levels 0,1,2 +axillary inboard recess: inferior tags min >=0.05 m at levels 0,1,2 +axillary downward recess: inferior tags min >=0.05 m at levels 0,1,2 +pelvic vertical wrap: min >=0.05 m at levels 0,1,2 +pelvic lateral ratio: min >=1.05 at levels 0,1,2 +front depth wrap: min >=0.005 m at levels 0,1,2 +back depth wrap: min >=0.005 m at levels 0,1,2 +downward thigh root: the vertical-wrap scalar plus port direction -Y +``` + +The exact measures are: + +- **Neck:** `delta_y=port.y-junction.y`; the neck port MUST be above the + thorax-neck junction by `delta_y>=0.05 m` at every level. +- **Shoulder surface:** for each side and level, form the unique set of all + evaluated vertices incident to evaluated faces whose base-face ancestor's + construction owner is that side's shoulder domain. Require + `max(shoulder_surface.y) <= min(neck_port.y)-0.05 m`. Face ancestry and + chart incidence select this set; domain labels attached to vertices and + spatial or visual bounding boxes are forbidden substitutes. +- **Arm-port support:** independently derive the side's evaluated arm-port + loop and require `max(arm_port.y) <= min(neck_port.y)-0.05 m`. This + supporting gate does not satisfy or replace shoulder-surface descent. +- **Axillary turn depth and path stretch:** arm/shoulder tags are `(j,k)` + after dropping `i`. At each level and for every exact reduced dyadic depth + tag `k`, derive three unique samples independently from face/chart + incidence: `U` is the upper shoulder-junction sample at `j=6`, `A` is the + same side's shoulder-junction axilla sample at `j=4`, and `O` is the + inferior arm-port sample at `j=4`. Each trace MUST independently yield the + complete reduced dyadic tag set over `0<=k<=2` for that level, and the three + sets MUST be equal before pairing. The topology fixes the ordered trace + `U -> A -> O`; no finite-chord projection chooses or reorders a sample. In + the x-y plane, compute in the section-7 binary64 primitive order: + + ```text + r = A-U + s = O-A + c = O-U + lr = norm((r.x,r.y,0)) + ls = norm((s.x,s.y,0)) + lc = norm((c.x,c.y,0)) + path = fl(lr+ls) + cross_z = fl(fl(c.x*r.y)-fl(c.y*r.x)) + oriented_cross = cross_z for left, fl(-cross_z) for right + turn_depth = fl(oriented_cross/path) + path_stretch = fl(path/lc) + ``` + + The production predicate uses this exact failure order for every U/A/O + sample: + + ```text + 1. require U, A, and O finite + 2. compute r, s, c, lr, ls, and lc in the printed operation order + 3. require lr finite and lr>0 + 4. require ls finite and ls>0 + 5. require lc finite and lc>0 + 6. compute path=fl(lr+ls); require path finite and path>0 + 7. compute cross_z, oriented_cross, turn_depth, and path_stretch; + require all four finite + 8. require turn_depth>=0x1.999999999999ap-5 m + 9. require path_stretch<=0x1.4000000000000p+1 + ``` + + No division may occur before steps 3 through 6 have passed. Empty, + duplicate, or ambiguous sample sets fail closed before this predicate. + Signed turn depth verifies that the topology-ordered trace turns toward the + axillary hollow; the scale-free path-stretch ceiling rejects unbounded + hooked or sagging detours that could otherwise pass turn depth. These two + mechanical guards remain insufficient to establish visual quality, so the + fixed-view visual appraisal remains necessary. Both gates are independent + of the following two supporting recess gates. + + The closed principal constants, all exact binary64 values, are: + + ```text + level = 2 + k = {numerator:3,denominator:4} + U0 = (-0x1.0866666666667p+0,0x1.1333333333333p+1,-0x1.699999999999ap-4) + A0 = (-0x1.289999999999ap+0,0x1.9533333333334p+0,-0x1.2f28f5c28f5c4p-4) + O0 = (-0x1.599999999999ap+0,0x1.d99999999999ap+0,-0x1.47ae147ae147bp-4) + principal_turn_depth = 0x1.4016a28cc89afp-3 = 0.15629317276132101 m + principal_path_stretch = 0x1.0ab0f3d101d06p+1 = 2.0835251589338695 + historical_old_t = 0x1.1a1d8e870c54fp+0 = 1.1020135001857232 + ``` + + `historical_old_t` is provenance for the former fixture name + `old-t>1-valid-hollow` and is exactly the rejected historical x-y-plane + finite-chord projection + `dot((A0-U0)_xy,(O0-U0)_xy)/dot((O0-U0)_xy,(O0-U0)_xy)`, where `_xy` + means the two-component vector containing only x and y. It is not an + admitted predicate, threshold, or gate. + + The seven U/A/O production-predicate executions, in exact order, are: + + | fixture ID | side and exact U/A/O construction | exact derived result | expected | + | --- | --- | --- | --- | + | `axillary.principal-left-pass` | left; `(U,A,O)=(U0,A0,O0)` | principal values above | pass | + | `axillary.principal-right-mirror-pass` | right; negate only each x component of `U0,A0,O0` | identical principal values | pass | + | `axillary.wrong-sign-left` | left; `(U,A,O)=(O0,A0,U0)` | `turn_depth=-0x1.4016a28cc89afp-3`; `path_stretch=0x1.0ab0f3d101d06p+1` | fail at step 8 only | + | `axillary.U-equals-A` | left; `(U,A,O)=(U0,U0,O0)` | `lr=0x0.0p+0` | hard failure at step 3 | + | `axillary.A-equals-O` | left; `(U,A,O)=(U0,O0,O0)` | `lr=0x1.bf1092ac1a7f1p-2`; `ls=0x0.0p+0` | hard failure at step 4 | + | `axillary.U-equals-O` | left; `(U,A,O)=(U0,A0,U0)` | `lr=ls=0x1.29747f9d3ab49p-1`; `lc=0x0.0p+0` | hard failure at step 5 | + | `axillary.long-sag-left` | left; `U=(0x0.0p+0,0x1.0000000000000p+0,0x0.0p+0)`, `A=(0x0.0p+0,-0x1.4000000000000p+3,0x0.0p+0)`, `O=(-0x1.0000000000000p+0,0x0.0p+0,0x0.0p+0)` | `turn_depth=0x1.0b8e161fdc225p-1`; `path_stretch=0x1.dc4de77c38e3cp+3` | pass step 8; fail step 9 | + + The other six executions are direct finite-scalar comparator fixtures, not + U/A/O reachability tests. Their exact IDs, values, and outcomes are: + + ```text + axillary.scalar.turn-depth-predecessor 0x1.9999999999999p-5 fail step 8 + axillary.scalar.turn-depth-boundary 0x1.999999999999ap-5 pass step 8 + axillary.scalar.turn-depth-successor 0x1.999999999999bp-5 pass step 8 + axillary.scalar.path-stretch-predecessor 0x1.3ffffffffffffp+1 pass step 9 + axillary.scalar.path-stretch-boundary 0x1.4000000000000p+1 pass step 9 + axillary.scalar.path-stretch-successor 0x1.4000000000001p+1 fail step 9 + ``` + + The axillary fixture suite is exactly the seven table rows followed by those + six scalar rows: `2 principal/mirror + 1 wrong-sign + 3 degeneracy + 1 + long-sag + 6 scalar = 13` executions. Every case invokes the applicable + production predicate and emits no artifact. +- **Axillary supporting recesses:** the inferior + set is exactly every reduced dyadic tag with `4<=j<=5`, including both + endpoints and every midpoint generated at levels 1 and 2. Derive the + shoulder-junction and arm-port samples independently from face/chart + incidence. On the left require `junction.x-arm_port.x >=0.05 m`; on the + right require `arm_port.x-junction.x >=0.05 m`. Require + `arm_port.y-junction.y >=0.05 m` for every inferior tag on both sides. + No endpoint or maximum-only substitute is permitted. +- **Pelvis:** thigh and pelvis/hip tags are `(i,k)` after dropping `j` and + are paired by identical reduced dyadic tags. For each side, + `vertical_wrap=junction.y-port.y`; require its minimum to be at least + 0.05 m at every level. For each tag with nonzero denominator, + `lateral_ratio=abs(junction.x-P_s.x)/abs(port.x-P_s.x)` and require the + minimum to be at least 1.05; at least one such tag is required. A zero + denominator is reported as omitted and cannot satisfy the gate. Front tags + are exactly `k>1`, with `front_wrap=junction.z-port.z`; back tags are + exactly `k<1`, with `back_wrap=port.z-junction.z`. Tags with `k=1` are + excluded from both depth sets and remain in vertical wrap. +- **Thigh:** downward thigh root is the same `vertical_wrap` scalar already + required above, reported under this compatibility label together with the + independently required `-Y` port orientation. It is not a second gate or + a weaker level-0/1 alternative. + +The following clearances MUST be at least `0.05 m` at every level: + +```text +neck min(spanX,spanZ) +axilla side min(spanY,spanZ) +groin minX(right hip junction)-maxX(left hip junction) +medial thigh minX(right thigh port)-maxX(left thigh port) +``` + +For any named sample set `S`, `spanX(S)`, `spanY(S)`, and `spanZ(S)` are +respectively `max(p.x)-min(p.x)`, `max(p.y)-min(p.y)`, and +`max(p.z)-min(p.z)` over all and only the exact tag-paired samples selected +for that feature at that level. `minX` and `maxX` use the same closed sample +sets. An empty or ambiguous sample set fails closed; no visual bounding box +or unpaired endpoint may substitute. In the clearance list, `S` is the neck +port loop for `neck`, the corresponding arm-port loop for `axilla side`, and +the corresponding paired hip-junction or thigh-port samples for `groin` or +`medial thigh` respectively. + +Every selector in this section is reconstructed from retained face incidence, +base-face ancestry, chart incidence, exact port/junction catalogs, and reduced +dyadic tags. A stored semantic label, lineage colour, render-space feature, +axis-aligned bounding box, or threshold-selected coordinate subset MUST NOT be +used as a selector or as a substitute for the prescribed incidence proof. + +The disposable trial observed approximately 0.6394 m, 0.3 m, 0.8394 m, and +1.36 m for its corresponding clearances, but those values are historical +observations and not threshold substitutions. Positive gates do not claim a complete humanoid; +the main thread's fixed-view inspection remains authoritative for readable +thorax, abdomen, pelvis, neck, shoulder, axilla, and thigh-root form. + +### 8.1 Exhaustive gate-manifest inventory + +The gate manifest is generated from the following closed templates; it is not +assembled opportunistically by checks that happen to run. Template axes use +these exact ordered sets: + +```text +levels = [0,1,2] +sides = [left,right] +junctions = [junction.pelvis__left_hip,junction.pelvis__abdomen, + junction.abdomen__thorax,junction.thorax__left_shoulder, + junction.thorax__neck,junction.pelvis__right_hip, + junction.thorax__right_shoulder] +ports = [port.neck,port.left_arm,port.right_arm, + port.left_thigh,port.right_thigh] +junction_base_samples = [8,10,10,8,6,8,8] +port_base_samples = [6,8,8,8,8] +bilateral_anatomy = [shoulder_surface_descent,arm_port_descent, + axillary_turn_depth,axillary_path_stretch, + axillary_inboard_recess,axillary_downward_recess, + pelvic_vertical_wrap,pelvic_lateral_ratio, + front_depth_wrap,back_depth_wrap] +clearances = [neck,left_axilla,right_axilla,groin,medial_thigh] +``` + +Substitution preserves the printed axis order only while generating records; +each finished group is sorted by `gate_id` UTF-8 bytes. `nJ` and `nP` below +are the matching base-sample entries. `V_L,E_L,Q_L,Tri_L,B_L` are the exact +level counts in section 6. `cardinality(selector)` means the number of unique +samples produced by the exact incidence/chart selector before measuring; an +empty, duplicated, non-finite, or ambiguous selected set fails and cannot be +aggregated. + +| target group | gate ID template and Cartesian-product axes | exact sample selector and sample count | aggregation and threshold | +| --- | --- | --- | --- | +| structural | `structural.catalog.{metric}` for the 15 catalog metrics below | one computed scalar; `1` | `min=max=value`; catalog relation/value below | +| structural | `structural.catalog_boolean.{metric}` for the 13 booleans below | one complete predicate; `1` | `min=max=1`; `eq 1` | +| structural | `structural.L{L}.count.{metric}` for `levels x [vertices,edges,quads,triangles,boundary_edges]` | one computed count; `1` | `min=max=count`; `eq` section-6 count | +| structural | `structural.L{L}.surface_boolean.{metric}` for `levels x [connected,orientable,outward_wound,boundary_components_match_ports]` | one complete per-level predicate; `1` | `min=max=1`; `eq 1` | +| structural | `structural.L{L}.finite.{metric}` for `levels x [coordinates,quad_normals,triangle_areas,quad_areas]` | respectively all scalar coordinate components, normal components, triangle areas, or quad areas; `3*V_L`, `3*Q_L`, `2*Q_L`, or `Q_L` | require every member finite, then `min=max=1`; `eq 1` | +| structural | `structural.L{L}.floor.{metric}` for `levels x [edge_length,triangle_area,quad_area]` | all `E_L`, `2*Q_L`, or `Q_L` values; same number | observed minimum and maximum; `ge` the matching section-7 floor | +| structural | `structural.L{L}.invalid_count.{metric}` for `levels x` the nine invalid metrics below | one complete count; `1` | `min=max=count`; `eq 0` | +| structural | `structural.L{L}.chart.{metric}` for `levels x [charts,interior_transitions,maximum_samples_per_vertex]` | one complete count/maximum; `1` | `min=max=value`; `eq` section-5.1 value | +| structural | `structural.L2.lineage_cap.{metric}` for `[base_control_contributors,dependency_union_keys,contributor_domains]` | one value per level-2 vertex; `1737` | observed maximum; respectively `le 20`, `le 54`, `le 5` | +| structural | `structural.subdivision.{metric}` for the seven subdivision predicates below | one complete predicate; `1` | `min=max=1`; `eq 1` | +| continuity | `continuity.{junction}.L{L}.{metric}` for `junctions x levels x [tag_identity,opposite_trace_direction,coordinate_residual,fold_angle]` | complete paired traces for the junction; respectively `1`, `1`, `3*nJ*2^L`, `nJ*2^L` | first two `eq 1`; residual observed maximum `le T`; fold observed maximum `lt 90`, `lt 60`, or `lt 30` degrees for L0/L1/L2 | +| continuity | `continuity.{port}.L{L}.{metric}` for `ports x levels x [orientation,planarity,area_ratio,co_normal]` | exact evaluated port loop; respectively `1`, `nP*2^L`, `1`, `nP*2^L` | orientation scalar `ge 0.99`; planarity observed maximum `le T`; area scalar `ge 0.0001`; co-normal observed minimum `ge 0.80` | +| anatomy | `anatomy.neck_exposure.L{L}` for `levels` | all exact paired neck-junction/port tags; `6*2^L` | observed minimum; `ge 0.05 m` | +| anatomy | `anatomy.{metric}.{side}.L{L}` for `bilateral_anatomy x sides x levels` | selector/count rules below | observed minimum or maximum and relation specified below | +| anatomy | `anatomy.clearance.{name}.L{L}` for `clearances x levels` | one scalar from the named exact sample sets; `1` | `min=max=value`; `ge 0.05 m` | +| intersection | `intersection.L{L}.{metric}` for `levels x [triangle_count,broad_phase_candidate_count,intersection_hit_count,pair_policy_complete]` | one complete count or predicate; `1` | triangle count `eq Tri_L`; candidate count `le 1000000`; hit count `eq 0`; predicate `eq 1` | + +The 15 catalog metrics and values are exactly: + +```text +selected_cells=58, un_capped_faces=122, domains=8, junctions=7, ports=5, +controls=120, base_quads=104, base_edges=227, base_boundary_edges=38, +boundary_components=5, connected_components=1, euler_characteristic=-3, +extraordinary_controls=20, special_case_ids=9, topology_decision_sites=3 +``` + +All use `eq` except `topology_decision_sites`, which uses `le 3` and records +the observed value 3. Their units are `count` except Euler characteristic, +whose unit is `dimensionless`. The 13 catalog booleans are exactly +`all_domains_nonempty`, `selected_cell_inventory_exact`, +`control_catalog_exact`, `face_catalog_exact`, `junction_catalog_exact`, +`port_catalog_exact`, `special_case_catalog_exact`, +`base_face_controls_distinct`, `base_edge_use_within_two`, +`construction_ownership_complete`, `port_caps_exactly_removed`, +`axillary_fixture_suite_complete`, and +`intersection_fixture_suite_complete`. + +`intersection_fixture_suite_complete` equals 1 if and only if the seed builder +independently executes the exact 105 section-7 cases in their frozen order +through the production predicates and every case produces its frozen result. +`axillary_fixture_suite_complete` equals 1 if and only if the seed builder +independently executes the exact 13 section-8 cases in their frozen order +through the applicable production U/A/O or scalar predicate and every result +matches. Omission, duplication, substitution, a non-production predicate, a +wrong order or count, an unexpected result, an artifact emission, or reuse of +a unit-test result makes the corresponding Boolean 0. The managed tests in +section 11 independently execute the same 105 and 13 cases and do not trust +these manifest Booleans or reuse either seed builder's result. Both seed-local +fixture self-checks each contribute exactly one structural gate result, run +inside the existing `geometry-gates` timing and stage, and add no artifact or +output role. + +The nine per-level invalid metrics are exactly `duplicate_vertex_ids`, +`duplicate_face_ids`, `degenerate_faces`, `zero_length_edges`, +`non_manifold_edges`, `orientation_conflicts`, `unowned_elements`, +`overowned_elements`, and `accidental_boundary_components`. The seven +subdivision predicates are exactly `recurrence_exact`, `incidence_complete`, +`boundary_neighbors_exact`, `face_emission_exact`, `lineage_complete`, +`chart_complete`, and `transition_complete`. + +For bilateral anatomy, sample counts and thresholds are closed as follows: + +| metric | exact selector and sample count at level L | threshold | +| --- | --- | --- | +| `shoulder_surface_descent` | each unique vertex in the section-8 side shoulder-surface set; `cardinality(selector)` | `ge 0.05 m` for `min(neck-port y)-vertex.y` | +| `arm_port_descent` | each vertex in that side's evaluated arm-port loop; `8*2^L` | `ge 0.05 m` for `min(neck-port y)-vertex.y` | +| `axillary_turn_depth` | every reduced depth tag `k`; `2*2^L+1`, hence 3/5/9 at L0/L1/L2 | observed minimum; `ge 0.05 m` for `turn_depth` | +| `axillary_path_stretch` | the same independently reconstructed and paired depth-tag set; `2*2^L+1`, hence 3/5/9 at L0/L1/L2 | observed maximum; `le 2.5 dimensionless` for `path_stretch` | +| `axillary_inboard_recess` | every shoulder-trace perimeter tag with `4<=j<=5`; `4*2^L+1` | `ge 0.05 m` | +| `axillary_downward_recess` | the same independently selected perimeter-tag set; `4*2^L+1` | `ge 0.05 m` | +| `pelvic_vertical_wrap` | every paired hip-junction/thigh-port perimeter tag; `8*2^L` | `ge 0.05 m` | +| `pelvic_lateral_ratio` | those perimeter tags whose exact denominator is nonzero; `cardinality(selector after exact-zero exclusion)`, required positive | `ge 1.05 dimensionless` | +| `front_depth_wrap` | perimeter tags with `k>1`; `4*2^L-1` | `ge 0.005 m` | +| `back_depth_wrap` | perimeter tags with `k<1`; `4*2^L-1` | `ge 0.005 m` | + +The closed bilateral-anatomy inventory therefore contains exactly 10 metrics. +`axillary_turn_depth` and `axillary_path_stretch` each generate exactly +`2 sides * 3 levels = 6` aggregate gate results over their respective +3/5/9-sample level sets. + +The downward-thigh compatibility label creates no gate result. The port +orientation and pelvic-vertical-wrap results already provide its two exact +facts. Every sample selector above is reconstructed independently from +face/chart incidence as required by sections 5 and 8; labels, colours, or +bounding boxes cannot supply samples. + +Generated-threshold units are closed: predicates and finite checks use `boolean`; +integer inventories, topology/count results, chart/lineage counts, and +intersection counts use `count`; coordinate residual, planarity, edge length, +and linear anatomy/clearance measures use `m`; triangle and quad areas use +`m2`; fold angles use `degree`; and Euler characteristic, area ratio, +orientation dot, co-normal dot, and pelvic lateral ratio use `dimensionless`. +Axillary path stretch also uses `dimensionless`. No other unit string is +generated. The separately fixed report threshold +`gate.boolean-pass` retains its section-10.2 unit `dimensionless`. + +For every generated `gate_id`, generate exactly one `threshold_record` with +`threshold_id="threshold." + gate_id`; its relation, bound(s), and unit are +the values in the tables above. No two gate results share that generated +threshold ID. The only additional threshold is `gate.boolean-pass`, used by +the six run-report gates in section 10.2. Consequently the gate manifest has +exactly 356 generated gate thresholds plus that one report threshold: 357 +threshold records, with no unused or missing record. + +Before aggregation, every raw numeric sample MUST be finite. A boolean or +single count has `sample_count=1` and equal integer observed +minimum/maximum. A +multi-sample minimum, maximum, ratio, residual, area, or distance has the +exact selector cardinality as `sample_count` and stores the true minimum and +maximum of all raw samples, regardless of which bound decides the gate. No +summary may hide a failing member. Successful arrays equal the generated +inventories exactly, with no extra, empty, or omitted record. The arithmetic +is: + +```text +structural = 15+13+(3*5)+(3*4)+(3*4)+(3*3)+(3*9)+(3*3)+3+7 = 122 +continuity = 7*3*4 + 5*3*4 = 144 +anatomy = 3 + 10*2*3 + 5*3 = 78 +intersection = 3*4 = 12 +total gate results = 356 +``` + +## 9. Causality, must-affect, and locality + +The exact 33 source-derived must-affect parameter IDs are: + +```text +left.r_y, right.r_y, lower_pelvis.L_y, lower_pelvis.C_z, +left.r_x, right.r_x, lower_pelvis.R_x, +left.r_z, right.r_z, lower_pelvis.R_f, lower_pelvis.R_b, +left.thigh_start_x, left.thigh_start_y, left.thigh_start_z, +right.thigh_start_x, right.thigh_start_y, right.thigh_start_z, +neck_collar.C_y, neck_collar.rL, neck_upper.C_y, neck_upper.rL, +left.axilla_x, left.axilla_y, right.axilla_x, right.axilla_y, +left.peak_y, right.peak_y, +left.start_lateral, right.start_lateral, +left.start_up, right.start_up, +left.shoulder_depth, right.shoulder_depth +``` + +Their exact prepared-component selectors are: + +```text +left.r_y -> hips.left.r_y +right.r_y -> hips.right.r_y +lower_pelvis.L_y -> stations.lower_pelvis.C.y +lower_pelvis.C_z -> stations.lower_pelvis.C.z +left.r_x -> hips.left.r_x +right.r_x -> hips.right.r_x +lower_pelvis.R_x -> stations.lower_pelvis.rL +left.r_z -> hips.left.r_z +right.r_z -> hips.right.r_z +lower_pelvis.R_f -> stations.lower_pelvis.rA +lower_pelvis.R_b -> stations.lower_pelvis.rP +left.thigh_start_x -> hips.left.P_s.x +left.thigh_start_y -> hips.left.P_s.y +left.thigh_start_z -> hips.left.P_s.z +right.thigh_start_x -> hips.right.P_s.x +right.thigh_start_y -> hips.right.P_s.y +right.thigh_start_z -> hips.right.P_s.z +neck_collar.C_y -> stations.neck_collar.C.y +neck_collar.rL -> stations.neck_collar.rL +neck_upper.C_y -> stations.neck_upper.C.y +neck_upper.rL -> stations.neck_upper.rL +left.axilla_x -> shoulders.left.axilla.x +left.axilla_y -> shoulders.left.axilla.y +right.axilla_x -> shoulders.right.axilla.x +right.axilla_y -> shoulders.right.axilla.y +left.peak_y -> shoulders.left.peak.y +right.peak_y -> shoulders.right.peak.y +left.start_lateral -> shoulders.left.start_lateral +right.start_lateral -> shoulders.right.start_lateral +left.start_up -> shoulders.left.start_up +right.start_up -> shoulders.right.start_up +left.shoulder_depth -> shoulders.left.shoulder_depth +right.shoulder_depth -> shoulders.right.shoulder_depth +``` + +For each ID independently, copy the validated prepared input, add exactly +binary64 `+0.01 m` to that one selected scalar, and change no other prepared +component. This is a one-sided positive perturbation; no negative or central +difference run is admitted. A selector that resolves to zero, multiple, or a +different component fails before geometry. Analytic nonzero derivative support +MUST be derived from the frozen +formulas and propagated through the fixed subdivision stencils; it MUST NOT be +inferred from metadata, lineage labels, or observed movement. Zero-coefficient +contributors are reported separately and excluded from predicted support. + +Causality support is defined only over the numeric level-2 vertex indices +`0..1736`. For index `i`, calculate the vector +`delta_i=perturbed_coordinate_i-baseline_coordinate_i` componentwise and +`movement_i=norm(delta_i)` in the section-7 primitive order. The predicted +support is the sorted unique set of indices whose exact analytic derivative +with respect to the selected prepared component is nonzero after propagation +through both fixed subdivision stencils. The observed support is the sorted +unique set of indices for which `movement_i>T`. The two sets MUST be equal; +equivalently every predicted member moves by more than `T` and every other +level-2 vertex moves by at most `T`. + +At `lambda_x=1.00`, the exact level-2 predicted support for the +`hips.left.P_s.x` and `hips.right.P_s.x` perturbations is expected to contain +436 vertices per side. This is a dependency/support expectation only; the +fresh predicted and observed support sets and hashes remain mandatory. + +Each support set is hashed over this exact byte domain: + +```text +ASCII bytes "CKSUPPORTv1" +one NUL byte +one unsigned byte with value 2 +little-endian uint32 count +count little-endian uint32 numeric vertex indices in ascending order +no trailing byte +``` + +The count is at most 1737; every index is in range and strictly greater than +its predecessor. Empty predicted or observed support fails the perturbation +gate even though the byte grammar can represent count zero. Support bytes are +hash domains only and are not additional output files. + +For every parameter, the builder MUST prove: + +```text +support is nonempty +predicted and observed level-2 support sets and their hashes agree +max movement over predicted support >= M_min, where +M_min=fl(binary64(2.5e-4)*S)=0x1.d14e3bcd35a85p-11 m +final serialized mesh bytes differ from baseline +topology, IDs, formulas, ownership, and lineage are unchanged +all level-2 vertices outside predicted support move by at most T +``` + +Any admitted geometry-driving source role without a downstream consumer, +metadata movement without the required coordinate movement, or lineage +without a causal source binding fails closed. Forbidden inputs include profile +identity, finished geometry, connectivity, perimeters, point clouds, fields, +masks, corrective offsets, prior serialized output, and out-of-scope module +state. + +## 10. Artifact, schema, serialization, and rendering contract + +### 10.1 Canonical bytes and reusable records + +Canonical JSON bytes are produced only by exactly CPython 3.10.12 under the +frozen runtime fingerprint. Parse with a rejecting `object_pairs_hook` and +reject duplicate object keys before normalization. Canonical processing is +schema-aware: first recognize the exact closed object shape and field grammar. +Every map key MUST be a string and every value MUST be the declared JSON +string, boolean, null, array, map, integer, finite number, or binary64 type. +Type dispatch tests `bool` before `int`, so booleans never satisfy an integer +or numeric field. + +At runtime a field declared `binary64` contains only a finite Python `float`. +The encoder emits either signed binary64 zero as the single JSON integer token +`0`; every other binary64 float retains the exact CPython encoding below. It +preserves integers only in fields whose grammar admits integers and preserves +nonzero finite floats in fields whose grammar admits them. Then encode exactly: + +```python +json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") +``` + +The result has no BOM and no trailing LF. During schema-aware decoding of any +contract-owned canonical artifact, after duplicate-key rejection and closed +shape/key recognition but before binary64 type validation or numeric use, a +value in a `binary64` field is admitted only when it is a finite Python +`float`, or when its exact Python type is `int` and its value is exactly zero. +That sole integer-zero case is immediately coerced to binary64 `+0.0`; every +other integer token in a binary64 field rejects. A decoded `-0.0` or `0.0` +float is valid in memory but re-encodes as `0`, so either noncanonical wire +spelling fails the mandatory byte-for-byte re-encoding check. + +The builder and comparator MUST canonical re-encode every decoded prepared +input, manifest, report, receipt, and nested record and require byte equality +with the original artifact before checking hashes, references, identities, +semantic relations, or cross-seed equality. Semantic checks use the coerced +runtime object; SHA-256 and stable byte comparison use the original bytes +after this canonicality proof. Parsing and reserializing bytes does not itself +replace or redefine the hashing operation. +Hashes are SHA-256 over exact bytes and lowercase hexadecimal. Coordinate hash +bytes are row-major triples `x,y,z` as IEEE-754 little-endian binary64 in +numeric vertex order. Triangle-index hash bytes are row-major signed +little-endian int64 indices in `(a,b,c),(a,c,d)` order. These byte strings have +no header or delimiter. A manifest hash covers the exact manifest bytes and is +referred to only by a later node in the DAG. + +Every object grammar in this section is closed: listed keys are all required +and no other key is allowed. `hex64` means a lowercase 64-hex string; +`finite_number` means a non-boolean integer or finite binary64 float; +`role_path` means a nonempty canonical slash-separated role with no absolute +root, empty component, `.` component, or `..` component; `address_tuple` is +the normalized four-item JSON array defined in section 2.3; `runtime_string` +means a string whose UTF-8 encoding is at most 128 bytes; +`runtime_string-or-null` means null or `runtime_string`; `locale_string` means +a string whose UTF-8 encoding is at most 512 bytes; and `distribution_name` +means a canonical lowercase distribution name whose UTF-8 encoding is at most +128 bytes. `domain_id`, `junction_id`, and `construction_owner` are the exact +closed canonical types in sections 3.1 and 3.4; `junction_id-or-null` admits +only null or one of those seven junction IDs. Reusable records are: + +```text +file_record = {role_path: role_path, bytes: nonnegative integer, sha256: hex64} +manifest_ref = {role_path: role_path, bytes: nonnegative integer, + sha256: hex64, schema: string} +source_binding_record = { + prepared_component: string, + derivation_id: one of "source.dimension-value.v1", + "source.world-placement-axis-sum.v1", + "source.world-landmark-axis-sum.v1", + source_addresses: sorted nonempty unique array of address_tuple, + source_pointers: sorted nonempty unique array of canonical JSON-pointer strings +} +threshold_record = {threshold_id: string, + relation: one of "eq","ge","gt","le","lt","range", + lower: finite_number-or-null, + upper: finite_number-or-null, + unit: string} +gate_result = {gate_id: string, outcome: exactly "pass", + sample_count: positive integer, + observed_min: finite_number, + observed_max: finite_number, + threshold_id: string} +level_count_record = {level: integer 0..2, vertices: positive integer, + edges: positive integer, quads: positive integer, + triangles: positive integer, + boundary_edges: positive integer} +timing_record = {phase: string, seconds: finite nonnegative binary64} +``` + +Threshold arrays sort by `threshold_id`; gate-result arrays sort by `gate_id`; +file and manifest arrays sort by `role_path`; source bindings sort by +`prepared_component`; level counts and coordinate/index hash arrays sort by +`level`; every named-value array sorts by `name`; and string arrays sort by +UTF-8 bytes unless a different order is explicitly stated. A `gate_result` can occur +in a sealed successful bundle only with `outcome="pass"`, a matching declared +threshold, finite observed values where the measure is numeric, and values +that satisfy the relation. An `eq` record has equal non-null bounds; `ge` and +`gt` have only `lower`; `le` and `lt` have only `upper`; and `range` has both +with `lower<=upper`. Boolean and count bounds and observations are integers; +measured geometry, ratio, residual, angle, and timing values are binary64. +Boolean checks use observed minimum and maximum 1 against an `eq` threshold +of 1. A failed, skipped, unknown, or warning value is +not part of this algebra and cannot be serialized into a successful bundle. +Warnings remain run-local diagnostics and cannot replace a gate. + +The exact runtime record grammar is: + +```text +runtime_fingerprint = { + schema: exactly "owned-root-assembly-successor-runtime.v2", + python: { + implementation: exactly "CPython", version: exactly "3.10.12", + build: runtime_string, compiler: runtime_string, cache_tag: exactly "cpython-310", + abiflags: runtime_string, soabi: runtime_string + }, + platform: { + system: exactly "Linux", release: runtime_string, version: runtime_string, + machine: runtime_string, pointer_bits: positive integer, + byteorder: one of "little","big", libc_name: runtime_string, + libc_version: runtime_string + }, + locale: {active: locale_string, preferred_encoding: locale_string}, + managed_launcher: file_record, + requirements: file_record, + direct_distributions: array of exactly three distribution_record in the + exact declared order, + resolved_distributions: sorted array of exactly nine distribution_record, + builtin_modules: array of exactly two builtin_module_record in order math,zlib +} +distribution_record = {name: distribution_name, version: runtime_string} +builtin_module_record = { + module_name: one of "math","zlib", __file__: exactly null, + find_spec_origin: exactly "built-in", + compile_version: runtime_string-or-null, runtime_version: runtime_string-or-null +} +``` + +The direct records are exactly +`{name:"numpy",version:"2.2.6"}`, +`{name:"scikit-image",version:"0.25.2"}`, and +`{name:"pillow",version:"11.1.0"}` in that order. The resolved records are +exactly `imageio 2.37.4`, `lazy-loader 0.5`, `networkx 3.4.2`, +`numpy 2.2.6`, `packaging 26.3`, `pillow 11.1.0`, `scikit-image 0.25.2`, +`scipy 1.15.3`, and `tifffile 2025.5.10`, sorted by canonical lowercase name. +The math record requires `__file__` to be absent/`None` and +`find_spec(...).origin` to be exactly `"built-in"`; its compile and runtime +versions are null. The zlib record has the same `__file__` and origin proof, +with `compile_version` exactly `zlib.ZLIB_VERSION` and `runtime_version` +exactly `zlib.ZLIB_RUNTIME_VERSION`. Every general runtime string, distribution +name, and distribution version is at most 128 UTF-8 bytes. `locale.active` and +`locale.preferred_encoding` are each at most 512 UTF-8 bytes. The runtime +fingerprint SHA is SHA-256 of these canonical runtime-v2 JSON bytes. + +### 10.2 Recipe, prepared input, manifests, and reports + +The normalized recipe object has schema ID +`owned-root-assembly-successor-recipe.v1` and exactly these keys: + +```text +schema, contract_role, contract_sha256, sidecar_role, source, profile_table, +profile_id, correction_round, topology_id, formula_ids, subdivision_levels, +special_case_ids, gate_set_id, renderer_id, artifact_roles, implementation_files, +runtime_fingerprint_sha256 +``` + +`contract_role` and `sidecar_role` are the fixed roles in section 2.1; +`source` and `profile_table` are `file_record`; `profile_id` is +`standard_neutral_reference`; `correction_round` is the contract value; +`topology_id` is exactly `owned-root-58-cell-120-control-104-quad.v1`; +`formula_ids` is the sorted array of the eight dispatch formula IDs in section +4.1, including `formula.axial.station`; `special_case_ids` is the sorted array +of exactly the nine closed IDs in section 6; +`subdivision_levels` is integer 2; `gate_set_id` is exactly +`owned-root-neutral-gates.v1`; `renderer_id` is exactly +`owned-root-raster-pillow-11.1.0.v1`; `artifact_roles` is the sorted 47-role +inventory below; `implementation_files` is the sorted fifteen `file_record` +array from section 12; and `runtime_fingerprint_sha256` is `hex64`. +That hash covers the complete expanded section-10.1 runtime-v2 object. Both +input and stable manifests store that full object; a matching hash without +matching canonical runtime-v2 bytes is insufficient. +`recipe_id` is SHA-256 of this object's canonical JSON bytes. The recipe has +no `recipe_id`, seed, invocation, host path, output hash, manifest hash, +timestamp, or temporary path, so it has no hash cycle. It is reconstructed, +not published as a seventh manifest. + +`prepared-input.json` is the exact closed nested object in section 2.2 encoded +by section 10.1. Its arrays retain the declared address order; provenance +source files sort by path. + +The six manifest filenames and schema IDs are exactly: + +```text +input-manifest.json: owned-root-assembly-successor-input-manifest.v1 +coordinate-manifest.json: owned-root-assembly-successor-coordinate-manifest.v1 +gate-manifest.json: owned-root-assembly-successor-gate-manifest.v1 +causality-manifest.json: owned-root-assembly-successor-causality-manifest.v1 +render-manifest.json: owned-root-assembly-successor-render-manifest.v1 +stable-manifest.json: owned-root-assembly-successor-stable-manifest.v1 +``` + +Their exact nested grammars are: + +```text +input-manifest = { + schema, contract_sha256: hex64, source: file_record, + profile_table: file_record, + profile_id: exactly "standard_neutral_reference", + prepared_input: file_record, + source_bindings: sorted array of exactly 92 source_binding_record, + runtime: runtime_fingerprint, + implementation_files: sorted array of exactly 15 file_record, + recipe_id: hex64 +} +coordinate-manifest = { + schema, contract_sha256: hex64, input_manifest: manifest_ref, + counts: array of exactly three level_count_record, + coordinate_hashes: array of exactly three + {level: integer 0..2, bytes: positive integer, sha256: hex64}, + triangle_index_hashes: array of exactly three + {level: integer 0..2, bytes: positive integer, sha256: hex64}, + surface_artifacts: sorted array of exactly three file_record +} +gate-manifest = { + schema, contract_sha256: hex64, coordinate_manifest: manifest_ref, + thresholds: sorted array of exactly 357 threshold_record, + structural: sorted array of exactly 122 gate_result, + continuity: sorted array of exactly 144 gate_result, + anatomy: sorted array of exactly 78 gate_result, + intersection: sorted array of exactly 12 gate_result +} +causality-manifest = { + schema, contract_sha256: hex64, input_manifest: manifest_ref, + formula_records: array of exactly 120 formula_record sorted by control_id, + source_bindings: sorted array of exactly 92 source_binding_record, + charts: chart_summary, + perturbations: array of exactly 33 perturbation_record sorted by parameter_id +} +formula_record = { + control_id: section-3 exact cNNN control ID, + lattice_key: array of exactly three integers, + formula_id: string, construction_owner: construction_owner, + index_parameters: closed family-dispatched object from section 4.1, + geometry_dependencies: sorted unique string array, + coordinate: vector3 +} +dyadic = {numerator: integer, denominator: positive power-of-two integer} + reduced to lowest terms, with zero exactly {numerator:0,denominator:1} +chart_summary = { + level_counts: array of exactly three + {level: integer 0..2, charts: positive integer, + interior_transitions: nonnegative integer, + maximum_samples_per_vertex: positive integer}, + chart_records: array of exactly 2184 sorted by chart_id, with elements + {chart_id: section-5.1 exact chart ID, level: integer 0..2, + face_id: section-5.1 exact level-specific face ID, + base_face_id: section-3 exact qNNN base-face ID, + construction_owner: domain_id, + corners: array in face-cycle order of exactly four + {vertex_id: section-5.1 exact level-specific vertex ID, + u: dyadic, v: dyadic}}, + transition_records: array sorted by transition_id of exactly 4235 + {transition_id: section-5.1 exact transition ID, level: integer 0..2, + source_chart: section-5.1 exact chart ID, + destination_chart: section-5.1 exact chart ID, + source_edge_slot: integer 0..3, destination_edge_slot: integer 0..3, + endpoint_ids: array in ascending numeric vertex order at that level of + exactly two section-5.1 vertex IDs, + t_destination_rule: exactly "1-t_source", + junction_id: junction_id-or-null, + incident_domains: array in section-3.1 catalog order with exactly one + domain_id when junction_id is null, otherwise exactly + the paired two domain_ids for that junction}, + vertex_records: array of exactly 2308 sorted by (level,numeric vertex order) + {level: integer 0..2, + vertex_id: section-5.1 exact level-specific vertex ID, + samples: nonempty array sorted by (chart_id,u,v), with elements + {chart_id: section-5.1 exact chart ID, u: dyadic, v: dyadic}, + base_control_contributors: sorted unique array of section-3 cNNN control IDs, + maximum 20, + geometry_dependency_union: sorted unique array of prepared component + IDs, maximum 54, + contributor_domains: unique domain_id array in section-3.1 catalog + order, maximum 5} +} +perturbation_record = { + parameter_id: string, prepared_component: string, + delta_m: exactly binary64 0.01, + support_level: exactly integer 2, + predicted_support_count: positive integer <=1737, + observed_support_count: positive integer <=1737, + predicted_support_sha256: hex64, observed_support_sha256: hex64, + maximum_movement_m: positive finite binary64, + artifact: file_record +} +render-manifest = { + schema, contract_sha256: hex64, coordinate_manifest: manifest_ref, + render_config: render_config_record, + visibility: {level: exactly 2, triangle_count: exactly 3328, + triangle_index_sha256: hex64, + rule: exactly "larger-depth-then-lower-triangle-index"}, + artifacts: sorted array of exactly two file_record +} +stable-manifest = { + schema, contract_sha256: hex64, recipe_id: hex64, + runtime: runtime_fingerprint, + implementation_files: sorted array of exactly 15 file_record, + input_manifest: manifest_ref, coordinate_manifest: manifest_ref, + gate_manifest: manifest_ref, causality_manifest: manifest_ref, + render_manifest: manifest_ref, + artifact_hashes: sorted array of exactly five file_record +} +``` + +Each manifest's `schema` is exactly the ID paired with its filename above. +Every `vector3` and every field declared `binary64` anywhere in these +manifests, their nested records, prepared input, run reports, the managed-test +receipt, and the comparison report uses the section-10.1 schema-aware runtime, +wire-zero, decode-coercion, and canonical re-encoding rule. +Every manifest reference uses that filename as `role_path` and its paired +schema ID. Input source/profile roles are the fixed section-2 paths and its +prepared role is `prepared-input.json`; coordinate surface roles are the three +named surface PLYs; perturbation artifacts use the exact parameter-to-filename +mapping in section 10.3; render artifacts are `direct.png` and `lineage.png`; +and stable artifact roles are exactly those three surface PLYs plus those two +PNGs. A role/schema mismatch rejects even when hash bytes happen to match. + +The `formula_record` fields are exactly those required by section 4.1. +`artifact_hashes` contains only the three surface PLYs and two PNGs; prepared +input, perturbations, and implementation files are already bound by the input +or causality nodes. Stable manifests contain no absolute/temporary path, +timestamp, seed, invocation, display state, or value that differs across the +two fresh seed processes. + +The managed-test receipt is a transient canonical JSON object with schema ID +`owned-root-assembly-successor-managed-test-receipt.v1`. It is staged outside +both seed bundles and has this exact closed grammar: + +```text +managed_test_receipt = { + schema: exactly "owned-root-assembly-successor-managed-test-receipt.v1", + outcome: exactly "success", + literal_invocation: { + environment: exactly ["PYTHONHASHSEED=0"], + argv: exactly + ["experiments/owned-root-assembly-successor/build_owned_root.py", + "--internal-managed-tests", "--receipt", + ] + }, + contract_sha256: hex64, + runtime_fingerprint_sha256: hex64, + implementation_files: sorted array of exactly 15 file_record, + executed_test_ids: sorted nonempty unique string array, + required_test_ids: exactly + ["test_mesh_correctness.ProductionIntersectionFixtureTests.test_contract_fixture_matrix", + "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix"], + results: {tests_run: positive integer, failures: exactly 0, + errors: exactly 0, skipped: exactly 0, + expected_failures: exactly 0, + unexpected_successes: exactly 0} +} +``` + +Both required IDs MUST occur exactly once in `executed_test_ids`. The internal +test mode snapshots the contract record, complete runtime-v2 bytes and hash, +and exact fifteen implementation `file_record`s before discovery; after all +tests it reconstructs them and requires byte-identical equality before it may +write this success receipt. `tests_run` MUST equal the cardinality of +`executed_test_ids`; zero tests, an unlisted duplicate ID, any nonzero result +count, or failure to execute exactly the 105 intersection and 13 axillary +production-fixture cases rejects without a receipt. The comparator validates +the receipt against its own current identity and both seed bundles, embeds the +validated object in the comparison report, and removes the transient staging +file before publication. The receipt is not a seed artifact, stable role, or +comparison output. + +The run-local `report.json` schema ID is +`owned-root-assembly-successor-run-report.v1` and its exact grammar is: + +```text +{ + schema, outcome: exactly "success", seed: one of 17,29, + literal_invocation: {environment: array of exactly one string + "PYTHONHASHSEED=", argv: nonempty string array}, + output_path: absolute host path, staging_path: absolute host path, + python_executable_path: absolute host path, + started_utc: UTC string `YYYY-MM-DDTHH:MM:SS.ffffffZ`, + finished_utc: UTC string `YYYY-MM-DDTHH:MM:SS.ffffffZ`, + timings: array of exactly seven timing_record in order + identity, prepared-input, catalogs, geometry-gates, + causality, serialization, total-before-seal, + runtime_fingerprint_sha256: hex64, + stable_manifest: manifest_ref, + gates: array of exactly six gate_result sorted by gate_id +} +``` + +Only this run-local report and the managed-test receipt, including its embedded +comparison-report copy, may contain literal executable, output, staging, or +temporary host paths. Its `report.sha256` is exactly one LF-terminated line +`<64 lowercase hexadecimal report SHA-256>report.json`. +Neither file participates in stable identity or cross-seed byte comparison. +The six report `gate_id` values are exactly `seed.1.identity`, +`seed.2.prepared-input`, `seed.3.catalogs`, `seed.4.geometry-gates`, +`seed.5.causality`, and `seed.6.serialization`; each has sample count 1, +observed minimum and maximum 1, and threshold ID `gate.boolean-pass`, whose +fixed record is `{threshold_id:"gate.boolean-pass",relation:"eq",lower:1, +upper:1,unit:"dimensionless"}` and MUST be present in the gate-manifest +threshold array. +`literal_invocation.argv` is exactly the three private-builder argument strings +in order: `experiments/owned-root-assembly-successor/build_owned_root.py`, +`--output`, and that seed's absolute staging output path. It records the +private builder invocation, never the public shell launcher command; +normalization or shell-joined reconstruction is forbidden. + +The final `comparison-report.json` schema ID is +`owned-root-assembly-successor-comparison-report.v1` and its exact grammar is: + +```text +{ + schema, outcome: exactly "success", + comparator: file_record, + runtime_fingerprint_sha256: hex64, + managed_test_receipt: managed_test_receipt, + seed_bundles: array in seed order 17,29 of exactly + {seed: integer, role_path: one of "seed-17","seed-29", + stable_manifest: manifest_ref, report: file_record, + report_sidecar: file_record}, + stable_comparisons: sorted array of exactly 45 file_record, + excluded_run_local_roles: exactly ["report.json","report.sha256"] +} +``` + +Each stable comparison record contains the one byte count and SHA shared by +the two byte-identical files at that role. `comparator` is the bound +implementation `file_record` for `compare_two_seed_outputs.py`; this binds +comparator identity into completed pair evidence. The companion +`comparison-report.sha256` is exactly one LF-terminated line +`<64 lowercase hexadecimal comparison-report SHA-256>comparison-report.json`. +In the first seed-bundle record `seed=17`, `role_path="seed-17"`, and the three +nested roles are `seed-17/stable-manifest.json`, `seed-17/report.json`, and +`seed-17/report.sha256`; the second record is the exact seed-29 analogue. +The comparator's role is exactly +`experiments/owned-root-assembly-successor/compare_two_seed_outputs.py`. +`managed_test_receipt` is the exact validated, schema-aware decoded receipt +object from the transient staging file; it is embedded before that file is +removed and introduces no additional comparison-directory role. + +### 10.3 Closed inventory and acyclic hash graph + +The exact successful per-seed inventory is 47 files: 3 surface PLYs, 33 +perturbation PLYs, 2 PNGs, 6 manifests, 1 prepared input, 1 run report, and 1 +run-report sidecar. Relative to a seed output root, the complete role inventory +is: + +```text +surface-level-0.ply, surface-level-1.ply, surface-level-2.ply +perturb-left-r_y.ply, perturb-right-r_y.ply +perturb-lower_pelvis-L_y.ply, perturb-left-r_x.ply +perturb-lower_pelvis-C_z.ply, +perturb-right-r_x.ply, perturb-lower_pelvis-R_x.ply +perturb-left-r_z.ply, perturb-right-r_z.ply +perturb-lower_pelvis-R_f.ply, perturb-lower_pelvis-R_b.ply +perturb-left-thigh_start_x.ply, perturb-left-thigh_start_y.ply +perturb-left-thigh_start_z.ply, perturb-right-thigh_start_x.ply +perturb-right-thigh_start_y.ply, perturb-right-thigh_start_z.ply +perturb-neck_collar-C_y.ply, perturb-neck_collar-rL.ply +perturb-neck_upper-C_y.ply, perturb-neck_upper-rL.ply +perturb-left-axilla_x.ply, perturb-left-axilla_y.ply +perturb-right-axilla_x.ply, perturb-right-axilla_y.ply +perturb-left-peak_y.ply, perturb-right-peak_y.ply +perturb-left-start_lateral.ply, perturb-right-start_lateral.ply +perturb-left-start_up.ply, perturb-right-start_up.ply +perturb-left-shoulder_depth.ply, perturb-right-shoulder_depth.ply +direct.png, lineage.png +input-manifest.json, coordinate-manifest.json, gate-manifest.json +causality-manifest.json, render-manifest.json, stable-manifest.json +prepared-input.json, report.json, report.sha256 +``` + +The cross-seed stable comparison set is exactly the 45 roles above after +excluding `report.json` and `report.sha256`. The exact one-way hash adjacency +list is: + +```text +recipe -> contract, source, profile table, runtime fingerprint, + 15 implementation files, fixed topology/formula/gate/renderer/ + artifact-role configuration +input-manifest -> recipe_id, prepared-input, contract, source, profile table, + runtime fingerprint, 15 implementation files +coordinate-manifest -> input-manifest, coordinate/index byte strings, + 3 surface PLYs +gate-manifest -> coordinate-manifest, thresholds, gate results +causality-manifest -> input-manifest, formula/source/chart records, + 33 perturbation PLYs +render-manifest -> coordinate-manifest, renderer/visibility record, 2 PNGs +stable-manifest -> input, coordinate, gate, causality, render manifests, + recipe_id, runtime fingerprint, 15 implementation files, + 3 surface PLYs, 2 PNGs +comparison-report -> validated embedded managed-test receipt, 2 closed seed + bundles, their 45 stable role comparisons, bound + comparator identity and common runtime fingerprint +``` + +No node hashes itself or an ancestor. A stable manifest never hashes itself, +a report, or a sidecar. The comparison report is outside both seed DAGs and is +created only after both sealed bundles exist. + +### 10.4 PLY bytes + +PLY serialization is ASCII 1.0 with LF, declared double coordinates, quads, +deterministic ordering, and one terminal LF. For each finite coordinate, +normalize either signed zero to integer zero, call exactly CPython 3.10.12 +`format(value,'.17g')`, and canonicalize scientific notation, if present, as +`e` where +`sign` is exactly `+` or `-`; the mantissa is otherwise unchanged. Non-finite +values reject. Integer indices use ordinary unsigned base-10 spelling with no +leading zero except `0`. The exact header grammar is: + +```text +ply +format ascii 1.0 +element vertex N +property double x +property double y +property double z +element face Q +property list uchar int vertex_indices +end_header +``` + +The header substitutes decimal `N` and `Q`. Vertex rows follow section-6 +numeric vertex order and face rows follow numeric face order; the section-5.1 +IDs determine those orders but are not serialized into PLY. Each vertex row is +three canonical coordinate spellings separated by one ASCII space. Each face row is +`4 i0 i1 i2 i3`. Rows are separated by LF, with no comment, BOM, blank row, or +trailing byte after the terminal LF. The three baseline names and all 33 +level-2 perturbation names are exactly the PLY roles in section 10.3. Each +perturbation PLY comes from its own fresh baseline-versus-`+0.01 m` build. + +### 10.5 Exact renderer bytes + +Rendering uses Pillow 11.1.0 and the level-2 arrays. Each PNG is RGB 512x1536, +made from three 512x512 panels in order front, side, 45deg. Panel-local row +`r` is written to canvas row `r`, `512+r`, or `1024+r` respectively, with the +same column. The camera vectors +are literal binary64 values: + +```text +front: right=(1,0,0), up=(0,1,0), depth=(0,0,1) +side: right=(0,0,1), up=(0,1,0), depth=(1,0,0) +45deg: right=(0.7071067811865476,0,-0.7071067811865475), + up=(0,1,0), + depth=(0.7071067811865475,0,0.7071067811865476) +``` + +With larger depth winning, the front panel exposes the anatomical `+Z` +surface from a camera on the `+Z` side looking toward `-Z`; the side panel +exposes the anatomical `+X` surface; and the 45-degree panel exposes the +front-right `(+X,+Z)` surface from that quadrant. These are the existing +gallery conventions, not interchangeable camera signs. + +Let `m=fl(fl(lo+hi)/2)` componentwise for the common object-space AABB. For every +vertex and each camera, calculate `r=p-m`, then `u=dot(r,right)`, +`v=dot(r,up)`, and `z=dot(r,depth)` in section-7 order. Let `extent` be the +maximum of `abs(u)` and `abs(v)` over every projected vertex in all three +views; non-finite or nonpositive extent rejects. Compute the one common scale +as `scale=fl(232.0/extent)`. Panel coordinates are exactly +`x=fl(256.0+fl(scale*u))` and `y=fl(256.0-fl(scale*v))`; this is the required +Y inversion and leaves 24 pixels from the drawable boundary at coordinate 24 +or 488. Pixel `(row,column)` has center `(column+0.5,row+0.5)` for rows and +columns 0 through 511. + +Quads use triangles `(a,b,c)` then `(a,c,d)` in quad order; triangle indices +therefore ascend from 0 through 3327. For projected triangle vertices +`A=(ax,ay)`, `B=(bx,by)`, `C=(cx,cy)` and pixel center `P=(px,py)`, evaluate: + +```text +d0 = fl(by-cy); d1=fl(ax-cx); d2=fl(cx-bx); d3=fl(ay-cy) +den = fl(fl(d0*d1)+fl(d2*d3)) +if den is non-finite: reject rendering +if abs(den)<=1e-15: mark degenerate and stop this triangle +n0a = fl(by-cy); n0b=fl(px-cx); n0c=fl(cx-bx); n0d=fl(py-cy) +n0 = fl(fl(n0a*n0b)+fl(n0c*n0d)); w0=fl(n0/den) +n1a = fl(cy-ay); n1b=fl(px-cx); n1c=fl(ax-cx); n1d=fl(py-cy) +n1 = fl(fl(n1a*n1b)+fl(n1c*n1d)); w1=fl(n1/den) +w2 = fl(fl(1.0-w0)-w1) +depth = fl(fl(fl(w0*za)+fl(w1*zb))+fl(w2*zc)) +``` + +After the explicit denominator test, any non-finite intermediate rejects. +A degenerate triangle draws no pixel. Otherwise the sample is included exactly when +`w0>=-1e-12`, `w1>=-1e-12`, and `w2>=-1e-12`; there is no backface culling. +Visit panels in declared order, rows top-to-bottom, columns left-to-right, and +triangles by ascending index. Each pixel starts with `has_sample=false` and no +owner; no non-finite depth sentinel is used. A sample replaces an empty pixel, +or a populated pixel when its depth is greater, or when depth is bitwise equal +and its triangle index is lower. Processing in ascending index means an equal +later sample is retained behind the earlier one. Direct and lineage rendering use identical projected triangles, +inclusion, depth, and visibility arrays. + +Raster bytes use background `(247,247,247)` and direct surface +`(188,198,210)`. A lineage triangle uses exactly its base-face ancestor's +construction-owner domain palette entry; junction contributor multiplicity +never changes face colour: + +```text +domain.pelvis=(214,83,83) domain.abdomen=(226,157,68) +domain.thorax=(93,150,213) domain.neck=(153,102,204) +domain.left_shoulder=(81,168,115) domain.right_shoulder=(81,168,115) +domain.left_hip=(221,112,166) domain.right_hip=(221,112,166) +``` + +There is no shading, lighting, label, outline, anti-aliasing, alpha, or +culling. Create each final canvas with +`Image.new("RGB",(512,1536),(247,247,247))`, copy panel rows into it in the +declared scan order, and call +`image.save(path,format="PNG",compress_level=9,optimize=False)` with no PNG +info, ICC profile, EXIF, DPI, timestamp, text, or other metadata argument. +Same-runtime reproduction is scoped to the frozen Pillow/runtime fingerprint. +The two images differ only in triangle RGB selection; lineage MUST NOT add, +hide, move, or imply an internal surface. + +`render_config_record` is the closed canonical JSON projection of every +literal and vector in this subsection with exactly these keys: + +```text +width, height, panel_width, panel_height, panel_order, padding, +background_rgb, direct_rgb, domain_palette, cameras, common_scale_rule, +pixel_center_rule, barycentric_tolerance, degenerate_tolerance, +depth_rule, tie_rule, quad_split, shading, lighting, labels, outlines, +anti_aliasing, alpha, culling, pillow_version, png_compress_level, +png_optimize, png_metadata +``` + +The exact values are `width=512`, `height=1536`, `panel_width=512`, +`panel_height=512`, `panel_order=["front","side","45deg"]`, `padding=24`, the +RGB arrays and eight-key palette above, and a three-record `cameras` array in +panel order whose records are exactly `{name,right,up,depth}` with the literal +vectors above. `common_scale_rule` is exactly +`aabb-midpoint-all-views-extent-232.v1`; `pixel_center_rule` is exactly +`column-plus-0.5-row-plus-0.5-y-down.v1`; `barycentric_tolerance=-1e-12`; +`degenerate_tolerance=1e-15`; `depth_rule="larger-depth-wins"`; +`tie_rule="lower-triangle-index-wins"`; and +`quad_split=[[0,1,2],[0,2,3]]`. All seven feature flags are `false`; +`pillow_version="11.1.0"`; `png_compress_level=9`; `png_optimize=false`; and +`png_metadata` is exactly the empty object. Maps have no other keys. + +## 11. Paths, launcher, and reproducibility + +The four fixed orchestration/private-executable and sidecar paths are exactly +(the contract, source, and profile paths are fixed inputs in section 2, not +entries in this list): + +```text +experiments/owned-root-assembly-successor/owned_root_launcher.sh +experiments/owned-root-assembly-successor/build_owned_root.py +experiments/owned-root-assembly-successor/compare_two_seed_outputs.py +experiments/owned-root-assembly-successor/design-contract.sha256 +``` + +`owned_root_launcher.sh` is the only public execution entrypoint. From the +repository root its one exact invocation form is: + +```bash +PYTHONHASHSEED=0 experiments/owned-root-assembly-successor/owned_root_launcher.sh --output ABSENT_PATH +``` + +`ABSENT_PATH` MUST be an absolute fresh absent path. The launcher accepts +exactly `--output PATH`, requires literal `PYTHONHASHSEED=0`, and rejects every +other argument, environment hash seed, existing output target, missing fixed +file identity, or static identity mismatch before source admission or staging. +Contract, sidecar, source, profile, runtime, implementation allowlist, builder, +and comparator paths are fixed here rather than caller-selectable. + +After static admission the public launcher selects, but does not create, a +fresh private sibling staging-root path on the output filesystem. It invokes +these private managed commands in order through the repository-owned +current-form launcher: + +```bash +PYTHONHASHSEED=0 experiments/current-form-surface-preview/surface_preview_launcher.sh \ + experiments/owned-root-assembly-successor/build_owned_root.py \ + --internal-managed-tests \ + --receipt "$STAGING/managed-test-receipt.json" + +PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh \ + experiments/owned-root-assembly-successor/build_owned_root.py \ + --output "$STAGING/seed-17" + +PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh \ + experiments/owned-root-assembly-successor/build_owned_root.py \ + --output "$STAGING/seed-29" + +PYTHONHASHSEED=0 experiments/current-form-surface-preview/surface_preview_launcher.sh \ + experiments/owned-root-assembly-successor/compare_two_seed_outputs.py \ + "$STAGING/seed-17" "$STAGING/seed-29" \ + --test-receipt "$STAGING/managed-test-receipt.json" \ + --output "$STAGING/comparison" +``` + +`$STAGING` denotes the launcher's absolute invocation-owned staging path; it +is not a caller input. Before creating `$STAGING`, the first private test mode +rechecks every fixed file identity, constructs and admits the complete runtime +identity, and admits no source geometry. It discovers `test_*.py` under +`experiments/owned-root-assembly-successor/tests` with `unittest` +programmatically and produces only the section-10.2 receipt after satisfying +its exact identities, result counts, required test IDs, 105 intersection +cases, and 13 axillary cases. Only then may it create `$STAGING` and atomically +stage the receipt. Managed tests MUST NOT invoke the public +`owned_root_launcher.sh`; they invoke production functions and, where needed, +the private builder modes directly, so orchestration cannot recurse. + +After the comparator succeeds and the transient receipt is removed, the +public launcher requires the closed staging root: + +```text +seed-17/ exactly 47 files +seed-29/ exactly 47 files +comparison/ exactly comparison-report.json and comparison-report.sha256 +``` + +It then atomically publishes that complete three-directory outer root at +`ABSENT_PATH` with a no-replace rename. There is no standalone public unit-test, +seed-builder, or comparator command and no alternate multi-command evidence +sequence. + +The sidecar is exactly one LF-terminated line: + +```text +<64 lowercase hexadecimal contract SHA-256>experiments/owned-root-assembly-successor/design-contract.md +``` + +The two spaces and the exact repository-relative path are required; no BOM, +extra line, or alternate path is accepted. After fresh review, the final +contract SHA is materialized as an independent literal named +EXPECTED_CONTRACT_SHA256 in both owned_root_launcher.sh and build_owned_root.py. +Both literals MUST equal the SHA of the exact contract bytes and MUST be +checked independently of the sidecar. During this pre-build candidate pass +the literal and sidecar are intentionally absent; an empty, placeholder, or +caller-supplied identity MUST fail before source admission. The README anchor +for the final contract SHA is likewise intentionally absent and may be added +only after fresh review; this candidate does not create or update it. + +The launcher MUST use the repository-pinned current-form-surface environment, +record the complete runtime-v2 identity, and validate the runtime-v2 grammar and +all runtime string, locale string, and canonical runtime JSON size caps before +source admission. Each private seed builder independently rechecks all fixed +identities and runs section-13 groups 1 through 6 before atomically sealing its +closed 47-file staging bundle. A sealed seed bundle is diagnostic input to the +comparison, not completed experiment evidence. Failure of tests, either +builder, comparison, receipt removal, closed-root validation, or publication +emits nothing at `ABSENT_PATH`; cleanup is limited to invocation-owned staging. +Large meshes, PNGs, caches, captures, and datasets remain outside Git under the +artifact policy. + +Bare system Python and ambient package imports are forbidden. The private +comparator requires literal `PYTHONHASHSEED=0` and accepts exactly, in order, +the seed-17 bundle path, the seed-29 bundle path, +`--test-receipt RECEIPT_PATH`, and `--output COMPARISON_PATH`. Both option +paths MUST be absolute staging paths, the receipt MUST be the one just produced +by this orchestration, and the comparison path MUST be fresh and absent. + +The comparator and public launcher perform these six ordered stages: + +1. **Structure and receipt admission:** require both exact closed 47-file seed + inventories, regular-file and size rules, report-sidecar lexical grammars, + and the canonical transient managed-test receipt at the exact staging path. +2. **Identity:** require contract, sidecar, both code literals, source, + profile, recipe, all 15 implementation records, the current runtime, both + seed runtime records, and every receipt identity and result count to agree. +3. **Stable DAG and gates:** validate each manifest in + `input -> coordinate -> gate -> causality -> render -> stable` dependency + order, including schemas, canonical bytes, references, hashes, exact gate + inventories, all 357 thresholds, and successful gate algebra. This does not + independently rerun the six seed-local groups or pre-validate their + run-report stage records, which belong to stage 5. +4. **Stable comparison:** compare exactly the 45 stable roles in ascending + UTF-8 role order and require byte identity. +5. **Reports and sidecars:** process seed 17 and then seed 29; validate each + run-local report completely, including its six stage-result records and + stable-manifest reference, and then validate its report sidecar. Reports + remain excluded from stable comparison. +6. **Pair and outer publication:** embed the validated managed-test receipt, + construct and atomically seal the exact two-file comparison directory, + remove the transient staging receipt, then let the public launcher validate + and atomically publish the exact three-directory outer root. + +Each seed builder and the comparator independently constructs the complete +section-10.1 runtime-v2 fingerprint after its runtime admission checks. During +stage 2 the comparator requires its own canonical fingerprint bytes and hash, +the seed-17 runtime object, and the seed-29 runtime object to be identical; +the comparison report records that one common hash. + +Only boundaries between these six stages define failure precedence. Within a +failed stage the implementation may aggregate diagnostics and sort them by +UTF-8 identifier for reproducibility, but the contract chooses no primary +failure and no intra-stage diagnostic order is evidence semantics. Any failed +stage exits 1 and stage 6 publishes neither the comparison directory nor outer +root; success exits 0. Those are the only specified exit codes. Only the +successfully published outer root, containing the two sealed seed bundles and +two-file comparison directory, is completed technical evidence. + +The pinned requirements path is +`experiments/current-form-surface-preview/requirements.txt`, whose complete +package set is exactly `numpy==2.2.6`, `scikit-image==0.25.2`, and +`Pillow==11.1.0`. The managed launcher is the fixed +`experiments/current-form-surface-preview/surface_preview_launcher.sh` file +record. Any other external shell helper is an operational prerequisite only: +if it is absent or fails, launch stops before source admission, and it is not +part of stable identity. + +The runtime-v2 fields have these exact meanings. The managed launcher and +requirements are raw regular-file `file_record`s at their fixed role paths. +`python` is read from the running interpreter and requires +`platform.python_implementation() == "CPython"`, +`platform.python_version() == "3.10.12"`, `platform.python_build()` joined by +one ASCII space for `build`, `platform.python_compiler()` for `compiler`, +`sys.implementation.cache_tag == "cpython-310"`, `sys.abiflags` for +`abiflags`, and `sysconfig.get_config_var("SOABI")` for `soabi`. Each value +is a `runtime_string`; missing or mismatched values reject. +No Python executable bytes, path, role, or hash are admitted. + +`platform` uses the exact strings from `platform.system()`, +`platform.release()`, `platform.version()`, and `platform.machine()`, exactly +`Linux` for `system`, `8*struct.calcsize("P")` for `pointer_bits`, +`sys.byteorder` for `byteorder`, and the two `runtime_string` values from +`platform.libc_ver()` for `libc_name` and `libc_version`. `locale.active` is +`locale.setlocale(locale.LC_ALL,None)` and `locale.preferred_encoding` is +`locale.getpreferredencoding(False)`; both are recorded as `locale_string` +values, each with its separate 512-byte cap. The builder changes neither and +does not freeze a current locale literal. + +Canonical distribution naming lowercases ASCII and replaces each maximal run +of `-`, `_`, or `.` with one `-`; any other name byte rejects. Direct records +are obtained from the fixed requirements and must be exactly the three +lowercase records in the grammar. Resolved records are obtained by exact +metadata version lookup for the nine names in the grammar and must match the +exact sorted name/version list. No distribution-file attestation, installation +tree enumeration, module-file record, or native-file attestation is performed +or serialized. + +The builder imports `math` and `zlib` and independently checks that each +module's `__file__` is absent or `None` and that +`importlib.util.find_spec(module_name).origin == "built-in"`. The ordered +`builtin_modules` records use null `compile_version` and `runtime_version` for +math. The zlib record uses the exact strings `zlib.ZLIB_VERSION` and +`zlib.ZLIB_RUNTIME_VERSION` for those two fields. No standard-library file +record is admitted. + +Every seed builder and the comparator independently constructs the complete +runtime-v2 object, canonicalizes its JSON bytes, and hashes those bytes. The +only runtime claim is byte identity across two fresh hash-seed processes when +the recorded CPython build, platform, dependency versions, managed launch +source, contract, source, and implementation are the same. This does not +claim hermetic recreation, wheel/native equivalence across separate installs, +or adversarial supply-chain integrity. Runtime JSON bytes and its hash are +full manifest inputs; host paths, timestamps, temporary paths, and external +shell-helper state remain run-local or operational only. + + +The four paths at the start of this section are fixed candidate identity, +public-orchestration, or private-executable roles; they are not by themselves +an implementation-file allowlist. +Exactly three of them -- `owned_root_launcher.sh`, `build_owned_root.py`, and +`compare_two_seed_outputs.py` -- are also members of the exhaustive fifteen- +file implementation package in section 12. The sidecar is not implementation. +The contract, sidecar, source, profile table, current-form launcher, and +requirements file are the exhaustive fixed admitted identity inputs outside +that fifteen-file package. This intentional three-path overlap is the complete +reconciliation of the lists and authorizes no other source file. Future +implementation files may be absent in this pre-build state, but before a build +the launcher and builder independently require all fifteen implementation +files, reject symlinks, special files, or any additional implementation +source, and bind each canonical role, raw byte count, and SHA-256 into the +input manifest and stable identity. +This complete identity and allowlist check occurs before source admission or +creation of staging or output. + +## 12. Complexity and source budgets + +These are hard caps, not permissions to fill them: + +```text +domains: exactly 8, cap <=8, all nonempty +junctions: exactly 7, cap <=7 +open ports: exactly 5, cap <=5 +base controls: cap <=128, candidate exact 120 +base quads: cap <=120, candidate exact 104 +subdivision levels: exactly 2 +unique geometry dependencies: exactly 92 used +dependencies per formula record: <=12 +lineage contributors per vertex: <=20 +dependency union per vertex: <=54 +contributor domains per vertex: <=5 +special-case IDs: exactly 9, with no unnamed case +topology decision sites: <=3 +triangles per intersection run: <=4096 +broad-phase candidates: <=1,000,000 +active-set candidate subsets per shared-one pair: exactly 11 (6+4+1) +active-set evaluated attempts per shared-one pair: <=11 +exact PNG pixels: 786432 per PNG, exactly 2 PNGs, <=2 MiB each +surface PLY files: exactly 3, <=2 MiB each +perturbation PLY files: exactly 33, <=2 MiB each +causality manifest: <=8 MiB +every other JSON artifact: <=2 MiB +non-test physical LOC: <=3400 +test physical LOC: <=2600 +``` + +The following resource caps are fixed, with no wall-clock or RSS gate: + +```text +requirements file: <=64 KiB +managed launcher: <=4,000,000 bytes +runtime JSON: <=64 KiB +runtime and distribution strings other than the two locale fields: <=128 UTF-8 bytes +locale.active and locale.preferred_encoding: <=512 UTF-8 bytes each +resolved distributions: exactly 9 +repository implementation input files: <=4,000,000 bytes each +published output artifacts: <=256 MiB each +``` + +The runtime/distribution string caps, the separate locale caps, and the +canonical runtime JSON cap are checked before source admission and do not +authorize an omitted runtime-v2 field or distribution record. The exact-nine +resolved distribution set and the exact two built-in module records remain +mandatory. + +The implementation allowlist is exact and missing, additional, non-regular, +or byte-drifted implementation source files fail closed before source +admission. Every path has one `file_record` in both the input-manifest and +stable-manifest: + +```text +experiments/owned-root-assembly-successor/build_owned_root.py +experiments/owned-root-assembly-successor/prepared_projection.py +experiments/owned-root-assembly-successor/owned_root_surface.py +experiments/owned-root-assembly-successor/mesh_correctness.py +experiments/owned-root-assembly-successor/render_export.py +experiments/owned-root-assembly-successor/owned_root_launcher.sh +experiments/owned-root-assembly-successor/compare_two_seed_outputs.py +experiments/owned-root-assembly-successor/artifact_serialization.py +experiments/owned-root-assembly-successor/anatomy_gates.py +experiments/owned-root-assembly-successor/chart_lineage.py +experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +experiments/owned-root-assembly-successor/tests/test_prepared_projection.py +experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py +experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py +experiments/owned-root-assembly-successor/tests/test_render_export.py +``` + +The first ten paths are production files and the final five are test files; +this single 15-path list is the exhaustive package allowlist. Package-local +implementation source means every recursively discovered regular `.py` or +`.sh` file under `experiments/owned-root-assembly-successor`; the discovered +set MUST equal this list, and no differently suffixed package-local file may be +executed or imported. Documentation and the future SHA sidecar are identity +inputs, not implementation source. + +The implementation files are measured from the package root and test files +from its `tests/` directory with GNU `wc -l`: + +```bash +wc -l -- experiments/owned-root-assembly-successor/build_owned_root.py experiments/owned-root-assembly-successor/prepared_projection.py experiments/owned-root-assembly-successor/owned_root_surface.py experiments/owned-root-assembly-successor/mesh_correctness.py experiments/owned-root-assembly-successor/render_export.py experiments/owned-root-assembly-successor/owned_root_launcher.sh experiments/owned-root-assembly-successor/compare_two_seed_outputs.py experiments/owned-root-assembly-successor/artifact_serialization.py experiments/owned-root-assembly-successor/anatomy_gates.py experiments/owned-root-assembly-successor/chart_lineage.py +wc -l -- experiments/owned-root-assembly-successor/tests/test_build_owned_root.py experiments/owned-root-assembly-successor/tests/test_prepared_projection.py experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py experiments/owned-root-assembly-successor/tests/test_render_export.py +``` + +The sums of the first and second commands MUST remain within their respective +caps. The nine special-case IDs, exact allowlists, chart counts, and topology +catalog are closed sets; compressing code or omitting tests does not authorize +removing a required check. + +## 13. Seed-local gate and pair-publication order + +Before sealing one seed bundle, the per-seed builder MUST verify these six +groups in order: + +1. contract/sidecar, all fixed input and runtime identities, the exact + implementation allowlist, and recipe identity; +2. exact prepared schema, source bindings, metre behavior, neutral profile, + provenance cardinality, and non-geometric exclusions; +3. topology, ownership, junction, port, chart, transition, and special-case + catalogs and the eleven static catalog Boolean checks; +4. inside the existing `geometry-gates` timing, execute + `structural.catalog_boolean.axillary_fixture_suite_complete` and then + `structural.catalog_boolean.intersection_fixture_suite_complete` in + ascending UTF-8 gate-ID order, independently running the exact 13-case + axillary catalog and exact 105-execution intersection catalog through their + production predicates; then verify finite coordinates, structural floors, + subdivision, lineage, continuity, winding, folds, clearances, anatomy + selectors/gates, and intersection policy; +5. analytic causality for all 33 must-affect parameters, perturbation movement, + serialized difference, and locality; and +6. canonical manifests/PLYs, same-surface direct/lineage rendering, closed + 47-role inventory, resource/LOC caps, and run-report sidecar. + +The two fixture-suite Booleans are structural gate results despite executing +in group 4 rather than the static-catalog work in group 3. They reuse the +existing `geometry-gates` timing record, create no timing or gate stage, and +emit no artifact. The public launcher's mandatory internal managed tests in +section 11 precede both private seed builders and do not replace either +builder's independent group-4 self-check. + +The builder MUST publish no partial result after any failed group and MUST NOT +invoke or require the comparator: its own bundle cannot be compared before it +exists. After the two independently seeded private builders atomically seal +their staging bundles, the public orchestration invokes the private comparator +and completes section 11's ordered publication. The pair is incomplete +diagnostic material until the exact outer root is atomically published. The +direct and lineage diagnostics are two colourings of the same final evaluated +surface. No label, manifest, internal model review, or one seed's success can +replace the corresponding geometry, byte comparison, or later visual evidence. + +## 14. Neutral-only lock and future activation boundary + +This section is explicitly neutral-only. Passing every neutral technical gate, +plus a recorded main-thread inspection that finds the fixed neutral cues +credible, makes this candidate eligible for a separately SHA-256-bound +`exact-five-activation-contract.md`; it does not activate exact-five and does +not authorize exact-five output, gallery work, or a human checkpoint by itself. +The canonical prohibition on exact-five work before credible neutral remains +in force. + +The future additive activation contract may define only base-neutral +identity/evidence, the ordered five profile IDs, exact profile projection, +invocation/identity, and publication/comparison. It MUST freeze the 92- +component profile mapping, decimal factor and ties-to-even millimetre +projection, identity rotations and local landmarks, profile-placement parsing, +dual source/profile pointers, and fail-closed rule uniqueness. Geometry sees +numbers only and never a profile ID. + +That additive contract MUST NOT alter topology, formulas, tunables, thresholds, +gates, subdivision, ownership, causality, or renderer. It has its own exact +allowlist, hashes, and literals, and its additive freeze consumes zero +geometry corrections from this contract. The exact-five output cardinality is +intentionally undefined until that activation contract exists. If activated, +its profile order is exactly: + +```text +standard_neutral_reference +compact_broad_short_limb_large_head +tall_narrow_long_legged +slender_long_limb +stocky_broad_chested +``` + +## 15. Exclusions and disposition + +The prior seven-ring topology, projection, formulas, macros, candidate IDs, +thresholds, loops, and anatomy-specific tests are hard-excluded from this +candidate. Only separately audited representation-independent generic +utilities may be reused. No seven-ring branch, fallback, hidden surface, +global remesh, solver, or render correction may enter this implementation. + +This contract freezes a reproducible candidate design; it does not claim that +the candidate is implemented or good. The preliminary evidence remains +incomplete as stated in section 1. If the initial build plus two permitted shared +corrections still fails a frozen gate or the fixed visual cues, the candidate +is rejected or inconclusive and archived. Do not tune indefinitely, run +exact-five early, add distal anatomy or a tail, or silently switch +representations. A different representation requires a newly recorded runway +and human authorization. diff --git a/experiments/owned-root-assembly-successor/design-contract.sha256 b/experiments/owned-root-assembly-successor/design-contract.sha256 new file mode 100644 index 0000000..0380a76 --- /dev/null +++ b/experiments/owned-root-assembly-successor/design-contract.sha256 @@ -0,0 +1 @@ +3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490 experiments/owned-root-assembly-successor/design-contract.md From 0db1fdf782e9e3797ddd6ded21d3d044b461c027 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 21:19:18 +1200 Subject: [PATCH 05/38] Restore metre-native root-complex compatibility --- .../programmatic-root-complex-surface/README.md | 3 +++ .../prepared_projection.py | 10 +++++----- .../tests/test_prepared_projection.py | 11 ++++++++--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/experiments/programmatic-root-complex-surface/README.md b/experiments/programmatic-root-complex-surface/README.md index 673cd2b..eb7b12c 100644 --- a/experiments/programmatic-root-complex-surface/README.md +++ b/experiments/programmatic-root-complex-surface/README.md @@ -58,6 +58,9 @@ protocol](../../docs/research/visual-quality-evaluation.md). The admission gate accepts only source-derived scalar dimensions or measurements, rigid frames, individually named landmarks, section stations with scalar width/depth/offset/taper/squareness, module state, and provenance. +Dimension values are finite, strictly positive canonical metre values and are +admitted exactly as authored; this consumer does not interpret integers as +thousandths or apply a `/1000` scale. The prepared input is capped at 8 frames, 24 landmarks, 10 stations, and 6 scalars per station. Every numeric value carries source provenance or a deterministic derivation. The four scalar records emitted by the frozen diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index 45e3ed2..d912895 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -26,7 +26,7 @@ class _JSONRootTypeError(TypeError): pass _BODY = {"attachments", "capabilities", "dimensions", "fields", "frames", "joints", "landmarks", "modules", "parts", "regions", "sockets"} _COUNT = {"parts": 18, "frames": 16, "landmarks": 43, "dimensions": 153} _I = (0, 0, 0, 1) -_D = "derivation=source_dimension_integer_as_thousandths_of_canonical_metre_v1" +_D = "derivation=source_dimension_canonical_metre_value_v1" _P = "derivation=parent_local_part_translation_plus_landmark_position_v1" _BILATERAL_SCALARS = {"arm_root_depth": ("upper_arm", "form_arm_profile_upper_arm_start_forward_radius"), "arm_root_outward": ("upper_arm", "form_arm_profile_upper_arm_start_lateral_radius"), "thigh_lateral_radius": ("thigh", "form_leg_profile_thigh_start_lateral_radius"), "thigh_depth": ("thigh", "form_leg_profile_thigh_start_forward_radius")} @@ -106,9 +106,9 @@ def _part(rows, owner, parent): _ok(containment == {"root": True} if parent is None else set(containment) == {"parent"} and _addr(containment["parent"], where) == parent, where, "invalid containment") return translation, where def _add(a, b): result = tuple(x + y for x, y in zip(a, b)); _ok(all(_finite(value) for value in result), "derived point", "expected finite number"); return result -def _dimension(rows, owner, role): - row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions"); _ok(not isinstance(row["value"], bool) and isinstance(row["value"], int), f"{where}.value", "expected integer dimension"); value = _num(row["value"], f"{where}.value", True) / 1000.0 - return value, f"{where}.value; {_D}" +def _validate_dimensions(rows): + for i, raw in enumerate(rows): where, row = f"body.dimensions[{i}]", _dict(raw, f"body.dimensions[{i}]"); _ok(set(row) == {"owner", "role", "value"}, where, "unknown or missing required field"); _addr(row["owner"], f"{where}.owner"); _ok(isinstance(row["role"], str) and row["role"], f"{where}.role", "expected non-empty role"); _num(row["value"], f"{where}.value", True) +def _dimension(rows, owner, role): row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions"); return row["value"], f"{where}.value; {_D}" def _landmark(rows, owner, role, frame): row, where = _pick(rows, owner, role, {"owner", "role", "frame", "position"}, "landmarks"); ref = _dict(row["frame"], f"{where}.frame"); _ok(set(ref) == {"owner", "role"} and (_addr(ref["owner"], where), ref["role"]) == frame, where, "invalid landmark frame"); return _vec(row["position"], f"{where}.position"), where def _world_part(part_data, world, owner, parent): @@ -133,7 +133,7 @@ def prepare_standard_neutral(path): _ok(source["profiles"] == {"semantic_numeric": "ck.numeric-frame.r1"} and source["extensions"] == [], "source", "unsupported profile or extension") body = _dict(source["body"], "source.body"); _ok(set(body) == _BODY, "source.body", "unknown or missing collection") _ok(body["fields"] == [], "body.fields", "forbidden geometry-input collection") - for name, count in _COUNT.items(): _ok(isinstance(body[name], list) and len(body[name]) == count, f"body.{name}", f"expected {count} records") + for name, count in _COUNT.items(): _ok(isinstance(body[name], list) and len(body[name]) == count, f"body.{name}", f"expected {count} records"); _validate_dimensions(body["dimensions"]) if name == "dimensions" else None ns = source["source"]["namespace"] def part(role, side=None): return ns, () if side is None else (side,), "part", role p = {part("pelvis"): _part(body["parts"], part("pelvis"), None), part("torso"): _part(body["parts"], part("torso"), part("pelvis")), part("neck"): _part(body["parts"], part("neck"), part("torso"))} diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index 770924d..f0201d0 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -49,7 +49,7 @@ def test_source_identity_provenance_and_expected_controls(self): self.assertLess(self.prepared["landmarks"]["shoulder_peak_left"]["point"][0], 0) self.assertGreater(self.prepared["landmarks"]["shoulder_peak_right"]["point"][0], 0) self.assertEqual(self.prepared["scalars"]["arm_root_depth"]["value"], self.prepared["scalars"]["thigh_lateral_radius"]["value"]) - point_derivation = "derivation=parent_local_part_translation_plus_landmark_position_v1"; dimension_derivation = "derivation=source_dimension_integer_as_thousandths_of_canonical_metre_v1" + point_derivation = "derivation=parent_local_part_translation_plus_landmark_position_v1"; dimension_derivation = "derivation=source_dimension_canonical_metre_value_v1" expected_provenance = ( ("shoulder_peak_left", ("body.parts[0].placement.translation", "body.parts[1].placement.translation", "body.parts[4].placement.translation", "body.landmarks[0].position", point_derivation)), ("shoulder_peak_right", ("body.parts[0].placement.translation", "body.parts[1].placement.translation", "body.parts[7].placement.translation", "body.landmarks[2].position", point_derivation)), @@ -145,10 +145,15 @@ def test_add_rejects_non_finite_result_from_finite_operands(self): def test_consumed_source_rejects_invalid_dimension_values(self): pelvis = self.owner("pelvis") role = "form_torso_profile_lower_pelvis_lateral_radius" - cases = ((10**400, "expected finite number"), (1500.5, "expected integer dimension"), (True, "expected integer dimension")) + cases = ((10**400, "expected finite number"), (True, "expected finite number"), (False, "expected finite number"), (0, "expected positive number"), (-0.01, "expected positive number")) for value, message in cases: with self.subTest(value=value): self.assert_rejected(rf"body\.dimensions\[\d+\]\.value: {message}", lambda source, value=value: source["body"]["dimensions"][self.record_index(source, "dimensions", pelvis, role)].__setitem__("value", value)) + for index in range(153): self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) + def test_canonical_metre_dimensions_and_non_dimension_routes(self): + with tempfile.TemporaryDirectory() as directory: source = copy.deepcopy(self.source); source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_lateral_radius")]["value"] = 1.2345; source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_anterior_radius")]["value"] = 2; path = Path(directory) / "source.json"; path.write_text(json.dumps(source), encoding="utf-8"); prepared = prepare_standard_neutral(path) + self.assertEqual(prepared["stations"]["lower_pelvis"]["lateral_radius"], 1.2345); self.assertEqual(prepared["stations"]["lower_pelvis"]["front_extent"], 2) + self.assertEqual(prepared["basis"], self.prepared["basis"]); self.assertEqual(prepared["frames"], self.prepared["frames"]); self.assertEqual(prepared["landmarks"], self.prepared["landmarks"]); self.assertEqual({name: station["center"] for name, station in prepared["stations"].items()}, {name: station["center"] for name, station in self.prepared["stations"].items()}) def test_add_rejects_arbitrary_precision_integer(self): with self.assertRaisesRegex(PreparedProjectionError, r"derived point: expected finite number"): _add((10**400, 0, 0), (0, 0, 0)) @@ -171,4 +176,4 @@ def test_required_source_shape_and_routes_fail_closed(self): self.assert_rejected(r"body\.landmarks\.form_torso_profile_lower_pelvis: missing or duplicate required record", lambda source: self.duplicate_record(source, "landmarks", (pelvis, "form_torso_profile_lower_pelvis"), (pelvis, "form_torso_profile_upper_pelvis"))) self.assert_rejected(r"body\.landmarks\[\d+\]: missing record selector", lambda source: self.blank_record(source, "landmarks", (self.owner("upper_arm", ("left",)), "form_shoulder_peak"))) self.assert_rejected(r"source\.body: unknown or missing collection", lambda source: source["body"].__setitem__("unknown", [])) - self.assert_rejected(r"body\.frames\.form_torso_profile_control: missing or duplicate required record", lambda source: self.duplicate_record(source, "frames", (self.owner("torso"), "form_torso_profile_control"), (pelvis, "form_torso_profile_control"))) + self.assert_rejected(r"body\.frames\.form_torso_profile_control: missing or duplicate required record", lambda source: self.duplicate_record(source, "frames", (self.owner("torso"), "form_torso_profile_control"), (pelvis, "form_torso_profile_control"))); self.assert_rejected(r"body\.dimensions\[0\]: unknown or missing required field", lambda source: source["body"]["dimensions"][0].__setitem__("extra", 1)); self.assert_rejected(r"body\.dimensions\[0\]\.owner: invalid part address", lambda source: source["body"]["dimensions"][0]["owner"].__setitem__("kind", "joint")); self.assert_rejected(r"body\.dimensions\[0\]\.role: expected non-empty role", lambda source: source["body"]["dimensions"][0].__setitem__("role", "")) From b3c5cb7b36a4b11bac14c5240975ba3b8ddf2714 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 21:57:42 +1200 Subject: [PATCH 06/38] Add successor artifact and mesh foundations --- .../artifact_serialization.py | 503 ++++++++++++++ .../mesh_correctness.py | 649 ++++++++++++++++++ .../tests/test_build_owned_root.py | 556 +++++++++++++++ .../tests/test_mesh_correctness.py | 562 +++++++++++++++ .../tests/test_prepared_projection.py | 5 - 5 files changed, 2270 insertions(+), 5 deletions(-) create mode 100644 experiments/owned-root-assembly-successor/artifact_serialization.py create mode 100644 experiments/owned-root-assembly-successor/mesh_correctness.py create mode 100644 experiments/owned-root-assembly-successor/tests/test_build_owned_root.py create mode 100644 experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py diff --git a/experiments/owned-root-assembly-successor/artifact_serialization.py b/experiments/owned-root-assembly-successor/artifact_serialization.py new file mode 100644 index 0000000..45c7f38 --- /dev/null +++ b/experiments/owned-root-assembly-successor/artifact_serialization.py @@ -0,0 +1,503 @@ +"""Closed artifact serialization, stable inventory, and publication.""" +from __future__ import annotations +import ctypes +import errno +import hashlib +import json +import math +import os +import re +import secrets +import stat +import struct +from collections.abc import Iterable, Mapping +from pathlib import Path +from typing import Any + +CONTRACT_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +RENAME_NOREPLACE = 1 +SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) +_CLOEXEC = getattr(os, "O_CLOEXEC", 0) +_PATH = getattr(os, "O_PATH", os.O_RDONLY) +_STAT_FIELDS = ("st_dev", "st_ino", "st_mode", "st_nlink", "st_uid", "st_gid", + "st_size", "st_mtime_ns", "st_ctime_ns", "st_rdev", "st_blksize", + "st_blocks") +_PUBLISHED_STAT_FIELDS = tuple(field for field in _STAT_FIELDS if field != "st_ctime_ns") + + +class ArtifactSerializationError(ValueError): + pass + + +def _stat_key(info: os.stat_result) -> tuple[object, ...]: + """Return stable stat fields; atime is omitted because reads may update it.""" + return tuple(getattr(info, field, None) for field in _STAT_FIELDS) + + +def _same_stat(left: os.stat_result, right: os.stat_result) -> bool: + return _stat_key(left) == _stat_key(right) + + +def _require_same_stat(expected: os.stat_result, observed: os.stat_result, message: str) -> None: + if not _same_stat(expected, observed): + raise ArtifactSerializationError(message) + + +def _same_published_state(left: os.stat_result, right: os.stat_result) -> bool: + return (os.path.samestat(left, right) + and all(getattr(left, field, None) == getattr(right, field, None) + for field in _PUBLISHED_STAT_FIELDS)) + + +def _require_regular(info: os.stat_result, label: str) -> None: + if not stat.S_ISREG(info.st_mode): + raise ArtifactSerializationError(f"{label} is not a regular file") + if info.st_nlink > 1: + raise ArtifactSerializationError(f"{label} has external hardlinks") + + +def _require_publishable(info: os.stat_result, label: str) -> None: + if stat.S_ISLNK(info.st_mode): + raise ArtifactSerializationError(f"{label} must not be a symlink") + if stat.S_ISDIR(info.st_mode): + return + if not stat.S_ISREG(info.st_mode): + raise ArtifactSerializationError(f"{label} must be a regular file or directory") + if info.st_nlink > 1: + raise ArtifactSerializationError(f"{label} has external hardlinks") + + +def validate_role_path(value: object, *, label: str = "role_path") -> str: + if not isinstance(value, str) or not value or "\x00" in value: + raise ArtifactSerializationError(f"{label} must be a canonical relative path") + if value.startswith("/") or "\\" in value: + raise ArtifactSerializationError(f"{label} must be a canonical relative path") + if any(not part or part in {".", ".."} for part in value.split("/")): + raise ArtifactSerializationError(f"{label} contains an invalid component") + return value +def _canonical(value: Any, path: str = "$") -> Any: + if type(value) is float: + if not math.isfinite(value): + raise ArtifactSerializationError(f"non-finite number at {path}") + return 0 if value == 0.0 else value + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, Mapping): + if any(not isinstance(key, str) for key in value): + raise ArtifactSerializationError(f"invalid object key at {path}") + return {key: _canonical(item, f"{path}.{key}") for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_canonical(item, f"{path}[{i}]") for i, item in enumerate(value)] + raise ArtifactSerializationError(f"non-JSON value at {path}") +def canonical_json_bytes(value: Any) -> bytes: + try: + return json.dumps(_canonical(value), sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") + except (TypeError, ValueError, UnicodeEncodeError) as exc: + if isinstance(exc, ArtifactSerializationError): + raise + raise ArtifactSerializationError("value cannot be canonically encoded") from exc +def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result = {} + for key, value in pairs: + if key in result: + raise ArtifactSerializationError(f"duplicate object key: {key}") + result[key] = value + return result +def _reject_constant(value: str) -> None: + raise ArtifactSerializationError(f"non-finite JSON constant: {value}") +def decode_canonical_json(data: bytes | bytearray | memoryview | str) -> Any: + raw = data.encode("utf-8") if isinstance(data, str) else bytes(data) + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs, + parse_constant=_reject_constant) + except (UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError) as exc: + if isinstance(exc, ArtifactSerializationError): + raise + raise ArtifactSerializationError("invalid JSON artifact") from exc + if canonical_json_bytes(value) != raw: + raise ArtifactSerializationError("JSON artifact is not canonical") + return value +def coerce_binary64(value: object, *, label: str = "binary64") -> float: + if type(value) is float and math.isfinite(value): + return value + if type(value) is int and value == 0: + return 0.0 + raise ArtifactSerializationError(f"{label} is not a finite binary64 float or zero integer") +def sha256_bytes(data: bytes | bytearray | memoryview) -> str: + if not isinstance(data, (bytes, bytearray, memoryview)): + raise ArtifactSerializationError("hash input must be bytes-like") + return hashlib.sha256(bytes(data)).hexdigest() +def _path(path: str | os.PathLike[str]) -> Path: + try: + value = os.fspath(path) + return Path(os.path.abspath(os.fsdecode(value) if isinstance(value, bytes) else value)) + except (TypeError, ValueError) as exc: + raise ArtifactSerializationError("path must be a filesystem path") from exc +def _component(value: str, label: str) -> str: + if (not isinstance(value, str) or not value or value in {".", ".."} + or "/" in value or "\\" in value or "\x00" in value): + raise ArtifactSerializationError(f"{label} is not a safe path component") + return value +def _open_directory(path: str | os.PathLike[str]) -> int: + absolute = _path(path) + flags = os.O_RDONLY | os.O_DIRECTORY | _NOFOLLOW | _CLOEXEC + descriptor = os.open(absolute.anchor, flags) + try: + for part in absolute.parts[1:]: + child = os.open(_component(part, "directory component"), flags, + dir_fd=descriptor) + os.close(descriptor) + descriptor = child + if not stat.S_ISDIR(os.fstat(descriptor).st_mode): + raise ArtifactSerializationError("directory is not a directory") + return descriptor + except Exception: + os.close(descriptor) + raise +def _read_stable_with_identity(parent_fd: int, name: str, + max_bytes: int | None) -> tuple[bytes, os.stat_result]: + try: + fd = os.open(_component(name, "file name"), os.O_RDONLY | _NOFOLLOW | _CLOEXEC, + dir_fd=parent_fd) + except OSError as exc: + raise ArtifactSerializationError("cannot open regular file") from exc + try: + initial = os.fstat(fd) + _require_regular(initial, "opened file") + if max_bytes is not None and (type(max_bytes) is not int or max_bytes < 0 + or initial.st_size > max_bytes): + raise ArtifactSerializationError("regular file exceeds size cap") + readings = [] + for _ in range(2): + before_read = os.fstat(fd) + _require_same_stat(initial, before_read, "regular file changed before repeated read") + chunks, offset = [], 0 + while True: + before_chunk = os.fstat(fd) + _require_same_stat(initial, before_chunk, "regular file changed between chunks") + chunk = os.pread(fd, 1024 * 1024, offset) + after_chunk = os.fstat(fd) + _require_same_stat(initial, after_chunk, "regular file changed between chunks") + if not chunk: + break + offset += len(chunk) + if max_bytes is not None and offset > max_bytes: + raise ArtifactSerializationError("regular file exceeds size cap") + chunks.append(chunk) + readings.append(b"".join(chunks)) + final = os.fstat(fd) + _require_same_stat(initial, final, "regular file changed while reading") + if final.st_size != len(readings[1]) or readings[0] != readings[1]: + raise ArtifactSerializationError("regular file changed while reading") + return readings[1], final + except OSError as exc: + raise ArtifactSerializationError("regular file cannot be read stably") from exc + finally: + os.close(fd) + + +def _read_stable(parent_fd: int, name: str, max_bytes: int | None) -> bytes: + return _read_stable_with_identity(parent_fd, name, max_bytes)[0] + + +def read_regular_file(path: str | os.PathLike[str], *, max_bytes: int | None = None) -> bytes: + absolute = _path(path) + parent_fd = _open_directory(absolute.parent) + try: + data, opened = _read_stable_with_identity(parent_fd, absolute.name, max_bytes) + try: + named = os.stat(absolute.name, dir_fd=parent_fd, follow_symlinks=False) + except OSError as exc: + raise ArtifactSerializationError("requested file path changed while reading") from exc + if not _same_stat(opened, named): + raise ArtifactSerializationError("requested file path changed while reading") + return data + finally: + os.close(parent_fd) + + +def regular_file_record(path: str | os.PathLike[str], role_path: str | None = None, + *, max_bytes: int | None = None) -> dict[str, Any]: + absolute = _path(path) + role = absolute.name if role_path is None else validate_role_path(role_path) + data = read_regular_file(absolute, max_bytes=max_bytes) + return {"role_path": role, + "bytes": len(data), "sha256": sha256_bytes(data)} +def coordinate_hash_bytes(coordinates: Iterable[Iterable[object]]) -> bytes: + result = bytearray() + for row_index, row in enumerate(coordinates): + values = tuple(row) + if len(values) != 3: + raise ArtifactSerializationError(f"coordinate row {row_index} is not a vector3") + for axis, value in zip("xyz", values): + if type(value) is not float or not math.isfinite(value): + raise ArtifactSerializationError(f"coordinate {row_index}.{axis} is not binary64") + result.extend(struct.pack(" bytes: + result = bytearray() + for row_index, row in enumerate(triangles): + values = tuple(row) + if (len(values) != 3 or any(type(value) is not int or not -(1 << 63) <= value < (1 << 63) + for value in values)): + raise ArtifactSerializationError(f"triangle row {row_index} is invalid") + result.extend(struct.pack(" bytes: + if not isinstance(contract_sha256, str) or SHA256_RE.fullmatch(contract_sha256) is None: + raise ArtifactSerializationError("contract SHA-256 must be lowercase 64-hex") + return f"{contract_sha256} {CONTRACT_ROLE}\n".encode("ascii") +def validate_contract_sidecar(data: bytes | bytearray | memoryview, + expected_sha256: str) -> None: + if bytes(data) != contract_sidecar_bytes(expected_sha256): + raise ArtifactSerializationError("contract sidecar is not the exact required line") +def closed_inventory(root: str | os.PathLike[str], roles: Iterable[str], *, + max_file_bytes: int | None = None) -> tuple[dict[str, Any], ...]: + values = tuple(validate_role_path(role) for role in roles) + if len(set(values)) != len(values): + raise ArtifactSerializationError("closed inventory contains duplicate roles") + if max_file_bytes is not None and (type(max_file_bytes) is not int or max_file_bytes < 0): + raise ArtifactSerializationError("max_file_bytes must be a nonnegative integer") + expected = tuple(sorted(values, key=lambda value: value.encode("utf-8"))) + root_fd = _open_directory(root) + try: + expected_dirs = set() + for role in expected: + while "/" in role: + role = role.rsplit("/", 1)[0] + expected_dirs.add(role) + first = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) + second = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) + files = tuple(sorted((role for role, value in first.items() if value[1] is not None), + key=lambda value: value.encode("utf-8"))) + if first != second or files != expected: + raise ArtifactSerializationError("closed inventory changed or does not match") + return tuple(first[role][1] for role in expected) + finally: + os.close(root_fd) + + +def _inventory_snapshot(root_fd: int, expected_dirs: set[str], max_bytes: int | None) -> dict[str, Any]: + snapshot: dict[str, Any] = {} + try: + for relative, directories, _files, directory_fd in os.fwalk( + ".", topdown=True, follow_symlinks=False, dir_fd=root_fd): + prefix = "" if relative == "." else relative.removeprefix("./") + before = os.fstat(directory_fd) + if prefix in snapshot and snapshot[prefix][0] != _stat_key(before): + raise ArtifactSerializationError("inventory child directory changed while opening") + snapshot.setdefault(prefix, (_stat_key(before), None)) + names = sorted(os.listdir(directory_fd), key=lambda value: value.encode("utf-8")) + child_directories = [] + for name in names: + _component(name, "inventory entry") + role = f"{prefix}/{name}" if prefix else name + entry = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if stat.S_ISLNK(entry.st_mode): + raise ArtifactSerializationError(f"inventory contains a symlink: {role}") + if stat.S_ISDIR(entry.st_mode): + if role not in expected_dirs: + raise ArtifactSerializationError(f"inventory contains an unexpected directory: {role}") + snapshot[role] = (_stat_key(entry), None) + child_directories.append((name, role, entry)) + elif stat.S_ISREG(entry.st_mode): + _require_regular(entry, f"inventory file {role}") + data, opened = _read_stable_with_identity(directory_fd, name, max_bytes) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if (not _same_stat(entry, opened) or not _same_stat(opened, current) + or current.st_size != len(data)): + raise ArtifactSerializationError("inventory file was replaced while reading") + snapshot[role] = (_stat_key(current), + {"role_path": validate_role_path(role), + "bytes": len(data), "sha256": sha256_bytes(data)}) + else: + raise ArtifactSerializationError(f"inventory contains a non-regular entry: {role}") + for name, _role, expected_entry in child_directories: + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if not _same_stat(expected_entry, current): + raise ArtifactSerializationError("inventory child entry changed during traversal") + directories[:] = [name for name in directories + if (f"{prefix}/{name}" if prefix else name) in expected_dirs] + after = sorted(os.listdir(directory_fd), key=lambda value: value.encode("utf-8")) + if names != after or not _same_stat(before, os.fstat(directory_fd)): + raise ArtifactSerializationError("inventory directory changed during traversal") + except (OSError, UnicodeError) as exc: + raise ArtifactSerializationError("inventory traversal failed") from exc + return snapshot + + +def _rename_no_replace(parent_fd: int, source: str, destination: str) -> None: + if os.name != "posix": + raise ArtifactSerializationError("atomic no-replace publication requires Linux/WSL") + function = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) + if function is None: + raise ArtifactSerializationError("renameat2 is unavailable") + function.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, + ctypes.c_char_p, ctypes.c_uint] + function.restype = ctypes.c_int + result = function(parent_fd, os.fsencode(source), parent_fd, + os.fsencode(destination), RENAME_NOREPLACE) + if result == 0: + return + error = ctypes.get_errno() + if error == errno.EEXIST: + raise FileExistsError(destination) + raise ArtifactSerializationError(f"atomic no-replace rename failed: {os.strerror(error)}") + + +def _move_to_rollback_quarantine(parent_fd: int, name: str) -> str: + """Atomically preserve the entry currently at name under a fresh sibling name.""" + for _ in range(32): + quarantine = f".rollback-{os.getpid()}-{secrets.token_hex(8)}" + try: + _rename_no_replace(parent_fd, name, quarantine) + return quarantine + except FileExistsError: + continue + raise ArtifactSerializationError("unable to allocate publication rollback quarantine") + + +def _rollback_publication(parent_fd: int, source: str, destination: str, + expected_fd: int) -> bool: + """Restore the expected inode to source without deleting any directory entry.""" + quarantine = _move_to_rollback_quarantine(parent_fd, destination) + moved = os.stat(quarantine, dir_fd=parent_fd, follow_symlinks=False) + if not os.path.samestat(os.fstat(expected_fd), moved): + try: + _rename_no_replace(parent_fd, quarantine, destination) + except Exception as exc: + raise ArtifactSerializationError( + "unrelated destination entry remains preserved in rollback quarantine" + ) from exc + return False + try: + _rename_no_replace(parent_fd, quarantine, source) + except FileExistsError as exc: + raise ArtifactSerializationError( + "staging name was occupied; published entry remains in rollback quarantine" + ) from exc + restored = os.stat(source, dir_fd=parent_fd, follow_symlinks=False) + if not os.path.samestat(os.fstat(expected_fd), restored): + raise ArtifactSerializationError("rolled-back staging entry was replaced") + return True + + +def _publish_at(parent_fd: int, source: str, destination: str, + expected: os.stat_result, expected_fd: int) -> None: + _require_same_stat(expected, os.fstat(expected_fd), + "pinned staging entry changed before publication") + current = os.stat(source, dir_fd=parent_fd, follow_symlinks=False) + _require_publishable(current, "staging entry") + if not _same_stat(expected, current): + raise ArtifactSerializationError("staging entry changed before publication") + try: + os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise FileExistsError(destination) + renamed = False + try: + _rename_no_replace(parent_fd, source, destination) + renamed = True + installed = os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) + _require_publishable(installed, "published entry") + if not _same_published_state(expected, installed): + raise ArtifactSerializationError("published entry identity changed") + os.fsync(parent_fd) + verified = os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) + if (not os.path.samestat(expected, verified) + or not _same_published_state(expected, verified)): + raise ArtifactSerializationError("published entry changed after fsync") + _require_publishable(verified, "published entry") + except Exception as publication_failure: + if renamed: + try: + rolled_back = _rollback_publication( + parent_fd, source, destination, expected_fd + ) + except Exception as rollback_failure: + raise ArtifactSerializationError( + "publication failed and exact atomic rollback did not complete; " + f"original failure: {publication_failure}" + ) from rollback_failure + if not rolled_back: + raise ArtifactSerializationError( + "publication failed after destination replacement; " + "the unrelated entry was preserved" + ) from publication_failure + raise +def publish_no_replace(staging: str | os.PathLike[str], destination: str | os.PathLike[str]) -> Path: + stage, target = _path(staging), _path(destination) + if stage.parent != target.parent or stage.name == target.name: + raise ArtifactSerializationError("staging and destination must be distinct siblings") + _component(stage.name, "staging name") + _component(target.name, "destination name") + parent_fd = _open_directory(stage.parent) + source_fd = -1 + try: + source_fd = os.open(stage.name, _PATH | _NOFOLLOW | _CLOEXEC, + dir_fd=parent_fd) + source = os.fstat(source_fd) + _require_publishable(source, "staging entry") + _publish_at(parent_fd, stage.name, target.name, source, source_fd) + finally: + if source_fd >= 0: + os.close(source_fd) + os.close(parent_fd) + return target +def _temporary_file(parent_fd: int, target_name: str) -> tuple[int, str]: + for _ in range(32): + name = f".{target_name}.stage-{os.getpid()}-{secrets.token_hex(8)}" + try: + fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW | _CLOEXEC, + 0o600, dir_fd=parent_fd) + return fd, name + except FileExistsError: + continue + raise ArtifactSerializationError("unable to create a unique temporary artifact") +def write_bytes_no_replace(path: str | os.PathLike[str], data: bytes) -> Path: + if not isinstance(data, bytes): + raise ArtifactSerializationError("atomic payload must be bytes") + target = _path(path) + _component(target.name, "destination name") + parent_fd = _open_directory(target.parent) + descriptor, temporary_name = -1, "" + try: + try: + os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise FileExistsError(str(target)) + descriptor, temporary_name = _temporary_file(parent_fd, target.name) + identity = os.fstat(descriptor) + _require_regular(identity, "temporary artifact") + view = memoryview(data) + while view: + written = os.write(descriptor, view) + if written <= 0: + raise ArtifactSerializationError("temporary artifact write made no progress") + view = view[written:] + os.fsync(descriptor) + identity = os.fstat(descriptor) + _require_regular(identity, "temporary artifact") + _publish_at(parent_fd, temporary_name, target.name, identity, descriptor) + os.close(descriptor) + descriptor = -1 + return target + except Exception: + if descriptor >= 0: + os.close(descriptor) + # Conditional unlink by pathname is not available. Retaining the + # staging entry is safer than deleting an adversarial replacement. + raise + finally: + os.close(parent_fd) +def write_canonical_json_no_replace(path: str | os.PathLike[str], value: Any) -> Path: + return write_bytes_no_replace(path, canonical_json_bytes(value)) +def write_contract_sidecar_no_replace(path: str | os.PathLike[str], + contract_sha256: str) -> Path: + return write_bytes_no_replace(path, contract_sidecar_bytes(contract_sha256)) diff --git a/experiments/owned-root-assembly-successor/mesh_correctness.py b/experiments/owned-root-assembly-successor/mesh_correctness.py new file mode 100644 index 0000000..2097790 --- /dev/null +++ b/experiments/owned-root-assembly-successor/mesh_correctness.py @@ -0,0 +1,649 @@ +"""Fail-closed topology, geometry, and intersection checks.""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass +from fractions import Fraction +import itertools +import math + +_FIXED_I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") +_FIXED_D = float.fromhex("0x1.0000000000000p-46") +_FIXED_S = float.fromhex("0x1.c666666666666p+1") +_FIXED_T = float.fromhex("0x1.c666666666666p-45") +_FIXED_PI = float.fromhex("0x1.921fb54442d18p+1") +_FIXED_FOLD_LIMITS = (90.0, 60.0, 30.0) +_MAX_TRIANGLES = 4096 +_MAX_QUADS = _MAX_TRIANGLES // 2 +_MAX_CANDIDATES = 1_000_000 +_PORT_ORIENTATION, _PORT_AREA_RATIO, _PORT_CO_NORMAL = 0.99, 0.0001, 0.80 + +I0 = INTERSECTION_TOLERANCE = _FIXED_I0 +D = DEGENERACY_FLOOR = _FIXED_D +S, T, PI = _FIXED_S, _FIXED_T, _FIXED_PI +FOLD_LIMITS_DEGREES = _FIXED_FOLD_LIMITS +MAX_TRIANGLES, MAX_CANDIDATES = _MAX_TRIANGLES, _MAX_CANDIDATES +_STRUCTURAL_FLOORS = { + 0: {"edge_length": 0.10, "triangle_area": 0.010, "quad_area": 0.010}, + 1: {"edge_length": 0.04, "triangle_area": 0.002, "quad_area": 0.002}, + 2: {"edge_length": 0.02, "triangle_area": 0.0005, "quad_area": 0.0005}, +} +STRUCTURAL_FLOORS = {level: dict(values) for level, values in _STRUCTURAL_FLOORS.items()} +_THRESHOLD_RECORDS = tuple( + {"threshold_id": f"threshold.intersection.L{level}.broad_phase_candidate_count", + "relation": "le", "lower": None, "upper": _MAX_CANDIDATES, "unit": "count"} + for level in range(3) +) + +class MeshCorrectnessError(ValueError): + """A deterministic, fail-closed mesh correctness failure.""" + +def _fail(message: str) -> None: raise MeshCorrectnessError(message) +def _finite_float(value, label: str) -> float: + if type(value) is not float or not math.isfinite(value): _fail(f"{label} must be a finite binary64 value") + return value +def _integer(value, label: str) -> int: + if type(value) is not int: _fail(f"{label} must be an integer") + return value +def _sequence(raw, label: str, cap=None): + if type(raw) not in (list, tuple): + _fail(f"{label} must be an exact list or tuple") + if cap is not None and len(raw) > cap: + _fail(f"{label.rstrip('s')} cap exceeded: {len(raw)} > {cap}") + return raw +def _named_mapping(raw, label, count=None): + if type(raw) is not dict or not raw: + _fail(f"{label} must be a non-empty exact dict") + if any(type(name) is not str or not name for name in raw): + _fail(f"{label} names must be non-empty strings") + if count is not None and len(raw) != count: + _fail(f"exactly {count} {label} are required") + return raw +def _vec(value, label: str) -> tuple[float, float, float]: + values = _sequence(value, label) + if len(values) != 3: + _fail(f"{label} must be a finite 3-vector") + return tuple(_finite_float(item, f"{label}[{i}]") for i, item in enumerate(values)) +def _points(raw): + values = _sequence(raw, "vertices") + if not values: + _fail("vertices must not be empty") + return tuple(_vec(value, f"vertices[{i}]") for i, value in enumerate(values)) +def _simple_indices(raw, vertex_count, label): + values = tuple(_integer(value, label) for value in _sequence(raw, label)) + if (len(values) < 3 or len(set(values)) != len(values) + or any(index < 0 or index >= vertex_count for index in values)): _fail(f"{label} must be simple and in range") + return values +def _indexed_rows(raw, width, vertex_count, label, cap=None): + rows = _sequence(raw, label, cap) + result = [] + for face_index, row in enumerate(rows): + values = _sequence(row, f"{label}[{face_index}]") + if len(values) != width: + _fail(f"{label}[{face_index}] must have {width} indices") + face = tuple(_integer(value, f"{label}[{face_index}]") for value in values) + if any(index < 0 or index >= vertex_count for index in face): + _fail(f"{label} index out of range at {face_index}") + if len(set(face)) != width: + _fail(f"{label[:-1]} has repeated vertex index at {face_index}") + result.append(face) + return tuple(result) + +def _canonical_cycle(face): + return min(sequence[i:] + sequence[:i] + for sequence in (tuple(face), tuple(reversed(face))) + for i in range(len(face))) + +def _quads(raw, vertex_count): + faces = _indexed_rows(raw, 4, vertex_count, "quads", _MAX_QUADS) + keys = tuple(_canonical_cycle(face) for face in faces) + if len(set(keys)) != len(keys): + _fail("duplicate quad, including reversed/cyclic duplicate") + return faces + +def _add_vec(a, b): return tuple(a[i] + b[i] for i in range(3)) +def _sub_vec(a, b): return tuple(a[i] - b[i] for i in range(3)) +def _dot_vec(a, b): return (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2] + +def _cross_vec(a, b): + return (a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]) + +def _norm_vec(value): return math.sqrt(_dot_vec(value, value)) + +def _normalize_vec(value, label): + length = _norm_vec(value) + if not math.isfinite(length) or length <= 0.0: + _fail(f"{label} must be finite and nonzero") + return tuple(component / length for component in value) + +def add(a, b): return _add_vec(_vec(a, "left vector"), _vec(b, "right vector")) +def sub(a, b): return _sub_vec(_vec(a, "left vector"), _vec(b, "right vector")) +def dot(a, b): return _dot_vec(_vec(a, "left vector"), _vec(b, "right vector")) +def cross(a, b): return _cross_vec(_vec(a, "left vector"), _vec(b, "right vector")) +def norm(value): return _norm_vec(_vec(value, "vector")) +def normalize(value): return _normalize_vec(_vec(value, "vector"), "vector normal") + +def _normalize_points(points): + lower = tuple(min(point[i] for point in points) for i in range(3)) + extent = tuple(max(point[i] for point in points) - lower[i] for i in range(3)) + scale = _norm_vec(extent) + if not math.isfinite(scale) or scale <= 0.0: + _fail("mesh normalization scale must be finite and positive") + normalized = tuple(tuple((point[i] - lower[i]) / scale for i in range(3)) + for point in points) + if any(not math.isfinite(value) for point in normalized for value in point): + _fail("normalized coordinates must be finite") + return normalized, scale + +def interval_disjoint(lower_a, upper_a, lower_b, upper_b): + values = tuple(_finite_float(value, label) for value, label in zip( + (lower_a, upper_a, lower_b, upper_b), + ("lower_A", "upper_A", "lower_B", "upper_B"))) + return _interval_disjoint(*values) + +def _interval_disjoint(lower_a, upper_a, lower_b, upper_b): + return (upper_a < lower_b - _FIXED_I0 + or upper_b < lower_a - _FIXED_I0) + +def _edge_incidence(faces): + result = defaultdict(list) + for face_index, face in enumerate(faces): + for slot, start in enumerate(face): + end = face[(slot + 1) % len(face)] + result[(min(start, end), max(start, end))].append((face_index, start, end)) + return result + +def _validate_loops(raw, vertex_count): + if raw is None: + return {} + raw = _named_mapping(raw, "boundary loops") + result, used = {}, set() + for name in sorted(raw, key=lambda value: value.encode("utf-8")): + loop = _simple_indices(raw[name], vertex_count, f"boundary loop {name}") + if used.intersection(loop): + _fail(f"boundary loops overlap at {name}") + used.update(loop) + result[name] = loop + return result + +def _cyclic_equal(actual, expected, reverse=False): + target = tuple(reversed(expected)) if reverse else tuple(expected) + return len(actual) == len(target) and any(actual == target[i:] + target[:i] for i in range(len(target))) + +def _boundary_cycles(edges): + outgoing = defaultdict(list) + for _, start, end in edges: + outgoing[start].append(end) + if any(len(values) != 1 for values in outgoing.values()): + _fail("boundary edges do not form directed cycles") + next_vertex = {start: values[0] for start, values in outgoing.items()} + remaining, cycles = set(next_vertex), [] + while remaining: + start = current = min(remaining) + cycle = [] + while current in remaining: + remaining.remove(current) + cycle.append(current) + current = next_vertex[current] + if current != start or len(cycle) < 3: + _fail("boundary cycle is not closed") + cycles.append(tuple(cycle)) + return tuple(sorted(cycles, key=lambda cycle: min(cycle))) + +@dataclass(frozen=True) +class TopologyReport: + vertex_count: int + edge_count: int + face_count: int + boundary_edge_count: int + boundary_components: int + connected_components: int + euler: int + non_manifold_edges: int + orientation_conflicts: int + boundary_lengths: tuple[int, ...] + valence_inventory: tuple[tuple[int, int], ...] + + @property + def euler_characteristic(self): + return self.euler + +def _connected_components(adjacency, vertex_count): + unseen, components = set(range(vertex_count)), 0 + while unseen: + todo = [unseen.pop()] + components += 1 + while todo: + neighbours = adjacency[todo.pop()].intersection(unseen) + unseen.difference_update(neighbours) + todo.extend(neighbours) + return components + +def _topology_report(vertex_count, quads, loops, expected_faces): + if expected_faces is not None: + expected = _indexed_rows( + expected_faces, 4, vertex_count, "expected_faces", _MAX_QUADS) + if quads != expected: _fail("face winding/catalog does not match exactly") + incidence = _edge_incidence(quads) + non_manifold = sum(len(items) > 2 for items in incidence.values()) + if non_manifold: _fail(f"non-manifold edge count {non_manifold}") + conflicts = sum(len(items) == 2 and items[0][1:] == items[1][1:] + for items in incidence.values()) + if conflicts: _fail(f"orientation conflict count {conflicts}") + boundary = [items[0] for items in incidence.values() if len(items) == 1] + cycles = _boundary_cycles(boundary) if boundary else () + if loops: + expected = tuple(sorted(loops.values(), key=lambda cycle: min(cycle))) + if len(cycles) != len(expected) or any( + sum(_cyclic_equal(actual, wanted) for wanted in expected) != 1 + for actual in cycles): + _fail("boundary cycle does not match a declared loop orientation") + adjacency, valence, used = defaultdict(set), defaultdict(int), set() + for first, second in incidence: + adjacency[first].add(second) + adjacency[second].add(first) + valence[first] += 1 + valence[second] += 1 + used.update((first, second)) + if len(used) != vertex_count: + _fail("unused vertex IDs are not permitted") + components = _connected_components(adjacency, vertex_count) + if components != 1: _fail("surface is not connected") + return TopologyReport( + vertex_count, len(incidence), len(quads), len(boundary), len(cycles), components, + vertex_count - len(incidence) + len(quads), non_manifold, conflicts, + tuple(len(cycle) for cycle in cycles), tuple(sorted(valence.items()))) + +def validate_topology(vertex_count, faces, boundary_loops=None, expected_faces=None): + _integer(vertex_count, "vertex_count") + if vertex_count <= 0: + _fail("vertex_count must be positive") + quads = _quads(faces, vertex_count) + return _topology_report(vertex_count, quads, _validate_loops(boundary_loops, vertex_count), + expected_faces) + +def _triangle_normal(triangle, points): + return _cross_vec(_sub_vec(points[triangle[1]], points[triangle[0]]), _sub_vec(points[triangle[2]], points[triangle[0]])) +def _quad_data(quad, points): + first, second, third, fourth = (points[index] for index in quad) + normal_a = _cross_vec(_sub_vec(second, first), _sub_vec(third, first)) + normal_b = _cross_vec(_sub_vec(third, first), _sub_vec(fourth, first)) + area = 0.5 * _norm_vec(normal_a) + 0.5 * _norm_vec(normal_b) + return area, _normalize_vec(_add_vec(normal_a, normal_b), "quad normal") +def _loop_geometry(selected): + centroid = (0.0, 0.0, 0.0) + for point in selected: + centroid = _add_vec(centroid, point) + centroid = tuple(value / len(selected) for value in centroid) + area = (0.0, 0.0, 0.0) + for index, point in enumerate(selected): + area = _add_vec(area, _cross_vec(_sub_vec(point, centroid), + _sub_vec(selected[(index + 1) % len(selected)], centroid))) + return centroid, tuple(0.5 * value for value in area) + +def port_loop_metrics(points, loop, outward_direction, adjacent_normals): + points = _points(points) + loop = _simple_indices(loop, len(points), "port loop") + direction = _normalize_vec(_vec(outward_direction, "port direction"), "port direction") + selected = tuple(points[index] for index in loop) + centroid, area = _loop_geometry(selected) + area_unit = _normalize_vec(area, "port area normal") + normals = tuple(_normalize_vec(_vec(value, "adjacent face normal"), + "adjacent face normal") + for value in _sequence(adjacent_normals, "adjacent normals")) + if len(normals) != len(loop): + _fail("port adjacent-normal count must equal loop edge count") + result = { + "orientation": -_dot_vec(area_unit, direction), + "planarity": max(abs(_dot_vec(_sub_vec(point, centroid), area_unit)) + for point in selected), + "area_ratio": _norm_vec(area) / (_FIXED_S * _FIXED_S), + "co_normal": min( + _dot_vec(_normalize_vec(_cross_vec( + _normalize_vec(_sub_vec(selected[(i + 1) % len(selected)], selected[i]), + "port tangent"), normal), "port co-normal"), direction) + for i, normal in enumerate(normals)), + } + if any(not math.isfinite(value) for value in result.values()): + _fail("port metrics must be finite") + return result + +def validate_port_loop(points, loop, outward_direction, adjacent_normals): + metrics = port_loop_metrics(points, loop, outward_direction, adjacent_normals) + if metrics["orientation"] < _PORT_ORIENTATION: + _fail("port orientation gate failed") + if metrics["planarity"] > _FIXED_T: + _fail("port planarity gate failed") + if metrics["area_ratio"] < _PORT_AREA_RATIO: + _fail("port area-ratio gate failed") + if metrics["co_normal"] < _PORT_CO_NORMAL: + _fail("port induced co-normal gate failed") + return metrics + +def _tagged_trace(raw, label): + items = _sequence(raw, label) + result, seen = [], set() + for item in items: + if type(item) not in (tuple, list) or len(item) != 2: + _fail(f"{label} contains an invalid tagged sample") + tag, point = item + try: + if tag in seen: + _fail(f"{label} contains duplicate tags") + seen.add(tag) + except TypeError as exc: + raise MeshCorrectnessError(f"{label} contains an unhashable tag") from exc + result.append((tag, _vec(point, f"{label}[{tag!r}]"))) + if not result: + _fail(f"{label} must not be empty") + return tuple(result) + +def junction_continuity_metrics(trace_a, trace_b): + first, second = _tagged_trace(trace_a, "trace A"), _tagged_trace(trace_b, "trace B") + first_tags, second_tags = tuple(tag for tag, _ in first), tuple(tag for tag, _ in second) + if set(first_tags) != set(second_tags): + _fail("junction trace tag sets differ") + if not _cyclic_equal(first_tags, second_tags, reverse=True): + _fail("junction trace directions are not opposite") + first_values, second_values = dict(first), dict(second) + try: + tags = sorted(first_values) + except TypeError as exc: + raise MeshCorrectnessError("junction trace tags must be orderable") from exc + residual = max(max(abs(first_values[tag][axis] - second_values[tag][axis]) + for axis in range(3)) for tag in tags) + if not math.isfinite(residual) or residual > _FIXED_T: + _fail("junction coordinate residual exceeds tolerance") + return {"tag_identity": True, "opposite_trace_direction": True, + "coordinate_residual": residual} + +def fold_angle_degrees(normal_a, normal_b): + first = _normalize_vec(_vec(normal_a, "fold normal A"), "fold normal A") + second = _normalize_vec(_vec(normal_b, "fold normal B"), "fold normal B") + cosine = max(-1.0, min(1.0, _dot_vec(first, second))) + angle = math.acos(cosine) + first_step = angle * 180.0 + return first_step / _FIXED_PI + +def validate_fold(normal_a, normal_b, level): + level = _integer(level, "fold level") + if level not in range(3): + _fail("fold level must be 0, 1, or 2") + angle = fold_angle_degrees(normal_a, normal_b) + if not angle < _FIXED_FOLD_LIMITS[level]: + _fail(f"fold angle {angle!r} is not below {_FIXED_FOLD_LIMITS[level]!r}") + return angle + +def _validate_junction_traces(raw): + raw = _named_mapping(raw, "junction traces", 7) + result = {} + for name in sorted(raw, key=lambda value: value.encode("utf-8")): + pair = _sequence(raw[name], f"{name} trace pair") + if len(pair) != 2: + _fail(f"{name} requires two traces") + result[name] = tuple(_tagged_trace(value, f"{name}.{side}") + for side, value in zip(("A", "B"), pair)) + return result + +def _face_owners(raw, face_count): + owners = _sequence(raw, "face_owners", _MAX_QUADS) + if len(owners) != face_count or any(type(owner) is not str or not owner for owner in owners): + _fail("face_owners must contain one non-empty string per face") + return owners + +def _boundary_normals(loops, incidence, quad_normals): + result = {} + for name, loop in loops.items(): + normals = [] + for slot, start in enumerate(loop): + end = loop[(slot + 1) % len(loop)] + uses = incidence.get((min(start, end), max(start, end)), ()) + if len(uses) != 1: + _fail(f"{name} boundary edge is not uniquely derived") + normals.append(quad_normals[uses[0][0]]) + result[name] = tuple(normals) + return result + +def _run_fold_gates(incidence, owners, quad_normals, level): + count = 0 + for uses in incidence.values(): + if len(uses) == 2 and owners[uses[0][0]] != owners[uses[1][0]]: + validate_fold(quad_normals[uses[0][0]], quad_normals[uses[1][0]], level) + count += 1 + return count + +def _aabb(points, triangle): + corners = tuple(points[index] for index in triangle) + return (tuple(min(point[i] for point in corners) for i in range(3)) + + tuple(max(point[i] for point in corners) for i in range(3))) +def _shared_edge_direction(triangle, shared): + shared = set(shared) + for i, start in enumerate(triangle): + end = triangle[(i + 1) % 3] + if {start, end} == shared: + return start, end + _fail("shared edge is absent") + +def _axis_list(first, second): + edges_a = tuple(_sub_vec(first[(i + 1) % 3], first[i]) for i in range(3)) + edges_b = tuple(_sub_vec(second[(i + 1) % 3], second[i]) for i in range(3)) + normal_a = _cross_vec(_sub_vec(first[1], first[0]), _sub_vec(first[2], first[0])) + normal_b = _cross_vec(_sub_vec(second[1], second[0]), _sub_vec(second[2], second[0])) + return ((normal_a, normal_b) + + tuple(_cross_vec(a, b) for a in edges_a for b in edges_b) + + tuple(_cross_vec(normal_a, edge) for edge in edges_a) + + tuple(_cross_vec(normal_b, edge) for edge in edges_b)) + +def _sat_disjoint(first, second): + for axis in _axis_list(first, second): + length = _norm_vec(axis) + if not math.isfinite(length): + _fail("SAT axis must be finite") + if length <= _FIXED_D: + continue + unit = _normalize_vec(axis, "SAT axis") + projections = tuple(_dot_vec(point, unit) for point in first + second) + if not all(math.isfinite(value) for value in projections): + _fail("SAT projections must be finite") + if _interval_disjoint(min(projections[:3]), max(projections[:3]), + min(projections[3:]), max(projections[3:])): + return True + return False + +def _rational(value): return Fraction(0, 1) if value == 0.0 else Fraction(*value.as_integer_ratio()) +def _ray_difference(first, second): return tuple(_rational(first[i]) - _rational(second[i]) for i in range(3)) + +def _active_solution(rays, subset): + matrix = [[rays[index][row] for index in subset] + [Fraction(0, 1)] + for row in range(3)] + matrix.append([Fraction(1, 1) for _ in subset] + [Fraction(1, 1)]) + for pivot_row, column in enumerate(range(len(subset))): + pivot = next((row for row in range(pivot_row, 4) if matrix[row][column]), None) + if pivot is None: + return None + matrix[pivot_row], matrix[pivot] = matrix[pivot], matrix[pivot_row] + divisor = matrix[pivot_row][column] + matrix[pivot_row] = [value / divisor for value in matrix[pivot_row]] + for row in range(4): + if row != pivot_row and matrix[row][column]: + factor = matrix[row][column] + matrix[row] = [left - factor * right + for left, right in zip(matrix[row], matrix[pivot_row])] + if any(not any(row[:-1]) and row[-1] for row in matrix): + return None + solution = [Fraction(0, 1)] * 4 + for row, column in enumerate(range(len(subset))): + solution[subset[column]] = matrix[row][-1] + if (any(value < 0 for value in solution) + or solution[0] + solution[1] <= 0 + or solution[2] + solution[3] <= 0): + return None + return tuple(solution) + +def shared_one_intersects(shared, a0, a1, b0, b1): + values = tuple(_vec(value, label) for value, label in ( + (shared, "shared point"), (a0, "A0"), (a1, "A1"), (b0, "B0"), (b1, "B1"))) + shared, a0, a1, b0, b1 = values + rays = (_ray_difference(a0, shared), _ray_difference(a1, shared), + _ray_difference(shared, b0), _ray_difference(shared, b1)) + if any(not any(value for value in ray) for ray in rays): + _fail("shared-one classifier received a zero ray") + return any(_active_solution(rays, subset) is not None + for size in (2, 3, 4) + for subset in itertools.combinations(range(4), size)) + +def classify_shared_one(shared, a0, a1, b0, b1): return "hit" if shared_one_intersects(shared, a0, a1, b0, b1) else "point-only" + +def _classify_shared_one_triangles(first, second, points): + shared = next(index for index in first if index in second) + a = [index for index in first if index != shared] + b = [index for index in second if index != shared] + return shared_one_intersects(points[shared], points[a[0]], points[a[1]], + points[b[0]], points[b[1]]) + +def _intersection_inputs(vertices, triangles): + points = _points(vertices) + faces = _indexed_rows(triangles, 3, len(points), "triangles", _MAX_TRIANGLES) + normalized, scale = _normalize_points(points) + for index, face in enumerate(faces): + length = _norm_vec(_triangle_normal(face, normalized)) + if not math.isfinite(length) or length <= _FIXED_D: + _fail(f"normalized triangle normal degeneracy at {index}") + bounds = tuple(_aabb(normalized, face) for face in faces) + return faces, normalized, scale, bounds, tuple(frozenset(face) for face in faces) + +def _aabb_disjoint(first, second): return any(_interval_disjoint(first[i], first[i + 3], second[i], second[i + 3]) for i in range(3)) +def _pair_status(first_index, second_index, faces, normalized, bounds, face_sets): + pair = (first_index, second_index) + common = face_sets[first_index].intersection(face_sets[second_index]) + if len(common) == 3: + _fail(f"duplicate triangle pair {pair}") + if len(common) == 2: + first_edge = _shared_edge_direction(faces[first_index], common) + second_edge = _shared_edge_direction(faces[second_index], common) + if first_edge != (second_edge[1], second_edge[0]): + _fail(f"shared-two edge direction conflict at pair {pair}") + return "excluded-adjacent" + if len(common) == 1: + if normalized is None: + return "shared-one" + hit = _classify_shared_one_triangles(faces[first_index], faces[second_index], normalized) + return "hit" if hit else "point-only" + return "aabb-disjoint" if _aabb_disjoint(bounds[first_index], bounds[second_index]) else "candidate" + +def _append_candidate(result, pair, cap): + if len(result) >= cap: + _fail(f"AABB candidate cap exceeded: >{cap}") + result.append(pair) + +def _collect_candidate_pairs(faces, bounds, face_sets, cap): + cap = _integer(cap, "candidate cap") + if cap <= 0: + _fail("candidate cap must be a positive integer") + result = [] + for first in range(len(faces)): + for second in range(first + 1, len(faces)): + if _pair_status(first, second, faces, None, bounds, face_sets) == "candidate": + _append_candidate(result, (first, second), cap) + return tuple(result) + +def _enumerate_fixture_candidates(vertices, triangles, cap): + """Fixture-only cap injection. Production always uses the fixed cap.""" + faces, _, _, bounds, face_sets = _intersection_inputs(vertices, triangles) + return _collect_candidate_pairs(faces, bounds, face_sets, cap) +def enumerate_broad_phase_candidates(points, triangles): + faces, _, _, bounds, face_sets = _intersection_inputs(points, triangles) + return _collect_candidate_pairs(faces, bounds, face_sets, _MAX_CANDIDATES) + +def intersection_diagnostics(vertices, triangles): + faces, normalized, scale, bounds, face_sets = _intersection_inputs(vertices, triangles) + candidates, hits, classifications = [], [], [] + for first, second in itertools.combinations(range(len(faces)), 2): + pair = (first, second) + stage = _pair_status(first, second, faces, normalized, bounds, face_sets) + if stage == "candidate": + _append_candidate(candidates, pair, _MAX_CANDIDATES) + first_points = tuple(normalized[index] for index in faces[first]) + second_points = tuple(normalized[index] for index in faces[second]) + stage = "hit" if not _sat_disjoint(first_points, second_points) else "sat-disjoint" + if stage == "hit": + hits.append(pair) + classifications.append((pair, stage)) + return { + "triangle_count": len(faces), "normalization_scale": scale, + "broad_phase_candidate_count": len(candidates), "intersection_hit_count": len(hits), + "pair_policy_complete": len(classifications) == len(faces) * (len(faces) - 1) // 2, + "candidate_pairs": tuple(candidates), "hit_pairs": tuple(hits), + "classifications": tuple(classifications), + } + +def validate_geometry(vertices, quads, level, boundary_loops, port_directions, + expected_faces, junction_traces, face_owners): + level = _integer(level, "level") + if level not in _STRUCTURAL_FLOORS: + _fail("level must be 0, 1, or 2") + if any(value is None for value in ( + boundary_loops, port_directions, expected_faces, junction_traces, face_owners)): + _fail("all production geometry selectors and gate data are required") + points = _points(vertices) + faces = _quads(quads, len(points)) + loops = _validate_loops(boundary_loops, len(points)) + if len(loops) != 5: + _fail("exactly 5 boundary loops are required") + topology = _topology_report(len(points), faces, loops, expected_faces) + owners = _face_owners(face_owners, len(faces)) + incidence = _edge_incidence(faces) + edge_lengths = tuple(_norm_vec(_sub_vec(points[b], points[a])) for a, b in incidence) + triangles = tuple((face[0], face[1], face[2]) for face in faces) + tuple( + (face[0], face[2], face[3]) for face in faces) + triangle_areas = tuple(0.5 * _norm_vec(_triangle_normal(face, points)) + for face in triangles) + quad_data = tuple(_quad_data(face, points) for face in faces) + quad_areas = tuple(value[0] for value in quad_data) + if any(not math.isfinite(value) for value in edge_lengths + triangle_areas + quad_areas): + _fail("structural metrics must be finite") + floor = _STRUCTURAL_FLOORS[level] + if (min(edge_lengths) < floor["edge_length"] + or min(triangle_areas) < floor["triangle_area"] + or min(quad_areas) < floor["quad_area"]): + _fail("structural floor failed") + hits = intersection_diagnostics(points, triangles)["hit_pairs"] + if hits: + _fail(f"{len(hits)} triangle intersections, first pair {hits[0]}") + port_directions = _named_mapping(port_directions, "port directions", 5) + if set(port_directions) != set(loops): + _fail("port directions must match boundary loops") + quad_normals = tuple(value[1] for value in quad_data) + normals = _boundary_normals(loops, incidence, quad_normals) + port_metrics = {} + for name in sorted(loops, key=lambda value: value.encode("utf-8")): + port_metrics[name] = validate_port_loop( + points, loops[name], port_directions[name], normals[name]) + fold_count = _run_fold_gates(incidence, owners, quad_normals, level) + traces = _validate_junction_traces(junction_traces) + residuals = [] + for name in traces: + metrics = junction_continuity_metrics(*traces[name]) + residuals.append((name, metrics["coordinate_residual"])) + return { + "topology": topology, "edge_length_min": min(edge_lengths), + "triangle_area_min": min(triangle_areas), "quad_area_min": min(quad_areas), + "intersection_hit_count": 0, "port_count": len(loops), + "port_metrics": port_metrics, "fold_count": fold_count, + "junction_count": len(traces), "junction_residuals": tuple(residuals), + } + +def intersection_candidate_threshold_records(): return tuple(dict(record) for record in _THRESHOLD_RECORDS) +__all__ = [ + "D", "DEGENERACY_FLOOR", "FOLD_LIMITS_DEGREES", "I0", "INTERSECTION_TOLERANCE", + "MAX_CANDIDATES", "MAX_TRIANGLES", "MeshCorrectnessError", "PI", "S", + "STRUCTURAL_FLOORS", "T", "TopologyReport", "add", "classify_shared_one", + "cross", "dot", "enumerate_broad_phase_candidates", "fold_angle_degrees", + "intersection_candidate_threshold_records", "intersection_diagnostics", "interval_disjoint", + "junction_continuity_metrics", + "norm", "normalize", "port_loop_metrics", "shared_one_intersects", "sub", + "validate_fold", "validate_geometry", "validate_port_loop", "validate_topology", +] diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py new file mode 100644 index 0000000..b4d9739 --- /dev/null +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -0,0 +1,556 @@ +from __future__ import annotations + +import hashlib +import os +import sys +import tempfile +import unittest +from unittest import mock +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +import artifact_serialization as artifacts # noqa: E402 + + +class CanonicalArtifactTests(unittest.TestCase): + def test_canonical_json_is_compact_utf8_and_has_no_trailing_lf(self) -> None: + value = {"z": "é", "a": [1, True], "nested": {"b": 2, "a": 1}} + self.assertEqual( + artifacts.canonical_json_bytes(value), + b'{"a":[1,true],"nested":{"a":1,"b":2},"z":"\xc3\xa9"}', + ) + + def test_binary64_zeros_have_one_wire_spelling_and_nonfinite_values_fail(self) -> None: + self.assertEqual( + artifacts.canonical_json_bytes({"positive": 0.0, "negative": -0.0}), + b'{"negative":0,"positive":0}', + ) + for value in (float("nan"), float("inf"), float("-inf")): + with self.subTest(value=value), self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.canonical_json_bytes({"value": value}) + + def test_coordinate_and_triangle_hash_domains_are_exact(self) -> None: + coordinates = ((1.0, -0.0, 2.5),) + triangles = ((0, 1, 2), (-1, 4, 8)) + expected_coordinates = b"".join( + value.to_bytes(8, "little", signed=False) + for value in (0x3FF0000000000000, 0x8000000000000000, 0x4004000000000000) + ) + self.assertEqual(artifacts.coordinate_hash_bytes(coordinates), expected_coordinates) + expected_triangles = b"".join( + int(value).to_bytes(8, "little", signed=True) + for row in triangles + for value in row + ) + self.assertEqual(artifacts.triangle_index_hash_bytes(triangles), expected_triangles) + self.assertEqual( + artifacts.sha256_bytes(artifacts.coordinate_hash_bytes(coordinates)), + hashlib.sha256(expected_coordinates).hexdigest(), + ) + + def test_canonical_decode_rejects_duplicates_and_noncanonical_bytes(self) -> None: + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.decode_canonical_json(b'{"a":1,"a":2}') + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.decode_canonical_json(b'{"a": 1}') + self.assertEqual(artifacts.decode_canonical_json(b'{"a":0}'), {"a": 0}) + self.assertEqual(artifacts.coerce_binary64(0), 0.0) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.coerce_binary64(1) + + +class FileAdmissionTests(unittest.TestCase): + def test_regular_file_record_hashes_exact_bytes_and_rejects_symlinks(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / "payload.bin" + payload.write_bytes(b"payload") + record = artifacts.regular_file_record(payload, "seed/payload.bin") + self.assertEqual(record["bytes"], 7) + self.assertEqual(record["sha256"], hashlib.sha256(b"payload").hexdigest()) + self.assertEqual(artifacts.regular_file_record(payload, "seed/payload.bin"), record) + link = root / "link" + link.symlink_to(payload) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.regular_file_record(link, "seed/link") + hardlink = root / "hardlink" + os.link(payload, hardlink) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.regular_file_record(payload, "seed/payload.bin") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.validate_role_path("../payload.bin") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.regular_file_record(payload, "") + + def test_sidecar_is_exact_one_lf_terminated_line(self) -> None: + digest = hashlib.sha256(b"contract").hexdigest() + expected = f"{digest} {artifacts.CONTRACT_ROLE}\n".encode("ascii") + self.assertEqual(artifacts.contract_sidecar_bytes(digest), expected) + artifacts.validate_contract_sidecar(expected, digest) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.validate_contract_sidecar(expected + b"\n", digest) + with self.assertRaises(TypeError): + artifacts.contract_sidecar_bytes(digest, contract_role="alternate") + with self.assertRaises(TypeError): + artifacts.validate_contract_sidecar( + expected, digest, contract_role="alternate" + ) + with tempfile.TemporaryDirectory() as directory: + sidecar = Path(directory) / "design-contract.sha256" + self.assertEqual( + artifacts.write_contract_sidecar_no_replace(sidecar, digest), sidecar + ) + self.assertEqual(sidecar.read_bytes(), expected) + with self.assertRaises(TypeError): + artifacts.write_contract_sidecar_no_replace( + Path(directory) / "alternate.sha256", + digest, + contract_role="alternate", + ) + + def test_closed_inventory_requires_exact_regular_file_set(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "a").write_bytes(b"a") + (root / "nested").mkdir() + (root / "nested" / "b").write_bytes(b"b") + records = artifacts.closed_inventory(root, ("a", "nested/b")) + self.assertEqual(tuple(record["role_path"] for record in records), ("a", "nested/b")) + (root / "extra").write_bytes(b"extra") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("a", "nested/b")) + + def test_closed_inventory_rejects_hardlinked_file(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / "payload" + alias = root / "alias" + payload.write_bytes(b"payload") + os.link(payload, alias) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("payload",)) + + def test_closed_inventory_rejects_unexpected_directory_and_symlink(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "a").write_bytes(b"a") + (root / "empty").mkdir() + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("a",)) + (root / "empty").rmdir() + (root / "link").symlink_to(root / "a") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("a",)) + + def test_closed_inventory_rejects_deterministic_insertion_and_removal(self) -> None: + for operation in ("insert", "remove"): + with self.subTest(operation=operation), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / "payload" + payload.write_bytes(b"payload") + original_listdir = artifacts.os.listdir + calls = 0 + + def listdir(path): + nonlocal calls + names = original_listdir(path) + if isinstance(path, int) and calls == 0: + calls += 1 + if operation == "insert": + (root / "inserted").write_bytes(b"race") + else: + payload.unlink() + return names + + with mock.patch.object(artifacts.os, "listdir", side_effect=listdir): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("payload",)) + + def test_closed_inventory_rejects_deterministic_same_name_replacement(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / "payload" + payload.write_bytes(b"original") + moved = root / "moved" + original_pread = artifacts.os.pread + replaced = False + + def pread(fd, count, offset): + nonlocal replaced + data = original_pread(fd, count, offset) + if data and not replaced: + replaced = True + payload.rename(moved) + payload.write_bytes(b"replacement") + return data + + with mock.patch.object(artifacts.os, "pread", side_effect=pread): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("payload",)) + + def test_closed_inventory_rejects_expected_nested_directory_replacement(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + nested = root / "nested" + nested.mkdir() + (nested / "payload").write_bytes(b"original") + moved = root / "nested-moved" + original_stat = artifacts.os.stat + replaced = False + + def stat(path, *args, **kwargs): + nonlocal replaced + result = original_stat(path, *args, **kwargs) + if path == "nested" and kwargs.get("dir_fd") is not None and not replaced: + replaced = True + nested.rename(moved) + nested.mkdir() + (nested / "payload").write_bytes(b"replacement") + return result + + with mock.patch.object(artifacts.os, "stat", side_effect=stat): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(root, ("nested/payload",)) + + def test_regular_file_read_rejects_real_same_size_pwrite_between_chunks(self) -> None: + with tempfile.TemporaryDirectory() as directory: + payload = Path(directory) / "payload" + chunk_size = 1024 * 1024 + payload.write_bytes(b"a" * (chunk_size * 2)) + writer_fd = os.open(payload, os.O_WRONLY) + original_pread = artifacts.os.pread + mutated = False + + def pread(fd, count, offset): + nonlocal mutated + data = original_pread(fd, count, offset) + if offset == 0 and data and not mutated: + mutated = True + self.assertEqual(os.pwrite(writer_fd, b"b", chunk_size), 1) + return data + + try: + with mock.patch.object(artifacts.os, "pread", side_effect=pread): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.read_regular_file(payload) + finally: + os.close(writer_fd) + + def test_regular_file_read_rechecks_requested_path_identity(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / "payload" + moved = root / "moved" + payload.write_bytes(b"original") + original_read = artifacts._read_stable_with_identity + + def read_then_replace(parent_fd, name, max_bytes): + result = original_read(parent_fd, name, max_bytes) + payload.rename(moved) + payload.write_bytes(b"replacement") + return result + + with mock.patch.object(artifacts, "_read_stable_with_identity", + side_effect=read_then_replace): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.read_regular_file(payload) + + def test_regular_file_read_rejects_deterministic_same_size_mutation(self) -> None: + with tempfile.TemporaryDirectory() as directory: + payload = Path(directory) / "payload" + payload.write_bytes(b"original") + original_pread = artifacts.os.pread + mutated = False + + def pread(fd, count, offset): + nonlocal mutated + data = original_pread(fd, count, offset) + if data and not mutated: + mutated = True + payload.write_bytes(b"mutated!") + return data + + with mock.patch.object(artifacts.os, "pread", side_effect=pread): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.read_regular_file(payload) + + +class PublicationTests(unittest.TestCase): + def test_atomic_json_write_and_no_replace_preserve_existing_target(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + target = root / "artifact.json" + artifacts.write_canonical_json_no_replace(target, {"ok": True}) + self.assertEqual(target.read_bytes(), b'{"ok":true}') + with self.assertRaises(FileExistsError): + artifacts.write_canonical_json_no_replace(target, {"ok": False}) + self.assertEqual(target.read_bytes(), b'{"ok":true}') + self.assertEqual( + [path.name for path in root.iterdir()], + ["artifact.json"], + ) + + def test_directory_publication_is_atomic_and_no_replace(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / ".bundle.stage" + target = root / "bundle" + stage.mkdir() + (stage / "payload").write_bytes(b"new") + self.assertEqual(artifacts.publish_no_replace(stage, target), target) + self.assertEqual((target / "payload").read_bytes(), b"new") + second = root / ".second.stage" + second.mkdir() + (second / "payload").write_bytes(b"replacement") + with self.assertRaises(FileExistsError): + artifacts.publish_no_replace(second, target) + self.assertEqual((target / "payload").read_bytes(), b"new") + + def test_publication_rejects_hardlinked_staging_file(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + alias = root / "alias" + target = root / "target" + stage.write_bytes(b"staged") + os.link(stage, alias) + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual(stage.read_bytes(), b"staged") + self.assertEqual(alias.read_bytes(), b"staged") + + def test_parent_fsync_failure_rolls_exact_file_back_to_stage(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + stage.write_bytes(b"staged") + + def fail_fsync(_descriptor): + raise OSError("injected parent fsync failure") + + with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): + with self.assertRaisesRegex(OSError, "injected parent fsync failure"): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual(stage.read_bytes(), b"staged") + + def test_published_hardlink_is_rejected_and_alias_is_preserved(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + alias = root / "alias" + stage.write_bytes(b"staged") + + def hardlink_then_fail(_descriptor): + os.link(target, alias) + raise OSError("injected parent fsync failure") + + with mock.patch.object(artifacts.os, "fsync", side_effect=hardlink_then_fail): + with self.assertRaisesRegex(OSError, "injected parent fsync failure"): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual(stage.read_bytes(), b"staged") + self.assertEqual(alias.read_bytes(), b"staged") + + def test_directory_fsync_failure_rolls_back_whole_directory(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + stage.mkdir() + (stage / "payload").write_bytes(b"staged") + + def fail_fsync(_descriptor): + raise OSError("injected parent fsync failure") + + with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): + with self.assertRaisesRegex(OSError, "injected parent fsync failure"): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual((stage / "payload").read_bytes(), b"staged") + + def test_directory_mutation_is_rolled_back_without_recursive_deletion(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + stage.mkdir() + (stage / "payload").write_bytes(b"staged") + + def mutate_then_fail(_descriptor): + (target / "payload").write_bytes(b"mutated") + (target / "added").write_bytes(b"preserved") + raise OSError("injected parent fsync failure") + + with mock.patch.object(artifacts.os, "unlink", + side_effect=AssertionError("must not unlink")): + with mock.patch.object(artifacts.os, "rmdir", + side_effect=AssertionError("must not rmdir")): + with mock.patch.object(artifacts.os, "fsync", + side_effect=mutate_then_fail): + with self.assertRaisesRegex( + OSError, "injected parent fsync failure"): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual((stage / "payload").read_bytes(), b"mutated") + self.assertEqual((stage / "added").read_bytes(), b"preserved") + + def test_parent_fsync_failure_preserves_replaced_target(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + replacement = root / "replacement" + stage.write_bytes(b"staged") + replacement.write_bytes(b"unrelated") + + published_original = root / "published-original" + original_rename = artifacts._rename_no_replace + rename_calls = 0 + + def fail_fsync(_descriptor): + raise OSError("injected parent fsync failure") + + def replace_before_rollback(parent_fd, source, destination): + nonlocal rename_calls + rename_calls += 1 + if rename_calls == 2: + target.rename(published_original) + replacement.rename(target) + original_rename(parent_fd, source, destination) + + with mock.patch.object(artifacts, "_rename_no_replace", + side_effect=replace_before_rollback): + with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.publish_no_replace(stage, target) + self.assertEqual(target.read_bytes(), b"unrelated") + self.assertEqual(published_original.read_bytes(), b"staged") + self.assertFalse(any(path.name.startswith(".rollback-") + for path in root.iterdir())) + + def test_parent_fsync_failure_preserves_replaced_source(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + stage.write_bytes(b"staged") + + def occupy_source_then_fail(_descriptor): + stage.write_bytes(b"unrelated") + raise OSError("injected parent fsync failure") + + with mock.patch.object(artifacts.os, "fsync", + side_effect=occupy_source_then_fail): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.publish_no_replace(stage, target) + self.assertFalse(target.exists()) + self.assertEqual(stage.read_bytes(), b"unrelated") + quarantined = [path for path in root.iterdir() + if path.name.startswith(".rollback-")] + self.assertEqual(len(quarantined), 1) + self.assertEqual(quarantined[0].read_bytes(), b"staged") + + def test_failed_temporary_write_does_not_delete_replacement(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + target = root / "target" + original_temporary_file = artifacts._temporary_file + temporary_path = None + + def capture_temporary(parent_fd, target_name): + nonlocal temporary_path + descriptor, name = original_temporary_file(parent_fd, target_name) + temporary_path = root / name + return descriptor, name + + def replace_temporary_then_fail(_descriptor): + assert temporary_path is not None + temporary_path.unlink() + temporary_path.write_bytes(b"unrelated") + raise OSError("injected temporary fsync failure") + + with mock.patch.object(artifacts, "_temporary_file", + side_effect=capture_temporary): + with mock.patch.object(artifacts.os, "fsync", + side_effect=replace_temporary_then_fail): + with self.assertRaisesRegex( + OSError, "injected temporary fsync failure"): + artifacts.write_bytes_no_replace(target, b"staged") + self.assertFalse(target.exists()) + self.assertIsNotNone(temporary_path) + self.assertEqual(temporary_path.read_bytes(), b"unrelated") + + def test_source_to_symlink_race_fails_without_following_victim(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stage = root / "stage" + target = root / "target" + victim = root / "victim" + stage.write_bytes(b"staged") + victim.write_bytes(b"must remain") + original_rename = artifacts._rename_no_replace + replaced = False + + def replace_source_then_rename(parent_fd, source, destination): + nonlocal replaced + if not replaced: + replaced = True + os.unlink(source, dir_fd=parent_fd) + os.symlink(victim.name, source, dir_fd=parent_fd) + original_rename(parent_fd, source, destination) + + with mock.patch.object(artifacts, "_rename_no_replace", + side_effect=replace_source_then_rename): + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.publish_no_replace(stage, target) + self.assertTrue(target.is_symlink()) + self.assertEqual(victim.read_bytes(), b"must remain") + + def test_write_temp_and_publish_stay_on_held_parent_after_replacement(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / "parent" + root.mkdir() + moved = Path(directory) / "parent-moved" + original_temporary_file = artifacts._temporary_file + + def replace_parent_then_create(parent_fd, target_name): + root.rename(moved) + root.mkdir() + return original_temporary_file(parent_fd, target_name) + + with mock.patch.object(artifacts, "_temporary_file", side_effect=replace_parent_then_create): + artifacts.write_bytes_no_replace(root / "artifact", b"held") + self.assertEqual((moved / "artifact").read_bytes(), b"held") + self.assertFalse((root / "artifact").exists()) + + def test_post_publication_verification_stays_on_held_parent(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / "parent" + root.mkdir() + stage = root / "stage" + stage.mkdir() + (stage / "payload").write_bytes(b"held") + target = root / "bundle" + moved = Path(directory) / "parent-moved" + original_rename = artifacts._rename_no_replace + + def rename_then_replace_parent(parent_fd, source, destination): + original_rename(parent_fd, source, destination) + root.rename(moved) + root.mkdir() + + with mock.patch.object(artifacts, "_rename_no_replace", side_effect=rename_then_replace_parent): + artifacts.publish_no_replace(stage, target) + self.assertEqual((moved / "bundle" / "payload").read_bytes(), b"held") + self.assertFalse((root / "bundle").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py new file mode 100644 index 0000000..aa39eee --- /dev/null +++ b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py @@ -0,0 +1,562 @@ +from __future__ import annotations + +import math +from pathlib import Path +import sys +import unittest + + +PACKAGE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(PACKAGE)) +import mesh_correctness as mesh # noqa: E402 + + +P0 = float.fromhex("0x0.0p+0") +N0 = -P0 +ONE = float.fromhex("0x1.0000000000000p+0") +HALF = float.fromhex("0x1.0000000000000p-1") +D50 = float.fromhex("0x1.0000000000000p-50") +MIN_SUBNORMAL = float.fromhex("0x0.0000000000001p-1022") +D = float.fromhex("0x1.0000000000000p-46") +I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") + + +def _pair(a_points, b_points): + points = tuple(a_points) + tuple(b_points) + return points, ((0, 1, 2), (3, 4, 5)) + + +def _shared_base(b0=(ONE, P0, P0), b1=(P0, ONE, P0)): + shared = (P0, P0, P0) + a0 = (ONE, P0, P0) + a1 = (P0, ONE, P0) + return [shared, a0, a1], [shared, b0, b1] + + +def _transform(point, scale, translation): + return tuple(float(float(scale * value) + offset) for value, offset in zip(point, translation)) + + +def _negative_zero(point): + return tuple(math.copysign(0.0, -1.0) if value == 0.0 else value for value in point) + + +class _CoercibleFloat: + def __float__(self): + return 1.0 + + +class _ListSubclass(list): + pass + + +def _fixture_shared_one(): + return ( + ("shared1.offset-d50-point-only", (ONE, P0, D50), (P0, ONE, D50), "point-only"), + ("shared1.coplanar-duplicate-hit", (ONE, P0, P0), (P0, ONE, P0), "hit"), + ("shared1.offset-positive-minsub-point-only", (ONE, P0, MIN_SUBNORMAL), (P0, ONE, MIN_SUBNORMAL), "point-only"), + ("shared1.offset-negative-minsub-point-only", (ONE, P0, -MIN_SUBNORMAL), (P0, ONE, -MIN_SUBNORMAL), "point-only"), + ("shared1.coplanar-disjoint-fans", (-ONE, P0, P0), (P0, -ONE, P0), "point-only"), + ("shared1.ray-cone-hit", (ONE, ONE, P0), (P0, P0, ONE), "hit"), + ("shared1.near-coplanar-full-rank-hit", (ONE, P0, D50), (P0, ONE, -D50), "hit"), + ("shared1.transformed-point-only", (ONE, P0, D50), (P0, ONE, D50), "point-only"), + ("shared1.transformed-hit", (ONE, P0, D50), (P0, ONE, -D50), "hit"), + ("shared1.negative-zero-hit", (ONE, P0, P0), (P0, ONE, P0), "hit"), + ("shared1.level2-ply-point-only", + (float.fromhex("0x1.37918e2798bb6p-8"), float.fromhex("0x1.61bcdab8dcc06p-4"), float.fromhex("0x1.43c9e5ce2aeb6p-4")), + (float.fromhex("0x1.7bc42ac7f04b0p-7"), float.fromhex("0x1.6cae8c4686bb2p-4"), float.fromhex("0x1.0be935f6a339ep-4")), + "point-only"), + ) + + +_CUBE_DIRECTIONS = ( + (1, 0, 0), (-1, 0, 0), (0, 1, 0), + (0, -1, 0), (0, 0, 1), (0, 0, -1), +) + + +def _face_corners(cube, direction): + x, y, z = cube + if direction == (1, 0, 0): + return ((x + 1, y, z), (x + 1, y + 1, z), + (x + 1, y + 1, z + 1), (x + 1, y, z + 1)) + if direction == (-1, 0, 0): + return ((x, y, z), (x, y, z + 1), + (x, y + 1, z + 1), (x, y + 1, z)) + if direction == (0, 1, 0): + return ((x, y + 1, z), (x, y + 1, z + 1), + (x + 1, y + 1, z + 1), (x + 1, y + 1, z)) + if direction == (0, -1, 0): + return ((x, y, z), (x + 1, y, z), + (x + 1, y, z + 1), (x, y, z + 1)) + if direction == (0, 0, 1): + return ((x, y, z + 1), (x + 1, y, z + 1), + (x + 1, y + 1, z + 1), (x, y + 1, z + 1)) + return ((x, y, z), (x, y + 1, z), + (x + 1, y + 1, z), (x + 1, y, z)) + + +def _integrated_fixture(): + occupied = {(x, y, z) for x in range(3) for y in range(3) for z in range(3)} + arms = { + "port.0": (((3, 1, 1), (4, 1, 1)), (1, 0, 0)), + "port.1": (((-1, 1, 1), (-2, 1, 1)), (-1, 0, 0)), + "port.2": (((1, 3, 1), (1, 4, 1)), (0, 1, 0)), + "port.3": (((1, -1, 1), (1, -2, 1)), (0, -1, 0)), + "port.4": (((1, 1, 3), (1, 1, 4)), (0, 0, 1)), + } + omitted = {} + for name, (cubes, direction) in arms.items(): + occupied.update(cubes) + omitted[(cubes[-1], direction)] = name + + coordinates = [] + vertex_ids = {} + faces = [] + metadata = [] + port_corners = {} + + def vertex_id(corner): + if corner not in vertex_ids: + vertex_ids[corner] = len(coordinates) + coordinates.append(tuple(float(value) for value in corner)) + return vertex_ids[corner] + + for cube in sorted(occupied): + for direction in _CUBE_DIRECTIONS: + neighbour = tuple(cube[axis] + direction[axis] for axis in range(3)) + if neighbour in occupied: + continue + corners = _face_corners(cube, direction) + port_name = omitted.get((cube, direction)) + if port_name is not None: + port_corners[port_name] = corners + continue + faces.append(tuple(vertex_id(corner) for corner in corners)) + metadata.append((cube, direction)) + + loops = { + name: tuple(vertex_ids[corner] for corner in reversed(port_corners[name])) + for name in sorted(port_corners) + } + directions = { + name: tuple(float(value) for value in arms[name][1]) + for name in sorted(arms) + } + owners = ["surface"] * len(faces) + owners[metadata.index(((1, 1, 0), (0, 0, -1)))] = "flat-seam" + trace = ( + ("sample.0", (0.0, 0.0, 0.0)), + ("sample.1", (1.0, 0.0, 0.0)), + ("sample.2", (1.0, 1.0, 0.0)), + ) + traces = { + f"junction.{index}": (trace, tuple(reversed(trace))) + for index in range(7) + } + inputs = { + "vertices": tuple(coordinates), + "quads": tuple(faces), + "level": 0, + "boundary_loops": loops, + "port_directions": directions, + "expected_faces": tuple(faces), + "junction_traces": traces, + "face_owners": tuple(owners), + } + return inputs, tuple(metadata), vertex_ids + + +class PrimitiveTests(unittest.TestCase): + def test_interval_disjoint_uses_both_subtractions_and_one_tolerance(self): + just_abutting = math.nextafter(I0, math.inf) + self.assertFalse(mesh.interval_disjoint(P0, P0, I0, I0)) + self.assertTrue(mesh.interval_disjoint(P0, P0, just_abutting, just_abutting)) + self.assertFalse(mesh.interval_disjoint(P0, P0, I0, math.nextafter(I0, math.inf))) + + def test_shared_one_classifier_is_exact_and_swap_invariant(self): + for name, b0, b1, expected in _fixture_shared_one()[:7]: + with self.subTest(name=name): + first, second = _shared_base(b0, b1) + shared, a0, a1 = first + _, bb0, bb1 = second + self.assertEqual(mesh.classify_shared_one(shared, a0, a1, bb0, bb1), expected) + self.assertEqual(mesh.classify_shared_one(shared, a1, a0, bb0, bb1), expected) + self.assertEqual(mesh.classify_shared_one(shared, a0, a1, bb1, bb0), expected) + self.assertEqual(mesh.classify_shared_one(shared, bb0, bb1, a0, a1), expected) + + def test_shared_one_rejects_zero_ray(self): + with self.assertRaisesRegex(ValueError, "zero ray"): + mesh.shared_one_intersects((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), + (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (0.0, 0.0, 1.0)) + + def test_coordinate_and_scalar_admission_is_exact_python_float(self): + for value in (1, "1", True, _CoercibleFloat()): + with self.subTest(value=type(value).__name__): + with self.assertRaisesRegex(ValueError, "finite binary64"): + mesh.interval_disjoint(value, 0.0, 2.0, 3.0) + for value in (1, "1", True, _CoercibleFloat()): + with self.subTest(vector_value=type(value).__name__): + with self.assertRaisesRegex(ValueError, "finite binary64"): + mesh.norm((value, 0.0, 0.0)) + + def test_rows_require_exact_bounded_sequences_before_traversal(self): + points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + + def exploding_generator(): + raise AssertionError("generator was traversed") + yield (0, 1, 2) + + for rows in ({0: (0, 1, 2)}, {(0, 1, 2)}, range(1), + _ListSubclass([(0, 1, 2)]), exploding_generator()): + with self.subTest(rows=type(rows).__name__): + with self.assertRaisesRegex(ValueError, "exact list or tuple"): + mesh.intersection_diagnostics(points, rows) + for row in ({0: 0, 1: 1, 2: 2}, {0, 1, 2}, range(3), + exploding_generator()): + with self.subTest(row=type(row).__name__): + with self.assertRaisesRegex(ValueError, "exact list or tuple"): + mesh.intersection_diagnostics(points, (row,)) + with self.assertRaisesRegex(ValueError, "triangle cap"): + mesh.intersection_diagnostics(points, [object()] * 4097) + with self.assertRaisesRegex(ValueError, "quad cap"): + mesh.validate_topology(4, [object()] * 2049) + + +class TopologyGeometryTests(unittest.TestCase): + def setUp(self): + self.points = ( + (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), + (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0), + ) + self.faces = ( + (0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), + (1, 2, 6, 5), (3, 7, 6, 2), (0, 4, 7, 3), + ) + + def test_closed_box_has_valid_topology_and_geometry(self): + report = mesh.validate_topology(len(self.points), self.faces) + self.assertEqual((report.edge_count, report.boundary_edge_count, report.euler), (12, 0, 2)) + with self.assertRaises(TypeError): + mesh.validate_geometry(self.points, self.faces) + + def test_topology_rejects_same_direction_edge_and_unused_control(self): + bad = list(self.faces) + bad[1] = tuple(reversed(bad[1])) + with self.assertRaisesRegex(ValueError, "orientation conflict"): + mesh.validate_topology(8, bad) + with self.assertRaisesRegex(ValueError, "unused vertex"): + mesh.validate_topology(9, self.faces) + + def test_topology_rejects_duplicate_and_reversed_duplicate_quads(self): + duplicates = (self.faces[0], tuple(reversed(self.faces[0])), + self.faces[0][1:] + self.faces[0][:1]) + for duplicate in duplicates: + with self.subTest(duplicate=duplicate): + with self.assertRaisesRegex(ValueError, "duplicate quad"): + mesh.validate_topology(8, self.faces + (duplicate,)) + + def test_clearance_semantics_are_owned_by_anatomy(self): + self.assertFalse(hasattr(mesh, "boundary_clearance_ratios")) + self.assertFalse(hasattr(mesh, "validate_boundary_clearances")) + self.assertNotIn("boundary_clearance_ratios", mesh.__all__) + + def test_port_continuity_and_fold_are_independent(self): + loop_points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (1.0, 0.0, 1.0), (0.0, 0.0, 1.0)) + adjacent = ((0.0, 0.0, -1.0), (1.0, 0.0, 0.0), + (0.0, 0.0, 1.0), (-1.0, 0.0, 0.0)) + metrics = mesh.validate_port_loop(loop_points, (0, 1, 2, 3), + (0.0, 1.0, 0.0), adjacent) + self.assertEqual(metrics["orientation"], 1.0) + self.assertEqual(metrics["co_normal"], 1.0) + traces = ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))) + reverse = tuple(reversed(traces)) + self.assertTrue(mesh.junction_continuity_metrics(traces, reverse)["opposite_trace_direction"]) + self.assertLess(mesh.validate_fold((1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 0), 90.0) + with self.assertRaisesRegex(ValueError, "co-normal"): + mesh.validate_port_loop(loop_points, (0, 1, 2, 3), + (0.0, 1.0, 0.0), + tuple((0.0, 0.0, 1.0) for _ in range(4))) + + def test_port_winding_and_continuity_fail_closed(self): + with self.assertRaisesRegex(ValueError, "orientation"): + mesh.validate_port_loop(((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (1.0, 0.0, 1.0), (0.0, 0.0, 1.0)), + (0, 3, 2, 1), (0.0, 1.0, 0.0), + ((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), + (-1.0, 0.0, 0.0), (0.0, 0.0, 1.0))) + with self.assertRaisesRegex(ValueError, "directions"): + mesh.junction_continuity_metrics( + ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))), + ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))), + ) + + def test_contract_threshold_and_normalization_knobs_are_not_public(self): + loop_points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (1.0, 0.0, 1.0), (0.0, 0.0, 1.0)) + with self.assertRaises(TypeError): + mesh.validate_port_loop(loop_points, (0, 1, 2, 3), + (0.0, 1.0, 0.0)) + with self.assertRaisesRegex(ValueError, "exact list or tuple"): + mesh.port_loop_metrics(loop_points, (0, 1, 2, 3), + (0.0, 1.0, 0.0), None) + self.assertFalse(hasattr(mesh, "validate_junction_continuity")) + triangles = ((0, 1, 2),) + points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + with self.assertRaises(TypeError): + mesh.intersection_diagnostics(points, triangles, scale=1.0) + with self.assertRaises(TypeError): + mesh.enumerate_broad_phase_candidates(points, triangles, cap=3) + with self.assertRaisesRegex(ValueError, "below"): + mesh.validate_fold((1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 2) + + def test_production_geometry_requires_all_selectors_and_gate_data(self): + with self.assertRaises(TypeError): + mesh.validate_geometry(self.points, self.faces) + with self.assertRaisesRegex(ValueError, "required"): + mesh.validate_geometry(self.points, self.faces, 0, None, None, None, None, None) + + +class IntegratedGeometryTests(unittest.TestCase): + def setUp(self): + self.inputs, self.metadata, self.vertex_ids = _integrated_fixture() + + def _validate(self, **changes): + return mesh.validate_geometry(**{**self.inputs, **changes}) + + def test_success_runs_every_mandatory_production_gate(self): + report = self._validate() + floor = mesh.STRUCTURAL_FLOORS[0] + self.assertEqual(report["topology"].boundary_components, 5) + self.assertEqual(report["intersection_hit_count"], 0) + self.assertEqual(report["port_count"], 5) + self.assertEqual(set(report["port_metrics"]), set(self.inputs["boundary_loops"])) + self.assertTrue(all(metrics["co_normal"] >= 0.80 + for metrics in report["port_metrics"].values())) + self.assertEqual(report["fold_count"], 4) + self.assertEqual(report["junction_count"], 7) + self.assertEqual(report["junction_residuals"], tuple( + (f"junction.{index}", 0.0) for index in range(7))) + self.assertGreaterEqual(report["edge_length_min"], floor["edge_length"]) + self.assertGreaterEqual(report["triangle_area_min"], floor["triangle_area"]) + self.assertGreaterEqual(report["quad_area_min"], floor["quad_area"]) + + def test_topology_and_exact_five_port_gates_fail_in_production(self): + faces = list(self.inputs["quads"]) + faces[0] = tuple(reversed(faces[0])) + with self.assertRaisesRegex(ValueError, "orientation conflict"): + self._validate(quads=tuple(faces), expected_faces=tuple(faces)) + + loops = dict(self.inputs["boundary_loops"]) + loops.pop("port.4") + directions = dict(self.inputs["port_directions"]) + directions.pop("port.4") + with self.assertRaisesRegex(ValueError, "exactly 5 boundary loops"): + self._validate(boundary_loops=loops, port_directions=directions) + + def test_structural_intersection_conormal_and_fold_gates_fail_in_production(self): + scaled = tuple(tuple(0.01 * value for value in point) + for point in self.inputs["vertices"]) + with self.assertRaisesRegex(ValueError, "structural floor"): + self._validate(vertices=scaled) + + crossed = list(self.inputs["vertices"]) + crossed[self.vertex_ids[(5, 1, 1)]] = (-3.0, 1.0, 1.0) + with self.assertRaisesRegex(ValueError, "triangle intersections"): + self._validate(vertices=tuple(crossed)) + + flared = list(self.inputs["vertices"]) + replacements = { + (4, 1, 1): (4.0, 0.0, 0.0), + (4, 2, 1): (4.0, 3.0, 0.0), + (4, 2, 2): (4.0, 3.0, 3.0), + (4, 1, 2): (4.0, 0.0, 3.0), + } + for corner, point in replacements.items(): + flared[self.vertex_ids[corner]] = point + with self.assertRaisesRegex(ValueError, "co-normal"): + self._validate(vertices=tuple(flared)) + + owners = list(self.inputs["face_owners"]) + owners[self.metadata.index(((0, 0, 0), (0, 0, -1)))] = "sharp-seam" + with self.assertRaisesRegex(ValueError, "fold angle"): + self._validate(face_owners=tuple(owners)) + + def test_each_of_seven_junction_residuals_fails_in_production(self): + for name in sorted(self.inputs["junction_traces"]): + with self.subTest(name=name): + traces = dict(self.inputs["junction_traces"]) + first, second = traces[name] + bad_second = list(second) + tag, _ = bad_second[0] + bad_second[0] = (tag, (2.0, 2.0, 2.0)) + traces[name] = (first, tuple(bad_second)) + with self.assertRaisesRegex(ValueError, "coordinate residual"): + self._validate(junction_traces=traces) + + +class ProductionIntersectionFixtureTests(unittest.TestCase): + def _assert_pair(self, name, points_a, points_b, expected, stage): + points, triangles = _pair(points_a, points_b) + report = mesh.intersection_diagnostics(points, triangles) + self.assertTrue(report["pair_policy_complete"], name) + self.assertEqual(report["classifications"], (((0, 1), stage),), name) + actual = "hit" if report["intersection_hit_count"] else "point-only" + self.assertEqual(actual, expected, name) + + def test_contract_fixture_matrix(self): + executions = 0 + self.assertEqual(mesh.MAX_CANDIDATES, 1_000_000) + self.assertEqual( + mesh.intersection_candidate_threshold_records(), + tuple( + { + "threshold_id": f"threshold.intersection.L{level}.broad_phase_candidate_count", + "relation": "le", + "lower": None, + "upper": 1_000_000, + "unit": "count", + } + for level in range(3) + ), + ) + for name, b0, b1, expected in _fixture_shared_one(): + if name == "shared1.level2-ply-point-only": + shared = (float.fromhex("0x1.8b59f7e4bf4dfp-7"), float.fromhex("0x1.0a35e0636f7c1p-4"), float.fromhex("0x1.264d28c7c3da4p-4")) + first = [shared, b0, b1] + second = [shared, + (float.fromhex("0x1.7888e87a16156p-6"), float.fromhex("0x1.7eec0987f75cdp-4"), float.fromhex("0x1.d5d88ce274e30p-5")), + (float.fromhex("0x1.8b59f7e4bf4dfp-6"), float.fromhex("0x1.18982604f83a1p-4"), float.fromhex("0x1.07df2315527a3p-4"))] + else: + first, second = _shared_base(b0, b1) + if name == "shared1.transformed-point-only" or name == "shared1.transformed-hit": + translation = (4.0, -2.0, 1.0) + first = [_transform(point, 8.0, translation) for point in first] + second = [_transform(point, 8.0, translation) for point in second] + if name == "shared1.negative-zero-hit": + first = [_negative_zero(point) for point in first] + second = [_negative_zero(point) for point in second] + base_points = tuple(first) + tuple(second[1:]) + base_triangles = ((0, 1, 2), (0, 3, 4)) + for suffix in ("p000", "p001", "p010", "p011", "p100", "p101", "p110", "p111"): + a = list(base_triangles[0]) + b = list(base_triangles[1]) + if suffix[1] == "1": + a, b = b, a + if suffix[2] == "1": + a[1], a[2] = a[2], a[1] + if suffix[3] == "1": + b[1], b[2] = b[2], b[1] + report = mesh.intersection_diagnostics(base_points, (tuple(a), tuple(b))) + self.assertTrue(report["pair_policy_complete"], f"{name}.{suffix}") + self.assertEqual(report["classifications"], (((0, 1), expected),), f"{name}.{suffix}") + actual = "hit" if report["intersection_hit_count"] else "point-only" + self.assertEqual(actual, expected, f"{name}.{suffix}") + executions += 1 + + general = ( + ("shared0.clear-hit-origin", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + ((0.0, -1.0, 0.0), (HALF, HALF, 0.0), (-HALF, HALF, 0.0)), "hit"), + ("shared0.clear-hit-translated", ((4.0, -2.0, 1.0), (5.0, -2.0, 1.0), (4.0, -1.0, 1.0)), + ((4.0, -3.0, 1.0), (4.5, -1.5, 1.0), (3.5, -1.5, 1.0)), "hit"), + ("shared0.sub-I0-contact-origin", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + ((0.0, 0.0, float.fromhex("0x1.0000000000000p-34")), (1.0, 0.0, float.fromhex("0x1.0000000000000p-34")), (0.0, 1.0, float.fromhex("0x1.0000000000000p-34"))), "hit"), + ("shared0.sub-I0-contact-translated", ((4.0, -2.0, 1.0), (5.0, -2.0, 1.0), (4.0, -1.0, 1.0)), + ((4.0, -2.0, 1.0 + float.fromhex("0x1.0000000000000p-34")), (5.0, -2.0, 1.0 + float.fromhex("0x1.0000000000000p-34")), (4.0, -1.0, 1.0 + float.fromhex("0x1.0000000000000p-34"))), "hit"), + ("shared0.aabb-disjoint", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), ((0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (0.0, 1.0, 1.0)), "point-only"), + ("shared0.sat-disjoint", ((0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (0.0, 2.0, 0.0)), ((2.0, 2.0, 0.0), (2.0, 1.5, 0.0), (1.5, 2.0, 0.0)), "point-only"), + ("shared0.extreme-small-hit", tuple(tuple(float(2.0 ** -500 * x) for x in point) for point in ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))), + tuple(tuple(float(2.0 ** -500 * x) for x in point) for point in ((0.0, -1.0, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0))), "hit"), + ("shared0.extreme-large-hit", tuple(tuple(float(2.0 ** 500 * x) for x in point) for point in ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))), + tuple(tuple(float(2.0 ** 500 * x) for x in point) for point in ((0.0, -1.0, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0))), "hit"), + ) + stages = { + "shared0.clear-hit-origin": "hit", + "shared0.clear-hit-translated": "hit", + "shared0.sub-I0-contact-origin": "hit", + "shared0.sub-I0-contact-translated": "hit", + "shared0.aabb-disjoint": "aabb-disjoint", + "shared0.sat-disjoint": "sat-disjoint", + "shared0.extreme-small-hit": "hit", + "shared0.extreme-large-hit": "hit", + } + for name, first, second, expected in general: + self._assert_pair(name, first, second, expected, stages[name]) + executions += 1 + + with self.assertRaisesRegex(ValueError, "normalized triangle normal"): + mesh.intersection_diagnostics(((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, D, 0.0)), ((0, 1, 2),)) + self.assertEqual(mesh.intersection_diagnostics( + ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, float.fromhex("0x1.0000000000000p-45"), 0.0)), ((0, 1, 2),) + )["intersection_hit_count"], 0) + executions += 2 + + valid_shared2 = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0)) + self.assertEqual(mesh.intersection_diagnostics(valid_shared2, ((0, 1, 2), (1, 0, 3)))["classifications"], (( (0, 1), "excluded-adjacent"),)) + executions += 1 + with self.assertRaisesRegex(ValueError, "shared-two"): + mesh.intersection_diagnostics(valid_shared2, ((0, 1, 2), (0, 1, 3))) + executions += 1 + with self.assertRaisesRegex(ValueError, "duplicate triangle"): + mesh.intersection_diagnostics(((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), ((0, 1, 2), (0, 1, 2))) + executions += 1 + + cap_points = [] + cap_triangles = [] + for row in range(4096): + offset = 3 * row + x = float(4 * row) + cap_points.extend(((x, 0.0, 0.0), (float(x + 1.0), 0.0, 0.0), (x, 1.0, 0.0))) + cap_triangles.append((offset, offset + 1, offset + 2)) + cap_report = mesh.intersection_diagnostics(tuple(cap_points), tuple(cap_triangles)) + self.assertEqual((cap_report["triangle_count"], cap_report["broad_phase_candidate_count"]), (4096, 0)) + pair_count = 4096 * 4095 // 2 + self.assertEqual(len(cap_report["classifications"]), pair_count) + self.assertEqual(cap_report["classifications"][0], ((0, 1), "aabb-disjoint")) + self.assertEqual(cap_report["classifications"][-1], ((4094, 4095), "aabb-disjoint")) + self.assertTrue(all(stage == "aabb-disjoint" for _, stage in cap_report["classifications"])) + self.assertTrue(cap_report["pair_policy_complete"]) + executions += 1 + with self.assertRaisesRegex(ValueError, "triangle cap"): + mesh.intersection_diagnostics(tuple(cap_points) + ((0.0, 0.0, 0.0), + (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + tuple(cap_triangles) + ((12288, 12289, 12290),)) + executions += 1 + + candidate_points = tuple(point for _ in range(3) for point in ((0.0, 0.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0))) + candidate_triangles = tuple((3 * row, 3 * row + 1, 3 * row + 2) for row in range(3)) + boundary_report = mesh.intersection_diagnostics(candidate_points, candidate_triangles) + self.assertEqual(boundary_report["candidate_pairs"], ((0, 1), (0, 2), (1, 2))) + self.assertEqual(boundary_report["intersection_hit_count"], 3) + self.assertEqual( + boundary_report["classifications"], + (((0, 1), "hit"), ((0, 2), "hit"), ((1, 2), "hit")), + ) + self.assertEqual(mesh._enumerate_fixture_candidates(candidate_points, candidate_triangles, 3), + ((0, 1), (0, 2), (1, 2))) + executions += 1 + with self.assertRaisesRegex(ValueError, "candidate cap"): + mesh._enumerate_fixture_candidates( + candidate_points + ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + candidate_triangles + ((9, 10, 11),), 3) + executions += 1 + self.assertEqual(executions, 105) + + def test_candidate_cap_fixture_helper_is_local_and_deterministic(self): + points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + triangles = ((0, 1, 2), (3, 4, 5), (6, 7, 8)) + self.assertEqual(mesh._enumerate_fixture_candidates(points, triangles, 3), ((0, 1), (0, 2), (1, 2))) + points = points + ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + triangles = triangles + ((9, 10, 11),) + with self.assertRaisesRegex(ValueError, "candidate cap"): + mesh._enumerate_fixture_candidates(points, triangles, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index f0201d0..9e5fe39 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -9,14 +9,12 @@ import unittest from pathlib import Path from unittest.mock import patch - ROOT = Path(__file__).resolve().parents[1] REPOSITORY = ROOT.parents[1] SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" sys.path.insert(0, str(ROOT)) import root_complex_surface as surface # noqa: E402 from prepared_projection import (PreparedProjectionError, _add, _load, _reject_excessive_json_nesting, canonical_json_bytes, canonical_json_sha256, prepare_standard_neutral) # noqa: E402 - BILATERAL_SCALARS = ( ("arm_root_depth", "upper_arm", "form_arm_profile_upper_arm_start_forward_radius"), ("arm_root_outward", "upper_arm", "form_arm_profile_upper_arm_start_lateral_radius"), @@ -134,14 +132,11 @@ def test_full_source_rejects_overflowed_number_in_unconsumed_record(self): prepare_standard_neutral(path) self.assertEqual(str(context.exception), "source contains non-finite JSON numbers") self.assertIsInstance(context.exception.__cause__, ValueError) - def test_non_empty_fields_are_rejected_before_projection(self): self.assert_rejected(r"body\.fields: forbidden geometry-input collection", lambda source: source["body"]["fields"].append({"geometry": "must-not-reach-prepared-output"})) - def test_add_rejects_non_finite_result_from_finite_operands(self): with self.assertRaisesRegex(PreparedProjectionError, r"derived point: expected finite number"): _add((sys.float_info.max, 0, 0), (sys.float_info.max, 0, 0)) - def test_consumed_source_rejects_invalid_dimension_values(self): pelvis = self.owner("pelvis") role = "form_torso_profile_lower_pelvis_lateral_radius" From ebadbca0e1997e2b096e685803857711366d8a38 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 21:58:19 +1200 Subject: [PATCH 07/38] Use New Zealand gallery timestamp format --- dev-tools/visual-review/static/app.js | 2 +- dev-tools/visual-review/tests/test_visual_review.py | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/dev-tools/visual-review/static/app.js b/dev-tools/visual-review/static/app.js index a1d1469..a5078ff 100644 --- a/dev-tools/visual-review/static/app.js +++ b/dev-tools/visual-review/static/app.js @@ -79,7 +79,7 @@ card.appendChild(node("code", session.id, "stable-id")); if (session.published_at) { var published = new Date(session.published_at); - var publishedText = Number.isNaN(published.getTime()) ? session.published_at : published.toLocaleString(); + var publishedText = Number.isNaN(published.getTime()) ? session.published_at : published.toLocaleString("en-NZ"); var publishedNode = node("time", "Published " + publishedText, "session-published"); publishedNode.dateTime = session.published_at; card.appendChild(publishedNode); diff --git a/dev-tools/visual-review/tests/test_visual_review.py b/dev-tools/visual-review/tests/test_visual_review.py index f6e33a1..4a0c381 100644 --- a/dev-tools/visual-review/tests/test_visual_review.py +++ b/dev-tools/visual-review/tests/test_visual_review.py @@ -974,6 +974,15 @@ def test_context_is_preserved_by_review_get(self): class StaticAssetTests(unittest.TestCase): + def test_published_timestamp_uses_explicit_nz_locale_and_invalid_fallback(self): + js = (HERE / "static" / "app.js").read_text(encoding="utf-8") + display_start = js.index("var publishedText =") + display = js[display_start:js.index(";", display_start) + 1] + + self.assertIn('published.toLocaleString("en-NZ")', display) + self.assertNotIn("published.toLocaleString()", display) + self.assertIn("Number.isNaN(published.getTime()) ? session.published_at :", display) + def test_image_accessible_labels_include_description_without_html_interpolation(self): js = (HERE / "static" / "app.js").read_text(encoding="utf-8") script = r''' From e668ed268d7bf31fc06853ec27d98980f7a3451b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 22:05:54 +1200 Subject: [PATCH 08/38] Clarify successor ownership and reproduction --- .../owned-root-assembly-investigation.md | 21 ++-- .../owned-root-assembly-successor/README.md | 100 +++++++++++++++--- 2 files changed, 96 insertions(+), 25 deletions(-) diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index fbe8f42..07a3300 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -93,10 +93,11 @@ port orientations, extraordinary placement and valence, continuity tolerances, normal/fold bounds, and subdivision support are frozen in the required design contract before coordinates or images are judged. -Each domain owns its interior faces and controls. Each shared boundary is -represented once by a named junction owned by its incident domains; there are -no overlapping skins that merely happen to coincide. Domains, charts, ports, -and junctions are ephemeral experiment records, not canonical anatomy IDs. +Each domain owns its interior faces and controls. Each declared junction is the +single construction owner of its shared boundary and records all incident +domains; the boundary is represented once, with no overlapping skins that +merely happen to coincide. Domains, charts, ports, and junctions are ephemeral +experiment records, not canonical anatomy IDs. The frozen design must enumerate every base face and control owner, every junction adjacency and its incident domains, and every domain's nonempty interior. It rejects any domain interior that crosses a required neck, @@ -129,10 +130,14 @@ The required sole freeze artifact for the candidate design is `experiments/owned-root-assembly-successor/design-contract.md`. Its exact raw bytes are frozen and SHA-256-bound at `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`, recorded -by `experiments/owned-root-assembly-successor/design-contract.sha256`. The -builder must require that identity and reject a missing file or any mismatch -before admitting inputs or producing output. The bounded implementation is -next under this frozen contract; no implementation result is implied. +by the existing +`experiments/owned-root-assembly-successor/design-contract.sha256` sidecar, +which records that matching contract SHA-256. The implementation README records +two completed independent FREEZE reviews. The builder must require that +identity and reject a missing file or any mismatch before admitting inputs or +producing output. The bounded implementation is next under this frozen +contract; no implementation result is implied. This research record remains +experiment-local, non-authoritative evidence and direction context. The frozen design contract covers every item in the preflight below and sets finite caps for total junction count and interface cardinality; chart, formula, diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 09d5988..417db34 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -21,8 +21,8 @@ experiment does not change their lifecycle. Related DRs: DR-0013 context only; DR-0009 and DR-0010 remain parked -Freeze state: double-FREEZE; two independent Sol reviews returned `FREEZE` -with zero blockers +Freeze state: double-FREEZE; two completed independent Sol FREEZE reviews +returned `FREEZE` with zero blockers Design contract SHA-256: `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490` @@ -144,25 +144,29 @@ serialized production schemas, canonical identifiers, or additions to - **Domain plan**: one owner for each domain interior and its local chart, including declared boundary participation. - **Junction plan**: the shared boundary between incident domains, its ordered - interface curve, port relationship, and continuity obligations. + interface curve, port relationship, and continuity obligations; the declared + junction is the boundary's single construction owner and records all incident + domains. - **Causal binding**: source address/role to derived parameter, control, subdivision stencil, and evaluated-surface lineage. - **Surface artifact**: one welded control/evaluated surface with ephemeral domain, junction, port, chart, contributor, and diagnostic metadata. -The construction layer owns base faces, domain interiors, and junction -construction. The semantic layer carries causality from authored addresses and -roles through derived parameters and subdivision stencils. The evaluated -surface carries contributor and chart lineage, which may name multiple -domains. These layers may reference one another through explicit bindings but -may not silently replace one another. +The construction layer owns base faces, domain interiors, and each declared +junction's shared boundary; each junction records all incident domains. The +semantic layer carries causality from authored addresses and roles through +derived parameters and subdivision stencils. The evaluated surface carries +contributor and chart lineage, which may name multiple domains. These layers +may reference one another through explicit bindings but may not silently +replace one another. Every base face and control has exactly one construction owner: a domain -interior or a declared junction. Every shared junction boundary is represented -once in the welded surface and records all incident domains. Every evaluated -surface element has valid contributor/chart lineage. There is no unowned -output. A categorical colour or legend may expose lineage in a diagnostic, -but it is never evidence of causality by itself. +interior or a declared junction. Every declared junction is the single +construction owner of its shared boundary, which is represented once in the +welded surface and records all incident domains. Every evaluated surface +element has valid contributor/chart lineage. There is no unowned output. A +categorical colour or legend may expose lineage in a diagnostic, but it is +never evidence of causality by itself. ## Fixed scope and hard caps @@ -198,9 +202,12 @@ ownership rules, it stops before producing evidence. The bounded design pass created `experiments/owned-root-assembly-successor/design-contract.md` as the sole freeze artifact for the candidate design. Its exact raw bytes are recorded in -`experiments/owned-root-assembly-successor/design-contract.sha256` with -SHA-256 `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`. -The builder must require that identity, hash the file before admitting source +the existing +`experiments/owned-root-assembly-successor/design-contract.sha256` sidecar, +which records matching SHA-256 +`3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`. The +implementation README records two completed independent FREEZE reviews. The +builder must require that identity, hash the file before admitting source inputs, and reject a missing file or mismatch without producing an artifact. The bounded implementation phase is active under this frozen contract. @@ -388,6 +395,65 @@ This implementation-phase README provides the exact copy-paste reproduction command and lists all raw outputs. Execution remains bounded by that command and the frozen design-contract identity. +## Exact reproduction and final output + +From the repository root, use the only public entrypoint with the contract's +exact invocation form: + +```bash +PYTHONHASHSEED=0 experiments/owned-root-assembly-successor/owned_root_launcher.sh --output ABSENT_PATH +``` + +Replace `ABSENT_PATH` with a fresh absolute path that does not exist before the +invocation. The final successful output is the complete outer root below. Each +seed directory contains exactly the same 47 relative roles listed in the +inventory; the comparison directory contains exactly its two listed files. + +```text +ABSENT_PATH/ +├── seed-17/ exact 47-role inventory below +├── seed-29/ the same exact 47-role inventory below +└── comparison/ + ├── comparison-report.json + └── comparison-report.sha256 + +Per-seed roles, relative to seed-17/ or seed-29/: +surface-level-0.ply, surface-level-1.ply, surface-level-2.ply +perturb-left-r_y.ply, perturb-right-r_y.ply +perturb-lower_pelvis-L_y.ply, perturb-left-r_x.ply +perturb-lower_pelvis-C_z.ply, perturb-right-r_x.ply +perturb-lower_pelvis-R_x.ply, perturb-left-r_z.ply +perturb-right-r_z.ply, perturb-lower_pelvis-R_f.ply +perturb-lower_pelvis-R_b.ply, perturb-left-thigh_start_x.ply +perturb-left-thigh_start_y.ply, perturb-left-thigh_start_z.ply +perturb-right-thigh_start_x.ply, perturb-right-thigh_start_y.ply +perturb-right-thigh_start_z.ply, perturb-neck_collar-C_y.ply +perturb-neck_collar-rL.ply, perturb-neck_upper-C_y.ply +perturb-neck_upper-rL.ply, perturb-left-axilla_x.ply +perturb-left-axilla_y.ply, perturb-right-axilla_x.ply +perturb-right-axilla_y.ply, perturb-left-peak_y.ply +perturb-right-peak_y.ply, perturb-left-start_lateral.ply +perturb-right-start_lateral.ply, perturb-left-start_up.ply +perturb-right-start_up.ply, perturb-left-shoulder_depth.ply +perturb-right-shoulder_depth.ply +direct.png, lineage.png +input-manifest.json, coordinate-manifest.json, gate-manifest.json +causality-manifest.json, render-manifest.json, stable-manifest.json +prepared-input.json, report.json, report.sha256 +``` + +The repository contract sidecar is an input, not a published output role. The +managed-test receipt is staging-only and is removed before publication. On any +failed test, builder, comparison, receipt removal, closed-root validation, or +publication stage, the launcher exits `1`, publishes neither the comparison +directory nor the outer root, and emits nothing at `ABSENT_PATH`; cleanup is +limited to invocation-owned staging. Success exits `0`, and only the complete +published outer root is technical evidence. See the frozen contract's +[§10.3](design-contract.md#103-closed-inventory-and-acyclic-hash-graph), +[§11](design-contract.md#11-paths-launcher-and-reproducibility), and +[§13](design-contract.md#13-seed-local-gate-and-pair-publication-order) for +the authoritative inventory and publication rules. + ## Correction stop The initial implementation is followed by at most two shared correction From 0895609b62f3a8d70bc6157328b6695ff779b930 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 22:16:32 +1200 Subject: [PATCH 09/38] Address bounded review findings --- docs/research/README.md | 7 ++++--- .../prepared_projection.py | 3 ++- .../tests/test_prepared_projection.py | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/research/README.md b/docs/research/README.md index c8cefe0..221b6b7 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -27,9 +27,10 @@ hypotheses, references, and research context. it is non-normative, blocks exact-five continuation, and does not activate DR-0009/0010 or replace DR-0013 Stage 1 proof. - [Owned root assembly investigation](owned-root-assembly-investigation.md) — a - planned, Ben-authorized, experiment-local successor direction using explicit - domain/junction ownership; it is non-normative and remains bounded by the - Active runway and the later exact-five human checkpoint. + Ben-authorized, experiment-local successor direction whose design is frozen + and whose bounded implementation is active, using explicit domain/junction + ownership; it is non-normative, remains bounded by the Active runway, and + leads to the later exact-five human checkpoint. - [Numeric and frame profile experiment design](numeric-frame-profile-experiment.md) — planned and unregistered evidence for numeric admission, exact dyadic/ULP boundaries, deterministic normalization and offline half-chord derivation, diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index d912895..9b67a28 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -133,7 +133,8 @@ def prepare_standard_neutral(path): _ok(source["profiles"] == {"semantic_numeric": "ck.numeric-frame.r1"} and source["extensions"] == [], "source", "unsupported profile or extension") body = _dict(source["body"], "source.body"); _ok(set(body) == _BODY, "source.body", "unknown or missing collection") _ok(body["fields"] == [], "body.fields", "forbidden geometry-input collection") - for name, count in _COUNT.items(): _ok(isinstance(body[name], list) and len(body[name]) == count, f"body.{name}", f"expected {count} records"); _validate_dimensions(body["dimensions"]) if name == "dimensions" else None + for name, count in _COUNT.items(): _ok(isinstance(body[name], list) and len(body[name]) == count, f"body.{name}", f"expected {count} records") + _validate_dimensions(body["dimensions"]) ns = source["source"]["namespace"] def part(role, side=None): return ns, () if side is None else (side,), "part", role p = {part("pelvis"): _part(body["parts"], part("pelvis"), None), part("torso"): _part(body["parts"], part("torso"), part("pelvis")), part("neck"): _part(body["parts"], part("neck"), part("torso"))} diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index 9e5fe39..b2f6a7b 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -143,8 +143,8 @@ def test_consumed_source_rejects_invalid_dimension_values(self): cases = ((10**400, "expected finite number"), (True, "expected finite number"), (False, "expected finite number"), (0, "expected positive number"), (-0.01, "expected positive number")) for value, message in cases: with self.subTest(value=value): self.assert_rejected(rf"body\.dimensions\[\d+\]\.value: {message}", lambda source, value=value: source["body"]["dimensions"][self.record_index(source, "dimensions", pelvis, role)].__setitem__("value", value)) - - for index in range(153): self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) + for index in range(153): + with self.subTest(index=index): self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) def test_canonical_metre_dimensions_and_non_dimension_routes(self): with tempfile.TemporaryDirectory() as directory: source = copy.deepcopy(self.source); source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_lateral_radius")]["value"] = 1.2345; source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_anterior_radius")]["value"] = 2; path = Path(directory) / "source.json"; path.write_text(json.dumps(source), encoding="utf-8"); prepared = prepare_standard_neutral(path) self.assertEqual(prepared["stations"]["lower_pelvis"]["lateral_radius"], 1.2345); self.assertEqual(prepared["stations"]["lower_pelvis"]["front_extent"], 2) From 9877fd76b9f3346a0e1243ce2a66808657235bde Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 22:21:24 +1200 Subject: [PATCH 10/38] Preserve predecessor complexity boundary --- .../programmatic-root-complex-surface/prepared_projection.py | 1 - 1 file changed, 1 deletion(-) diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index 9b67a28..bc8714d 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -124,7 +124,6 @@ def _bilateral_scalar(rows, owners, role, name): _ok(left[0] == right[0], f"scalars.{name}", "left and right dimensions must match") return {"value": left[0], "provenance": "; ".join((left[1], right[1], "derivation=validated_bilateral_scalar_v1"))} - def prepare_standard_neutral(path): source, digest = _load(path); _ok(set(source) == _TOP, "source", "unknown or missing top-level field") _ok(source["contract"] == {"family": "creature-kernel.body", "revision": 1}, "source.contract", "wrong contract") From fab17aa5e945e9d3e603e83aeafc3ec606c846bb Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 4 Sep 2026 23:16:41 +1200 Subject: [PATCH 11/38] Address hosted review maintenance findings --- docs/project/current-handover.md | 2 +- .../prepared_projection.py | 18 +++++------ .../tests/test_prepared_projection.py | 30 ++++++++++++++----- .../tests/test_render_export.py | 16 ---------- 4 files changed, 33 insertions(+), 33 deletions(-) diff --git a/docs/project/current-handover.md b/docs/project/current-handover.md index d42bc29..cf97048 100644 --- a/docs/project/current-handover.md +++ b/docs/project/current-handover.md @@ -12,7 +12,7 @@ untrusted until verified live: - Checkout: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` - Worktree: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` - Branch: `codex/owned-root-assembly-successor` -- Pull request: none yet; successor-plan worktree is not a PR +- Pull request: PR #127 is an open draft for `codex/owned-root-assembly-successor` ## Live verification checklist diff --git a/experiments/programmatic-root-complex-surface/prepared_projection.py b/experiments/programmatic-root-complex-surface/prepared_projection.py index bc8714d..8552cd7 100644 --- a/experiments/programmatic-root-complex-surface/prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/prepared_projection.py @@ -7,21 +7,15 @@ import math from pathlib import Path - class PreparedProjectionError(ValueError): pass - class _DuplicateJSONKeyError(ValueError): pass - class _NonFiniteJSONConstantError(ValueError): pass - class _NonFiniteJSONNumberError(ValueError): pass - class _JSONRootTypeError(TypeError): pass - _TOP = {"basis", "body", "contract", "extensions", "profiles", "source"} _BODY = {"attachments", "capabilities", "dimensions", "fields", "frames", "joints", "landmarks", "modules", "parts", "regions", "sockets"} _COUNT = {"parts": 18, "frames": 16, "landmarks": 43, "dimensions": 153} @@ -107,8 +101,15 @@ def _part(rows, owner, parent): return translation, where def _add(a, b): result = tuple(x + y for x, y in zip(a, b)); _ok(all(_finite(value) for value in result), "derived point", "expected finite number"); return result def _validate_dimensions(rows): - for i, raw in enumerate(rows): where, row = f"body.dimensions[{i}]", _dict(raw, f"body.dimensions[{i}]"); _ok(set(row) == {"owner", "role", "value"}, where, "unknown or missing required field"); _addr(row["owner"], f"{where}.owner"); _ok(isinstance(row["role"], str) and row["role"], f"{where}.role", "expected non-empty role"); _num(row["value"], f"{where}.value", True) -def _dimension(rows, owner, role): row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions"); return row["value"], f"{where}.value; {_D}" + for i, raw in enumerate(rows): + where, row = f"body.dimensions[{i}]", _dict(raw, f"body.dimensions[{i}]") + _ok(set(row) == {"owner", "role", "value"}, where, "unknown or missing required field") + _addr(row["owner"], f"{where}.owner") + _ok(isinstance(row["role"], str) and row["role"], f"{where}.role", "expected non-empty role") + _num(row["value"], f"{where}.value", True) +def _dimension(rows, owner, role): + row, where = _pick(rows, owner, role, {"owner", "role", "value"}, "dimensions") + return row["value"], f"{where}.value; {_D}" def _landmark(rows, owner, role, frame): row, where = _pick(rows, owner, role, {"owner", "role", "frame", "position"}, "landmarks"); ref = _dict(row["frame"], f"{where}.frame"); _ok(set(ref) == {"owner", "role"} and (_addr(ref["owner"], where), ref["role"]) == frame, where, "invalid landmark frame"); return _vec(row["position"], f"{where}.position"), where def _world_part(part_data, world, owner, parent): @@ -166,7 +167,6 @@ def part(role, side=None): return ns, () if side is None else (side,), "part", r for name, (role, dimension_role) in _BILATERAL_SCALARS.items()} return {"source": {"document": source["source"]["document"], "namespace": ns, "sha256": digest, "provenance": "raw_source_utf8_bytes_sha256_v1"}, "basis": dict(source["basis"]), "frames": {"body": frame_body}, "landmarks": landmarks, "stations": stations, "scalars": scalars} - def canonical_json_bytes(value): return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") def canonical_json_sha256(value): return hashlib.sha256(canonical_json_bytes(value)).hexdigest() __all__ = ["PreparedProjectionError", "canonical_json_bytes", "canonical_json_sha256", "prepare_standard_neutral"] diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index b2f6a7b..0d68a25 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -47,7 +47,8 @@ def test_source_identity_provenance_and_expected_controls(self): self.assertLess(self.prepared["landmarks"]["shoulder_peak_left"]["point"][0], 0) self.assertGreater(self.prepared["landmarks"]["shoulder_peak_right"]["point"][0], 0) self.assertEqual(self.prepared["scalars"]["arm_root_depth"]["value"], self.prepared["scalars"]["thigh_lateral_radius"]["value"]) - point_derivation = "derivation=parent_local_part_translation_plus_landmark_position_v1"; dimension_derivation = "derivation=source_dimension_canonical_metre_value_v1" + point_derivation = "derivation=parent_local_part_translation_plus_landmark_position_v1" + dimension_derivation = "derivation=source_dimension_canonical_metre_value_v1" expected_provenance = ( ("shoulder_peak_left", ("body.parts[0].placement.translation", "body.parts[1].placement.translation", "body.parts[4].placement.translation", "body.landmarks[0].position", point_derivation)), ("shoulder_peak_right", ("body.parts[0].placement.translation", "body.parts[1].placement.translation", "body.parts[7].placement.translation", "body.landmarks[2].position", point_derivation)), @@ -142,13 +143,25 @@ def test_consumed_source_rejects_invalid_dimension_values(self): role = "form_torso_profile_lower_pelvis_lateral_radius" cases = ((10**400, "expected finite number"), (True, "expected finite number"), (False, "expected finite number"), (0, "expected positive number"), (-0.01, "expected positive number")) for value, message in cases: - with self.subTest(value=value): self.assert_rejected(rf"body\.dimensions\[\d+\]\.value: {message}", lambda source, value=value: source["body"]["dimensions"][self.record_index(source, "dimensions", pelvis, role)].__setitem__("value", value)) + with self.subTest(value=value): + self.assert_rejected(rf"body\.dimensions\[\d+\]\.value: {message}", lambda source, value=value: source["body"]["dimensions"][self.record_index(source, "dimensions", pelvis, role)].__setitem__("value", value)) for index in range(153): - with self.subTest(index=index): self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) + with self.subTest(index=index): + self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) def test_canonical_metre_dimensions_and_non_dimension_routes(self): - with tempfile.TemporaryDirectory() as directory: source = copy.deepcopy(self.source); source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_lateral_radius")]["value"] = 1.2345; source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_anterior_radius")]["value"] = 2; path = Path(directory) / "source.json"; path.write_text(json.dumps(source), encoding="utf-8"); prepared = prepare_standard_neutral(path) - self.assertEqual(prepared["stations"]["lower_pelvis"]["lateral_radius"], 1.2345); self.assertEqual(prepared["stations"]["lower_pelvis"]["front_extent"], 2) - self.assertEqual(prepared["basis"], self.prepared["basis"]); self.assertEqual(prepared["frames"], self.prepared["frames"]); self.assertEqual(prepared["landmarks"], self.prepared["landmarks"]); self.assertEqual({name: station["center"] for name, station in prepared["stations"].items()}, {name: station["center"] for name, station in self.prepared["stations"].items()}) + with tempfile.TemporaryDirectory() as directory: + source = copy.deepcopy(self.source) + source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_lateral_radius")]["value"] = 1.2345 + source["body"]["dimensions"][self.record_index(source, "dimensions", self.owner("pelvis"), "form_torso_profile_lower_pelvis_anterior_radius")]["value"] = 2 + path = Path(directory) / "source.json" + path.write_text(json.dumps(source), encoding="utf-8") + prepared = prepare_standard_neutral(path) + self.assertEqual(prepared["stations"]["lower_pelvis"]["lateral_radius"], 1.2345) + self.assertEqual(prepared["stations"]["lower_pelvis"]["front_extent"], 2) + self.assertEqual(prepared["basis"], self.prepared["basis"]) + self.assertEqual(prepared["frames"], self.prepared["frames"]) + self.assertEqual(prepared["landmarks"], self.prepared["landmarks"]) + self.assertEqual({name: station["center"] for name, station in prepared["stations"].items()}, {name: station["center"] for name, station in self.prepared["stations"].items()}) def test_add_rejects_arbitrary_precision_integer(self): with self.assertRaisesRegex(PreparedProjectionError, r"derived point: expected finite number"): _add((10**400, 0, 0), (0, 0, 0)) @@ -171,4 +184,7 @@ def test_required_source_shape_and_routes_fail_closed(self): self.assert_rejected(r"body\.landmarks\.form_torso_profile_lower_pelvis: missing or duplicate required record", lambda source: self.duplicate_record(source, "landmarks", (pelvis, "form_torso_profile_lower_pelvis"), (pelvis, "form_torso_profile_upper_pelvis"))) self.assert_rejected(r"body\.landmarks\[\d+\]: missing record selector", lambda source: self.blank_record(source, "landmarks", (self.owner("upper_arm", ("left",)), "form_shoulder_peak"))) self.assert_rejected(r"source\.body: unknown or missing collection", lambda source: source["body"].__setitem__("unknown", [])) - self.assert_rejected(r"body\.frames\.form_torso_profile_control: missing or duplicate required record", lambda source: self.duplicate_record(source, "frames", (self.owner("torso"), "form_torso_profile_control"), (pelvis, "form_torso_profile_control"))); self.assert_rejected(r"body\.dimensions\[0\]: unknown or missing required field", lambda source: source["body"]["dimensions"][0].__setitem__("extra", 1)); self.assert_rejected(r"body\.dimensions\[0\]\.owner: invalid part address", lambda source: source["body"]["dimensions"][0]["owner"].__setitem__("kind", "joint")); self.assert_rejected(r"body\.dimensions\[0\]\.role: expected non-empty role", lambda source: source["body"]["dimensions"][0].__setitem__("role", "")) + self.assert_rejected(r"body\.frames\.form_torso_profile_control: missing or duplicate required record", lambda source: self.duplicate_record(source, "frames", (self.owner("torso"), "form_torso_profile_control"), (pelvis, "form_torso_profile_control"))) + self.assert_rejected(r"body\.dimensions\[0\]: unknown or missing required field", lambda source: source["body"]["dimensions"][0].__setitem__("extra", 1)) + self.assert_rejected(r"body\.dimensions\[0\]\.owner: invalid part address", lambda source: source["body"]["dimensions"][0]["owner"].__setitem__("kind", "joint")) + self.assert_rejected(r"body\.dimensions\[0\]\.role: expected non-empty role", lambda source: source["body"]["dimensions"][0].__setitem__("role", "")) diff --git a/experiments/programmatic-root-complex-surface/tests/test_render_export.py b/experiments/programmatic-root-complex-surface/tests/test_render_export.py index e02a382..d9ad3dd 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_render_export.py +++ b/experiments/programmatic-root-complex-surface/tests/test_render_export.py @@ -7,20 +7,17 @@ import numpy as np from PIL import Image - ROOT = Path(__file__).resolve().parents[1]; REPOSITORY = ROOT.parents[1] SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json"; LAUNCHER = ROOT / "root_complex_launcher.sh"; BUILD_SCRIPT = ROOT / "build_root_complex.py"; ARTIFACTS = ("prepared.json", "skin.ply", "skin.png", "cage.png", "metrics.json", "manifest.json") sys.path.insert(0, str(ROOT)) import build_root_complex as builder # noqa: E402 import render_export # noqa: E402 - VERTICES = np.asarray(((-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0)), dtype=np.float64) QUADS = np.asarray(((0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (4, 0, 3, 7)), dtype=np.int64) DEPTH_VERTICES = np.asarray(((-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (1.0, 1.0, 3.0), (-1.0, 1.0, 3.0), (-1.0, -1.0, 1.6), (1.0, -1.0, 1.6), (1.0, 1.0, 1.6), (-1.0, 1.0, 1.6)), dtype=np.float64) DEPTH_QUADS = np.asarray(((0, 1, 2, 3), (4, 5, 6, 7)), dtype=np.int64); EXTREME_VERTICES = VERTICES * (np.finfo(np.float64).max / 2.0) - def png_chunk_types(data: bytes) -> list[bytes]: offset, result = 8, [] while offset < len(data): @@ -29,7 +26,6 @@ def png_chunk_types(data: bytes) -> list[bytes]: offset += 12 + length return result - class RenderExportTests(unittest.TestCase): def test_ply_has_counts_and_stable_quad_triangle_order(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: @@ -52,42 +48,35 @@ def test_skin_z_buffer_chooses_local_near_depth_independent_of_triangle_order(se with Image.open(root / "forward.png") as image: pixel = image.getpixel(sample) normal = np.cross(DEPTH_VERTICES[1] - DEPTH_VERTICES[0], DEPTH_VERTICES[2] - DEPTH_VERTICES[0]); brightness = 0.38 + 0.62 * max(0.0, float(np.dot(normal / np.linalg.norm(normal), render_export._LIGHT))) self.assertEqual(pixel, tuple(int(round(channel * brightness)) for channel in render_export._BASE_COLOUR)) - def test_png_is_rgb_fixed_size_and_has_no_metadata_chunks(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: path = Path(d) / "skin.png"; render_export.render_skin_png(path, VERTICES, QUADS); data = path.read_bytes() with Image.open(path) as image: self.assertEqual((image.mode, image.size, image.info), ("RGB", render_export.CANVAS_SIZE, {})); self.assertEqual(png_chunk_types(data), [b"IHDR", b"IDAT", b"IEND"]) - def test_cage_diagnostic_is_rgb_and_has_visible_edges(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: path = Path(d) / "cage.png"; render_export.render_cage_png(path, VERTICES, QUADS); data = path.read_bytes() with Image.open(path) as image: self.assertEqual((image.mode, image.size), ("RGB", render_export.CANVAS_SIZE)); self.assertIn((237, 188, 86), set(image.getdata())); self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n")) - def test_existing_outputs_are_not_replaced(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: root = Path(d) for name, writer in (("skin.ply", render_export.write_skin_ply), ("skin.png", render_export.render_skin_png), ("cage.png", render_export.render_cage_png)): path = root / name; path.write_bytes(b"keep me"); self.assertRaises(FileExistsError, writer, path, VERTICES, QUADS); self.assertEqual(path.read_bytes(), b"keep me") - def test_changing_a_supplied_vertex_changes_ply_and_skin_png(self) -> None: changed = VERTICES.copy(); changed[6, 0] += 0.35 with tempfile.TemporaryDirectory(prefix="root-complex-render-") as d: root = Path(d) for suffix, writer in (("ply", render_export.write_skin_ply), ("png", render_export.render_skin_png)): writer(root / f"original.{suffix}", VERTICES, QUADS); writer(root / f"changed.{suffix}", changed, QUADS); self.assertNotEqual((root / f"original.{suffix}").read_bytes(), (root / f"changed.{suffix}").read_bytes()) - def test_nonfinite_and_invalid_indices_are_rejected(self) -> None: bad_vertices = VERTICES.copy(); bad_vertices[0, 0] = np.nan; self.assertRaises(ValueError, render_export.triangulate_quads, bad_vertices, QUADS) for value, dtype in ((np.inf, np.float64), (0.5, np.float64), (-1, np.int64), (len(VERTICES), np.int64)): bad_indices = QUADS.astype(dtype); bad_indices[0, 0] = value; self.assertRaises(ValueError, render_export.triangulate_quads, VERTICES, bad_indices) - def test_extreme_finite_coordinates_keep_frame_projection_finite(self) -> None: cameras, centres, scale = render_export._frames(EXTREME_VERTICES) self.assertTrue(np.isfinite(np.asarray(cameras)).all()); self.assertTrue(np.isfinite(np.asarray(centres)).all()); self.assertTrue(np.isfinite(scale) and scale > 0.0) with tempfile.TemporaryDirectory(prefix="root-complex-render-extreme-") as d: path = Path(d) / "skin.png"; render_export.render_skin_png(path, EXTREME_VERTICES, QUADS) with Image.open(path) as image: self.assertEqual((image.mode, image.size), ("RGB", render_export.CANVAS_SIZE)) - def test_builder_rejects_nonzero_intersections_before_publication(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-intersection-") as d: root = Path(d); target = root / "standard-neutral"; evaluated = SimpleNamespace(intersection_counts=(0, 1)) @@ -96,22 +85,18 @@ def test_builder_rejects_nonzero_intersections_before_publication(self) -> None: publish.assert_not_called() self.assertFalse(target.exists()) self.assertEqual(list(root.glob(f".{target.name}.staging-*")), []) - def test_builder_publishes_complete_metrics_and_manifest(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-build-") as d: target = Path(d) / "standard-neutral"; self.assertEqual(builder.build(SOURCE, target), target); self.assertEqual({p.name for p in target.iterdir()}, set(ARTIFACTS)) metrics = json.loads((target / "metrics.json").read_text(encoding="utf-8")); manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8")); self.assertEqual(metrics["intersection_status"], "zero"); self.assertEqual(metrics["intersection_counts_by_level"], [0, 0]); self.assertNotIn("metrics.json", metrics["files"]); self.assertEqual(set(manifest["files"]), set(ARTIFACTS) - {"manifest.json"}); self.assertEqual(manifest["files"]["metrics.json"], hashlib.sha256((target / "metrics.json").read_bytes()).hexdigest()) - def test_atomic_publication_refuses_existing_target_without_overwrite(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-publish-") as d: root = Path(d); stage, target = root / "stage", root / "target"; stage.mkdir(); (stage / "payload").write_bytes(b"new"); target.mkdir(); (target / "payload").write_bytes(b"keep"); self.assertRaises(FileExistsError, builder._publish_no_replace, stage, target) self.assertEqual((stage / "payload").read_bytes(), b"new"); self.assertEqual((target / "payload").read_bytes(), b"keep") - def test_builder_cleans_staging_after_generation_failure(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-failure-") as d: root = Path(d); target = root / "standard-neutral"; self.assertRaises(ValueError, builder.build, root / "missing-source.json", target) self.assertFalse(target.exists()); self.assertEqual(list(root.glob(f".{target.name}.staging-*")), []) - def test_launcher_fresh_processes_are_byte_identical(self) -> None: with tempfile.TemporaryDirectory(prefix="root-complex-determinism-") as d: root = Path(d); targets = (root / "seed-one", root / "seed-two") @@ -124,6 +109,5 @@ def test_launcher_fresh_processes_are_byte_identical(self) -> None: self.fail(f"launcher {description}\nstdout:\n{getattr(exc, 'stdout', '')}\nstderr:\n{getattr(exc, 'stderr', '')}") for name in ARTIFACTS: self.assertEqual((targets[0] / name).read_bytes(), (targets[1] / name).read_bytes(), name) - if __name__ == "__main__": unittest.main() From 2cad17eb3052b47b4fa94d08ff3f43d6c4a17e97 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 00:08:53 +1200 Subject: [PATCH 12/38] Add prepared projection and bounded mesh validation --- .../mesh_correctness.py | 169 +++--- .../prepared_projection.py | 500 ++++++++++++++++++ .../tests/test_mesh_correctness.py | 153 +++++- .../tests/test_prepared_projection.py | 460 ++++++++++++++++ 4 files changed, 1189 insertions(+), 93 deletions(-) create mode 100644 experiments/owned-root-assembly-successor/prepared_projection.py create mode 100644 experiments/owned-root-assembly-successor/tests/test_prepared_projection.py diff --git a/experiments/owned-root-assembly-successor/mesh_correctness.py b/experiments/owned-root-assembly-successor/mesh_correctness.py index 2097790..cc21ced 100644 --- a/experiments/owned-root-assembly-successor/mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/mesh_correctness.py @@ -2,11 +2,12 @@ from __future__ import annotations +import itertools +import math from collections import defaultdict from dataclasses import dataclass from fractions import Fraction -import itertools -import math +from typing import NoReturn _FIXED_I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") _FIXED_D = float.fromhex("0x1.0000000000000p-46") @@ -16,8 +17,11 @@ _FIXED_FOLD_LIMITS = (90.0, 60.0, 30.0) _MAX_TRIANGLES = 4096 _MAX_QUADS = _MAX_TRIANGLES // 2 +_MAX_BASE_CONTROLS, _MAX_BASE_QUADS = 128, 120 _MAX_CANDIDATES = 1_000_000 +_MAX_CLASSIFICATION_DETAILS, _MAX_DIAGNOSTIC_EVIDENCE = 4096, 64 _PORT_ORIENTATION, _PORT_AREA_RATIO, _PORT_CO_NORMAL = 0.99, 0.0001, 0.80 +_FINAL_CLASSIFICATION_STAGES = ("aabb-disjoint", "sat-disjoint", "hit", "point-only", "excluded-adjacent") I0 = INTERSECTION_TOLERANCE = _FIXED_I0 D = DEGENERACY_FLOOR = _FIXED_D @@ -39,12 +43,15 @@ class MeshCorrectnessError(ValueError): """A deterministic, fail-closed mesh correctness failure.""" -def _fail(message: str) -> None: raise MeshCorrectnessError(message) +def _fail(message: str) -> NoReturn: + raise MeshCorrectnessError(message) def _finite_float(value, label: str) -> float: - if type(value) is not float or not math.isfinite(value): _fail(f"{label} must be a finite binary64 value") + if type(value) is not float or not math.isfinite(value): + _fail(f"{label} must be a finite binary64 value") return value def _integer(value, label: str) -> int: - if type(value) is not int: _fail(f"{label} must be an integer") + if type(value) is not int: + _fail(f"{label} must be an integer") return value def _sequence(raw, label: str, cap=None): if type(raw) not in (list, tuple): @@ -73,7 +80,8 @@ def _points(raw): def _simple_indices(raw, vertex_count, label): values = tuple(_integer(value, label) for value in _sequence(raw, label)) if (len(values) < 3 or len(set(values)) != len(values) - or any(index < 0 or index >= vertex_count for index in values)): _fail(f"{label} must be simple and in range") + or any(index < 0 or index >= vertex_count for index in values)): + _fail(f"{label} must be simple and in range") return values def _indexed_rows(raw, width, vertex_count, label, cap=None): rows = _sequence(raw, label, cap) @@ -89,43 +97,35 @@ def _indexed_rows(raw, width, vertex_count, label, cap=None): _fail(f"{label[:-1]} has repeated vertex index at {face_index}") result.append(face) return tuple(result) - def _canonical_cycle(face): return min(sequence[i:] + sequence[:i] for sequence in (tuple(face), tuple(reversed(face))) for i in range(len(face))) - def _quads(raw, vertex_count): faces = _indexed_rows(raw, 4, vertex_count, "quads", _MAX_QUADS) keys = tuple(_canonical_cycle(face) for face in faces) if len(set(keys)) != len(keys): _fail("duplicate quad, including reversed/cyclic duplicate") return faces - def _add_vec(a, b): return tuple(a[i] + b[i] for i in range(3)) def _sub_vec(a, b): return tuple(a[i] - b[i] for i in range(3)) def _dot_vec(a, b): return (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2] - def _cross_vec(a, b): return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) - def _norm_vec(value): return math.sqrt(_dot_vec(value, value)) - def _normalize_vec(value, label): length = _norm_vec(value) if not math.isfinite(length) or length <= 0.0: _fail(f"{label} must be finite and nonzero") return tuple(component / length for component in value) - def add(a, b): return _add_vec(_vec(a, "left vector"), _vec(b, "right vector")) def sub(a, b): return _sub_vec(_vec(a, "left vector"), _vec(b, "right vector")) def dot(a, b): return _dot_vec(_vec(a, "left vector"), _vec(b, "right vector")) def cross(a, b): return _cross_vec(_vec(a, "left vector"), _vec(b, "right vector")) def norm(value): return _norm_vec(_vec(value, "vector")) def normalize(value): return _normalize_vec(_vec(value, "vector"), "vector normal") - def _normalize_points(points): lower = tuple(min(point[i] for point in points) for i in range(3)) extent = tuple(max(point[i] for point in points) - lower[i] for i in range(3)) @@ -137,17 +137,14 @@ def _normalize_points(points): if any(not math.isfinite(value) for point in normalized for value in point): _fail("normalized coordinates must be finite") return normalized, scale - def interval_disjoint(lower_a, upper_a, lower_b, upper_b): values = tuple(_finite_float(value, label) for value, label in zip( (lower_a, upper_a, lower_b, upper_b), ("lower_A", "upper_A", "lower_B", "upper_B"))) return _interval_disjoint(*values) - def _interval_disjoint(lower_a, upper_a, lower_b, upper_b): return (upper_a < lower_b - _FIXED_I0 or upper_b < lower_a - _FIXED_I0) - def _edge_incidence(faces): result = defaultdict(list) for face_index, face in enumerate(faces): @@ -155,7 +152,6 @@ def _edge_incidence(faces): end = face[(slot + 1) % len(face)] result[(min(start, end), max(start, end))].append((face_index, start, end)) return result - def _validate_loops(raw, vertex_count): if raw is None: return {} @@ -168,11 +164,9 @@ def _validate_loops(raw, vertex_count): used.update(loop) result[name] = loop return result - def _cyclic_equal(actual, expected, reverse=False): target = tuple(reversed(expected)) if reverse else tuple(expected) return len(actual) == len(target) and any(actual == target[i:] + target[:i] for i in range(len(target))) - def _boundary_cycles(edges): outgoing = defaultdict(list) for _, start, end in edges: @@ -210,7 +204,6 @@ class TopologyReport: @property def euler_characteristic(self): return self.euler - def _connected_components(adjacency, vertex_count): unseen, components = set(range(vertex_count)), 0 while unseen: @@ -221,18 +214,20 @@ def _connected_components(adjacency, vertex_count): unseen.difference_update(neighbours) todo.extend(neighbours) return components - def _topology_report(vertex_count, quads, loops, expected_faces): if expected_faces is not None: expected = _indexed_rows( expected_faces, 4, vertex_count, "expected_faces", _MAX_QUADS) - if quads != expected: _fail("face winding/catalog does not match exactly") + if quads != expected: + _fail("face winding/catalog does not match exactly") incidence = _edge_incidence(quads) non_manifold = sum(len(items) > 2 for items in incidence.values()) - if non_manifold: _fail(f"non-manifold edge count {non_manifold}") + if non_manifold: + _fail(f"non-manifold edge count {non_manifold}") conflicts = sum(len(items) == 2 and items[0][1:] == items[1][1:] for items in incidence.values()) - if conflicts: _fail(f"orientation conflict count {conflicts}") + if conflicts: + _fail(f"orientation conflict count {conflicts}") boundary = [items[0] for items in incidence.values() if len(items) == 1] cycles = _boundary_cycles(boundary) if boundary else () if loops: @@ -251,7 +246,8 @@ def _topology_report(vertex_count, quads, loops, expected_faces): if len(used) != vertex_count: _fail("unused vertex IDs are not permitted") components = _connected_components(adjacency, vertex_count) - if components != 1: _fail("surface is not connected") + if components != 1: + _fail("surface is not connected") return TopologyReport( vertex_count, len(incidence), len(quads), len(boundary), len(cycles), components, vertex_count - len(incidence) + len(quads), non_manifold, conflicts, @@ -264,7 +260,6 @@ def validate_topology(vertex_count, faces, boundary_loops=None, expected_faces=N quads = _quads(faces, vertex_count) return _topology_report(vertex_count, quads, _validate_loops(boundary_loops, vertex_count), expected_faces) - def _triangle_normal(triangle, points): return _cross_vec(_sub_vec(points[triangle[1]], points[triangle[0]]), _sub_vec(points[triangle[2]], points[triangle[0]])) def _quad_data(quad, points): @@ -283,7 +278,6 @@ def _loop_geometry(selected): area = _add_vec(area, _cross_vec(_sub_vec(point, centroid), _sub_vec(selected[(index + 1) % len(selected)], centroid))) return centroid, tuple(0.5 * value for value in area) - def port_loop_metrics(points, loop, outward_direction, adjacent_normals): points = _points(points) loop = _simple_indices(loop, len(points), "port loop") @@ -340,7 +334,6 @@ def _tagged_trace(raw, label): if not result: _fail(f"{label} must not be empty") return tuple(result) - def junction_continuity_metrics(trace_a, trace_b): first, second = _tagged_trace(trace_a, "trace A"), _tagged_trace(trace_b, "trace B") first_tags, second_tags = tuple(tag for tag, _ in first), tuple(tag for tag, _ in second) @@ -359,7 +352,6 @@ def junction_continuity_metrics(trace_a, trace_b): _fail("junction coordinate residual exceeds tolerance") return {"tag_identity": True, "opposite_trace_direction": True, "coordinate_residual": residual} - def fold_angle_degrees(normal_a, normal_b): first = _normalize_vec(_vec(normal_a, "fold normal A"), "fold normal A") second = _normalize_vec(_vec(normal_b, "fold normal B"), "fold normal B") @@ -367,7 +359,6 @@ def fold_angle_degrees(normal_a, normal_b): angle = math.acos(cosine) first_step = angle * 180.0 return first_step / _FIXED_PI - def validate_fold(normal_a, normal_b, level): level = _integer(level, "fold level") if level not in range(3): @@ -376,7 +367,6 @@ def validate_fold(normal_a, normal_b, level): if not angle < _FIXED_FOLD_LIMITS[level]: _fail(f"fold angle {angle!r} is not below {_FIXED_FOLD_LIMITS[level]!r}") return angle - def _validate_junction_traces(raw): raw = _named_mapping(raw, "junction traces", 7) result = {} @@ -387,13 +377,11 @@ def _validate_junction_traces(raw): result[name] = tuple(_tagged_trace(value, f"{name}.{side}") for side, value in zip(("A", "B"), pair)) return result - def _face_owners(raw, face_count): owners = _sequence(raw, "face_owners", _MAX_QUADS) if len(owners) != face_count or any(type(owner) is not str or not owner for owner in owners): _fail("face_owners must contain one non-empty string per face") return owners - def _boundary_normals(loops, incidence, quad_normals): result = {} for name, loop in loops.items(): @@ -406,7 +394,6 @@ def _boundary_normals(loops, incidence, quad_normals): normals.append(quad_normals[uses[0][0]]) result[name] = tuple(normals) return result - def _run_fold_gates(incidence, owners, quad_normals, level): count = 0 for uses in incidence.values(): @@ -414,7 +401,6 @@ def _run_fold_gates(incidence, owners, quad_normals, level): validate_fold(quad_normals[uses[0][0]], quad_normals[uses[1][0]], level) count += 1 return count - def _aabb(points, triangle): corners = tuple(points[index] for index in triangle) return (tuple(min(point[i] for point in corners) for i in range(3)) @@ -426,7 +412,6 @@ def _shared_edge_direction(triangle, shared): if {start, end} == shared: return start, end _fail("shared edge is absent") - def _axis_list(first, second): edges_a = tuple(_sub_vec(first[(i + 1) % 3], first[i]) for i in range(3)) edges_b = tuple(_sub_vec(second[(i + 1) % 3], second[i]) for i in range(3)) @@ -436,7 +421,6 @@ def _axis_list(first, second): + tuple(_cross_vec(a, b) for a in edges_a for b in edges_b) + tuple(_cross_vec(normal_a, edge) for edge in edges_a) + tuple(_cross_vec(normal_b, edge) for edge in edges_b)) - def _sat_disjoint(first, second): for axis in _axis_list(first, second): length = _norm_vec(axis) @@ -452,10 +436,8 @@ def _sat_disjoint(first, second): min(projections[3:]), max(projections[3:])): return True return False - def _rational(value): return Fraction(0, 1) if value == 0.0 else Fraction(*value.as_integer_ratio()) def _ray_difference(first, second): return tuple(_rational(first[i]) - _rational(second[i]) for i in range(3)) - def _active_solution(rays, subset): matrix = [[rays[index][row] for index in subset] + [Fraction(0, 1)] for row in range(3)] @@ -482,7 +464,6 @@ def _active_solution(rays, subset): or solution[2] + solution[3] <= 0): return None return tuple(solution) - def shared_one_intersects(shared, a0, a1, b0, b1): values = tuple(_vec(value, label) for value, label in ( (shared, "shared point"), (a0, "A0"), (a1, "A1"), (b0, "B0"), (b1, "B1"))) @@ -494,16 +475,13 @@ def shared_one_intersects(shared, a0, a1, b0, b1): return any(_active_solution(rays, subset) is not None for size in (2, 3, 4) for subset in itertools.combinations(range(4), size)) - def classify_shared_one(shared, a0, a1, b0, b1): return "hit" if shared_one_intersects(shared, a0, a1, b0, b1) else "point-only" - def _classify_shared_one_triangles(first, second, points): shared = next(index for index in first if index in second) a = [index for index in first if index != shared] b = [index for index in second if index != shared] return shared_one_intersects(points[shared], points[a[0]], points[a[1]], points[b[0]], points[b[1]]) - def _intersection_inputs(vertices, triangles): points = _points(vertices) faces = _indexed_rows(triangles, 3, len(points), "triangles", _MAX_TRIANGLES) @@ -514,7 +492,6 @@ def _intersection_inputs(vertices, triangles): _fail(f"normalized triangle normal degeneracy at {index}") bounds = tuple(_aabb(normalized, face) for face in faces) return faces, normalized, scale, bounds, tuple(frozenset(face) for face in faces) - def _aabb_disjoint(first, second): return any(_interval_disjoint(first[i], first[i + 3], second[i], second[i + 3]) for i in range(3)) def _pair_status(first_index, second_index, faces, normalized, bounds, face_sets): pair = (first_index, second_index) @@ -533,12 +510,21 @@ def _pair_status(first_index, second_index, faces, normalized, bounds, face_sets hit = _classify_shared_one_triangles(faces[first_index], faces[second_index], normalized) return "hit" if hit else "point-only" return "aabb-disjoint" if _aabb_disjoint(bounds[first_index], bounds[second_index]) else "candidate" - +def _record_pair_policy(triangle_count, first, second, ordinal, stage, class_counts): + expected_ordinal = (first * (2 * triangle_count - first - 1) // 2 + + second - first - 1) + if ordinal != expected_ordinal: + _fail("intersection pair coverage is not exhaustive reference order") + if stage not in _FINAL_CLASSIFICATION_STAGES: + _fail("intersection pair has an invalid classification") + class_counts[stage] += 1 def _append_candidate(result, pair, cap): if len(result) >= cap: _fail(f"AABB candidate cap exceeded: >{cap}") result.append(pair) - +def _append_bounded(result, value): + if len(result) < _MAX_DIAGNOSTIC_EVIDENCE: + result.append(value) def _collect_candidate_pairs(faces, bounds, face_sets, cap): cap = _integer(cap, "candidate cap") if cap <= 0: @@ -549,7 +535,6 @@ def _collect_candidate_pairs(faces, bounds, face_sets, cap): if _pair_status(first, second, faces, None, bounds, face_sets) == "candidate": _append_candidate(result, (first, second), cap) return tuple(result) - def _enumerate_fixture_candidates(vertices, triangles, cap): """Fixture-only cap injection. Production always uses the fixed cap.""" faces, _, _, bounds, face_sets = _intersection_inputs(vertices, triangles) @@ -557,28 +542,72 @@ def _enumerate_fixture_candidates(vertices, triangles, cap): def enumerate_broad_phase_candidates(points, triangles): faces, _, _, bounds, face_sets = _intersection_inputs(points, triangles) return _collect_candidate_pairs(faces, bounds, face_sets, _MAX_CANDIDATES) - -def intersection_diagnostics(vertices, triangles): +def intersection_diagnostics(vertices, triangles, *, include_classifications=False): + if type(include_classifications) is not bool: + _fail("include_classifications must be a boolean") faces, normalized, scale, bounds, face_sets = _intersection_inputs(vertices, triangles) - candidates, hits, classifications = [], [], [] + expected_pairs = len(faces) * (len(faces) - 1) // 2 + if include_classifications and expected_pairs > _MAX_CLASSIFICATION_DETAILS: + _fail(f"classification detail cap exceeded: {expected_pairs} > {_MAX_CLASSIFICATION_DETAILS}") + candidates, hits, nontrivial_evidence = [], [], [] + candidate_count = hit_count = 0 + first_pair = last_pair = first_hit_pair = None + classifications = [] if include_classifications else None + class_counts = {stage: 0 for stage in _FINAL_CLASSIFICATION_STAGES} + processed_pairs = 0 for first, second in itertools.combinations(range(len(faces)), 2): pair = (first, second) stage = _pair_status(first, second, faces, normalized, bounds, face_sets) if stage == "candidate": - _append_candidate(candidates, pair, _MAX_CANDIDATES) + candidate_count += 1 + if candidate_count > _MAX_CANDIDATES: + _fail(f"AABB candidate cap exceeded: >{_MAX_CANDIDATES}") + _append_bounded(candidates, pair) first_points = tuple(normalized[index] for index in faces[first]) second_points = tuple(normalized[index] for index in faces[second]) stage = "hit" if not _sat_disjoint(first_points, second_points) else "sat-disjoint" + _record_pair_policy( + len(faces), first, second, processed_pairs, stage, class_counts) if stage == "hit": - hits.append(pair) - classifications.append((pair, stage)) - return { + hit_count += 1 + if first_hit_pair is None: + first_hit_pair = pair + _append_bounded(hits, pair) + if stage != "aabb-disjoint": + _append_bounded(nontrivial_evidence, (pair, stage)) + if classifications is not None: + classifications.append((pair, stage)) + if first_pair is None: + first_pair = pair + last_pair = pair + processed_pairs += 1 + pair_policy_complete = ( + processed_pairs == expected_pairs + and first_pair == ((0, 1) if expected_pairs else None) + and last_pair == ((len(faces) - 2, len(faces) - 1) if expected_pairs else None) + and sum(class_counts.values()) == expected_pairs) + pair_policy_evidence = { + "expected_pair_count": expected_pairs, "processed_pair_count": processed_pairs, + "first_pair": first_pair, "last_pair": last_pair, + "class_counts": tuple((stage, class_counts[stage]) for stage in _FINAL_CLASSIFICATION_STAGES), + "nontrivial_pair_count": expected_pairs - class_counts["aabb-disjoint"], + "nontrivial_classifications": tuple(nontrivial_evidence), + "nontrivial_evidence_truncated": expected_pairs - class_counts["aabb-disjoint"] > len(nontrivial_evidence), + } + report = { "triangle_count": len(faces), "normalization_scale": scale, - "broad_phase_candidate_count": len(candidates), "intersection_hit_count": len(hits), - "pair_policy_complete": len(classifications) == len(faces) * (len(faces) - 1) // 2, + "pair_count": expected_pairs, + "broad_phase_candidate_count": candidate_count, "intersection_hit_count": hit_count, + "pair_policy_complete": pair_policy_complete, + "pair_policy_evidence": pair_policy_evidence, "candidate_pairs": tuple(candidates), "hit_pairs": tuple(hits), - "classifications": tuple(classifications), + "candidate_pairs_truncated": candidate_count > len(candidates), + "hit_pairs_truncated": hit_count > len(hits), + "first_hit_pair": first_hit_pair, } + if classifications is not None: + report["classifications"] = tuple(classifications) + return report def validate_geometry(vertices, quads, level, boundary_loops, port_directions, expected_faces, junction_traces, face_owners): @@ -590,6 +619,10 @@ def validate_geometry(vertices, quads, level, boundary_loops, port_directions, _fail("all production geometry selectors and gate data are required") points = _points(vertices) faces = _quads(quads, len(points)) + if level == 0 and len(points) > _MAX_BASE_CONTROLS: + _fail(f"level 0 base control cap exceeded: {len(points)} > {_MAX_BASE_CONTROLS}") + if level == 0 and len(faces) > _MAX_BASE_QUADS: + _fail(f"level 0 base quad cap exceeded: {len(faces)} > {_MAX_BASE_QUADS}") loops = _validate_loops(boundary_loops, len(points)) if len(loops) != 5: _fail("exactly 5 boundary loops are required") @@ -610,9 +643,11 @@ def validate_geometry(vertices, quads, level, boundary_loops, port_directions, or min(triangle_areas) < floor["triangle_area"] or min(quad_areas) < floor["quad_area"]): _fail("structural floor failed") - hits = intersection_diagnostics(points, triangles)["hit_pairs"] - if hits: - _fail(f"{len(hits)} triangle intersections, first pair {hits[0]}") + intersection = intersection_diagnostics(points, triangles) + hit_count = intersection["intersection_hit_count"] + if hit_count: + _fail(f"{hit_count} triangle intersections, " + f"first pair {intersection['first_hit_pair']}") port_directions = _named_mapping(port_directions, "port directions", 5) if set(port_directions) != set(loops): _fail("port directions must match boundary loops") @@ -638,12 +673,12 @@ def validate_geometry(vertices, quads, level, boundary_loops, port_directions, def intersection_candidate_threshold_records(): return tuple(dict(record) for record in _THRESHOLD_RECORDS) __all__ = [ - "D", "DEGENERACY_FLOOR", "FOLD_LIMITS_DEGREES", "I0", "INTERSECTION_TOLERANCE", - "MAX_CANDIDATES", "MAX_TRIANGLES", "MeshCorrectnessError", "PI", "S", - "STRUCTURAL_FLOORS", "T", "TopologyReport", "add", "classify_shared_one", - "cross", "dot", "enumerate_broad_phase_candidates", "fold_angle_degrees", - "intersection_candidate_threshold_records", "intersection_diagnostics", "interval_disjoint", - "junction_continuity_metrics", + "DEGENERACY_FLOOR", "FOLD_LIMITS_DEGREES", "I0", "INTERSECTION_TOLERANCE", + "MAX_CANDIDATES", "MAX_TRIANGLES", "PI", "STRUCTURAL_FLOORS", "D", + "MeshCorrectnessError", "S", "T", "TopologyReport", "add", + "classify_shared_one", "cross", "dot", "enumerate_broad_phase_candidates", + "fold_angle_degrees", "intersection_candidate_threshold_records", + "intersection_diagnostics", "interval_disjoint", "junction_continuity_metrics", "norm", "normalize", "port_loop_metrics", "shared_one_intersects", "sub", "validate_fold", "validate_geometry", "validate_port_loop", "validate_topology", ] diff --git a/experiments/owned-root-assembly-successor/prepared_projection.py b/experiments/owned-root-assembly-successor/prepared_projection.py new file mode 100644 index 0000000..6b0db20 --- /dev/null +++ b/experiments/owned-root-assembly-successor/prepared_projection.py @@ -0,0 +1,500 @@ +"""Closed section-2 source admission and standard-neutral projection.""" +import json +import math +from functools import wraps +from pathlib import Path + +import artifact_serialization as artifacts + + +class PreparedProjectionError(ValueError): + """A source, profile, or prepared-input boundary failed closed.""" +ROOT = Path(__file__).resolve().parents[2] +CONTRACT_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" +CONTRACT_PATH = ROOT / CONTRACT_ROLE +SIDECAR_PATH = ROOT / "experiments/owned-root-assembly-successor/design-contract.sha256" +SOURCE_PATH, PROFILE_TABLE_PATH = ROOT / SOURCE_ROLE, ROOT / PROFILE_ROLE +EXPECTED_CONTRACT_SHA256 = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +EXPECTED_SOURCE_SHA256 = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +EXPECTED_PROFILE_TABLE_SHA256 = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +EXPECTED_BINDING_COMPONENTS_SHA256 = "58c7ba6d4fd20135f9e93bc8b92690102287f11ae6092b9f3b82459e59375a5f" +EXPECTED_BINDINGS_SHA256 = "57ce3638fd31cca47294d8c9ddf142d783b527b18be431a5501fccda1085bc12" +EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES = 56984, 29970 +# Definition-time immutable admission commitments. Public constants remain +# inspectable, but their ordinary reassignment cannot redirect admission. +_ADMISSION = ((CONTRACT_ROLE, SOURCE_ROLE, PROFILE_ROLE), + (CONTRACT_PATH, SIDECAR_PATH, SOURCE_PATH, PROFILE_TABLE_PATH), + (EXPECTED_CONTRACT_SHA256, EXPECTED_SOURCE_SHA256, EXPECTED_PROFILE_TABLE_SHA256), + (173184, 127, EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES), + (EXPECTED_BINDING_COMPONENTS_SHA256, EXPECTED_BINDINGS_SHA256)) +_ROLES, _PATHS, _HASHES, _SIZES, _BINDING_HASHES = _ADMISSION +(_JSON_BYTES, _DECODE_JSON, _COERCE_BINARY64, _READ_FILE, _SHA256_BYTES) = ( + artifacts.canonical_json_bytes, artifacts.decode_canonical_json, + artifacts.coerce_binary64, artifacts.read_regular_file, artifacts.sha256_bytes) +_SIDECAR_CONTENT = artifacts.contract_sidecar_bytes(_HASHES[0]) +_PREPARED_SCHEMA = "owned-root-assembly-successor-prepared.v1" +_NEUTRAL_PROFILE = "standard_neutral_reference" +_ROTATION = (0.0, 0.0, 0.0, 1.0) +_AXES = ("x", "y", "z") +_BASIS_ITEMS = (("length_unit", "metre"), ("handedness", "right"), ("up", "+y"), ("forward", "+z")) +_SOURCE_DOCUMENT = "stylized_digitigrade_biped_authored_form" +_SOURCE_CONTRACT = (("family", "creature-kernel.body"), ("revision", 1)) +_SOURCE_IDENTITY = (("document", _SOURCE_DOCUMENT), ("namespace", "main")) +PARTS = (("pelvis", None), ("torso", None), ("neck", None), ("upper_arm", "left"), ("upper_arm", "right"), + ("thigh", "left"), ("thigh", "right")) +STATIONS = (("lower_pelvis", "pelvis", "form_torso_profile_lower_pelvis"), + ("upper_pelvis", "pelvis", "form_torso_profile_upper_pelvis"), + ("lower_abdomen", "torso", "form_torso_profile_lower_abdomen"), + ("waist_abdomen", "torso", "form_torso_profile_waist_abdomen"), + ("upper_abdomen", "torso", "form_torso_profile_upper_abdomen"), + ("lower_ribcage", "torso", "form_torso_profile_lower_ribcage"), + ("upper_ribcage_shoulder", "torso", "form_torso_profile_upper_ribcage_shoulder"), + ("neck_collar", "neck", "form_head_neck_profile_neck_collar"), + ("neck_upper", "neck", "form_head_neck_profile_neck_upper")) +SHOULDER_DIMS = (("start_lateral", "form_arm_profile_upper_arm_start_lateral_radius"), + ("start_up", "form_arm_profile_upper_arm_start_up_radius"), + ("start_forward", "form_arm_profile_upper_arm_start_forward_radius"), + ("shoulder_depth", "form_shoulder_depth_radius")) +HIP_DIMS = (("r_x", "form_leg_profile_thigh_start_lateral_radius"), ("r_y", "form_leg_profile_thigh_start_up_radius"), + ("r_z", "form_leg_profile_thigh_start_forward_radius")) +SHOULDER_SUMS = (("axilla", "form_axilla"), ("peak", "form_shoulder_peak"), ("arm_origin", None)) +HIP_SUMS = (("P_s", "form_leg_profile_thigh_start"),) +SIDE_CONFIGS = (("shoulders", "upper_arm", (("axilla", "form_axilla", "form_shoulder_control"), + ("peak", "form_shoulder_peak", "form_shoulder_control")), SHOULDER_DIMS), + ("hips", "thigh", (("P_s", "form_leg_profile_thigh_start", "form_leg_profile_control"),), HIP_DIMS)) +BODY_COUNTS = {"attachments": 1, "capabilities": 3, "dimensions": 153, "fields": 0, + "frames": 16, "joints": 17, "landmarks": 43, "modules": 1, + "parts": 18, "regions": 4, "sockets": 2} +SOURCE_ROW_FIELDS = {"dimensions": {"owner", "role", "value"}, "frames": {"owner", "role", "transform"}, + "landmarks": {"frame", "owner", "position", "role"}} +PROFILE_IDS = ("standard_neutral_reference", "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested") +PROFILE_DIMENSION_KEYS = frozenset(( # noqa: SIM905 -- compact frozen key universe + "arm_profile_forward arm_profile_lateral arm_profile_up arm_radius arm_shoulder body_extent_x " + "body_extent_y body_extent_z body_profile_depth body_profile_lateral foot_extent_x foot_extent_y " + "foot_extent_z foot_profile_forward foot_profile_lateral foot_profile_up hand_extent_x hand_extent_y " + "hand_extent_z head_extent_x head_extent_y head_extent_z head_profile_forward head_profile_lateral " + "head_profile_up leg_profile_forward leg_profile_lateral leg_profile_up leg_radius neck_profile_forward " + "neck_profile_lateral neck_profile_up neck_radius tail_root_end tail_root_start tail_tip_end tail_tip_start" +).split()) +_ADDRESS, _B64, _PB64 = object(), ("binary64", False), ("binary64", True) +_IDENTITY_SPEC = {"path": str, "sha256": str} +_PART_SPEC = {"address": _ADDRESS, "placement": { + "translation": ("vector", 3), "rotation_xyzw": ("vector", 4)}} +_STATION_SPEC = {"owner": _ADDRESS, "prefix": str, "C": ("vector", 3), "rL": _PB64, "rA": _PB64, "rP": _PB64} +_SHOULDER_SPEC = {field: _PB64 for field, _ in SHOULDER_DIMS} +_SHOULDER_SPEC.update({field: ("vector", 3) for field in ("axilla", "peak", "arm_origin")}) +_HIP_SPEC = {"P_s": ("vector", 3), **{field: _PB64 for field, _ in HIP_DIMS}} +_PREPARED_SPEC = { + "schema": str, "contract": _IDENTITY_SPEC, "source": _IDENTITY_SPEC, + "profile_selection": {"profile_id": str, "profile_table_path": str, "profile_table_sha256": str, + "dimensions": {key: _B64 for key in PROFILE_DIMENSION_KEYS}}, + "basis": {key: str for key, _ in _BASIS_ITEMS}, + "parts": ("list", len(PARTS), _PART_SPEC), + "stations": {name: _STATION_SPEC for name, _, _ in STATIONS}, + "shoulders": {side: _SHOULDER_SPEC for side in ("left", "right")}, + "hips": {side: _HIP_SPEC for side in ("left", "right")}, + "provenance": {"source_files": ("list", 2, {"path": str, "sha256": str, "bytes": int})}, +} +def _public_admission(function): + @wraps(function) + def guarded(*args, **kwargs): + try: + return function(*args, **kwargs) + except PreparedProjectionError: + raise + except Exception as exc: + raise PreparedProjectionError(f"{function.__name__}: malformed admission") from exc + return guarded +def _need(test, where, message): + if not test: + raise PreparedProjectionError(f"{where}: {message}") +def _obj(value, where): + _need(type(value) is dict, where, "expected object") + return value +def _keys(value, expected, where): + _obj(value, where) + valid = all(type(key) is str for key in value) and set(value) == set(expected) + _need(valid, where, "unknown, missing, or non-string field") + return value +def _text(value, where, nonempty=True): + _need(type(value) is str and (value or not nonempty), where, "expected string") + return value +def _literal(value, expected, where): _need(type(value) is type(expected) and value == expected, where, "wrong value") +def _attempt(function, args, caught, where, message, kwargs=None): + try: + return function(*args, **(kwargs or {})) + except caught as exc: + raise PreparedProjectionError(f"{where}: {message}") from exc +def _number(value, where, *, runtime=False, positive=False, wire=False): + if wire: + result = _attempt(_COERCE_BINARY64, (value,), artifacts.ArtifactSerializationError, + where, "invalid canonical binary64", {"label": where}) + elif runtime: + _need(type(value) is float, where, "expected runtime binary64 float") + result = value + else: + _need(type(value) in (int, float), where, "expected finite number") + result = _attempt(float, (value,), (OverflowError, ValueError), where, "expected finite number") + label = "positive " if positive else "" + _need(math.isfinite(result) and (not positive or result > 0.0), where, f"expected finite {label}number") + return result +def _vector(value, where, length=3, *, runtime=False, wire=False): + _need(type(value) is list and len(value) == length, where, f"expected {length}-vector") + return [_number(item, f"{where}[{i}]", runtime=runtime, wire=wire) for i, item in enumerate(value)] +def _pairs(items): + result = dict(items) + if len(result) != len(items): + raise ValueError("duplicate JSON key") + return result +def _constant(token): raise ValueError(f"non-finite JSON constant {token}") +def _decode_source_json(raw, where): + _need(type(raw) is bytes, where, "expected raw bytes") + caught = (UnicodeDecodeError, json.JSONDecodeError, RecursionError, TypeError, ValueError) + text = _attempt(raw.decode, ("utf-8",), caught, where, "source is not strict UTF-8 JSON") + value = _attempt(json.loads, (text,), caught, where, "source is not strict UTF-8 JSON", + {"object_pairs_hook": _pairs, "parse_constant": _constant}) + return _obj(value, where), _SHA256_BYTES(raw) +def _read(path, where): return _attempt(_READ_FILE, (path,), (OSError, TypeError, ValueError), where, "read failed") +def _fixed_path(path, expected, where): + candidate = _attempt(Path, (path,), (TypeError, ValueError), where, "invalid path").absolute() + _need(candidate == expected, where, "path is not the fixed canonical path") + _need(not candidate.is_symlink() and candidate.is_file(), where, "expected regular file") + return candidate +@_public_admission +def normalize_source_address(raw): + value = _keys(raw, {"namespace", "anchors", "kind", "role"}, "source address") + for key in ("namespace", "kind", "role"): + _text(value[key], f"source address.{key}") + anchors = value["anchors"] + _need(type(anchors) is list and all(type(item) is str for item in anchors), "source anchors", "invalid array") + return [value["namespace"], list(anchors), value["kind"], value["role"]] +def _address(raw): + value = normalize_source_address(raw) + return value[0], tuple(value[1]), value[2], value[3] +def _runtime_address(value, where): + _need(type(value) is list and len(value) == 4, where, "expected normalized address") + namespace, anchors, kind, role = value + _text(namespace, f"{where}[0]") + _need(type(anchors) is list and all(type(item) is str for item in anchors), f"{where}[1]", "invalid anchors") + _text(kind, f"{where}[2]") + _text(role, f"{where}[3]") + return namespace, tuple(anchors), kind, role +def _a(role, side=None): return "main", () if side is None else (side,), "part", role +def _address_json(value): return [value[0], list(value[1]), value[2], value[3]] +def _add(left, right): return [left[index] + right[index] for index in range(3)] +def _source_transform(raw, where, *, zero_translation=False): + transform = _keys(raw, {"translation", "rotation_xyzw"}, where) + translation = _vector(transform["translation"], f"{where}.translation") + rotation = _vector(transform["rotation_xyzw"], f"{where}.rotation_xyzw", 4) + _need(tuple(rotation) == _ROTATION, where, "rotation must be exact identity") + _need(not zero_translation or translation == [0.0, 0.0, 0.0], where, "frame translation must be zero") + return translation +def _validate_selector_rows(rows, name): + selectors, frame_references = {}, set() + for index, raw in enumerate(rows): + where = f"body.{name}[{index}]" + row = _keys(raw, SOURCE_ROW_FIELDS[name], where) + owner = _address(row["owner"]) + role = _text(row["role"], f"{where}.role") + _need((owner, role) not in selectors, where, "duplicate selector") + selectors[owner, role] = row, index + if name == "dimensions": + _number(row["value"], f"{where}.value", positive=True) + elif name == "frames": + _source_transform(row["transform"], f"{where}.transform", zero_translation=True) + else: + frame = _keys(row["frame"], {"owner", "role"}, f"{where}.frame") + frame_owner = _address(frame["owner"]) + frame_role = _text(frame["role"], f"{where}.frame.role") + _need(frame_owner == owner, f"{where}.frame", "wrong frame owner") + frame_references.add((frame_owner, frame_role)) + _vector(row["position"], f"{where}.position") + return selectors, frame_references +def _fixed_scalars(value, items, where): + record = _keys(value, {key for key, _ in items}, where) + for key, expected in items: + _literal(record[key], expected, f"{where}.{key}") +def _validate_source_document(source): + _keys(source, {"contract", "source", "basis", "profiles", "body", "extensions"}, "source") + _fixed_scalars(source["contract"], _SOURCE_CONTRACT, "source.contract") + identity = _obj(source["source"], "source.source") + _keys(identity, {"document", "namespace", "dependencies"}, "source.source") + for key, expected in _SOURCE_IDENTITY: + _literal(identity[key], expected, f"source.source.{key}") + _need(type(identity["dependencies"]) is list and not identity["dependencies"], "source.dependencies", "not empty") + _fixed_scalars(source["basis"], _BASIS_ITEMS, "source.basis") + _fixed_scalars(source["profiles"], (("semantic_numeric", "ck.numeric-frame.r1"),), "source.profiles") + _need(type(source["extensions"]) is list and not source["extensions"], "source.extensions", "not empty") + body = _obj(source["body"], "source.body") + _keys(body, BODY_COUNTS, "source.body") + valid_counts = all(type(body[name]) is list and len(body[name]) == count for name, count in BODY_COUNTS.items()) + _need(valid_counts, "source.body", "wrong required record counts") + parts = {} + for index, raw in enumerate(body["parts"]): + where = f"body.parts[{index}]" + row = _keys(raw, {"address", "containment", "placement"}, where) + address = _address(row["address"]) + _need(address not in parts, where, "duplicate part address") + _source_transform(row["placement"], f"{where}.placement") + _obj(row["containment"], f"{where}.containment") + parts[address] = row, index + dimensions, _ = _validate_selector_rows(body["dimensions"], "dimensions") + frames, _ = _validate_selector_rows(body["frames"], "frames") + landmarks, references = _validate_selector_rows(body["landmarks"], "landmarks") + _need(references <= set(frames), "source.body.landmarks", "missing referenced frame") + return parts, frames, landmarks, dimensions +def _admit_source_bytes(raw): + source, digest = _decode_source_json(raw, "source") + _need(len(raw) == _SIZES[2] and digest == _HASHES[1], "source", "source identity mismatch") + parts, frames, landmarks, dimensions = _validate_source_document(source) + return {"parts": parts, "frames": frames, "landmarks": landmarks, + "dimensions": dimensions, "bytes": raw, "sha256": digest} +def _validate_profile_table(table): + _keys(table, {"base_source", "canonicalization", "format", "profiles", "transform"}, "profile table") + _literal(table["format"], "creature-kernel.disposable-structural-profile-candidates.v1", "profile table.format") + _fixed_scalars(table["base_source"], (("document", _SOURCE_DOCUMENT), ("namespace", "main"), + ("path", _ROLES[1]), ("sha256", _HASHES[1]), + ), "profile table.base_source") + profiles = table["profiles"] + _need(type(profiles) is list and len(profiles) == len(PROFILE_IDS), "profile profiles", "wrong count") + for index, raw in enumerate(profiles): + where = f"profile table.profiles[{index}]" + row = _keys(raw, {"dimension_scales", "id", "label", "part_placements"}, where) + _literal(row["id"], PROFILE_IDS[index], f"{where}.id") + _text(row["label"], f"{where}.label") + scales = _obj(row["dimension_scales"], f"{where}.dimension_scales") + _keys(scales, PROFILE_DIMENSION_KEYS, f"{where}.dimension_scales") + _need(all(type(number) is int and number > 0 for number in scales.values()), where, "invalid profile scale") + _need(index != 0 or all(number == 1000 for number in scales.values()), where, "neutral scales differ") + _obj(row["part_placements"], f"{where}.part_placements") + return profiles[0] +def _admit_profile_bytes(raw): + table, digest = _decode_source_json(raw, "profile table") + _need(len(raw) == _SIZES[3] and digest == _HASHES[2], "profile table", "profile identity mismatch") + return _validate_profile_table(table), raw, digest +def _verify_contract(path=_PATHS[0]): + contract = _fixed_path(path, _PATHS[0], "contract path") + sidecar = _fixed_path(_PATHS[1], _PATHS[1], "contract sidecar path") + contract_raw, sidecar_raw = _read(contract, "contract"), _read(sidecar, "contract sidecar") + _need(len(contract_raw) == _SIZES[0] and _SHA256_BYTES(contract_raw) == _HASHES[0], "contract", "identity mismatch") + _need(len(sidecar_raw) == _SIZES[1] and sidecar_raw == _SIDECAR_CONTENT, "contract sidecar", "identity mismatch") +def _fixed_inputs(source_path, contract_path, profile_path): + _verify_contract(contract_path) + source = _fixed_path(source_path, _PATHS[2], "source path") + profile = _fixed_path(profile_path, _PATHS[3], "profile table path") + admission = _admit_source_bytes(_read(source, "source")) + selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")) + return admission, selected, raw, digest +def _select(rows, owner, role, name): + match = rows.get((owner, role)) + _need(match is not None, f"body.{name}.{role}", "missing required record") + return match +def _world(parts, chain): + _need(chain and all(owner in parts for owner in chain), "world translation", "invalid chain") + result = [0.0, 0.0, 0.0] + for owner in chain: + placement = parts[owner][0]["placement"] + result = _add(result, _vector(placement["translation"], "part placement.translation")) + return result +def _select_position(admission, owner, role, frame_role, worlds): + row, index = _select(admission["landmarks"], owner, role, "landmarks") + frame = _keys(row["frame"], {"owner", "role"}, f"body.landmarks[{index}].frame") + _need(_address(frame["owner"]) == owner and frame["role"] == frame_role, + f"body.landmarks[{index}].frame", "wrong landmark frame") + _select(admission["frames"], owner, frame_role, "frames") + position = _vector(row["position"], f"body.landmarks[{index}].position") + return _add(worlds[owner], position) +def _dimension(admission, owner, role): + row, index = _select(admission["dimensions"], owner, role, "dimensions") + return _number(row["value"], f"body.dimensions[{index}].value", positive=True), index +def _source_files(source_digest, source_size, profile_digest, profile_size): + records = ({"path": _ROLES[1], "sha256": source_digest, "bytes": source_size}, + {"path": _ROLES[2], "sha256": profile_digest, "bytes": profile_size}) + return sorted(records, key=lambda record: record["path"].encode("utf-8")) +def _identity(path, digest): return {"path": path, "sha256": digest} +def _walk(value, spec, where, *, wire): + if spec is str: + return _text(value, where, nonempty=False) + if spec is int: + _need(type(value) is int, where, "expected integer") + return value + if spec is _ADDRESS: + _runtime_address(value, where) + return value + if type(spec) is dict: + record = _keys(value, spec, where) + for field, child_spec in spec.items(): + converted = _walk(record[field], child_spec, f"{where}.{field}", wire=wire) + if wire: + record[field] = converted + return record + kind, argument, *tail = spec + if kind == "binary64": + return _number(value, where, runtime=not wire, positive=argument and not wire, wire=wire) + if kind == "vector": + return _vector(value, where, argument, runtime=not wire, wire=wire) + _need(kind == "list" and type(value) is list and len(value) == argument, where, "wrong list shape") + for index, item in enumerate(value): + converted = _walk(item, tail[0], f"{where}[{index}]", wire=wire) + if wire: + value[index] = converted + return value +def _validate_prepared_structure(prepared, *, wire=False): return _walk(prepared, _PREPARED_SPEC, "prepared", wire=wire) +def _validate_prepared_shape(prepared): return _validate_prepared_structure(prepared) +def _chains(): + pelvis, torso, neck = _a("pelvis"), _a("torso"), _a("neck") + result = {pelvis: (pelvis,), torso: (pelvis, torso), neck: (pelvis, torso, neck)} + for side in ("left", "right"): + result[_a("upper_arm", side)] = (pelvis, torso, _a("upper_arm", side)) + result[_a("thigh", side)] = (pelvis, _a("thigh", side)) + return result +def _part_output(parts, owner): + value = _vector(parts[owner][0]["placement"]["translation"], "part placement.translation") + return {"address": _address_json(owner), "placement": {"translation": value, "rotation_xyzw": list(_ROTATION)}} +def _station_suffixes(role): + return (("lateral_radius", "forward_radius", "forward_radius") if role == "neck" + else ("lateral_radius", "anterior_radius", "posterior_radius")) +def _station_output(admission, worlds, role, prefix): + owner = _a(role) + frame = "form_head_neck_profile_control" if role == "neck" else "form_torso_profile_control" + radii = [_dimension(admission, owner, f"{prefix}_{suffix}")[0] + for suffix in _station_suffixes(role)] + return {"owner": _address_json(owner), "prefix": prefix, + "C": _select_position(admission, owner, prefix, frame, worlds), + "rL": radii[0], "rA": radii[1], "rP": radii[2]} +def _side_output(admission, worlds, side, part_role, positions, dimensions): + owner = _a(part_role, side) + result = {field: _select_position(admission, owner, role, frame, worlds) + for field, role, frame in positions} + if part_role == "upper_arm": + result["arm_origin"] = list(worlds[owner]) + for field, role in dimensions: + result[field] = _dimension(admission, owner, role)[0] + return result +def _build_prepared(admission, profile, profile_raw, profile_digest): + parts, chains = admission["parts"], _chains() + worlds = {owner: _world(parts, chain) for owner, chain in chains.items()} + sides = { + group: {side: _side_output(admission, worlds, side, role, positions, dimensions) + for side in ("left", "right")} + for group, role, positions, dimensions in SIDE_CONFIGS + } + prepared = { + "schema": _PREPARED_SCHEMA, + "contract": _identity(_ROLES[0], _HASHES[0]), + "source": _identity(_ROLES[1], _HASHES[1]), + "profile_selection": { + "profile_id": _NEUTRAL_PROFILE, "profile_table_path": _ROLES[2], + "profile_table_sha256": profile_digest, + "dimensions": {key: float(number) for key, number in profile["dimension_scales"].items()}, + }, + "basis": dict(_BASIS_ITEMS), + "parts": [_part_output(parts, _a(role, side)) for role, side in PARTS], + "stations": {n: _station_output(admission, worlds, r, p) for n, r, p in STATIONS}, + "shoulders": sides["shoulders"], + "hips": sides["hips"], + "provenance": {"source_files": _source_files( + admission["sha256"], len(admission["bytes"]), profile_digest, len(profile_raw))}, + } + return _validate_prepared_shape(prepared) +@_public_admission +def validate_prepared(prepared): + """Admit only the projection freshly derived from the fixed files.""" + value = _validate_prepared_shape(prepared) + expected = _build_prepared(*_fixed_inputs(_PATHS[2], _PATHS[0], _PATHS[3])) + _need(_JSON_BYTES(value) == _JSON_BYTES(expected), "prepared", "values do not match fixed projection") + return value +@_public_admission +def admit_prepared_bytes(raw): + """Decode and admit exact canonical prepared bytes with schema-aware floats.""" + _need(type(raw) is bytes, "prepared bytes", "expected bytes") + decoded = _attempt(_DECODE_JSON, (raw,), (artifacts.ArtifactSerializationError, RecursionError), + "prepared bytes", "invalid canonical JSON") + value = _validate_prepared_structure(decoded, wire=True) + _need(_JSON_BYTES(value) == raw, "prepared bytes", "coercion changed canonical bytes") + return validate_prepared(value) +@_public_admission +def prepare_standard_neutral(source_path=_PATHS[2], *, contract_path=_PATHS[0], profile_table_path=_PATHS[3]): + """Admit fixed inputs and return the exact standard-neutral object.""" + return _build_prepared(*_fixed_inputs(source_path, contract_path, profile_table_path)) +def _pointer(kind, index, axis=None): + if kind in {"part", "landmark"}: + _need(axis in range(3), "source pointer", "invalid axis") + path = "parts" if kind == "part" else "landmarks" + field = "placement/translation" if kind == "part" else "position" + return f"/body/{path}/{index}/{field}/{axis}" + _need(kind == "dimension" and axis is None, "source pointer", "invalid pointer kind") + return f"/body/dimensions/{index}/value" +def _bind(component, derivation, addresses, pointers): + addresses = sorted(set(addresses), key=lambda item: _JSON_BYTES(_address_json(item))) + pointers = sorted(set(pointers), key=str.encode) + _need(addresses and pointers, "source binding", "empty binding") + return {"prepared_component": component, "derivation_id": derivation, + "source_addresses": [_address_json(item) for item in addresses], + "source_pointers": pointers} +def _validate_binding_records(records): + _need(type(records) is list and len(records) == 92, "source bindings", "expected 92 records") + components = [] + for index, raw in enumerate(records): + where = f"source bindings[{index}]" + row = _keys(raw, {"prepared_component", "derivation_id", "source_addresses", "source_pointers"}, where) + components.append(_text(row["prepared_component"], f"{where}.prepared_component")) + _text(row["derivation_id"], f"{where}.derivation_id") + addresses, pointers = row["source_addresses"], row["source_pointers"] + _need(type(addresses) is list and addresses, where, "expected source addresses") + _need(type(pointers) is list and pointers, where, "expected source pointers") + for address_index, address in enumerate(addresses): + _runtime_address(address, f"{where}.source_addresses[{address_index}]") + for pointer_index, pointer in enumerate(pointers): + _text(pointer, f"{where}.source_pointers[{pointer_index}]") + _need(len(set(components)) == 92 and components == sorted(components, key=str.encode), + "source bindings", "wrong component order or uniqueness") + _need(canonical_json_sha256(components) == _BINDING_HASHES[0], "source bindings", "component universe mismatch") + _need(canonical_json_sha256(records) == _BINDING_HASHES[1], "source bindings", "mapping mismatch") + return records +def _append_sum(bindings, admission, parts, chains, component, owner, landmark_role): + chain, landmark_index = chains[owner], None + if landmark_role is not None: + landmark_index = _select(admission["landmarks"], owner, landmark_role, "landmarks")[1] + derivation = ("source.world-landmark-axis-sum.v1" if landmark_role + else "source.world-placement-axis-sum.v1") + for axis, name in enumerate(_AXES): + pointers = [_pointer("part", parts[item][1], axis) for item in chain] + if landmark_index is not None: + pointers.append(_pointer("landmark", landmark_index, axis)) + bindings.append(_bind(f"{component}.{name}", derivation, chain, pointers)) +def _append_group(bindings, admission, parts, chains, prefix, owner, sums, dimensions): + for field, landmark in sums: + _append_sum(bindings, admission, parts, chains, f"{prefix}.{field}", owner, landmark) + for field, role in dimensions: + _, index = _dimension(admission, owner, role) + bindings.append(_bind(f"{prefix}.{field}", "source.dimension-value.v1", + (owner,), (_pointer("dimension", index),))) +@_public_admission +def source_binding_records(source_path=_PATHS[2], *, contract_path=_PATHS[0], profile_table_path=_PATHS[3]): + admission, _, _, _ = _fixed_inputs(source_path, contract_path, profile_table_path) + parts, bindings, chains = admission["parts"], [], _chains() + for name, role, prefix in STATIONS: + owner = _a(role) + dimensions = tuple((field, f"{prefix}_{suffix}") + for field, suffix in zip(("rL", "rA", "rP"), _station_suffixes(role))) + _append_group(bindings, admission, parts, chains, f"stations.{name}", owner, (("C", prefix),), dimensions) + for side in ("left", "right"): + _append_group(bindings, admission, parts, chains, f"shoulders.{side}", + _a("upper_arm", side), SHOULDER_SUMS, SHOULDER_DIMS) + _append_group(bindings, admission, parts, chains, f"hips.{side}", _a("thigh", side), HIP_SUMS, HIP_DIMS) + ordered = sorted(bindings, key=lambda item: item["prepared_component"].encode("utf-8")) + return _validate_binding_records(ordered) +build_source_binding_records = source_binding_records +canonical_json_bytes = _JSON_BYTES +def canonical_json_sha256(value): return _SHA256_BYTES(_JSON_BYTES(value)) +__all__ = [ + "EXPECTED_CONTRACT_SHA256", "EXPECTED_PROFILE_TABLE_SHA256", + "EXPECTED_SOURCE_SHA256", "PreparedProjectionError", + "admit_prepared_bytes", "build_source_binding_records", "canonical_json_bytes", + "canonical_json_sha256", "normalize_source_address", + "prepare_standard_neutral", "source_binding_records", "validate_prepared", +] diff --git a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py index aa39eee..1318d75 100644 --- a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py @@ -1,14 +1,14 @@ from __future__ import annotations import math -from pathlib import Path import sys import unittest - +from importlib import import_module +from pathlib import Path PACKAGE = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PACKAGE)) -import mesh_correctness as mesh # noqa: E402 +mesh = import_module("mesh_correctness") P0 = float.fromhex("0x0.0p+0") @@ -41,6 +41,26 @@ def _negative_zero(point): return tuple(math.copysign(0.0, -1.0) if value == 0.0 else value for value in point) +def _count_fixture(quad_count, control_count=128): + points = tuple((float(index), 0.0, 0.0) for index in range(control_count)) + faces = [] + for first in range(1, control_count): + for second in range(first + 1, control_count): + for third in range(second + 1, control_count): + faces.append((0, first, second, third)) + if len(faces) == quad_count: + return points, tuple(faces) + raise AssertionError("fixture does not have enough unique quads") + + +def _assert_reaches_boundary_gate(test_case, level, points, faces): + with test_case.assertRaisesRegex(ValueError, "exactly 5 boundary loops"): + mesh.validate_geometry( + points, faces, level, {"only": (0, 1, 2)}, {}, faces, {}, + ("owner",) * len(faces), + ) + + class _CoercibleFloat: def __float__(self): return 1.0 @@ -193,13 +213,13 @@ def test_shared_one_rejects_zero_ray(self): def test_coordinate_and_scalar_admission_is_exact_python_float(self): for value in (1, "1", True, _CoercibleFloat()): - with self.subTest(value=type(value).__name__): - with self.assertRaisesRegex(ValueError, "finite binary64"): - mesh.interval_disjoint(value, 0.0, 2.0, 3.0) + with self.subTest(value=type(value).__name__), self.assertRaisesRegex( + ValueError, "finite binary64"): + mesh.interval_disjoint(value, 0.0, 2.0, 3.0) for value in (1, "1", True, _CoercibleFloat()): - with self.subTest(vector_value=type(value).__name__): - with self.assertRaisesRegex(ValueError, "finite binary64"): - mesh.norm((value, 0.0, 0.0)) + with self.subTest(vector_value=type(value).__name__), self.assertRaisesRegex( + ValueError, "finite binary64"): + mesh.norm((value, 0.0, 0.0)) def test_rows_require_exact_bounded_sequences_before_traversal(self): points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) @@ -210,14 +230,14 @@ def exploding_generator(): for rows in ({0: (0, 1, 2)}, {(0, 1, 2)}, range(1), _ListSubclass([(0, 1, 2)]), exploding_generator()): - with self.subTest(rows=type(rows).__name__): - with self.assertRaisesRegex(ValueError, "exact list or tuple"): - mesh.intersection_diagnostics(points, rows) + with self.subTest(rows=type(rows).__name__), self.assertRaisesRegex( + ValueError, "exact list or tuple"): + mesh.intersection_diagnostics(points, rows) for row in ({0: 0, 1: 1, 2: 2}, {0, 1, 2}, range(3), exploding_generator()): - with self.subTest(row=type(row).__name__): - with self.assertRaisesRegex(ValueError, "exact list or tuple"): - mesh.intersection_diagnostics(points, (row,)) + with self.subTest(row=type(row).__name__), self.assertRaisesRegex( + ValueError, "exact list or tuple"): + mesh.intersection_diagnostics(points, (row,)) with self.assertRaisesRegex(ValueError, "triangle cap"): mesh.intersection_diagnostics(points, [object()] * 4097) with self.assertRaisesRegex(ValueError, "quad cap"): @@ -253,9 +273,9 @@ def test_topology_rejects_duplicate_and_reversed_duplicate_quads(self): duplicates = (self.faces[0], tuple(reversed(self.faces[0])), self.faces[0][1:] + self.faces[0][:1]) for duplicate in duplicates: - with self.subTest(duplicate=duplicate): - with self.assertRaisesRegex(ValueError, "duplicate quad"): - mesh.validate_topology(8, self.faces + (duplicate,)) + with self.subTest(duplicate=duplicate), self.assertRaisesRegex( + ValueError, "duplicate quad"): + mesh.validate_topology(8, self.faces + (duplicate,)) def test_clearance_semantics_are_owned_by_anatomy(self): self.assertFalse(hasattr(mesh, "boundary_clearance_ratios")) @@ -319,6 +339,32 @@ def test_production_geometry_requires_all_selectors_and_gate_data(self): mesh.validate_geometry(self.points, self.faces, 0, None, None, None, None, None) +class GeometryCountTests(unittest.TestCase): + def test_level_zero_count_boundaries_reach_the_next_gate(self): + points, faces = _count_fixture(120, 128) + _assert_reaches_boundary_gate(self, 0, points, faces) + + def test_level_zero_count_overruns_fail_closed(self): + points, faces = _count_fixture(1, 129) + with self.assertRaisesRegex(ValueError, "base control cap"): + mesh.validate_geometry( + points, faces, 0, {"only": (0, 1, 2)}, {}, faces, {}, + ("owner",), + ) + points, faces = _count_fixture(121, 128) + with self.assertRaisesRegex(ValueError, "base quad cap"): + mesh.validate_geometry( + points, faces, 0, {"only": (0, 1, 2)}, {}, faces, {}, + ("owner",) * len(faces), + ) + + def test_subdivision_quad_counts_are_not_subject_to_base_cap(self): + for level, quad_count in ((1, 416), (2, 1664)): + with self.subTest(level=level): + points, faces = _count_fixture(quad_count) + _assert_reaches_boundary_gate(self, level, points, faces) + + class IntegratedGeometryTests(unittest.TestCase): def setUp(self): self.inputs, self.metadata, self.vertex_ids = _integrated_fixture() @@ -400,7 +446,8 @@ def test_each_of_seven_junction_residuals_fails_in_production(self): class ProductionIntersectionFixtureTests(unittest.TestCase): def _assert_pair(self, name, points_a, points_b, expected, stage): points, triangles = _pair(points_a, points_b) - report = mesh.intersection_diagnostics(points, triangles) + report = mesh.intersection_diagnostics( + points, triangles, include_classifications=True) self.assertTrue(report["pair_policy_complete"], name) self.assertEqual(report["classifications"], (((0, 1), stage),), name) actual = "hit" if report["intersection_hit_count"] else "point-only" @@ -449,7 +496,8 @@ def test_contract_fixture_matrix(self): a[1], a[2] = a[2], a[1] if suffix[3] == "1": b[1], b[2] = b[2], b[1] - report = mesh.intersection_diagnostics(base_points, (tuple(a), tuple(b))) + report = mesh.intersection_diagnostics( + base_points, (tuple(a), tuple(b)), include_classifications=True) self.assertTrue(report["pair_policy_complete"], f"{name}.{suffix}") self.assertEqual(report["classifications"], (((0, 1), expected),), f"{name}.{suffix}") actual = "hit" if report["intersection_hit_count"] else "point-only" @@ -494,7 +542,13 @@ def test_contract_fixture_matrix(self): executions += 2 valid_shared2 = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0)) - self.assertEqual(mesh.intersection_diagnostics(valid_shared2, ((0, 1, 2), (1, 0, 3)))["classifications"], (( (0, 1), "excluded-adjacent"),)) + self.assertEqual( + mesh.intersection_diagnostics( + valid_shared2, ((0, 1, 2), (1, 0, 3)), + include_classifications=True, + )["classifications"], + (((0, 1), "excluded-adjacent"),), + ) executions += 1 with self.assertRaisesRegex(ValueError, "shared-two"): mesh.intersection_diagnostics(valid_shared2, ((0, 1, 2), (0, 1, 3))) @@ -513,11 +567,34 @@ def test_contract_fixture_matrix(self): cap_report = mesh.intersection_diagnostics(tuple(cap_points), tuple(cap_triangles)) self.assertEqual((cap_report["triangle_count"], cap_report["broad_phase_candidate_count"]), (4096, 0)) pair_count = 4096 * 4095 // 2 - self.assertEqual(len(cap_report["classifications"]), pair_count) - self.assertEqual(cap_report["classifications"][0], ((0, 1), "aabb-disjoint")) - self.assertEqual(cap_report["classifications"][-1], ((4094, 4095), "aabb-disjoint")) - self.assertTrue(all(stage == "aabb-disjoint" for _, stage in cap_report["classifications"])) + evidence = cap_report["pair_policy_evidence"] + self.assertEqual(cap_report["pair_count"], pair_count) + self.assertEqual( + (evidence["expected_pair_count"], evidence["processed_pair_count"]), + (pair_count, pair_count), + ) + self.assertEqual( + (evidence["first_pair"], evidence["last_pair"]), + ((0, 1), (4094, 4095)), + ) + self.assertEqual( + evidence["class_counts"], + (("aabb-disjoint", pair_count), ("sat-disjoint", 0), + ("hit", 0), ("point-only", 0), ("excluded-adjacent", 0)), + ) + self.assertEqual(evidence["nontrivial_pair_count"], 0) + self.assertEqual(evidence["nontrivial_classifications"], ()) + self.assertFalse(evidence["nontrivial_evidence_truncated"]) + self.assertEqual(cap_report["candidate_pairs"], ()) + self.assertEqual(cap_report["hit_pairs"], ()) + self.assertFalse(cap_report["candidate_pairs_truncated"]) + self.assertFalse(cap_report["hit_pairs_truncated"]) + self.assertIsNone(cap_report["first_hit_pair"]) + self.assertNotIn("classifications", cap_report) self.assertTrue(cap_report["pair_policy_complete"]) + with self.assertRaisesRegex(ValueError, "classification detail cap"): + mesh.intersection_diagnostics( + tuple(cap_points), tuple(cap_triangles), include_classifications=True) executions += 1 with self.assertRaisesRegex(ValueError, "triangle cap"): mesh.intersection_diagnostics(tuple(cap_points) + ((0.0, 0.0, 0.0), @@ -529,9 +606,14 @@ def test_contract_fixture_matrix(self): (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))) candidate_triangles = tuple((3 * row, 3 * row + 1, 3 * row + 2) for row in range(3)) - boundary_report = mesh.intersection_diagnostics(candidate_points, candidate_triangles) + boundary_report = mesh.intersection_diagnostics( + candidate_points, candidate_triangles, include_classifications=True) self.assertEqual(boundary_report["candidate_pairs"], ((0, 1), (0, 2), (1, 2))) self.assertEqual(boundary_report["intersection_hit_count"], 3) + self.assertEqual(boundary_report["hit_pairs"], ((0, 1), (0, 2), (1, 2))) + self.assertEqual(boundary_report["first_hit_pair"], (0, 1)) + self.assertFalse(boundary_report["candidate_pairs_truncated"]) + self.assertFalse(boundary_report["hit_pairs_truncated"]) self.assertEqual( boundary_report["classifications"], (((0, 1), "hit"), ((0, 2), "hit"), ((1, 2), "hit")), @@ -546,6 +628,25 @@ def test_contract_fixture_matrix(self): executions += 1 self.assertEqual(executions, 105) + def test_all_hit_diagnostics_keep_exact_counts_and_bounded_pair_evidence(self): + triangle = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + points = tuple(point for _ in range(100) for point in triangle) + triangles = tuple((3 * row, 3 * row + 1, 3 * row + 2) for row in range(100)) + report = mesh.intersection_diagnostics(points, triangles) + pair_count = 100 * 99 // 2 + + self.assertEqual(report["pair_count"], pair_count) + self.assertEqual(report["broad_phase_candidate_count"], pair_count) + self.assertEqual(report["intersection_hit_count"], pair_count) + self.assertEqual(report["first_hit_pair"], (0, 1)) + self.assertEqual(len(report["candidate_pairs"]), 64) + self.assertEqual(len(report["hit_pairs"]), 64) + self.assertTrue(report["candidate_pairs_truncated"]) + self.assertTrue(report["hit_pairs_truncated"]) + self.assertEqual(report["candidate_pairs"], report["hit_pairs"]) + self.assertTrue(report["pair_policy_complete"]) + self.assertNotIn("classifications", report) + def test_candidate_cap_fixture_helper_is_local_and_deterministic(self): points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), diff --git a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py new file mode 100644 index 0000000..9d1e56d --- /dev/null +++ b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py @@ -0,0 +1,460 @@ +# ruff: noqa: SIM905 +from __future__ import annotations + +import copy +import hashlib +import json +import runpy +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +PACKAGE = Path(__file__).resolve().parents[1] +REPOSITORY = PACKAGE.parents[1] +SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_TABLE = REPOSITORY / "experiments/current-form-surface-preview/structural_profile_candidates.json" +CONTRACT = PACKAGE / "design-contract.md" +SIDECAR = PACKAGE / "design-contract.sha256" +CONTRACT_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" +CONTRACT_HASH = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +SOURCE_HASH = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +PROFILE_HASH = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +COMPONENTS_HASH = "58c7ba6d4fd20135f9e93bc8b92690102287f11ae6092b9f3b82459e59375a5f" +BINDINGS_HASH = "57ce3638fd31cca47294d8c9ddf142d783b527b18be431a5501fccda1085bc12" +SIDECAR_BYTES = (b"3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490 " + b"experiments/owned-root-assembly-successor/design-contract.md\n") +sys.path.insert(0, str(PACKAGE)) + +import artifact_serialization as artifacts +import prepared_projection as projection +from prepared_projection import ( + PreparedProjectionError, + _admit_profile_bytes, + _admit_source_bytes, + _validate_binding_records, + _validate_profile_table, + _validate_source_document, + admit_prepared_bytes, + build_source_binding_records, + canonical_json_bytes, + canonical_json_sha256, + normalize_source_address, + prepare_standard_neutral, + source_binding_records, + validate_prepared, +) + +PROFILE_DIMENSION_KEYS = frozenset(""" +arm_profile_forward arm_profile_lateral arm_profile_up arm_radius arm_shoulder +body_extent_x body_extent_y body_extent_z body_profile_depth body_profile_lateral +foot_extent_x foot_extent_y foot_extent_z foot_profile_forward foot_profile_lateral +foot_profile_up hand_extent_x hand_extent_y hand_extent_z head_extent_x head_extent_y +head_extent_z head_profile_forward head_profile_lateral head_profile_up +leg_profile_forward leg_profile_lateral leg_profile_up leg_radius neck_profile_forward +neck_profile_lateral neck_profile_up neck_radius tail_root_end tail_root_start +tail_tip_end tail_tip_start +""".split()) +def _address(role: str, side: str | None = None) -> list[object]: + return ["main", [] if side is None else [side], "part", role] +def _mutated(value, path, replacement): + candidate = copy.deepcopy(value) + target = candidate + for key in path[:-1]: + target = target[key] + target[path[-1]] = replacement + return candidate +class _Explosive: + def __eq__(self, other): + raise RuntimeError("comparison escaped") + def __hash__(self): + raise RuntimeError("hash escaped") + def __fspath__(self): + raise RuntimeError("path conversion escaped") +PART_ADDRESS_BY_INDEX = { + 0: _address("pelvis"), 1: _address("torso"), 2: _address("neck"), + 4: _address("upper_arm", "left"), 7: _address("upper_arm", "right"), + 10: _address("thigh", "left"), 13: _address("thigh", "right"), +} +def _expected_world_records(component, chain, landmark): + derivation = ("source.world-placement-axis-sum.v1" if landmark is None + else "source.world-landmark-axis-sum.v1") + addresses = sorted((PART_ADDRESS_BY_INDEX[index] for index in chain), key=canonical_json_bytes) + result = [] + for axis in range(3): + pointers = [f"/body/parts/{index}/placement/translation/{axis}" for index in chain] + if landmark is not None: + pointers.append(f"/body/landmarks/{landmark}/position/{axis}") + result.append({ + "prepared_component": f"{component}.{'xyz'[axis]}", + "derivation_id": derivation, + "source_addresses": addresses, + "source_pointers": sorted(pointers), + }) + return result +def _expected_dimension(component, owner, index): + return { + "prepared_component": component, + "derivation_id": "source.dimension-value.v1", + "source_addresses": [PART_ADDRESS_BY_INDEX[owner]], + "source_pointers": [f"/body/dimensions/{index}/value"], + } +def _expected_bindings(): + records = [] + stations = (("lower_pelvis", (0,), 24, 0, (6, 7, 8)), + ("upper_pelvis", (0,), 25, 0, (9, 10, 11)), + ("lower_abdomen", (0, 1), 26, 1, (12, 13, 14)), + ("waist_abdomen", (0, 1), 27, 1, (15, 16, 17)), + ("upper_abdomen", (0, 1), 28, 1, (18, 19, 20)), + ("lower_ribcage", (0, 1), 29, 1, (21, 22, 23)), + ("upper_ribcage_shoulder", (0, 1), 30, 1, (24, 25, 26)), + ("neck_collar", (0, 1, 2), 31, 2, (27, 29, 29)), + ("neck_upper", (0, 1, 2), 32, 2, (30, 32, 32)), + ) + for name, chain, landmark, owner, indices in stations: + records.extend(_expected_world_records(f"stations.{name}.C", chain, landmark)) + for field, index in zip(("rL", "rA", "rP"), indices): + records.append(_expected_dimension(f"stations.{name}.{field}", owner, index)) + for side, owner, axilla, peak, indices in (("left", 4, 1, 0, (67, 68, 69, 56)), + ("right", 7, 3, 2, (82, 83, 84, 62)), + ): + chain = (0, 1, owner) + records.extend(_expected_world_records(f"shoulders.{side}.axilla", chain, axilla)) + records.extend(_expected_world_records(f"shoulders.{side}.peak", chain, peak)) + records.extend(_expected_world_records(f"shoulders.{side}.arm_origin", chain, None)) + fields = ("start_lateral", "start_up", "start_forward", "shoulder_depth") + records.extend(_expected_dimension(f"shoulders.{side}.{field}", owner, index) + for field, index in zip(fields, indices)) + for side, owner, landmark, indices in (("left", 10, 14, (97, 98, 99)), + ("right", 13, 19, (112, 113, 114)), + ): + records.extend(_expected_world_records(f"hips.{side}.P_s", (0, owner), landmark)) + records.extend(_expected_dimension(f"hips.{side}.{field}", owner, index) + for field, index in zip(("r_x", "r_y", "r_z"), indices)) + return sorted(records, key=lambda record: record["prepared_component"].encode("utf-8")) +class PreparedProjectionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.source_document = json.loads(SOURCE.read_bytes()) + cls.profile_document = json.loads(PROFILE_TABLE.read_bytes()) + cls.prepared = prepare_standard_neutral(SOURCE) + + def assert_runtime_vector(self, value, length=3): + self.assertIs(type(value), list) + self.assertEqual(len(value), length) + self.assertTrue(all(type(item) is float for item in value)) + def test_complete_prepared_schema_values_and_runtime_types(self): + prepared = self.prepared + self.assertEqual(set(prepared), { + "schema", "contract", "source", "profile_selection", "basis", + "parts", "stations", "shoulders", "hips", "provenance", + }) + self.assertEqual(prepared["schema"], "owned-root-assembly-successor-prepared.v1") + for key, path, digest in (("contract", CONTRACT_ROLE, CONTRACT_HASH), + ("source", SOURCE_ROLE, SOURCE_HASH), + ): + self.assertEqual(prepared[key], {"path": path, "sha256": digest}) + self.assertEqual(set(prepared[key]), {"path", "sha256"}) + selection = prepared["profile_selection"] + self.assertEqual(set(selection), { + "profile_id", "profile_table_path", "profile_table_sha256", "dimensions", + }) + self.assertEqual((selection["profile_id"], selection["profile_table_path"], + selection["profile_table_sha256"]), + ("standard_neutral_reference", PROFILE_ROLE, PROFILE_HASH)) + self.assertEqual(set(selection["dimensions"]), PROFILE_DIMENSION_KEYS) + self.assertTrue(all(type(value) is float and value == 1000.0 + for value in selection["dimensions"].values())) + self.assertEqual(prepared["basis"], { + "length_unit": "metre", "handedness": "right", "up": "+y", "forward": "+z", + }) + parts = (("pelvis", None, [0.0, 0.0, 0.0]), ("torso", None, [0.0, 1.0, 0.0]), + ("neck", None, [0.0, 1.0, 0.0]), ("upper_arm", "left", [-1.0, 1.0, 0.0]), + ("upper_arm", "right", [1.0, 1.0, 0.0]), ("thigh", "left", [-1.0, -1.0, 0.0]), + ("thigh", "right", [1.0, -1.0, 0.0]), + ) + self.assertEqual(len(prepared["parts"]), len(parts)) + for record, (role, side, translation) in zip(prepared["parts"], parts): + self.assertEqual(set(record), {"address", "placement"}) + self.assertEqual(record["address"], _address(role, side)) + self.assertEqual(set(record["placement"]), {"translation", "rotation_xyzw"}) + self.assertEqual(record["placement"]["translation"], translation) + self.assertEqual(record["placement"]["rotation_xyzw"], [0.0, 0.0, 0.0, 1.0]) + self.assert_runtime_vector(record["placement"]["translation"]) + self.assert_runtime_vector(record["placement"]["rotation_xyzw"], 4) + stations = { + "lower_pelvis": ("pelvis", "form_torso_profile_lower_pelvis", [0.0, -0.45, 0.0], (1.5, .85, .6)), + "upper_pelvis": ("pelvis", "form_torso_profile_upper_pelvis", [0.0, -.2, 0.0], (1.35, .78, .56)), + "lower_abdomen": ("torso", "form_torso_profile_lower_abdomen", [0.0, .25, 0.0], (1.125, .68, .54)), + "waist_abdomen": ("torso", "form_torso_profile_waist_abdomen", [0.0, .5, 0.0], (.875, .5, .4)), + "upper_abdomen": ("torso", "form_torso_profile_upper_abdomen", [0.0, .8, 0.0], (1.225, .725, .56)), + "lower_ribcage": ("torso", "form_torso_profile_lower_ribcage", [0.0, 1.05, 0.0], (1.45, .875, .675)), + "upper_ribcage_shoulder": ( + "torso", "form_torso_profile_upper_ribcage_shoulder", [0.0, 1.95, 0.0], (1.5, .9, .7)), + "neck_collar": ("neck", "form_head_neck_profile_neck_collar", [0.0, 2.15, 0.0], (.42, .4, .4)), + "neck_upper": ("neck", "form_head_neck_profile_neck_upper", [0.0, 2.55, 0.0], (.34, .33, .33)), + } + self.assertEqual(list(prepared["stations"]), list(stations)) + for name, (owner, prefix, center, radii) in stations.items(): + record = prepared["stations"][name] + self.assertEqual(set(record), {"owner", "prefix", "C", "rL", "rA", "rP"}) + self.assertEqual((record["owner"], record["prefix"], record["C"]), (_address(owner), prefix, center)) + self.assertEqual(tuple(record[field] for field in ("rL", "rA", "rP")), radii) + self.assert_runtime_vector(record["C"]) + self.assertTrue(all(type(record[field]) is float for field in ("rL", "rA", "rP"))) + for side, sign in (("left", -1.0), ("right", 1.0)): + shoulder = prepared["shoulders"][side] + self.assertEqual(set(shoulder), { + "axilla", "peak", "arm_origin", "start_lateral", "start_up", + "start_forward", "shoulder_depth", + }) + expected = ([1.1 * sign, 1.7, 0.0], [1.1 * sign, 2.15, 0.0], + [sign, 2.0, 0.0], .35, .3, .32, .35) + self.assertEqual(tuple(shoulder.values()), expected) + for field in ("axilla", "peak", "arm_origin"): + self.assert_runtime_vector(shoulder[field]) + self.assertTrue(all(type(shoulder[field]) is float + for field in ("start_lateral", "start_up", "start_forward", "shoulder_depth"))) + hip = prepared["hips"][side] + self.assertEqual(set(hip), {"P_s", "r_x", "r_y", "r_z"}) + self.assertEqual(tuple(hip.values()), ([sign, -1.0, 0.0], .32, .28, .3)) + self.assert_runtime_vector(hip["P_s"]) + self.assertTrue(all(type(hip[field]) is float for field in ("r_x", "r_y", "r_z"))) + self.assertEqual(prepared["provenance"], {"source_files": [ + {"path": SOURCE_ROLE, "sha256": SOURCE_HASH, "bytes": 56984}, + {"path": PROFILE_ROLE, "sha256": PROFILE_HASH, "bytes": 29970}, + ]}) + def test_public_validator_is_closed_against_schema_and_value_forgery(self): + self.assertIs(validate_prepared(self.prepared), self.prepared) + extra = copy.deepcopy(self.prepared) + extra["stations"]["neck_upper"]["unknown"] = 1.0 + missing = copy.deepcopy(self.prepared) + del missing["profile_selection"]["dimensions"]["arm_radius"] + cases = (("extra", extra), ("missing", missing), + ("type", _mutated(self.prepared, ("shoulders", "left", "axilla"), (0.0, 0.0, 0.0))), + ("part", _mutated(self.prepared, ("parts", 0, "placement", "translation", 0), .125)), + ("station", _mutated(self.prepared, ("stations", "lower_pelvis", "rL"), 1.51)), + ("shoulder", _mutated(self.prepared, ("shoulders", "left", "axilla", 0), -1.05)), + ("hip", _mutated(self.prepared, ("hips", "right", "r_x"), .33)), + ) + for name, candidate in cases: + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + validate_prepared(candidate) + def test_canonical_prepared_bytes_round_trip_and_rejections(self): + encoded = canonical_json_bytes(self.prepared) + admitted = admit_prepared_bytes(encoded) + self.assertEqual(admitted, self.prepared) + self.assertEqual(canonical_json_bytes(admitted), encoded) + self.assertIs(type(admitted["parts"][0]["placement"]["translation"][0]), float) + negative_zero = _mutated(self.prepared, ("parts", 0, "placement", "translation", 0), -0.0) + self.assertEqual(canonical_json_bytes(negative_zero), encoded) + self.assertEqual(admit_prepared_bytes(canonical_json_bytes(negative_zero)), self.prepared) + integer = _mutated(self.prepared, ("parts", 0, "placement", "translation", 0), 1) + boolean = _mutated(self.prepared, ("shoulders", "left", "shoulder_depth"), True) + unknown = copy.deepcopy(self.prepared) + unknown["hips"]["left"]["forged"] = 0.0 + cases = (("nonzero integer", canonical_json_bytes(integer)), + ("boolean", canonical_json_bytes(boolean)), + ("unknown field", canonical_json_bytes(unknown)), + ("nonfinite", encoded.replace(b'"r_x":0.32', b'"r_x":NaN', 1)), + ("duplicate", encoded[:-1] + b',"schema":"owned-root-assembly-successor-prepared.v1"}'), + ("noncanonical", encoded + b"\n"), + ) + for name, raw in cases: + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + admit_prepared_bytes(raw) + def test_all_92_bindings_match_independent_complete_mapping(self): + expected = _expected_bindings() + actual = source_binding_records(SOURCE) + components = [record["prepared_component"] for record in expected] + self.assertEqual(len(expected), 92) + self.assertEqual(hashlib.sha256(canonical_json_bytes(components)).hexdigest(), COMPONENTS_HASH) + self.assertEqual(hashlib.sha256(canonical_json_bytes(expected)).hexdigest(), BINDINGS_HASH) + self.assertEqual(actual, expected) + self.assertEqual(build_source_binding_records(SOURCE), expected) + self.assertEqual(len(set(components)), 92) + self.assertEqual(components, sorted(components)) + for record in actual: + self.assertEqual(set(record), { + "prepared_component", "derivation_id", "source_addresses", "source_pointers", + }) + self.assertTrue(record["source_addresses"] and record["source_pointers"]) + self.assertEqual(record["source_pointers"], sorted(set(record["source_pointers"]))) + addresses = record["source_addresses"] + self.assertEqual(len(addresses), len({canonical_json_bytes(item) for item in addresses})) + self.assertEqual(addresses, sorted(addresses, key=canonical_json_bytes)) + def test_binding_commitments_reject_each_forgery_class(self): + records = _expected_bindings() + for name, path, value in (("id", (0, "prepared_component"), "forged.component"), + ("derivation", (0, "derivation_id"), "forged.derivation"), + ("address", (0, "source_addresses", 0, 3), "forged_role"), + ("pointer", (0, "source_pointers", 0), "/forged/pointer"), + ): + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + _validate_binding_records(_mutated(records, path, value)) + def test_fixed_paths_reject_exact_byte_copies(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + copies = root / "contract.md", root / "source.json", root / "profiles.json" + for target, canonical in zip(copies, (CONTRACT, SOURCE, PROFILE_TABLE)): + target.write_bytes(canonical.read_bytes()) + cases = (("contract path", {"source_path": SOURCE, "contract_path": copies[0]}), + ("source path", {"source_path": copies[1]}), + ("profile table path", {"source_path": SOURCE, "profile_table_path": copies[2]}), + ) + for message, kwargs in cases: + with self.subTest(message=message), self.assertRaisesRegex(PreparedProjectionError, message): + prepare_standard_neutral(**kwargs) + def test_public_constant_reassignment_cannot_redirect_fixed_admission(self): + encoded, expected_bindings = canonical_json_bytes(self.prepared), _expected_bindings() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + paths = [root / name for name in ("contract", "sidecar", "source", "profile")] + for target, canonical in zip(paths, (CONTRACT, SIDECAR, SOURCE, PROFILE_TABLE)): + target.write_bytes(canonical.read_bytes()) + replacements = { + "CONTRACT_ROLE": "forged/contract", "SOURCE_ROLE": "forged/source", + "PROFILE_ROLE": "forged/profile", "CONTRACT_PATH": paths[0], + "SIDECAR_PATH": paths[1], "SOURCE_PATH": paths[2], "PROFILE_TABLE_PATH": paths[3], + "EXPECTED_CONTRACT_SHA256": "0" * 64, "EXPECTED_SOURCE_SHA256": "1" * 64, + "EXPECTED_PROFILE_TABLE_SHA256": "2" * 64, "EXPECTED_SOURCE_BYTES": 1, + "EXPECTED_PROFILE_BYTES": 2, "EXPECTED_BINDING_COMPONENTS_SHA256": "3" * 64, + "EXPECTED_BINDINGS_SHA256": "4" * 64, + } + with patch.multiple(projection, **replacements), patch.object( + projection.artifacts, "contract_sidecar_bytes", side_effect=RuntimeError("redirected"), + ): + self.assertEqual(projection.prepare_standard_neutral(), self.prepared) + self.assertIs(projection.validate_prepared(self.prepared), self.prepared) + self.assertEqual(projection.admit_prepared_bytes(encoded), self.prepared) + self.assertEqual(projection.source_binding_records(), expected_bindings) + with self.assertRaises(PreparedProjectionError): + projection.prepare_standard_neutral( + projection.SOURCE_PATH, contract_path=projection.CONTRACT_PATH, + profile_table_path=projection.PROFILE_TABLE_PATH) + def test_fixed_hashes_sidecar_and_sizes_are_independent_literals(self): + for path, size, digest in ( + (CONTRACT, 173184, CONTRACT_HASH), (SIDECAR, 127, hashlib.sha256(SIDECAR_BYTES).hexdigest()), + (SOURCE, 56984, SOURCE_HASH), (PROFILE_TABLE, 29970, PROFILE_HASH), + ): + raw = path.read_bytes() + self.assertEqual(len(raw), size) + self.assertEqual(hashlib.sha256(raw).hexdigest(), digest) + self.assertEqual(SIDECAR.read_bytes(), SIDECAR_BYTES) + self.assertEqual(projection._SIDECAR_CONTENT, SIDECAR_BYTES) + def test_contract_sidecar_call_uses_fixed_signature(self): + with patch.object(artifacts, "contract_sidecar_bytes", wraps=artifacts.contract_sidecar_bytes) as call: + runpy.run_path(str(PACKAGE / "prepared_projection.py")) + call.assert_called_once_with(CONTRACT_HASH) + def test_source_and_profile_identity_fail_closed_through_byte_seams(self): + source = _mutated(self.source_document, ("basis", "forward"), "-z") + with self.assertRaisesRegex(PreparedProjectionError, "source identity mismatch"): + _admit_source_bytes(json.dumps(source).encode()) + profile = _mutated(self.profile_document, ("profiles", 0, "dimension_scales", "arm_radius"), 1001) + mutated_profile = json.dumps(profile).encode() + real_read = projection._READ_FILE + + def read_with_mutated_profile(path): + return mutated_profile if Path(path) == PROFILE_TABLE else real_read(path) + + with patch.object(projection, "_READ_FILE", side_effect=read_with_mutated_profile), \ + self.assertRaisesRegex(PreparedProjectionError, "profile identity mismatch"): + prepare_standard_neutral(SOURCE) + with self.assertRaisesRegex(PreparedProjectionError, "profile identity mismatch"): + _admit_profile_bytes(mutated_profile) + def test_source_profile_schema_and_selector_boundaries(self): + missing = copy.deepcopy(self.source_document) + del missing["body"]["parts"][0]["placement"] + duplicate = _mutated(self.source_document, ("body", "dimensions", 1), + copy.deepcopy(self.source_document["body"]["dimensions"][0])) + source_cases = ( + ("schema", missing), + ("identity", _mutated(self.source_document, ("source", "document"), "forged")), + ("cardinality", _mutated(self.source_document, ("body", "dimensions"), + self.source_document["body"]["dimensions"][:-1])), + ("rotation", _mutated(self.source_document, + ("body", "parts", 17, "placement", "rotation_xyzw"), [0.0] * 4)), + ("selector", duplicate), + ("frame", _mutated(self.source_document, + ("body", "landmarks", 0, "frame", "role"), "missing_frame")), + ) + for name, candidate in source_cases: + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + _validate_source_document(candidate) + wrong_order = copy.deepcopy(self.profile_document) + wrong_order["profiles"][0], wrong_order["profiles"][1] = wrong_order["profiles"][1::-1] + for name, candidate in ( + ("order", wrong_order), + ("scale", _mutated(self.profile_document, + ("profiles", 0, "dimension_scales", "arm_radius"), 1001)), + ): + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + _validate_profile_table(candidate) + def test_every_source_dimension_requires_positive_finite_binary64(self): + for index in range(153): + with self.subTest(index=index), self.assertRaises(PreparedProjectionError): + _validate_source_document(_mutated( + self.source_document, ("body", "dimensions", index, "value"), 0)) + for name, value in (("boolean", True), ("nonfinite", float("inf")), ("overflow", 10 ** 400)): + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + _validate_source_document(_mutated( + self.source_document, ("body", "dimensions", 152, "value"), value)) + def test_strict_source_json_boundaries(self): + source = SOURCE.read_bytes() + cases = ( + source.replace(b'"extensions": []', b'"extensions": [], "extensions": []', 1), + source.replace(b'"value": 1.7', b'"value": NaN', 1), b"\xff", + ) + for raw in cases: + with self.subTest(raw=raw[:24]), self.assertRaisesRegex(PreparedProjectionError, "strict UTF-8 JSON"): + _admit_source_bytes(raw) + def test_malformed_public_admissions_normalize_exceptions(self): + for name, path in ( + ("schema", ("schema",)), ("address", ("parts", 0, "address", 3)), + ("provenance", ("provenance", "source_files", 0, "sha256")), + ("basis", ("basis", "up")), + ): + with self.subTest(name=name), self.assertRaises(PreparedProjectionError): + validate_prepared(_mutated(self.prepared, path, _Explosive())) + with patch.object(projection, "_DECODE_JSON", side_effect=RecursionError), \ + self.assertRaises(PreparedProjectionError): + admit_prepared_bytes(b"{}") + with patch.object(projection, "_JSON_BYTES", + side_effect=artifacts.ArtifactSerializationError("forged")), \ + self.assertRaises(PreparedProjectionError): + validate_prepared(self.prepared) + for function in (prepare_standard_neutral, source_binding_records): + with self.subTest(function=function.__name__), self.assertRaises(PreparedProjectionError): + function(_Explosive()) + def test_normalization_aliases_canonical_bytes_and_closed_content(self): + raw = {"role": "upper_arm", "kind": "part", "anchors": ["left"], "namespace": "main"} + normalized = normalize_source_address(raw) + self.assertEqual(normalized, ["main", ["left"], "part", "upper_arm"]) + self.assertIsNot(normalized, raw) + self.assertIsNot(normalized[1], raw["anchors"]) + for bad in ( + {"namespace": "main", "anchors": [], "kind": "part"}, + {"namespace": "main", "anchors": [1], "kind": "part", "role": "x"}, + {"namespace": "main", "anchors": [], "kind": "", "role": "x"}, + {"namespace": "main", "anchors": [], "kind": "part", "role": "x", "extra": 1}, + ): + with self.subTest(bad=bad), self.assertRaises(PreparedProjectionError): + normalize_source_address(bad) + stations = self.prepared["stations"] + self.assertEqual(stations["neck_collar"]["rA"], stations["neck_collar"]["rP"]) + encoded = canonical_json_bytes(self.prepared) + self.assertNotIn(b"-0.0", encoded) + self.assertIn(b'"rotation_xyzw":[0,0,0,1.0]', encoded) + self.assertEqual(canonical_json_sha256(self.prepared), hashlib.sha256(encoded).hexdigest()) + self.assertEqual(encoded, canonical_json_bytes(prepare_standard_neutral(SOURCE))) + self.assertEqual(canonical_json_bytes({"value": -0.0}), b'{"value":0}') + serialized = encoded.decode() + for field in ("vertices", "faces", "edges", "connectivity", "perimeter", "point_cloud", + "mask", "silhouette", "corrective_offset", "serialized_output", "part_placements"): + self.assertNotIn(field, serialized) + +if __name__ == "__main__": + unittest.main() From f8f2e79478e0d8b70d559bf267c53cf6464b87ee Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 03:47:51 +1200 Subject: [PATCH 13/38] Complete owned root assembly implementation --- .../anatomy_gates.py | 245 +++++ .../artifact_serialization.py | 462 ++++----- .../build_owned_root.py | 431 ++++++++ .../chart_lineage.py | 220 ++++ .../compare_two_seed_outputs.py | 236 +++++ .../mesh_correctness.py | 787 ++++++--------- .../owned_root_launcher.sh | 46 + .../owned_root_surface.py | 562 +++++++++++ .../prepared_projection.py | 412 ++++---- .../render_export.py | 215 ++++ .../tests/test_build_owned_root.py | 947 ++++++++---------- .../tests/test_mesh_correctness.py | 447 +++++---- .../tests/test_owned_root_surface.py | 400 ++++++++ .../tests/test_prepared_projection.py | 157 ++- .../tests/test_render_export.py | 287 ++++++ 15 files changed, 4133 insertions(+), 1721 deletions(-) create mode 100644 experiments/owned-root-assembly-successor/anatomy_gates.py create mode 100644 experiments/owned-root-assembly-successor/build_owned_root.py create mode 100644 experiments/owned-root-assembly-successor/chart_lineage.py create mode 100644 experiments/owned-root-assembly-successor/compare_two_seed_outputs.py create mode 100755 experiments/owned-root-assembly-successor/owned_root_launcher.sh create mode 100644 experiments/owned-root-assembly-successor/owned_root_surface.py create mode 100644 experiments/owned-root-assembly-successor/render_export.py create mode 100644 experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py create mode 100644 experiments/owned-root-assembly-successor/tests/test_render_export.py diff --git a/experiments/owned-root-assembly-successor/anatomy_gates.py b/experiments/owned-root-assembly-successor/anatomy_gates.py new file mode 100644 index 0000000..bff2ec9 --- /dev/null +++ b/experiments/owned-root-assembly-successor/anatomy_gates.py @@ -0,0 +1,245 @@ +"""Independent anatomy selectors, gates, thresholds, and production fixtures; owns no surface, chart, transition, sample, or summary construction.""" +from __future__ import annotations + +from collections import defaultdict, namedtuple +from collections.abc import Mapping +from fractions import Fraction +from math import isfinite, sqrt + +try: + import owned_root_surface as surface +except ImportError: # pragma: no cover + from . import owned_root_surface as surface +LEVEL_COUNTS = ((120, 104, 227), (451, 416, 870), (1737, 1664, 3404)); DOMAINS, PORTS, JUNCTIONS = surface.DOMAINS, surface.PORTS, surface.JUNCTIONS +PAIRS = {j: tuple(surface.JUNCTION_INFO[j][0]) for j in JUNCTIONS}; DROPS = {j: surface.JUNCTION_INFO[j][1] for j in JUNCTIONS} +ANATOMY_METRICS = ("shoulder_surface_descent", "arm_port_descent", "axillary_turn_depth", "axillary_path_stretch", "axillary_inboard_recess", "axillary_downward_recess", "pelvic_vertical_wrap", "pelvic_lateral_ratio", "front_depth_wrap", "back_depth_wrap") +CLEARANCES = ("neck", "left_axilla", "right_axilla", "groin", "medial_thigh") +THRESHOLD = 0.05 +class AnatomyGateError(ValueError): + def __init__(self, message, diagnostics=()): + self.diagnostics = tuple(sorted(map(str, diagnostics))); super().__init__(message + (": " + ", ".join(self.diagnostics) if self.diagnostics else "")) +def _fail(message, *diagnostics): raise AnatomyGateError(message, diagnostics) +def _get(value, name): return value[name] if isinstance(value, Mapping) else getattr(value, name) +def _edges(mesh): + result = defaultdict(list) + for fi, face in enumerate(_get(mesh, "quads")): + for slot, a in enumerate(face): result[tuple(sorted((a, face[(slot + 1) % 4])))].append((fi, slot)) + return result +def _chart_path(level, index): return () if level == 0 else (index % 4,) if level == 1 else ((index % 16) // 4, index % 4) +def _chart_id(level, index): base = index // (4 ** level); path = _chart_path(level, index); return f"chart.q{base:03d}" if not path else f"chart.q{base:03d}/L{level}.s{'.s'.join(map(str, path))}" +def _chart_uv(path): + corners = ((Fraction(0), Fraction(0)), (Fraction(1), Fraction(0)), (Fraction(1), Fraction(1)), (Fraction(0), Fraction(1))) + for child in path: + mids = tuple(tuple((left + right) / 2 for left, right in zip(corners[i], corners[(i + 1) % 4])) for i in range(4)); center = tuple(sum((point[axis] for point in corners), Fraction(0)) / 4 for axis in range(2)); corners = ((corners[0], mids[0], center, mids[3]), (corners[1], mids[1], center, mids[0]), (corners[2], mids[2], center, mids[1]), (corners[3], mids[3], center, mids[2]))[child] + return corners +def _dyadic(value, expected, where): + if not isinstance(value, Mapping) or set(value) != {"numerator", "denominator"}: _fail("chart dyadic schema mismatch", where) + numerator, denominator = value["numerator"], value["denominator"] + if type(numerator) is not int or type(denominator) is not int or denominator <= 0 or denominator & (denominator - 1): _fail("chart dyadic grammar mismatch", where) + reduced = Fraction(numerator, denominator); invalid = reduced.numerator != numerator or reduced.denominator != denominator or reduced != expected + if invalid: _fail("chart dyadic value or reduction mismatch", where) +def _chart_levels(charts, levels): + if isinstance(charts, Mapping) and "chart_records" not in charts: _fail("chart ancestry is required") + if isinstance(charts, Mapping): charts = charts["chart_records"] + if not isinstance(charts, (list, tuple)): _fail("chart ancestry is required") + if len(charts) == 3 and all(isinstance(item, (list, tuple)) for item in charts): by_level = tuple(tuple(item) for item in charts) + else: + if any(not isinstance(item, Mapping) or "level" not in item for item in charts): _fail("chart ancestry record is malformed") + if any(not isinstance(item.get("chart_id"), str) for item in charts): _fail("chart ID is malformed") + if any(type(item["level"]) is not int or item["level"] not in range(3) for item in charts): _fail("chart level is malformed or out of range") + if tuple(item["chart_id"] for item in charts) != tuple(sorted((item["chart_id"] for item in charts), key=str.encode)): _fail("chart records are not sorted by chart ID") + by_level = tuple(tuple(item for item in charts if item["level"] == level) for level in range(3)) + seen = set(); result = [] + for level, (mesh, records) in enumerate(zip(levels, by_level)): + if len(records) != len(_get(mesh, "quads")): _fail("chart ancestry cardinality mismatch", f"L{level}") + checked = [] + for index, chart in enumerate(records): + where = f"L{level}[{index}]" + if not isinstance(chart, Mapping) or set(chart) != {"chart_id", "level", "face_id", "base_face_id", "construction_owner", "corners"}: _fail("chart ancestry schema mismatch", where) + if type(chart["level"]) is not int or chart["level"] != level: _fail("chart level is malformed or misplaced", where) + expected_id = _chart_id(level, index); base = surface.FACE_RECORDS[index // (4 ** level)][0] + face_id, owner = _get(mesh, "face_ids")[index], _get(mesh, "face_owners")[index] + if (chart["chart_id"], chart["level"], chart["face_id"], chart["base_face_id"], chart["construction_owner"]) != (expected_id, level, face_id, base, owner): _fail("chart ancestry disagrees with public face authority", where) + if chart["chart_id"] in seen: _fail("chart ancestry has duplicate IDs", where) + seen.add(chart["chart_id"]); corners = chart["corners"]; face = _get(mesh, "quads")[index] + if not isinstance(corners, (list, tuple)) or len(corners) != 4: _fail("chart corner incidence is incomplete", where) + for corner, (entry, vertex) in enumerate(zip(corners, face)): + corner_where = f"{where}c{corner}" + if not isinstance(entry, Mapping) or set(entry) != {"vertex_id", "u", "v"} or entry["vertex_id"] != _get(mesh, "control_ids")[vertex]: _fail("chart corner incidence disagrees with public topology", corner_where) + expected_u, expected_v = _chart_uv(_chart_path(level, index))[corner] + _dyadic(entry["u"], expected_u, corner_where + ".u"); _dyadic(entry["v"], expected_v, corner_where + ".v") + checked.append(chart) + result.append(tuple(checked)) + if len(result) != 3 or len(seen) != sum(len(row) for row in result): _fail("chart ancestry is not a three-level sequence") + return tuple(result) +def validate_evaluated_surface(value, chart_summary=None, *, prepared=None): + try: levels = surface.validate_evaluation(value, prepared) + except (ValueError, IndexError, TypeError) as exc: _fail("evaluated surface admission is invalid", str(exc)) + for level, mesh in enumerate(levels): + if (len(mesh.vertices), len(mesh.quads), len(surface.topology_incidence(mesh))) != LEVEL_COUNTS[level]: _fail("evaluated surface count mismatch", f"L{level}") + if chart_summary is not None: _chart_levels(chart_summary, levels) + return levels +def _context(value, prepared, chart_summary): + if chart_summary is None: _fail("chart ancestry is required for anatomy selectors") + levels = validate_evaluated_surface(value, prepared=prepared); return levels, _chart_levels(chart_summary, levels) +def _actual_feature_edges(mesh, charts, feature, expected=None): + edges = _edges(mesh) + if feature in PORTS: + boundary = {edge for edge, uses in edges.items() if len(uses) == 1}; groups = []; unseen = set(boundary) + while unseen: + group, todo = set(), [unseen.pop()] + while todo: + edge = todo.pop(); group.add(edge); neighbours = {other for other in unseen if set(edge) & set(other)} + unseen.difference_update(neighbours); todo.extend(neighbours) + groups.append(group) + expected = _base_feature_edges(feature, mesh) if expected is None else expected + if len(groups) == len(PORTS) and sum(group == expected for group in groups) == 1: return expected + return boundary + owners = tuple(c["construction_owner"] for c in charts); result = set(); matches = PAIRS[feature] + for edge, uses in edges.items(): + if len(uses) == 2 and frozenset((owners[uses[0][0]], owners[uses[1][0]])) == frozenset(matches): result.add(edge) + return result +def _base_feature_edges(feature, mesh): + ids = surface.PORT_INFO[feature][2] if feature in PORTS else surface.JUNCTION_TRACES[feature]; indexes = {name: i for i, name in enumerate(mesh.control_ids)}; cycle = tuple(indexes[name] for name in ids); return {tuple(sorted((a, cycle[(i + 1) % len(cycle)]))) for i, a in enumerate(cycle)} +def _feature_edges(levels, charts, feature, target): + selected = _base_feature_edges(feature, levels[0]); actual = _actual_feature_edges(levels[0], charts[0], feature, selected) + if selected != actual: _fail("incidence selector disagrees with catalog", f"{feature}:L0") + for level in range(1, target + 1): + parent = levels[level - 1]; incidence = surface.subdivision_incidence(parent); edge_point = dict(incidence["edge_point_indices"]); expected = set() + for a, b in selected: mid = edge_point[(a, b)]; expected.update((tuple(sorted((a, mid))), tuple(sorted((mid, b))))) + actual = _actual_feature_edges(levels[level], charts[level], feature, expected) + if expected != actual: _fail("propagated incidence selector disagrees with catalog", f"{feature}:L{level}") + selected = expected + return selected +def _tag(control, feature): + coords = surface.COORDINATE_BY_CONTROL[control]; axes = (0, 2) if feature in PORTS and feature in ("port.neck", "port.left_thigh", "port.right_thigh") else (1, 2) if feature in PORTS else tuple(0 if x == "i" else 1 if x == "j" else 2 for x in DROPS[feature][1]); return tuple(Fraction(coords[a]) for a in axes) +def _feature_tags(levels, charts, feature, target): + base = {c: _tag(levels[0].control_ids[c], feature) for edge in _feature_edges(levels, charts, feature, 0) for c in edge}; tags = base + for level in range(1, target + 1): + parent = levels[level - 1]; incidence = surface.subdivision_incidence(parent); edge_points = dict(incidence["edge_point_indices"]) + out = {i: tag for i, tag in tags.items()} + for edge in _feature_edges(levels, charts, feature, level - 1): out[edge_points[edge]] = tuple((tags[edge[0]][a] + tags[edge[1]][a]) / 2 for a in range(2)) + expected = {v for edge in _feature_edges(levels, charts, feature, level) for v in edge} + if set(out) != expected: _fail("feature tag propagation mismatch", f"{feature}:L{level}") + tags = out + return tags +def _trace(levels, charts, feature, level): + if feature not in PORTS + JUNCTIONS or level not in range(3): _fail("unknown anatomy selector", feature) + tags = _feature_tags(levels, charts, feature, level); result = {tag: tuple(levels[level].vertices[index]) for index, tag in tags.items()} + if len(result) != len(tags): _fail("ambiguous anatomy selector", feature) + return dict(sorted(result.items())) +def select_trace(value, feature, level=2, chart_summary=None, *, prepared=None): + levels, charts = _context(value, prepared, chart_summary); return _trace(levels, charts, feature, level) +def _vec(value, name): + if not isinstance(value, (tuple, list)) or len(value) != 3 or any(type(x) is not float or not isfinite(x) for x in value): raise ValueError(f"{name} must be a finite binary64 vector3") + return tuple(value) +def _sub(a, b): return tuple(float(a[i] - b[i]) for i in range(3)) +def _xy(v): return sqrt(float(v[0] * v[0] + v[1] * v[1])) +def _div(a, b): return float(a / b) +AxillaryPredicateResult = namedtuple("AxillaryPredicateResult", "passed stage turn_depth path_stretch lr ls lc", defaults=(None, None, None)) +class AxillaryPredicateError(ValueError): + def __init__(self, stage, lr=None, ls=None, lc=None): + self.stage, self.lr, self.ls, self.lc = stage, lr, ls, lc; super().__init__(f"axillary predicate failed at step {stage}") +_TURN = float.fromhex("0x1.999999999999ap-5"); _STRETCH = float.fromhex("0x1.4000000000000p+1") +def evaluate_axillary_predicate(side, U, A, O, _turn=_TURN, _stretch=_STRETCH): + if side not in ("left", "right"): raise ValueError("axillary side must be left or right") + U, A, O = _vec(U, "U"), _vec(A, "A"), _vec(O, "O"); r, s, c = _sub(A, U), _sub(O, A), _sub(O, U) + lr, ls, lc = _xy(r), _xy(s), _xy(c) + for step, value, name in ((3, lr, "lr"), (4, ls, "ls"), (5, lc, "lc")): + if not isfinite(value) or value <= 0: raise AxillaryPredicateError(step, lr, ls, lc) + path = float(lr + ls) + if not isfinite(path) or path <= 0: raise ValueError("axillary predicate failed at step 6: path") + cross = float(c[0] * r[1] - c[1] * r[0]); oriented = cross if side == "left" else float(-cross) + turn, stretch = _div(oriented, path), _div(path, lc) + if not all(isfinite(x) for x in (turn, stretch)): raise ValueError("axillary predicate failed at step 7: non-finite measure") + if turn < _turn: return AxillaryPredicateResult(False, 8, turn, stretch, lr, ls, lc) + if stretch > _stretch: return AxillaryPredicateResult(False, 9, turn, stretch, lr, ls, lc) + return AxillaryPredicateResult(True, None, turn, stretch, lr, ls, lc) +def axillary_predicate(side, U, A, O): return evaluate_axillary_predicate(side, U, A, O).passed +def evaluate_axillary_scalars(turn_depth, path_stretch, _turn=_TURN, _stretch=_STRETCH): + if type(turn_depth) is not float or type(path_stretch) is not float or not all(isfinite(x) for x in (turn_depth, path_stretch)): raise ValueError("axillary scalar fixture values must be finite binary64") + if turn_depth < _turn: return AxillaryPredicateResult(False, 8, turn_depth, path_stretch) + if path_stretch > _stretch: return AxillaryPredicateResult(False, 9, turn_depth, path_stretch) + return AxillaryPredicateResult(True, None, turn_depth, path_stretch) +_U0 = (-float.fromhex("0x1.0866666666667p+0"), float.fromhex("0x1.1333333333333p+1"), -float.fromhex("0x1.699999999999ap-4")) +_A0 = (-float.fromhex("0x1.289999999999ap+0"), float.fromhex("0x1.9533333333334p+0"), -float.fromhex("0x1.2f28f5c28f5c4p-4")) +_O0 = (-float.fromhex("0x1.599999999999ap+0"), float.fromhex("0x1.d99999999999ap+0"), -float.fromhex("0x1.47ae147ae147bp-4")) +AXILLARY_FIXTURE_IDS = ("axillary.principal-left-pass", "axillary.principal-right-mirror-pass", "axillary.wrong-sign-left", "axillary.U-equals-A", "axillary.A-equals-O", "axillary.U-equals-O", "axillary.long-sag-left", "axillary.scalar.turn-depth-predecessor", "axillary.scalar.turn-depth-boundary", "axillary.scalar.turn-depth-successor", "axillary.scalar.path-stretch-predecessor", "axillary.scalar.path-stretch-boundary", "axillary.scalar.path-stretch-successor") +def run_axillary_fixture_matrix(_turn=_TURN, _stretch=_STRETCH): + mirror = lambda p: tuple(-x if i == 0 else x for i, x in enumerate(p)) + calls = (("left", _U0, _A0, _O0), ("right", mirror(_U0), mirror(_A0), mirror(_O0)), ("left", _O0, _A0, _U0), ("left", _U0, _U0, _O0), ("left", _U0, _O0, _O0), ("left", _U0, _A0, _U0), ("left", (0., 1., 0.), (0., -10., 0.), (-1., 0., 0.))) + expected = ((True, None, float.fromhex("0x1.4016a28cc89afp-3"), float.fromhex("0x1.0ab0f3d101d06p+1")), (True, None, float.fromhex("0x1.4016a28cc89afp-3"), float.fromhex("0x1.0ab0f3d101d06p+1")), (False, 8, -float.fromhex("0x1.4016a28cc89afp-3"), float.fromhex("0x1.0ab0f3d101d06p+1")), ("hard-failure", 3, None, None), ("hard-failure", 4, None, None), ("hard-failure", 5, None, None), (False, 9, float.fromhex("0x1.0b8e161fdc225p-1"), float.fromhex("0x1.dc4de77c38e3cp+3"))) + hard_values = ((0.0, None, None), (float.fromhex("0x1.bf1092ac1a7f1p-2"), 0.0, None), (float.fromhex("0x1.29747f9d3ab49p-1"), float.fromhex("0x1.29747f9d3ab49p-1"), 0.0)) + result = [] + for fixture, call, wanted in zip(AXILLARY_FIXTURE_IDS[:7], calls, expected): + try: + row = evaluate_axillary_predicate(*call) + if wanted[0] == "hard-failure" or (row.passed, row.stage, row.turn_depth, row.path_stretch) != wanted: raise AssertionError(f"{fixture} expected {wanted!r}") + result.append({"fixture_id": fixture, "outcome": "pass" if row.passed else "fail", "stage": row.stage, "turn_depth": row.turn_depth, "path_stretch": row.path_stretch, "lr": row.lr, "ls": row.ls, "lc": row.lc}) + except AxillaryPredicateError as exc: + if wanted[0] != "hard-failure": raise AssertionError(f"{fixture} unexpectedly failed at step {exc.stage}") from exc + values = hard_values[wanted[1] - 3]; actual_values = (exc.lr, exc.ls, exc.lc) + if exc.stage != wanted[1] or any(want is not None and actual != want for actual, want in zip(actual_values, values)): raise AssertionError(f"{fixture} hard failure changed: {(exc.stage, exc.lr, exc.ls, exc.lc)!r}") + result.append({"fixture_id": fixture, "outcome": "hard-failure", "stage": exc.stage, "turn_depth": None, "path_stretch": None, "lr": exc.lr, "ls": exc.ls, "lc": exc.lc}) + except ValueError as exc: raise AssertionError(f"{fixture} raised an unclassified failure") from exc + scalar = ((float.fromhex("0x1.9999999999999p-5"), 1.), (_turn, 1.), (float.fromhex("0x1.999999999999bp-5"), 1.), (1., float.fromhex("0x1.3ffffffffffffp+1")), (1., _stretch), (1., float.fromhex("0x1.4000000000001p+1"))) + wanted = ((False, 8), (True, None), (True, None), (True, None), (True, None), (False, 9)) + for fixture, values, (okay, stage) in zip(AXILLARY_FIXTURE_IDS[7:], scalar, wanted): + row = evaluate_axillary_scalars(*values) + if (row.passed, row.stage, row.turn_depth, row.path_stretch) != (okay, stage, *values): raise AssertionError(f"{fixture} changed: {(row.passed, row.stage, row.turn_depth, row.path_stretch)!r}") + result.append({"fixture_id": fixture, "outcome": "pass" if okay else "fail", "stage": row.stage, "turn_depth": row.turn_depth, "path_stretch": row.path_stretch}) + return tuple(result) +def _put(out, key, values, relation="ge", unit="m", omitted=0): + values = tuple(float(x) for x in values) + if not values or any(not isfinite(x) for x in values): _fail("anatomy measure is empty or non-finite", key) + out[key] = {"values": values, "minimum": min(values), "maximum": max(values), "sample_count": len(values), "relation": relation, "unit": unit, "omitted_count": omitted} +def _span(points, axis): return max(p[axis] for p in points) - min(p[axis] for p in points) +def _pair(a, b, name): + if not a or set(a) != set(b): _fail("anatomy traces are missing or unequal", name) + return [(tag, a[tag], b[tag]) for tag in sorted(a)] +def _side(out, levels, charts, level, side, neck_y, prepared): + shoulder = _trace(levels, charts, f"junction.thorax__{side}_shoulder", level); arm = _trace(levels, charts, f"port.{side}_arm", level); prefix = "anatomy." + _put(out, prefix + f"arm_port_descent.{side}.L{level}", [neck_y - p[1] for p in arm.values()]) + owners = tuple(c["construction_owner"] for c in charts[level]); points = {i for fi, face in enumerate(levels[level].quads) if owners[fi] == f"domain.{side}_shoulder" for i in face} + _put(out, prefix + f"shoulder_surface_descent.{side}.L{level}", [neck_y - levels[level].vertices[i][1] for i in sorted(points)]) + upper = {tag[1]: p for tag, p in shoulder.items() if tag[0] == 6}; axilla = {tag[1]: p for tag, p in shoulder.items() if tag[0] == 4}; inferior = {tag[1]: p for tag, p in arm.items() if tag[0] == 4}; axillary = [] + if set(upper) != set(axilla) or set(axilla) != set(inferior): _fail("axillary traces are missing or unequal", side) + for tag in sorted(upper): + try: row = evaluate_axillary_predicate(side, upper[tag], axilla[tag], inferior[tag]) + except ValueError as exc: _fail("axillary predicate rejected selected trace", side, str(exc)) + axillary.append(row) + _put(out, prefix + f"axillary_turn_depth.{side}.L{level}", [x.turn_depth for x in axillary]); _put(out, prefix + f"axillary_path_stretch.{side}.L{level}", [x.path_stretch for x in axillary], "le", "dimensionless") + paired = _pair({t: p for t, p in shoulder.items() if 4 <= t[0] <= 5}, {t: p for t, p in arm.items() if 4 <= t[0] <= 5}, "axillary recess"); sign = 1 if side == "right" else -1 + _put(out, prefix + f"axillary_inboard_recess.{side}.L{level}", [sign * (o[0] - j[0]) for _, j, o in paired]); _put(out, prefix + f"axillary_downward_recess.{side}.L{level}", [o[1] - j[1] for _, j, o in paired]) + hip = _trace(levels, charts, f"junction.pelvis__{side}_hip", level); thigh = _trace(levels, charts, f"port.{side}_thigh", level); paired = _pair(hip, thigh, "pelvic wrap"); + _put(out, prefix + f"pelvic_vertical_wrap.{side}.L{level}", [j[1] - p[1] for _, j, p in paired]) + ps_x = prepared["hips"][side]["P_s"][0]; ratios = [abs(j[0] - ps_x) / abs(p[0] - ps_x) for _, j, p in paired if p[0] - ps_x != 0.0]; omitted = len(paired) - len(ratios) + if not ratios: _fail("pelvic lateral ratio has no nonzero denominators", side) + _put(out, prefix + f"pelvic_lateral_ratio.{side}.L{level}", ratios, "ge", "dimensionless", omitted) + _put(out, prefix + f"front_depth_wrap.{side}.L{level}", [j[2] - p[2] for tag, j, p in paired if tag[1] > 1], "ge", "m"); _put(out, prefix + f"back_depth_wrap.{side}.L{level}", [p[2] - j[2] for tag, j, p in paired if tag[1] < 1], "ge", "m") + _put(out, prefix + f"clearance.{side}_axilla.L{level}", [min(_span(tuple(arm.values()), 1), _span(tuple(arm.values()), 2))]) +def measure_anatomy(value, prepared, chart_summary=None): + levels, charts = _context(value, prepared, chart_summary); out = {} + for level in range(3): + neck = _trace(levels, charts, "port.neck", level); neck_junction = _trace(levels, charts, "junction.thorax__neck", level); paired = _pair(neck, neck_junction, "neck exposure") + _put(out, f"anatomy.neck_exposure.L{level}", [port[1] - junction[1] for _, port, junction in paired]); neck_y = min(p[1] for p in neck.values()) + for side in ("left", "right"): _side(out, levels, charts, level, side, neck_y, prepared) + left_hip, right_hip = _trace(levels, charts, "junction.pelvis__left_hip", level), _trace(levels, charts, "junction.pelvis__right_hip", level); left_thigh, right_thigh = _trace(levels, charts, "port.left_thigh", level), _trace(levels, charts, "port.right_thigh", level) + _put(out, f"anatomy.clearance.neck.L{level}", [min(_span(tuple(neck.values()), 0), _span(tuple(neck.values()), 2))]); _put(out, f"anatomy.clearance.groin.L{level}", [min(p[0] for p in right_hip.values()) - max(p[0] for p in left_hip.values())]); _put(out, f"anatomy.clearance.medial_thigh.L{level}", [min(p[0] for p in right_thigh.values()) - max(p[0] for p in left_thigh.values())]) + if len(out) != 78: _fail("anatomy inventory is not exactly 78 measures", len(out)) + return out +def _spec(key, _threshold=THRESHOLD): + return ("le", 2.5, "dimensionless") if "path_stretch" in key else ("ge", 1.05, "dimensionless") if "lateral_ratio" in key else ("ge", .005, "m") if "depth_wrap" in key else ("ge", _threshold, "m") +def anatomy_threshold_records(): + ids = [f"anatomy.neck_exposure.L{l}" for l in range(3)] + [f"anatomy.{m}.{s}.L{l}" for m in ANATOMY_METRICS for s in ("left", "right") for l in range(3)] + [f"anatomy.clearance.{c}.L{l}" for c in CLEARANCES for l in range(3)]; result = [] + for key in sorted(ids): relation, bound, unit = _spec(key); result.append({"threshold_id": f"threshold.{key}", "relation": relation, "lower": bound if relation == "ge" else None, "upper": bound if relation == "le" else None, "unit": unit}) + return result +def anatomy_gate_records(value, prepared, chart_summary=None): + measures = measure_anatomy(value, prepared, chart_summary); failures = [] + for key, item in measures.items(): + relation, bound, _ = _spec(key); valid = item["maximum"] <= bound if relation == "le" else item["minimum"] >= bound + failures.extend((key,) if not valid else ()) + if failures: _fail("anatomy gates failed", *failures) + return [{"gate_id": key, "outcome": "pass", "sample_count": item["sample_count"], "observed_min": item["minimum"], "observed_max": item["maximum"], "threshold_id": f"threshold.{key}"} for key, item in sorted(measures.items())] +run_production_axillary_fixtures = run_axillary_fixture_matrix +__all__ = ["ANATOMY_METRICS", "AXILLARY_FIXTURE_IDS", "CLEARANCES", "AnatomyGateError", "AxillaryPredicateError", "anatomy_gate_records", "anatomy_threshold_records", "axillary_predicate", "evaluate_axillary_predicate", "evaluate_axillary_scalars", "measure_anatomy", "run_axillary_fixture_matrix", "run_production_axillary_fixtures", "select_trace", "validate_evaluated_surface"] diff --git a/experiments/owned-root-assembly-successor/artifact_serialization.py b/experiments/owned-root-assembly-successor/artifact_serialization.py index 45c7f38..f70072e 100644 --- a/experiments/owned-root-assembly-successor/artifact_serialization.py +++ b/experiments/owned-root-assembly-successor/artifact_serialization.py @@ -1,5 +1,6 @@ """Closed artifact serialization, stable inventory, and publication.""" from __future__ import annotations + import ctypes import errno import hashlib @@ -21,113 +22,68 @@ _CLOEXEC = getattr(os, "O_CLOEXEC", 0) _PATH = getattr(os, "O_PATH", os.O_RDONLY) _STAT_FIELDS = ("st_dev", "st_ino", "st_mode", "st_nlink", "st_uid", "st_gid", - "st_size", "st_mtime_ns", "st_ctime_ns", "st_rdev", "st_blksize", - "st_blocks") + "st_size", "st_mtime_ns", "st_ctime_ns", "st_rdev", "st_blksize", "st_blocks") _PUBLISHED_STAT_FIELDS = tuple(field for field in _STAT_FIELDS if field != "st_ctime_ns") - - -class ArtifactSerializationError(ValueError): - pass - - -def _stat_key(info: os.stat_result) -> tuple[object, ...]: +class ArtifactSerializationError(ValueError): pass +def _stat_key(info: os.stat_result, fields=_STAT_FIELDS) -> tuple[object, ...]: """Return stable stat fields; atime is omitted because reads may update it.""" - return tuple(getattr(info, field, None) for field in _STAT_FIELDS) - - -def _same_stat(left: os.stat_result, right: os.stat_result) -> bool: - return _stat_key(left) == _stat_key(right) - - + return tuple(getattr(info, field, None) for field in fields) +def _same_stat(left: os.stat_result, right: os.stat_result) -> bool: return _stat_key(left) == _stat_key(right) def _require_same_stat(expected: os.stat_result, observed: os.stat_result, message: str) -> None: - if not _same_stat(expected, observed): - raise ArtifactSerializationError(message) - - + if not _same_stat(expected, observed): raise ArtifactSerializationError(message) def _same_published_state(left: os.stat_result, right: os.stat_result) -> bool: - return (os.path.samestat(left, right) - and all(getattr(left, field, None) == getattr(right, field, None) - for field in _PUBLISHED_STAT_FIELDS)) - - + return os.path.samestat(left, right) and _stat_key(left, _PUBLISHED_STAT_FIELDS) == _stat_key(right, _PUBLISHED_STAT_FIELDS) def _require_regular(info: os.stat_result, label: str) -> None: - if not stat.S_ISREG(info.st_mode): - raise ArtifactSerializationError(f"{label} is not a regular file") - if info.st_nlink > 1: - raise ArtifactSerializationError(f"{label} has external hardlinks") - - + if not stat.S_ISREG(info.st_mode): raise ArtifactSerializationError(f"{label} is not a regular file") + if info.st_nlink > 1: raise ArtifactSerializationError(f"{label} has external hardlinks") def _require_publishable(info: os.stat_result, label: str) -> None: - if stat.S_ISLNK(info.st_mode): - raise ArtifactSerializationError(f"{label} must not be a symlink") - if stat.S_ISDIR(info.st_mode): - return - if not stat.S_ISREG(info.st_mode): - raise ArtifactSerializationError(f"{label} must be a regular file or directory") - if info.st_nlink > 1: - raise ArtifactSerializationError(f"{label} has external hardlinks") - - + if stat.S_ISLNK(info.st_mode): raise ArtifactSerializationError(f"{label} must not be a symlink") + if stat.S_ISDIR(info.st_mode): return + if not stat.S_ISREG(info.st_mode): raise ArtifactSerializationError(f"{label} must be a regular file or directory") + if info.st_nlink > 1: raise ArtifactSerializationError(f"{label} has external hardlinks") def validate_role_path(value: object, *, label: str = "role_path") -> str: - if not isinstance(value, str) or not value or "\x00" in value: - raise ArtifactSerializationError(f"{label} must be a canonical relative path") - if value.startswith("/") or "\\" in value: - raise ArtifactSerializationError(f"{label} must be a canonical relative path") - if any(not part or part in {".", ".."} for part in value.split("/")): - raise ArtifactSerializationError(f"{label} contains an invalid component") + if not isinstance(value, str) or not value or "\x00" in value: raise ArtifactSerializationError(f"{label} must be a canonical relative path") + if value.startswith("/") or "\\" in value: raise ArtifactSerializationError(f"{label} must be a canonical relative path") + if any(not part or part in {".", ".."} for part in value.split("/")): raise ArtifactSerializationError(f"{label} contains an invalid component") return value def _canonical(value: Any, path: str = "$") -> Any: if type(value) is float: - if not math.isfinite(value): - raise ArtifactSerializationError(f"non-finite number at {path}") + if not math.isfinite(value): raise ArtifactSerializationError(f"non-finite number at {path}") return 0 if value == 0.0 else value - if value is None or isinstance(value, (str, bool, int)): - return value + if value is None or isinstance(value, (str, bool, int)): return value if isinstance(value, Mapping): - if any(not isinstance(key, str) for key in value): - raise ArtifactSerializationError(f"invalid object key at {path}") + if any(not isinstance(key, str) for key in value): raise ArtifactSerializationError(f"invalid object key at {path}") return {key: _canonical(item, f"{path}.{key}") for key, item in value.items()} - if isinstance(value, (list, tuple)): - return [_canonical(item, f"{path}[{i}]") for i, item in enumerate(value)] + if isinstance(value, (list, tuple)): return [_canonical(item, f"{path}[{i}]") for i, item in enumerate(value)] raise ArtifactSerializationError(f"non-JSON value at {path}") def canonical_json_bytes(value: Any) -> bytes: try: - return json.dumps(_canonical(value), sort_keys=True, separators=(",", ":"), - ensure_ascii=False, allow_nan=False).encode("utf-8") + return json.dumps(_canonical(value), sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") except (TypeError, ValueError, UnicodeEncodeError) as exc: - if isinstance(exc, ArtifactSerializationError): - raise + if isinstance(exc, ArtifactSerializationError): raise raise ArtifactSerializationError("value cannot be canonically encoded") from exc def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result = {} for key, value in pairs: - if key in result: - raise ArtifactSerializationError(f"duplicate object key: {key}") + if key in result: raise ArtifactSerializationError(f"duplicate object key: {key}") result[key] = value return result -def _reject_constant(value: str) -> None: - raise ArtifactSerializationError(f"non-finite JSON constant: {value}") +def _reject_constant(value: str) -> None: raise ArtifactSerializationError(f"non-finite JSON constant: {value}") def decode_canonical_json(data: bytes | bytearray | memoryview | str) -> Any: raw = data.encode("utf-8") if isinstance(data, str) else bytes(data) try: - value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs, - parse_constant=_reject_constant) + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs, parse_constant=_reject_constant) except (UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError) as exc: - if isinstance(exc, ArtifactSerializationError): - raise + if isinstance(exc, ArtifactSerializationError): raise raise ArtifactSerializationError("invalid JSON artifact") from exc - if canonical_json_bytes(value) != raw: - raise ArtifactSerializationError("JSON artifact is not canonical") + if canonical_json_bytes(value) != raw: raise ArtifactSerializationError("JSON artifact is not canonical") return value def coerce_binary64(value: object, *, label: str = "binary64") -> float: - if type(value) is float and math.isfinite(value): - return value - if type(value) is int and value == 0: - return 0.0 + if type(value) is float and math.isfinite(value): return value + if type(value) is int and value == 0: return 0.0 raise ArtifactSerializationError(f"{label} is not a finite binary64 float or zero integer") def sha256_bytes(data: bytes | bytearray | memoryview) -> str: - if not isinstance(data, (bytes, bytearray, memoryview)): - raise ArtifactSerializationError("hash input must be bytes-like") + if not isinstance(data, (bytes, bytearray, memoryview)): raise ArtifactSerializationError("hash input must be bytes-like") return hashlib.sha256(bytes(data)).hexdigest() def _path(path: str | os.PathLike[str]) -> Path: try: @@ -136,9 +92,8 @@ def _path(path: str | os.PathLike[str]) -> Path: except (TypeError, ValueError) as exc: raise ArtifactSerializationError("path must be a filesystem path") from exc def _component(value: str, label: str) -> str: - if (not isinstance(value, str) or not value or value in {".", ".."} - or "/" in value or "\\" in value or "\x00" in value): - raise ArtifactSerializationError(f"{label} is not a safe path component") + if (not isinstance(value, str) or not value or value in {".", ".."} or "/" in value + or "\\" in value or "\x00" in value): raise ArtifactSerializationError(f"{label} is not a safe path component") return value def _open_directory(path: str | os.PathLike[str]) -> int: absolute = _path(path) @@ -146,16 +101,35 @@ def _open_directory(path: str | os.PathLike[str]) -> int: descriptor = os.open(absolute.anchor, flags) try: for part in absolute.parts[1:]: - child = os.open(_component(part, "directory component"), flags, - dir_fd=descriptor) + child = os.open(_component(part, "directory component"), flags, dir_fd=descriptor) os.close(descriptor) descriptor = child - if not stat.S_ISDIR(os.fstat(descriptor).st_mode): - raise ArtifactSerializationError("directory is not a directory") + if not stat.S_ISDIR(os.fstat(descriptor).st_mode): raise ArtifactSerializationError("directory is not a directory") return descriptor except Exception: os.close(descriptor) raise +def _read_stable_once(fd: int, initial: os.stat_result, max_bytes: int | None) -> bytes: + _require_same_stat(initial, os.fstat(fd), "regular file changed before repeated read") + chunks, offset = [], 0 + while True: + _require_same_stat(initial, os.fstat(fd), "regular file changed between chunks") + chunk = os.pread(fd, 1024 * 1024, offset) + _require_same_stat(initial, os.fstat(fd), "regular file changed between chunks") + if not chunk: break + offset += len(chunk) + if max_bytes is not None and offset > max_bytes: raise ArtifactSerializationError("regular file exceeds size cap") + chunks.append(chunk) + return b"".join(chunks) +def _read_stable_fd(fd: int, max_bytes: int | None) -> tuple[bytes, os.stat_result]: + initial = os.fstat(fd) + _require_regular(initial, "opened file") + if max_bytes is not None and (type(max_bytes) is not int or max_bytes < 0 or initial.st_size > max_bytes): raise ArtifactSerializationError("regular file exceeds size cap") + readings = [_read_stable_once(fd, initial, max_bytes) for _ in range(2)] + final = os.fstat(fd) + _require_same_stat(initial, final, "regular file changed while reading") + if final.st_size != len(readings[1]) or readings[0] != readings[1]: raise ArtifactSerializationError("regular file changed while reading") + return readings[1], final def _read_stable_with_identity(parent_fd: int, name: str, max_bytes: int | None) -> tuple[bytes, os.stat_result]: try: @@ -164,44 +138,13 @@ def _read_stable_with_identity(parent_fd: int, name: str, except OSError as exc: raise ArtifactSerializationError("cannot open regular file") from exc try: - initial = os.fstat(fd) - _require_regular(initial, "opened file") - if max_bytes is not None and (type(max_bytes) is not int or max_bytes < 0 - or initial.st_size > max_bytes): - raise ArtifactSerializationError("regular file exceeds size cap") - readings = [] - for _ in range(2): - before_read = os.fstat(fd) - _require_same_stat(initial, before_read, "regular file changed before repeated read") - chunks, offset = [], 0 - while True: - before_chunk = os.fstat(fd) - _require_same_stat(initial, before_chunk, "regular file changed between chunks") - chunk = os.pread(fd, 1024 * 1024, offset) - after_chunk = os.fstat(fd) - _require_same_stat(initial, after_chunk, "regular file changed between chunks") - if not chunk: - break - offset += len(chunk) - if max_bytes is not None and offset > max_bytes: - raise ArtifactSerializationError("regular file exceeds size cap") - chunks.append(chunk) - readings.append(b"".join(chunks)) - final = os.fstat(fd) - _require_same_stat(initial, final, "regular file changed while reading") - if final.st_size != len(readings[1]) or readings[0] != readings[1]: - raise ArtifactSerializationError("regular file changed while reading") - return readings[1], final + return _read_stable_fd(fd, max_bytes) except OSError as exc: raise ArtifactSerializationError("regular file cannot be read stably") from exc finally: os.close(fd) - - def _read_stable(parent_fd: int, name: str, max_bytes: int | None) -> bytes: return _read_stable_with_identity(parent_fd, name, max_bytes)[0] - - def read_regular_file(path: str | os.PathLike[str], *, max_bytes: int | None = None) -> bytes: absolute = _path(path) parent_fd = _open_directory(absolute.parent) @@ -211,83 +154,76 @@ def read_regular_file(path: str | os.PathLike[str], *, max_bytes: int | None = N named = os.stat(absolute.name, dir_fd=parent_fd, follow_symlinks=False) except OSError as exc: raise ArtifactSerializationError("requested file path changed while reading") from exc - if not _same_stat(opened, named): - raise ArtifactSerializationError("requested file path changed while reading") + if not _same_stat(opened, named): raise ArtifactSerializationError("requested file path changed while reading") return data finally: os.close(parent_fd) - - def regular_file_record(path: str | os.PathLike[str], role_path: str | None = None, *, max_bytes: int | None = None) -> dict[str, Any]: absolute = _path(path) role = absolute.name if role_path is None else validate_role_path(role_path) data = read_regular_file(absolute, max_bytes=max_bytes) - return {"role_path": role, - "bytes": len(data), "sha256": sha256_bytes(data)} -def coordinate_hash_bytes(coordinates: Iterable[Iterable[object]]) -> bytes: + return {"role_path": role, "bytes": len(data), "sha256": sha256_bytes(data)} +def _hash_rows(rows: Iterable[Iterable[object]], coordinates: bool) -> bytes: result = bytearray() - for row_index, row in enumerate(coordinates): + for row_index, row in enumerate(rows): values = tuple(row) if len(values) != 3: - raise ArtifactSerializationError(f"coordinate row {row_index} is not a vector3") + raise ArtifactSerializationError( + f"coordinate row {row_index} is not a vector3" + if coordinates else f"triangle row {row_index} is invalid" + ) for axis, value in zip("xyz", values): - if type(value) is not float or not math.isfinite(value): - raise ArtifactSerializationError(f"coordinate {row_index}.{axis} is not binary64") - result.extend(struct.pack(" bytes: + return _hash_rows(coordinates, True) def triangle_index_hash_bytes(triangles: Iterable[Iterable[object]]) -> bytes: - result = bytearray() - for row_index, row in enumerate(triangles): - values = tuple(row) - if (len(values) != 3 or any(type(value) is not int or not -(1 << 63) <= value < (1 << 63) - for value in values)): - raise ArtifactSerializationError(f"triangle row {row_index} is invalid") - result.extend(struct.pack(" bytes: - if not isinstance(contract_sha256, str) or SHA256_RE.fullmatch(contract_sha256) is None: - raise ArtifactSerializationError("contract SHA-256 must be lowercase 64-hex") + if not isinstance(contract_sha256, str) or SHA256_RE.fullmatch(contract_sha256) is None: raise ArtifactSerializationError("contract SHA-256 must be lowercase 64-hex") return f"{contract_sha256} {CONTRACT_ROLE}\n".encode("ascii") def validate_contract_sidecar(data: bytes | bytearray | memoryview, expected_sha256: str) -> None: - if bytes(data) != contract_sidecar_bytes(expected_sha256): - raise ArtifactSerializationError("contract sidecar is not the exact required line") + if bytes(data) != contract_sidecar_bytes(expected_sha256): raise ArtifactSerializationError("contract sidecar is not the exact required line") +def _closed_inventory_fd(root_fd: int, expected: tuple[str, ...], + max_file_bytes: int | None) -> tuple[tuple[dict[str, Any], ...], tuple[Any, ...]]: + expected_dirs = set() + for role in expected: + while "/" in role: + role = role.rsplit("/", 1)[0] + expected_dirs.add(role) + first = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) + second = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) + files = tuple(sorted((role for role, value in first.items() if value[1] is not None), key=lambda value: value.encode("utf-8"))) + if first != second or files != expected: raise ArtifactSerializationError("closed inventory changed or does not match") + identities = tuple(sorted(((role, value[0]) for role, value in first.items() if role), key=lambda row: row[0].encode("utf-8"))) + return tuple(first[role][1] for role in expected), identities def closed_inventory(root: str | os.PathLike[str], roles: Iterable[str], *, max_file_bytes: int | None = None) -> tuple[dict[str, Any], ...]: values = tuple(validate_role_path(role) for role in roles) - if len(set(values)) != len(values): - raise ArtifactSerializationError("closed inventory contains duplicate roles") - if max_file_bytes is not None and (type(max_file_bytes) is not int or max_file_bytes < 0): - raise ArtifactSerializationError("max_file_bytes must be a nonnegative integer") + if len(set(values)) != len(values): raise ArtifactSerializationError("closed inventory contains duplicate roles") + if max_file_bytes is not None and (type(max_file_bytes) is not int or max_file_bytes < 0): raise ArtifactSerializationError("max_file_bytes must be a nonnegative integer") expected = tuple(sorted(values, key=lambda value: value.encode("utf-8"))) root_fd = _open_directory(root) try: - expected_dirs = set() - for role in expected: - while "/" in role: - role = role.rsplit("/", 1)[0] - expected_dirs.add(role) - first = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) - second = _inventory_snapshot(root_fd, expected_dirs, max_file_bytes) - files = tuple(sorted((role for role, value in first.items() if value[1] is not None), - key=lambda value: value.encode("utf-8"))) - if first != second or files != expected: - raise ArtifactSerializationError("closed inventory changed or does not match") - return tuple(first[role][1] for role in expected) + return _closed_inventory_fd(root_fd, expected, max_file_bytes)[0] finally: os.close(root_fd) - - def _inventory_snapshot(root_fd: int, expected_dirs: set[str], max_bytes: int | None) -> dict[str, Any]: snapshot: dict[str, Any] = {} try: - for relative, directories, _files, directory_fd in os.fwalk( - ".", topdown=True, follow_symlinks=False, dir_fd=root_fd): + for relative, directories, _files, directory_fd in os.fwalk(".", topdown=True, follow_symlinks=False, dir_fd=root_fd): prefix = "" if relative == "." else relative.removeprefix("./") before = os.fstat(directory_fd) - if prefix in snapshot and snapshot[prefix][0] != _stat_key(before): - raise ArtifactSerializationError("inventory child directory changed while opening") + if prefix in snapshot and snapshot[prefix][0] != _stat_key(before): raise ArtifactSerializationError("inventory child directory changed while opening") snapshot.setdefault(prefix, (_stat_key(before), None)) names = sorted(os.listdir(directory_fd), key=lambda value: value.encode("utf-8")) child_directories = [] @@ -295,58 +231,71 @@ def _inventory_snapshot(root_fd: int, expected_dirs: set[str], max_bytes: int | _component(name, "inventory entry") role = f"{prefix}/{name}" if prefix else name entry = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - if stat.S_ISLNK(entry.st_mode): - raise ArtifactSerializationError(f"inventory contains a symlink: {role}") + if stat.S_ISLNK(entry.st_mode): raise ArtifactSerializationError(f"inventory contains a symlink: {role}") if stat.S_ISDIR(entry.st_mode): - if role not in expected_dirs: - raise ArtifactSerializationError(f"inventory contains an unexpected directory: {role}") + if role not in expected_dirs: raise ArtifactSerializationError(f"inventory contains an unexpected directory: {role}") snapshot[role] = (_stat_key(entry), None) child_directories.append((name, role, entry)) elif stat.S_ISREG(entry.st_mode): _require_regular(entry, f"inventory file {role}") data, opened = _read_stable_with_identity(directory_fd, name, max_bytes) current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - if (not _same_stat(entry, opened) or not _same_stat(opened, current) - or current.st_size != len(data)): - raise ArtifactSerializationError("inventory file was replaced while reading") - snapshot[role] = (_stat_key(current), - {"role_path": validate_role_path(role), - "bytes": len(data), "sha256": sha256_bytes(data)}) - else: - raise ArtifactSerializationError(f"inventory contains a non-regular entry: {role}") + if not _same_stat(entry, opened) or not _same_stat(opened, current) or current.st_size != len(data): raise ArtifactSerializationError("inventory file was replaced while reading") + snapshot[role] = (_stat_key(current), {"role_path": validate_role_path(role), "bytes": len(data), "sha256": sha256_bytes(data)}) + else: raise ArtifactSerializationError(f"inventory contains a non-regular entry: {role}") for name, _role, expected_entry in child_directories: current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - if not _same_stat(expected_entry, current): - raise ArtifactSerializationError("inventory child entry changed during traversal") - directories[:] = [name for name in directories - if (f"{prefix}/{name}" if prefix else name) in expected_dirs] + if not _same_stat(expected_entry, current): raise ArtifactSerializationError("inventory child entry changed during traversal") + directories[:] = [name for name in directories if (f"{prefix}/{name}" if prefix else name) in expected_dirs] after = sorted(os.listdir(directory_fd), key=lambda value: value.encode("utf-8")) - if names != after or not _same_stat(before, os.fstat(directory_fd)): - raise ArtifactSerializationError("inventory directory changed during traversal") + if names != after or not _same_stat(before, os.fstat(directory_fd)): raise ArtifactSerializationError("inventory directory changed during traversal") except (OSError, UnicodeError) as exc: raise ArtifactSerializationError("inventory traversal failed") from exc return snapshot - - +def _freeze_inventory(records: Iterable[Mapping[str, Any]]) -> tuple[tuple[str, int, str], ...]: + try: + values = tuple(records) + if any(not isinstance(record, Mapping) or set(record) != {"role_path", "bytes", "sha256"} for record in values): raise ArtifactSerializationError("expected inventory must contain closed file_records") + frozen = tuple((validate_role_path(record["role_path"]), record["bytes"], record["sha256"]) + for record in values) + except (KeyError, TypeError, UnicodeError, ValueError) as exc: + if isinstance(exc, ArtifactSerializationError): raise + raise ArtifactSerializationError("expected inventory must contain closed file_records") from exc + if any(type(size) is not int or size < 0 or not isinstance(digest, str) or SHA256_RE.fullmatch(digest) is None for _role, size, digest in frozen): raise ArtifactSerializationError("expected inventory contains an invalid file_record") + ordered = tuple(sorted(frozen, key=lambda row: row[0].encode("utf-8"))) + if frozen != ordered or len({role for role, _size, _digest in frozen}) != len(frozen): raise ArtifactSerializationError("expected inventory must be uniquely ordered by role_path") + return frozen +def _inventory_verifier(fd: int, expected: tuple[tuple[str, int, str], ...], max_bytes: int): + root, roles, baseline = os.fstat(fd), tuple(row[0] for row in expected), None + def verify() -> None: + nonlocal baseline + if stat.S_ISDIR(root.st_mode): + records, identities = _closed_inventory_fd(fd, roles, max_bytes) + else: + if len(expected) != 1: raise ArtifactSerializationError("regular-file publication requires exactly one file_record") + try: data, identity = _read_stable_fd(fd, max_bytes) + except OSError as exc: raise ArtifactSerializationError("publication inventory cannot be read stably") from exc + records = ({"role_path": roles[0], "bytes": len(data), "sha256": sha256_bytes(data)},) + identities = ((roles[0], _stat_key(identity, _PUBLISHED_STAT_FIELDS)),) + if _freeze_inventory(records) != expected: raise ArtifactSerializationError("publication inventory does not match expected records") + if baseline is None: baseline = identities + elif identities != baseline: raise ArtifactSerializationError("publication inventory file identities changed") + return verify def _rename_no_replace(parent_fd: int, source: str, destination: str) -> None: - if os.name != "posix": - raise ArtifactSerializationError("atomic no-replace publication requires Linux/WSL") + if os.name != "posix": raise ArtifactSerializationError("atomic no-replace publication requires Linux/WSL") function = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) - if function is None: - raise ArtifactSerializationError("renameat2 is unavailable") - function.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, - ctypes.c_char_p, ctypes.c_uint] + if function is None: raise ArtifactSerializationError("renameat2 is unavailable") + function.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] function.restype = ctypes.c_int - result = function(parent_fd, os.fsencode(source), parent_fd, - os.fsencode(destination), RENAME_NOREPLACE) - if result == 0: - return + result = function(parent_fd, os.fsencode(source), parent_fd, os.fsencode(destination), RENAME_NOREPLACE) + if result == 0: return error = ctypes.get_errno() - if error == errno.EEXIST: - raise FileExistsError(destination) + if error == errno.EEXIST: raise FileExistsError(destination) raise ArtifactSerializationError(f"atomic no-replace rename failed: {os.strerror(error)}") - - +def _verify_canonical_publication(parent_fd: int, parent_path: Path, destination: str, expected: os.stat_result) -> None: + try: current_parent = os.stat(parent_path, follow_symlinks=False); current_target = os.stat(parent_path / destination, follow_symlinks=False) + except OSError as exc: raise ArtifactSerializationError("requested publication pathname changed") from exc + if not os.path.samestat(os.fstat(parent_fd), current_parent) or not _same_published_state(expected, current_target): raise ArtifactSerializationError("published entry is not bound to requested pathname") def _move_to_rollback_quarantine(parent_fd: int, name: str) -> str: """Atomically preserve the entry currently at name under a fresh sibling name.""" for _ in range(32): @@ -354,24 +303,13 @@ def _move_to_rollback_quarantine(parent_fd: int, name: str) -> str: try: _rename_no_replace(parent_fd, name, quarantine) return quarantine - except FileExistsError: - continue + except FileExistsError: continue raise ArtifactSerializationError("unable to allocate publication rollback quarantine") - - -def _rollback_publication(parent_fd: int, source: str, destination: str, - expected_fd: int) -> bool: - """Restore the expected inode to source without deleting any directory entry.""" +def _rollback_publication(parent_fd: int, source: str, destination: str, expected_fd: int) -> bool: + """Restore the expected inode or quarantine a replacement; never delete either.""" quarantine = _move_to_rollback_quarantine(parent_fd, destination) moved = os.stat(quarantine, dir_fd=parent_fd, follow_symlinks=False) - if not os.path.samestat(os.fstat(expected_fd), moved): - try: - _rename_no_replace(parent_fd, quarantine, destination) - except Exception as exc: - raise ArtifactSerializationError( - "unrelated destination entry remains preserved in rollback quarantine" - ) from exc - return False + if not os.path.samestat(os.fstat(expected_fd), moved): return False try: _rename_no_replace(parent_fd, quarantine, source) except FileExistsError as exc: @@ -379,71 +317,76 @@ def _rollback_publication(parent_fd: int, source: str, destination: str, "staging name was occupied; published entry remains in rollback quarantine" ) from exc restored = os.stat(source, dir_fd=parent_fd, follow_symlinks=False) - if not os.path.samestat(os.fstat(expected_fd), restored): - raise ArtifactSerializationError("rolled-back staging entry was replaced") + if not os.path.samestat(os.fstat(expected_fd), restored): raise ArtifactSerializationError("rolled-back staging entry was replaced") return True +def _require_absent(parent_fd: int, name: str, error_name: str) -> None: + try: + os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + return + raise FileExistsError(error_name) - -def _publish_at(parent_fd: int, source: str, destination: str, - expected: os.stat_result, expected_fd: int) -> None: - _require_same_stat(expected, os.fstat(expected_fd), - "pinned staging entry changed before publication") +def _publish_at(parent_fd: int, parent_path: Path, source: str, destination: str, expected: os.stat_result, expected_fd: int, verify=None) -> None: + _require_same_stat(expected, os.fstat(expected_fd), "pinned staging entry changed before publication") current = os.stat(source, dir_fd=parent_fd, follow_symlinks=False) _require_publishable(current, "staging entry") if not _same_stat(expected, current): raise ArtifactSerializationError("staging entry changed before publication") - try: - os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) - except FileNotFoundError: - pass - else: - raise FileExistsError(destination) + if verify is not None: verify() + _require_absent(parent_fd, destination, destination) renamed = False try: _rename_no_replace(parent_fd, source, destination) - renamed = True + renamed = True; _verify_canonical_publication(parent_fd, parent_path, destination, expected) installed = os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) _require_publishable(installed, "published entry") if not _same_published_state(expected, installed): raise ArtifactSerializationError("published entry identity changed") os.fsync(parent_fd) + if verify is not None: verify() verified = os.stat(destination, dir_fd=parent_fd, follow_symlinks=False) - if (not os.path.samestat(expected, verified) - or not _same_published_state(expected, verified)): - raise ArtifactSerializationError("published entry changed after fsync") - _require_publishable(verified, "published entry") + if not os.path.samestat(expected, verified) or not _same_published_state(expected, verified): raise ArtifactSerializationError("published entry changed after fsync") + _require_publishable(verified, "published entry"); _verify_canonical_publication(parent_fd, parent_path, destination, expected) except Exception as publication_failure: if renamed: - try: - rolled_back = _rollback_publication( - parent_fd, source, destination, expected_fd - ) - except Exception as rollback_failure: - raise ArtifactSerializationError( - "publication failed and exact atomic rollback did not complete; " - f"original failure: {publication_failure}" - ) from rollback_failure - if not rolled_back: - raise ArtifactSerializationError( - "publication failed after destination replacement; " - "the unrelated entry was preserved" - ) from publication_failure + _handle_publication_failure( + parent_fd, source, destination, expected_fd, publication_failure + ) raise -def publish_no_replace(staging: str | os.PathLike[str], destination: str | os.PathLike[str]) -> Path: +def _handle_publication_failure(parent_fd: int, source: str, destination: str, expected_fd: int, failure: Exception) -> None: + try: + rolled_back = _rollback_publication(parent_fd, source, destination, expected_fd) + except Exception as rollback_failure: + raise ArtifactSerializationError( + "publication failed and exact atomic rollback did not complete; " + f"original failure: {failure}" + ) from rollback_failure + if not rolled_back: + raise ArtifactSerializationError( + "publication failed after destination replacement; the unrelated entry was quarantined" + ) from failure + +def publish_no_replace(staging: str | os.PathLike[str], destination: str | os.PathLike[str], expected_inventory: Iterable[Mapping[str, Any]], *, max_file_bytes: int) -> Path: + """Publish a sibling only if its pinned files still match prior closed inventory records.""" + expected = _freeze_inventory(expected_inventory) + if type(max_file_bytes) is not int or max_file_bytes < 0: raise ArtifactSerializationError("max_file_bytes must be a nonnegative integer") stage, target = _path(staging), _path(destination) - if stage.parent != target.parent or stage.name == target.name: - raise ArtifactSerializationError("staging and destination must be distinct siblings") + if stage.parent != target.parent or stage.name == target.name: raise ArtifactSerializationError("staging and destination must be distinct siblings") _component(stage.name, "staging name") _component(target.name, "destination name") parent_fd = _open_directory(stage.parent) - source_fd = -1 + source_fd = inventory_fd = -1 try: - source_fd = os.open(stage.name, _PATH | _NOFOLLOW | _CLOEXEC, - dir_fd=parent_fd) + source_fd = os.open(stage.name, _PATH | _NOFOLLOW | _CLOEXEC, dir_fd=parent_fd) source = os.fstat(source_fd) _require_publishable(source, "staging entry") - _publish_at(parent_fd, stage.name, target.name, source, source_fd) + inventory_fd = os.open(stage.name, os.O_RDONLY | os.O_NONBLOCK | _NOFOLLOW | _CLOEXEC, dir_fd=parent_fd) + _require_same_stat(source, os.fstat(inventory_fd), "staging entry changed before inventory binding") + _publish_at(parent_fd, stage.parent, stage.name, target.name, source, source_fd, + _inventory_verifier(inventory_fd, expected, max_file_bytes)) finally: + if inventory_fd >= 0: + os.close(inventory_fd) if source_fd >= 0: os.close(source_fd) os.close(parent_fd) @@ -452,45 +395,36 @@ def _temporary_file(parent_fd: int, target_name: str) -> tuple[int, str]: for _ in range(32): name = f".{target_name}.stage-{os.getpid()}-{secrets.token_hex(8)}" try: - fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW | _CLOEXEC, - 0o600, dir_fd=parent_fd) + fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW | _CLOEXEC, 0o600, dir_fd=parent_fd) return fd, name except FileExistsError: continue raise ArtifactSerializationError("unable to create a unique temporary artifact") def write_bytes_no_replace(path: str | os.PathLike[str], data: bytes) -> Path: - if not isinstance(data, bytes): - raise ArtifactSerializationError("atomic payload must be bytes") + if not isinstance(data, bytes): raise ArtifactSerializationError("atomic payload must be bytes") target = _path(path) _component(target.name, "destination name") parent_fd = _open_directory(target.parent) - descriptor, temporary_name = -1, "" + descriptor = -1 try: - try: - os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) - except FileNotFoundError: - pass - else: - raise FileExistsError(str(target)) + _require_absent(parent_fd, target.name, str(target)) descriptor, temporary_name = _temporary_file(parent_fd, target.name) identity = os.fstat(descriptor) _require_regular(identity, "temporary artifact") view = memoryview(data) while view: written = os.write(descriptor, view) - if written <= 0: - raise ArtifactSerializationError("temporary artifact write made no progress") + if written <= 0: raise ArtifactSerializationError("temporary artifact write made no progress") view = view[written:] os.fsync(descriptor) identity = os.fstat(descriptor) _require_regular(identity, "temporary artifact") - _publish_at(parent_fd, temporary_name, target.name, identity, descriptor) + _publish_at(parent_fd, target.parent, temporary_name, target.name, identity, descriptor) os.close(descriptor) descriptor = -1 return target except Exception: - if descriptor >= 0: - os.close(descriptor) + if descriptor >= 0: os.close(descriptor) # Conditional unlink by pathname is not available. Retaining the # staging entry is safer than deleting an adversarial replacement. raise diff --git a/experiments/owned-root-assembly-successor/build_owned_root.py b/experiments/owned-root-assembly-successor/build_owned_root.py new file mode 100644 index 0000000..f90efd6 --- /dev/null +++ b/experiments/owned-root-assembly-successor/build_owned_root.py @@ -0,0 +1,431 @@ +"""Private managed-test and seeded-bundle builder for the frozen successor.""" +from __future__ import annotations +import datetime, importlib.metadata, importlib.util, io, locale, math, os, platform, re +import shutil, struct, sys, sysconfig, tempfile, time, unittest, zlib +from pathlib import Path; import artifact_serialization as artifacts +ROOT = Path(__file__).resolve().parents[2] +PACKAGE, TESTS = ROOT / "experiments/owned-root-assembly-successor", ROOT / "experiments/owned-root-assembly-successor/tests" +CONTRACT_ROLE, SIDECAR_ROLE, SOURCE_ROLE = ("experiments/owned-root-assembly-successor/design-contract.md", "experiments/owned-root-assembly-successor/design-contract.sha256", "examples/body-documents/stylized-digitigrade-biped-authored-form.json") +PROFILE_ROLE, LAUNCHER_ROLE, REQUIREMENTS_ROLE = ("experiments/current-form-surface-preview/structural_profile_candidates.json", "experiments/current-form-surface-preview/surface_preview_launcher.sh", "experiments/current-form-surface-preview/requirements.txt") +EXPECTED_CONTRACT_SHA256 = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +EXPECTED_SOURCE_SHA256 = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +EXPECTED_PROFILE_SHA256 = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES = 56984, 29970 +IMPLEMENTATION_ROLES = tuple("experiments/owned-root-assembly-successor/anatomy_gates.py experiments/owned-root-assembly-successor/artifact_serialization.py experiments/owned-root-assembly-successor/build_owned_root.py experiments/owned-root-assembly-successor/chart_lineage.py experiments/owned-root-assembly-successor/compare_two_seed_outputs.py experiments/owned-root-assembly-successor/mesh_correctness.py experiments/owned-root-assembly-successor/owned_root_launcher.sh experiments/owned-root-assembly-successor/owned_root_surface.py experiments/owned-root-assembly-successor/prepared_projection.py experiments/owned-root-assembly-successor/render_export.py experiments/owned-root-assembly-successor/tests/test_build_owned_root.py experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py experiments/owned-root-assembly-successor/tests/test_prepared_projection.py experiments/owned-root-assembly-successor/tests/test_render_export.py".split()) +FORMULA_IDS = tuple("formula.axial.j1.edge formula.axial.j1.interior formula.axial.station formula.neck.stem formula.shoulder.left formula.shoulder.right formula.hip.left formula.hip.right".split()) +SPECIAL_CASE_IDS = tuple("formula.axial.j1.edge formula.axial.j1.interior formula.neck.stem formula.shoulder.left formula.shoulder.right formula.hip.left formula.hip.right topology.open-port-cap topology.shared-junction".split()) +PARAMETER_IDS = tuple("left.r_y right.r_y lower_pelvis.L_y lower_pelvis.C_z left.r_x right.r_x lower_pelvis.R_x left.r_z right.r_z lower_pelvis.R_f lower_pelvis.R_b left.thigh_start_x left.thigh_start_y left.thigh_start_z right.thigh_start_x right.thigh_start_y right.thigh_start_z neck_collar.C_y neck_collar.rL neck_upper.C_y neck_upper.rL left.axilla_x left.axilla_y right.axilla_x right.axilla_y left.peak_y right.peak_y left.start_lateral right.start_lateral left.start_up right.start_up left.shoulder_depth right.shoulder_depth".split()) +SURFACE_ROLES = ("surface-level-0.ply", "surface-level-1.ply", "surface-level-2.ply") +PERTURBATION_ROLES = tuple(f"perturb-{p.replace('.', '-')}.ply" for p in PARAMETER_IDS) +ARTIFACT_ROLES = (*SURFACE_ROLES, *PERTURBATION_ROLES, "direct.png", "lineage.png", "input-manifest.json", "coordinate-manifest.json", "gate-manifest.json", "causality-manifest.json", "render-manifest.json", "stable-manifest.json", "prepared-input.json", "report.json", "report.sha256") +RUN_REPORT_GATES = tuple(f"seed.{i}.{name}" for i, name in enumerate(("identity", "prepared-input", "catalogs", "geometry-gates", "causality", "serialization"), 1)) +REQUIRED_TEST_IDS = ("test_mesh_correctness.ProductionIntersectionFixtureTests.test_contract_fixture_matrix", "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix") +LEVEL_COUNTS = ((120, 227, 104, 208, 38), (451, 870, 416, 832, 76), (1737, 3404, 1664, 3328, 152)) +MANIFEST_SCHEMAS = {name + "-manifest.json": f"owned-root-assembly-successor-{name}-manifest.v1" for name in ("input", "coordinate", "gate", "causality", "render", "stable")} +RUN_PHASES = ("identity", "prepared-input", "catalogs", "geometry-gates", "causality", "serialization", "total-before-seal") +STABLE_ARTIFACT_ROLES = tuple(sorted((*SURFACE_ROLES, "direct.png", "lineage.png"), key=str.encode)) +_SHA256 = re.compile(r"[0-9a-f]{64}\Z") +_UTC = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\Z") +_RUNTIME_DISTS = (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")) +_DIRECT_DISTS = (("numpy", "2.2.6"), ("scikit-image", "0.25.2"), ("pillow", "11.1.0")) +class BuildError(ValueError): """A closed builder admission, evidence, or publication failure.""" +def _fail(message): raise BuildError(message) +def _need(condition, message): return None if condition else _fail(message) +def _order(values): return tuple(sorted(values, key=lambda value: value.encode("utf-8"))) +def _order_records(records, field): return sorted(records, key=lambda row: row[field].encode("utf-8")) +def _record(role): + path = ROOT / role; _need(not path.is_symlink() and path.is_file(), f"missing or non-regular fixed file: {role}") + try: return artifacts.regular_file_record(path, role, max_bytes=64 * 1024 if role == REQUIREMENTS_ROLE else 4 * 1024 * 1024) + except Exception as exc: raise BuildError(f"cannot admit fixed file: {role}") from exc +def _implementation_files(): + found = [] + for directory, subdirectories, filenames in os.walk(PACKAGE, followlinks=False): + subdirectories[:] = [n for n in subdirectories if not (Path(directory) / n).is_symlink()]; found.extend((Path(directory) / n).relative_to(ROOT).as_posix() for n in filenames if Path(n).suffix in (".py", ".sh")) + expected, found = _order(IMPLEMENTATION_ROLES), _order(found); _need(found == expected, f"implementation allowlist mismatch; missing={sorted(set(expected) - set(found), key=str.encode)}; extra={sorted(set(found) - set(expected), key=str.encode)}"); return tuple(_record(role) for role in expected) +def _runtime_text(value, label, limit=128): return value if type(value) is str and len(value.encode("utf-8")) <= limit else _fail(f"{label} is not a bounded runtime string") +def _distribution(name, version): + try: actual = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError as exc: raise BuildError(f"missing required distribution: {name}=={version}") from exc + _need(actual == version, f"wrong distribution version: {name}=={actual}, expected {version}"); return {"name": name.lower(), "version": _runtime_text(actual, f"{name}.version")} +def _builtin(name): + module, spec = __import__(name), importlib.util.find_spec(name); _need(getattr(module, "__file__", None) is None and spec is not None and spec.origin == "built-in", f"{name} is not admitted as a built-in module"); versions = (None, None) if name == "math" else (_runtime_text(zlib.ZLIB_VERSION, "zlib compile version"), _runtime_text(zlib.ZLIB_RUNTIME_VERSION, "zlib runtime version")); return {"module_name": name, "__file__": None, "find_spec_origin": "built-in", "compile_version": versions[0], "runtime_version": versions[1]} +def _runtime(launcher, requirements): + _need(platform.python_implementation() == "CPython" and platform.python_version() == "3.10.12" and getattr(sys.implementation, "cache_tag", None) == "cpython-310", "runtime requires CPython 3.10.12 with cache tag cpython-310"); soabi = sysconfig.get_config_var("SOABI"); _need(type(soabi) is str, "runtime SOABI is missing") + python = {"implementation": "CPython", "version": "3.10.12", "build": _runtime_text(" ".join(platform.python_build()), "python.build"), "compiler": _runtime_text(platform.python_compiler(), "python.compiler"), "cache_tag": "cpython-310", "abiflags": _runtime_text(getattr(sys, "abiflags", ""), "python.abiflags"), "soabi": _runtime_text(soabi, "python.soabi")} + libc_name, libc_version = platform.libc_ver(); platform_value = {"system": platform.system(), "release": platform.release(), "version": platform.version(), "machine": platform.machine(), "pointer_bits": 8 * struct.calcsize("P"), "byteorder": sys.byteorder, "libc_name": libc_name, "libc_version": libc_version} + for key in ("system", "release", "version", "machine", "libc_name", "libc_version"): platform_value[key] = _runtime_text(platform_value[key], f"platform.{key}") + _need(platform_value["system"] == "Linux" and platform_value["byteorder"] in ("little", "big") and type(platform_value["pointer_bits"]) is int and platform_value["pointer_bits"] > 0, "runtime platform is not admitted"); locale_value = {"active": _runtime_text(locale.setlocale(locale.LC_ALL, None), "locale.active", 512), "preferred_encoding": _runtime_text(locale.getpreferredencoding(False), "locale.preferred_encoding", 512)}; return {"schema": "owned-root-assembly-successor-runtime.v2", "python": python, "platform": platform_value, "locale": locale_value, "managed_launcher": launcher, "requirements": requirements, "direct_distributions": [_distribution(*d) for d in _DIRECT_DISTS], "resolved_distributions": [_distribution(*d) for d in _RUNTIME_DISTS], "builtin_modules": [_builtin("math"), _builtin("zlib")]} +def _static_admission(): + contract, sidecar = _record(CONTRACT_ROLE), _record(SIDECAR_ROLE); _need(contract["bytes"] == 173184 and contract["sha256"] == EXPECTED_CONTRACT_SHA256, "contract identity mismatch"); sidecar_bytes = f"{EXPECTED_CONTRACT_SHA256} {CONTRACT_ROLE}\n".encode("ascii"); _need(sidecar["bytes"] == len(sidecar_bytes) and artifacts.read_regular_file(ROOT / SIDECAR_ROLE) == sidecar_bytes, "contract sidecar identity mismatch") + source, profile = _record(SOURCE_ROLE), _record(PROFILE_ROLE); _need((source["bytes"], source["sha256"]) == (EXPECTED_SOURCE_BYTES, EXPECTED_SOURCE_SHA256) and (profile["bytes"], profile["sha256"]) == (EXPECTED_PROFILE_BYTES, EXPECTED_PROFILE_SHA256), "source or profile identity mismatch"); launcher, requirements = _record(LAUNCHER_ROLE), _record(REQUIREMENTS_ROLE); _need(artifacts.read_regular_file(ROOT / REQUIREMENTS_ROLE) == b"numpy==2.2.6\nscikit-image==0.25.2\nPillow==11.1.0\n", "requirements are not the exact pinned file") + implementation = _implementation_files(); runtime = _runtime(launcher, requirements); runtime_bytes = artifacts.canonical_json_bytes(runtime); _need(len(runtime_bytes) <= 64 * 1024, "runtime fingerprint exceeds 64 KiB"); return {"contract": contract, "source": source, "profile_table": profile, "runtime": runtime, "runtime_bytes": runtime_bytes, "runtime_fingerprint_sha256": artifacts.sha256_bytes(runtime_bytes), "implementation_files": implementation} +def _recipe(admission): + value = {"schema": "owned-root-assembly-successor-recipe.v1", "contract_role": CONTRACT_ROLE, "contract_sha256": EXPECTED_CONTRACT_SHA256, "sidecar_role": SIDECAR_ROLE, "source": admission["source"], "profile_table": admission["profile_table"], "profile_id": "standard_neutral_reference", "correction_round": 0, "topology_id": "owned-root-58-cell-120-control-104-quad.v1", "formula_ids": list(_order(FORMULA_IDS)), "subdivision_levels": 2, "special_case_ids": list(_order(SPECIAL_CASE_IDS)), "gate_set_id": "owned-root-neutral-gates.v1", "renderer_id": "owned-root-raster-pillow-11.1.0.v1", "artifact_roles": list(_order(ARTIFACT_ROLES)), "implementation_files": list(admission["implementation_files"]), "runtime_fingerprint_sha256": admission["runtime_fingerprint_sha256"]}; return value, artifacts.sha256_bytes(artifacts.canonical_json_bytes(value)) +def _gate(gate_id, count, minimum, maximum, relation, lower, upper, unit): + threshold = {"threshold_id": f"threshold.{gate_id}", "relation": relation, "lower": lower, "upper": upper, "unit": unit}; passed = minimum == lower and maximum == upper if relation == "eq" else minimum >= lower if relation == "ge" else maximum <= upper if relation == "le" else maximum < upper; return {"gate_id": gate_id, "outcome": "pass" if passed else "fail", "sample_count": count, "observed_min": minimum, "observed_max": maximum, "threshold_id": threshold["threshold_id"]}, threshold +def _bool(gate_id): return _gate(gate_id, 1, 1, 1, "eq", 1, 1, "boolean") +def _put(rows, thresholds, pair): rows.append(pair[0]); thresholds.append(pair[1]) +def _directions(surface): return {name: {"+X": (1.0, 0.0, 0.0), "-X": (-1.0, 0.0, 0.0), "+Y": (0.0, 1.0, 0.0), "-Y": (0.0, -1.0, 0.0)}[info[1]] for name, info in surface.PORT_INFO.items()} +def _chart_owners(mesh, summary): + if summary is None: return tuple(mesh.face_owners) + rows = [row for row in summary["chart_records"] if row["level"] == mesh.level]; owners = {} + for row in rows: + if row["face_id"] in owners: _fail(f"duplicate chart face ownership at L{mesh.level}") + owners[row["face_id"]] = row["construction_owner"] + _need(len(rows) == len(mesh.face_ids) and set(owners) == set(mesh.face_ids), f"chart face incidence is incomplete at L{mesh.level}"); return tuple(owners[face_id] for face_id in mesh.face_ids) +def _junction_cycles(mesh, owners, domains): + uses = {} + for face_index, face in enumerate(mesh.quads): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4]; uses.setdefault(tuple(sorted((left, right))), []).append((owners[face_index], left, right)) + result = [] + for domain in domains: + following = {} + for rows in uses.values(): + if len(rows) != 2 or frozenset(row[0] for row in rows) != frozenset(domains): continue + selected = [row for row in rows if row[0] == domain]; _need(len(selected) == 1, "junction domain incidence is not independently unique") + if selected[0][1] in following: _fail("junction domain incidence has duplicate trace starts") + following[selected[0][1]] = selected[0][2] + _need(following, f"no junction trace for {domain}"); start = current = min(following); cycle = [] + while current not in cycle: + cycle.append(current); _need(current in following, "junction trace is not closed"); current = following[current] + _need(current == start and len(cycle) == len(following), "junction trace is not one closed cycle"); result.append(tuple(cycle)) + return tuple(result) +def _half_tag(left, right): + numerator = left[0] * right[1] + right[0] * left[1]; denominator = 2 * left[1] * right[1]; common = math.gcd(abs(numerator), denominator); return numerator // common, denominator // common +def _domain_tags(meshes, owners, domains, domain_index, axes, level, surface): + axis_index = {"i": 0, "j": 1, "k": 2}; cycles = tuple(_junction_cycles(mesh, owner, domains)[domain_index] for mesh, owner in zip(meshes[:level + 1], owners[:level + 1])); tags = {vertex: tuple((surface.COORDINATE_BY_CONTROL[meshes[0].control_ids[vertex]][axis_index[axis]], 1) for axis in axes) for vertex in cycles[0]} + for current in range(1, level + 1): + points = dict(surface.subdivision_incidence(meshes[current - 1])["edge_point_indices"]); previous = cycles[current - 1]; out = {vertex: tags[vertex] for vertex in cycles[current] if vertex in tags} + for slot, left in enumerate(previous): + right = previous[(slot + 1) % len(previous)]; edge = tuple(sorted((left, right))); point = points.get(edge); _need(point is not None, "junction edge midpoint is absent"); out[point] = tuple(_half_tag(tags[left][axis], tags[right][axis]) for axis in range(2)) + _need(set(out) == set(cycles[current]), "junction tag incidence is incomplete"); tags = out + return dict(sorted(tags.items())) +def _junction_inputs(surface, evaluation, level, chart_summary=None): + meshes = (evaluation.cage, *evaluation.levels); _need(level in range(3), "junction level is outside the frozen three-level universe"); owners = tuple(_chart_owners(mesh, chart_summary) for mesh in meshes); result = {} + for junction in surface.JUNCTIONS: + domains, (_drop, axes) = surface.JUNCTION_INFO[junction]; maps = tuple(_domain_tags(meshes, owners, domains, index, axes, level, surface) for index in range(2)); reference = tuple(_domain_tags(meshes, owners, domains, index, axes, level, surface) for index in range(2)); result[junction] = {"incident_domains": domains, "domain_vertex_tags": maps, "expected_domain_vertex_tags": reference} + return result +def _metric_values(mesh): + edges = {tuple(sorted((left, face[(slot + 1) % 4]))) for face in mesh.quads for slot, left in enumerate(face)} + sub = lambda a, b: tuple(a[i] - b[i] for i in range(3)); cross = lambda a, b: (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); norm = lambda p: math.sqrt(sum(v * v for v in p)) + edge = tuple(norm(sub(mesh.vertices[b], mesh.vertices[a])) for a, b in sorted(edges)); triangles, quads = [], [] + for face in mesh.quads: + a, b, c, d = (mesh.vertices[i] for i in face); areas = (0.5 * norm(cross(sub(b, a), sub(c, a))), 0.5 * norm(cross(sub(c, a), sub(d, a)))); triangles.extend(areas); quads.append(sum(areas)) + return edge, tuple(triangles), tuple(quads) +def _edge_uses(mesh): + uses = {} + for face_index, face in enumerate(mesh.quads): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4]; uses.setdefault(tuple(sorted((left, right))), []).append(face_index) + return uses +def _edge_candidates(uses, owners, boundary, junction_edges): + result = [] + for edge, faces in uses.items(): + if len(faces) == 1 and edge in boundary: result.append((("edge", edge), "classification", True)) + if len(faces) == 2 and owners[faces[0]] == owners[faces[1]]: result.append((("edge", edge), "classification", True)) + if len(faces) == 2 and edge in junction_edges.get(frozenset(owners[index] for index in faces), ()): result.append((("edge", edge), "classification", True)) + return result +def _fold_samples(mesh, surface, junction, level, mesh_api): + uses = {} + for face_index, face in enumerate(mesh.quads): + for slot, left in enumerate(face): uses.setdefault(tuple(sorted((left, face[(slot + 1) % 4]))), []).append(face_index) + owners = frozenset(surface.JUNCTION_INFO[junction][0]) + values = tuple(mesh_api.fold_angle_degrees(mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[0]]), mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[1]])) for faces in uses.values() if len(faces) == 2 and frozenset(mesh.face_owners[i] for i in faces) == owners); _need(bool(values), f"no fold samples for {junction} at L{level}"); return values +def _ownership_counts(surface, evaluation, chart_api, mesh_api, prepared, formulas, summary, level): + mesh = (evaluation.cage, *evaluation.levels)[level]; uses = _edge_uses(mesh); expected_counts = LEVEL_COUNTS[level]; _need((len(mesh.control_ids), len(mesh.quads), len(uses), len(surface.PORTS)) == (expected_counts[0], expected_counts[2], expected_counts[1], 5) and sum((expected_counts[0], expected_counts[2], expected_counts[1], 5)) == (456, 1742, 6810)[level], f"ownership element universe changed at L{level}") + edges = tuple(uses); keys = tuple(("vertex", value) for value in mesh.control_ids) + tuple(("face", value) for value in mesh.face_ids) + tuple(("edge", value) for value in edges) + tuple(("boundary", value) for value in surface.PORTS); required = {key: ("construction", "lineage") if level == 0 and key[0] == "vertex" else ("lineage",) if key[0] == "vertex" else ("chart",) if key[0] == "face" else ("classification",) if key[0] == "edge" else ("boundary",) for key in keys}; expected = chart_api.build_chart_summary(evaluation, formulas); formula_by_id = {row["control_id"]: row for row in formulas}; expected_vertices = {(row["level"], row["vertex_id"]): row for row in expected["vertex_records"]}; expected_faces = {(row["level"], row["face_id"]): row for row in expected["chart_records"]}; records = [( ("vertex", row["control_id"]), "construction", row == formula_by_id.get(row["control_id"]) ) for row in evaluation.cage.formula_records] if level == 0 else [] + records.extend((("vertex", row["vertex_id"]), "lineage", row == expected_vertices.get((level, row["vertex_id"]))) for row in summary["vertex_records"] if row["level"] == level); records.extend((("face", row["face_id"]), "chart", row == expected_faces.get((level, row["face_id"]))) for row in summary["chart_records"] if row["level"] == level) + owners = mesh.face_owners; junction_edges = {} + for junction in surface.JUNCTIONS: + domains = surface.JUNCTION_INFO[junction][0]; cycle = _junction_cycles(mesh, owners, domains)[0]; junction_edges[frozenset(domains)] = {tuple(sorted((left, cycle[(slot + 1) % len(cycle)]))) for slot, left in enumerate(cycle)} + boundary = {edge for edge, faces in uses.items() if len(faces) == 1}; records.extend(_edge_candidates(uses, owners, boundary, junction_edges)); records.extend((("boundary", port), "boundary", all(edge in boundary for edge in {tuple(sorted((left, loop[(slot + 1) % len(loop)]))) for slot, left in enumerate(loop)}) and len(boundary) == sum(len({tuple(sorted((left, loop[(slot + 1) % len(loop)]))) for slot, left in enumerate(values)}) for _, values in mesh.boundary_loops)) for port, loop in mesh.boundary_loops) + return mesh_api.classify_ownership_records(keys, required, tuple(records)) +def _invalid_counts(mesh, report, edges, triangles, ownership, surface): + return {"duplicate_vertex_ids": len(mesh.control_ids) - len(set(mesh.control_ids)), "duplicate_face_ids": len(mesh.face_ids) - len(set(mesh.face_ids)), "degenerate_faces": sum(triangles[2 * index] <= 0.0 or triangles[2 * index + 1] <= 0.0 for index in range(len(mesh.quads))), "zero_length_edges": sum(value == 0.0 for value in edges), "non_manifold_edges": report["topology"].non_manifold_edges, "orientation_conflicts": report["topology"].orientation_conflicts, "unowned_elements": ownership["unowned_elements"], "overowned_elements": ownership["overowned_elements"], "accidental_boundary_components": abs(report["topology"].boundary_components - len(surface.PORTS))} +def _catalog(surface): + surface.validate_catalogs(); values = {"selected_cells": 58, "un_capped_faces": 122, "domains": 8, "junctions": 7, "ports": 5, "controls": 120, "base_quads": 104, "base_edges": 227, "base_boundary_edges": 38, "boundary_components": 5, "connected_components": 1, "euler_characteristic": -3, "extraordinary_controls": 20, "special_case_ids": 9, "topology_decision_sites": 3}; booleans = "all_domains_nonempty selected_cell_inventory_exact control_catalog_exact face_catalog_exact junction_catalog_exact port_catalog_exact special_case_catalog_exact base_face_controls_distinct base_edge_use_within_two construction_ownership_complete port_caps_exactly_removed axillary_fixture_suite_complete intersection_fixture_suite_complete".split(); gates, thresholds = [], [] + [_put(gates, thresholds, _gate(f"structural.catalog.{name}", 1, value, value, *("le", None, 3) if name == "topology_decision_sites" else ("eq", value, value), "dimensionless" if name == "euler_characteristic" else "count")) for name, value in values.items()] + [_put(gates, thresholds, _bool(f"structural.catalog_boolean.{name}")) for name in booleans]; return gates, thresholds +def _sample_gate(rows, thresholds, gate_id, values, relation, lower, upper, unit): + values = tuple(values); _need(bool(values) and all(math.isfinite(value) for value in values), f"{gate_id} has a non-finite or empty raw sample collection"); _put(rows, thresholds, _gate(gate_id, len(values), min(values), max(values), relation, lower, upper, unit)) +def _continuity(surface, mesh_api, evaluation, reports, chart_summary=None): + gates, thresholds, limits = [], [], (90.0, 60.0, 30.0); meshes = (evaluation.cage, *evaluation.levels) + for level, mesh in enumerate(meshes): + inputs = _junction_inputs(surface, evaluation, level, chart_summary) + for junction in surface.JUNCTIONS: + metrics = mesh_api.junction_continuity_metrics(mesh.vertices, mesh.quads, mesh.face_owners, **inputs[junction]); count = len(metrics["traces"][0]); residuals, folds = metrics["coordinate_residual_samples"], _fold_samples(mesh, surface, junction, level, mesh_api); _need(len(residuals) == 3 * count and len(folds) == count, f"continuity sample cardinality changed for {junction} at L{level}") + values = (("tag_identity", (1,), "eq", 1, 1, "boolean"), ("opposite_trace_direction", (1,), "eq", 1, 1, "boolean"), ("coordinate_residual", residuals, "le", None, mesh_api.T, "m"), ("fold_angle", folds, "lt", None, limits[level], "degree")); [_sample_gate(gates, thresholds, f"continuity.{junction}.L{level}.{name}", samples, relation, lower, upper, unit) for name, samples, relation, lower, upper, unit in values] + for port, metric in reports[level]["port_metrics"].items(): + count = len(dict(mesh.boundary_loops)[port]); _need(len(metric["planarity_samples"]) == count and len(metric["co_normal_samples"]) == count, f"port sample cardinality changed for {port} at L{level}"); values = (("orientation", (metric["orientation"],), "ge", .99, None, "dimensionless"), ("planarity", metric["planarity_samples"], "le", None, mesh_api.T, "m"), ("area_ratio", (metric["area_ratio"],), "ge", .0001, None, "dimensionless"), ("co_normal", metric["co_normal_samples"], "ge", .80, None, "dimensionless")); [_sample_gate(gates, thresholds, f"continuity.{port}.L{level}.{name}", samples, relation, lower, upper, unit) for name, samples, relation, lower, upper, unit in values] + return gates, thresholds +def _geometry(surface, mesh_api, chart, anatomy, prepared): + axillary = anatomy.run_production_axillary_fixtures(); _need(len(axillary) == 13 and tuple(row["fixture_id"] for row in axillary) == anatomy.AXILLARY_FIXTURE_IDS, "axillary production fixture suite did not execute its exact 13 IDs") + runner = getattr(mesh_api, "run_production_intersection_fixtures", None); _need(runner is not None, "missing required public API: mesh_correctness.run_production_intersection_fixtures (105 cases)") + fixtures = runner(); _need(len(fixtures) == 105 and tuple(row["fixture_id"] for row in fixtures) == mesh_api.INTERSECTION_FIXTURE_IDS, "intersection production fixture suite did not execute its exact 105 IDs") + evaluation = surface.evaluate(prepared); meshes = (evaluation.cage, *evaluation.levels); formulas = tuple(surface.formula_candidate_records(prepared)); chart_summary = chart.build_chart_summary(evaluation, formulas); chart.validate_chart_summary(chart_summary, evaluation, formulas); anatomy.validate_evaluated_surface(evaluation, chart_summary); anatomy_rows = tuple(anatomy.anatomy_gate_records(evaluation, prepared, chart_summary)) + expected = tuple(tuple(int(control[1:]) for control in row[2]) for row in surface.FACE_RECORDS); derived = mesh_api.derive_expected_face_catalogs(expected); _need(tuple(len(rows) for rows in derived) == (104, 416, 1664), "independently derived expected topology differs") + reports, intersection_reports = [], [] + for level, mesh in enumerate(meshes): + inputs = _junction_inputs(surface, evaluation, level, chart_summary); reports.append(mesh_api.validate_geometry(mesh.vertices, mesh.quads, level, dict(mesh.boundary_loops), _directions(surface), expected, inputs, mesh.face_owners)); intersection_reports.append(mesh_api.intersection_diagnostics(mesh.vertices, mesh.triangles)) + structural, thresholds = [], []; invalid = "duplicate_vertex_ids duplicate_face_ids degenerate_faces zero_length_edges non_manifold_edges orientation_conflicts unowned_elements overowned_elements accidental_boundary_components".split(); chart_counts = {row["level"]: row for row in chart_summary["level_counts"]} + for level, (mesh, report) in enumerate(zip(meshes, reports)): + edge, triangles, quads = _metric_values(mesh); top = report["topology"]; [_put(structural, thresholds, _gate(f"structural.L{level}.count.{name}", 1, value, value, "eq", value, value, "count")) for name, value in zip(("vertices", "edges", "quads", "triangles", "boundary_edges"), (len(mesh.vertices), top.edge_count, len(mesh.quads), len(mesh.triangles), top.boundary_edge_count))] + [_put(structural, thresholds, _bool(f"structural.L{level}.surface_boolean.{name}")) for name in "connected orientable outward_wound boundary_components_match_ports".split()] + [(_put(structural, thresholds, _bool(f"structural.L{level}.finite.{name}")), structural[-1].__setitem__("sample_count", count)) for name, count in (("coordinates", 3 * len(mesh.vertices)), ("quad_normals", 3 * len(mesh.quads)), ("triangle_areas", len(triangles)), ("quad_areas", len(quads)))] + [_put(structural, thresholds, _gate(f"structural.L{level}.floor.{name}", len(values), min(values), max(values), "ge", mesh_api.STRUCTURAL_FLOORS[level][name], None, "m" if name == "edge_length" else "m2")) for name, values in (("edge_length", edge), ("triangle_area", triangles), ("quad_area", quads))] + invalid_values = _invalid_counts(mesh, report, edge, triangles, _ownership_counts(surface, evaluation, chart, mesh_api, prepared, formulas, chart_summary, level), surface); [_put(structural, thresholds, _gate(f"structural.L{level}.invalid_count.{name}", 1, invalid_values[name], invalid_values[name], "eq", 0, 0, "count")) for name in invalid] + [_put(structural, thresholds, _gate(f"structural.L{level}.chart.{name}", 1, chart_counts[level][name], chart_counts[level][name], "eq", chart_counts[level][name], chart_counts[level][name], "count")) for name in ("charts", "interior_transitions", "maximum_samples_per_vertex")] + for name, limit in (("base_control_contributors", 20), ("dependency_union_keys", 54), ("contributor_domains", 5)): + rows = [row for row in chart_summary["vertex_records"] if row["level"] == 2]; field = {"base_control_contributors": "base_control_contributors", "dependency_union_keys": "geometry_dependency_union", "contributor_domains": "contributor_domains"}[name]; value = max(len(row[field]) for row in rows); row, threshold = _gate(f"structural.L2.lineage_cap.{name}", 1737, value, value, "le", None, limit, "count"); structural.append(row); thresholds.append(threshold) + [_put(structural, thresholds, _bool(f"structural.subdivision.{name}")) for name in "recurrence_exact incidence_complete boundary_neighbors_exact face_emission_exact lineage_complete chart_complete transition_complete".split()] + continuity, continuity_thresholds = _continuity(surface, mesh_api, evaluation, reports, chart_summary); thresholds.extend(continuity_thresholds); thresholds.extend(anatomy.anatomy_threshold_records()); intersection, intersection_thresholds = [], [] + for level, (mesh, report) in enumerate(zip(meshes, intersection_reports)): + values = (("triangle_count", report["triangle_count"], "eq", len(mesh.triangles), len(mesh.triangles), "count"), ("broad_phase_candidate_count", report["broad_phase_candidate_count"], "le", None, mesh_api.MAX_CANDIDATES, "count"), ("intersection_hit_count", report["intersection_hit_count"], "eq", 0, 0, "count"), ("pair_policy_complete", int(report["pair_policy_complete"]), "eq", 1, 1, "boolean")) + [_put(intersection, intersection_thresholds, _gate(f"intersection.L{level}.{name}", 1, value, value, relation, lower, upper, unit)) for name, value, relation, lower, upper, unit in values] + thresholds.extend(intersection_thresholds); thresholds.append({"threshold_id": "gate.boolean-pass", "relation": "eq", "lower": 1, "upper": 1, "unit": "dimensionless"}); _need((len(structural), len(continuity), len(anatomy_rows), len(intersection), len(thresholds)) == (94, 144, 78, 12, 329), "geometry gate inventory is not closed"); return {"evaluation": evaluation, "formula_records": formulas, "chart_summary": chart_summary, "reports": reports, "structural": structural, "continuity": continuity, "anatomy": anatomy_rows, "intersection": intersection, "thresholds": thresholds} +def _support_hash(indices): + values = tuple(indices) + if tuple(sorted(set(values))) != values or any(type(index) is not int or not 0 <= index < 1737 for index in values): _fail("support indices are not ascending level-2 indices") + payload = b"CKSUPPORTv1\0\2" + struct.pack(" mesh_api.T); maximum = max(movement) + if not predicted or actual != predicted or maximum < minimum or any(movement[index] > mesh_api.T for index in range(1737) if index not in predicted): _fail(f"support/movement gate failed for {parameter}") + if parameter in ("left.thigh_start_x", "right.thigh_start_x") and len(predicted) != 436: _fail(f"hip support cardinality changed for {parameter}") + role = f"perturb-{parameter.replace('.', '-')}.ply" + payloads[role] = render.ply_bytes(observed) + if payloads[role] == baseline_ply: _fail(f"serialized perturbation is unchanged for {parameter}") + perturbations.append({"parameter_id": parameter, "prepared_component": component, "delta_m": float(surface.PERTURBATION_DELTA_M), "support_level": 2, "predicted_support_count": len(predicted), "observed_support_count": len(actual), "predicted_support_sha256": _support_hash(predicted), "observed_support_sha256": _support_hash(actual), "maximum_movement_m": maximum, "artifact": None}) + return perturbations, payloads +def _manifest_ref(record, schema): return {"role_path": record["role_path"], "bytes": record["bytes"], "sha256": record["sha256"], "schema": schema} +def _write_json(path, value): artifacts.write_canonical_json_no_replace(path, value); return artifacts.regular_file_record(path, path.name) +def _write(path, value): artifacts.write_bytes_no_replace(path, value); return artifacts.regular_file_record(path, path.name) +def _limits(stage, admission): + records = artifacts.closed_inventory(stage, ARTIFACT_ROLES, max_file_bytes=8 * 1024 * 1024) + for record in records: + limit = 8 * 1024 * 1024 if record["role_path"] == "causality-manifest.json" else 2 * 1024 * 1024 + if record["bytes"] > limit: _fail(f"artifact resource cap exceeded: {record['role_path']}") + production = sum(artifacts.read_regular_file(ROOT / record["role_path"]).count(b"\n") for record in admission["implementation_files"] if "/tests/" not in record["role_path"]) + tests = sum(artifacts.read_regular_file(ROOT / record["role_path"]).count(b"\n") for record in admission["implementation_files"] if "/tests/" in record["role_path"]) + if production > 3400 or tests > 2600: _fail(f"implementation LOC cap exceeded: production={production}, tests={tests}") + return records +def _now(): return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") +def _keys(value, expected, label): return value if type(value) is dict and set(value) == set(expected) else _fail(f"{label} does not have the exact closed keys") +def _text(value, label): return value if type(value) is str and value else _fail(f"{label} must be a nonempty string") +def _integer(value, label, minimum=0): return value if type(value) is int and value >= minimum else _fail(f"{label} must be an integer >= {minimum}") +def _binary64(value, label): return artifacts.coerce_binary64(value, label=label) +def _hex(value, label): return value if type(value) is str and _SHA256.fullmatch(value) is not None else _fail(f"{label} must be lowercase SHA-256") +def _absolute(value, label): return Path(value) if type(value) is str and value and Path(value).is_absolute() and os.path.normpath(value) == value else _fail(f"{label} must be an absolute canonical path") +def _same_json(left, right, label): return None if artifacts.canonical_json_bytes(left) == artifacts.canonical_json_bytes(right) else _fail(f"{label} differs from the frozen value") +def _file_record(value, label, role=None): + row = _keys(value, ("role_path", "bytes", "sha256"), label) + try: artifacts.validate_role_path(row["role_path"]) + except Exception as exc: raise BuildError(f"{label}.role_path is invalid") from exc + _need(role is None or row["role_path"] == role, f"{label}.role_path is not {role}"); _integer(row["bytes"], f"{label}.bytes"); _hex(row["sha256"], f"{label}.sha256"); return row +def _manifest_reference(value, label, role, record): _keys(value, ("role_path", "bytes", "sha256", "schema"), label); _need(value == _manifest_ref(record, MANIFEST_SCHEMAS[role]), f"{label} does not reference the exact admitted manifest"); return value +def _validate_identity(identity): + row = _keys(identity, ("contract", "source", "profile_table", "runtime", "runtime_bytes", "runtime_fingerprint_sha256", "implementation_files"), "identity"); contract = _file_record(row["contract"], "identity.contract", CONTRACT_ROLE); source = _file_record(row["source"], "identity.source", SOURCE_ROLE); profile = _file_record(row["profile_table"], "identity.profile_table", PROFILE_ROLE) + if (contract["bytes"], contract["sha256"]) != (173184, EXPECTED_CONTRACT_SHA256) or (source["bytes"], source["sha256"]) != (EXPECTED_SOURCE_BYTES, EXPECTED_SOURCE_SHA256) or (profile["bytes"], profile["sha256"]) != (EXPECTED_PROFILE_BYTES, EXPECTED_PROFILE_SHA256): _fail("identity fixed-file records differ") + implementation = row["implementation_files"]; _need(type(implementation) in (list, tuple) and len(implementation) == 15, "identity implementation inventory is not exactly 15 files") + for index, (record, role) in enumerate(zip(implementation, _order(IMPLEMENTATION_ROLES))): _file_record(record, f"identity.implementation_files[{index}]", role) + runtime_bytes = row["runtime_bytes"]; _need(type(runtime_bytes) is bytes and len(runtime_bytes) <= 64 * 1024 and artifacts.canonical_json_bytes(row["runtime"]) == runtime_bytes and artifacts.sha256_bytes(runtime_bytes) == _hex(row["runtime_fingerprint_sha256"], "identity.runtime_fingerprint_sha256"), "identity runtime bytes or hash differ"); return row +def _canonical_value(raw, value, label): + _need(type(raw) is bytes, f"{label} raw value must be bytes") + try: decoded = artifacts.decode_canonical_json(raw) + except Exception as exc: raise BuildError(f"{label} is not canonical JSON") from exc + _need(decoded == value and artifacts.canonical_json_bytes(value) == raw, f"{label} value differs from its canonical bytes"); return value +def validate_managed_test_receipt(*, receipt, raw, identity): + identity = _validate_identity(identity); value = _canonical_value(raw, receipt, "managed-test receipt"); _keys(value, ("schema", "outcome", "literal_invocation", "contract_sha256", "runtime_fingerprint_sha256", "implementation_files", "executed_test_ids", "required_test_ids", "results"), "managed-test receipt") + _need(value["schema"] == "owned-root-assembly-successor-managed-test-receipt.v1" and value["outcome"] == "success" and value["contract_sha256"] == EXPECTED_CONTRACT_SHA256 and value["runtime_fingerprint_sha256"] == identity["runtime_fingerprint_sha256"] and value["implementation_files"] == list(identity["implementation_files"]), "managed-test receipt identity, schema, or outcome differs") + invocation = _keys(value["literal_invocation"], ("environment", "argv"), "managed-test receipt invocation"); argv = invocation["argv"]; _need(invocation["environment"] == ["PYTHONHASHSEED=0"] and type(argv) is list and len(argv) == 4 and argv[:3] == ["experiments/owned-root-assembly-successor/build_owned_root.py", "--internal-managed-tests", "--receipt"] and _absolute(argv[3], "managed-test receipt path").name == "managed-test-receipt.json", "managed-test receipt invocation differs") + executed, required = value["executed_test_ids"], value["required_test_ids"]; _need(type(executed) is list and bool(executed) and all(type(item) is str and item for item in executed) and executed == list(_order(executed)) and len(executed) == len(set(executed)) and required == list(REQUIRED_TEST_IDS) and all(executed.count(item) == 1 for item in REQUIRED_TEST_IDS), "managed-test executed or required IDs differ") + result = _keys(value["results"], ("tests_run", "failures", "errors", "skipped", "expected_failures", "unexpected_successes"), "managed-test results"); expected = {"tests_run": len(executed), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0} + _need(result == expected and all(type(item) is int for item in result.values()), "managed-test result is not an exact all-pass result") + return value +def validate_run_report(*, root, seed, report, identity): + identity = _validate_identity(identity); _need(type(seed) is int and seed in (17, 29), "run report seed must be integer 17 or 29"); root = Path(root); _need(root.is_absolute() and os.path.normpath(str(root)) == str(root) and root.name == f"seed-{seed}" and not root.is_symlink() and root.is_dir(), "run report root is not the exact admitted seed directory") + value = _keys(report, ("schema", "outcome", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "stable_manifest", "gates"), "run report") + _need(value["schema"] == "owned-root-assembly-successor-run-report.v1" and value["outcome"] == "success" and value["seed"] == seed and type(value["seed"]) is int and value["runtime_fingerprint_sha256"] == identity["runtime_fingerprint_sha256"], "run report identity, schema, outcome, or seed differs") + invocation = _keys(value["literal_invocation"], ("environment", "argv"), "run report invocation"); _need(invocation == {"environment": [f"PYTHONHASHSEED={seed}"], "argv": ["experiments/owned-root-assembly-successor/build_owned_root.py", "--output", str(root)]} and value["output_path"] == str(root), "run report invocation or output path differs") + staging = _absolute(value["staging_path"], "run report staging path"); _absolute(value["python_executable_path"], "run report Python executable"); _need(staging.parent == root.parent and staging.name.startswith(f".{root.name}.stage-") and staging != root, "run report staging path is not the builder sibling staging path") + started, finished = value["started_utc"], value["finished_utc"]; _need(type(started) is str and type(finished) is str and _UTC.fullmatch(started) is not None and _UTC.fullmatch(finished) is not None and finished >= started, "run report timestamps are not ordered fixed UTC timestamps") + timings = value["timings"]; _need(type(timings) is list and [item.get("phase") if type(item) is dict else None for item in timings] == list(RUN_PHASES), "run report timings differ from the exact phase order") + for index, item in enumerate(timings): _keys(item, ("phase", "seconds"), f"run report timings[{index}]"); _need(_binary64(item["seconds"], f"run report timings[{index}].seconds") >= 0.0, "run report timing is negative") + stable = _keys(value["stable_manifest"], ("role_path", "bytes", "sha256", "schema"), "run report stable manifest"); _need(stable["role_path"] == "stable-manifest.json" and stable["schema"] == MANIFEST_SCHEMAS["stable-manifest.json"], "run report stable manifest reference differs"); _integer(stable["bytes"], "run report stable manifest bytes"); _hex(stable["sha256"], "run report stable manifest sha256") + _need(value["gates"] == [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in RUN_REPORT_GATES], "run report gate inventory is not the exact six all-pass gates"); return value +def _expected_gate_contract(): + import anatomy_gates as anatomy; import mesh_correctness as mesh_api; import owned_root_surface as surface + catalog_gates, catalog_thresholds = _catalog(surface); groups = {"structural": [row["gate_id"] for row in catalog_gates], "continuity": [], "anatomy": [], "intersection": []}; thresholds = list(catalog_thresholds) + def add(group, gate_id, relation, lower, upper, unit): groups[group].append(gate_id); thresholds.append({"threshold_id": f"threshold.{gate_id}", "relation": relation, "lower": lower, "upper": upper, "unit": unit}) + invalid = "duplicate_vertex_ids duplicate_face_ids degenerate_faces zero_length_edges non_manifold_edges orientation_conflicts unowned_elements overowned_elements accidental_boundary_components".split(); chart_counts = ((104, 189, 5), (416, 794, 5), (1664, 3252, 5)) + for level, counts in enumerate(LEVEL_COUNTS): + for name, count in zip(("vertices", "edges", "quads", "triangles", "boundary_edges"), counts): add("structural", f"structural.L{level}.count.{name}", "eq", count, count, "count") + for name in "connected orientable outward_wound boundary_components_match_ports".split(): add("structural", f"structural.L{level}.surface_boolean.{name}", "eq", 1, 1, "boolean") + for name in "coordinates quad_normals triangle_areas quad_areas".split(): add("structural", f"structural.L{level}.finite.{name}", "eq", 1, 1, "boolean") + for name in ("edge_length", "triangle_area", "quad_area"): add("structural", f"structural.L{level}.floor.{name}", "ge", mesh_api.STRUCTURAL_FLOORS[level][name], None, "m" if name == "edge_length" else "m2") + for name in invalid: add("structural", f"structural.L{level}.invalid_count.{name}", "eq", 0, 0, "count") + for name, count in zip(("charts", "interior_transitions", "maximum_samples_per_vertex"), chart_counts[level]): add("structural", f"structural.L{level}.chart.{name}", "eq", count, count, "count") + for name, limit in (("base_control_contributors", 20), ("dependency_union_keys", 54), ("contributor_domains", 5)): add("structural", f"structural.L2.lineage_cap.{name}", "le", None, limit, "count") + for name in "recurrence_exact incidence_complete boundary_neighbors_exact face_emission_exact lineage_complete chart_complete transition_complete".split(): add("structural", f"structural.subdivision.{name}", "eq", 1, 1, "boolean") + for level, fold_limit in enumerate((90.0, 60.0, 30.0)): + [add("continuity", f"continuity.{junction}.L{level}.{name}", relation, lower, upper, unit) for junction in surface.JUNCTIONS for name, relation, lower, upper, unit in (("tag_identity", "eq", 1, 1, "boolean"), ("opposite_trace_direction", "eq", 1, 1, "boolean"), ("coordinate_residual", "le", None, mesh_api.T, "m"), ("fold_angle", "lt", None, fold_limit, "degree"))] + [add("continuity", f"continuity.{port}.L{level}.{name}", relation, lower, upper, unit) for port in surface.PORT_INFO for name, relation, lower, upper, unit in (("orientation", "ge", .99, None, "dimensionless"), ("planarity", "le", None, mesh_api.T, "m"), ("area_ratio", "ge", .0001, None, "dimensionless"), ("co_normal", "ge", .80, None, "dimensionless"))] + [(thresholds.append(threshold), groups["anatomy"].append(threshold["threshold_id"].removeprefix("threshold."))) for threshold in anatomy.anatomy_threshold_records()] + for level, triangle_count in enumerate((208, 832, 3328)): + for name, relation, lower, upper, unit in (("triangle_count", "eq", triangle_count, triangle_count, "count"), ("broad_phase_candidate_count", "le", None, mesh_api.MAX_CANDIDATES, "count"), ("intersection_hit_count", "eq", 0, 0, "count"), ("pair_policy_complete", "eq", 1, 1, "boolean")): add("intersection", f"intersection.L{level}.{name}", relation, lower, upper, unit) + thresholds.append({"threshold_id": "gate.boolean-pass", "relation": "eq", "lower": 1, "upper": 1, "unit": "dimensionless"}); groups = {group: list(_order(ids)) for group, ids in groups.items()}; thresholds = _order_records(thresholds, "threshold_id"); _need(tuple(len(groups[name]) for name in ("structural", "continuity", "anatomy", "intersection")) == (122, 144, 78, 12) and len(thresholds) == 357, "derived validator gate inventory differs from the frozen contract") + return groups, thresholds +def _validate_gate(row, threshold, label): + row = _keys(row, ("gate_id", "outcome", "sample_count", "observed_min", "observed_max", "threshold_id"), label) + if threshold is None or row["outcome"] != "pass" or row["threshold_id"] != f"threshold.{row['gate_id']}": _fail(f"{label} is not linked all-pass evidence") + _integer(row["sample_count"], f"{label}.sample_count", 1); integer = threshold["unit"] in ("boolean", "count") or threshold["unit"] == "dimensionless" and type(row["observed_min"]) is int and type(row["observed_max"]) is int; minimum = 0 if threshold["unit"] in ("boolean", "count") else -(1 << 63) + low = _integer(row["observed_min"], f"{label}.observed_min", minimum) if integer else _binary64(row["observed_min"], f"{label}.observed_min"); high = _integer(row["observed_max"], f"{label}.observed_max", minimum) if integer else _binary64(row["observed_max"], f"{label}.observed_max") + if low > high: _fail(f"{label} has reversed observations") + relation, lower, upper = threshold["relation"], threshold["lower"], threshold["upper"] + if not ((low == lower and high == upper) if relation == "eq" else low >= lower if relation == "ge" else high <= upper if relation == "le" else high < upper): _fail(f"{label} does not satisfy its threshold") +def _validate_gate_manifest(value): + groups, expected = _expected_gate_contract(); thresholds = value["thresholds"]; _need(type(thresholds) is list, "gate thresholds must be a list") + for index, row in enumerate(thresholds): row = _keys(row, ("threshold_id", "relation", "lower", "upper", "unit"), f"gate threshold[{index}]"); _need(bool(_text(row["threshold_id"], f"gate threshold[{index}].threshold_id")) and row["relation"] in ("eq", "ge", "le", "lt") and row["unit"] in ("boolean", "count", "degree", "dimensionless", "m", "m2"), "gate threshold relation or unit is not admitted") + _same_json(thresholds, expected, "gate threshold inventory"); threshold_map = {row["threshold_id"]: row for row in thresholds} + for group, ids in groups.items(): rows = value[group]; _need(type(rows) is list and [row.get("gate_id") if type(row) is dict else None for row in rows] == ids, f"{group} gate IDs are not the exact sorted inventory"); [_validate_gate(row, threshold_map.get(row.get("threshold_id")), f"{group} gate[{index}]") for index, row in enumerate(rows)] +def _bundle_blob(root, role, record_map): + cap = 8 * 1024 * 1024 if role == "causality-manifest.json" else 2 * 1024 * 1024; raw = artifacts.read_regular_file(root / role, max_bytes=cap); expected = record_map[role] + _need(expected == {"role_path": role, "bytes": len(raw), "sha256": artifacts.sha256_bytes(raw)}, f"bundle artifact changed while validating: {role}"); return raw +def _closed_inventory(root): + try: return artifacts.closed_inventory(root, ARTIFACT_ROLES, max_file_bytes=8 * 1024 * 1024) + except Exception as exc: raise BuildError("bundle closed-inventory admission failed") from exc +def _bundle_json(root, role, record_map): + raw = _bundle_blob(root, role, record_map) + try: value = artifacts.decode_canonical_json(raw) + except Exception as exc: raise BuildError(f"bundle JSON is not canonical: {role}") from exc + if type(value) is not dict: _fail(f"bundle JSON must be an object: {role}") + return raw, value +def _parse_ply(raw, role, vertices_count, quads_count, render): + try: lines = raw.decode("ascii").splitlines() + except UnicodeDecodeError as exc: raise BuildError(f"PLY is not ASCII: {role}") from exc + header = ["ply", "format ascii 1.0", f"element vertex {vertices_count}", "property double x", "property double y", "property double z", f"element face {quads_count}", "property list uchar int vertex_indices", "end_header"] + if not raw.endswith(b"\n") or lines[:9] != header or len(lines) != 9 + vertices_count + quads_count: _fail(f"PLY header or row count differs: {role}") + try: vertices = tuple(tuple(float(item) for item in line.split()) for line in lines[9:9 + vertices_count]); quads = tuple(tuple(int(item) for item in line.split()[1:]) for line in lines[9 + vertices_count:]) + except ValueError as exc: raise BuildError(f"PLY row is not numeric: {role}") from exc + if any(len(row) != 3 for row in vertices) or any(len(row) != 4 or line.split()[0] != "4" for row, line in zip(quads, lines[9 + vertices_count:])): _fail(f"PLY row shape differs: {role}") + try: canonical = render.ply_bytes(vertices, quads) + except Exception as exc: raise BuildError(f"PLY geometry is invalid: {role}") from exc + if canonical != raw: _fail(f"PLY bytes are not the exact canonical serialization: {role}") + return vertices, quads +def _validate_png(raw, role): + try: + from PIL import Image + image = Image.open(io.BytesIO(raw)); _need(image.format == "PNG" and image.mode == "RGB" and image.size == (512, 1536) and not image.info, f"PNG dimensions, mode, or metadata differ: {role}"); image.verify() + except BuildError: raise + except Exception as exc: raise BuildError(f"PNG failed exact decoding: {role}") from exc +def validate_seed_bundle(*, root, seed, identity): + identity = _validate_identity(identity); _need(type(seed) is int and seed in (17, 29), "seed bundle seed must be integer 17 or 29"); root = Path(root); _need(root.is_absolute() and os.path.normpath(str(root)) == str(root) and root.name == f"seed-{seed}" and not root.is_symlink() and root.is_dir(), "seed bundle root is not the exact admitted seed directory") + records = _closed_inventory(root); record_map = {record["role_path"]: record for record in records}; _limits(root, identity) + import chart_lineage as chart; import owned_root_surface as surface; import prepared_projection as prepared_api; import render_export as render + prepared_raw = _bundle_blob(root, "prepared-input.json", record_map) + try: prepared = prepared_api.admit_prepared_bytes(prepared_raw) + except Exception as exc: raise BuildError("prepared-input.json failed fixed projection admission") from exc + bindings = list(prepared_api.source_binding_records()); manifests = {role: _bundle_json(root, role, record_map)[1] for role in MANIFEST_SCHEMAS} + input_value = _keys(manifests["input-manifest.json"], ("schema", "contract_sha256", "source", "profile_table", "profile_id", "prepared_input", "source_bindings", "runtime", "implementation_files", "recipe_id"), "input manifest"); recipe_id = _recipe(identity)[1] + _need(input_value["schema"] == MANIFEST_SCHEMAS["input-manifest.json"] and input_value["contract_sha256"] == EXPECTED_CONTRACT_SHA256 and input_value["source"] == identity["source"] and input_value["profile_table"] == identity["profile_table"] and input_value["profile_id"] == "standard_neutral_reference" and input_value["runtime"] == identity["runtime"] and input_value["implementation_files"] == list(identity["implementation_files"]) and input_value["recipe_id"] == recipe_id and _file_record(input_value["prepared_input"], "input manifest prepared input", "prepared-input.json") == record_map["prepared-input.json"], "input manifest fixed identity, recipe, or prepared record differs"); _same_json(input_value["source_bindings"], bindings, "input manifest source bindings") + coordinate = _keys(manifests["coordinate-manifest.json"], ("schema", "contract_sha256", "input_manifest", "counts", "coordinate_hashes", "triangle_index_hashes", "surface_artifacts"), "coordinate manifest") + expected_counts = [{"level": level, "vertices": values[0], "edges": values[1], "quads": values[2], "triangles": values[3], "boundary_edges": values[4]} for level, values in enumerate(LEVEL_COUNTS)]; _need(coordinate["schema"] == MANIFEST_SCHEMAS["coordinate-manifest.json"] and coordinate["contract_sha256"] == EXPECTED_CONTRACT_SHA256 and coordinate["counts"] == expected_counts, "coordinate manifest identity or counts differ"); _manifest_reference(coordinate["input_manifest"], "coordinate input reference", "input-manifest.json", record_map["input-manifest.json"]) + baseline, coordinate_hashes, triangle_hashes = {}, [], [] + for level, role in enumerate(SURFACE_ROLES): + raw = _bundle_blob(root, role, record_map); vertices, quads = _parse_ply(raw, role, LEVEL_COUNTS[level][0], LEVEL_COUNTS[level][2], render); triangles = tuple(item for a, b, c, d in quads for item in ((a, b, c), (a, c, d))); coordinate_bytes = artifacts.coordinate_hash_bytes(vertices); triangle_bytes = artifacts.triangle_index_hash_bytes(triangles) + coordinate_hashes.append({"level": level, "bytes": len(coordinate_bytes), "sha256": artifacts.sha256_bytes(coordinate_bytes)}); triangle_hashes.append({"level": level, "bytes": len(triangle_bytes), "sha256": artifacts.sha256_bytes(triangle_bytes)}); baseline[level] = (raw, vertices, quads) + _need(coordinate["coordinate_hashes"] == coordinate_hashes and coordinate["triangle_index_hashes"] == triangle_hashes and coordinate["surface_artifacts"] == [record_map[role] for role in _order(SURFACE_ROLES)], "coordinate hashes or surface artifact records differ") + gate = _keys(manifests["gate-manifest.json"], ("schema", "contract_sha256", "coordinate_manifest", "thresholds", "structural", "continuity", "anatomy", "intersection"), "gate manifest") + _need(gate["schema"] == MANIFEST_SCHEMAS["gate-manifest.json"] and gate["contract_sha256"] == EXPECTED_CONTRACT_SHA256, "gate manifest identity differs"); _manifest_reference(gate["coordinate_manifest"], "gate coordinate reference", "coordinate-manifest.json", record_map["coordinate-manifest.json"]); _validate_gate_manifest(gate) + causality = _keys(manifests["causality-manifest.json"], ("schema", "contract_sha256", "input_manifest", "formula_records", "source_bindings", "charts", "perturbations"), "causality manifest") + _need(causality["schema"] == MANIFEST_SCHEMAS["causality-manifest.json"] and causality["contract_sha256"] == EXPECTED_CONTRACT_SHA256, "causality manifest identity differs"); _manifest_reference(causality["input_manifest"], "causality input reference", "input-manifest.json", record_map["input-manifest.json"]) + formulas = list(surface.formula_candidate_records(prepared)); _same_json(causality["formula_records"], formulas, "causality formula records"); _same_json(causality["source_bindings"], bindings, "causality source bindings") + evaluation = surface.evaluate(prepared) + try: chart.validate_chart_summary(causality["charts"], evaluation, formulas) + except Exception as exc: raise BuildError("causality chart summary validation failed") from exc + for level, mesh in enumerate((evaluation.cage, *evaluation.levels)): + if render.ply_bytes(mesh) != baseline[level][0]: _fail(f"baseline PLY differs from evaluated level {level}") + perturbations = causality["perturbations"]; expected_parameters = list(_order(PARAMETER_IDS)); _need(type(perturbations) is list and [item.get("parameter_id") if type(item) is dict else None for item in perturbations] == expected_parameters and tuple(surface.MUST_AFFECT_PARAMETER_IDS) == PARAMETER_IDS and surface.PERTURBATION_DELTA_M == 0.01, "runtime or manifest must-affect inventory differs") + minimum = float.fromhex("0x1.d14e3bcd35a85p-11") + for index, row in enumerate(perturbations): + value = _keys(row, ("parameter_id", "prepared_component", "delta_m", "support_level", "predicted_support_count", "observed_support_count", "predicted_support_sha256", "observed_support_sha256", "maximum_movement_m", "artifact"), f"causality perturbation[{index}]"); parameter, role = value["parameter_id"], f"perturb-{value['parameter_id'].replace('.', '-')}.ply" + _need(value["prepared_component"] == surface.MUST_AFFECT_COMPONENTS.get(parameter) and _binary64(value["delta_m"], f"causality perturbation[{index}].delta_m") == 0.01 and value["support_level"] == 2 and type(value["support_level"]) is int, f"causality perturbation selector, delta, or level differs: {parameter}") + predicted = _integer(value["predicted_support_count"], f"causality perturbation[{index}].predicted_support_count", 1); observed = _integer(value["observed_support_count"], f"causality perturbation[{index}].observed_support_count", 1) + _need(predicted == observed and predicted <= 1737 and value["predicted_support_sha256"] == value["observed_support_sha256"], f"causality support differs between analytic and observed evidence: {parameter}") + _hex(value["predicted_support_sha256"], f"causality perturbation[{index}].predicted_support_sha256"); _hex(value["observed_support_sha256"], f"causality perturbation[{index}].observed_support_sha256") + _need(not (parameter in ("left.thigh_start_x", "right.thigh_start_x") and predicted != 436) and _binary64(value["maximum_movement_m"], f"causality perturbation[{index}].maximum_movement_m") >= minimum and _file_record(value["artifact"], f"causality perturbation[{index}].artifact", role) == record_map[role], f"causality support cardinality, movement, or artifact differs: {parameter}") + perturb_raw = _bundle_blob(root, role, record_map); _, perturb_quads = _parse_ply(perturb_raw, role, LEVEL_COUNTS[2][0], LEVEL_COUNTS[2][2], render) + if perturb_quads != baseline[2][2] or perturb_raw == baseline[2][0]: _fail(f"causality perturbation topology changed or bytes did not: {parameter}") + render_value = _keys(manifests["render-manifest.json"], ("schema", "contract_sha256", "coordinate_manifest", "render_config", "visibility", "artifacts"), "render manifest") + _need(render_value["schema"] == MANIFEST_SCHEMAS["render-manifest.json"] and render_value["contract_sha256"] == EXPECTED_CONTRACT_SHA256, "render manifest identity differs"); _manifest_reference(render_value["coordinate_manifest"], "render coordinate reference", "coordinate-manifest.json", record_map["coordinate-manifest.json"]) + try: render.validate_render_config(render_value["render_config"]) + except Exception as exc: raise BuildError("render configuration validation failed") from exc + visibility = _keys(render_value["visibility"], ("level", "triangle_count", "triangle_index_sha256", "rule"), "render visibility") + _need(visibility == {"level": 2, "triangle_count": 3328, "triangle_index_sha256": triangle_hashes[2]["sha256"], "rule": "larger-depth-then-lower-triangle-index"} and render_value["artifacts"] == [record_map[role] for role in _order(("direct.png", "lineage.png"))], "render visibility or artifact records differ") + for role in ("direct.png", "lineage.png"): _validate_png(_bundle_blob(root, role, record_map), role) + stable = _keys(manifests["stable-manifest.json"], ("schema", "contract_sha256", "recipe_id", "runtime", "implementation_files", "input_manifest", "coordinate_manifest", "gate_manifest", "causality_manifest", "render_manifest", "artifact_hashes"), "stable manifest") + _need(stable["schema"] == MANIFEST_SCHEMAS["stable-manifest.json"] and stable["contract_sha256"] == EXPECTED_CONTRACT_SHA256 and stable["recipe_id"] == recipe_id and stable["runtime"] == identity["runtime"] and stable["implementation_files"] == list(identity["implementation_files"]), "stable manifest identity or recipe differs") + for field, role in (("input_manifest", "input-manifest.json"), ("coordinate_manifest", "coordinate-manifest.json"), ("gate_manifest", "gate-manifest.json"), ("causality_manifest", "causality-manifest.json"), ("render_manifest", "render-manifest.json")): + _manifest_reference(stable[field], f"stable {field}", role, record_map[role]) + _need(stable["artifact_hashes"] == [record_map[role] for role in STABLE_ARTIFACT_ROLES], "stable artifact hashes are not the exact five stable roles") + report_raw, report = _bundle_json(root, "report.json", record_map); validate_run_report(root=root, seed=seed, report=report, identity=identity); _manifest_reference(report["stable_manifest"], "report stable manifest", "stable-manifest.json", record_map["stable-manifest.json"]) + _need(_bundle_blob(root, "report.sha256", record_map) == f"{artifacts.sha256_bytes(report_raw)} report.json\n".encode("ascii"), "report sidecar is not the exact report hash line") + return manifests +def run_managed_tests(receipt_path): + _need(os.environ.get("PYTHONHASHSEED") == "0", "managed tests require literal PYTHONHASHSEED=0"); receipt = Path(receipt_path); _need(receipt.is_absolute() and receipt.name == "managed-test-receipt.json" and os.path.normpath(str(receipt)) == str(receipt) and not os.path.lexists(receipt) and not receipt.parent.is_symlink() and not (receipt.parent.exists() and not receipt.parent.is_dir()) and receipt.parent.parent.is_dir(), "managed receipt must be absolute, canonical, fresh, and staging-parented"); before = _static_admission() + sys.path.insert(0, str(PACKAGE)) + try: + suite = unittest.TestLoader().discover(str(TESTS), pattern="test_*.py") + def flatten(value): + for item in value: + yield from flatten(item) if isinstance(item, unittest.TestSuite) else (item,) + tests = tuple(flatten(suite)); ids = tuple(test.id() for test in tests); _need(bool(ids) and len(ids) == len(set(ids)) and all(ids.count(required) == 1 for required in REQUIRED_TEST_IDS), "managed discovery did not produce the exact required fixture IDs"); result = unittest.TestResult(); suite.run(result) + finally: + if sys.path and sys.path[0] == str(PACKAGE): sys.path.pop(0) + after = _static_admission(); snapshot = ("contract", "source", "profile_table", "implementation_files", "runtime_bytes"); _need(all(before[key] == after[key] for key in snapshot), "identity changed during managed tests"); _need(result.testsRun == len(ids) and not (result.failures or result.errors or result.skipped or result.expectedFailures or result.unexpectedSuccesses), "managed tests were not an exact all-pass result") + value = {"schema": "owned-root-assembly-successor-managed-test-receipt.v1", "outcome": "success", "literal_invocation": {"environment": ["PYTHONHASHSEED=0"], "argv": ["experiments/owned-root-assembly-successor/build_owned_root.py", "--internal-managed-tests", "--receipt", str(receipt)]}, "contract_sha256": EXPECTED_CONTRACT_SHA256, "runtime_fingerprint_sha256": after["runtime_fingerprint_sha256"], "implementation_files": list(after["implementation_files"]), "executed_test_ids": list(_order(ids)), "required_test_ids": list(REQUIRED_TEST_IDS), "results": {"tests_run": len(ids), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}} + receipt.parent.mkdir(exist_ok=True); artifacts.write_canonical_json_no_replace(receipt, value); return value +def build_seed(output_path): + _need(os.environ.get("PYTHONHASHSEED") in ("17", "29"), "seed builder requires literal PYTHONHASHSEED=17 or 29"); output = Path(output_path); _need(output.is_absolute() and os.path.normpath(str(output)) == str(output) and not os.path.lexists(output) and output.parent.is_dir(), "seed output must be an absolute canonical fresh path"); started, clock, stage, timings = _now(), time.perf_counter(), None, [] + try: + mark = time.perf_counter(); admission = _static_admission(); recipe, recipe_id = _recipe(admission); timings.append({"phase": "identity", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); import prepared_projection as prepared_api; prepared = prepared_api.prepare_standard_neutral(); prepared_api.validate_prepared(prepared); prepared_bytes = prepared_api.canonical_json_bytes(prepared); prepared_api.admit_prepared_bytes(prepared_bytes); bindings = prepared_api.source_binding_records(); timings.append({"phase": "prepared-input", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); import anatomy_gates as anatomy; import chart_lineage as chart; import mesh_correctness as mesh_api; import owned_root_surface as surface; import render_export as render; catalog, catalog_thresholds = _catalog(surface); timings.append({"phase": "catalogs", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); geometry = _geometry(surface, mesh_api, chart, anatomy, prepared); geometry["structural"] = catalog + geometry["structural"]; geometry["thresholds"] = catalog_thresholds + geometry["thresholds"] + _need(len(geometry["structural"]) == 122 and len(geometry["thresholds"]) == 357, "closed gate inventory count mismatch"); timings.append({"phase": "geometry-gates", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); perturbations, perturb_payloads = _causality(surface, render, mesh_api, prepared, geometry); timings.append({"phase": "causality", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); stage = Path(tempfile.mkdtemp(prefix=f".{output.name}.stage-", dir=output.parent)); prepared_record = _write(stage / "prepared-input.json", prepared_bytes); meshes = (geometry["evaluation"].cage, *geometry["evaluation"].levels); surface_records, coordinates, triangle_hashes = [], [], [] + for role, mesh in zip(SURFACE_ROLES, meshes): surface_records.append(_write(stage / role, render.ply_bytes(mesh))); coordinate_bytes = artifacts.coordinate_hash_bytes(mesh.vertices); index_bytes = artifacts.triangle_index_hash_bytes(mesh.triangles); coordinates.append({"level": mesh.level, "bytes": len(coordinate_bytes), "sha256": artifacts.sha256_bytes(coordinate_bytes)}); triangle_hashes.append({"level": mesh.level, "bytes": len(index_bytes), "sha256": artifacts.sha256_bytes(index_bytes)}) + for index, role in enumerate(PERTURBATION_ROLES): _write(stage / role, perturb_payloads[role]); perturbations[index]["artifact"] = artifacts.regular_file_record(stage / role, role) + direct, lineage, visibility = render.render_pair_bytes(meshes[-1]); direct_record, lineage_record = _write(stage / "direct.png", direct), _write(stage / "lineage.png", lineage) + input_manifest = {"schema": "owned-root-assembly-successor-input-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "source": admission["source"], "profile_table": admission["profile_table"], "profile_id": "standard_neutral_reference", "prepared_input": prepared_record, "source_bindings": list(bindings), "runtime": admission["runtime"], "implementation_files": list(admission["implementation_files"]), "recipe_id": recipe_id}; input_record = _write_json(stage / "input-manifest.json", input_manifest) + coordinate_manifest = {"schema": "owned-root-assembly-successor-coordinate-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "input_manifest": _manifest_ref(input_record, input_manifest["schema"]), "counts": [{"level": level, "vertices": len(mesh.vertices), "edges": report["topology"].edge_count, "quads": len(mesh.quads), "triangles": len(mesh.triangles), "boundary_edges": report["topology"].boundary_edge_count} for level, (mesh, report) in enumerate(zip(meshes, geometry["reports"]))], "coordinate_hashes": coordinates, "triangle_index_hashes": triangle_hashes, "surface_artifacts": sorted(surface_records, key=lambda record: record["role_path"].encode("utf-8"))}; coordinate_record = _write_json(stage / "coordinate-manifest.json", coordinate_manifest) + gate_manifest = {"schema": "owned-root-assembly-successor-gate-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "coordinate_manifest": _manifest_ref(coordinate_record, coordinate_manifest["schema"]), "thresholds": _order_records(geometry["thresholds"], "threshold_id"), "structural": _order_records(geometry["structural"], "gate_id"), "continuity": _order_records(geometry["continuity"], "gate_id"), "anatomy": _order_records(geometry["anatomy"], "gate_id"), "intersection": _order_records(geometry["intersection"], "gate_id")}; _validate_gate_manifest(gate_manifest); gate_record = _write_json(stage / "gate-manifest.json", gate_manifest) + causality_manifest = {"schema": "owned-root-assembly-successor-causality-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "input_manifest": _manifest_ref(input_record, input_manifest["schema"]), "formula_records": list(geometry["formula_records"]), "source_bindings": list(bindings), "charts": geometry["chart_summary"], "perturbations": list(_order_records(perturbations, "parameter_id"))}; causality_record = _write_json(stage / "causality-manifest.json", causality_manifest) + render_manifest = {"schema": "owned-root-assembly-successor-render-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "coordinate_manifest": _manifest_ref(coordinate_record, coordinate_manifest["schema"]), "render_config": render.render_config_record(), "visibility": render.visibility_record(visibility), "artifacts": sorted((direct_record, lineage_record), key=lambda record: record["role_path"].encode("utf-8"))}; render_record = _write_json(stage / "render-manifest.json", render_manifest) + stable_artifacts = sorted((*surface_records, direct_record, lineage_record), key=lambda record: record["role_path"].encode("utf-8")); stable_manifest = {"schema": "owned-root-assembly-successor-stable-manifest.v1", "contract_sha256": EXPECTED_CONTRACT_SHA256, "recipe_id": recipe_id, "runtime": admission["runtime"], "implementation_files": list(admission["implementation_files"]), "input_manifest": _manifest_ref(input_record, input_manifest["schema"]), "coordinate_manifest": _manifest_ref(coordinate_record, coordinate_manifest["schema"]), "gate_manifest": _manifest_ref(gate_record, gate_manifest["schema"]), "causality_manifest": _manifest_ref(causality_record, causality_manifest["schema"]), "render_manifest": _manifest_ref(render_record, render_manifest["schema"]), "artifact_hashes": stable_artifacts}; stable_record = _write_json(stage / "stable-manifest.json", stable_manifest); timings.append({"phase": "serialization", "seconds": float(time.perf_counter() - mark)}) + report = {"schema": "owned-root-assembly-successor-run-report.v1", "outcome": "success", "seed": int(os.environ["PYTHONHASHSEED"]), "literal_invocation": {"environment": [f"PYTHONHASHSEED={os.environ['PYTHONHASHSEED']}"], "argv": ["experiments/owned-root-assembly-successor/build_owned_root.py", "--output", str(output)]}, "output_path": str(output), "staging_path": str(stage), "python_executable_path": str(Path(sys.executable).absolute()), "started_utc": started, "finished_utc": _now(), "timings": timings + [{"phase": "total-before-seal", "seconds": float(time.perf_counter() - clock)}], "runtime_fingerprint_sha256": admission["runtime_fingerprint_sha256"], "stable_manifest": _manifest_ref(stable_record, stable_manifest["schema"]), "gates": [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in RUN_REPORT_GATES]} + report_bytes = artifacts.canonical_json_bytes(report); _write(stage / "report.json", report_bytes); _write(stage / "report.sha256", f"{artifacts.sha256_bytes(report_bytes)} report.json\n".encode("ascii")); inventory = _limits(stage, admission); artifacts.publish_no_replace(stage, output, inventory, max_file_bytes=8 * 1024 * 1024); stage = None; return output + except Exception: + if stage is not None and stage.exists(): shutil.rmtree(stage) + raise +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + try: + if argv[:1] == ["--internal-managed-tests"] and len(argv) == 3 and argv[1] == "--receipt": run_managed_tests(argv[2]); return 0 + if argv[:1] == ["--output"] and len(argv) == 2: build_seed(argv[1]); return 0 + _fail("private builder accepts only --internal-managed-tests --receipt ABS or --output ABS") + except Exception as exc: print(f"build_owned_root: error: {exc}", file=sys.stderr); return 1 +if __name__ == "__main__": raise SystemExit(main()) diff --git a/experiments/owned-root-assembly-successor/chart_lineage.py b/experiments/owned-root-assembly-successor/chart_lineage.py new file mode 100644 index 0000000..c5eec1e --- /dev/null +++ b/experiments/owned-root-assembly-successor/chart_lineage.py @@ -0,0 +1,220 @@ +"""Independent chart, transition, and propagated-lineage validation.""" +from collections import defaultdict +from fractions import Fraction +from hashlib import sha256 +from math import isfinite + +import owned_root_surface as surface + + +class ChartLineageError(ValueError): pass +COUNTS = ((120, 227, 104, 38, 189), (451, 870, 416, 76, 794), (1737, 3404, 1664, 152, 3252)) +TOPOLOGY_HASH = "230cad4872ddafafd28110e6baf45510c1a11fb6b39e12ffc0ef787d9c89bdb9" +JUNCTION_HASH = "1637c96b888e47c7714fbf4dc68521f86bf9e14d113ca14a55d4a430fb68f5b3" +FORMULA_HASH = "da8569de79e3c7479f94a94c5a2d45a9a131f623880c9301835a8e5f8e322bd5" +NEUTRAL_HASH = "caa90159002661fb7e36063e1f2cbab2c26d1bcbb8e35227cd2d34eddbc400e0" +FORMULA_FIELDS = ("control_id", "lattice_key", "formula_id", "construction_owner", "index_parameters", + "geometry_dependencies", "coordinate") +def _fail(message): + raise ChartLineageError(message) +def _hash(value): + return sha256(repr(value).encode("ascii")).hexdigest() +def _strict(actual, expected, where): + if type(actual) is not type(expected): _fail(f"{where} has an invalid type") + if type(expected) is dict: + if set(actual) != set(expected): _fail(f"{where} has an open schema") + [_strict(actual[key], expected[key], f"{where}.{key}") for key in expected] + elif type(expected) in (list, tuple): + if len(actual) != len(expected): _fail(f"{where} has an invalid length") + [_strict(actual[index], value, f"{where}[{index}]") for index, value in enumerate(expected)] + elif type(expected) is float and (not isfinite(actual) or actual != expected): _fail(f"{where} is non-finite or incorrect") + elif actual != expected: _fail(f"{where} does not match the frozen contract") +def _incidence(faces, vertex_count): + uses, around, boundary = defaultdict(list), defaultdict(list), defaultdict(set) + for face_index, face in enumerate(faces): + if type(face) is not tuple or len(face) != 4 or len(set(face)) != 4: _fail("a face is not a four-vertex cycle") + if any(type(v) is not int or not 0 <= v < vertex_count for v in face): _fail("a face has an invalid vertex") + for slot, left in enumerate(face): + around[left].append(face_index) + uses[tuple(sorted((left, face[(slot + 1) % 4])))].append((face_index, slot, left, face[(slot + 1) % 4])) + for edge, rows in uses.items(): + if len(rows) not in (1, 2) or (len(rows) == 2 and rows[0][2:] == rows[1][2:]): + _fail("edge incidence is non-manifold or inconsistently oriented") + if len(rows) == 1: + boundary[edge[0]].add(edge[1]) + boundary[edge[1]].add(edge[0]) + return dict(uses), around, boundary +def _subdivide(faces, loops, vertex_count): + uses, around, boundary = _incidence(faces, vertex_count) + edges = tuple(sorted(uses)) + points = tuple((edge, vertex_count + i) for i, edge in enumerate(edges)) + point_by_edge, face_start = dict(points), vertex_count + len(edges) + vertices = tuple((v, *sorted(boundary[v])) if v in boundary else tuple(x for fi in sorted(around[v]) for x in faces[fi]) for v in range(vertex_count)) + if any(v in boundary and len(boundary[v]) != 2 for v in range(vertex_count)): _fail("invalid boundary valence") + edge_stencils = tuple((edge, edge + tuple(v for fi, *_ in uses[edge] for v in faces[fi])) for edge in edges) + children = tuple((fi, corner, (v, point_by_edge[tuple(sorted((v, face[(corner + 1) % 4])))], face_start + fi, point_by_edge[tuple(sorted((face[(corner - 1) % 4], v)))])) for fi, face in enumerate(faces) for corner, v in enumerate(face)) + propagated = tuple((name, tuple(x for i, v in enumerate(loop) for x in (v, point_by_edge[tuple(sorted((v, loop[(i + 1) % len(loop)])))]))) for name, loop in loops) + local = {"vertex_stencils": vertices, "edge_stencils": edge_stencils, "face_stencils": tuple(enumerate(faces)), "edge_point_indices": points, "child_emission": children, "propagated_port_loops": propagated} + stencils = vertices + tuple(row[1] for row in edge_stencils) + tuple(faces) + return local, stencils +def _topology(evaluation): + meshes, symbolic = (evaluation.cage, *evaluation.levels), surface.symbolic_topology() + if len(meshes) != 3 or _hash(symbolic) != TOPOLOGY_HASH: _fail("symbolic topology is not frozen") + controls, next_faces, next_loops = symbolic + levels, incidences, subdivisions, next_stencils, base_owners = [], [], [], None, None + for level, mesh in enumerate(meshes): + vertices, edges, faces, boundary, _ = COUNTS[level] + report, incidence = surface.level_topology(mesh), surface.topology_incidence(mesh) + if level == 0: base_owners = report["face_owners"] + owners = tuple(base_owners[i // (4 ** level)] for i in range(faces)) + vertex_ids = controls if level == 0 else tuple(f"vertex.L{level}.v{i:04d}" for i in range(vertices)) + face_ids = tuple(f"q{i:03d}" for i in range(faces)) if level == 0 else tuple(f"face.L{level}.q{i:04d}" for i in range(faces)) + _strict((report["vertex_ids"], report["face_ids"], report["face_owners"], report["faces"], report["boundary_loops"]), (vertex_ids, face_ids, owners, next_faces, next_loops), f"L{level} order") + uses, _, _ = _incidence(next_faces, vertices) + expected_incidence = tuple({"edge": edge, "incident_faces": tuple(r[0] for r in uses[edge]), "slots": tuple(r[1] for r in uses[edge])} for edge in sorted(uses)) + _strict(incidence, expected_incidence, f"topology_incidence[{level}]") + boundary_edges = {edge for edge, rows in uses.items() if len(rows) == 1} + loop_edges = {tuple(sorted((loop[i], loop[(i + 1) % len(loop)]))) for _, loop in next_loops for i in range(len(loop))} + if (len(uses), len(boundary_edges)) != (edges, boundary) or boundary_edges != loop_edges: _fail("bad edge/port inventory") + if len(mesh.vertices) != vertices or any(type(p) is not tuple or len(p) != 3 or any(type(x) is not float or not isfinite(x) for x in p) for p in mesh.vertices): + _fail("surface coordinates are not finite binary64 vector3 values") + _strict(mesh.source_stencils, tuple((i,) for i in range(120)) if level == 0 else next_stencils, f"source_stencils[{level}]") + levels.append(report) + incidences.append(incidence) + if level < 2: + candidate = surface.subdivision_incidence(mesh) + local, next_stencils = _subdivide(next_faces, next_loops, vertices) + [_strict(candidate[key], expected, f"subdivision_incidence[{level}].{key}") for key, expected in local.items()] + _strict(surface.propagate_port_loops(mesh), dict(local["propagated_port_loops"]), "propagated ports") + subdivisions.append((candidate, next_stencils)) + next_faces, next_loops = tuple(row[2] for row in local["child_emission"]), local["propagated_port_loops"] + neutral = tuple(levels), tuple(incidences), tuple(candidate for candidate, _ in subdivisions) + if _hash(neutral) != NEUTRAL_HASH: _fail("neutral topology commitment changed") + return meshes, controls, levels, subdivisions +def _formulas(records, controls, vertices, control_domains, junctions): + if type(records) is not tuple or len(records) != 120: _fail("formula inventory is not exactly 120 records") + ledger, dependencies, lattice = [], {}, [] + for index, (record, control) in enumerate(zip(records, controls)): + if type(record) is not dict or set(record) != set(FORMULA_FIELDS): _fail(f"formula_records[{index}] has an open schema") + domains = control_domains[index] + owner = domains[0] if len(domains) == 1 else junctions.get(frozenset(domains)) + deps, key = record["geometry_dependencies"], record["lattice_key"] + invalid = record["control_id"] != control or record["construction_owner"] != owner or type(key) is not list or len(key) != 3 or any(type(x) is not int for x in key) or type(deps) is not list or deps != sorted(set(deps)) or len(deps) > 12 + if owner is None or invalid: _fail(f"formula_records[{index}] has invalid IDs, ownership, lattice, or dependencies") + _strict(record["coordinate"], list(vertices[index]), f"formula_records[{index}].coordinate") + ledger.append({field: record[field] for field in FORMULA_FIELDS[:-1]}) + dependencies[control], lattice = deps, lattice + [key] + if _hash(tuple(ledger)) != FORMULA_HASH: _fail("formula shape/dependency ledger is not frozen") + if len({item for values in dependencies.values() for item in values}) != 92: _fail("dependency universe is not 92") + return dependencies, lattice +def _domain_boundary(topology, domain): + uses = defaultdict(list) + for face, owner in zip(topology["faces"], topology["face_owners"]): + if owner == domain: + for i, left in enumerate(face): + edge = tuple(sorted((left, face[(i + 1) % 4]))) + uses[edge].append((left, face[(i + 1) % 4])) + return {edge: rows[0] for edge, rows in uses.items() if len(rows) == 1} +def _domain_cycle(boundary, shared): + following = {boundary[e][0]: boundary[e][1] for e in shared} + if len(following) != len(shared): _fail("a junction is not a domain boundary cycle") + cycle = [min(following)] + while following.get(cycle[-1]) != cycle[0] and len(cycle) <= len(shared): + cycle.append(following[cycle[-1]]) + if len(cycle) != len(shared) or following.get(cycle[-1]) != cycle[0]: _fail("a junction is not one closed trace") + return tuple(cycle) +def _traces(levels, subdivisions, rows, lattice, evaluation): + axes, result, meshes = {"i": 0, "j": 1, "k": 2}, [{} for _ in levels], (evaluation.cage, *evaluation.levels) + for row in rows: + jid, domains, tags, expected_tags = row["junction_id"], row["incident_domains"], None, [] + for level, topology in enumerate(levels): + boundaries = tuple(_domain_boundary(topology, domain) for domain in domains) + shared = set(boundaries[0]) & set(boundaries[1]) + first, second = (_domain_cycle(boundary, shared) for boundary in boundaries) + paired = (second[0], *reversed(second[1:])) + residuals = (abs(meshes[level].vertices[a][axis] - meshes[level].vertices[b][axis]) for a, b in zip(first, paired) for axis in range(3)) + if first != paired or any(value > float.fromhex("0x1.c666666666666p-45") for value in residuals): + _fail("junction traces disagree") + result[level][jid] = shared + if level == 0: + indices = tuple(int(control[1:]) for control in row["base_control_ids"]) + if set(first) != set(indices): _fail("junction controls do not match independent incidence") + base_tags = tuple(tuple(lattice[v][axes[a]] for a in row["tag_axes"]) for v in indices) + if base_tags != row["base_lattice_tags"]: _fail("junction lattice tags are incorrect") + tags = {v: tuple((lattice[v][axes[a]], 1) for a in row["tag_axes"]) for v in first} + if set(tags) != set(first): _fail("junction tag membership is incomplete") + expected_tags.append(dict(sorted(tags.items()))) + if level < 2: + points = dict(subdivisions[level][0]["edge_point_indices"]) + tags = tags | {points[e]: tuple(((Fraction(*tags[e[0]][a]) + Fraction(*tags[e[1]][a])) / 2).as_integer_ratio() for a in range(2)) for e in shared} + _strict(surface.propagate_junction_tags(evaluation, jid), tuple(expected_tags), f"junction_tags.{jid}") + return result +def _uv(path): + corners = ((Fraction(0), Fraction(0)), (Fraction(1), Fraction(0)), (Fraction(1), Fraction(1)), (Fraction(0), Fraction(1))) + for child in path: + mids = tuple(tuple((a + b) / 2 for a, b in zip(corners[i], corners[(i + 1) % 4])) for i in range(4)) + center = tuple(sum(point[a] for point in corners) / 4 for a in range(2)) + corners = ((corners[0], mids[0], center, mids[3]), (corners[1], mids[1], center, mids[0]), (corners[2], mids[2], center, mids[1]), (corners[3], mids[3], center, mids[2]))[child] + return corners +def _charts(topology, level): + records, samples = [], [[] for _ in topology["vertex_ids"]] + for index, face in enumerate(topology["faces"]): + base = index // (4 ** level) + path = () if level == 0 else ((index % 4,) if level == 1 else ((index % 16) // 4, index % 4)) + chart_id = f"chart.q{base:03d}" if level == 0 else f"chart.q{base:03d}/L{level}.s{'.s'.join(map(str, path))}" + corners = [] + for vertex, uv in zip(face, _uv(path)): + sample = {"chart_id": chart_id, "u": {"numerator": uv[0].numerator, "denominator": uv[0].denominator}, "v": {"numerator": uv[1].numerator, "denominator": uv[1].denominator}} + samples[vertex].append(sample) + corners.append({"vertex_id": topology["vertex_ids"][vertex], "u": sample["u"], "v": sample["v"]}) + records.append({"chart_id": chart_id, "level": level, "face_id": topology["face_ids"][index], "base_face_id": f"q{base:03d}", "construction_owner": topology["face_owners"][index], "corners": corners}) + return records, samples +def _transitions(topology, charts, level, traces, junctions, domain_order): + uses, _, _ = _incidence(topology["faces"], len(topology["vertex_ids"])) + records, observed = [], defaultdict(set) + for edge, rows in sorted(uses.items()): + if len(rows) == 1: continue + source, destination = sorted((rows[0][0], rows[1][0])) + source_row, destination_row = (next(row for row in rows if row[0] == face) for face in (source, destination)) + owners = topology["face_owners"][source], topology["face_owners"][destination] + junction = None if owners[0] == owners[1] else junctions.get(frozenset(owners)) + if owners[0] != owners[1] and (junction is None or edge not in traces[junction]): _fail("bad cross-domain transition") + if junction: observed[junction].add(edge) + endpoints = [topology["vertex_ids"][v] for v in edge] + records.append({"transition_id": f"transition/L{level}/e{endpoints[0]}-{endpoints[1]}", "level": level, "source_chart": charts[source]["chart_id"], "destination_chart": charts[destination]["chart_id"], "source_edge_slot": source_row[1], "destination_edge_slot": destination_row[1], "endpoint_ids": endpoints, "t_destination_rule": "1-t_source", "junction_id": junction, "incident_domains": [owners[0]] if junction is None else [d for d in domain_order if d in owners]}) + if any(observed[jid] != edges for jid, edges in traces.items()): _fail("junction transition membership is incomplete") + return records +def _derive(evaluation, formula_records): + meshes, controls, levels, subdivisions = _topology(evaluation) + junction_rows = surface.junction_trace_inputs() + if _hash(junction_rows) != JUNCTION_HASH: _fail("the seven junction declarations are not frozen") + junctions = {frozenset(row["incident_domains"]): row["junction_id"] for row in junction_rows} + port_domains = tuple(next(owner for face, owner in zip(levels[0]["faces"], levels[0]["face_owners"]) if loop[0] in face and loop[1] in face) for _, loop in levels[0]["boundary_loops"]) + domain_order = tuple(junction_rows[i]["incident_domains"][j] for i, j in ((0, 0), (1, 1), (2, 1))) + port_domains + if len(set(domain_order)) != 8: _fail("domain order is incomplete") + control_domains = [tuple(domain for domain in domain_order if any(owner == domain and index in face for face, owner in zip(levels[0]["faces"], levels[0]["face_owners"]))) for index in range(120)] + dependencies, lattice = _formulas(formula_records, controls, meshes[0].vertices, control_domains, junctions) + traces = _traces(levels, subdivisions, junction_rows, lattice, evaluation) + contributors = [[{i} for i in range(120)]] + for _, stencils in subdivisions: + previous = contributors[-1] + contributors.append([{base for source in stencil for base in previous[source]} for stencil in stencils]) + chart_levels, transition_levels, vertices = [], [], [] + for level, topology in enumerate(levels): + charts, samples = _charts(topology, level) + transitions = _transitions(topology, charts, level, traces[level], junctions, domain_order) + if (len(charts), len(transitions), max(map(len, samples))) != (COUNTS[level][2], COUNTS[level][4], 5): + _fail("bad chart, transition, or sample count") + if any(not values or len(values) > 5 for values in samples): _fail("vertex chart samples are empty or over cap") + for index, base in enumerate(contributors[level]): + base_ids = [f"c{i:03d}" for i in sorted(base)] + union = sorted({item for control in base_ids for item in dependencies[control]}) + domains = [domain for domain in domain_order if any(domain in control_domains[i] for i in base)] + if len(base_ids) > 20 or len(union) > 54 or len(domains) > 5: _fail("propagated lineage exceeds a frozen cap") + key = lambda row: (row["chart_id"], Fraction(row["u"]["numerator"], row["u"]["denominator"]), Fraction(row["v"]["numerator"], row["v"]["denominator"])) + vertices.append({"level": level, "vertex_id": topology["vertex_ids"][index], "samples": sorted(samples[index], key=key), "base_control_contributors": base_ids, "geometry_dependency_union": union, "contributor_domains": domains}) + chart_levels.append(charts) + transition_levels.append(transitions) + return {"level_counts": [{"level": level, "charts": COUNTS[level][2], "interior_transitions": COUNTS[level][4], "maximum_samples_per_vertex": 5} for level in range(3)], "chart_records": sorted((r for rows in chart_levels for r in rows), key=lambda r: r["chart_id"]), "transition_records": sorted((r for rows in transition_levels for r in rows), key=lambda r: r["transition_id"]), "vertex_records": vertices} +def build_chart_summary(evaluation, formula_records): return _derive(evaluation, formula_records) +def validate_chart_summary(summary, evaluation, formula_records): _strict(summary, _derive(evaluation, formula_records), "chart_summary") diff --git a/experiments/owned-root-assembly-successor/compare_two_seed_outputs.py b/experiments/owned-root-assembly-successor/compare_two_seed_outputs.py new file mode 100644 index 0000000..d0aac53 --- /dev/null +++ b/experiments/owned-root-assembly-successor/compare_two_seed_outputs.py @@ -0,0 +1,236 @@ +"""Private, fail-closed comparator for two sealed successor seed bundles.""" +from __future__ import annotations +import importlib, importlib.metadata, importlib.util, locale, os, platform, shutil, stat, struct, sys, sysconfig, tempfile +from pathlib import Path +PACKAGE = Path(__file__).resolve().parent; REPO = PACKAGE.parents[1] +sys.path.insert(0, str(PACKAGE)) +import artifact_serialization as artifacts # noqa: E402 +EXPECTED_CONTRACT_SHA256, EXPECTED_SOURCE_SHA256, EXPECTED_PROFILE_SHA256 = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490", "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14", "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +CONTRACT_ROLE, SIDECAR_ROLE, SOURCE_ROLE = "experiments/owned-root-assembly-successor/design-contract.md", "experiments/owned-root-assembly-successor/design-contract.sha256", "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE, CURRENT_LAUNCHER_ROLE, REQUIREMENTS_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json", "experiments/current-form-surface-preview/surface_preview_launcher.sh", "experiments/current-form-surface-preview/requirements.txt" +BUILDER_ROLE, COMPARATOR_ROLE = "experiments/owned-root-assembly-successor/build_owned_root.py", "experiments/owned-root-assembly-successor/compare_two_seed_outputs.py" +IMPLEMENTATION_ROLES = tuple(sorted(("experiments/owned-root-assembly-successor/" + role for role in "build_owned_root.py prepared_projection.py owned_root_surface.py mesh_correctness.py render_export.py owned_root_launcher.sh compare_two_seed_outputs.py artifact_serialization.py anatomy_gates.py chart_lineage.py tests/test_build_owned_root.py tests/test_prepared_projection.py tests/test_owned_root_surface.py tests/test_mesh_correctness.py tests/test_render_export.py".split()), key=lambda value: value.encode("utf-8"))) +ROLES = tuple("surface-level-0.ply surface-level-1.ply surface-level-2.ply perturb-left-r_y.ply perturb-right-r_y.ply perturb-lower_pelvis-L_y.ply perturb-left-r_x.ply perturb-lower_pelvis-C_z.ply perturb-right-r_x.ply perturb-lower_pelvis-R_x.ply perturb-left-r_z.ply perturb-right-r_z.ply perturb-lower_pelvis-R_f.ply perturb-lower_pelvis-R_b.ply perturb-left-thigh_start_x.ply perturb-left-thigh_start_y.ply perturb-left-thigh_start_z.ply perturb-right-thigh_start_x.ply perturb-right-thigh_start_y.ply perturb-right-thigh_start_z.ply perturb-neck_collar-C_y.ply perturb-neck_collar-rL.ply perturb-neck_upper-C_y.ply perturb-neck_upper-rL.ply perturb-left-axilla_x.ply perturb-left-axilla_y.ply perturb-right-axilla_x.ply perturb-right-axilla_y.ply perturb-left-peak_y.ply perturb-right-peak_y.ply perturb-left-start_lateral.ply perturb-right-start_lateral.ply perturb-left-start_up.ply perturb-right-start_up.ply perturb-left-shoulder_depth.ply perturb-right-shoulder_depth.ply direct.png lineage.png input-manifest.json coordinate-manifest.json gate-manifest.json causality-manifest.json render-manifest.json stable-manifest.json prepared-input.json report.json report.sha256".split()) +STABLE_ROLES = tuple(sorted(set(ROLES) - {"report.json", "report.sha256"}, key=lambda value: value.encode("utf-8"))) +READ_FLAGS = os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC +class ComparatorError(ValueError): pass +def _need(condition: bool, message: str) -> None: + if not condition: raise ComparatorError(message) +def _bounded(value: object, label: str, limit: int = 128) -> str: + _need(type(value) is str and len(value.encode("utf-8")) <= limit, f"{label} is not a bounded runtime string"); return value +def _json(path: Path) -> tuple[dict, bytes]: + raw = artifacts.read_regular_file(path, max_bytes=2 * 1024 * 1024); value = artifacts.decode_canonical_json(raw); _need(isinstance(value, dict), f"{path} is not a JSON object"); return value, raw +def _record(path: Path, role: str, cap: int = 4 * 1024 * 1024) -> dict: return artifacts.regular_file_record(path, role, max_bytes=cap) +def _implementation_nodes() -> list[tuple[str, os.stat_result]]: + result, flags = [], os.O_RDONLY | os.O_DIRECTORY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC + def visit(directory: int, prefix: str) -> None: + with os.scandir(directory) as entries: + for entry in entries: + info = entry.stat(follow_symlinks=False); role = f"{prefix}/{entry.name}" + if entry.name.endswith((".py", ".sh")): result.append((role, info)) + if stat.S_ISDIR(info.st_mode): + child = os.open(entry.name, flags, dir_fd=directory) + try: artifacts._require_same_stat(info, os.fstat(child), "implementation directory changed during admission"); visit(child, role) + finally: os.close(child) + root = artifacts._open_directory(PACKAGE) + try: visit(root, PACKAGE.relative_to(REPO).as_posix()) + finally: os.close(root) + return sorted(result, key=lambda item: item[0].encode("utf-8")) +def _implementation_record(role: str, admitted: os.stat_result) -> dict: + parts = Path(role).relative_to(PACKAGE.relative_to(REPO)).parts; parent = artifacts._open_directory(PACKAGE.joinpath(*parts[:-1])) + try: + descriptor = os.open(parts[-1], READ_FLAGS, dir_fd=parent) + try: + opened = os.fstat(descriptor); artifacts._require_regular(opened, role); artifacts._require_same_stat(admitted, opened, f"{role} changed after allowlist scan") + readings = [artifacts._read_stable_once(descriptor, opened, 4 * 1024 * 1024) for _ in range(2)] + artifacts._require_same_stat(opened, os.stat(parts[-1], dir_fd=parent, follow_symlinks=False), f"{role} changed while reading") + if readings[0] != readings[1] or len(readings[1]) != opened.st_size: raise ComparatorError(f"{role} changed while reading") + finally: os.close(descriptor) + finally: os.close(parent) + return {"role_path": role, "bytes": len(readings[1]), "sha256": artifacts.sha256_bytes(readings[1])} +def _implementation_files() -> list[dict]: + before = _implementation_nodes(); found = tuple(role for role, _ in before) + _need(not any(not stat.S_ISREG(info.st_mode) for _, info in before), "package implementation allowlist contains a non-regular .py/.sh node"); _need(found == IMPLEMENTATION_ROLES, "package implementation source does not match the exact 15-file allowlist") + records = [_implementation_record(role, info) for role, info in before]; after = _implementation_nodes() + _need(len(after) == len(before) and not any(left[0] != right[0] or not artifacts._same_stat(left[1], right[1]) for left, right in zip(before, after)), "package implementation allowlist changed while reading"); return records +def _unchanged(path: Path, role: str, expected: dict, cap: int = 4 * 1024 * 1024) -> None: + _need(_record(path, role, cap) == expected, f"{role} changed after inventory") +def _bundle(root: Path) -> dict: + rows = artifacts.closed_inventory(root, ROLES, max_file_bytes=8 * 1024 * 1024) + _need(not any(row["bytes"] > (8 if row["role_path"] == "causality-manifest.json" else 2) * 1024 * 1024 for row in rows), "seed bundle exceeds its exact artifact size caps"); return {row["role_path"]: row for row in rows} +def _api(module: object, name: str): + function = getattr(module, name, None); _need(callable(function), f"missing future builder API: build_owned_root.{name}()"); return function +def _runtime(launcher: dict, requirements: dict) -> tuple[dict, bytes, str]: + _need((platform.python_implementation(), platform.python_version(), platform.system(), getattr(sys.implementation, "cache_tag", None)) == ("CPython", "3.10.12", "Linux", "cpython-310"), "runtime must be CPython 3.10.12 on Linux with cache tag cpython-310") + direct = (("numpy", "2.2.6"), ("scikit-image", "0.25.2"), ("pillow", "11.1.0")) + resolved = (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")) + for name, expected in (*direct, *resolved): + try: observed = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError as exc: raise ComparatorError(f"runtime distribution is missing: {name}") from exc + _need(observed == expected, f"runtime distribution drift: {name}=={observed}") + builtins = [] + for name in ("math", "zlib"): + module, spec = importlib.import_module(name), importlib.util.find_spec(name) + _need(getattr(module, "__file__", None) is None and spec is not None and spec.origin == "built-in", f"{name} is not the required built-in module") + versions = (None, None) if name == "math" else (_bounded(module.ZLIB_VERSION, "zlib compile version"), _bounded(module.ZLIB_RUNTIME_VERSION, "zlib runtime version")) + builtins.append({"module_name": name, "__file__": None, "find_spec_origin": "built-in", "compile_version": versions[0], "runtime_version": versions[1]}) + build, compiler = _bounded(" ".join(platform.python_build()), "python.build"), _bounded(platform.python_compiler(), "python.compiler") + python = {"implementation": "CPython", "version": "3.10.12", "build": build, "compiler": compiler, "cache_tag": "cpython-310", "abiflags": _bounded(sys.abiflags, "python.abiflags"), "soabi": _bounded(sysconfig.get_config_var("SOABI"), "python.soabi")} + libc_name, libc_version = platform.libc_ver() + platform_value = {"system": platform.system(), "release": platform.release(), "version": platform.version(), "machine": platform.machine(), "pointer_bits": 8 * struct.calcsize("P"), "byteorder": sys.byteorder, "libc_name": libc_name, "libc_version": libc_version} + for key in ("system", "release", "version", "machine", "libc_name", "libc_version"): platform_value[key] = _bounded(platform_value[key], f"platform.{key}") + _need(platform_value["system"] == "Linux" and platform_value["byteorder"] in ("little", "big") and platform_value["pointer_bits"] > 0, "runtime platform is not admitted") + locale_value = {"active": _bounded(locale.setlocale(locale.LC_ALL, None), "locale.active", 512), "preferred_encoding": _bounded(locale.getpreferredencoding(False), "locale.preferred_encoding", 512)} + value = {"schema": "owned-root-assembly-successor-runtime.v2", "python": python, "platform": platform_value, "locale": locale_value, "managed_launcher": launcher, "requirements": requirements, "direct_distributions": [{"name": n, "version": v} for n, v in direct], "resolved_distributions": [{"name": n, "version": v} for n, v in resolved], "builtin_modules": builtins} + raw = artifacts.canonical_json_bytes(value) + _need(len(raw) <= 64 * 1024, "runtime fingerprint exceeds its 64 KiB cap"); return value, raw, artifacts.sha256_bytes(raw) +def _static() -> dict: + _need(os.environ.get("PYTHONHASHSEED") == "0", "comparator requires literal PYTHONHASHSEED=0") + contract = _record(REPO / CONTRACT_ROLE, CONTRACT_ROLE) + _need(contract["sha256"] == EXPECTED_CONTRACT_SHA256, "design-contract SHA-256 does not match the independent literal") + artifacts.validate_contract_sidecar(artifacts.read_regular_file(REPO / SIDECAR_ROLE), EXPECTED_CONTRACT_SHA256) + source, profile = _record(REPO / SOURCE_ROLE, SOURCE_ROLE), _record(REPO / PROFILE_ROLE, PROFILE_ROLE) + _need((source["sha256"], profile["sha256"]) == (EXPECTED_SOURCE_SHA256, EXPECTED_PROFILE_SHA256), "fixed source or profile identity drifted") + launcher, requirements = _record(REPO / CURRENT_LAUNCHER_ROLE, CURRENT_LAUNCHER_ROLE), _record(REPO / REQUIREMENTS_ROLE, REQUIREMENTS_ROLE) + shell_literal = f'EXPECTED_CONTRACT_SHA256="{EXPECTED_CONTRACT_SHA256}"'.encode("ascii"); python_literal = f'EXPECTED_CONTRACT_SHA256 = "{EXPECTED_CONTRACT_SHA256}"'.encode("ascii") + _need(artifacts.read_regular_file(PACKAGE / "owned_root_launcher.sh").count(shell_literal) == 1 and artifacts.read_regular_file(PACKAGE / "build_owned_root.py").count(python_literal) == 1, "the two required code literals do not match the contract identity"); _need(artifacts.read_regular_file(REPO / REQUIREMENTS_ROLE) == b"numpy==2.2.6\nscikit-image==0.25.2\nPillow==11.1.0\n", "requirements are not the exact pinned file") + implementation = _implementation_files(); runtime, runtime_bytes, runtime_sha = _runtime(launcher, requirements) + return {"contract": contract, "source": source, "profile_table": profile, "runtime": runtime, "runtime_bytes": runtime_bytes, "runtime_fingerprint_sha256": runtime_sha, "implementation_files": implementation} +def _args() -> tuple[Path, Path, Path, Path]: + _need(len(sys.argv) == 7 and sys.argv[3] == "--test-receipt" and sys.argv[5] == "--output", "usage: compare_two_seed_outputs.py SEED17 SEED29 --test-receipt RECEIPT --output COMPARISON") + raw_values = (sys.argv[1], sys.argv[2], sys.argv[4], sys.argv[6]) + _need(not any(not raw.startswith("/") or any(part in ("", ".", "..") for part in raw.split("/")[1:]) for raw in raw_values), "all comparator paths must be canonical absolute paths without empty or dot components") + values = tuple(Path(raw) for raw in raw_values); seed17, seed29, receipt, output = values + _need((seed17.name, seed29.name, receipt.name, output.name) == ("seed-17", "seed-29", "managed-test-receipt.json", "comparison"), "comparator paths do not use the fixed role names"); _need(seed17.parent == seed29.parent == receipt.parent == output.parent, "seed bundles, receipt, and comparison must be invocation-owned siblings"); _need(not any(not os.path.lexists(path) for path in (seed17, seed29, receipt)) and not os.path.lexists(output), "seed bundles and receipt must exist, while comparison must be absent") + return values +def _admit_receipt(path: Path) -> tuple: + parent = artifacts._open_directory(path.parent) + try: + parent_state = os.fstat(parent); descriptor = os.open(path.name, READ_FLAGS, dir_fd=parent) + try: + raw, receipt_state = artifacts._read_stable_fd(descriptor, 2 * 1024 * 1024); artifacts._require_same_stat(receipt_state, os.stat(path.name, dir_fd=parent, follow_symlinks=False), "managed-test receipt changed during admission") + value = artifacts.decode_canonical_json(raw); _need(isinstance(value, dict), "managed-test receipt is not an object"); return value, raw, parent, descriptor, parent_state, receipt_state + except Exception: os.close(descriptor); raise + except Exception: os.close(parent); raise +def _remove_receipt(path: Path, raw: bytes, parent: int, descriptor: int, parent_state: os.stat_result, receipt_state: os.stat_result, stage: Path) -> None: + current_parent = artifacts._open_directory(path.parent) + try: + current_parent_state = os.fstat(current_parent); _need(os.path.samestat(parent_state, current_parent_state) and all(getattr(parent_state, field) == getattr(current_parent_state, field) for field in ("st_mode", "st_uid", "st_gid", "st_rdev")), "managed-test receipt parent identity changed before removal") + finally: os.close(current_parent) + observed, observed_state = artifacts._read_stable_fd(descriptor, 2 * 1024 * 1024); _need(observed == raw, "managed-test receipt bytes changed before removal"); artifacts._require_same_stat(receipt_state, observed_state, "managed-test receipt identity changed before removal"); artifacts._require_same_stat(receipt_state, os.stat(path.name, dir_fd=parent, follow_symlinks=False), "managed-test receipt pathname was substituted") + stage_fd, tomb = artifacts._open_directory(stage), ".managed-test-receipt.remove" + try: + os.rename(path.name, tomb, src_dir_fd=parent, dst_dir_fd=stage_fd) + try: os.stat(path.name, dir_fd=parent, follow_symlinks=False); raise ComparatorError("managed-test receipt pathname remained after removal move") + except FileNotFoundError: pass + _need(artifacts._same_published_state(receipt_state, os.stat(tomb, dir_fd=stage_fd, follow_symlinks=False)), "managed-test receipt pathname was substituted during removal"); final, final_state = artifacts._read_stable_fd(descriptor, 2 * 1024 * 1024); _need(final == raw and artifacts._same_published_state(receipt_state, final_state), "managed-test receipt bytes or identity changed during removal"); os.unlink(tomb, dir_fd=stage_fd) + try: os.stat(tomb, dir_fd=stage_fd, follow_symlinks=False); raise ComparatorError("managed-test receipt tomb remained after removal") + except FileNotFoundError: pass + finally: os.close(stage_fd) +def _receipt(value: dict, raw: bytes, path: Path, identity: dict, builder: object) -> dict: + keys = {"schema", "outcome", "literal_invocation", "contract_sha256", "runtime_fingerprint_sha256", "implementation_files", "executed_test_ids", "required_test_ids", "results"}; required = ["test_mesh_correctness.ProductionIntersectionFixtureTests.test_contract_fixture_matrix", "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix"]; executed, results = value.get("executed_test_ids"), value.get("results") + _need(set(value) == keys and value.get("schema") == "owned-root-assembly-successor-managed-test-receipt.v1" and value.get("outcome") == "success" and value.get("contract_sha256") == EXPECTED_CONTRACT_SHA256 and value.get("runtime_fingerprint_sha256") == identity["runtime_fingerprint_sha256"] and value.get("implementation_files") == identity["implementation_files"] and isinstance(executed, list) and bool(executed) and all(type(item) is str for item in executed) and executed == sorted(set(executed), key=lambda item: item.encode("utf-8")) and value.get("required_test_ids") == required and all(executed.count(item) == 1 for item in required), "managed-test receipt identity or test inventory is invalid") + expected_invocation = {"environment": ["PYTHONHASHSEED=0"], "argv": [BUILDER_ROLE, "--internal-managed-tests", "--receipt", str(path)]} + _need(value.get("literal_invocation") == expected_invocation, "managed-test receipt invocation is not exact") + expected_results = {"tests_run": len(executed), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0} + _need(isinstance(results, dict) and set(results) == set(expected_results) and all(type(results[name]) is int for name in results) and results == expected_results, "managed-test receipt result counts are not exact"); _api(builder, "validate_managed_test_receipt")(receipt=value, raw=raw, identity=identity); return value +def _sidecar(raw: bytes, payload: bytes, name: str) -> None: + _need(raw == f"{artifacts.sha256_bytes(payload)} {name}\n".encode("ascii"), f"{name} sidecar is not the exact LF-terminated hash line") +def _admit_report_sidecar(root: Path, records: dict) -> None: + path = root / "report.sha256"; raw = artifacts.read_regular_file(path, max_bytes=128) + _need(len(raw) == 78 and raw[64:] == b" report.json\n" and not any(byte not in b"0123456789abcdef" for byte in raw[:64]), f"{path} does not have the required lexical grammar"); _unchanged(path, "report.sha256", records["report.sha256"]) +def _stable(root: Path, records: dict, identity: dict) -> dict: + path = root / "stable-manifest.json"; value, _ = _json(path); _unchanged(path, "stable-manifest.json", records["stable-manifest.json"]) + keys = {"schema", "contract_sha256", "recipe_id", "runtime", "implementation_files", "input_manifest", "coordinate_manifest", "gate_manifest", "causality_manifest", "render_manifest", "artifact_hashes"} + _need(set(value) == keys and value.get("schema") == "owned-root-assembly-successor-stable-manifest.v1" and value.get("contract_sha256") == EXPECTED_CONTRACT_SHA256 and value.get("implementation_files") == identity["implementation_files"] and artifacts.canonical_json_bytes(value.get("runtime")) == identity["runtime_bytes"], "stable manifest has a mismatched identity"); return value +def _report(root: Path, seed: int, records: dict, identity: dict, builder: object, stable: dict) -> None: + report_path, sidecar_path = root / "report.json", root / "report.sha256"; payload = artifacts.read_regular_file(report_path, max_bytes=2 * 1024 * 1024); value = artifacts.decode_canonical_json(payload) + keys = {"schema", "outcome", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "stable_manifest", "gates"} + _need(isinstance(value, dict) and set(value) == keys and value.get("schema") == "owned-root-assembly-successor-run-report.v1" and value.get("outcome") == "success" and value.get("seed") == seed and value.get("runtime_fingerprint_sha256") == identity["runtime_fingerprint_sha256"], f"seed-{seed} run report identity is invalid") + _unchanged(report_path, "report.json", records["report.json"], 2 * 1024 * 1024) + reference = {"role_path": "stable-manifest.json", "bytes": records["stable-manifest.json"]["bytes"], "sha256": records["stable-manifest.json"]["sha256"], "schema": stable["schema"]} + _need(value.get("stable_manifest") == reference, f"seed-{seed} run report stable-manifest reference is invalid"); _api(builder, "validate_run_report")(root=root, seed=seed, report=value, identity=identity); _unchanged(sidecar_path, "report.sha256", records["report.sha256"]); _sidecar(artifacts.read_regular_file(sidecar_path, max_bytes=128), payload, "report.json") +def _outer_nodes(root: Path) -> None: + if not root.is_absolute() or os.path.normpath(str(root)) != str(root): raise ComparatorError("outer staging root is not canonical and absolute") + descriptor = artifacts._open_directory(root) + try: + with os.scandir(descriptor) as entries: rows = sorted((entry.name, entry.stat(follow_symlinks=False)) for entry in entries) + finally: os.close(descriptor) + if [name for name, _ in rows] != ["comparison", "seed-17", "seed-29"] or any(not stat.S_ISDIR(info.st_mode) for _, info in rows): raise ComparatorError("staging root is not the exact closed outer inventory") +def outer_publication_inventory(root: Path) -> list[dict]: + """Semantically re-admit a completed pair and return its exact closed inventory.""" + root = Path(root); _outer_nodes(root); identity = _static(); builder = importlib.import_module("build_owned_root") + comparison_root = root / "comparison"; comparison_rows = artifacts.closed_inventory(comparison_root, ("comparison-report.json", "comparison-report.sha256"), max_file_bytes=2 * 1024 * 1024); comparison_records = {row["role_path"]: row for row in comparison_rows} + value, raw = _json(comparison_root / "comparison-report.json"); _unchanged(comparison_root / "comparison-report.json", "comparison-report.json", comparison_records["comparison-report.json"], 2 * 1024 * 1024) + _sidecar(artifacts.read_regular_file(comparison_root / "comparison-report.sha256", max_bytes=128), raw, "comparison-report.json"); _unchanged(comparison_root / "comparison-report.sha256", "comparison-report.sha256", comparison_records["comparison-report.sha256"]) + keys = {"schema", "outcome", "comparator", "runtime_fingerprint_sha256", "managed_test_receipt", "seed_bundles", "stable_comparisons", "excluded_run_local_roles"}; comparator = next(row for row in identity["implementation_files"] if row["role_path"] == COMPARATOR_ROLE) + if (set(value) != keys or value.get("schema") != "owned-root-assembly-successor-comparison-report.v1" or value.get("outcome") != "success" or value.get("comparator") != comparator or value.get("runtime_fingerprint_sha256") != identity["runtime_fingerprint_sha256"] or value.get("excluded_run_local_roles") != ["report.json", "report.sha256"]): raise ComparatorError("comparison report identity or closed schema is invalid") + receipt = value.get("managed_test_receipt"); receipt_path = root / "managed-test-receipt.json" + if not isinstance(receipt, dict): raise ComparatorError("comparison report managed receipt is invalid") + _receipt(receipt, artifacts.canonical_json_bytes(receipt), receipt_path, identity, builder) + comparisons, bundles = value.get("stable_comparisons"), value.get("seed_bundles") + if not isinstance(comparisons, list) or [row.get("role_path") if isinstance(row, dict) else None for row in comparisons] != list(STABLE_ROLES) or not isinstance(bundles, list) or len(bundles) != 2: raise ComparatorError("comparison report inventories are not exact") + groups = [] + for index, seed in enumerate((17, 29)): + seed_root = root / f"seed-{seed}"; records = _bundle(seed_root); stable = _stable(seed_root, records, identity); _api(builder, "validate_seed_bundle")(root=seed_root, seed=seed, identity=identity); _report(seed_root, seed, records, identity, builder, stable) + expected_bundle = {"seed": seed, "role_path": f"seed-{seed}", "stable_manifest": {"role_path": f"seed-{seed}/stable-manifest.json", "bytes": records["stable-manifest.json"]["bytes"], "sha256": records["stable-manifest.json"]["sha256"], "schema": stable["schema"]}, "report": {**records["report.json"], "role_path": f"seed-{seed}/report.json"}, "report_sidecar": {**records["report.sha256"], "role_path": f"seed-{seed}/report.sha256"}} + if bundles[index] != expected_bundle or any(records[role] != comparisons[position] for position, role in enumerate(STABLE_ROLES)): raise ComparatorError(f"seed-{seed} bytes are not bound by the comparison report") + groups.append((f"seed-{seed}", records.values())) + if artifacts.closed_inventory(comparison_root, ("comparison-report.json", "comparison-report.sha256"), max_file_bytes=2 * 1024 * 1024) != comparison_rows: raise ComparatorError("comparison result changed during outer admission") + groups.append(("comparison", comparison_rows)); inventory = sorted(({**record, "role_path": f"{prefix}/{record['role_path']}"} for prefix, records in groups for record in records), key=lambda record: record["role_path"].encode("utf-8")) + if len(inventory) != 96: raise ComparatorError("outer publication inventory is not exactly 47+47+2 roles") + return inventory +def _compare_admitted(seed17: Path, seed29: Path, receipt_path: Path, output: Path, records17: dict, records29: dict, admission: tuple) -> Path: + receipt, receipt_raw, receipt_parent, receipt_fd, receipt_parent_state, receipt_state = admission + # Stage 2: all fixed, runtime, seed, recipe, and receipt identities. + identity = _static() + builder = importlib.import_module("build_owned_root") + receipt = _receipt(receipt, receipt_raw, receipt_path, identity, builder) + stables = [_stable(root, records, identity) for root, records in ((seed17, records17), (seed29, records29))] + recipe_api = getattr(builder, "_recipe", None) + if not callable(recipe_api) or any(stable["recipe_id"] != recipe_api(identity)[1] for stable in stables): + raise ComparatorError("seed recipe identities differ") + # Stage 3: each stable DAG and its gates, in seed order. + for seed, root in ((17, seed17), (29, seed29)): + _api(builder, "validate_seed_bundle")(root=root, seed=seed, identity=identity) + # Stage 4: exactly 45 stable roles in canonical role order. + comparisons = [] + for role in STABLE_ROLES: + left, right = (artifacts.read_regular_file(root / role, max_bytes=8 * 1024 * 1024) for root in (seed17, seed29)) + for data, record in ((left, records17[role]), (right, records29[role])): + if len(data) != record["bytes"] or artifacts.sha256_bytes(data) != record["sha256"]: + raise ComparatorError(f"stable role changed after inventory: {role}") + if left != right: + raise ComparatorError(f"stable role differs across seeds: {role}") + comparisons.append({"role_path": role, "bytes": len(left), "sha256": artifacts.sha256_bytes(left)}) + # Stage 5: each complete report followed by its sidecar, in seed order. + for seed, root, records, stable in ((17, seed17, records17, stables[0]), (29, seed29, records29, stables[1])): + _report(root, seed, records, identity, builder, stable) + # Stage 6: private construction, receipt removal, then atomic publication. + bundles = [{"seed": seed, "role_path": f"seed-{seed}", "stable_manifest": {"role_path": f"seed-{seed}/stable-manifest.json", "bytes": records["stable-manifest.json"]["bytes"], "sha256": records["stable-manifest.json"]["sha256"], "schema": stable["schema"]}, "report": {**records["report.json"], "role_path": f"seed-{seed}/report.json"}, "report_sidecar": {**records["report.sha256"], "role_path": f"seed-{seed}/report.sha256"}} for seed, records, stable in ((17, records17, stables[0]), (29, records29, stables[1]))] + report = {"schema": "owned-root-assembly-successor-comparison-report.v1", "outcome": "success", "comparator": next(row for row in identity["implementation_files"] if row["role_path"] == COMPARATOR_ROLE), "runtime_fingerprint_sha256": identity["runtime_fingerprint_sha256"], "managed_test_receipt": receipt, "seed_bundles": bundles, "stable_comparisons": comparisons, "excluded_run_local_roles": ["report.json", "report.sha256"]} + stage = Path(tempfile.mkdtemp(prefix=f".{output.name}.stage-", dir=output.parent)) + try: + payload = artifacts.canonical_json_bytes(report) + artifacts.write_bytes_no_replace(stage / "comparison-report.json", payload) + artifacts.write_bytes_no_replace(stage / "comparison-report.sha256", f"{artifacts.sha256_bytes(payload)} comparison-report.json\n".encode("ascii")) + _sidecar(artifacts.read_regular_file(stage / "comparison-report.sha256"), payload, "comparison-report.json"); comparison_inventory = artifacts.closed_inventory(stage, ("comparison-report.json", "comparison-report.sha256"), max_file_bytes=2 * 1024 * 1024) + _remove_receipt(receipt_path, receipt_raw, receipt_parent, receipt_fd, receipt_parent_state, receipt_state, stage) + artifacts.publish_no_replace(stage, output, comparison_inventory, max_file_bytes=2 * 1024 * 1024) + stage = None + return output + finally: + if stage is not None and stage.exists() and not stage.is_symlink(): + shutil.rmtree(stage) +def compare(seed17: Path, seed29: Path, receipt_path: Path, output: Path) -> Path: + # Stage 1: closed structure, lexical report sidecars, and canonical receipt. + records17, records29 = _bundle(seed17), _bundle(seed29); _admit_report_sidecar(seed17, records17); _admit_report_sidecar(seed29, records29) + admission = _admit_receipt(receipt_path) + try: return _compare_admitted(seed17, seed29, receipt_path, output, records17, records29, admission) + finally: os.close(admission[3]); os.close(admission[2]) +def main() -> int: + try: compare(*_args()) + except Exception as exc: print(f"owned-root comparator: error: {exc}", file=sys.stderr); return 1 + return 0 +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/owned-root-assembly-successor/mesh_correctness.py b/experiments/owned-root-assembly-successor/mesh_correctness.py index cc21ced..9acfba5 100644 --- a/experiments/owned-root-assembly-successor/mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/mesh_correctness.py @@ -7,6 +7,7 @@ from collections import defaultdict from dataclasses import dataclass from fractions import Fraction +from functools import wraps from typing import NoReturn _FIXED_I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") @@ -28,97 +29,62 @@ S, T, PI = _FIXED_S, _FIXED_T, _FIXED_PI FOLD_LIMITS_DEGREES = _FIXED_FOLD_LIMITS MAX_TRIANGLES, MAX_CANDIDATES = _MAX_TRIANGLES, _MAX_CANDIDATES -_STRUCTURAL_FLOORS = { - 0: {"edge_length": 0.10, "triangle_area": 0.010, "quad_area": 0.010}, - 1: {"edge_length": 0.04, "triangle_area": 0.002, "quad_area": 0.002}, - 2: {"edge_length": 0.02, "triangle_area": 0.0005, "quad_area": 0.0005}, -} +_STRUCTURAL_FLOORS = {0: {"edge_length": 0.10, "triangle_area": 0.010, "quad_area": 0.010}, 1: {"edge_length": 0.04, "triangle_area": 0.002, "quad_area": 0.002}, 2: {"edge_length": 0.02, "triangle_area": 0.0005, "quad_area": 0.0005}} STRUCTURAL_FLOORS = {level: dict(values) for level, values in _STRUCTURAL_FLOORS.items()} -_THRESHOLD_RECORDS = tuple( - {"threshold_id": f"threshold.intersection.L{level}.broad_phase_candidate_count", - "relation": "le", "lower": None, "upper": _MAX_CANDIDATES, "unit": "count"} - for level in range(3) -) +_THRESHOLD_RECORDS = tuple({"threshold_id": f"threshold.intersection.L{level}.broad_phase_candidate_count", "relation": "le", "lower": None, "upper": _MAX_CANDIDATES, "unit": "count"} for level in range(3)) +class MeshCorrectnessError(ValueError): """A deterministic, fail-closed mesh correctness failure.""" -class MeshCorrectnessError(ValueError): - """A deterministic, fail-closed mesh correctness failure.""" - -def _fail(message: str) -> NoReturn: - raise MeshCorrectnessError(message) +def _fail(message: str) -> NoReturn: raise MeshCorrectnessError(message) def _finite_float(value, label: str) -> float: - if type(value) is not float or not math.isfinite(value): - _fail(f"{label} must be a finite binary64 value") + if type(value) is not float or not math.isfinite(value): _fail(f"{label} must be a finite binary64 value") return value def _integer(value, label: str) -> int: - if type(value) is not int: - _fail(f"{label} must be an integer") + if type(value) is not int: _fail(f"{label} must be an integer") return value def _sequence(raw, label: str, cap=None): - if type(raw) not in (list, tuple): - _fail(f"{label} must be an exact list or tuple") - if cap is not None and len(raw) > cap: - _fail(f"{label.rstrip('s')} cap exceeded: {len(raw)} > {cap}") + if type(raw) not in (list, tuple): _fail(f"{label} must be an exact list or tuple") + if cap is not None and len(raw) > cap: _fail(f"{label.rstrip('s')} cap exceeded: {len(raw)} > {cap}") return raw def _named_mapping(raw, label, count=None): - if type(raw) is not dict or not raw: - _fail(f"{label} must be a non-empty exact dict") - if any(type(name) is not str or not name for name in raw): - _fail(f"{label} names must be non-empty strings") - if count is not None and len(raw) != count: - _fail(f"exactly {count} {label} are required") + if type(raw) is not dict or not raw: _fail(f"{label} must be a non-empty exact dict") + if any(type(name) is not str or not name for name in raw): _fail(f"{label} names must be non-empty strings") + if count is not None and len(raw) != count: _fail(f"exactly {count} {label} are required") return raw def _vec(value, label: str) -> tuple[float, float, float]: values = _sequence(value, label) - if len(values) != 3: - _fail(f"{label} must be a finite 3-vector") + if len(values) != 3: _fail(f"{label} must be a finite 3-vector") return tuple(_finite_float(item, f"{label}[{i}]") for i, item in enumerate(values)) def _points(raw): values = _sequence(raw, "vertices") - if not values: - _fail("vertices must not be empty") + if not values: _fail("vertices must not be empty") return tuple(_vec(value, f"vertices[{i}]") for i, value in enumerate(values)) def _simple_indices(raw, vertex_count, label): values = tuple(_integer(value, label) for value in _sequence(raw, label)) - if (len(values) < 3 or len(set(values)) != len(values) - or any(index < 0 or index >= vertex_count for index in values)): - _fail(f"{label} must be simple and in range") + if len(values) < 3 or len(set(values)) != len(values) or any(index < 0 or index >= vertex_count for index in values): _fail(f"{label} must be simple and in range") return values def _indexed_rows(raw, width, vertex_count, label, cap=None): - rows = _sequence(raw, label, cap) - result = [] + rows = _sequence(raw, label, cap); result = [] for face_index, row in enumerate(rows): values = _sequence(row, f"{label}[{face_index}]") - if len(values) != width: - _fail(f"{label}[{face_index}] must have {width} indices") + if len(values) != width: _fail(f"{label}[{face_index}] must have {width} indices") face = tuple(_integer(value, f"{label}[{face_index}]") for value in values) - if any(index < 0 or index >= vertex_count for index in face): - _fail(f"{label} index out of range at {face_index}") - if len(set(face)) != width: - _fail(f"{label[:-1]} has repeated vertex index at {face_index}") + if any(index < 0 or index >= vertex_count for index in face): _fail(f"{label} index out of range at {face_index}") + if len(set(face)) != width: _fail(f"{label[:-1]} has repeated vertex index at {face_index}") result.append(face) return tuple(result) -def _canonical_cycle(face): - return min(sequence[i:] + sequence[:i] - for sequence in (tuple(face), tuple(reversed(face))) - for i in range(len(face))) +def _canonical_cycle(face): return min(sequence[i:] + sequence[:i] for sequence in (tuple(face), tuple(reversed(face))) for i in range(len(face))) def _quads(raw, vertex_count): - faces = _indexed_rows(raw, 4, vertex_count, "quads", _MAX_QUADS) - keys = tuple(_canonical_cycle(face) for face in faces) - if len(set(keys)) != len(keys): - _fail("duplicate quad, including reversed/cyclic duplicate") + faces = _indexed_rows(raw, 4, vertex_count, "quads", _MAX_QUADS); keys = tuple(_canonical_cycle(face) for face in faces) + if len(set(keys)) != len(keys): _fail("duplicate quad, including reversed/cyclic duplicate") return faces def _add_vec(a, b): return tuple(a[i] + b[i] for i in range(3)) def _sub_vec(a, b): return tuple(a[i] - b[i] for i in range(3)) def _dot_vec(a, b): return (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2] -def _cross_vec(a, b): - return (a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0]) +def _cross_vec(a, b): return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) def _norm_vec(value): return math.sqrt(_dot_vec(value, value)) def _normalize_vec(value, label): length = _norm_vec(value) - if not math.isfinite(length) or length <= 0.0: - _fail(f"{label} must be finite and nonzero") + if not math.isfinite(length) or length <= 0.0: _fail(f"{label} must be finite and nonzero") return tuple(component / length for component in value) def add(a, b): return _add_vec(_vec(a, "left vector"), _vec(b, "right vector")) def sub(a, b): return _sub_vec(_vec(a, "left vector"), _vec(b, "right vector")) @@ -127,270 +93,232 @@ def cross(a, b): return _cross_vec(_vec(a, "left vector"), _vec(b, "right vector def norm(value): return _norm_vec(_vec(value, "vector")) def normalize(value): return _normalize_vec(_vec(value, "vector"), "vector normal") def _normalize_points(points): - lower = tuple(min(point[i] for point in points) for i in range(3)) - extent = tuple(max(point[i] for point in points) - lower[i] for i in range(3)) - scale = _norm_vec(extent) - if not math.isfinite(scale) or scale <= 0.0: - _fail("mesh normalization scale must be finite and positive") - normalized = tuple(tuple((point[i] - lower[i]) / scale for i in range(3)) - for point in points) - if any(not math.isfinite(value) for point in normalized for value in point): - _fail("normalized coordinates must be finite") + lower = tuple(min(point[i] for point in points) for i in range(3)); extent = tuple(max(point[i] for point in points) - lower[i] for i in range(3)); scale = _norm_vec(extent) + if not math.isfinite(scale) or scale <= 0.0: _fail("mesh normalization scale must be finite and positive") + normalized = tuple(tuple((point[i] - lower[i]) / scale for i in range(3)) for point in points) + if any(not math.isfinite(value) for point in normalized for value in point): _fail("normalized coordinates must be finite") return normalized, scale def interval_disjoint(lower_a, upper_a, lower_b, upper_b): - values = tuple(_finite_float(value, label) for value, label in zip( - (lower_a, upper_a, lower_b, upper_b), - ("lower_A", "upper_A", "lower_B", "upper_B"))) + values = tuple(_finite_float(value, label) for value, label in zip((lower_a, upper_a, lower_b, upper_b), ("lower_A", "upper_A", "lower_B", "upper_B"))) return _interval_disjoint(*values) def _interval_disjoint(lower_a, upper_a, lower_b, upper_b): - return (upper_a < lower_b - _FIXED_I0 - or upper_b < lower_a - _FIXED_I0) + cut_b = lower_b - _FIXED_I0 + cut_a = lower_a - _FIXED_I0 + return upper_a < cut_b or upper_b < cut_a def _edge_incidence(faces): result = defaultdict(list) for face_index, face in enumerate(faces): for slot, start in enumerate(face): - end = face[(slot + 1) % len(face)] - result[(min(start, end), max(start, end))].append((face_index, start, end)) + end = face[(slot + 1) % len(face)]; result[(min(start, end), max(start, end))].append((face_index, start, end)) return result +def _child_face_catalog(faces, vertex_count): + edges = tuple(sorted(_edge_incidence(faces))); edge_points = {edge: vertex_count + index for index, edge in enumerate(edges)}; face_start = vertex_count + len(edges); children = [] + for face_index, face in enumerate(faces): + center = face_start + face_index + for slot, vertex in enumerate(face): + following = tuple(sorted((vertex, face[(slot + 1) % 4]))); preceding = tuple(sorted((face[(slot - 1) % 4], vertex))) + children.append((vertex, edge_points[following], center, edge_points[preceding])) + return tuple(children), face_start + len(faces) +def _expected_face_catalogs(raw): + rows = _sequence(raw, "expected base faces", _MAX_BASE_QUADS) + if not rows: _fail("expected base faces must not be empty") + rows = tuple(_sequence(row, f"expected base faces[{face_index}]") for face_index, row in enumerate(rows)) + if any(len(row) != 4 for row in rows): _fail("expected base faces must contain four-index cycles") + indices = tuple(_integer(value, f"expected base faces[{face_index}]") for face_index, row in enumerate(rows) for value in row) + if any(index < 0 for index in indices): _fail("expected base face index must be non-negative") + vertex_count = max(indices) + 1 + if vertex_count > _MAX_BASE_CONTROLS: _fail("expected base control cap exceeded") + base = _indexed_rows(rows, 4, vertex_count, "expected base faces", _MAX_BASE_QUADS) + if len({_canonical_cycle(face) for face in base}) != len(base): _fail("duplicate expected base face") + level1, count1 = _child_face_catalog(base, vertex_count); level2, _ = _child_face_catalog(level1, count1) + return base, level1, level2 +def derive_expected_face_catalogs(expected_base_faces): return _expected_face_catalogs(expected_base_faces) def _validate_loops(raw, vertex_count): - if raw is None: - return {} - raw = _named_mapping(raw, "boundary loops") - result, used = {}, set() + if raw is None: return {} + raw = _named_mapping(raw, "boundary loops"); result, used = {}, set() for name in sorted(raw, key=lambda value: value.encode("utf-8")): loop = _simple_indices(raw[name], vertex_count, f"boundary loop {name}") - if used.intersection(loop): - _fail(f"boundary loops overlap at {name}") - used.update(loop) - result[name] = loop + if used.intersection(loop): _fail(f"boundary loops overlap at {name}") + used.update(loop); result[name] = loop return result def _cyclic_equal(actual, expected, reverse=False): target = tuple(reversed(expected)) if reverse else tuple(expected) return len(actual) == len(target) and any(actual == target[i:] + target[:i] for i in range(len(target))) def _boundary_cycles(edges): outgoing = defaultdict(list) - for _, start, end in edges: - outgoing[start].append(end) - if any(len(values) != 1 for values in outgoing.values()): - _fail("boundary edges do not form directed cycles") - next_vertex = {start: values[0] for start, values in outgoing.items()} - remaining, cycles = set(next_vertex), [] + for _, start, end in edges: outgoing[start].append(end) + if any(len(values) != 1 for values in outgoing.values()): _fail("boundary edges do not form directed cycles") + next_vertex = {start: values[0] for start, values in outgoing.items()}; remaining, cycles = set(next_vertex), [] while remaining: - start = current = min(remaining) - cycle = [] - while current in remaining: - remaining.remove(current) - cycle.append(current) - current = next_vertex[current] - if current != start or len(cycle) < 3: - _fail("boundary cycle is not closed") + start = current = min(remaining); cycle = [] + while current in remaining: remaining.remove(current); cycle.append(current); current = next_vertex[current] + if current != start or len(cycle) < 3: _fail("boundary cycle is not closed") cycles.append(tuple(cycle)) return tuple(sorted(cycles, key=lambda cycle: min(cycle))) @dataclass(frozen=True) class TopologyReport: - vertex_count: int - edge_count: int - face_count: int - boundary_edge_count: int - boundary_components: int - connected_components: int - euler: int - non_manifold_edges: int - orientation_conflicts: int - boundary_lengths: tuple[int, ...] - valence_inventory: tuple[tuple[int, int], ...] + vertex_count: int; edge_count: int; face_count: int; boundary_edge_count: int; boundary_components: int; connected_components: int; euler: int; non_manifold_edges: int; orientation_conflicts: int; boundary_lengths: tuple[int, ...]; valence_inventory: tuple[tuple[int, int], ...] @property - def euler_characteristic(self): - return self.euler + def euler_characteristic(self): return self.euler def _connected_components(adjacency, vertex_count): unseen, components = set(range(vertex_count)), 0 while unseen: - todo = [unseen.pop()] - components += 1 + todo = [unseen.pop()]; components += 1 while todo: - neighbours = adjacency[todo.pop()].intersection(unseen) - unseen.difference_update(neighbours) - todo.extend(neighbours) + neighbours = adjacency[todo.pop()].intersection(unseen); unseen.difference_update(neighbours); todo.extend(neighbours) return components def _topology_report(vertex_count, quads, loops, expected_faces): if expected_faces is not None: - expected = _indexed_rows( - expected_faces, 4, vertex_count, "expected_faces", _MAX_QUADS) - if quads != expected: - _fail("face winding/catalog does not match exactly") - incidence = _edge_incidence(quads) - non_manifold = sum(len(items) > 2 for items in incidence.values()) - if non_manifold: - _fail(f"non-manifold edge count {non_manifold}") - conflicts = sum(len(items) == 2 and items[0][1:] == items[1][1:] - for items in incidence.values()) - if conflicts: - _fail(f"orientation conflict count {conflicts}") - boundary = [items[0] for items in incidence.values() if len(items) == 1] - cycles = _boundary_cycles(boundary) if boundary else () + expected = _indexed_rows(expected_faces, 4, vertex_count, "expected_faces", _MAX_QUADS) + if quads != expected: _fail("face winding/catalog does not match exactly") + incidence = _edge_incidence(quads); non_manifold = sum(len(items) > 2 for items in incidence.values()) + if non_manifold: _fail(f"non-manifold edge count {non_manifold}") + conflicts = sum(len(items) == 2 and items[0][1:] == items[1][1:] for items in incidence.values()) + if conflicts: _fail(f"orientation conflict count {conflicts}") + boundary = [items[0] for items in incidence.values() if len(items) == 1]; cycles = _boundary_cycles(boundary) if boundary else () if loops: expected = tuple(sorted(loops.values(), key=lambda cycle: min(cycle))) - if len(cycles) != len(expected) or any( - sum(_cyclic_equal(actual, wanted) for wanted in expected) != 1 - for actual in cycles): - _fail("boundary cycle does not match a declared loop orientation") + if len(cycles) != len(expected) or any(sum(_cyclic_equal(actual, wanted) for wanted in expected) != 1 for actual in cycles): _fail("boundary cycle does not match a declared loop orientation") adjacency, valence, used = defaultdict(set), defaultdict(int), set() for first, second in incidence: - adjacency[first].add(second) - adjacency[second].add(first) - valence[first] += 1 - valence[second] += 1 - used.update((first, second)) - if len(used) != vertex_count: - _fail("unused vertex IDs are not permitted") + adjacency[first].add(second); adjacency[second].add(first); valence[first] += 1; valence[second] += 1; used.update((first, second)) + if len(used) != vertex_count: _fail("unused vertex IDs are not permitted") components = _connected_components(adjacency, vertex_count) - if components != 1: - _fail("surface is not connected") - return TopologyReport( - vertex_count, len(incidence), len(quads), len(boundary), len(cycles), components, - vertex_count - len(incidence) + len(quads), non_manifold, conflicts, - tuple(len(cycle) for cycle in cycles), tuple(sorted(valence.items()))) - + if components != 1: _fail("surface is not connected") + return TopologyReport(vertex_count, len(incidence), len(quads), len(boundary), len(cycles), components, vertex_count - len(incidence) + len(quads), non_manifold, conflicts, tuple(len(cycle) for cycle in cycles), tuple(sorted(valence.items()))) def validate_topology(vertex_count, faces, boundary_loops=None, expected_faces=None): _integer(vertex_count, "vertex_count") - if vertex_count <= 0: - _fail("vertex_count must be positive") + if vertex_count <= 0: _fail("vertex_count must be positive") quads = _quads(faces, vertex_count) - return _topology_report(vertex_count, quads, _validate_loops(boundary_loops, vertex_count), - expected_faces) -def _triangle_normal(triangle, points): - return _cross_vec(_sub_vec(points[triangle[1]], points[triangle[0]]), _sub_vec(points[triangle[2]], points[triangle[0]])) + return _topology_report(vertex_count, quads, _validate_loops(boundary_loops, vertex_count), expected_faces) +def _triangle_normal(triangle, points): return _cross_vec(_sub_vec(points[triangle[1]], points[triangle[0]]), _sub_vec(points[triangle[2]], points[triangle[0]])) def _quad_data(quad, points): first, second, third, fourth = (points[index] for index in quad) - normal_a = _cross_vec(_sub_vec(second, first), _sub_vec(third, first)) - normal_b = _cross_vec(_sub_vec(third, first), _sub_vec(fourth, first)) - area = 0.5 * _norm_vec(normal_a) + 0.5 * _norm_vec(normal_b) - return area, _normalize_vec(_add_vec(normal_a, normal_b), "quad normal") + normal_a = _cross_vec(_sub_vec(second, first), _sub_vec(third, first)); normal_b = _cross_vec(_sub_vec(third, first), _sub_vec(fourth, first)) + return 0.5 * _norm_vec(normal_a) + 0.5 * _norm_vec(normal_b), _normalize_vec(_add_vec(normal_a, normal_b), "quad normal") +def quad_normal(vertices, quad): + points = _points(vertices); return _quad_data(_indexed_rows((quad,), 4, len(points), "quad")[0], points)[1] def _loop_geometry(selected): centroid = (0.0, 0.0, 0.0) - for point in selected: - centroid = _add_vec(centroid, point) - centroid = tuple(value / len(selected) for value in centroid) - area = (0.0, 0.0, 0.0) - for index, point in enumerate(selected): - area = _add_vec(area, _cross_vec(_sub_vec(point, centroid), - _sub_vec(selected[(index + 1) % len(selected)], centroid))) + for point in selected: centroid = _add_vec(centroid, point) + centroid = tuple(value / len(selected) for value in centroid); area = (0.0, 0.0, 0.0) + for index, point in enumerate(selected): area = _add_vec(area, _cross_vec(_sub_vec(point, centroid), _sub_vec(selected[(index + 1) % len(selected)], centroid))) return centroid, tuple(0.5 * value for value in area) def port_loop_metrics(points, loop, outward_direction, adjacent_normals): - points = _points(points) - loop = _simple_indices(loop, len(points), "port loop") - direction = _normalize_vec(_vec(outward_direction, "port direction"), "port direction") - selected = tuple(points[index] for index in loop) - centroid, area = _loop_geometry(selected) - area_unit = _normalize_vec(area, "port area normal") - normals = tuple(_normalize_vec(_vec(value, "adjacent face normal"), - "adjacent face normal") - for value in _sequence(adjacent_normals, "adjacent normals")) - if len(normals) != len(loop): - _fail("port adjacent-normal count must equal loop edge count") + points = _points(points); loop = _simple_indices(loop, len(points), "port loop"); direction = _normalize_vec(_vec(outward_direction, "port direction"), "port direction") + selected = tuple(points[index] for index in loop); centroid, area = _loop_geometry(selected); area_unit = _normalize_vec(area, "port area normal") + normals = tuple(_normalize_vec(_vec(value, "adjacent face normal"), "adjacent face normal") for value in _sequence(adjacent_normals, "adjacent normals")) + if len(normals) != len(loop): _fail("port adjacent-normal count must equal loop edge count") + planarity = tuple(abs(_dot_vec(_sub_vec(point, centroid), area_unit)) for point in selected) + co_normal = tuple(_dot_vec(_normalize_vec(_cross_vec(_normalize_vec(_sub_vec(selected[(i + 1) % len(selected)], selected[i]), "port tangent"), normal), "port co-normal"), direction) for i, normal in enumerate(normals)) result = { "orientation": -_dot_vec(area_unit, direction), - "planarity": max(abs(_dot_vec(_sub_vec(point, centroid), area_unit)) - for point in selected), + "planarity": max(planarity), "planarity_samples": planarity, "area_ratio": _norm_vec(area) / (_FIXED_S * _FIXED_S), - "co_normal": min( - _dot_vec(_normalize_vec(_cross_vec( - _normalize_vec(_sub_vec(selected[(i + 1) % len(selected)], selected[i]), - "port tangent"), normal), "port co-normal"), direction) - for i, normal in enumerate(normals)), + "co_normal": min(co_normal), "co_normal_samples": co_normal, } - if any(not math.isfinite(value) for value in result.values()): - _fail("port metrics must be finite") + if any(not math.isfinite(value) for value in tuple(result[key] for key in ("orientation", "planarity", "area_ratio", "co_normal")) + planarity + co_normal): _fail("port metrics must be finite") return result - def validate_port_loop(points, loop, outward_direction, adjacent_normals): metrics = port_loop_metrics(points, loop, outward_direction, adjacent_normals) - if metrics["orientation"] < _PORT_ORIENTATION: - _fail("port orientation gate failed") - if metrics["planarity"] > _FIXED_T: - _fail("port planarity gate failed") - if metrics["area_ratio"] < _PORT_AREA_RATIO: - _fail("port area-ratio gate failed") - if metrics["co_normal"] < _PORT_CO_NORMAL: - _fail("port induced co-normal gate failed") + if metrics["orientation"] < _PORT_ORIENTATION: _fail("port orientation gate failed") + if metrics["planarity"] > _FIXED_T: _fail("port planarity gate failed") + if metrics["area_ratio"] < _PORT_AREA_RATIO: _fail("port area-ratio gate failed") + if metrics["co_normal"] < _PORT_CO_NORMAL: _fail("port induced co-normal gate failed") return metrics - -def _tagged_trace(raw, label): - items = _sequence(raw, label) +def _tagged_cycle(cycle, raw, points, label): + if type(raw) is not dict or not raw or any(type(vertex) is not int for vertex in raw): _fail(f"{label} tags must be a non-empty exact vertex-ID dict") + if set(raw) != set(cycle): _fail(f"{label} vertex IDs differ from independently derived incidence") result, seen = [], set() - for item in items: - if type(item) not in (tuple, list) or len(item) != 2: - _fail(f"{label} contains an invalid tagged sample") - tag, point = item + for vertex in cycle: + tag = raw[vertex] try: - if tag in seen: - _fail(f"{label} contains duplicate tags") + if tag in seen: _fail(f"{label} contains duplicate tags") seen.add(tag) - except TypeError as exc: - raise MeshCorrectnessError(f"{label} contains an unhashable tag") from exc - result.append((tag, _vec(point, f"{label}[{tag!r}]"))) - if not result: - _fail(f"{label} must not be empty") + except TypeError as exc: raise MeshCorrectnessError(f"{label} contains an unhashable tag") from exc + result.append((tag, vertex, points[vertex])) return tuple(result) -def junction_continuity_metrics(trace_a, trace_b): - first, second = _tagged_trace(trace_a, "trace A"), _tagged_trace(trace_b, "trace B") - first_tags, second_tags = tuple(tag for tag, _ in first), tuple(tag for tag, _ in second) - if set(first_tags) != set(second_tags): - _fail("junction trace tag sets differ") - if not _cyclic_equal(first_tags, second_tags, reverse=True): - _fail("junction trace directions are not opposite") - first_values, second_values = dict(first), dict(second) - try: - tags = sorted(first_values) - except TypeError as exc: - raise MeshCorrectnessError("junction trace tags must be orderable") from exc - residual = max(max(abs(first_values[tag][axis] - second_values[tag][axis]) - for axis in range(3)) for tag in tags) - if not math.isfinite(residual) or residual > _FIXED_T: - _fail("junction coordinate residual exceeds tolerance") - return {"tag_identity": True, "opposite_trace_direction": True, - "coordinate_residual": residual} +def _junction_continuity_metrics(points, faces, owners, incident_domains, domain_vertex_tags, expected_domain_vertex_tags=None): + domains = _sequence(incident_domains, "incident domains") + if len(domains) != 2 or any(type(domain) is not str or not domain for domain in domains) or domains[0] == domains[1]: _fail("incident domains must be two distinct non-empty strings") + tag_maps = _sequence(domain_vertex_tags, "domain vertex tags") + if len(tag_maps) != 2: _fail("domain vertex tags must contain two independently derived mappings") + if tag_maps[0] is tag_maps[1]: _fail("domain vertex tags must be independent mappings") + if expected_domain_vertex_tags is None and all(type(tag) is tuple for mapping in tag_maps for tag in mapping.values()): _fail("frozen rational junction tags require an independent reference") + if expected_domain_vertex_tags is not None and tuple(tag_maps) != tuple(_sequence(expected_domain_vertex_tags, "expected domain vertex tags")): _fail("junction tags differ from independent reference") + edge_rows = [[], []] + for uses in _edge_incidence(faces).values(): + if len(uses) != 2 or frozenset(owners[use[0]] for use in uses) != frozenset(domains): continue + for side, domain in enumerate(domains): + selected = [use for use in uses if owners[use[0]] == domain] + if len(selected) != 1: _fail("junction domain incidence is not independently unique") + edge_rows[side].append(selected[0]) + cycles = tuple(_boundary_cycles(rows) if rows else () for rows in edge_rows) + if any(len(value) != 1 for value in cycles): _fail("incident domains do not derive one shared junction cycle each") + traces = tuple(_tagged_cycle(cycles[side][0], tag_maps[side], points, f"trace {side}") for side in range(2)) + keys = tuple(tuple((tag, vertex) for tag, vertex, _ in trace) for trace in traces) + if set(keys[0]) != set(keys[1]): _fail("junction trace tags and vertex IDs differ") + if not _cyclic_equal(keys[0], keys[1], reverse=True): _fail("junction trace directions are not opposite") + first_values, second_values = ({tag: (vertex, point) for tag, vertex, point in trace} for trace in traces) + try: tags = sorted(first_values) + except TypeError as exc: raise MeshCorrectnessError("junction trace tags must be orderable") from exc + residual_samples = tuple(abs(first_values[tag][1][axis] - second_values[tag][1][axis]) for tag in tags for axis in range(3)); residual = max(residual_samples) + if not math.isfinite(residual) or residual > _FIXED_T: _fail("junction coordinate residual exceeds tolerance") + return {"tag_identity": True, "vertex_id_identity": True, "opposite_trace_direction": True, "coordinate_residual": residual, "coordinate_residual_samples": residual_samples, "traces": traces} +def junction_continuity_metrics(vertices, quads, face_owners, incident_domains, domain_vertex_tags, expected_domain_vertex_tags=None): + points = _points(vertices); faces = _quads(quads, len(points)); owners = _face_owners(face_owners, len(faces)) + return _junction_continuity_metrics(points, faces, owners, incident_domains, domain_vertex_tags, expected_domain_vertex_tags) +def classify_ownership_records(element_keys, obligations, candidate_records): + keys = tuple(_sequence(element_keys, "ownership element universe")) + if not keys or len(set(keys)) != len(keys) or type(obligations) is not dict or set(obligations) != set(keys): _fail("ownership universe and obligations must be exact and disjoint") + required = {} + for key in keys: + values = tuple(_sequence(obligations[key], f"ownership obligations for {key}")) + if not values or len(set(values)) != len(values) or any(type(value) is not str or not value for value in values): _fail("ownership obligations must be non-empty unique strings") + required[key] = values + grouped = defaultdict(list) + for index, row in enumerate(_sequence(candidate_records, "ownership candidate records")): + if type(row) not in (tuple, list) or len(row) != 3: _fail(f"ownership candidate {index} is not a key/obligation/validity record") + key, obligation, valid = row + if key not in required or obligation not in required[key] or type(valid) is not bool: _fail(f"ownership candidate {index} names an unknown obligation or has invalid validity") + grouped[(key, obligation)].append(valid) + classifications = [] + for key in keys: + states = tuple((obligation, "multiple" if len(grouped.get((key, obligation), ())) > 1 else "one" if grouped.get((key, obligation), ()) and grouped[(key, obligation)][0] else "zero") for obligation in required[key]) + classifications.append((key, states)) + overowned = sum(any(state == "multiple" for _, state in states) for _, states in classifications) + unowned = sum(not any(state == "multiple" for _, state in states) and any(state == "zero" for _, state in states) for _, states in classifications) + return {"unowned_elements": unowned, "overowned_elements": overowned, "classifications": tuple(classifications)} def fold_angle_degrees(normal_a, normal_b): - first = _normalize_vec(_vec(normal_a, "fold normal A"), "fold normal A") - second = _normalize_vec(_vec(normal_b, "fold normal B"), "fold normal B") - cosine = max(-1.0, min(1.0, _dot_vec(first, second))) - angle = math.acos(cosine) - first_step = angle * 180.0 + first = _normalize_vec(_vec(normal_a, "fold normal A"), "fold normal A"); second = _normalize_vec(_vec(normal_b, "fold normal B"), "fold normal B") + cosine = max(-1.0, min(1.0, _dot_vec(first, second))); angle = math.acos(cosine); first_step = angle * 180.0 return first_step / _FIXED_PI def validate_fold(normal_a, normal_b, level): level = _integer(level, "fold level") - if level not in range(3): - _fail("fold level must be 0, 1, or 2") + if level not in range(3): _fail("fold level must be 0, 1, or 2") angle = fold_angle_degrees(normal_a, normal_b) - if not angle < _FIXED_FOLD_LIMITS[level]: - _fail(f"fold angle {angle!r} is not below {_FIXED_FOLD_LIMITS[level]!r}") + if not angle < _FIXED_FOLD_LIMITS[level]: _fail(f"fold angle {angle!r} is not below {_FIXED_FOLD_LIMITS[level]!r}") return angle -def _validate_junction_traces(raw): - raw = _named_mapping(raw, "junction traces", 7) - result = {} +def _validate_junction_inputs(raw): + raw = _named_mapping(raw, "junction inputs", 7); result = {} for name in sorted(raw, key=lambda value: value.encode("utf-8")): - pair = _sequence(raw[name], f"{name} trace pair") - if len(pair) != 2: - _fail(f"{name} requires two traces") - result[name] = tuple(_tagged_trace(value, f"{name}.{side}") - for side, value in zip(("A", "B"), pair)) + row = raw[name] + if type(row) is not dict or set(row) not in ({"incident_domains", "domain_vertex_tags"}, {"incident_domains", "domain_vertex_tags", "expected_domain_vertex_tags"}): _fail(f"{name} must contain exact junction derivation inputs") + result[name] = row return result def _face_owners(raw, face_count): owners = _sequence(raw, "face_owners", _MAX_QUADS) - if len(owners) != face_count or any(type(owner) is not str or not owner for owner in owners): - _fail("face_owners must contain one non-empty string per face") + if len(owners) != face_count or any(type(owner) is not str or not owner for owner in owners): _fail("face_owners must contain one non-empty string per face") return owners def _boundary_normals(loops, incidence, quad_normals): result = {} for name, loop in loops.items(): normals = [] for slot, start in enumerate(loop): - end = loop[(slot + 1) % len(loop)] - uses = incidence.get((min(start, end), max(start, end)), ()) - if len(uses) != 1: - _fail(f"{name} boundary edge is not uniquely derived") + end = loop[(slot + 1) % len(loop)]; uses = incidence.get((min(start, end), max(start, end)), ()) + if len(uses) != 1: _fail(f"{name} boundary edge is not uniquely derived") normals.append(quad_normals[uses[0][0]]) result[name] = tuple(normals) return result @@ -398,142 +326,93 @@ def _run_fold_gates(incidence, owners, quad_normals, level): count = 0 for uses in incidence.values(): if len(uses) == 2 and owners[uses[0][0]] != owners[uses[1][0]]: - validate_fold(quad_normals[uses[0][0]], quad_normals[uses[1][0]], level) - count += 1 + validate_fold(quad_normals[uses[0][0]], quad_normals[uses[1][0]], level); count += 1 return count def _aabb(points, triangle): corners = tuple(points[index] for index in triangle) - return (tuple(min(point[i] for point in corners) for i in range(3)) - + tuple(max(point[i] for point in corners) for i in range(3))) + return tuple(min(point[i] for point in corners) for i in range(3)) + tuple(max(point[i] for point in corners) for i in range(3)) def _shared_edge_direction(triangle, shared): shared = set(shared) for i, start in enumerate(triangle): end = triangle[(i + 1) % 3] - if {start, end} == shared: - return start, end + if {start, end} == shared: return start, end _fail("shared edge is absent") def _axis_list(first, second): - edges_a = tuple(_sub_vec(first[(i + 1) % 3], first[i]) for i in range(3)) - edges_b = tuple(_sub_vec(second[(i + 1) % 3], second[i]) for i in range(3)) - normal_a = _cross_vec(_sub_vec(first[1], first[0]), _sub_vec(first[2], first[0])) - normal_b = _cross_vec(_sub_vec(second[1], second[0]), _sub_vec(second[2], second[0])) - return ((normal_a, normal_b) - + tuple(_cross_vec(a, b) for a in edges_a for b in edges_b) - + tuple(_cross_vec(normal_a, edge) for edge in edges_a) - + tuple(_cross_vec(normal_b, edge) for edge in edges_b)) + edges_a = tuple(_sub_vec(first[(i + 1) % 3], first[i]) for i in range(3)); edges_b = tuple(_sub_vec(second[(i + 1) % 3], second[i]) for i in range(3)) + normal_a = _cross_vec(_sub_vec(first[1], first[0]), _sub_vec(first[2], first[0])); normal_b = _cross_vec(_sub_vec(second[1], second[0]), _sub_vec(second[2], second[0])) + return (normal_a, normal_b) + tuple(_cross_vec(a, b) for a in edges_a for b in edges_b) + tuple(_cross_vec(normal_a, edge) for edge in edges_a) + tuple(_cross_vec(normal_b, edge) for edge in edges_b) def _sat_disjoint(first, second): for axis in _axis_list(first, second): length = _norm_vec(axis) - if not math.isfinite(length): - _fail("SAT axis must be finite") - if length <= _FIXED_D: - continue - unit = _normalize_vec(axis, "SAT axis") - projections = tuple(_dot_vec(point, unit) for point in first + second) - if not all(math.isfinite(value) for value in projections): - _fail("SAT projections must be finite") - if _interval_disjoint(min(projections[:3]), max(projections[:3]), - min(projections[3:]), max(projections[3:])): - return True + if not math.isfinite(length): _fail("SAT axis must be finite") + if length <= _FIXED_D: continue + unit = _normalize_vec(axis, "SAT axis"); projections = tuple(_dot_vec(point, unit) for point in first + second) + if not all(math.isfinite(value) for value in projections): _fail("SAT projections must be finite") + if _interval_disjoint(min(projections[:3]), max(projections[:3]), min(projections[3:]), max(projections[3:])): return True return False def _rational(value): return Fraction(0, 1) if value == 0.0 else Fraction(*value.as_integer_ratio()) def _ray_difference(first, second): return tuple(_rational(first[i]) - _rational(second[i]) for i in range(3)) def _active_solution(rays, subset): - matrix = [[rays[index][row] for index in subset] + [Fraction(0, 1)] - for row in range(3)] + matrix = [[rays[index][row] for index in subset] + [Fraction(0, 1)] for row in range(3)] matrix.append([Fraction(1, 1) for _ in subset] + [Fraction(1, 1)]) for pivot_row, column in enumerate(range(len(subset))): pivot = next((row for row in range(pivot_row, 4) if matrix[row][column]), None) - if pivot is None: - return None - matrix[pivot_row], matrix[pivot] = matrix[pivot], matrix[pivot_row] - divisor = matrix[pivot_row][column] - matrix[pivot_row] = [value / divisor for value in matrix[pivot_row]] + if pivot is None: return None + matrix[pivot_row], matrix[pivot] = matrix[pivot], matrix[pivot_row]; divisor = matrix[pivot_row][column]; matrix[pivot_row] = [value / divisor for value in matrix[pivot_row]] for row in range(4): if row != pivot_row and matrix[row][column]: - factor = matrix[row][column] - matrix[row] = [left - factor * right - for left, right in zip(matrix[row], matrix[pivot_row])] - if any(not any(row[:-1]) and row[-1] for row in matrix): - return None + factor = matrix[row][column]; matrix[row] = [left - factor * right for left, right in zip(matrix[row], matrix[pivot_row])] + if any(not any(row[:-1]) and row[-1] for row in matrix): return None solution = [Fraction(0, 1)] * 4 - for row, column in enumerate(range(len(subset))): - solution[subset[column]] = matrix[row][-1] - if (any(value < 0 for value in solution) - or solution[0] + solution[1] <= 0 - or solution[2] + solution[3] <= 0): - return None + for row, column in enumerate(range(len(subset))): solution[subset[column]] = matrix[row][-1] + if any(value < 0 for value in solution) or solution[0] + solution[1] <= 0 or solution[2] + solution[3] <= 0: return None return tuple(solution) def shared_one_intersects(shared, a0, a1, b0, b1): - values = tuple(_vec(value, label) for value, label in ( - (shared, "shared point"), (a0, "A0"), (a1, "A1"), (b0, "B0"), (b1, "B1"))) + values = tuple(_vec(value, label) for value, label in ((shared, "shared point"), (a0, "A0"), (a1, "A1"), (b0, "B0"), (b1, "B1"))) shared, a0, a1, b0, b1 = values - rays = (_ray_difference(a0, shared), _ray_difference(a1, shared), - _ray_difference(shared, b0), _ray_difference(shared, b1)) - if any(not any(value for value in ray) for ray in rays): - _fail("shared-one classifier received a zero ray") - return any(_active_solution(rays, subset) is not None - for size in (2, 3, 4) - for subset in itertools.combinations(range(4), size)) + rays = (_ray_difference(a0, shared), _ray_difference(a1, shared), _ray_difference(shared, b0), _ray_difference(shared, b1)) + if any(not any(value for value in ray) for ray in rays): _fail("shared-one classifier received a zero ray") + return any(_active_solution(rays, subset) is not None for size in (2, 3, 4) for subset in itertools.combinations(range(4), size)) def classify_shared_one(shared, a0, a1, b0, b1): return "hit" if shared_one_intersects(shared, a0, a1, b0, b1) else "point-only" def _classify_shared_one_triangles(first, second, points): - shared = next(index for index in first if index in second) - a = [index for index in first if index != shared] - b = [index for index in second if index != shared] - return shared_one_intersects(points[shared], points[a[0]], points[a[1]], - points[b[0]], points[b[1]]) + shared = next(index for index in first if index in second); a = [index for index in first if index != shared]; b = [index for index in second if index != shared] + return shared_one_intersects(points[shared], points[a[0]], points[a[1]], points[b[0]], points[b[1]]) def _intersection_inputs(vertices, triangles): - points = _points(vertices) - faces = _indexed_rows(triangles, 3, len(points), "triangles", _MAX_TRIANGLES) - normalized, scale = _normalize_points(points) + points = _points(vertices); faces = _indexed_rows(triangles, 3, len(points), "triangles", _MAX_TRIANGLES); normalized, scale = _normalize_points(points) for index, face in enumerate(faces): length = _norm_vec(_triangle_normal(face, normalized)) - if not math.isfinite(length) or length <= _FIXED_D: - _fail(f"normalized triangle normal degeneracy at {index}") + if not math.isfinite(length) or length <= _FIXED_D: _fail(f"normalized triangle normal degeneracy at {index}") bounds = tuple(_aabb(normalized, face) for face in faces) return faces, normalized, scale, bounds, tuple(frozenset(face) for face in faces) def _aabb_disjoint(first, second): return any(_interval_disjoint(first[i], first[i + 3], second[i], second[i + 3]) for i in range(3)) def _pair_status(first_index, second_index, faces, normalized, bounds, face_sets): - pair = (first_index, second_index) - common = face_sets[first_index].intersection(face_sets[second_index]) - if len(common) == 3: - _fail(f"duplicate triangle pair {pair}") + pair = (first_index, second_index); common = face_sets[first_index].intersection(face_sets[second_index]) + if len(common) == 3: _fail(f"duplicate triangle pair {pair}") if len(common) == 2: - first_edge = _shared_edge_direction(faces[first_index], common) - second_edge = _shared_edge_direction(faces[second_index], common) - if first_edge != (second_edge[1], second_edge[0]): - _fail(f"shared-two edge direction conflict at pair {pair}") + first_edge = _shared_edge_direction(faces[first_index], common); second_edge = _shared_edge_direction(faces[second_index], common) + if first_edge != (second_edge[1], second_edge[0]): _fail(f"shared-two edge direction conflict at pair {pair}") return "excluded-adjacent" if len(common) == 1: - if normalized is None: - return "shared-one" - hit = _classify_shared_one_triangles(faces[first_index], faces[second_index], normalized) - return "hit" if hit else "point-only" + if normalized is None: return "shared-one" + return "hit" if _classify_shared_one_triangles(faces[first_index], faces[second_index], normalized) else "point-only" return "aabb-disjoint" if _aabb_disjoint(bounds[first_index], bounds[second_index]) else "candidate" def _record_pair_policy(triangle_count, first, second, ordinal, stage, class_counts): - expected_ordinal = (first * (2 * triangle_count - first - 1) // 2 - + second - first - 1) - if ordinal != expected_ordinal: - _fail("intersection pair coverage is not exhaustive reference order") - if stage not in _FINAL_CLASSIFICATION_STAGES: - _fail("intersection pair has an invalid classification") + expected_ordinal = first * (2 * triangle_count - first - 1) // 2 + second - first - 1 + if ordinal != expected_ordinal: _fail("intersection pair coverage is not exhaustive reference order") + if stage not in _FINAL_CLASSIFICATION_STAGES: _fail("intersection pair has an invalid classification") class_counts[stage] += 1 def _append_candidate(result, pair, cap): - if len(result) >= cap: - _fail(f"AABB candidate cap exceeded: >{cap}") + if len(result) >= cap: _fail(f"AABB candidate cap exceeded: >{cap}") result.append(pair) def _append_bounded(result, value): - if len(result) < _MAX_DIAGNOSTIC_EVIDENCE: - result.append(value) + if len(result) < _MAX_DIAGNOSTIC_EVIDENCE: result.append(value) def _collect_candidate_pairs(faces, bounds, face_sets, cap): cap = _integer(cap, "candidate cap") - if cap <= 0: - _fail("candidate cap must be a positive integer") + if cap <= 0: _fail("candidate cap must be a positive integer") result = [] for first in range(len(faces)): for second in range(first + 1, len(faces)): - if _pair_status(first, second, faces, None, bounds, face_sets) == "candidate": - _append_candidate(result, (first, second), cap) + if _pair_status(first, second, faces, None, bounds, face_sets) == "candidate": _append_candidate(result, (first, second), cap) return tuple(result) def _enumerate_fixture_candidates(vertices, triangles, cap): """Fixture-only cap injection. Production always uses the fixed cap.""" @@ -543,142 +422,134 @@ def enumerate_broad_phase_candidates(points, triangles): faces, _, _, bounds, face_sets = _intersection_inputs(points, triangles) return _collect_candidate_pairs(faces, bounds, face_sets, _MAX_CANDIDATES) def intersection_diagnostics(vertices, triangles, *, include_classifications=False): - if type(include_classifications) is not bool: - _fail("include_classifications must be a boolean") - faces, normalized, scale, bounds, face_sets = _intersection_inputs(vertices, triangles) - expected_pairs = len(faces) * (len(faces) - 1) // 2 - if include_classifications and expected_pairs > _MAX_CLASSIFICATION_DETAILS: - _fail(f"classification detail cap exceeded: {expected_pairs} > {_MAX_CLASSIFICATION_DETAILS}") - candidates, hits, nontrivial_evidence = [], [], [] - candidate_count = hit_count = 0 - first_pair = last_pair = first_hit_pair = None - classifications = [] if include_classifications else None - class_counts = {stage: 0 for stage in _FINAL_CLASSIFICATION_STAGES} - processed_pairs = 0 + if type(include_classifications) is not bool: _fail("include_classifications must be a boolean") + faces, normalized, scale, bounds, face_sets = _intersection_inputs(vertices, triangles); expected_pairs = len(faces) * (len(faces) - 1) // 2 + if include_classifications and expected_pairs > _MAX_CLASSIFICATION_DETAILS: _fail(f"classification detail cap exceeded: {expected_pairs} > {_MAX_CLASSIFICATION_DETAILS}") + candidates, hits, nontrivial_evidence = [], [], []; candidate_count = hit_count = 0; first_pair = last_pair = first_hit_pair = None + classifications = [] if include_classifications else None; class_counts = {stage: 0 for stage in _FINAL_CLASSIFICATION_STAGES}; processed_pairs = 0 for first, second in itertools.combinations(range(len(faces)), 2): - pair = (first, second) - stage = _pair_status(first, second, faces, normalized, bounds, face_sets) + pair = (first, second); stage = _pair_status(first, second, faces, normalized, bounds, face_sets) if stage == "candidate": candidate_count += 1 - if candidate_count > _MAX_CANDIDATES: - _fail(f"AABB candidate cap exceeded: >{_MAX_CANDIDATES}") - _append_bounded(candidates, pair) - first_points = tuple(normalized[index] for index in faces[first]) - second_points = tuple(normalized[index] for index in faces[second]) - stage = "hit" if not _sat_disjoint(first_points, second_points) else "sat-disjoint" - _record_pair_policy( - len(faces), first, second, processed_pairs, stage, class_counts) + if candidate_count > _MAX_CANDIDATES: _fail(f"AABB candidate cap exceeded: >{_MAX_CANDIDATES}") + _append_bounded(candidates, pair); first_points = tuple(normalized[index] for index in faces[first]); second_points = tuple(normalized[index] for index in faces[second]); stage = "hit" if not _sat_disjoint(first_points, second_points) else "sat-disjoint" + _record_pair_policy(len(faces), first, second, processed_pairs, stage, class_counts) if stage == "hit": hit_count += 1 - if first_hit_pair is None: - first_hit_pair = pair + if first_hit_pair is None: first_hit_pair = pair _append_bounded(hits, pair) - if stage != "aabb-disjoint": - _append_bounded(nontrivial_evidence, (pair, stage)) - if classifications is not None: - classifications.append((pair, stage)) - if first_pair is None: - first_pair = pair - last_pair = pair - processed_pairs += 1 - pair_policy_complete = ( - processed_pairs == expected_pairs - and first_pair == ((0, 1) if expected_pairs else None) - and last_pair == ((len(faces) - 2, len(faces) - 1) if expected_pairs else None) - and sum(class_counts.values()) == expected_pairs) - pair_policy_evidence = { - "expected_pair_count": expected_pairs, "processed_pair_count": processed_pairs, - "first_pair": first_pair, "last_pair": last_pair, - "class_counts": tuple((stage, class_counts[stage]) for stage in _FINAL_CLASSIFICATION_STAGES), - "nontrivial_pair_count": expected_pairs - class_counts["aabb-disjoint"], - "nontrivial_classifications": tuple(nontrivial_evidence), - "nontrivial_evidence_truncated": expected_pairs - class_counts["aabb-disjoint"] > len(nontrivial_evidence), - } - report = { - "triangle_count": len(faces), "normalization_scale": scale, - "pair_count": expected_pairs, - "broad_phase_candidate_count": candidate_count, "intersection_hit_count": hit_count, - "pair_policy_complete": pair_policy_complete, - "pair_policy_evidence": pair_policy_evidence, - "candidate_pairs": tuple(candidates), "hit_pairs": tuple(hits), - "candidate_pairs_truncated": candidate_count > len(candidates), - "hit_pairs_truncated": hit_count > len(hits), - "first_hit_pair": first_hit_pair, - } - if classifications is not None: - report["classifications"] = tuple(classifications) + if stage != "aabb-disjoint": _append_bounded(nontrivial_evidence, (pair, stage)) + if classifications is not None: classifications.append((pair, stage)) + if first_pair is None: first_pair = pair + last_pair = pair; processed_pairs += 1 + pair_policy_complete = processed_pairs == expected_pairs and first_pair == ((0, 1) if expected_pairs else None) and last_pair == ((len(faces) - 2, len(faces) - 1) if expected_pairs else None) and sum(class_counts.values()) == expected_pairs + pair_policy_evidence = {"expected_pair_count": expected_pairs, "processed_pair_count": processed_pairs, "first_pair": first_pair, "last_pair": last_pair, "class_counts": tuple((stage, class_counts[stage]) for stage in _FINAL_CLASSIFICATION_STAGES), "nontrivial_pair_count": expected_pairs - class_counts["aabb-disjoint"], "nontrivial_classifications": tuple(nontrivial_evidence), "nontrivial_evidence_truncated": expected_pairs - class_counts["aabb-disjoint"] > len(nontrivial_evidence)} + report = {"triangle_count": len(faces), "normalization_scale": scale, "pair_count": expected_pairs, "broad_phase_candidate_count": candidate_count, "intersection_hit_count": hit_count, "pair_policy_complete": pair_policy_complete, "pair_policy_evidence": pair_policy_evidence, "candidate_pairs": tuple(candidates), "hit_pairs": tuple(hits), "candidate_pairs_truncated": candidate_count > len(candidates), "hit_pairs_truncated": hit_count > len(hits), "first_hit_pair": first_hit_pair} + if classifications is not None: report["classifications"] = tuple(classifications) return report +_P0 = float.fromhex("0x0.0p+0"); _N0 = -_P0; _ONE = float.fromhex("0x1.0000000000000p+0"); _HALF = float.fromhex("0x1.0000000000000p-1"); _D50 = float.fromhex("0x1.0000000000000p-50"); _MIN_SUBNORMAL = float.fromhex("0x0.0000000000001p-1022") +_FIXTURE_SUFFIXES = ("p000", "p001", "p010", "p011", "p100", "p101", "p110", "p111") +_GENERAL_FIXTURE_IDS = ("shared0.clear-hit-origin", "shared0.clear-hit-translated", "shared0.sub-I0-contact-origin", "shared0.sub-I0-contact-translated", "shared0.aabb-disjoint", "shared0.sat-disjoint", "shared0.extreme-small-hit", "shared0.extreme-large-hit", "normal.boundary-D-reject", "normal.successor-D-accept", "shared2.opposite-edge-valid", "shared2.same-direction-reject", "shared3.duplicate-triangle-reject", "triangle-cap.boundary-4096", "triangle-cap.successor-4097", "candidate-cap.boundary-injected-3", "candidate-cap.successor-injected-3") +def _fixture_pair(a0, a1, b0, b1, shared=(_P0, _P0, _P0)): return ((shared, a0, a1), (shared, b0, b1)) +def _transform_fixture(pair, scale, translation): return tuple(tuple(tuple(float(float(scale * value) + offset) for value, offset in zip(point, translation)) for point in triangle) for triangle in pair) +def _negative_zero_fixture(pair): return tuple(tuple(tuple(math.copysign(0.0, -1.0) if value == 0.0 else value for value in point) for point in triangle) for triangle in pair) +_A0, _A1 = (_ONE, _P0, _P0), (_P0, _ONE, _P0) +_SHARED_ONE_FIXTURES = ( ("shared1.offset-d50-point-only", _fixture_pair(_A0, _A1, (_ONE, _P0, _D50), (_P0, _ONE, _D50)), "point-only"), ("shared1.coplanar-duplicate-hit", _fixture_pair(_A0, _A1, _A0, _A1), "hit"), ("shared1.offset-positive-minsub-point-only", _fixture_pair(_A0, _A1, (_ONE, _P0, _MIN_SUBNORMAL), (_P0, _ONE, _MIN_SUBNORMAL)), "point-only"), ("shared1.offset-negative-minsub-point-only", _fixture_pair(_A0, _A1, (_ONE, _P0, -_MIN_SUBNORMAL), (_P0, _ONE, -_MIN_SUBNORMAL)), "point-only"), ("shared1.coplanar-disjoint-fans", _fixture_pair(_A0, _A1, (-_ONE, _P0, _P0), (_P0, -_ONE, _P0)), "point-only"), ("shared1.ray-cone-hit", _fixture_pair(_A0, _A1, (_ONE, _ONE, _P0), (_P0, _P0, _ONE)), "hit"), ("shared1.near-coplanar-full-rank-hit", _fixture_pair(_A0, _A1, (_ONE, _P0, _D50), (_P0, _ONE, -_D50)), "hit"), ("shared1.transformed-point-only", _transform_fixture(_fixture_pair(_A0, _A1, (_ONE, _P0, _D50), (_P0, _ONE, _D50)), 8.0, (4.0, -2.0, 1.0)), "point-only"), ("shared1.transformed-hit", _transform_fixture(_fixture_pair(_A0, _A1, (_ONE, _P0, _D50), (_P0, _ONE, -_D50)), 8.0, (4.0, -2.0, 1.0)), "hit"), ("shared1.negative-zero-hit", _negative_zero_fixture(_fixture_pair(_A0, _A1, _A0, _A1)), "hit"), ("shared1.level2-ply-point-only", _fixture_pair((float.fromhex("0x1.37918e2798bb6p-8"), float.fromhex("0x1.61bcdab8dcc06p-4"), float.fromhex("0x1.43c9e5ce2aeb6p-4")), (float.fromhex("0x1.7bc42ac7f04b0p-7"), float.fromhex("0x1.6cae8c4686bb2p-4"), float.fromhex("0x1.0be935f6a339ep-4")), (float.fromhex("0x1.7888e87a16156p-6"), float.fromhex("0x1.7eec0987f75cdp-4"), float.fromhex("0x1.d5d88ce274e30p-5")), (float.fromhex("0x1.8b59f7e4bf4dfp-6"), float.fromhex("0x1.18982604f83a1p-4"), float.fromhex("0x1.07df2315527a3p-4")), (float.fromhex("0x1.8b59f7e4bf4dfp-7"), float.fromhex("0x1.0a35e0636f7c1p-4"), float.fromhex("0x1.264d28c7c3da4p-4"))), "point-only"), ) +INTERSECTION_FIXTURE_IDS = tuple(f"{name}.{suffix}" for name, _, _ in _SHARED_ONE_FIXTURES for suffix in _FIXTURE_SUFFIXES) + _GENERAL_FIXTURE_IDS +_CLEAR_PAIR = (((-_ONE, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0)), ((_P0, -_ONE, _P0), (_HALF, _HALF, _P0), (-_HALF, _HALF, _P0))) +_SUB_I0_PAIR = (((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0)), ((_P0, _P0, float.fromhex("0x1.0000000000000p-34")), (_ONE, _P0, float.fromhex("0x1.0000000000000p-34")), (_P0, _ONE, float.fromhex("0x1.0000000000000p-34")))) +_SHARED_ZERO_FIXTURES = ( (_GENERAL_FIXTURE_IDS[0], _CLEAR_PAIR, "hit"), (_GENERAL_FIXTURE_IDS[1], _transform_fixture(_CLEAR_PAIR, _ONE, (4.0, -2.0, 1.0)), "hit"), (_GENERAL_FIXTURE_IDS[2], _SUB_I0_PAIR, "hit"), (_GENERAL_FIXTURE_IDS[3], _transform_fixture(_SUB_I0_PAIR, _ONE, (4.0, -2.0, 1.0)), "hit"), (_GENERAL_FIXTURE_IDS[4], (((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0)), ((_P0, _P0, _ONE), (_ONE, _P0, _ONE), (_P0, _ONE, _ONE))), "aabb-disjoint"), (_GENERAL_FIXTURE_IDS[5], (((_P0, _P0, _P0), (2.0, _P0, _P0), (_P0, 2.0, _P0)), ((2.0, 2.0, _P0), (2.0, 1.5, _P0), (1.5, 2.0, _P0))), "sat-disjoint"), (_GENERAL_FIXTURE_IDS[6], _transform_fixture(_CLEAR_PAIR, float.fromhex("0x1.0000000000000p-500"), (_P0, _P0, _P0)), "hit"), (_GENERAL_FIXTURE_IDS[7], _transform_fixture(_CLEAR_PAIR, float.fromhex("0x1.0000000000000p+500"), (_P0, _P0, _P0)), "hit"), ) +def _fixture_failure(fixture_id, message, function, *args): + try: function(*args) + except MeshCorrectnessError as exc: + if message not in str(exc): _fail(f"{fixture_id} failed at the wrong stage: {exc}") + else: _fail(f"{fixture_id} did not fail") + return {"fixture_id": fixture_id, "outcome": "hard-failure"} +def _fixture_pair_result(fixture_id, pair, expected): + report = intersection_diagnostics(pair[0] + pair[1], ((0, 1, 2), (3, 4, 5)), include_classifications=True) + actual = report["classifications"][0][1] + if not report["pair_policy_complete"] or report["pair_count"] != 1 or actual != expected or report["intersection_hit_count"] != (expected == "hit"): _fail(f"{fixture_id} changed: {actual!r}") + return {"fixture_id": fixture_id, "outcome": actual} +def run_production_intersection_fixtures(): + expected_thresholds = tuple({"threshold_id": f"threshold.intersection.L{level}.broad_phase_candidate_count", "relation": "le", "lower": None, "upper": 1_000_000, "unit": "count"} for level in range(3)) + if _MAX_CANDIDATES != 1_000_000 or intersection_candidate_threshold_records() != expected_thresholds: _fail("intersection production cap or thresholds changed") + result = [] + for base_name, pair, expected in _SHARED_ONE_FIXTURES: + points = pair[0] + pair[1][1:] + for suffix in _FIXTURE_SUFFIXES: + first, second = [0, 1, 2], [0, 3, 4] + if suffix[1] == "1": first, second = second, first + if suffix[2] == "1": first[1], first[2] = first[2], first[1] + if suffix[3] == "1": second[1], second[2] = second[2], second[1] + actual = "hit" if _classify_shared_one_triangles(first, second, points) else "point-only"; fixture_id = f"{base_name}.{suffix}" + if actual != expected: _fail(f"{fixture_id} changed: {actual!r}") + result.append({"fixture_id": fixture_id, "outcome": actual}) + result.extend(_fixture_pair_result(*fixture) for fixture in _SHARED_ZERO_FIXTURES) + normal_points = ((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _FIXED_D, _P0)); one_triangle = ((0, 1, 2),) + result.append(_fixture_failure(_GENERAL_FIXTURE_IDS[8], "normalized triangle normal", intersection_diagnostics, normal_points, one_triangle)) + admitted = intersection_diagnostics((normal_points[0], normal_points[1], (_P0, float.fromhex("0x1.0000000000000p-45"), _P0)), one_triangle) + if (admitted["triangle_count"], admitted["pair_count"], admitted["intersection_hit_count"]) != (1, 0, 0): _fail(f"{_GENERAL_FIXTURE_IDS[9]} changed") + result.append({"fixture_id": _GENERAL_FIXTURE_IDS[9], "outcome": "pass"}) + shared2_points = ((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0), (_P0, -_ONE, _P0)) + valid_shared2 = intersection_diagnostics(shared2_points, ((0, 1, 2), (1, 0, 3)), include_classifications=True) + if valid_shared2["classifications"] != (((0, 1), "excluded-adjacent"),): _fail(f"{_GENERAL_FIXTURE_IDS[10]} changed") + result.append({"fixture_id": _GENERAL_FIXTURE_IDS[10], "outcome": "excluded-adjacent"}) + result.append(_fixture_failure(_GENERAL_FIXTURE_IDS[11], "shared-two", intersection_diagnostics, shared2_points, ((0, 1, 2), (0, 1, 3)))) + result.append(_fixture_failure(_GENERAL_FIXTURE_IDS[12], "duplicate triangle", intersection_diagnostics, normal_points[:2] + ((_P0, _ONE, _P0),), ((0, 1, 2), (0, 1, 2)))) + cap_points, cap_triangles = [], [] + for row in range(_MAX_TRIANGLES): + offset = 3 * row; x = float(4 * row); cap_points.extend(((x, _P0, _P0), (float(x + _ONE), _P0, _P0), (x, _ONE, _P0))); cap_triangles.append((offset, offset + 1, offset + 2)) + cap_report = intersection_diagnostics(tuple(cap_points), tuple(cap_triangles)); pair_count = _MAX_TRIANGLES * (_MAX_TRIANGLES - 1) // 2; evidence = cap_report["pair_policy_evidence"] + cap_actual = (cap_report["triangle_count"], cap_report["pair_count"], cap_report["broad_phase_candidate_count"], cap_report["intersection_hit_count"], cap_report["pair_policy_complete"], cap_report["candidate_pairs"], cap_report["hit_pairs"], cap_report["candidate_pairs_truncated"], cap_report["hit_pairs_truncated"], cap_report["first_hit_pair"], "classifications" in cap_report, evidence["expected_pair_count"], evidence["processed_pair_count"], evidence["first_pair"], evidence["last_pair"], evidence["class_counts"], evidence["nontrivial_pair_count"], evidence["nontrivial_classifications"], evidence["nontrivial_evidence_truncated"]) + cap_expected = (_MAX_TRIANGLES, pair_count, 0, 0, True, (), (), False, False, None, False, pair_count, pair_count, (0, 1), (4094, 4095), (("aabb-disjoint", pair_count), ("sat-disjoint", 0), ("hit", 0), ("point-only", 0), ("excluded-adjacent", 0)), 0, (), False) + if cap_actual != cap_expected: _fail(f"{_GENERAL_FIXTURE_IDS[13]} changed") + result.append({"fixture_id": _GENERAL_FIXTURE_IDS[13], "outcome": "pass"}) + overflow_points = tuple(cap_points) + ((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0)); overflow_triangles = tuple(cap_triangles) + ((12288, 12289, 12290),) + result.append(_fixture_failure(_GENERAL_FIXTURE_IDS[14], "triangle cap", intersection_diagnostics, overflow_points, overflow_triangles)) + candidate_points = tuple(point for _ in range(3) for point in ((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0))); candidate_triangles = tuple((3 * row, 3 * row + 1, 3 * row + 2) for row in range(3)); expected_pairs = ((0, 1), (0, 2), (1, 2)) + candidate_report = intersection_diagnostics(candidate_points, candidate_triangles, include_classifications=True) + if (_enumerate_fixture_candidates(candidate_points, candidate_triangles, 3), candidate_report["pair_count"], candidate_report["candidate_pairs"], candidate_report["hit_pairs"], candidate_report["intersection_hit_count"], candidate_report["first_hit_pair"], candidate_report["candidate_pairs_truncated"], candidate_report["hit_pairs_truncated"], candidate_report["classifications"]) != (expected_pairs, 3, expected_pairs, expected_pairs, 3, (0, 1), False, False, (((0, 1), "hit"), ((0, 2), "hit"), ((1, 2), "hit"))): _fail(f"{_GENERAL_FIXTURE_IDS[15]} changed") + result.append({"fixture_id": _GENERAL_FIXTURE_IDS[15], "outcome": "hit"}) + candidate_points += ((_P0, _P0, _P0), (_ONE, _P0, _P0), (_P0, _ONE, _P0)); candidate_triangles += ((9, 10, 11),) + result.append(_fixture_failure(_GENERAL_FIXTURE_IDS[16], "candidate cap", _enumerate_fixture_candidates, candidate_points, candidate_triangles, 3)) + if len(result) != 105 or tuple(row["fixture_id"] for row in result) != INTERSECTION_FIXTURE_IDS: _fail("intersection fixture execution order or count changed") + return tuple(result) -def validate_geometry(vertices, quads, level, boundary_loops, port_directions, - expected_faces, junction_traces, face_owners): +def validate_geometry(vertices, quads, level, boundary_loops, port_directions, expected_base_faces, junction_inputs, face_owners): level = _integer(level, "level") - if level not in _STRUCTURAL_FLOORS: - _fail("level must be 0, 1, or 2") - if any(value is None for value in ( - boundary_loops, port_directions, expected_faces, junction_traces, face_owners)): - _fail("all production geometry selectors and gate data are required") - points = _points(vertices) - faces = _quads(quads, len(points)) - if level == 0 and len(points) > _MAX_BASE_CONTROLS: - _fail(f"level 0 base control cap exceeded: {len(points)} > {_MAX_BASE_CONTROLS}") - if level == 0 and len(faces) > _MAX_BASE_QUADS: - _fail(f"level 0 base quad cap exceeded: {len(faces)} > {_MAX_BASE_QUADS}") + if level not in _STRUCTURAL_FLOORS: _fail("level must be 0, 1, or 2") + if any(value is None for value in (boundary_loops, port_directions, expected_base_faces, junction_inputs, face_owners)): _fail("all production geometry selectors and gate data are required") + points = _points(vertices); faces = _quads(quads, len(points)) + if level == 0 and len(points) > _MAX_BASE_CONTROLS: _fail(f"level 0 base control cap exceeded: {len(points)} > {_MAX_BASE_CONTROLS}") + if level == 0 and len(faces) > _MAX_BASE_QUADS: _fail(f"level 0 base quad cap exceeded: {len(faces)} > {_MAX_BASE_QUADS}") loops = _validate_loops(boundary_loops, len(points)) - if len(loops) != 5: - _fail("exactly 5 boundary loops are required") - topology = _topology_report(len(points), faces, loops, expected_faces) - owners = _face_owners(face_owners, len(faces)) - incidence = _edge_incidence(faces) + if len(loops) != 5: _fail("exactly 5 boundary loops are required") + topology = _topology_report(len(points), faces, loops, _expected_face_catalogs(expected_base_faces)[level]); owners = _face_owners(face_owners, len(faces)); incidence = _edge_incidence(faces) edge_lengths = tuple(_norm_vec(_sub_vec(points[b], points[a])) for a, b in incidence) - triangles = tuple((face[0], face[1], face[2]) for face in faces) + tuple( - (face[0], face[2], face[3]) for face in faces) - triangle_areas = tuple(0.5 * _norm_vec(_triangle_normal(face, points)) - for face in triangles) - quad_data = tuple(_quad_data(face, points) for face in faces) - quad_areas = tuple(value[0] for value in quad_data) - if any(not math.isfinite(value) for value in edge_lengths + triangle_areas + quad_areas): - _fail("structural metrics must be finite") + triangles = tuple((face[0], face[1], face[2]) for face in faces) + tuple((face[0], face[2], face[3]) for face in faces) + triangle_areas = tuple(0.5 * _norm_vec(_triangle_normal(face, points)) for face in triangles); quad_data = tuple(_quad_data(face, points) for face in faces); quad_areas = tuple(value[0] for value in quad_data) + if any(not math.isfinite(value) for value in edge_lengths + triangle_areas + quad_areas): _fail("structural metrics must be finite") floor = _STRUCTURAL_FLOORS[level] - if (min(edge_lengths) < floor["edge_length"] - or min(triangle_areas) < floor["triangle_area"] - or min(quad_areas) < floor["quad_area"]): - _fail("structural floor failed") - intersection = intersection_diagnostics(points, triangles) - hit_count = intersection["intersection_hit_count"] - if hit_count: - _fail(f"{hit_count} triangle intersections, " - f"first pair {intersection['first_hit_pair']}") + if min(edge_lengths) < floor["edge_length"] or min(triangle_areas) < floor["triangle_area"] or min(quad_areas) < floor["quad_area"]: _fail("structural floor failed") + intersection = intersection_diagnostics(points, triangles); hit_count = intersection["intersection_hit_count"] + if hit_count: _fail(f"{hit_count} triangle intersections, first pair {intersection['first_hit_pair']}") port_directions = _named_mapping(port_directions, "port directions", 5) - if set(port_directions) != set(loops): - _fail("port directions must match boundary loops") - quad_normals = tuple(value[1] for value in quad_data) - normals = _boundary_normals(loops, incidence, quad_normals) - port_metrics = {} - for name in sorted(loops, key=lambda value: value.encode("utf-8")): - port_metrics[name] = validate_port_loop( - points, loops[name], port_directions[name], normals[name]) + if set(port_directions) != set(loops): _fail("port directions must match boundary loops") + quad_normals = tuple(value[1] for value in quad_data); normals = _boundary_normals(loops, incidence, quad_normals) + port_metrics = {name: validate_port_loop(points, loops[name], port_directions[name], normals[name]) for name in sorted(loops, key=lambda value: value.encode("utf-8"))} + junctions = _validate_junction_inputs(junction_inputs) + residuals = tuple((name, _junction_continuity_metrics(points, faces, owners, row["incident_domains"], row["domain_vertex_tags"], row.get("expected_domain_vertex_tags"))["coordinate_residual"]) for name, row in junctions.items()) fold_count = _run_fold_gates(incidence, owners, quad_normals, level) - traces = _validate_junction_traces(junction_traces) - residuals = [] - for name in traces: - metrics = junction_continuity_metrics(*traces[name]) - residuals.append((name, metrics["coordinate_residual"])) - return { - "topology": topology, "edge_length_min": min(edge_lengths), - "triangle_area_min": min(triangle_areas), "quad_area_min": min(quad_areas), - "intersection_hit_count": 0, "port_count": len(loops), - "port_metrics": port_metrics, "fold_count": fold_count, - "junction_count": len(traces), "junction_residuals": tuple(residuals), - } + return {"topology": topology, "edge_length_min": min(edge_lengths), "triangle_area_min": min(triangle_areas), "quad_area_min": min(quad_areas), "intersection_hit_count": 0, "port_count": len(loops), "port_metrics": port_metrics, "fold_count": fold_count, "junction_count": len(junctions), "junction_residuals": residuals} def intersection_candidate_threshold_records(): return tuple(dict(record) for record in _THRESHOLD_RECORDS) -__all__ = [ - "DEGENERACY_FLOOR", "FOLD_LIMITS_DEGREES", "I0", "INTERSECTION_TOLERANCE", - "MAX_CANDIDATES", "MAX_TRIANGLES", "PI", "STRUCTURAL_FLOORS", "D", - "MeshCorrectnessError", "S", "T", "TopologyReport", "add", - "classify_shared_one", "cross", "dot", "enumerate_broad_phase_candidates", - "fold_angle_degrees", "intersection_candidate_threshold_records", - "intersection_diagnostics", "interval_disjoint", "junction_continuity_metrics", - "norm", "normalize", "port_loop_metrics", "shared_one_intersects", "sub", - "validate_fold", "validate_geometry", "validate_port_loop", "validate_topology", -] +def _normalize_public(function): + @wraps(function) + def checked(*args, **kwargs): + try: return function(*args, **kwargs) + except MeshCorrectnessError: raise + except Exception as exc: raise MeshCorrectnessError(f"{function.__name__} rejected malformed public input") from exc + return checked +_PUBLIC_FUNCTIONS = ("add", "classify_ownership_records", "classify_shared_one", "cross", "derive_expected_face_catalogs", "dot", "enumerate_broad_phase_candidates", "fold_angle_degrees", "intersection_candidate_threshold_records", "intersection_diagnostics", "interval_disjoint", "junction_continuity_metrics", "norm", "normalize", "port_loop_metrics", "quad_normal", "run_production_intersection_fixtures", "shared_one_intersects", "sub", "validate_fold", "validate_geometry", "validate_port_loop", "validate_topology") +for _public_name in _PUBLIC_FUNCTIONS: globals()[_public_name] = _normalize_public(globals()[_public_name]) +__all__ = ["DEGENERACY_FLOOR", "FOLD_LIMITS_DEGREES", "I0", "INTERSECTION_FIXTURE_IDS", "INTERSECTION_TOLERANCE", "MAX_CANDIDATES", "MAX_TRIANGLES", "PI", "STRUCTURAL_FLOORS", "D", "MeshCorrectnessError", "S", "T", "TopologyReport", "add", "classify_ownership_records", "classify_shared_one", "cross", "derive_expected_face_catalogs", "dot", "enumerate_broad_phase_candidates", "fold_angle_degrees", "intersection_candidate_threshold_records", "intersection_diagnostics", "interval_disjoint", "junction_continuity_metrics", "norm", "normalize", "port_loop_metrics", "quad_normal", "run_production_intersection_fixtures", "shared_one_intersects", "sub", "validate_fold", "validate_geometry", "validate_port_loop", "validate_topology"] diff --git a/experiments/owned-root-assembly-successor/owned_root_launcher.sh b/experiments/owned-root-assembly-successor/owned_root_launcher.sh new file mode 100755 index 0000000..c35edc4 --- /dev/null +++ b/experiments/owned-root-assembly-successor/owned_root_launcher.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail +EXPECTED_CONTRACT_SHA256="3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" EXPECTED_SOURCE_SHA256="82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" EXPECTED_PROFILE_SHA256="a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +SCRIPT_DIR="$(CDPATH='' cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +PACKAGE_DIR="$SCRIPT_DIR"; REPO_ROOT="$(CDPATH='' cd -P -- "$PACKAGE_DIR/../.." && pwd)" +CURRENT_LAUNCHER="$REPO_ROOT/experiments/current-form-surface-preview/surface_preview_launcher.sh"; CONTRACT="$PACKAGE_DIR/design-contract.md"; SIDECAR="$PACKAGE_DIR/design-contract.sha256" +SOURCE="$REPO_ROOT/examples/body-documents/stylized-digitigrade-biped-authored-form.json"; PROFILE="$REPO_ROOT/experiments/current-form-surface-preview/structural_profile_candidates.json"; REQUIREMENTS="$REPO_ROOT/experiments/current-form-surface-preview/requirements.txt"; BUILDER_ROLE="experiments/owned-root-assembly-successor/build_owned_root.py"; COMPARATOR_ROLE="experiments/owned-root-assembly-successor/compare_two_seed_outputs.py" +OUTPUT=""; STAGING="" +error() { printf 'owned-root-launcher: error: %s\n' "$*">&2; exit 1; } +cleanup() { [[ -n "$STAGING" && -d "$STAGING" && ! -L "$STAGING" ]] || return 0; rm -rf -- "$STAGING"; } +finish() { local status=$?; trap - EXIT; cleanup || status=1; (( status == 0 )) || exit 1; } +trap finish EXIT; trap 'exit 1' HUP INT TERM +[[ "${PYTHONHASHSEED-}" == 0 ]] || error "public invocation requires literal PYTHONHASHSEED=0" +[[ $# == 2 && $1 == --output ]] || error "usage: PYTHONHASHSEED=0 owned_root_launcher.sh --output ABSENT_PATH" +OUTPUT="$2"; [[ "$OUTPUT" == /* && "$(realpath -m -- "$OUTPUT")" == "$OUTPUT" ]] || error "--output requires a canonical absolute path" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || error "--output must name an absent path"; OUTPUT_PARENT="$(dirname -- "$OUTPUT")" +[[ -d "$OUTPUT_PARENT" && -w "$OUTPUT_PARENT" ]] || error "output parent must be an existing writable directory" +case "$(df -P -T -- "$OUTPUT_PARENT" 2>/dev/null | awk 'NR == 2 { print $2; exit }')" in ""|9p|drvfs|fuseblk|cifs|smb|smb2|smb3|ntfs|ntfs3|vfat|exfat|fat|fat32) error "output parent must be native Linux storage";; esac +for fixed in "$CONTRACT" "$SIDECAR" "$SOURCE" "$PROFILE" "$REQUIREMENTS" "$CURRENT_LAUNCHER"; do [[ -f "$fixed" && ! -L "$fixed" ]] || error "fixed path is not a regular non-symlink file: $fixed"; done +sha256sum -- "$CONTRACT" | awk -v expected="$EXPECTED_CONTRACT_SHA256" '$1 != expected { exit 1 }' || error "design-contract SHA-256 mismatch" +cmp -s <(printf '%s experiments/owned-root-assembly-successor/design-contract.md\n' "$EXPECTED_CONTRACT_SHA256") "$SIDECAR" || error "design-contract sidecar mismatch" +sha256sum -- "$SOURCE" | awk -v expected="$EXPECTED_SOURCE_SHA256" '$1 != expected { exit 1 }' || error "source SHA-256 mismatch" +sha256sum -- "$PROFILE" | awk -v expected="$EXPECTED_PROFILE_SHA256" '$1 != expected { exit 1 }' || error "profile-table SHA-256 mismatch" +cmp -s <(printf 'numpy==2.2.6\nscikit-image==0.25.2\nPillow==11.1.0\n') "$REQUIREMENTS" || error "requirements are not the exact pinned file" +PYTHONHASHSEED=0 "$CURRENT_LAUNCHER" - <<'PY' +import importlib, importlib.metadata, importlib.util, platform, sys +if (platform.python_implementation(), platform.python_version(), platform.system(), getattr(sys.implementation, "cache_tag", None)) != ("CPython", "3.10.12", "Linux", "cpython-310"): raise SystemExit("owned-root-launcher: runtime is not the pinned CPython 3.10.12 Linux form") +for name, expected in (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")): + if importlib.metadata.version(name) != expected: raise SystemExit(f"owned-root-launcher: runtime distribution drift: {name}") +if not all((getattr(module := importlib.import_module(name), "__file__", None) is None and (spec := importlib.util.find_spec(name)) is not None and spec.origin == "built-in") for name in ("math", "zlib")): raise SystemExit("owned-root-launcher: built-in module admission failed") +PY +IMPLEMENTATION_FILES=(build_owned_root.py prepared_projection.py owned_root_surface.py mesh_correctness.py render_export.py owned_root_launcher.sh compare_two_seed_outputs.py artifact_serialization.py anatomy_gates.py chart_lineage.py tests/test_build_owned_root.py tests/test_prepared_projection.py tests/test_owned_root_surface.py tests/test_mesh_correctness.py tests/test_render_export.py); expected="$(printf 'f %s\n' "${IMPLEMENTATION_FILES[@]}" | LC_ALL=C sort)"; actual="$(find -P "$PACKAGE_DIR" \( -name '*.py' -o -name '*.sh' \) -printf '%y %P\n' | LC_ALL=C sort)" +[[ "$actual" == "$expected" ]] || error "package implementation source does not match the exact 15-file allowlist" +for relative in "${IMPLEMENTATION_FILES[@]}"; do path="$PACKAGE_DIR/$relative"; [[ -f "$path" && ! -L "$path" ]] || error "required implementation file is missing or not regular: $relative"; (( $(stat -c '%s' -- "$path") <= 4000000 )) || error "implementation file exceeds 4,000,000 bytes: $relative"; done +cd -- "$REPO_ROOT"; token="$(if [[ -r /proc/sys/kernel/random/uuid ]]; then tr -d '-' 0 else -1.0) + derivative = _rational(coefficient) * value.derivative; return _Dual(0.0 if magnitude == 0.0 else (-magnitude if value.value < 0 else magnitude), derivative) + magnitude = pow(abs(value), exponent); return 0.0 if magnitude == 0.0 else (-magnitude if value < 0.0 else magnitude) +def _lerp(a, b, t): return _add(_mul(_sub(1.0, t), a), _mul(t, b)) +def _vadd(a, b): return tuple(_add(x, y) for x, y in zip(a, b)) +def _vlerp(a, b, t): return tuple(_lerp(x, y, t) for x, y in zip(a, b)) +def _e(center, u, q, r_l, r_a, r_p, n): + exponent = _div(2.0, n); return (_add(center[0], _mul(r_l, _sp(u, exponent))), center[1], _add(center[2], _mul(r_a if q >= 0.0 else r_p, _sp(q, exponent)))) +def _cell_inventory(): + rows = {"domain.pelvis": [(i, 0) for i in range(5)], "domain.abdomen": [(i, j) for i in range(1, 4) for j in (1, 2)], "domain.thorax": [(i, j) for i in range(1, 4) for j in (3, 4, 5)], "domain.neck": [(2, 6)], "domain.left_shoulder": [(0, 4), (0, 5)], "domain.right_shoulder": [(4, 4), (4, 5)], "domain.left_hip": [(i, -1) for i in (0, 1)], "domain.right_hip": [(i, -1) for i in (3, 4)]} + return tuple((domain, i, j, k) for domain in DOMAINS for i, j in rows[domain] for k in (0, 1)) +CELL_CATALOG = _cell_inventory() +def _cube_faces(i, j, k): + return ((-1, ((i, j, k), (i, j, k + 1), (i, j + 1, k + 1), (i, j + 1, k))), (1, ((i + 1, j, k), (i + 1, j + 1, k), (i + 1, j + 1, k + 1), (i + 1, j, k + 1))), (-2, ((i, j, k), (i + 1, j, k), (i + 1, j, k + 1), (i, j, k + 1))), (2, ((i, j + 1, k), (i, j + 1, k + 1), (i + 1, j + 1, k + 1), (i + 1, j + 1, k))), (-3, ((i, j, k), (i, j + 1, k), (i + 1, j + 1, k), (i + 1, j, k))), (3, ((i, j, k + 1), (i + 1, j, k + 1), (i + 1, j + 1, k + 1), (i, j + 1, k + 1)))) +def _generated_faces(): + uses = defaultdict(list) + for domain, i, j, k in CELL_CATALOG: + for direction, cycle in _cube_faces(i, j, k): uses[tuple(sorted(cycle))].append((domain, direction, cycle)) + excluded = {("domain.neck", 2), ("domain.left_shoulder", -1), ("domain.right_shoulder", 1), ("domain.left_hip", -2), ("domain.right_hip", -2)} + return {tuple(CONTROL_BY_COORDINATE[p] for p in rows[0][2]): rows[0][0] for rows in uses.values() if len(rows) == 1 and (rows[0][0], rows[0][1]) not in excluded} +def _catalog_faces(): + generated = _generated_faces() + if len(generated) != 104: raise ValueError("selected-cell/port-cap face count mismatch") + result = [] + for face_id, domain, cycle in FACE_CATALOG: + ids = tuple(f"c{x:03d}" for x in cycle) + if generated.get(ids) != domain: raise ValueError(f"face catalog mismatch at {face_id}") + result.append((face_id, domain, ids)) + if set(generated) != {row[2] for row in result}: raise ValueError("face catalog is not a bijection") + return tuple(result) +FACE_RECORDS = _catalog_faces() +def _edges(faces): + result = defaultdict(list) + for fi, (_, domain, face) in enumerate(faces): + for slot, a in enumerate(face): + b = face[(slot + 1) % 4]; key = tuple(sorted((a, b), key=lambda x: int(x[1:]))); result[key].append((fi, slot, a, b, domain)) + return dict(result) +def _control_sources(): + incident = {control: {domain for _, domain, face in FACE_RECORDS if control in face} for control in CONTROL_IDS} + ordered = {control: tuple(domain for domain in DOMAINS if domain in incident[control]) for control in CONTROL_IDS}; by_pair = {frozenset(info[0]): jid for jid, info in JUNCTION_INFO.items()}; owners = {} + for control, domains in ordered.items(): + if len(domains) == 1: owners[control] = domains[0] + elif frozenset(domains) in by_pair: owners[control] = by_pair[frozenset(domains)] + else: raise ValueError(f"invalid incident domains for {control}") + return ordered, owners +CONTROL_DOMAIN_INCIDENTS, CONTROL_OWNERS = _control_sources() +CONTROL_JUNCTION_INCIDENTS = {c: CONTROL_OWNERS[c] for c in CONTROL_IDS if CONTROL_OWNERS[c].startswith("junction.")} +EDGE_RECORDS = _edges(FACE_RECORDS) +TopologyReport = namedtuple("TopologyReport", "vertex_count edge_count face_count boundary_edge_count boundary_components euler_characteristic extraordinary_controls") +def _numeric_id(value): return int(value[1:]) +def _edge_key(left, right): return tuple(sorted((left, right), key=_numeric_id)) +def _boundary_components(edges): + adjacency = defaultdict(set) + for left, right in edges: adjacency[left].add(right); adjacency[right].add(left) + unseen = set(adjacency); count = 0 + while unseen: + count += 1; todo = [unseen.pop()] + while todo: + vertex = todo.pop(); neighbours = adjacency[vertex] & unseen; unseen.difference_update(neighbours); todo.extend(neighbours) + return count +def _domain_boundary_edges(domain): + counts = defaultdict(int) + for _, owner, face in FACE_RECORDS: + if owner == domain: + for left, right in zip(face, face[1:] + face[:1]): counts[_edge_key(left, right)] += 1 + return {edge for edge, count in counts.items() if count == 1} +def _directed_boundary_cycle(domain, shared): + following = {} + for _, owner, face in FACE_RECORDS: + if owner != domain: continue + for left, right in zip(face, face[1:] + face[:1]): + if _edge_key(left, right) in shared: + if left in following and following[left] != right: raise ValueError("ambiguous directed junction edge") + following[left] = right + vertices = {vertex for edge in shared for vertex in edge} + if len(following) != len(shared) or set(following) != vertices: raise ValueError("junction boundary is not a directed cycle") + return _closed_cycle(following, len(shared)) +def _closed_cycle(following, size): + start = min(following, key=_numeric_id); cycle = []; current = start + for _ in range(size): + cycle.append(current); current = following.get(current) + if current is None: raise ValueError("junction boundary cycle is open") + if current != start or len(set(cycle)) != size: raise ValueError("junction boundary cycle is not closed") + return tuple(cycle) +def _canonical_cycle(edges): + adjacency = defaultdict(set) + for left, right in edges: adjacency[left].add(right); adjacency[right].add(left) + if not adjacency or any(len(neighbours) != 2 for neighbours in adjacency.values()): raise ValueError("junction boundary is not one undirected cycle") + following = {}; previous = None; current = min(adjacency, key=_numeric_id) + while current not in following: + candidates = sorted(adjacency[current] - ({previous} if previous is not None else set()), key=_numeric_id) + if not candidates: raise ValueError("junction boundary cycle is open") + following[current] = candidates[0]; previous, current = current, candidates[0] + return _closed_cycle(following, len(edges)) +def _junction_evidence(): + result = {} + for junction in JUNCTIONS: + domains = JUNCTION_INFO[junction][0]; boundaries = tuple(_domain_boundary_edges(domain) for domain in domains); shared = boundaries[0] & boundaries[1] + first, second = (_directed_boundary_cycle(domain, shared) for domain in domains) + if first != (second[0], *reversed(second[1:])): raise ValueError(f"junction directions are not opposite: {junction}") + trace = _canonical_cycle(shared) + if tuple(JUNCTION_TRACES[junction]) != trace: raise ValueError(f"junction trace disagrees with face incidence: {junction}") + result[junction] = {"domains": domains, "trace": trace, "edges": shared} + return result +def validate_catalogs(): + boundary = {e for e, uses in EDGE_RECORDS.items() if len(uses) == 1}; vertices = {control for _, _, face in FACE_RECORDS for control in face} + if vertices != set(CONTROL_IDS) or (len(CELL_CATALOG), len(FACE_RECORDS), len(EDGE_RECORDS), len(boundary)) != (58, 104, 227, 38): raise ValueError("catalog count mismatch") + if any(len(uses) not in (1, 2) for uses in EDGE_RECORDS.values()): raise ValueError("non-manifold base edge") + directed = {(u[2], u[3]) for uses in EDGE_RECORDS.values() for u in uses} + if any(len(uses) == 2 and (uses[0][2], uses[0][3]) == (uses[1][2], uses[1][3]) for uses in EDGE_RECORDS.values()): raise ValueError("base orientation conflict") + declared = {tuple(sorted((loop[i], loop[(i + 1) % len(loop)]), key=lambda x: int(x[1:]))) for _, _, loop in PORT_INFO.values() for i in range(len(loop))} + if declared != boundary or any((loop[i], loop[(i + 1) % len(loop)]) not in directed for _, _, loop in PORT_INFO.values() for i in range(len(loop))): raise ValueError("port loops do not cover base boundary") + _junction_evidence(); boundary_vertices = {control for edge in boundary for control in edge}; incident_faces = {control: {index for index, (_, _, face) in enumerate(FACE_RECORDS) if control in face} for control in CONTROL_IDS} + extraordinary = tuple(control for control in CONTROL_IDS if control not in boundary_vertices and len(incident_faces[control]) != 4) + report = TopologyReport(len(vertices), len(EDGE_RECORDS), len(FACE_RECORDS), len(boundary), _boundary_components(boundary), len(vertices) - len(EDGE_RECORDS) + len(FACE_RECORDS), extraordinary) + if (report.vertex_count, report.edge_count, report.face_count, report.boundary_edge_count, report.boundary_components, report.euler_characteristic, len(report.extraordinary_controls)) != (120, 227, 104, 38, 5, -3, 20): raise ValueError("derived catalog topology does not match the frozen counts") + return report +CATALOG_REPORT = validate_catalogs() +def symbolic_topology(): return CONTROL_IDS, tuple(tuple(int(c[1:]) for c in f[2]) for f in FACE_RECORDS), tuple((name, tuple(int(c[1:]) for c in info[2])) for name, info in PORT_INFO.items()) +@dataclass(frozen=True) +class Mesh: + vertices: tuple[tuple[float, float, float], ...]; quads: tuple[tuple[int, int, int, int], ...] + control_ids: tuple[str, ...]; formula_ids: tuple[str, ...]; dependencies: tuple[tuple[str, ...], ...] + boundary_loops: tuple[tuple[str, tuple[int, ...]], ...]; triangles: tuple[tuple[int, int, int], ...] = () + level: int = 0; face_ids: tuple[str, ...] = (); face_owners: tuple[str, ...] = () + formula_records: tuple[Mapping[str, Any], ...] = (); vertex_records: tuple[Mapping[str, Any], ...] = (); source_stencils: tuple[tuple[int, ...], ...] = () +@dataclass(frozen=True) +class SurfaceEvaluation: cage: Mesh; levels: tuple[Mesh, Mesh] +_FORMULA_RECORD_FIELDS = ("control_id", "lattice_key", "formula_id", "construction_owner", "index_parameters", "geometry_dependencies", "coordinate") +_FORMULA_LEDGER_SHA256 = "da8569de79e3c7479f94a94c5a2d45a9a131f623880c9301835a8e5f8e322bd5" +def _reference_e(center, u, q, lateral, anterior, posterior, exponent): + def signed_power(value): + magnitude = pow(abs(value), 2.0 / exponent) + return 0.0 if magnitude == 0.0 else -magnitude if value < 0.0 else magnitude + return (center[0] + lateral * signed_power(u), center[1], center[2] + (anterior if q >= 0.0 else posterior) * signed_power(q)) +def _reference_control_coordinate(prepared, control): + i, j, k = COORDINATE_BY_CONTROL[control]; q = float(k - 1) + if j in (6, 7) and i in (2, 3): + row = prepared["stations"]["neck_collar" if j == 6 else "neck_upper"] + return _reference_e(row["C"], 2.0 * (float(i) - 2.5), q, row["rL"], row["rA"], row["rP"], 2.2) + if j in (4, 5, 6) and i in (0, 1, 4, 5): + side = "left" if i < 2 else "right"; sign = -1.0 if side == "left" else 1.0; a = 1 - i if side == "left" else i - 4; v = (float(j) - 4.0) / 2.0; row = prepared["shoulders"][side] + inner = tuple((1.0 - v) * row["axilla"][axis] + v * row["peak"][axis] for axis in range(3)); outer = (row["arm_origin"][0] + sign * row["start_lateral"], row["arm_origin"][1] + (2.0 * v - 1.0) * row["start_up"] * .5, row["arm_origin"][2]) + center = tuple((1.0 - float(a)) * inner[axis] + float(a) * outer[axis] for axis in range(3)); inner_depth = .75 * row["start_forward"] if v == 0.0 else row["shoulder_depth"]; depth = (1.0 - float(a)) * inner_depth + float(a) * row["start_forward"] + return _reference_e(center, 0.0, q, 0.0, depth, depth, 2.2) + if j in (-1, 0): + side = "left" if i <= 2 else "right"; row = prepared["hips"][side]; u = float(i) - (1.0 if side == "left" else 4.0); ps = row["P_s"] + if j == -1: return (ps[0] + u * row["r_x"], ps[1], ps[2] + q * row["r_z"]) + low = prepared["stations"]["lower_pelvis"]; distance = low["C"][1] - ps[1]; maximum_x = low["rL"] - abs(ps[0] - low["C"][0]); hc = row["r_y"] + .25 * (distance - row["r_y"]); hs = .70 * hc + jf = row["r_z"] + .20 * (low["rA"] - row["r_z"]); jb = row["r_z"] + .20 * (low["rP"] - row["r_z"]) + return (ps[0] + u * (row["r_x"] + (maximum_x - row["r_x"])), ps[1] + hs + (hc - hs) * (1.0 - u * u), ps[2] + .20 * (low["C"][2] - ps[2]) + (jf if q >= 0.0 else jb) * q) + if j == 1: + row = prepared["stations"]["upper_pelvis"] if i in (0, 5) else prepared["stations"]["lower_abdomen"]; u = (float(i) - 2.5) / 2.5 + center = row["C"] if i in (0, 5) else (row["C"][0], (prepared["stations"]["upper_pelvis"]["C"][1] + row["C"][1]) / 2.0, row["C"][2]) + return _reference_e(center, u, q, row["rL"], row["rA"], row["rP"], 2.6) + u = (float(i) - 2.5) / 1.5 + if j == 5: + low, high = (prepared["stations"][name] for name in ("lower_ribcage", "upper_ribcage_shoulder")); center = tuple((low["C"][axis] + high["C"][axis]) / 2.0 for axis in range(3)); radii = tuple((low[name] + high[name]) / 2.0 for name in ("rL", "rA", "rP")) + else: + row = prepared["stations"][("waist_abdomen", "upper_abdomen", "lower_ribcage")[j - 2]]; center, radii = row["C"], (row["rL"], row["rA"], row["rP"]) + return _reference_e(center, u, q, *radii, 2.6) +def _validate_cage_lineage(mesh, prepared): + if type(mesh.formula_records) is not tuple: raise ValueError("L0 formula records are not a tuple") + reference_vertices = tuple(tuple(float(x) for x in _reference_control_coordinate(prepared, control)) for control in CONTROL_IDS) + if mesh.vertices != reference_vertices: raise ValueError("L0 vertices differ from independent prepared reference") + ledger = [] + for index, (control, record) in enumerate(zip(CONTROL_IDS, mesh.formula_records)): + if type(record) is not dict or set(record) != set(_FORMULA_RECORD_FIELDS): raise ValueError(f"L0 formula record schema mismatch at {index}") + if type(record["coordinate"]) is not list or len(record["coordinate"]) != 3 or any(type(value) is not float or not isfinite(value) for value in record["coordinate"]) or record["coordinate"] != list(reference_vertices[index]): raise ValueError(f"L0 formula coordinate differs from independent prepared reference at {index}") + ledger.append({field: record[field] for field in _FORMULA_RECORD_FIELDS[:-1]}) + if sha256(repr(tuple(ledger)).encode("ascii")).hexdigest() != _FORMULA_LEDGER_SHA256: raise ValueError("L0 formula ledger differs from the frozen contract") + if mesh.formula_ids != tuple(record["formula_id"] for record in mesh.formula_records) or mesh.dependencies != tuple(tuple(record["geometry_dependencies"]) for record in mesh.formula_records): raise ValueError("L0 formula projections disagree with formula records") + if mesh.source_stencils != tuple((index,) for index in range(120)): raise ValueError("L0 source stencils are not the identity") + if mesh.vertex_records != tuple(_record(0, control, (control,), mesh.formula_records) for control in CONTROL_IDS): raise ValueError("L0 vertex records disagree with formula records") +def _check_faces(quads, vertex_count): + if any(len(f) != 4 or len(set(f)) != 4 or any(type(x) is not int or not 0 <= x < vertex_count for x in f) for f in quads): raise ValueError("invalid quad catalog") + uses = defaultdict(list) + for fi, face in enumerate(quads): + for slot, a in enumerate(face): + b = face[(slot + 1) % 4]; uses[tuple(sorted((a, b)))].append((fi, a, b, slot)) + if any(len(v) not in (1, 2) for v in uses.values()): raise ValueError("non-manifold edge") + if any(len(v) == 2 and v[0][1:3] == v[1][1:3] for v in uses.values()): raise ValueError("orientation conflict") + return dict(uses) +def _validate_level_shape(mesh): + if type(mesh) is not Mesh or type(mesh.level) is not int or mesh.level not in range(3): raise ValueError("invalid surface level") + expected = ((120, 104, 227), (451, 416, 870), (1737, 1664, 3404))[mesh.level]; expected_ids = CONTROL_IDS if mesh.level == 0 else tuple(f"vertex.L{mesh.level}.v{i:04d}" for i in range(expected[0])); expected_faces = tuple(tuple(int(c[1:]) for c in row[2]) for row in FACE_RECORDS) if mesh.level == 0 else None + expected_face_ids = tuple(row[0] for row in FACE_RECORDS) if mesh.level == 0 else tuple(f"face.L{mesh.level}.q{i:04d}" for i in range(expected[1])); expected_owners = tuple(row[1] for row in FACE_RECORDS) if mesh.level == 0 else tuple(FACE_RECORDS[i // (4 ** mesh.level)][1] for i in range(expected[1])) + if (type(mesh.vertices) is not tuple or type(mesh.quads) is not tuple or mesh.control_ids != expected_ids or len(mesh.face_ids) != expected[1] or tuple(mesh.face_ids) != expected_face_ids or len(mesh.face_owners) != expected[1] or tuple(mesh.face_owners) != expected_owners or (expected_faces is not None and mesh.quads != expected_faces)): raise ValueError(f"L{mesh.level} identifier/catalog mismatch") + if len(mesh.vertices) != expected[0] or any(type(point) is not tuple or len(point) != 3 or any(type(x) is not float or not isfinite(x) for x in point) for point in mesh.vertices): raise ValueError(f"L{mesh.level} coordinate shape mismatch") + if any(type(face) is not tuple or len(face) != 4 for face in mesh.quads): raise ValueError(f"L{mesh.level} quad shape mismatch") + if len(mesh.formula_ids) != expected[0] or len(mesh.dependencies) != expected[0] or len(mesh.vertex_records) != expected[0] or len(mesh.source_stencils) != expected[0] or len(mesh.formula_records) != 120: raise ValueError(f"L{mesh.level} lineage cardinality mismatch") + if type(mesh.boundary_loops) is not tuple or tuple(name for name, _ in mesh.boundary_loops) != PORTS: raise ValueError(f"L{mesh.level} port loop catalog mismatch") + loops = dict(mesh.boundary_loops); report = _generic.validate_topology(len(mesh.vertices), mesh.quads, loops, expected_faces) + if (len(mesh.vertices), len(mesh.quads), report.edge_count) != expected: raise ValueError(f"L{mesh.level} topology counts mismatch") + expected_triangles = tuple(t for face in mesh.quads for t in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) + if mesh.triangles != expected_triangles: raise ValueError(f"L{mesh.level} triangle catalog mismatch") + return report +def _mesh_difference(actual, expected): return next((field for field in Mesh.__dataclass_fields__ if getattr(actual, field) != getattr(expected, field)), None) +def _reference_subdivision(parent, level): + uses = _check_faces(parent.quads, len(parent.vertices)); edges = tuple(sorted(uses)); boundary, around, incident = defaultdict(set), defaultdict(list), defaultdict(list) + for face_index, face in enumerate(parent.quads): + for vertex in face: around[vertex].append(face_index) + for edge, rows in uses.items(): + for vertex in edge: incident[vertex].append(edge) + if len(rows) == 1: boundary[edge[0]].add(edge[1]); boundary[edge[1]].add(edge[0]) + face_points = [tuple(_div(_ordered(parent.vertices[v][axis] for v in face), 4.0) for axis in range(3)) for face in parent.quads] + vertex_sources = tuple((i, *sorted(boundary[i])) if i in boundary else tuple(v for face_index in sorted(around[i]) for v in parent.quads[face_index]) for i in range(len(parent.vertices))) + edge_sources = tuple(edge + tuple(v for face_index, *_ in sorted(uses[edge]) for v in parent.quads[face_index]) for edge in edges); sources = vertex_sources + edge_sources + tuple(parent.quads) + vertices, formulas = [], [] + for i, point in enumerate(parent.vertices): + if i in boundary: + left, right = sorted(boundary[i]); value = tuple((6.0 * point[axis] + parent.vertices[left][axis] + parent.vertices[right][axis]) / 8.0 for axis in range(3)); formula = "subdivision.open-boundary-vertex" + else: + faces, local_edges = sorted(around[i]), sorted(incident[i]); count = len(faces); average_face = tuple(_ordered(face_points[f][axis] for f in faces) / float(count) for axis in range(3)); average_edge = tuple(_ordered((parent.vertices[a][axis] + parent.vertices[b][axis]) / 2.0 for a, b in local_edges) / float(len(local_edges)) for axis in range(3)); value = tuple((average_face[axis] + 2.0 * average_edge[axis] + float(count - 3) * point[axis]) / float(count) for axis in range(3)); formula = "subdivision.interior-vertex" + vertices.append(value); formulas.append(formula) + for edge in edges: + a, b = edge + if len(uses[edge]) == 1: value, formula = tuple((parent.vertices[a][axis] + parent.vertices[b][axis]) / 2.0 for axis in range(3)), "subdivision.boundary-edge" + else: + f0, f1 = sorted(row[0] for row in uses[edge]); value, formula = tuple((parent.vertices[a][axis] + parent.vertices[b][axis] + face_points[f0][axis] + face_points[f1][axis]) / 4.0 for axis in range(3)), "subdivision.interior-edge" + vertices.append(value); formulas.append(formula) + vertices.extend(face_points); formulas.extend("subdivision.face-point" for _ in parent.quads) + edge_index = {edge: len(parent.vertices) + index for index, edge in enumerate(edges)}; face_start = len(parent.vertices) + len(edges) + quads = tuple((vertex, edge_index[tuple(sorted((vertex, face[(corner + 1) % 4])))], face_start + face_index, edge_index[tuple(sorted((face[(corner - 1) % 4], vertex)))]) for face_index, face in enumerate(parent.quads) for corner, vertex in enumerate(face)) + loops = tuple((name, tuple(item for index, vertex in enumerate(loop) for item in (vertex, edge_index[tuple(sorted((vertex, loop[(index + 1) % len(loop)])))]))) for name, loop in parent.boundary_loops); ids = tuple(f"vertex.L{level}.v{i:04d}" for i in range(len(vertices))) + def lineage(index, source): + controls = tuple(sorted({control for parent_index in source for control in parent.vertex_records[parent_index]["base_control_contributors"]}, key=lambda value: int(value[1:]))); dependencies = tuple(sorted({item for control in controls for item in parent.formula_records[int(control[1:])]["geometry_dependencies"]})); contributing = {domain for control in controls for domain in (JUNCTION_INFO[CONTROL_OWNERS[control]][0] if CONTROL_OWNERS[control].startswith("junction.") else (CONTROL_OWNERS[control],))} + return {"level": level, "vertex_id": ids[index], "base_control_contributors": controls, "geometry_dependency_union": dependencies, "contributor_domains": tuple(domain for domain in DOMAINS if domain in contributing)} + records = tuple(lineage(index, source) for index, source in enumerate(sources)); dependencies = tuple(record["geometry_dependency_union"] for record in records); triangles = tuple(triangle for face in quads for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) + return Mesh(tuple(vertices), quads, ids, tuple(formulas), dependencies, loops, triangles, level, tuple(f"face.L{level}.q{i:04d}" for i in range(len(quads))), tuple(parent.face_owners[index // 4] for index in range(len(quads))), parent.formula_records, records, sources) +def _validate_derived_level(mesh, parent): + report = _validate_level_shape(mesh) + if type(parent) is not Mesh or parent.level != mesh.level - 1: raise ValueError(f"L{mesh.level} requires its immediately preceding parent") + _validate_level_shape(parent); expected = _reference_subdivision(parent, mesh.level); difference = _mesh_difference(mesh, expected) + if difference is not None: raise ValueError(f"L{mesh.level} differs from its parent-derived {difference}") + return report +def _validate_level_structure_admitted(mesh, prepared, parent=None): + report = _validate_level_shape(mesh) + if mesh.level == 0: + if parent is not None: raise ValueError("level 0 cannot have a parent") + _validate_cage_lineage(mesh, prepared); return report + if type(parent) is Mesh and parent.level == 0: _validate_cage_lineage(parent, prepared) + return _validate_derived_level(mesh, parent) +def validate_level_structure(mesh, prepared=None, parent=None): + cage = mesh if type(mesh) is Mesh and mesh.level == 0 else parent if type(parent) is Mesh and parent.level == 0 else None + prepared = _infer_surface_prepared(cage) if prepared is None and cage is not None else prepared + if prepared is None: raise ValueError("prepared input is required when no L0 cage is available") + _admit_surface_prepared(prepared); return _validate_level_structure_admitted(mesh, prepared, parent) +def _evaluation_meshes(value): + if type(value) is SurfaceEvaluation: cage, levels = value.cage, value.levels + elif isinstance(value, Mapping) and set(value) == {"cage", "levels"}: cage, levels = value["cage"], value["levels"] + elif type(value) in (tuple, list) and len(value) == 3: return tuple(value) + else: raise ValueError("evaluation requires cage and levels 0 through 2") + if type(levels) is not tuple or len(levels) != 2: raise ValueError("evaluation requires two derived levels") + return (cage, *levels) +def validate_evaluation(value, prepared=None): + meshes = _evaluation_meshes(value) + prepared = _infer_surface_prepared(meshes[0]) if prepared is None else prepared; _admit_surface_prepared(prepared) + _validate_level_structure_admitted(meshes[0], prepared); _validate_level_structure_admitted(meshes[1], prepared, meshes[0]); _validate_level_structure_admitted(meshes[2], prepared, meshes[1]) + return meshes +def topology_incidence(mesh): + uses = _check_faces(mesh.quads, len(mesh.vertices)); return tuple({"edge": edge, "incident_faces": tuple(u[0] for u in uses[edge]), "slots": tuple(u[3] for u in uses[edge])} for edge in sorted(uses)) +def level_topology(mesh): + return {"level": mesh.level, "vertex_ids": mesh.control_ids, "face_ids": mesh.face_ids, "face_owners": mesh.face_owners, "faces": mesh.quads, "edges": topology_incidence(mesh), "boundary_loops": mesh.boundary_loops, "triangles": mesh.triangles} +def _component_dependencies(name, u, q): + return {f"stations.{name}.C.{axis}" for axis in "xyz"} | ({f"stations.{name}.rL"} if u != 0.0 else set()) | ({f"stations.{name}.rA"} if q > 0.0 else set()) | ({f"stations.{name}.rP"} if q < 0.0 else set()) +def _station(prepared, name): + row = prepared["stations"][name]; return row["C"], row["rL"], row["rA"], row["rP"] +def _formula_for_control(prepared, control_id): + i, j, k = COORDINATE_BY_CONTROL[control_id]; q = float(k - 1) + if j in (6, 7) and i in (2, 3): + name = "neck_collar" if j == 6 else "neck_upper"; C, rl, ra, rp = _station(prepared, name); u = _mul(2.0, _sub(float(i), 2.5)); point = _e(C, u, q, rl, ra, rp, 2.2) + deps = _component_dependencies(name, u, q); formula = "formula.neck.stem"; params = {"i": i, "j": j, "k": k, "u": u, "q": q, "n": 2.2, "station_selector": name} + elif j in (4, 5, 6) and i in (0, 1, 4, 5): + side = "left" if i < 2 else "right"; sign = -1 if side == "left" else 1 + a = 1 - i if side == "left" else i - 4; v = _div(_sub(float(j), 4.0), 2.0); row = prepared["shoulders"][side] + inner = _vlerp(row["axilla"], row["peak"], v); outer = _vadd(row["arm_origin"], (_mul(float(sign), row["start_lateral"]), _mul(_mul(_sub(_mul(2.0, v), 1.0), row["start_up"]), .5), 0.0)); inner_depth = _mul(.75, row["start_forward"]) if v == 0.0 else row["shoulder_depth"] + depth = _add(_mul(float(1 - a), inner_depth), _mul(float(a), row["start_forward"])); point = _e(_vlerp(inner, outer, float(a)), 0.0, q, 0.0, depth, depth, 2.2); deps = set() + if a == 0: + if v < 1: deps.update(f"shoulders.{side}.axilla.{x}" for x in "xyz") + if v > 0: deps.update(f"shoulders.{side}.peak.{x}" for x in "xyz") + if q != 0 and v == 0: deps.add(f"shoulders.{side}.start_forward") + if q != 0 and v > 0: deps.add(f"shoulders.{side}.shoulder_depth") + else: + deps.update(f"shoulders.{side}.arm_origin.{x}" for x in "xyz"); deps.add(f"shoulders.{side}.start_lateral"); + if v != .5: deps.add(f"shoulders.{side}.start_up") + if q != 0: deps.add(f"shoulders.{side}.start_forward") + formula = f"formula.shoulder.{side}"; params = {"i": i, "j": j, "k": k, "side": side, "a": float(a), "v": v, "q": q, "sign": sign} + elif j in (-1, 0): + side = "left" if i <= 2 else "right"; row = prepared["hips"][side]; u = _sub(float(i), 1.0 if side == "left" else 4.0) + if j == -1: + point = (_add(row["P_s"][0], _mul(u, row["r_x"])), row["P_s"][1], _add(row["P_s"][2], _mul(q, row["r_z"]))) + deps = {f"hips.{side}.P_s.{x}" for x in "xyz"} | ({f"hips.{side}.r_x"} if u != 0 else set()) | ({f"hips.{side}.r_z"} if q != 0 else set()) + else: + low = prepared["stations"]["lower_pelvis"]; ps = row["P_s"]; D = _sub(low["C"][1], ps[1]); Mx = _sub(low["rL"], abs(_sub(ps[0], low["C"][0]))); Hc = _add(row["r_y"], _mul(.25, _sub(D, row["r_y"]))); Hs = _mul(.70, Hc); Jx = _add(row["r_x"], _sub(Mx, row["r_x"])) + Jf = _add(row["r_z"], _mul(.20, _sub(low["rA"], row["r_z"]))); Jb = _add(row["r_z"], _mul(.20, _sub(low["rP"], row["r_z"]))); J0z = _lerp(ps[2], low["C"][2], .20); Qz = _mul(Jf if q >= 0 else Jb, q) + point = (_add(ps[0], _mul(u, Jx)), _add(_add(ps[1], Hs), _mul(_sub(Hc, Hs), _sub(1., _mul(u, u)))), _add(J0z, Qz)) + deps = {f"hips.{side}.P_s.y", f"hips.{side}.P_s.z", f"hips.{side}.r_y", "stations.lower_pelvis.C.y", "stations.lower_pelvis.C.z"} | ({f"hips.{side}.P_s.x"} if not ((side == "left" and u == -1.) or (side == "right" and u == 1.)) else set()) | ({"stations.lower_pelvis.rL", "stations.lower_pelvis.C.x"} if u != 0 else set()) | ({f"hips.{side}.r_z", "stations.lower_pelvis.rA"} if q > 0 else {f"hips.{side}.r_z", "stations.lower_pelvis.rP"} if q < 0 else set()) + formula = f"formula.hip.{side}"; params = {"i": i, "j": j, "k": k, "side": side, "u": u, "q": q} + else: + if j == 1 and i in (0, 5): + name, d = "upper_pelvis", 2.5; C, rl, ra, rp = _station(prepared, name); u = _div(_sub(float(i), 2.5), d); point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(name, u, q); formula = "formula.axial.j1.edge"; selector = name + elif j == 1: + low, up = prepared["stations"]["lower_abdomen"], prepared["stations"]["upper_pelvis"]; d = 2.5; u = _div(_sub(float(i), 2.5), d); C = (low["C"][0], _div(_add(up["C"][1], low["C"][1]), 2.), low["C"][2]); point = _e(C, u, q, low["rL"], low["rA"], low["rP"], 2.6) + deps = _component_dependencies("lower_abdomen", u, q) | {"stations.upper_pelvis.C.y"}; formula = "formula.axial.j1.interior"; selector = "virtual.upper_pelvis_y__lower_abdomen" + else: + d = 1.5; u = _div(_sub(float(i), 2.5), d) + if j == 5: + low, up = prepared["stations"]["lower_ribcage"], prepared["stations"]["upper_ribcage_shoulder"]; C = tuple(_div(_add(low["C"][x], up["C"][x]), 2.) for x in range(3)); radii = tuple(_div(_add(low[x], up[x]), 2.) for x in ("rL", "rA", "rP")); selector = "virtual.lower_ribcage__upper_ribcage_shoulder" + point = _e(C, u, q, *radii, 2.6); deps = {f"stations.{name}.C.{x}" for name in ("lower_ribcage", "upper_ribcage_shoulder") for x in "xyz"} + if u != 0: deps.update(f"stations.{name}.rL" for name in ("lower_ribcage", "upper_ribcage_shoulder")) + if q > 0: deps.update(f"stations.{name}.rA" for name in ("lower_ribcage", "upper_ribcage_shoulder")) + if q < 0: deps.update(f"stations.{name}.rP" for name in ("lower_ribcage", "upper_ribcage_shoulder")) + else: + selector = {2: "waist_abdomen", 3: "upper_abdomen", 4: "lower_ribcage"}[j]; C, rl, ra, rp = _station(prepared, selector); point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(selector, u, q) + formula = "formula.axial.station" + params = {"i": i, "j": j, "k": k, "u": u, "q": q, "d": float(d), "n": 2.6, "station_selector": selector} + return formula, tuple(sorted(deps)), tuple(point), params +def _formula_candidate_records_admitted(prepared): + return tuple({"control_id": control, "lattice_key": list(COORDINATE_BY_CONTROL[control]), "formula_id": formula, "construction_owner": CONTROL_OWNERS[control], "index_parameters": params, "geometry_dependencies": list(deps), "coordinate": [float(x) for x in point]} for control in CONTROL_IDS for formula, deps, point, params in (_formula_for_control(prepared, control),)) +def formula_candidate_records(prepared): + prepared_projection.validate_prepared(prepared); return _formula_candidate_records_admitted(prepared) +def _record(level, vertex_id, contributors, formulas): + controls = tuple(sorted(set(contributors), key=lambda x: int(x[1:]))); deps = tuple(sorted({d for c in controls for d in formulas[int(c[1:])]["geometry_dependencies"]})) + contributing = {domain for c in controls for domain in (JUNCTION_INFO[CONTROL_OWNERS[c]][0] if CONTROL_OWNERS[c].startswith("junction.") else (CONTROL_OWNERS[c],))}; domains = tuple(domain for domain in DOMAINS if domain in contributing) + return {"level": level, "vertex_id": vertex_id, "base_control_contributors": controls, "geometry_dependency_union": deps, "contributor_domains": domains} +def _contributors(mesh, indices): return [c for i in indices for c in mesh.vertex_records[i]["base_control_contributors"]] +def _incidence(mesh): + uses = _check_faces(mesh.quads, len(mesh.vertices)); edges = tuple(sorted(uses)); boundary = defaultdict(set); faces = defaultdict(list); incident_edges = defaultdict(list) + for fi, face in enumerate(mesh.quads): + for v in face: faces[v].append(fi) + for edge, rows in uses.items(): + for v in edge: incident_edges[v].append(edge) + if len(rows) == 1: boundary[edge[0]].add(edge[1]); boundary[edge[1]].add(edge[0]) + return uses, edges, boundary, faces, incident_edges +def subdivision_incidence(mesh): + uses, edges, boundary, faces, _incident_edges = _incidence(mesh); V, E, Q = len(mesh.vertices), len(edges), len(mesh.quads) + stencils = tuple((i, *sorted(boundary[i])) if i in boundary else tuple(v for fi in sorted(faces[i]) for v in mesh.quads[fi]) for i in range(V)) + edge_stencils = tuple((edge, tuple(edge) + tuple(v for fi, *_ in sorted(uses[edge]) for v in mesh.quads[fi])) for edge in edges) + face_stencils = tuple((fi, tuple(mesh.quads[fi])) for fi in range(Q)) + edge_indices = tuple((edge, V + i) for i, edge in enumerate(edges)); face_indices = tuple((fi, V + E + fi) for fi in range(Q)) + children = tuple((fi, corner, (face[corner], edge_indices[edges.index(tuple(sorted((face[corner], face[(corner + 1) % 4]))))][1], V + E + fi, edge_indices[edges.index(tuple(sorted((face[(corner - 1) % 4], face[corner]))))][1])) for fi, face in enumerate(mesh.quads) for corner in range(4)) + propagated = tuple((name, tuple(item for i, v in enumerate(loop) for item in (v, edge_indices[edges.index(tuple(sorted((v, loop[(i + 1) % len(loop)]))))][1])) ) for name, loop in mesh.boundary_loops) + return {"source_level": mesh.level, "target_level": mesh.level + 1, "edges": tuple((e, tuple(u[0] for u in uses[e])) for e in edges), "boundary_edges": tuple(e for e in edges if len(uses[e]) == 1), "vertex_stencils": stencils, "edge_stencils": edge_stencils, "face_stencils": face_stencils, "edge_point_indices": edge_indices, "face_point_indices": face_indices, "child_emission": children, "propagated_port_loops": propagated} +def propagate_port_loops(mesh): + return dict(subdivision_incidence(mesh)["propagated_port_loops"]) +def junction_trace_inputs(): + evidence = _junction_evidence(); result = [] + for junction in JUNCTIONS: + domains, (drop, tag_axes) = JUNCTION_INFO[junction]; trace = evidence[junction]["trace"] + result.append({"junction_id": junction, "incident_domains": domains, "drop_axis": drop, "tag_axes": tag_axes, "base_control_ids": trace, "base_lattice_tags": tuple(tuple(COORDINATE_BY_CONTROL[c][{"i": 0, "j": 1}.get(axis, 2)] for axis in tag_axes) for c in trace)}) + return tuple(result) +def propagate_junction_tags(mesh, junction): + if junction not in JUNCTIONS: raise ValueError("unknown junction") + trace = _junction_evidence()[junction]["trace"]; meshes = (mesh.cage, *mesh.levels) if hasattr(mesh, "cage") else tuple(mesh) if isinstance(mesh, (list, tuple)) else (mesh,) + if not meshes or len(meshes) > 3: raise ValueError("junction tag propagation requires levels 0 through 2") + axes = JUNCTION_INFO[junction][1][1]; index = {c: i for i, c in enumerate(meshes[0].control_ids)} + cycle = tuple(index[c] for c in trace); selected = {tuple(sorted((a, cycle[(i + 1) % len(cycle)]))) for i, a in enumerate(cycle)} + tags = {i: tuple((COORDINATE_BY_CONTROL[meshes[0].control_ids[i]][{"i": 0, "j": 1, "k": 2}[axis]], 1) for axis in axes) for i in {v for edge in selected for v in edge}} + result = (dict(sorted(tags.items())),) + for level in range(1, len(meshes)): + edge_points = dict(subdivision_incidence(meshes[level - 1])["edge_point_indices"]); out = dict(tags) + for a, b in selected: out[edge_points[(a, b)]] = tuple(_half_tag(tags[a][axis], tags[b][axis]) for axis in range(2)) + selected = {tuple(sorted((a, edge_points[(a, b)]))) for a, b in selected} | {tuple(sorted((edge_points[(a, b)], b))) for a, b in selected}; tags = out; result += (dict(sorted(tags.items())),) + return result +def _half_tag(left, right): + numerator = left[0] * right[1] + right[0] * left[1]; denominator = 2 * left[1] * right[1]; common = gcd(abs(numerator), denominator) + return numerator // common, denominator // common +def _build_cage_admitted(prepared): + records = _formula_candidate_records_admitted(prepared); quads = tuple(tuple(int(c[1:]) for c in f[2]) for f in FACE_RECORDS) + loops = tuple((name, tuple(int(c[1:]) for c in info[2])) for name, info in PORT_INFO.items()) + triangles = tuple(t for f in quads for t in ((f[0], f[1], f[2]), (f[0], f[2], f[3]))) + mesh = Mesh(tuple(tuple(r["coordinate"]) for r in records), quads, CONTROL_IDS, tuple(r["formula_id"] for r in records), tuple(tuple(r["geometry_dependencies"]) for r in records), loops, triangles, 0, tuple(f[0] for f in FACE_RECORDS), tuple(f[1] for f in FACE_RECORDS), records, tuple(_record(0, c, (c,), records) for c in CONTROL_IDS), tuple((i,) for i in range(120))) + _validate_level_structure_admitted(mesh, prepared); return mesh +def build_cage(prepared): + prepared_projection.validate_prepared(prepared); return _build_cage_admitted(prepared) +def _subdivide_once(mesh, level, points=None): + if type(level) is not int or level not in (1, 2) or mesh.level != level - 1: raise ValueError("subdivision level must follow level 0,1 order") + inc = subdivision_incidence(mesh); uses, edges, boundary, faces, incident_edges = _incidence(mesh); points = mesh.vertices if points is None else points + face_points = [tuple(_div(_ordered(points[v][axis] for v in face), 4.) for axis in range(3)) for face in mesh.quads] + vertices, stencils, formulas, deps = [], list(inc["vertex_stencils"]), [], [] + for i, point in enumerate(points): + source = stencils[i] + if i in boundary: n0, n1 = sorted(boundary[i]); value = tuple(_div(_add(_add(_mul(6., point[a]), points[n0][a]), points[n1][a]), 8.) for a in range(3)); formula = "subdivision.open-boundary-vertex" + else: + fs = sorted(faces[i]); es = sorted(incident_edges[i]); n = len(fs); F = tuple(_div(_ordered(face_points[f][a] for f in fs), float(n)) for a in range(3)); R = tuple(_div(_ordered(_div(_add(points[x][a], points[y][a]), 2.) for x, y in es), float(len(es))) for a in range(3)) + t0 = tuple(_mul(2., x) for x in R); t1 = tuple(_add(F[a], t0[a]) for a in range(3)); t2 = tuple(_mul(float(n - 3), point[a]) for a in range(3)); value = tuple(_div(_add(t1[a], t2[a]), float(n)) for a in range(3)); formula = "subdivision.interior-vertex" + vertices.append(value); formulas.append(formula); base = _contributors(mesh, source); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) + for edge in edges: + a, b = edge + if len(uses[edge]) == 1: value = tuple(_div(_add(points[a][x], points[b][x]), 2.) for x in range(3)); formula = "subdivision.boundary-edge" + else: f0, f1 = sorted(u[0] for u in uses[edge]); value = tuple(_div(_add(_add(_add(points[a][x], points[b][x]), face_points[f0][x]), face_points[f1][x]), 4.) for x in range(3)); formula = "subdivision.interior-edge" + vertices.append(value); formulas.append(formula); base = _contributors(mesh, inc["edge_stencils"][edges.index(edge)][1]); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) + for fi, face in enumerate(mesh.quads): + vertices.append(face_points[fi]); formulas.append("subdivision.face-point"); base = _contributors(mesh, face); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) + quads = tuple(child[2] for child in inc["child_emission"]); face_ids = tuple(f"face.L{level}.q{i:04d}" for i in range(len(quads))); owners = tuple(mesh.face_owners[fi] for fi, _, _ in inc["child_emission"]); loops = inc["propagated_port_loops"]; ids = tuple(f"vertex.L{level}.v{i:04d}" for i in range(len(vertices))) + records = tuple(_record(level, ids[i], _contributors(mesh, source), mesh.formula_records) for i, source in enumerate(stencils)) + records += tuple(_record(level, ids[index], _contributors(mesh, source), mesh.formula_records) for (edge, source), (_, index) in zip(inc["edge_stencils"], inc["edge_point_indices"])) + records += tuple(_record(level, ids[index], _contributors(mesh, face), mesh.formula_records) for (fi, face), (_, index) in zip(inc["face_stencils"], inc["face_point_indices"])); triangles = tuple(t for f in quads for t in ((f[0], f[1], f[2]), (f[0], f[2], f[3]))) + complete_stencils = tuple(stencils) + tuple(source for _, source in inc["edge_stencils"]) + tuple(face for _, face in inc["face_stencils"]); return Mesh(tuple(vertices), quads, ids, tuple(formulas), tuple(deps), loops, triangles, level, face_ids, owners, mesh.formula_records, records, complete_stencils) +def subdivide(mesh, level=1): + if type(level) is not int or level not in (1, 2) or type(mesh) is not Mesh or mesh.level >= level: raise ValueError("the frozen surface has exactly two ordered subdivision levels") + result = mesh + for target in range(mesh.level + 1, level + 1): + parent = result; result = _subdivide_once(parent, target); _validate_derived_level(result, parent) + return result +def _evaluate_cage(cage, prepared): + level1 = subdivide(cage, 1); level2 = subdivide(level1, 2); evaluation = SurfaceEvaluation(cage, (level1, level2)); validate_evaluation(evaluation, prepared); return evaluation +def evaluate(prepared, levels=2): + if type(levels) is not int or levels != 2: raise ValueError("the frozen neutral surface evaluates exactly two levels") + return _evaluate_cage(build_cage(prepared), prepared) +_MUST_AFFECT = ( + ("left.r_y", "hips.left.r_y"), ("right.r_y", "hips.right.r_y"), ("lower_pelvis.L_y", "stations.lower_pelvis.C.y"), ("lower_pelvis.C_z", "stations.lower_pelvis.C.z"), ("left.r_x", "hips.left.r_x"), ("right.r_x", "hips.right.r_x"), + ("lower_pelvis.R_x", "stations.lower_pelvis.rL"), ("left.r_z", "hips.left.r_z"), ("right.r_z", "hips.right.r_z"), ("lower_pelvis.R_f", "stations.lower_pelvis.rA"), ("lower_pelvis.R_b", "stations.lower_pelvis.rP"), + ("left.thigh_start_x", "hips.left.P_s.x"), ("left.thigh_start_y", "hips.left.P_s.y"), ("left.thigh_start_z", "hips.left.P_s.z"), ("right.thigh_start_x", "hips.right.P_s.x"), ("right.thigh_start_y", "hips.right.P_s.y"), ("right.thigh_start_z", "hips.right.P_s.z"), + ("neck_collar.C_y", "stations.neck_collar.C.y"), ("neck_collar.rL", "stations.neck_collar.rL"), ("neck_upper.C_y", "stations.neck_upper.C.y"), ("neck_upper.rL", "stations.neck_upper.rL"), + ("left.axilla_x", "shoulders.left.axilla.x"), ("left.axilla_y", "shoulders.left.axilla.y"), ("right.axilla_x", "shoulders.right.axilla.x"), ("right.axilla_y", "shoulders.right.axilla.y"), ("left.peak_y", "shoulders.left.peak.y"), ("right.peak_y", "shoulders.right.peak.y"), + ("left.start_lateral", "shoulders.left.start_lateral"), ("right.start_lateral", "shoulders.right.start_lateral"), ("left.start_up", "shoulders.left.start_up"), ("right.start_up", "shoulders.right.start_up"), + ("left.shoulder_depth", "shoulders.left.shoulder_depth"), ("right.shoulder_depth", "shoulders.right.shoulder_depth")) +MUST_AFFECT_PARAMETER_IDS = tuple(parameter for parameter, _ in _MUST_AFFECT) +MUST_AFFECT_COMPONENTS = dict(_MUST_AFFECT) +_MUST_AFFECT_PATHS = {parameter: tuple("xyz".index(axis) if len(axis) == 1 and axis in "xyz" else axis for axis in component.split(".")) for parameter, component in _MUST_AFFECT} +_PERTURBATION_DELTA = float.fromhex("0x1.47ae147ae147bp-7") +PERTURBATION_DELTA_M = _PERTURBATION_DELTA +def _path_get(value, path): + for key in path: value = value[key] + return value +def _path_set(value, path, replacement): _path_get(value, path[:-1])[path[-1]] = replacement +def _admit_surface_prepared(prepared): + try: + prepared_projection.validate_prepared(prepared); return prepared + except prepared_projection.PreparedProjectionError: + canonical = prepared_projection.prepare_standard_neutral(); canonical_bytes = prepared_projection.canonical_json_bytes(canonical); matches = 0 + for path in _MUST_AFFECT_PATHS.values(): + try: + baseline, candidate = _path_get(canonical, path), _path_get(prepared, path) + if type(candidate) is not float or candidate != float(baseline + _PERTURBATION_DELTA): continue + restored = copy.deepcopy(prepared); _path_set(restored, path, baseline); matches += prepared_projection.canonical_json_bytes(restored) == canonical_bytes + except (KeyError, IndexError, TypeError, ValueError, OverflowError): continue + if matches != 1: raise + return prepared +def _surface_prepared_candidates(): + canonical = prepared_projection.prepare_standard_neutral(); yield canonical + for path in _MUST_AFFECT_PATHS.values(): + candidate = copy.deepcopy(canonical); baseline = _path_get(candidate, path); _path_set(candidate, path, float(baseline + _PERTURBATION_DELTA)); yield candidate +def _infer_surface_prepared(cage): + if type(cage) is not Mesh: raise ValueError("prepared inference requires an L0 cage") + matches = [] + for candidate in _surface_prepared_candidates(): + try: _validate_cage_lineage(cage, candidate) + except (ValueError, TypeError, IndexError): continue + matches.append(candidate) + if len(matches) != 1: raise ValueError("L0 cage does not identify exactly one frozen prepared input") + return matches[0] +def perturb_prepared(prepared, parameter_id): + if type(parameter_id) is not str or parameter_id not in _MUST_AFFECT_PATHS: raise ValueError("parameter_id is not one of the 33 frozen must-affect parameters") + prepared_projection.validate_prepared(prepared); path = _MUST_AFFECT_PATHS[parameter_id]; component = MUST_AFFECT_COMPONENTS[parameter_id]; baseline = _path_get(prepared, path) + if type(baseline) is not float or not isfinite(baseline): raise ValueError(f"{component} is not binary64") + candidate = copy.deepcopy(prepared); changed = float(baseline + _PERTURBATION_DELTA); _path_set(candidate, path, changed) + if _path_get(candidate, path) != changed: raise ValueError("perturbation did not change its selected component") + restored = copy.deepcopy(candidate); _path_set(restored, path, baseline) + if prepared_projection.canonical_json_bytes(restored) != prepared_projection.canonical_json_bytes(prepared): raise ValueError("perturbation changed more than its selected component") + return candidate +def build_perturbed_cage(prepared, parameter_id): return _build_cage_admitted(perturb_prepared(prepared, parameter_id)) +def evaluate_perturbation(prepared, parameter_id, levels=2): + if type(levels) is not int or levels != 2: raise ValueError("the frozen surface evaluates exactly two levels") + candidate = perturb_prepared(prepared, parameter_id); return _evaluate_cage(_build_cage_admitted(candidate), candidate) +evaluate_perturbed = evaluate_perturbation +@dataclass(frozen=True) +class _Dual: + value: float + derivative: Fraction + def __add__(self, other): return _Dual(self.value + _value(other), self.derivative + _derivative(other)) + def __radd__(self, other): return self + other + def __sub__(self, other): return _Dual(self.value - _value(other), self.derivative - _derivative(other)) + def __rsub__(self, other): return _Dual(_value(other) - self.value, _derivative(other) - self.derivative) + def __mul__(self, other): return _Dual(self.value * _value(other), self.derivative * _rational(_value(other)) + _rational(self.value) * _derivative(other)) + def __rmul__(self, other): return self * other + def __truediv__(self, other): return _Dual(self.value / _value(other), (self.derivative * _rational(_value(other)) - _rational(self.value) * _derivative(other)) / (_rational(_value(other)) ** 2)) + def __rtruediv__(self, other): return _Dual(_value(other) / self.value, (_derivative(other) * _rational(self.value) - _rational(_value(other)) * self.derivative) / (_rational(self.value) ** 2)) + def __abs__(self): return _Dual(abs(self.value), self.derivative if self.value > 0 else -self.derivative if self.value < 0 else 0.0) +def _value(x): return x.value if isinstance(x, _Dual) else x +def _derivative(x): return x.derivative if isinstance(x, _Dual) else Fraction(0) +def _analytic_components(prepared): + source = {record["prepared_component"] for record in prepared_projection.source_binding_records()}; formula = {dependency for control in CONTROL_IDS for dependency in _formula_for_control(prepared, control)[1]} + if not formula <= source: raise ValueError("formula authority names a component outside frozen source bindings") + return formula +def analytic_control_derivatives(prepared, component): + _admit_surface_prepared(prepared) + if component not in _analytic_components(prepared): raise ValueError(f"unknown prepared component: {component}") + dual = copy.deepcopy(prepared); parts = component.split("/") if "/" in component else component.split("."); leaf = parts[-1] + if leaf in "xyz" and len(parts) >= 2: + target = dual + for part in parts[:-2]: target = target[part] + vector = list(target[parts[-2]]); vector["xyz".index(leaf)] = _Dual(vector["xyz".index(leaf)], Fraction(1)); target[parts[-2]] = tuple(vector) + else: + target = dual + for part in parts[:-1]: target = target[part] + target[leaf] = _Dual(target[leaf], Fraction(1)) + result = [] + for control in CONTROL_IDS: + _, _, point, _ = _formula_for_control(dual, control); result.append(tuple(_derivative(x) for x in point)) + return tuple(result) +def _propagate_values(mesh, values, level): return _subdivide_once(mesh, level, values).vertices +def propagate_derivative(mesh, derivatives, level=2): + if len(derivatives) != len(mesh.vertices): raise ValueError("derivative vector count mismatch") + result, current = tuple(tuple(_rational(x) for x in p) for p in derivatives), mesh + for target in range(mesh.level + 1, level + 1): result = _propagate_values(current, result, target); current = subdivide(current, target) + return result +def predicted_support(prepared, component): cage = build_cage(prepared); derivative = analytic_control_derivatives(prepared, component); level2 = propagate_derivative(cage, derivative, 2); return tuple(i for i, point in enumerate(level2) if any(value != 0.0 for value in point)) +analytic_derivative_support = predicted_support +causal_support = predicted_support +validate_topology, build_surface = validate_catalogs, build_cage +__all__ = ["CELL_CATALOG", "CONTROL_BY_COORDINATE", "CONTROL_DOMAIN_INCIDENTS", "CONTROL_IDS", "CONTROL_JUNCTION_INCIDENTS", "CONTROL_OWNERS", "COORDINATE_BY_CONTROL", "DOMAINS", "EDGE_RECORDS", "FACE_CATALOG", "FACE_RECORDS", "FORMULAS", "JUNCTIONS", "JUNCTION_INFO", "JUNCTION_TRACES", "MUST_AFFECT_COMPONENTS", "MUST_AFFECT_PARAMETER_IDS", "PERTURBATION_DELTA_M", "PORTS", "PORT_INFO", "SPECIAL_CASE_IDS", "Mesh", "SurfaceEvaluation", "analytic_control_derivatives", "analytic_derivative_support", "build_cage", "build_perturbed_cage", "causal_support", "evaluate", "evaluate_perturbation", "evaluate_perturbed", "formula_candidate_records", "junction_trace_inputs", "level_topology", "perturb_prepared", "predicted_support", "propagate_derivative", "propagate_junction_tags", "propagate_port_loops", "subdivide", "subdivision_incidence", "symbolic_topology", "topology_incidence", "validate_catalogs", "validate_evaluation", "validate_level_structure"] diff --git a/experiments/owned-root-assembly-successor/prepared_projection.py b/experiments/owned-root-assembly-successor/prepared_projection.py index 6b0db20..d41eb45 100644 --- a/experiments/owned-root-assembly-successor/prepared_projection.py +++ b/experiments/owned-root-assembly-successor/prepared_projection.py @@ -3,6 +3,7 @@ import math from functools import wraps from pathlib import Path +from types import MappingProxyType import artifact_serialization as artifacts @@ -42,43 +43,23 @@ class PreparedProjectionError(ValueError): _SOURCE_DOCUMENT = "stylized_digitigrade_biped_authored_form" _SOURCE_CONTRACT = (("family", "creature-kernel.body"), ("revision", 1)) _SOURCE_IDENTITY = (("document", _SOURCE_DOCUMENT), ("namespace", "main")) -PARTS = (("pelvis", None), ("torso", None), ("neck", None), ("upper_arm", "left"), ("upper_arm", "right"), - ("thigh", "left"), ("thigh", "right")) -STATIONS = (("lower_pelvis", "pelvis", "form_torso_profile_lower_pelvis"), - ("upper_pelvis", "pelvis", "form_torso_profile_upper_pelvis"), - ("lower_abdomen", "torso", "form_torso_profile_lower_abdomen"), - ("waist_abdomen", "torso", "form_torso_profile_waist_abdomen"), - ("upper_abdomen", "torso", "form_torso_profile_upper_abdomen"), - ("lower_ribcage", "torso", "form_torso_profile_lower_ribcage"), - ("upper_ribcage_shoulder", "torso", "form_torso_profile_upper_ribcage_shoulder"), - ("neck_collar", "neck", "form_head_neck_profile_neck_collar"), +PARTS = (("pelvis", None), ("torso", None), ("neck", None), ("upper_arm", "left"), ("upper_arm", "right"), ("thigh", "left"), ("thigh", "right")) +STATIONS = (("lower_pelvis", "pelvis", "form_torso_profile_lower_pelvis"), ("upper_pelvis", "pelvis", "form_torso_profile_upper_pelvis"), + ("lower_abdomen", "torso", "form_torso_profile_lower_abdomen"), ("waist_abdomen", "torso", "form_torso_profile_waist_abdomen"), + ("upper_abdomen", "torso", "form_torso_profile_upper_abdomen"), ("lower_ribcage", "torso", "form_torso_profile_lower_ribcage"), + ("upper_ribcage_shoulder", "torso", "form_torso_profile_upper_ribcage_shoulder"), ("neck_collar", "neck", "form_head_neck_profile_neck_collar"), ("neck_upper", "neck", "form_head_neck_profile_neck_upper")) -SHOULDER_DIMS = (("start_lateral", "form_arm_profile_upper_arm_start_lateral_radius"), - ("start_up", "form_arm_profile_upper_arm_start_up_radius"), - ("start_forward", "form_arm_profile_upper_arm_start_forward_radius"), - ("shoulder_depth", "form_shoulder_depth_radius")) -HIP_DIMS = (("r_x", "form_leg_profile_thigh_start_lateral_radius"), ("r_y", "form_leg_profile_thigh_start_up_radius"), - ("r_z", "form_leg_profile_thigh_start_forward_radius")) +SHOULDER_DIMS = (("start_lateral", "form_arm_profile_upper_arm_start_lateral_radius"), ("start_up", "form_arm_profile_upper_arm_start_up_radius"), + ("start_forward", "form_arm_profile_upper_arm_start_forward_radius"), ("shoulder_depth", "form_shoulder_depth_radius")) +HIP_DIMS = (("r_x", "form_leg_profile_thigh_start_lateral_radius"), ("r_y", "form_leg_profile_thigh_start_up_radius"), ("r_z", "form_leg_profile_thigh_start_forward_radius")) SHOULDER_SUMS = (("axilla", "form_axilla"), ("peak", "form_shoulder_peak"), ("arm_origin", None)) HIP_SUMS = (("P_s", "form_leg_profile_thigh_start"),) -SIDE_CONFIGS = (("shoulders", "upper_arm", (("axilla", "form_axilla", "form_shoulder_control"), - ("peak", "form_shoulder_peak", "form_shoulder_control")), SHOULDER_DIMS), +SIDE_CONFIGS = (("shoulders", "upper_arm", (("axilla", "form_axilla", "form_shoulder_control"), ("peak", "form_shoulder_peak", "form_shoulder_control")), SHOULDER_DIMS), ("hips", "thigh", (("P_s", "form_leg_profile_thigh_start", "form_leg_profile_control"),), HIP_DIMS)) -BODY_COUNTS = {"attachments": 1, "capabilities": 3, "dimensions": 153, "fields": 0, - "frames": 16, "joints": 17, "landmarks": 43, "modules": 1, - "parts": 18, "regions": 4, "sockets": 2} -SOURCE_ROW_FIELDS = {"dimensions": {"owner", "role", "value"}, "frames": {"owner", "role", "transform"}, - "landmarks": {"frame", "owner", "position", "role"}} -PROFILE_IDS = ("standard_neutral_reference", "compact_broad_short_limb_large_head", - "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested") -PROFILE_DIMENSION_KEYS = frozenset(( # noqa: SIM905 -- compact frozen key universe - "arm_profile_forward arm_profile_lateral arm_profile_up arm_radius arm_shoulder body_extent_x " - "body_extent_y body_extent_z body_profile_depth body_profile_lateral foot_extent_x foot_extent_y " - "foot_extent_z foot_profile_forward foot_profile_lateral foot_profile_up hand_extent_x hand_extent_y " - "hand_extent_z head_extent_x head_extent_y head_extent_z head_profile_forward head_profile_lateral " - "head_profile_up leg_profile_forward leg_profile_lateral leg_profile_up leg_radius neck_profile_forward " - "neck_profile_lateral neck_profile_up neck_radius tail_root_end tail_root_start tail_tip_end tail_tip_start" -).split()) +BODY_COUNTS = {"attachments": 1, "capabilities": 3, "dimensions": 153, "fields": 0, "frames": 16, "joints": 17, "landmarks": 43, "modules": 1, "parts": 18, "regions": 4, "sockets": 2} +SOURCE_ROW_FIELDS = {"dimensions": {"owner", "role", "value"}, "frames": {"owner", "role", "transform"}, "landmarks": {"frame", "owner", "position", "role"}} +PROFILE_IDS = ("standard_neutral_reference", "compact_broad_short_limb_large_head", "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested") +PROFILE_DIMENSION_KEYS = frozenset("""arm_profile_forward arm_profile_lateral arm_profile_up arm_radius arm_shoulder body_extent_x body_extent_y body_extent_z body_profile_depth body_profile_lateral foot_extent_x foot_extent_y foot_extent_z foot_profile_forward foot_profile_lateral foot_profile_up hand_extent_x hand_extent_y hand_extent_z head_extent_x head_extent_y head_extent_z head_profile_forward head_profile_lateral head_profile_up leg_profile_forward leg_profile_lateral leg_profile_up leg_radius neck_profile_forward neck_profile_lateral neck_profile_up neck_radius tail_root_end tail_root_start tail_tip_end tail_tip_start""".split()) # noqa: SIM905 _ADDRESS, _B64, _PB64 = object(), ("binary64", False), ("binary64", True) _IDENTITY_SPEC = {"path": str, "sha256": str} _PART_SPEC = {"address": _ADDRESS, "placement": { @@ -98,39 +79,47 @@ class PreparedProjectionError(ValueError): "hips": {side: _HIP_SPEC for side in ("left", "right")}, "provenance": {"source_files": ("list", 2, {"path": str, "sha256": str, "bytes": int})}, } -def _public_admission(function): +def _freeze(value): + if type(value) is dict: return MappingProxyType({key: _freeze(item) for key, item in value.items()}) + if type(value) is set: return frozenset(value) + if type(value) is tuple: return tuple(_freeze(item) for item in value) + return value +_COMMITMENTS = _freeze({ + "admission": {"roles": _ROLES, "paths": _PATHS, "hashes": _HASHES, "sizes": _SIZES, "binding_hashes": _BINDING_HASHES, "sidecar": _SIDECAR_CONTENT}, + "semantic": {"schema": _PREPARED_SCHEMA, "neutral_profile": _NEUTRAL_PROFILE, "rotation": _ROTATION, "axes": _AXES, "basis": _BASIS_ITEMS, "source_document": _SOURCE_DOCUMENT, "source_contract": _SOURCE_CONTRACT, + "source_identity": _SOURCE_IDENTITY, "parts": PARTS, "stations": STATIONS, "shoulder_dims": SHOULDER_DIMS, "hip_dims": HIP_DIMS, "shoulder_sums": SHOULDER_SUMS, "hip_sums": HIP_SUMS, + "side_configs": SIDE_CONFIGS, "body_counts": BODY_COUNTS, "source_row_fields": SOURCE_ROW_FIELDS, "profile_ids": PROFILE_IDS, "profile_dimension_keys": PROFILE_DIMENSION_KEYS, "address_marker": _ADDRESS}, + "prepared_spec": _PREPARED_SPEC, + "operations": {"json_bytes": _JSON_BYTES, "decode_json": _DECODE_JSON, "coerce_binary64": _COERCE_BINARY64, "read_file": _READ_FILE, "sha256_bytes": _SHA256_BYTES, "serialization_error": artifacts.ArtifactSerializationError, + "loads": json.loads, "source_json_errors": (UnicodeDecodeError, json.JSONDecodeError, RecursionError, TypeError, ValueError), "isfinite": math.isfinite, "path_type": Path, "error": PreparedProjectionError}, +}) +def _public_admission(function, _error=_COMMITMENTS["operations"]["error"]): @wraps(function) def guarded(*args, **kwargs): - try: - return function(*args, **kwargs) - except PreparedProjectionError: - raise - except Exception as exc: - raise PreparedProjectionError(f"{function.__name__}: malformed admission") from exc + try: return function(*args, **kwargs) + except _error: raise + except Exception as exc: raise _error(f"{function.__name__}: malformed admission") from exc return guarded -def _need(test, where, message): - if not test: - raise PreparedProjectionError(f"{where}: {message}") +def _need(test, where, message, _error=_COMMITMENTS["operations"]["error"]): + if not test: raise _error(f"{where}: {message}") def _obj(value, where): _need(type(value) is dict, where, "expected object") return value def _keys(value, expected, where): _obj(value, where) - valid = all(type(key) is str for key in value) and set(value) == set(expected) - _need(valid, where, "unknown, missing, or non-string field") + _need(all(type(key) is str for key in value) and set(value) == set(expected), where, "unknown, missing, or non-string field") return value def _text(value, where, nonempty=True): _need(type(value) is str and (value or not nonempty), where, "expected string") return value def _literal(value, expected, where): _need(type(value) is type(expected) and value == expected, where, "wrong value") -def _attempt(function, args, caught, where, message, kwargs=None): - try: - return function(*args, **(kwargs or {})) - except caught as exc: - raise PreparedProjectionError(f"{where}: {message}") from exc -def _number(value, where, *, runtime=False, positive=False, wire=False): +def _attempt(function, args, caught, where, message, kwargs=None, _error=_COMMITMENTS["operations"]["error"]): + try: return function(*args, **(kwargs or {})) + except caught as exc: raise _error(f"{where}: {message}") from exc +def _number(value, where, *, runtime=False, positive=False, wire=False, _c=_COMMITMENTS): + operations = _c["operations"] if wire: - result = _attempt(_COERCE_BINARY64, (value,), artifacts.ArtifactSerializationError, + result = _attempt(operations["coerce_binary64"], (value,), operations["serialization_error"], where, "invalid canonical binary64", {"label": where}) elif runtime: _need(type(value) is float, where, "expected runtime binary64 float") @@ -139,154 +128,136 @@ def _number(value, where, *, runtime=False, positive=False, wire=False): _need(type(value) in (int, float), where, "expected finite number") result = _attempt(float, (value,), (OverflowError, ValueError), where, "expected finite number") label = "positive " if positive else "" - _need(math.isfinite(result) and (not positive or result > 0.0), where, f"expected finite {label}number") + _need(operations["isfinite"](result) and (not positive or result > 0.0), where, f"expected finite {label}number") return result def _vector(value, where, length=3, *, runtime=False, wire=False): _need(type(value) is list and len(value) == length, where, f"expected {length}-vector") return [_number(item, f"{where}[{i}]", runtime=runtime, wire=wire) for i, item in enumerate(value)] def _pairs(items): result = dict(items) - if len(result) != len(items): - raise ValueError("duplicate JSON key") + if len(result) != len(items): raise ValueError("duplicate JSON key") return result def _constant(token): raise ValueError(f"non-finite JSON constant {token}") -def _decode_source_json(raw, where): +def _decode_source_json(raw, where, _c=_COMMITMENTS): _need(type(raw) is bytes, where, "expected raw bytes") - caught = (UnicodeDecodeError, json.JSONDecodeError, RecursionError, TypeError, ValueError) + operations, caught = _c["operations"], _c["operations"]["source_json_errors"] text = _attempt(raw.decode, ("utf-8",), caught, where, "source is not strict UTF-8 JSON") - value = _attempt(json.loads, (text,), caught, where, "source is not strict UTF-8 JSON", - {"object_pairs_hook": _pairs, "parse_constant": _constant}) - return _obj(value, where), _SHA256_BYTES(raw) -def _read(path, where): return _attempt(_READ_FILE, (path,), (OSError, TypeError, ValueError), where, "read failed") -def _fixed_path(path, expected, where): - candidate = _attempt(Path, (path,), (TypeError, ValueError), where, "invalid path").absolute() + value = _attempt(operations["loads"], (text,), caught, where, "source is not strict UTF-8 JSON", {"object_pairs_hook": _pairs, "parse_constant": _constant}) + return _obj(value, where), operations["sha256_bytes"](raw) +def _read(path, where, _reader=_COMMITMENTS["operations"]["read_file"]): return _attempt(_reader, (path,), (OSError, TypeError, ValueError), where, "read failed") +def _fixed_path(path, expected, where, _path_type=_COMMITMENTS["operations"]["path_type"]): + candidate = _attempt(_path_type, (path,), (TypeError, ValueError), where, "invalid path").absolute() _need(candidate == expected, where, "path is not the fixed canonical path") _need(not candidate.is_symlink() and candidate.is_file(), where, "expected regular file") return candidate @_public_admission def normalize_source_address(raw): value = _keys(raw, {"namespace", "anchors", "kind", "role"}, "source address") - for key in ("namespace", "kind", "role"): - _text(value[key], f"source address.{key}") + for key in ("namespace", "kind", "role"): _text(value[key], f"source address.{key}") anchors = value["anchors"] _need(type(anchors) is list and all(type(item) is str for item in anchors), "source anchors", "invalid array") return [value["namespace"], list(anchors), value["kind"], value["role"]] -def _address(raw): - value = normalize_source_address(raw) +def _address(raw, _normalize=normalize_source_address): + value = _normalize(raw) return value[0], tuple(value[1]), value[2], value[3] def _runtime_address(value, where): _need(type(value) is list and len(value) == 4, where, "expected normalized address") namespace, anchors, kind, role = value _text(namespace, f"{where}[0]") _need(type(anchors) is list and all(type(item) is str for item in anchors), f"{where}[1]", "invalid anchors") - _text(kind, f"{where}[2]") - _text(role, f"{where}[3]") + _text(kind, f"{where}[2]"); _text(role, f"{where}[3]") return namespace, tuple(anchors), kind, role def _a(role, side=None): return "main", () if side is None else (side,), "part", role def _address_json(value): return [value[0], list(value[1]), value[2], value[3]] def _add(left, right): return [left[index] + right[index] for index in range(3)] -def _source_transform(raw, where, *, zero_translation=False): +def _source_transform(raw, where, *, zero_translation=False, _rotation=_COMMITMENTS["semantic"]["rotation"]): transform = _keys(raw, {"translation", "rotation_xyzw"}, where) - translation = _vector(transform["translation"], f"{where}.translation") - rotation = _vector(transform["rotation_xyzw"], f"{where}.rotation_xyzw", 4) - _need(tuple(rotation) == _ROTATION, where, "rotation must be exact identity") - _need(not zero_translation or translation == [0.0, 0.0, 0.0], where, "frame translation must be zero") + translation = _vector(transform["translation"], f"{where}.translation"); rotation = _vector(transform["rotation_xyzw"], f"{where}.rotation_xyzw", 4) + _need(tuple(rotation) == _rotation, where, "rotation must be exact identity"); _need(not zero_translation or translation == [0.0, 0.0, 0.0], where, "frame translation must be zero") return translation -def _validate_selector_rows(rows, name): +def _validate_selector_rows(rows, name, _fields=_COMMITMENTS["semantic"]["source_row_fields"]): selectors, frame_references = {}, set() for index, raw in enumerate(rows): - where = f"body.{name}[{index}]" - row = _keys(raw, SOURCE_ROW_FIELDS[name], where) - owner = _address(row["owner"]) - role = _text(row["role"], f"{where}.role") + where = f"body.{name}[{index}]"; row = _keys(raw, _fields[name], where) + owner = _address(row["owner"]); role = _text(row["role"], f"{where}.role") _need((owner, role) not in selectors, where, "duplicate selector") selectors[owner, role] = row, index - if name == "dimensions": - _number(row["value"], f"{where}.value", positive=True) - elif name == "frames": - _source_transform(row["transform"], f"{where}.transform", zero_translation=True) + if name == "dimensions": _number(row["value"], f"{where}.value", positive=True) + elif name == "frames": _source_transform(row["transform"], f"{where}.transform", zero_translation=True) else: frame = _keys(row["frame"], {"owner", "role"}, f"{where}.frame") frame_owner = _address(frame["owner"]) - frame_role = _text(frame["role"], f"{where}.frame.role") - _need(frame_owner == owner, f"{where}.frame", "wrong frame owner") - frame_references.add((frame_owner, frame_role)) - _vector(row["position"], f"{where}.position") + frame_role = _text(frame["role"], f"{where}.frame.role"); _need(frame_owner == owner, f"{where}.frame", "wrong frame owner") + frame_references.add((frame_owner, frame_role)); _vector(row["position"], f"{where}.position") return selectors, frame_references def _fixed_scalars(value, items, where): record = _keys(value, {key for key, _ in items}, where) for key, expected in items: _literal(record[key], expected, f"{where}.{key}") -def _validate_source_document(source): +def _validate_source_document(source, _semantic=_COMMITMENTS["semantic"]): _keys(source, {"contract", "source", "basis", "profiles", "body", "extensions"}, "source") - _fixed_scalars(source["contract"], _SOURCE_CONTRACT, "source.contract") + _fixed_scalars(source["contract"], _semantic["source_contract"], "source.contract") identity = _obj(source["source"], "source.source") _keys(identity, {"document", "namespace", "dependencies"}, "source.source") - for key, expected in _SOURCE_IDENTITY: + for key, expected in _semantic["source_identity"]: _literal(identity[key], expected, f"source.source.{key}") _need(type(identity["dependencies"]) is list and not identity["dependencies"], "source.dependencies", "not empty") - _fixed_scalars(source["basis"], _BASIS_ITEMS, "source.basis") + _fixed_scalars(source["basis"], _semantic["basis"], "source.basis") _fixed_scalars(source["profiles"], (("semantic_numeric", "ck.numeric-frame.r1"),), "source.profiles") _need(type(source["extensions"]) is list and not source["extensions"], "source.extensions", "not empty") body = _obj(source["body"], "source.body") - _keys(body, BODY_COUNTS, "source.body") - valid_counts = all(type(body[name]) is list and len(body[name]) == count for name, count in BODY_COUNTS.items()) + _keys(body, _semantic["body_counts"], "source.body") + valid_counts = all(type(body[name]) is list and len(body[name]) == count for name, count in _semantic["body_counts"].items()) _need(valid_counts, "source.body", "wrong required record counts") parts = {} for index, raw in enumerate(body["parts"]): - where = f"body.parts[{index}]" - row = _keys(raw, {"address", "containment", "placement"}, where) - address = _address(row["address"]) - _need(address not in parts, where, "duplicate part address") + where = f"body.parts[{index}]"; row = _keys(raw, {"address", "containment", "placement"}, where) + address = _address(row["address"]); _need(address not in parts, where, "duplicate part address") _source_transform(row["placement"], f"{where}.placement") _obj(row["containment"], f"{where}.containment") parts[address] = row, index - dimensions, _ = _validate_selector_rows(body["dimensions"], "dimensions") - frames, _ = _validate_selector_rows(body["frames"], "frames") + dimensions, _ = _validate_selector_rows(body["dimensions"], "dimensions"); frames, _ = _validate_selector_rows(body["frames"], "frames") landmarks, references = _validate_selector_rows(body["landmarks"], "landmarks") _need(references <= set(frames), "source.body.landmarks", "missing referenced frame") return parts, frames, landmarks, dimensions -def _admit_source_bytes(raw): +def _admit_source_bytes(raw, _admission=_COMMITMENTS["admission"]): source, digest = _decode_source_json(raw, "source") - _need(len(raw) == _SIZES[2] and digest == _HASHES[1], "source", "source identity mismatch") + _need(len(raw) == _admission["sizes"][2] and digest == _admission["hashes"][1], "source", "source identity mismatch") parts, frames, landmarks, dimensions = _validate_source_document(source) return {"parts": parts, "frames": frames, "landmarks": landmarks, "dimensions": dimensions, "bytes": raw, "sha256": digest} -def _validate_profile_table(table): +def _validate_profile_table(table, _c=_COMMITMENTS): + admission, semantic = _c["admission"], _c["semantic"] _keys(table, {"base_source", "canonicalization", "format", "profiles", "transform"}, "profile table") _literal(table["format"], "creature-kernel.disposable-structural-profile-candidates.v1", "profile table.format") - _fixed_scalars(table["base_source"], (("document", _SOURCE_DOCUMENT), ("namespace", "main"), - ("path", _ROLES[1]), ("sha256", _HASHES[1]), - ), "profile table.base_source") + _fixed_scalars(table["base_source"], (("document", semantic["source_document"]), ("namespace", "main"), ("path", admission["roles"][1]), ("sha256", admission["hashes"][1])), "profile table.base_source") profiles = table["profiles"] - _need(type(profiles) is list and len(profiles) == len(PROFILE_IDS), "profile profiles", "wrong count") + _need(type(profiles) is list and len(profiles) == len(semantic["profile_ids"]), "profile profiles", "wrong count") for index, raw in enumerate(profiles): - where = f"profile table.profiles[{index}]" - row = _keys(raw, {"dimension_scales", "id", "label", "part_placements"}, where) - _literal(row["id"], PROFILE_IDS[index], f"{where}.id") - _text(row["label"], f"{where}.label") - scales = _obj(row["dimension_scales"], f"{where}.dimension_scales") - _keys(scales, PROFILE_DIMENSION_KEYS, f"{where}.dimension_scales") + where = f"profile table.profiles[{index}]"; row = _keys(raw, {"dimension_scales", "id", "label", "part_placements"}, where) + _literal(row["id"], semantic["profile_ids"][index], f"{where}.id"); _text(row["label"], f"{where}.label") + scales = _obj(row["dimension_scales"], f"{where}.dimension_scales"); _keys(scales, semantic["profile_dimension_keys"], f"{where}.dimension_scales") _need(all(type(number) is int and number > 0 for number in scales.values()), where, "invalid profile scale") _need(index != 0 or all(number == 1000 for number in scales.values()), where, "neutral scales differ") _obj(row["part_placements"], f"{where}.part_placements") return profiles[0] -def _admit_profile_bytes(raw): +def _admit_profile_bytes(raw, _admission=_COMMITMENTS["admission"]): table, digest = _decode_source_json(raw, "profile table") - _need(len(raw) == _SIZES[3] and digest == _HASHES[2], "profile table", "profile identity mismatch") + _need(len(raw) == _admission["sizes"][3] and digest == _admission["hashes"][2], "profile table", "profile identity mismatch") return _validate_profile_table(table), raw, digest -def _verify_contract(path=_PATHS[0]): - contract = _fixed_path(path, _PATHS[0], "contract path") - sidecar = _fixed_path(_PATHS[1], _PATHS[1], "contract sidecar path") +def _verify_contract(path=_PATHS[0], _c=_COMMITMENTS): + _admission, operations = _c["admission"], _c["operations"] + paths, hashes, sizes = _admission["paths"], _admission["hashes"], _admission["sizes"] + contract = _fixed_path(path, paths[0], "contract path") + sidecar = _fixed_path(paths[1], paths[1], "contract sidecar path") contract_raw, sidecar_raw = _read(contract, "contract"), _read(sidecar, "contract sidecar") - _need(len(contract_raw) == _SIZES[0] and _SHA256_BYTES(contract_raw) == _HASHES[0], "contract", "identity mismatch") - _need(len(sidecar_raw) == _SIZES[1] and sidecar_raw == _SIDECAR_CONTENT, "contract sidecar", "identity mismatch") -def _fixed_inputs(source_path, contract_path, profile_path): + _need(len(contract_raw) == sizes[0] and operations["sha256_bytes"](contract_raw) == hashes[0], "contract", "identity mismatch") + _need(len(sidecar_raw) == sizes[1] and sidecar_raw == _admission["sidecar"], "contract sidecar", "identity mismatch") +def _fixed_inputs(source_path, contract_path, profile_path, _admission=_COMMITMENTS["admission"]): + paths = _admission["paths"] _verify_contract(contract_path) - source = _fixed_path(source_path, _PATHS[2], "source path") - profile = _fixed_path(profile_path, _PATHS[3], "profile table path") - admission = _admit_source_bytes(_read(source, "source")) - selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")) + source = _fixed_path(source_path, paths[2], "source path"); profile = _fixed_path(profile_path, paths[3], "profile table path") + admission = _admit_source_bytes(_read(source, "source")); selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")) return admission, selected, raw, digest def _select(rows, owner, role, name): match = rows.get((owner, role)) @@ -296,130 +267,101 @@ def _world(parts, chain): _need(chain and all(owner in parts for owner in chain), "world translation", "invalid chain") result = [0.0, 0.0, 0.0] for owner in chain: - placement = parts[owner][0]["placement"] - result = _add(result, _vector(placement["translation"], "part placement.translation")) + placement = parts[owner][0]["placement"]; result = _add(result, _vector(placement["translation"], "part placement.translation")) return result def _select_position(admission, owner, role, frame_role, worlds): row, index = _select(admission["landmarks"], owner, role, "landmarks") frame = _keys(row["frame"], {"owner", "role"}, f"body.landmarks[{index}].frame") - _need(_address(frame["owner"]) == owner and frame["role"] == frame_role, - f"body.landmarks[{index}].frame", "wrong landmark frame") + _need(_address(frame["owner"]) == owner and frame["role"] == frame_role, f"body.landmarks[{index}].frame", "wrong landmark frame") _select(admission["frames"], owner, frame_role, "frames") - position = _vector(row["position"], f"body.landmarks[{index}].position") - return _add(worlds[owner], position) + position = _vector(row["position"], f"body.landmarks[{index}].position"); return _add(worlds[owner], position) def _dimension(admission, owner, role): row, index = _select(admission["dimensions"], owner, role, "dimensions") return _number(row["value"], f"body.dimensions[{index}].value", positive=True), index -def _source_files(source_digest, source_size, profile_digest, profile_size): - records = ({"path": _ROLES[1], "sha256": source_digest, "bytes": source_size}, - {"path": _ROLES[2], "sha256": profile_digest, "bytes": profile_size}) +def _source_files(source_digest, source_size, profile_digest, profile_size, _roles=_COMMITMENTS["admission"]["roles"]): + records = ({"path": _roles[1], "sha256": source_digest, "bytes": source_size}, {"path": _roles[2], "sha256": profile_digest, "bytes": profile_size}) return sorted(records, key=lambda record: record["path"].encode("utf-8")) def _identity(path, digest): return {"path": path, "sha256": digest} -def _walk(value, spec, where, *, wire): - if spec is str: - return _text(value, where, nonempty=False) - if spec is int: - _need(type(value) is int, where, "expected integer") - return value - if spec is _ADDRESS: - _runtime_address(value, where) - return value - if type(spec) is dict: +def _walk(value, spec, where, *, wire, _c=_COMMITMENTS): + if spec is str: return _text(value, where, nonempty=False) + if spec is int: _need(type(value) is int, where, "expected integer"); return value + if spec is _c["semantic"]["address_marker"]: _runtime_address(value, where); return value + if type(spec) is type(_c["prepared_spec"]): record = _keys(value, spec, where) for field, child_spec in spec.items(): converted = _walk(record[field], child_spec, f"{where}.{field}", wire=wire) - if wire: - record[field] = converted + if wire: record[field] = converted return record kind, argument, *tail = spec - if kind == "binary64": - return _number(value, where, runtime=not wire, positive=argument and not wire, wire=wire) - if kind == "vector": - return _vector(value, where, argument, runtime=not wire, wire=wire) + if kind == "binary64": return _number(value, where, runtime=not wire, positive=argument and not wire, wire=wire) + if kind == "vector": return _vector(value, where, argument, runtime=not wire, wire=wire) _need(kind == "list" and type(value) is list and len(value) == argument, where, "wrong list shape") for index, item in enumerate(value): converted = _walk(item, tail[0], f"{where}[{index}]", wire=wire) - if wire: - value[index] = converted + if wire: value[index] = converted return value -def _validate_prepared_structure(prepared, *, wire=False): return _walk(prepared, _PREPARED_SPEC, "prepared", wire=wire) +def _validate_prepared_structure(prepared, *, wire=False, _spec=_COMMITMENTS["prepared_spec"]): return _walk(prepared, _spec, "prepared", wire=wire) def _validate_prepared_shape(prepared): return _validate_prepared_structure(prepared) def _chains(): pelvis, torso, neck = _a("pelvis"), _a("torso"), _a("neck") result = {pelvis: (pelvis,), torso: (pelvis, torso), neck: (pelvis, torso, neck)} for side in ("left", "right"): - result[_a("upper_arm", side)] = (pelvis, torso, _a("upper_arm", side)) - result[_a("thigh", side)] = (pelvis, _a("thigh", side)) + result[_a("upper_arm", side)] = (pelvis, torso, _a("upper_arm", side)); result[_a("thigh", side)] = (pelvis, _a("thigh", side)) return result -def _part_output(parts, owner): +def _part_output(parts, owner, _rotation=_COMMITMENTS["semantic"]["rotation"]): value = _vector(parts[owner][0]["placement"]["translation"], "part placement.translation") - return {"address": _address_json(owner), "placement": {"translation": value, "rotation_xyzw": list(_ROTATION)}} -def _station_suffixes(role): - return (("lateral_radius", "forward_radius", "forward_radius") if role == "neck" - else ("lateral_radius", "anterior_radius", "posterior_radius")) + return {"address": _address_json(owner), "placement": {"translation": value, "rotation_xyzw": list(_rotation)}} +def _station_suffixes(role): return (("lateral_radius", "forward_radius", "forward_radius") if role == "neck" else ("lateral_radius", "anterior_radius", "posterior_radius")) def _station_output(admission, worlds, role, prefix): owner = _a(role) frame = "form_head_neck_profile_control" if role == "neck" else "form_torso_profile_control" - radii = [_dimension(admission, owner, f"{prefix}_{suffix}")[0] - for suffix in _station_suffixes(role)] - return {"owner": _address_json(owner), "prefix": prefix, - "C": _select_position(admission, owner, prefix, frame, worlds), - "rL": radii[0], "rA": radii[1], "rP": radii[2]} + radii = [_dimension(admission, owner, f"{prefix}_{suffix}")[0] for suffix in _station_suffixes(role)] + return {"owner": _address_json(owner), "prefix": prefix, "C": _select_position(admission, owner, prefix, frame, worlds), "rL": radii[0], "rA": radii[1], "rP": radii[2]} def _side_output(admission, worlds, side, part_role, positions, dimensions): owner = _a(part_role, side) - result = {field: _select_position(admission, owner, role, frame, worlds) - for field, role, frame in positions} - if part_role == "upper_arm": - result["arm_origin"] = list(worlds[owner]) - for field, role in dimensions: - result[field] = _dimension(admission, owner, role)[0] + result = {field: _select_position(admission, owner, role, frame, worlds) for field, role, frame in positions} + if part_role == "upper_arm": result["arm_origin"] = list(worlds[owner]) + for field, role in dimensions: result[field] = _dimension(admission, owner, role)[0] return result -def _build_prepared(admission, profile, profile_raw, profile_digest): +def _build_prepared(admission, profile, profile_raw, profile_digest, _c=_COMMITMENTS): + fixed, semantic = _c["admission"], _c["semantic"] parts, chains = admission["parts"], _chains() worlds = {owner: _world(parts, chain) for owner, chain in chains.items()} - sides = { - group: {side: _side_output(admission, worlds, side, role, positions, dimensions) - for side in ("left", "right")} - for group, role, positions, dimensions in SIDE_CONFIGS - } + sides = {group: {side: _side_output(admission, worlds, side, role, positions, dimensions) for side in ("left", "right")} for group, role, positions, dimensions in semantic["side_configs"]} prepared = { - "schema": _PREPARED_SCHEMA, - "contract": _identity(_ROLES[0], _HASHES[0]), - "source": _identity(_ROLES[1], _HASHES[1]), + "schema": semantic["schema"], "contract": _identity(fixed["roles"][0], fixed["hashes"][0]), "source": _identity(fixed["roles"][1], fixed["hashes"][1]), "profile_selection": { - "profile_id": _NEUTRAL_PROFILE, "profile_table_path": _ROLES[2], - "profile_table_sha256": profile_digest, - "dimensions": {key: float(number) for key, number in profile["dimension_scales"].items()}, + "profile_id": semantic["neutral_profile"], "profile_table_path": fixed["roles"][2], + "profile_table_sha256": profile_digest, "dimensions": {key: float(number) for key, number in profile["dimension_scales"].items()}, }, - "basis": dict(_BASIS_ITEMS), - "parts": [_part_output(parts, _a(role, side)) for role, side in PARTS], - "stations": {n: _station_output(admission, worlds, r, p) for n, r, p in STATIONS}, - "shoulders": sides["shoulders"], - "hips": sides["hips"], - "provenance": {"source_files": _source_files( - admission["sha256"], len(admission["bytes"]), profile_digest, len(profile_raw))}, + "basis": dict(semantic["basis"]), "parts": [_part_output(parts, _a(role, side)) for role, side in semantic["parts"]], + "stations": {n: _station_output(admission, worlds, r, p) for n, r, p in semantic["stations"]}, + "shoulders": sides["shoulders"], "hips": sides["hips"], + "provenance": {"source_files": _source_files(admission["sha256"], len(admission["bytes"]), profile_digest, len(profile_raw))}, } return _validate_prepared_shape(prepared) -@_public_admission -def validate_prepared(prepared): - """Admit only the projection freshly derived from the fixed files.""" - value = _validate_prepared_shape(prepared) - expected = _build_prepared(*_fixed_inputs(_PATHS[2], _PATHS[0], _PATHS[3])) - _need(_JSON_BYTES(value) == _JSON_BYTES(expected), "prepared", "values do not match fixed projection") - return value -@_public_admission -def admit_prepared_bytes(raw): - """Decode and admit exact canonical prepared bytes with schema-aware floats.""" - _need(type(raw) is bytes, "prepared bytes", "expected bytes") - decoded = _attempt(_DECODE_JSON, (raw,), (artifacts.ArtifactSerializationError, RecursionError), - "prepared bytes", "invalid canonical JSON") - value = _validate_prepared_structure(decoded, wire=True) - _need(_JSON_BYTES(value) == raw, "prepared bytes", "coercion changed canonical bytes") - return validate_prepared(value) -@_public_admission -def prepare_standard_neutral(source_path=_PATHS[2], *, contract_path=_PATHS[0], profile_table_path=_PATHS[3]): - """Admit fixed inputs and return the exact standard-neutral object.""" - return _build_prepared(*_fixed_inputs(source_path, contract_path, profile_table_path)) +def _prepared_apis(_c): + fixed, operations = _c["admission"], _c["operations"] + shape, structure, build, inputs, need, attempt = _validate_prepared_shape, _validate_prepared_structure, _build_prepared, _fixed_inputs, _need, _attempt + @_public_admission + def validate_prepared(prepared): + """Admit only the projection freshly derived from the fixed files.""" + value = shape(prepared); expected = build(*inputs(fixed["paths"][2], fixed["paths"][0], fixed["paths"][3])) + need(operations["json_bytes"](value) == operations["json_bytes"](expected), "prepared", "values do not match fixed projection") + return value + @_public_admission + def admit_prepared_bytes(raw): + """Decode and admit exact canonical prepared bytes with schema-aware floats.""" + need(type(raw) is bytes, "prepared bytes", "expected bytes") + decoded = attempt(operations["decode_json"], (raw,), (operations["serialization_error"], RecursionError), "prepared bytes", "invalid canonical JSON") + value = structure(decoded, wire=True); need(operations["json_bytes"](value) == raw, "prepared bytes", "coercion changed canonical bytes") + return validate_prepared(value) + @_public_admission + def prepare_standard_neutral(source_path=fixed["paths"][2], *, contract_path=fixed["paths"][0], profile_table_path=fixed["paths"][3]): + """Admit fixed inputs and return the exact standard-neutral object.""" + return build(*inputs(source_path, contract_path, profile_table_path)) + return validate_prepared, admit_prepared_bytes, prepare_standard_neutral +validate_prepared, admit_prepared_bytes, prepare_standard_neutral = _prepared_apis(_COMMITMENTS) def _pointer(kind, index, axis=None): if kind in {"part", "landmark"}: _need(axis in range(3), "source pointer", "invalid axis") @@ -428,14 +370,14 @@ def _pointer(kind, index, axis=None): return f"/body/{path}/{index}/{field}/{axis}" _need(kind == "dimension" and axis is None, "source pointer", "invalid pointer kind") return f"/body/dimensions/{index}/value" -def _bind(component, derivation, addresses, pointers): - addresses = sorted(set(addresses), key=lambda item: _JSON_BYTES(_address_json(item))) +def _bind(component, derivation, addresses, pointers, _json_bytes=_COMMITMENTS["operations"]["json_bytes"]): + addresses = sorted(set(addresses), key=lambda item: _json_bytes(_address_json(item))) pointers = sorted(set(pointers), key=str.encode) _need(addresses and pointers, "source binding", "empty binding") return {"prepared_component": component, "derivation_id": derivation, "source_addresses": [_address_json(item) for item in addresses], "source_pointers": pointers} -def _validate_binding_records(records): +def _validate_binding_records(records, _c=_COMMITMENTS): _need(type(records) is list and len(records) == 92, "source bindings", "expected 92 records") components = [] for index, raw in enumerate(records): @@ -452,16 +394,17 @@ def _validate_binding_records(records): _text(pointer, f"{where}.source_pointers[{pointer_index}]") _need(len(set(components)) == 92 and components == sorted(components, key=str.encode), "source bindings", "wrong component order or uniqueness") - _need(canonical_json_sha256(components) == _BINDING_HASHES[0], "source bindings", "component universe mismatch") - _need(canonical_json_sha256(records) == _BINDING_HASHES[1], "source bindings", "mapping mismatch") + hashes, operations = _c["admission"]["binding_hashes"], _c["operations"] + _need(operations["sha256_bytes"](operations["json_bytes"](components)) == hashes[0], "source bindings", "component universe mismatch") + _need(operations["sha256_bytes"](operations["json_bytes"](records)) == hashes[1], "source bindings", "mapping mismatch") return records -def _append_sum(bindings, admission, parts, chains, component, owner, landmark_role): +def _append_sum(bindings, admission, parts, chains, component, owner, landmark_role, _axes=_COMMITMENTS["semantic"]["axes"]): chain, landmark_index = chains[owner], None if landmark_role is not None: landmark_index = _select(admission["landmarks"], owner, landmark_role, "landmarks")[1] derivation = ("source.world-landmark-axis-sum.v1" if landmark_role else "source.world-placement-axis-sum.v1") - for axis, name in enumerate(_AXES): + for axis, name in enumerate(_axes): pointers = [_pointer("part", parts[item][1], axis) for item in chain] if landmark_index is not None: pointers.append(_pointer("landmark", landmark_index, axis)) @@ -473,24 +416,29 @@ def _append_group(bindings, admission, parts, chains, prefix, owner, sums, dimen _, index = _dimension(admission, owner, role) bindings.append(_bind(f"{prefix}.{field}", "source.dimension-value.v1", (owner,), (_pointer("dimension", index),))) -@_public_admission -def source_binding_records(source_path=_PATHS[2], *, contract_path=_PATHS[0], profile_table_path=_PATHS[3]): - admission, _, _, _ = _fixed_inputs(source_path, contract_path, profile_table_path) - parts, bindings, chains = admission["parts"], [], _chains() - for name, role, prefix in STATIONS: - owner = _a(role) - dimensions = tuple((field, f"{prefix}_{suffix}") - for field, suffix in zip(("rL", "rA", "rP"), _station_suffixes(role))) - _append_group(bindings, admission, parts, chains, f"stations.{name}", owner, (("C", prefix),), dimensions) - for side in ("left", "right"): - _append_group(bindings, admission, parts, chains, f"shoulders.{side}", - _a("upper_arm", side), SHOULDER_SUMS, SHOULDER_DIMS) - _append_group(bindings, admission, parts, chains, f"hips.{side}", _a("thigh", side), HIP_SUMS, HIP_DIMS) - ordered = sorted(bindings, key=lambda item: item["prepared_component"].encode("utf-8")) - return _validate_binding_records(ordered) +def _binding_api(_c): + fixed, semantic = _c["admission"], _c["semantic"] + inputs, chains_for_parts, address, suffixes, append, validate = _fixed_inputs, _chains, _a, _station_suffixes, _append_group, _validate_binding_records + @_public_admission + def source_binding_records(source_path=fixed["paths"][2], *, contract_path=fixed["paths"][0], profile_table_path=fixed["paths"][3]): + admission, _, _, _ = inputs(source_path, contract_path, profile_table_path) + parts, bindings, chains = admission["parts"], [], chains_for_parts() + for name, role, prefix in semantic["stations"]: + owner = address(role) + dimensions = tuple((field, f"{prefix}_{suffix}") for field, suffix in zip(("rL", "rA", "rP"), suffixes(role))) + append(bindings, admission, parts, chains, f"stations.{name}", owner, (("C", prefix),), dimensions) + for side in ("left", "right"): + append(bindings, admission, parts, chains, f"shoulders.{side}", address("upper_arm", side), semantic["shoulder_sums"], semantic["shoulder_dims"]) + append(bindings, admission, parts, chains, f"hips.{side}", address("thigh", side), semantic["hip_sums"], semantic["hip_dims"]) + return validate(sorted(bindings, key=lambda item: item["prepared_component"].encode("utf-8"))) + return source_binding_records +source_binding_records = _binding_api(_COMMITMENTS) build_source_binding_records = source_binding_records canonical_json_bytes = _JSON_BYTES -def canonical_json_sha256(value): return _SHA256_BYTES(_JSON_BYTES(value)) +def _sha_api(operations): + def canonical_json_sha256(value): return operations["sha256_bytes"](operations["json_bytes"](value)) + return canonical_json_sha256 +canonical_json_sha256 = _sha_api(_COMMITMENTS["operations"]) __all__ = [ "EXPECTED_CONTRACT_SHA256", "EXPECTED_PROFILE_TABLE_SHA256", "EXPECTED_SOURCE_SHA256", "PreparedProjectionError", diff --git a/experiments/owned-root-assembly-successor/render_export.py b/experiments/owned-root-assembly-successor/render_export.py new file mode 100644 index 0000000..fe50c35 --- /dev/null +++ b/experiments/owned-root-assembly-successor/render_export.py @@ -0,0 +1,215 @@ +"""Exact quad export and same-surface Pillow evidence rendering.""" +from __future__ import annotations + +import hashlib +import math +import re +import struct +from dataclasses import dataclass +from io import BytesIO +from typing import Any + +import owned_root_surface as _surface + + +class RenderExportError(ValueError): + """Raised when an export or render input is outside the closed contract.""" +WIDTH = HEIGHT = PANEL_WIDTH = PANEL_HEIGHT = 512 +FACE_COUNT, VERTEX_COUNT, TRIANGLE_COUNT = 1664, 1737, 3328 +PANEL_ORDER = ("front", "side", "45deg") +BACKGROUND_RGB, DIRECT_RGB = (247, 247, 247), (188, 198, 210) +PALETTE = {"domain.pelvis": (214, 83, 83), "domain.abdomen": (226, 157, 68), "domain.thorax": (93, 150, 213), "domain.neck": (153, 102, 204), "domain.left_shoulder": (81, 168, 115), "domain.right_shoulder": (81, 168, 115), "domain.left_hip": (221, 112, 166), "domain.right_hip": (221, 112, 166)} +CAMERAS = (("front", (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), ("side", (0.0, 0.0, 1.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)), ("45deg", (0.7071067811865476, 0.0, -0.7071067811865475), (0.0, 1.0, 0.0), (0.7071067811865475, 0.0, 0.7071067811865476))) +CONFIG_KEYS = ("width", "height", "panel_width", "panel_height", "panel_order", "padding", "background_rgb", "direct_rgb", "domain_palette", "cameras", "common_scale_rule", "pixel_center_rule", "barycentric_tolerance", "degenerate_tolerance", "depth_rule", "tie_rule", "quad_split", "shading", "lighting", "labels", "outlines", "anti_aliasing", "alpha", "culling", "pillow_version", "png_compress_level", "png_optimize", "png_metadata") + +def _frozen_l2_authority(): + (controls, quads, loops), owners = _surface.symbolic_topology(), tuple(record[1] for record in _surface.FACE_RECORDS) + mesh = _surface.Mesh((None,) * len(controls), quads, (), (), (), loops) + for level in (1, 2): + incidence = _surface.subdivision_incidence(mesh) + quads, owners = tuple(child[2] for child in incidence["child_emission"]), tuple(owners[child[0]] for child in incidence["child_emission"]) + mesh = _surface.Mesh((None,) * (len(mesh.vertices) + len(incidence["edges"]) + len(mesh.quads)), quads, (), (), (), incidence["propagated_port_loops"], level=level) + return quads, tuple(item for face in quads for item in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))), owners +_FROZEN_QUADS, _FROZEN_TRIANGLES, _FROZEN_OWNERS = _frozen_l2_authority() + +def _fl(value: float) -> float: + return float(value) +def _reject(condition: bool, message: str) -> None: + if condition: + raise RenderExportError(message) +def _finite(value: object, label: str) -> float: + _reject(type(value) is not float or not math.isfinite(value), f"{label} must be a finite binary64 float") + return value +def _dot(left: tuple[float, ...], right: tuple[float, ...]) -> float: + x, y, z = (_fl(left[i] * right[i]) for i in range(3)) + return _fl(_fl(x + y) + z) +def _vector(row: object, index: int) -> tuple[float, float, float]: + _reject(type(row) not in (tuple, list) or len(row) != 3, f"vertex {index} is not a vector3") + return tuple(_finite(item, f"vertex {index}") for item in row) +def _quad(row: object, index: int, vertex_count: int) -> tuple[int, int, int, int]: + _reject((type(row) not in (tuple, list) or len(row) != 4 or any(type(item) is not int for item in row) or len(set(row)) != 4 or any(not 0 <= item < vertex_count for item in row)), f"quad {index} is invalid") + return tuple(row) +def _parts(value: object, quads: object = None, *, level: int | None = None, owners: bool = False) -> tuple[Any, ...]: + if quads is None: + vertices, quads = getattr(value, "vertices", None), getattr(value, "quads", None) + _reject(level is not None and getattr(value, "level", None) != level, f"mesh must be level {level}") + face_owners = getattr(value, "face_owners", None) + else: + vertices, face_owners = value, None + _reject(type(vertices) not in (tuple, list) or type(quads) not in (tuple, list), "vertices and quads must be concrete sequences") + points = tuple(_vector(row, index) for index, row in enumerate(vertices)) + _reject(not points, "mesh has no vertices") + faces = tuple(_quad(row, index, len(points)) for index, row in enumerate(quads)) + _reject(not faces, "mesh has no quads") + if owners: + _reject(type(face_owners) not in (tuple, list) or len(face_owners) != len(faces) or any(type(item) is not str for item in face_owners), "level-2 mesh has no exact face ownership") + return points, faces, tuple(face_owners) if owners else () +def _coordinate(value: float) -> str: + value = _finite(value, "coordinate") + if value == 0.0: + return "0" + text = format(value, ".17g") + if "e" not in text: + return text + mantissa, exponent = text.split("e") + sign = "-" if exponent.startswith("-") else "+" + digits = exponent.lstrip("+-").lstrip("0") or "0" + return f"{mantissa}e{sign}{digits}" +def ply_bytes(value: object, quads: object = None) -> bytes: + points, faces, _ = _parts(value, quads) + rows = ["ply", "format ascii 1.0", f"element vertex {len(points)}", "property double x", "property double y", "property double z", f"element face {len(faces)}", "property list uchar int vertex_indices", "end_header"] + rows.extend(" ".join(_coordinate(item) for item in point) for point in points) + rows.extend("4 " + " ".join(str(item) for item in face) for face in faces) + data = ("\n".join(rows) + "\n").encode("ascii") + _reject(len(data) > 2 * 1024 * 1024, "PLY exceeds the frozen 2 MiB limit") + return data +def render_config_record() -> dict[str, Any]: + return { + "width": 512, "height": 1536, "panel_width": 512, "panel_height": 512, "panel_order": list(PANEL_ORDER), "padding": 24, "background_rgb": list(BACKGROUND_RGB), + "direct_rgb": list(DIRECT_RGB), "domain_palette": {k: list(v) for k, v in PALETTE.items()}, "cameras": [{"name": n, "right": list(r), "up": list(u), "depth": list(d)} for n, r, u, d in CAMERAS], + "common_scale_rule": "aabb-midpoint-all-views-extent-232.v1", "pixel_center_rule": "column-plus-0.5-row-plus-0.5-y-down.v1", + "barycentric_tolerance": -1e-12, "degenerate_tolerance": 1e-15, "depth_rule": "larger-depth-wins", "tie_rule": "lower-triangle-index-wins", + "quad_split": [[0, 1, 2], [0, 2, 3]], "shading": False, "lighting": False, "labels": False, "outlines": False, + "anti_aliasing": False, "alpha": False, "culling": False, "pillow_version": "11.1.0", "png_compress_level": 9, "png_optimize": False, "png_metadata": {}, + } +def _exact(value: object, expected: object) -> bool: + return type(value) is type(expected) and ((all(type(key) is str for key in value) and set(value) == set(expected) and all(_exact(value[key], item) for key, item in expected.items())) if type(expected) is dict else (len(value) == len(expected) and all(_exact(item, wanted) for item, wanted in zip(value, expected))) if type(expected) is list else value == expected) +def validate_render_config(value: object) -> None: + _reject(not _exact(value, render_config_record()), "render_config is not the exact closed record") +@dataclass(frozen=True) +class VisibilityBuffer: + owners: tuple[int | None, ...] + depths: tuple[float | None, ...] + triangle_owners: tuple[str, ...] + triangle_index_sha256: str + degenerate_triangles: int +def _hash_triangles(triangles: tuple[tuple[int, int, int], ...]) -> str: + return hashlib.sha256(b"".join(struct.pack(" None: + prior = depths[index] + equal = prior is not None and struct.pack(" prior or (equal and triangle < owners[index]): + depths[index], owners[index] = depth, triangle +def visibility_record(value: VisibilityBuffer) -> dict[str, Any]: + _validate_visibility(value) + return {"level": 2, "triangle_count": TRIANGLE_COUNT, "triangle_index_sha256": value.triangle_index_sha256, "rule": "larger-depth-then-lower-triangle-index"} +def _pillow() -> Any: + try: + import PIL + from PIL import Image + except ImportError as exc: + raise RenderExportError("Pillow 11.1.0 is required") from exc + _reject(PIL.__version__ != "11.1.0", "renderer requires Pillow 11.1.0") + return Image +def _validate_visibility(value: object) -> None: + _reject(type(value) is not VisibilityBuffer, "invalid visibility buffer") + _reject(not (type(value.owners) is tuple and type(value.depths) is tuple and len(value.owners) == 3 * WIDTH * HEIGHT and len(value.depths) == len(value.owners) and type(value.triangle_owners) is tuple and len(value.triangle_owners) == TRIANGLE_COUNT and type(value.triangle_index_sha256) is str and re.fullmatch(r"[0-9a-f]{64}", value.triangle_index_sha256) is not None and type(value.degenerate_triangles) is int and value.degenerate_triangles >= 0), "visibility buffer has an invalid closed shape") + _reject(any(item is not None and (type(item) is not int or not 0 <= item < TRIANGLE_COUNT) for item in value.owners), "visibility buffer has an invalid triangle owner") + _reject(any(item is not None and (type(item) is not float or not math.isfinite(item)) for item in value.depths), "visibility buffer has an invalid depth") + _reject(any((owner is None) != (depth is None) for owner, depth in zip(value.owners, value.depths)), "visibility buffer owner/depth occupancy disagrees") + _reject(any(type(item) is not str or item not in PALETTE for item in value.triangle_owners), "visibility buffer has an invalid domain owner") +def _panel_candidates(screen: tuple[tuple[float, float, float], ...], triangles): + records, rows, degenerate = [], [[] for _ in range(HEIGHT)], 0 + for triangle_index, (a, b, c) in enumerate(triangles): + ax, ay, za = screen[a] + bx, by, zb = screen[b] + cx, cy, zc = screen[c] + d0, d1, d2, d3 = _fl(by - cy), _fl(ax - cx), _fl(cx - bx), _fl(ay - cy) + denominator = _fl(_fl(d0 * d1) + _fl(d2 * d3)) + _reject(not math.isfinite(denominator), "barycentric denominator is non-finite") + if abs(denominator) <= 1e-15: + records.append(None) + degenerate += 1 + continue + c0, c1 = max(0, math.floor(min(ax, bx, cx) - 0.5) - 1), min(511, math.ceil(max(ax, bx, cx) - 0.5) + 1) + r0, r1 = max(0, math.floor(min(ay, by, cy) - 0.5) - 1), min(511, math.ceil(max(ay, by, cy) - 0.5) + 1) + records.append((ax, ay, za, bx, by, zb, cx, cy, zc, d0, d2, _fl(cy - ay), _fl(ax - cx), denominator, c0, c1)) + for row in range(r0, r1 + 1): + rows[row].append((triangle_index, c0, c1)) + return records, rows, degenerate +def build_visibility(mesh: object) -> VisibilityBuffer: + points, faces, face_owners = _parts(mesh, level=2, owners=True) + _reject((len(points), len(faces)) != (VERTEX_COUNT, FACE_COUNT), "level-2 mesh has the wrong closed cardinality") + _reject(faces != _FROZEN_QUADS or face_owners != _FROZEN_OWNERS, "level-2 topology or ancestry differs from frozen public authority") + triangles, catalog = _FROZEN_TRIANGLES, getattr(mesh, "triangles", None) + _reject(type(catalog) not in (tuple, list) or tuple(catalog) != triangles, "level-2 triangle catalog differs from frozen public topology") + expected_ids, face_ids = tuple(f"face.L2.q{i:04d}" for i in range(FACE_COUNT)), getattr(mesh, "face_ids", None) + _reject(type(face_ids) not in (tuple, list) or tuple(face_ids) != expected_ids, "level-2 face catalog does not match its numeric order") + low = tuple(min(point[axis] for point in points) for axis in range(3)) + high = tuple(max(point[axis] for point in points) for axis in range(3)) + midpoint = tuple(_fl(_fl(low[axis] + high[axis]) / 2.0) for axis in range(3)) + projected, extent = [], 0.0 + for _, right, up, depth in CAMERAS: + panel = [] + for point in points: + relative = tuple(_fl(point[axis] - midpoint[axis]) for axis in range(3)) + u, v, z = _dot(relative, right), _dot(relative, up), _dot(relative, depth) + _reject(not all(math.isfinite(item) for item in (u, v, z)), "camera projection is non-finite") + extent = max(extent, abs(u), abs(v)) + panel.append((u, v, z)) + projected.append(panel) + _reject(not all(math.isfinite(item) for item in midpoint) or not math.isfinite(extent) or extent <= 0.0, "camera extent is not positive and finite") + scale = _fl(232.0 / extent) + screens = [tuple((_fl(256.0 + _fl(scale * u)), _fl(256.0 - _fl(scale * v)), z) for u, v, z in panel) for panel in projected] + owners, depths, degenerate = [None] * (3 * WIDTH * HEIGHT), [None] * (3 * WIDTH * HEIGHT), 0 + for panel_index, screen in enumerate(screens): + records, rows, count = _panel_candidates(screen, triangles) + degenerate += count + base = panel_index * WIDTH * HEIGHT + for row in range(HEIGHT): + for column in range(WIDTH): + for triangle_index, c0, c1 in rows[row]: + if not c0 <= column <= c1: + continue + (_ax, _ay, za, _bx, _by, zb, cx, cy, zc, n0a, n0c, n1a, n1c, denominator, _, _) = records[triangle_index] + px, py = _fl(column + 0.5), _fl(row + 0.5) + n0 = _fl(_fl(n0a * _fl(px - cx)) + _fl(n0c * _fl(py - cy))) + w0 = _fl(n0 / denominator) + n1 = _fl(_fl(n1a * _fl(px - cx)) + _fl(n1c * _fl(py - cy))) + w1 = _fl(n1 / denominator) + w2 = _fl(_fl(1.0 - w0) - w1) + sample_depth = _fl(_fl(_fl(w0 * za) + _fl(w1 * zb)) + _fl(w2 * zc)) + _reject(not all(math.isfinite(item) for item in (n0, w0, n1, w1, w2, sample_depth)), "barycentric evaluation is non-finite") + if w0 >= -1e-12 and w1 >= -1e-12 and w2 >= -1e-12: + _accept_sample(owners, depths, base + row * WIDTH + column, triangle_index, sample_depth) + return VisibilityBuffer(tuple(owners), tuple(depths), tuple(_FROZEN_OWNERS[index // 2] for index in range(TRIANGLE_COUNT)), _hash_triangles(triangles), degenerate) +def render_png_bytes(value: VisibilityBuffer | object, *, lineage: bool = False) -> bytes: + _reject(type(lineage) is not bool, "lineage must be a boolean") + visibility = value if type(value) is VisibilityBuffer else build_visibility(value) + _validate_visibility(visibility) + pixels = (image := _pillow().new("RGB", (WIDTH, 3 * HEIGHT), BACKGROUND_RGB)).load() + for panel in range(3): + for row in range(HEIGHT): + for column in range(WIDTH): + triangle = visibility.owners[panel * WIDTH * HEIGHT + row * WIDTH + column] + if triangle is not None: + pixels[column, panel * HEIGHT + row] = PALETTE[visibility.triangle_owners[triangle]] if lineage else DIRECT_RGB + output = BytesIO() + image.save(output, format="PNG", compress_level=9, optimize=False) + data = output.getvalue() + _reject(len(data) > 2 * 1024 * 1024, "PNG exceeds the frozen 2 MiB limit") + return data +def render_pair_bytes(mesh: object) -> tuple[bytes, bytes, VisibilityBuffer]: + visibility = build_visibility(mesh) + return render_png_bytes(visibility), render_png_bytes(visibility, lineage=True), visibility +__all__ = ["RenderExportError", "VisibilityBuffer", "build_visibility", "ply_bytes", "render_config_record", "render_pair_bytes", "render_png_bytes", "validate_render_config", "visibility_record"] diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py index b4d9739..94e2f81 100644 --- a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -1,555 +1,444 @@ from __future__ import annotations +import copy import hashlib +import inspect import os +from pathlib import Path import sys import tempfile import unittest from unittest import mock -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import artifact_serialization as artifacts # noqa: E402 +PACKAGE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(PACKAGE)) +import build_owned_root as builder # noqa: E402 + + +def identity_fixture(): + runtime = {"schema": "owned-root-assembly-successor-runtime.v2", "fixture": "focused"} + runtime_bytes = builder.artifacts.canonical_json_bytes(runtime) + records = [ + {"role_path": role, "bytes": index + 1, "sha256": f"{index + 1:064x}"} + for index, role in enumerate(builder._order(builder.IMPLEMENTATION_ROLES)) + ] + return { + "contract": {"role_path": builder.CONTRACT_ROLE, "bytes": 173184, + "sha256": builder.EXPECTED_CONTRACT_SHA256}, + "source": {"role_path": builder.SOURCE_ROLE, "bytes": builder.EXPECTED_SOURCE_BYTES, + "sha256": builder.EXPECTED_SOURCE_SHA256}, + "profile_table": {"role_path": builder.PROFILE_ROLE, + "bytes": builder.EXPECTED_PROFILE_BYTES, + "sha256": builder.EXPECTED_PROFILE_SHA256}, + "runtime": runtime, + "runtime_bytes": runtime_bytes, + "runtime_fingerprint_sha256": builder.artifacts.sha256_bytes(runtime_bytes), + "implementation_files": records, + } + + +class FrozenInventoryTests(unittest.TestCase): + def test_contract_identity_and_private_roles_are_closed(self): + self.assertEqual(len(builder.PARAMETER_IDS), 33) + self.assertEqual(len(builder.SURFACE_ROLES), 3) + self.assertEqual(len(builder.PERTURBATION_ROLES), 33) + self.assertEqual(len(builder.ARTIFACT_ROLES), 47) + self.assertEqual(len(builder.IMPLEMENTATION_ROLES), 15) + self.assertEqual(len(set(builder.ARTIFACT_ROLES)), 47) + self.assertEqual(builder.RUN_REPORT_GATES[0], "seed.1.identity") + self.assertEqual(builder.RUN_REPORT_GATES[-1], "seed.6.serialization") + + def test_parameter_to_ply_mapping_is_literal_and_reversible(self): + expected = ( + "perturb-left-r_y.ply", "perturb-right-r_y.ply", + "perturb-lower_pelvis-L_y.ply", "perturb-lower_pelvis-C_z.ply", + "perturb-left-r_x.ply", "perturb-right-r_x.ply", + "perturb-lower_pelvis-R_x.ply", "perturb-left-r_z.ply", + "perturb-right-r_z.ply", "perturb-lower_pelvis-R_f.ply", + "perturb-lower_pelvis-R_b.ply", "perturb-left-thigh_start_x.ply", + "perturb-left-thigh_start_y.ply", "perturb-left-thigh_start_z.ply", + "perturb-right-thigh_start_x.ply", "perturb-right-thigh_start_y.ply", + "perturb-right-thigh_start_z.ply", "perturb-neck_collar-C_y.ply", + "perturb-neck_collar-rL.ply", "perturb-neck_upper-C_y.ply", + "perturb-neck_upper-rL.ply", "perturb-left-axilla_x.ply", + "perturb-left-axilla_y.ply", "perturb-right-axilla_x.ply", + "perturb-right-axilla_y.ply", "perturb-left-peak_y.ply", + "perturb-right-peak_y.ply", "perturb-left-start_lateral.ply", + "perturb-right-start_lateral.ply", "perturb-left-start_up.ply", + "perturb-right-start_up.ply", "perturb-left-shoulder_depth.ply", + "perturb-right-shoulder_depth.ply", + ) + self.assertEqual(builder.PERTURBATION_ROLES, expected) + def test_roles_are_sorted_only_at_schema_boundaries(self): + self.assertNotEqual(builder.ARTIFACT_ROLES, tuple(sorted(builder.ARTIFACT_ROLES))) + self.assertEqual(builder._order(builder.ARTIFACT_ROLES), tuple(sorted(builder.ARTIFACT_ROLES))) + self.assertEqual(builder._order(builder.IMPLEMENTATION_ROLES), tuple(sorted(builder.IMPLEMENTATION_ROLES))) -class CanonicalArtifactTests(unittest.TestCase): - def test_canonical_json_is_compact_utf8_and_has_no_trailing_lf(self) -> None: - value = {"z": "é", "a": [1, True], "nested": {"b": 2, "a": 1}} - self.assertEqual( - artifacts.canonical_json_bytes(value), - b'{"a":[1,true],"nested":{"a":1,"b":2},"z":"\xc3\xa9"}', - ) - def test_binary64_zeros_have_one_wire_spelling_and_nonfinite_values_fail(self) -> None: - self.assertEqual( - artifacts.canonical_json_bytes({"positive": 0.0, "negative": -0.0}), - b'{"negative":0,"positive":0}', +class SupportAndGateTests(unittest.TestCase): + def test_support_hash_uses_the_frozen_header_and_u32_indices(self): + indices = (0, 4, 1736) + payload = b"CKSUPPORTv1\0\2" + (3).to_bytes(4, "little") + b"".join( + index.to_bytes(4, "little") for index in indices ) - for value in (float("nan"), float("inf"), float("-inf")): - with self.subTest(value=value), self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.canonical_json_bytes({"value": value}) - - def test_coordinate_and_triangle_hash_domains_are_exact(self) -> None: - coordinates = ((1.0, -0.0, 2.5),) - triangles = ((0, 1, 2), (-1, 4, 8)) - expected_coordinates = b"".join( - value.to_bytes(8, "little", signed=False) - for value in (0x3FF0000000000000, 0x8000000000000000, 0x4004000000000000) + self.assertEqual(builder._support_hash(indices), hashlib.sha256(payload).hexdigest()) + for bad in ((1, 1), (-1,), (1737,), (1, 0)): + with self.subTest(bad=bad), self.assertRaises(builder.BuildError): + builder._support_hash(bad) + + def test_gate_records_have_the_closed_contract_shape(self): + result, threshold = builder._gate( + "structural.example", 3, 0.5, 1.0, "ge", 0.25, None, "m" ) - self.assertEqual(artifacts.coordinate_hash_bytes(coordinates), expected_coordinates) - expected_triangles = b"".join( - int(value).to_bytes(8, "little", signed=True) - for row in triangles - for value in row + self.assertEqual(set(result), {"gate_id", "outcome", "sample_count", + "observed_min", "observed_max", "threshold_id"}) + self.assertEqual(set(threshold), {"threshold_id", "relation", "lower", "upper", "unit"}) + self.assertEqual(result["threshold_id"], threshold["threshold_id"]) + self.assertEqual(builder._bool("structural.boolean")[0]["outcome"], "pass") + failed, zero = builder._gate("structural.L0.invalid_count.unowned_elements", + 1, 1, 1, "eq", 0, 0, "count") + self.assertEqual(failed["outcome"], "fail") + with self.assertRaises(builder.BuildError): builder._validate_gate(failed, zero, "hostile") + + def _synthetic_continuity(self, residual_samples, fold_samples): + counts = (2, 4, 8) + meshes = tuple(mock.Mock(vertices=(), quads=(), face_owners=(), + boundary_loops=()) for _ in counts) + evaluation = mock.Mock(cage=meshes[0], levels=meshes[1:]) + surface = mock.Mock(JUNCTIONS=("junction.synthetic",)) + mesh_api = mock.Mock(T=1.0) + mesh_api.junction_continuity_metrics.side_effect = [ + {"traces": (tuple(range(count)), ()), + "coordinate_residual_samples": residual_samples(count)} for count in counts + ] + reports = tuple({"port_metrics": {}} for _ in counts) + with mock.patch.object(builder, "_junction_inputs", + return_value={"junction.synthetic": {}}), mock.patch.object( + builder, "_fold_samples", + side_effect=[fold_samples(count) for count in counts]): + return builder._continuity(surface, mesh_api, evaluation, reports)[0] + + def test_nonuniform_residual_samples_publish_exact_truthful_extrema(self): + gates = self._synthetic_continuity( + lambda count: tuple(index / 100.0 for index in range(3 * count)), + lambda count: (1.0,) * count) + rows = {row["gate_id"]: row for row in gates} + for level, count in enumerate((2, 4, 8)): + row = rows[f"continuity.junction.synthetic.L{level}.coordinate_residual"] + self.assertEqual((row["sample_count"], row["observed_min"], + row["observed_max"]), + (3 * count, 0.0, (3 * count - 1) / 100.0)) + self.assertNotEqual(row["observed_min"], row["observed_max"]) + + def test_nonuniform_fold_samples_publish_exact_truthful_extrema(self): + gates = self._synthetic_continuity( + lambda count: (0.0,) * (3 * count), + lambda count: tuple(1.0 + index / 2.0 for index in range(count))) + rows = {row["gate_id"]: row for row in gates} + for level, count in enumerate((2, 4, 8)): + row = rows[f"continuity.junction.synthetic.L{level}.fold_angle"] + self.assertEqual((row["sample_count"], row["observed_min"], + row["observed_max"]), + (count, 1.0, 1.0 + (count - 1) / 2.0)) + self.assertNotEqual(row["observed_min"], row["observed_max"]) + + def test_manifest_reference_does_not_copy_extra_file_fields(self): + record = {"role_path": "input.json", "bytes": 12, "sha256": "a" * 64, + "unexpected": "not a manifest field"} + self.assertEqual(builder._manifest_ref(record, "schema.v1"), { + "role_path": "input.json", "bytes": 12, "sha256": "a" * 64, + "schema": "schema.v1", + }) + + def test_mesh_adapters_use_independent_topology_and_incident_domain_traces(self): + import mesh_correctness as mesh_api + import owned_root_surface as surface + import prepared_projection as prepared_api + import chart_lineage as chart_api + prepared = prepared_api.prepare_standard_neutral() + evaluation = surface.evaluate(prepared) + formulas = tuple(surface.formula_candidate_records(prepared)) + chart_summary = chart_api.build_chart_summary(evaluation, formulas) + base_faces = tuple(tuple(int(control[1:]) for control in row[2]) + for row in surface.FACE_RECORDS) + expected = mesh_api.derive_expected_face_catalogs(base_faces) + fixtures = mesh_api.run_production_intersection_fixtures() + self.assertEqual(tuple(row["fixture_id"] for row in fixtures), mesh_api.INTERSECTION_FIXTURE_IDS) + reports = [] + for level, mesh in enumerate((evaluation.cage, *evaluation.levels)): + self.assertEqual(mesh.quads, expected[level]) + inputs = builder._junction_inputs(surface, evaluation, level, chart_summary) + self.assertEqual(set(inputs), set(surface.JUNCTIONS)) + for row in inputs.values(): + self.assertIsNot(row["domain_vertex_tags"][0], row["domain_vertex_tags"][1]) + self.assertIsNot(row["domain_vertex_tags"], row["expected_domain_vertex_tags"]) + ownership = builder._ownership_counts(surface, evaluation, chart_api, mesh_api, + prepared, formulas, chart_summary, level) + self.assertEqual((ownership["unowned_elements"], + ownership["overowned_elements"]), (0, 0)) + for junction in surface.JUNCTIONS: + result = mesh_api.junction_continuity_metrics( + mesh.vertices, mesh.quads, mesh.face_owners, **inputs[junction] + ) + self.assertEqual(result["coordinate_residual"], 0.0) + self.assertEqual(len(result["traces"]), 2) + reports.append(mesh_api.validate_geometry( + mesh.vertices, mesh.quads, level, dict(mesh.boundary_loops), + builder._directions(surface), base_faces, inputs, mesh.face_owners)) + continuity, thresholds = builder._continuity( + surface, mesh_api, evaluation, reports, chart_summary) + self.assertEqual((len(continuity), len(thresholds)), (144, 144)) + + +class StaticAdmissionTests(unittest.TestCase): + def test_package_implementation_fits_frozen_physical_loc_caps(self): + counts = {"production": 0, "tests": 0} + for role in builder.IMPLEMENTATION_ROLES: + group = "tests" if "/tests/" in role else "production" + counts[group] += builder.artifacts.read_regular_file(builder.ROOT / role).count(b"\n") + self.assertLessEqual(counts["production"], 3400) + self.assertLessEqual(counts["tests"], 2600) + + def test_implementation_scan_never_reports_non_source_files(self): + found = [] + for directory, _, filenames in os.walk(builder.PACKAGE): + found.extend((Path(directory) / name).relative_to(builder.ROOT).as_posix() + for name in filenames if Path(name).suffix in (".py", ".sh")) + found = tuple(sorted(found, key=lambda value: value.encode("utf-8"))) + self.assertTrue(set(found) <= set(builder.IMPLEMENTATION_ROLES)) + + def test_runtime_string_rejects_non_strings_and_oversized_values(self): + self.assertEqual(builder._runtime_text("ok", "value"), "ok") + with self.assertRaises(builder.BuildError): + builder._runtime_text("x" * 129, "value") + with self.assertRaises(builder.BuildError): + builder._runtime_text(1, "value") + + def test_wrong_hash_seed_is_rejected_before_output_creation(self): + with tempfile.TemporaryDirectory() as directory, mock.patch.dict( + os.environ, {"PYTHONHASHSEED": "0"}, clear=False): + output = Path(directory) / "seed" + with self.assertRaisesRegex(builder.BuildError, "PYTHONHASHSEED"): + builder.build_seed(output) + self.assertFalse(output.exists()) + + def test_builder_binds_publication_inventory_and_never_self_feeds_mesh(self): + publication = inspect.getsource(builder.build_seed) + geometry = inspect.getsource(builder._geometry) + junctions = inspect.getsource(builder._junction_inputs) + self.assertIn("publish_no_replace(stage, output, inventory, max_file_bytes=", publication) + self.assertNotIn("publish_no_replace(stage, output)", publication) + self.assertLess(publication.index("_validate_gate_manifest(gate_manifest)"), + publication.index('_write_json(stage / "gate-manifest.json"')) + self.assertLess(publication.index("_validate_gate_manifest(gate_manifest)"), + publication.index("publish_no_replace")) + self.assertNotIn("else mesh.quads", geometry) + self.assertIn("derive_expected_face_catalogs(expected)", geometry) + self.assertNotIn("reversed", junctions) + self.assertNotIn("propagate_junction_tags", junctions) + + +class ManagedDispatchTests(unittest.TestCase): + def test_invalid_command_does_not_enter_admission(self): + with mock.patch.object(builder, "_static_admission") as admission: + self.assertEqual(builder.main(["--output"]), 1) + admission.assert_not_called() + + def test_internal_mode_dispatches_exactly_after_static_admission(self): + with mock.patch.object(builder, "run_managed_tests", return_value={}) as managed: + self.assertEqual(builder.main(["--internal-managed-tests", "--receipt", "/tmp/receipt"]), 0) + managed.assert_called_once_with("/tmp/receipt") + + def test_unittest_discovery_keeps_the_experiment_non_package(self): + loader = unittest.TestLoader() + suite = loader.discover(str(builder.TESTS), pattern="test_*.py") + tests = [] + + def flatten(value): + for item in value: + if isinstance(item, unittest.TestSuite): + yield from flatten(item) + else: + yield item + + tests.extend(flatten(suite)) + ids = {test.id() for test in tests} + self.assertIn( + "test_mesh_correctness.ProductionIntersectionFixtureTests.test_contract_fixture_matrix", ids ) - self.assertEqual(artifacts.triangle_index_hash_bytes(triangles), expected_triangles) - self.assertEqual( - artifacts.sha256_bytes(artifacts.coordinate_hash_bytes(coordinates)), - hashlib.sha256(expected_coordinates).hexdigest(), + self.assertIn( + "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix", ids ) - - def test_canonical_decode_rejects_duplicates_and_noncanonical_bytes(self) -> None: - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.decode_canonical_json(b'{"a":1,"a":2}') - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.decode_canonical_json(b'{"a": 1}') - self.assertEqual(artifacts.decode_canonical_json(b'{"a":0}'), {"a": 0}) - self.assertEqual(artifacts.coerce_binary64(0), 0.0) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.coerce_binary64(1) - - -class FileAdmissionTests(unittest.TestCase): - def test_regular_file_record_hashes_exact_bytes_and_rejects_symlinks(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - payload = root / "payload.bin" - payload.write_bytes(b"payload") - record = artifacts.regular_file_record(payload, "seed/payload.bin") - self.assertEqual(record["bytes"], 7) - self.assertEqual(record["sha256"], hashlib.sha256(b"payload").hexdigest()) - self.assertEqual(artifacts.regular_file_record(payload, "seed/payload.bin"), record) - link = root / "link" - link.symlink_to(payload) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.regular_file_record(link, "seed/link") - hardlink = root / "hardlink" - os.link(payload, hardlink) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.regular_file_record(payload, "seed/payload.bin") - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.validate_role_path("../payload.bin") - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.regular_file_record(payload, "") - - def test_sidecar_is_exact_one_lf_terminated_line(self) -> None: - digest = hashlib.sha256(b"contract").hexdigest() - expected = f"{digest} {artifacts.CONTRACT_ROLE}\n".encode("ascii") - self.assertEqual(artifacts.contract_sidecar_bytes(digest), expected) - artifacts.validate_contract_sidecar(expected, digest) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.validate_contract_sidecar(expected + b"\n", digest) - with self.assertRaises(TypeError): - artifacts.contract_sidecar_bytes(digest, contract_role="alternate") - with self.assertRaises(TypeError): - artifacts.validate_contract_sidecar( - expected, digest, contract_role="alternate" - ) - with tempfile.TemporaryDirectory() as directory: - sidecar = Path(directory) / "design-contract.sha256" - self.assertEqual( - artifacts.write_contract_sidecar_no_replace(sidecar, digest), sidecar - ) - self.assertEqual(sidecar.read_bytes(), expected) - with self.assertRaises(TypeError): - artifacts.write_contract_sidecar_no_replace( - Path(directory) / "alternate.sha256", - digest, - contract_role="alternate", - ) - - def test_closed_inventory_requires_exact_regular_file_set(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "a").write_bytes(b"a") - (root / "nested").mkdir() - (root / "nested" / "b").write_bytes(b"b") - records = artifacts.closed_inventory(root, ("a", "nested/b")) - self.assertEqual(tuple(record["role_path"] for record in records), ("a", "nested/b")) - (root / "extra").write_bytes(b"extra") - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("a", "nested/b")) - - def test_closed_inventory_rejects_hardlinked_file(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - payload = root / "payload" - alias = root / "alias" - payload.write_bytes(b"payload") - os.link(payload, alias) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("payload",)) - - def test_closed_inventory_rejects_unexpected_directory_and_symlink(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "a").write_bytes(b"a") - (root / "empty").mkdir() - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("a",)) - (root / "empty").rmdir() - (root / "link").symlink_to(root / "a") - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("a",)) - - def test_closed_inventory_rejects_deterministic_insertion_and_removal(self) -> None: - for operation in ("insert", "remove"): - with self.subTest(operation=operation), tempfile.TemporaryDirectory() as directory: - root = Path(directory) - payload = root / "payload" - payload.write_bytes(b"payload") - original_listdir = artifacts.os.listdir - calls = 0 - - def listdir(path): - nonlocal calls - names = original_listdir(path) - if isinstance(path, int) and calls == 0: - calls += 1 - if operation == "insert": - (root / "inserted").write_bytes(b"race") - else: - payload.unlink() - return names - - with mock.patch.object(artifacts.os, "listdir", side_effect=listdir): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("payload",)) - - def test_closed_inventory_rejects_deterministic_same_name_replacement(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - payload = root / "payload" - payload.write_bytes(b"original") - moved = root / "moved" - original_pread = artifacts.os.pread - replaced = False - - def pread(fd, count, offset): - nonlocal replaced - data = original_pread(fd, count, offset) - if data and not replaced: - replaced = True - payload.rename(moved) - payload.write_bytes(b"replacement") - return data - - with mock.patch.object(artifacts.os, "pread", side_effect=pread): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("payload",)) - - def test_closed_inventory_rejects_expected_nested_directory_replacement(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - nested = root / "nested" - nested.mkdir() - (nested / "payload").write_bytes(b"original") - moved = root / "nested-moved" - original_stat = artifacts.os.stat - replaced = False - - def stat(path, *args, **kwargs): - nonlocal replaced - result = original_stat(path, *args, **kwargs) - if path == "nested" and kwargs.get("dir_fd") is not None and not replaced: - replaced = True - nested.rename(moved) - nested.mkdir() - (nested / "payload").write_bytes(b"replacement") - return result - - with mock.patch.object(artifacts.os, "stat", side_effect=stat): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.closed_inventory(root, ("nested/payload",)) - - def test_regular_file_read_rejects_real_same_size_pwrite_between_chunks(self) -> None: - with tempfile.TemporaryDirectory() as directory: - payload = Path(directory) / "payload" - chunk_size = 1024 * 1024 - payload.write_bytes(b"a" * (chunk_size * 2)) - writer_fd = os.open(payload, os.O_WRONLY) - original_pread = artifacts.os.pread - mutated = False - - def pread(fd, count, offset): - nonlocal mutated - data = original_pread(fd, count, offset) - if offset == 0 and data and not mutated: - mutated = True - self.assertEqual(os.pwrite(writer_fd, b"b", chunk_size), 1) - return data - - try: - with mock.patch.object(artifacts.os, "pread", side_effect=pread): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.read_regular_file(payload) - finally: - os.close(writer_fd) - - def test_regular_file_read_rechecks_requested_path_identity(self) -> None: + self.assertEqual(len(ids), len(tests)) + + +class PublicValidatorTests(unittest.TestCase): + def receipt(self, path): + identity = identity_fixture() + executed = list(builder.REQUIRED_TEST_IDS) + value = { + "schema": "owned-root-assembly-successor-managed-test-receipt.v1", + "outcome": "success", + "literal_invocation": { + "environment": ["PYTHONHASHSEED=0"], + "argv": ["experiments/owned-root-assembly-successor/build_owned_root.py", + "--internal-managed-tests", "--receipt", str(path)], + }, + "contract_sha256": builder.EXPECTED_CONTRACT_SHA256, + "runtime_fingerprint_sha256": identity["runtime_fingerprint_sha256"], + "implementation_files": identity["implementation_files"], + "executed_test_ids": executed, + "required_test_ids": list(builder.REQUIRED_TEST_IDS), + "results": {"tests_run": len(executed), "failures": 0, "errors": 0, + "skipped": 0, "expected_failures": 0, + "unexpected_successes": 0}, + } + return identity, value + + def report(self, root, seed=17): + identity = identity_fixture() + stable = {"role_path": "stable-manifest.json", "bytes": 123, + "sha256": "a" * 64, + "schema": builder.MANIFEST_SCHEMAS["stable-manifest.json"]} + value = { + "schema": "owned-root-assembly-successor-run-report.v1", + "outcome": "success", + "seed": seed, + "literal_invocation": { + "environment": [f"PYTHONHASHSEED={seed}"], + "argv": ["experiments/owned-root-assembly-successor/build_owned_root.py", + "--output", str(root)], + }, + "output_path": str(root), + "staging_path": str(root.parent / f".{root.name}.stage-focused"), + "python_executable_path": "/pinned/python", + "started_utc": "2026-09-05T01:02:03.000004Z", + "finished_utc": "2026-09-05T01:02:04.000005Z", + "timings": [{"phase": phase, "seconds": 0.125} + for phase in builder.RUN_PHASES], + "runtime_fingerprint_sha256": identity["runtime_fingerprint_sha256"], + "stable_manifest": stable, + "gates": [{"gate_id": gate, "outcome": "pass", "sample_count": 1, + "observed_min": 1, "observed_max": 1, + "threshold_id": "gate.boolean-pass"} + for gate in builder.RUN_REPORT_GATES], + } + return identity, value + + def test_three_required_validator_exports_are_callable(self): + self.assertTrue(callable(builder.validate_managed_test_receipt)) + self.assertTrue(callable(builder.validate_seed_bundle)) + self.assertTrue(callable(builder.validate_run_report)) + + def test_managed_receipt_accepts_exact_canonical_all_pass_evidence(self): + path = Path(tempfile.gettempdir()) / "managed-stage" / "managed-test-receipt.json" + identity, value = self.receipt(path) + raw = builder.artifacts.canonical_json_bytes(value) + self.assertIs(builder.validate_managed_test_receipt( + receipt=value, raw=raw, identity=identity), value) + + def test_managed_receipt_rejects_forged_or_noncanonical_evidence(self): + path = Path(tempfile.gettempdir()) / "managed-stage" / "managed-test-receipt.json" + identity, value = self.receipt(path) + forged = copy.deepcopy(value) + forged["results"]["tests_run"] += 1 + with self.assertRaises(builder.BuildError): + builder.validate_managed_test_receipt( + receipt=forged, raw=builder.artifacts.canonical_json_bytes(forged), + identity=identity) + with self.assertRaises(builder.BuildError): + builder.validate_managed_test_receipt( + receipt=value, raw=builder.artifacts.canonical_json_bytes(value) + b"\n", + identity=identity) + + def test_run_report_accepts_exact_ordered_internal_evidence(self): with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - payload = root / "payload" - moved = root / "moved" - payload.write_bytes(b"original") - original_read = artifacts._read_stable_with_identity - - def read_then_replace(parent_fd, name, max_bytes): - result = original_read(parent_fd, name, max_bytes) - payload.rename(moved) - payload.write_bytes(b"replacement") - return result - - with mock.patch.object(artifacts, "_read_stable_with_identity", - side_effect=read_then_replace): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.read_regular_file(payload) - - def test_regular_file_read_rejects_deterministic_same_size_mutation(self) -> None: - with tempfile.TemporaryDirectory() as directory: - payload = Path(directory) / "payload" - payload.write_bytes(b"original") - original_pread = artifacts.os.pread - mutated = False - - def pread(fd, count, offset): - nonlocal mutated - data = original_pread(fd, count, offset) - if data and not mutated: - mutated = True - payload.write_bytes(b"mutated!") - return data - - with mock.patch.object(artifacts.os, "pread", side_effect=pread): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.read_regular_file(payload) - - -class PublicationTests(unittest.TestCase): - def test_atomic_json_write_and_no_replace_preserve_existing_target(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - target = root / "artifact.json" - artifacts.write_canonical_json_no_replace(target, {"ok": True}) - self.assertEqual(target.read_bytes(), b'{"ok":true}') - with self.assertRaises(FileExistsError): - artifacts.write_canonical_json_no_replace(target, {"ok": False}) - self.assertEqual(target.read_bytes(), b'{"ok":true}') - self.assertEqual( - [path.name for path in root.iterdir()], - ["artifact.json"], - ) - - def test_directory_publication_is_atomic_and_no_replace(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / ".bundle.stage" - target = root / "bundle" - stage.mkdir() - (stage / "payload").write_bytes(b"new") - self.assertEqual(artifacts.publish_no_replace(stage, target), target) - self.assertEqual((target / "payload").read_bytes(), b"new") - second = root / ".second.stage" - second.mkdir() - (second / "payload").write_bytes(b"replacement") - with self.assertRaises(FileExistsError): - artifacts.publish_no_replace(second, target) - self.assertEqual((target / "payload").read_bytes(), b"new") - - def test_publication_rejects_hardlinked_staging_file(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - alias = root / "alias" - target = root / "target" - stage.write_bytes(b"staged") - os.link(stage, alias) - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual(stage.read_bytes(), b"staged") - self.assertEqual(alias.read_bytes(), b"staged") - - def test_parent_fsync_failure_rolls_exact_file_back_to_stage(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - stage.write_bytes(b"staged") - - def fail_fsync(_descriptor): - raise OSError("injected parent fsync failure") - - with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): - with self.assertRaisesRegex(OSError, "injected parent fsync failure"): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual(stage.read_bytes(), b"staged") + root = Path(directory) / "seed-17" + root.mkdir() + identity, value = self.report(root) + self.assertIs(builder.validate_run_report( + root=root, seed=17, report=value, identity=identity), value) - def test_published_hardlink_is_rejected_and_alias_is_preserved(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - alias = root / "alias" - stage.write_bytes(b"staged") - - def hardlink_then_fail(_descriptor): - os.link(target, alias) - raise OSError("injected parent fsync failure") - - with mock.patch.object(artifacts.os, "fsync", side_effect=hardlink_then_fail): - with self.assertRaisesRegex(OSError, "injected parent fsync failure"): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual(stage.read_bytes(), b"staged") - self.assertEqual(alias.read_bytes(), b"staged") - - def test_directory_fsync_failure_rolls_back_whole_directory(self) -> None: + def test_run_report_rejects_wrong_phase_order_and_staging_scope(self): with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - stage.mkdir() - (stage / "payload").write_bytes(b"staged") - - def fail_fsync(_descriptor): - raise OSError("injected parent fsync failure") - - with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): - with self.assertRaisesRegex(OSError, "injected parent fsync failure"): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual((stage / "payload").read_bytes(), b"staged") - - def test_directory_mutation_is_rolled_back_without_recursive_deletion(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - stage.mkdir() - (stage / "payload").write_bytes(b"staged") - - def mutate_then_fail(_descriptor): - (target / "payload").write_bytes(b"mutated") - (target / "added").write_bytes(b"preserved") - raise OSError("injected parent fsync failure") - - with mock.patch.object(artifacts.os, "unlink", - side_effect=AssertionError("must not unlink")): - with mock.patch.object(artifacts.os, "rmdir", - side_effect=AssertionError("must not rmdir")): - with mock.patch.object(artifacts.os, "fsync", - side_effect=mutate_then_fail): - with self.assertRaisesRegex( - OSError, "injected parent fsync failure"): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual((stage / "payload").read_bytes(), b"mutated") - self.assertEqual((stage / "added").read_bytes(), b"preserved") - - def test_parent_fsync_failure_preserves_replaced_target(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - replacement = root / "replacement" - stage.write_bytes(b"staged") - replacement.write_bytes(b"unrelated") - - published_original = root / "published-original" - original_rename = artifacts._rename_no_replace - rename_calls = 0 - - def fail_fsync(_descriptor): - raise OSError("injected parent fsync failure") - - def replace_before_rollback(parent_fd, source, destination): - nonlocal rename_calls - rename_calls += 1 - if rename_calls == 2: - target.rename(published_original) - replacement.rename(target) - original_rename(parent_fd, source, destination) - - with mock.patch.object(artifacts, "_rename_no_replace", - side_effect=replace_before_rollback): - with mock.patch.object(artifacts.os, "fsync", side_effect=fail_fsync): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.publish_no_replace(stage, target) - self.assertEqual(target.read_bytes(), b"unrelated") - self.assertEqual(published_original.read_bytes(), b"staged") - self.assertFalse(any(path.name.startswith(".rollback-") - for path in root.iterdir())) - - def test_parent_fsync_failure_preserves_replaced_source(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - stage.write_bytes(b"staged") - - def occupy_source_then_fail(_descriptor): - stage.write_bytes(b"unrelated") - raise OSError("injected parent fsync failure") - - with mock.patch.object(artifacts.os, "fsync", - side_effect=occupy_source_then_fail): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.publish_no_replace(stage, target) - self.assertFalse(target.exists()) - self.assertEqual(stage.read_bytes(), b"unrelated") - quarantined = [path for path in root.iterdir() - if path.name.startswith(".rollback-")] - self.assertEqual(len(quarantined), 1) - self.assertEqual(quarantined[0].read_bytes(), b"staged") - - def test_failed_temporary_write_does_not_delete_replacement(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - target = root / "target" - original_temporary_file = artifacts._temporary_file - temporary_path = None - - def capture_temporary(parent_fd, target_name): - nonlocal temporary_path - descriptor, name = original_temporary_file(parent_fd, target_name) - temporary_path = root / name - return descriptor, name - - def replace_temporary_then_fail(_descriptor): - assert temporary_path is not None - temporary_path.unlink() - temporary_path.write_bytes(b"unrelated") - raise OSError("injected temporary fsync failure") - - with mock.patch.object(artifacts, "_temporary_file", - side_effect=capture_temporary): - with mock.patch.object(artifacts.os, "fsync", - side_effect=replace_temporary_then_fail): - with self.assertRaisesRegex( - OSError, "injected temporary fsync failure"): - artifacts.write_bytes_no_replace(target, b"staged") - self.assertFalse(target.exists()) - self.assertIsNotNone(temporary_path) - self.assertEqual(temporary_path.read_bytes(), b"unrelated") - - def test_source_to_symlink_race_fails_without_following_victim(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - stage = root / "stage" - target = root / "target" - victim = root / "victim" - stage.write_bytes(b"staged") - victim.write_bytes(b"must remain") - original_rename = artifacts._rename_no_replace - replaced = False - - def replace_source_then_rename(parent_fd, source, destination): - nonlocal replaced - if not replaced: - replaced = True - os.unlink(source, dir_fd=parent_fd) - os.symlink(victim.name, source, dir_fd=parent_fd) - original_rename(parent_fd, source, destination) - - with mock.patch.object(artifacts, "_rename_no_replace", - side_effect=replace_source_then_rename): - with self.assertRaises(artifacts.ArtifactSerializationError): - artifacts.publish_no_replace(stage, target) - self.assertTrue(target.is_symlink()) - self.assertEqual(victim.read_bytes(), b"must remain") - - def test_write_temp_and_publish_stay_on_held_parent_after_replacement(self) -> None: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) / "parent" + root = Path(directory) / "seed-17" root.mkdir() - moved = Path(directory) / "parent-moved" - original_temporary_file = artifacts._temporary_file - - def replace_parent_then_create(parent_fd, target_name): - root.rename(moved) - root.mkdir() - return original_temporary_file(parent_fd, target_name) - - with mock.patch.object(artifacts, "_temporary_file", side_effect=replace_parent_then_create): - artifacts.write_bytes_no_replace(root / "artifact", b"held") - self.assertEqual((moved / "artifact").read_bytes(), b"held") - self.assertFalse((root / "artifact").exists()) - - def test_post_publication_verification_stays_on_held_parent(self) -> None: + identity, value = self.report(root) + value["timings"][0], value["timings"][1] = value["timings"][1], value["timings"][0] + with self.assertRaises(builder.BuildError): + builder.validate_run_report(root=root, seed=17, report=value, + identity=identity) + _, value = self.report(root) + value["staging_path"] = str(root / ".seed-17.stage-wrong-parent") + with self.assertRaises(builder.BuildError): + builder.validate_run_report(root=root, seed=17, report=value, + identity=identity) + + def test_gate_validator_uses_exact_356_gate_and_357_threshold_contract(self): + groups, thresholds = builder._expected_gate_contract() + threshold_map = {item["threshold_id"]: item for item in thresholds} + manifest = {"thresholds": thresholds} + for group, gate_ids in groups.items(): + rows = [] + for gate_id in gate_ids: + threshold = threshold_map[f"threshold.{gate_id}"] + relation = threshold["relation"] + if relation == "eq": + low = high = threshold["lower"] + elif relation == "ge": + low = high = threshold["lower"] + elif relation == "le": + low = high = threshold["upper"] + else: + low = high = 0.0 + rows.append({"gate_id": gate_id, "outcome": "pass", "sample_count": 1, + "observed_min": low, "observed_max": high, + "threshold_id": f"threshold.{gate_id}"}) + manifest[group] = rows + builder._validate_gate_manifest(manifest) + self.assertEqual(sum(len(manifest[name]) for name in groups), 356) + self.assertEqual(len(thresholds), 357) + invalid_ids = [gate_id for gate_id in groups["structural"] + if ".invalid_count." in gate_id] + self.assertEqual(len(invalid_ids), 27) + self.assertTrue(all((threshold_map[f"threshold.{gate_id}"]["relation"], + threshold_map[f"threshold.{gate_id}"]["lower"], + threshold_map[f"threshold.{gate_id}"]["upper"]) + == ("eq", 0, 0) for gate_id in invalid_ids)) + for metric in ("unowned_elements", "overowned_elements"): + hostile = copy.deepcopy(manifest) + for row in hostile["structural"]: + if row["gate_id"].endswith(f"invalid_count.{metric}"): + row["observed_min"] = row["observed_max"] = 1 + with self.subTest(metric=metric), self.assertRaises(builder.BuildError): + builder._validate_gate_manifest(hostile) + manifest["thresholds"][0] = dict(manifest["thresholds"][0], relation="ge") + with self.assertRaises(builder.BuildError): + builder._validate_gate_manifest(manifest) + + def test_ply_validator_accepts_only_canonical_quad_serialization(self): + import render_export as render + vertices = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)) + quads = ((0, 1, 2, 3),) + raw = render.ply_bytes(vertices, quads) + self.assertEqual(builder._parse_ply(raw, "fixture.ply", 4, 1, render), + (vertices, quads)) + with self.assertRaises(builder.BuildError): + builder._parse_ply(raw.replace(b"0 0 0\n", b"0.0 0 0\n", 1), + "fixture.ply", 4, 1, render) + + def test_seed_validator_fails_closed_before_mutating_incomplete_bundle(self): with tempfile.TemporaryDirectory() as directory: - root = Path(directory) / "parent" + root = Path(directory) / "seed-17" root.mkdir() - stage = root / "stage" - stage.mkdir() - (stage / "payload").write_bytes(b"held") - target = root / "bundle" - moved = Path(directory) / "parent-moved" - original_rename = artifacts._rename_no_replace - - def rename_then_replace_parent(parent_fd, source, destination): - original_rename(parent_fd, source, destination) - root.rename(moved) - root.mkdir() - - with mock.patch.object(artifacts, "_rename_no_replace", side_effect=rename_then_replace_parent): - artifacts.publish_no_replace(stage, target) - self.assertEqual((moved / "bundle" / "payload").read_bytes(), b"held") - self.assertFalse((root / "bundle").exists()) + before = tuple(root.iterdir()) + with self.assertRaises(builder.BuildError): + builder.validate_seed_bundle(root=root, seed=17, + identity=identity_fixture()) + self.assertEqual(tuple(root.iterdir()), before) if __name__ == "__main__": diff --git a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py index 1318d75..f0e78ff 100644 --- a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py @@ -5,6 +5,7 @@ import unittest from importlib import import_module from pathlib import Path +from unittest.mock import patch PACKAGE = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PACKAGE)) @@ -12,20 +13,12 @@ P0 = float.fromhex("0x0.0p+0") -N0 = -P0 ONE = float.fromhex("0x1.0000000000000p+0") -HALF = float.fromhex("0x1.0000000000000p-1") D50 = float.fromhex("0x1.0000000000000p-50") MIN_SUBNORMAL = float.fromhex("0x0.0000000000001p-1022") D = float.fromhex("0x1.0000000000000p-46") I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") - -def _pair(a_points, b_points): - points = tuple(a_points) + tuple(b_points) - return points, ((0, 1, 2), (3, 4, 5)) - - def _shared_base(b0=(ONE, P0, P0), b1=(P0, ONE, P0)): shared = (P0, P0, P0) a0 = (ONE, P0, P0) @@ -33,14 +26,6 @@ def _shared_base(b0=(ONE, P0, P0), b1=(P0, ONE, P0)): return [shared, a0, a1], [shared, b0, b1] -def _transform(point, scale, translation): - return tuple(float(float(scale * value) + offset) for value, offset in zip(point, translation)) - - -def _negative_zero(point): - return tuple(math.copysign(0.0, -1.0) if value == 0.0 else value for value in point) - - def _count_fixture(quad_count, control_count=128): points = tuple((float(index), 0.0, 0.0) for index in range(control_count)) faces = [] @@ -79,16 +64,38 @@ def _fixture_shared_one(): ("shared1.coplanar-disjoint-fans", (-ONE, P0, P0), (P0, -ONE, P0), "point-only"), ("shared1.ray-cone-hit", (ONE, ONE, P0), (P0, P0, ONE), "hit"), ("shared1.near-coplanar-full-rank-hit", (ONE, P0, D50), (P0, ONE, -D50), "hit"), - ("shared1.transformed-point-only", (ONE, P0, D50), (P0, ONE, D50), "point-only"), - ("shared1.transformed-hit", (ONE, P0, D50), (P0, ONE, -D50), "hit"), - ("shared1.negative-zero-hit", (ONE, P0, P0), (P0, ONE, P0), "hit"), - ("shared1.level2-ply-point-only", - (float.fromhex("0x1.37918e2798bb6p-8"), float.fromhex("0x1.61bcdab8dcc06p-4"), float.fromhex("0x1.43c9e5ce2aeb6p-4")), - (float.fromhex("0x1.7bc42ac7f04b0p-7"), float.fromhex("0x1.6cae8c4686bb2p-4"), float.fromhex("0x1.0be935f6a339ep-4")), - "point-only"), ) +class _SubtractionRecorder: + def __init__(self, calls): + self.calls = calls + + def __rsub__(self, value): + self.calls.append(value) + return 0.0 + + +class OwnershipRecordTests(unittest.TestCase): + def test_exact_universes_classify_omission_and_duplicate_records(self): + for total in (456, 1742, 6810): + with self.subTest(total=total): + keys = tuple(("element", index) for index in range(total)) + obligations = {key: ("ownership",) for key in keys} + records = tuple((key, "ownership", True) for key in keys) + self.assertEqual(len(keys), total) + self.assertEqual(mesh.classify_ownership_records( + keys, obligations, records)["unowned_elements"], 0) + omitted = mesh.classify_ownership_records( + keys, obligations, records[:-1]) + self.assertEqual((omitted["unowned_elements"], + omitted["overowned_elements"]), (1, 0)) + duplicated = mesh.classify_ownership_records( + keys, obligations, records + ((keys[-1], "ownership", False),)) + self.assertEqual((duplicated["unowned_elements"], + duplicated["overowned_elements"]), (0, 1)) + + _CUBE_DIRECTIONS = ( (1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), @@ -164,14 +171,14 @@ def vertex_id(corner): for name in sorted(arms) } owners = ["surface"] * len(faces) - owners[metadata.index(((1, 1, 0), (0, 0, -1)))] = "flat-seam" - trace = ( - ("sample.0", (0.0, 0.0, 0.0)), - ("sample.1", (1.0, 0.0, 0.0)), - ("sample.2", (1.0, 1.0, 0.0)), - ) - traces = { - f"junction.{index}": (trace, tuple(reversed(trace))) + seam_index = metadata.index(((1, 1, 0), (0, 0, -1))) + owners[seam_index] = "flat-seam" + tags = {vertex: f"sample.{slot}" for slot, vertex in enumerate(faces[seam_index])} + junctions = { + f"junction.{index}": { + "incident_domains": ("flat-seam", "surface"), + "domain_vertex_tags": (dict(tags), dict(tags)), + } for index in range(7) } inputs = { @@ -180,20 +187,49 @@ def vertex_id(corner): "level": 0, "boundary_loops": loops, "port_directions": directions, - "expected_faces": tuple(faces), - "junction_traces": traces, + "expected_base_faces": tuple(faces), + "junction_inputs": junctions, "face_owners": tuple(owners), } return inputs, tuple(metadata), vertex_ids class PrimitiveTests(unittest.TestCase): + def test_full_quad_normal_uses_both_split_triangles(self): + vertices = ((0.0, 0.0, 0.0), (2.0, 0.0, 0.0), + (2.0, 1.0, 0.0), (0.0, 0.0, 2.0)) + actual = mesh.quad_normal(vertices, (0, 1, 2, 3)) + scale = math.sqrt(24.0) + expected = (2.0 / scale, -4.0 / scale, 2.0 / scale) + for component, value in zip(actual, expected): + self.assertAlmostEqual(component, value) + self.assertNotEqual(actual, (0.0, 0.0, 1.0)) + + def test_port_metrics_publish_raw_samples_and_true_extrema(self): + points = ((0.0, 0.0, 0.0), (2.0, 0.0, 0.0), + (2.0, 1.0, 1.0), (1.0, 2.0, 3.0), (0.0, 0.0, 2.0)) + metrics = mesh.port_loop_metrics( + points, (0, 1, 2, 3, 4), (0.0, 0.0, 1.0), + ((0.0, 1.0, 0.0),) * 5) + self.assertEqual(metrics["planarity"], max(metrics["planarity_samples"])) + self.assertEqual(metrics["co_normal"], min(metrics["co_normal_samples"])) + self.assertEqual((len(metrics["planarity_samples"]), + len(metrics["co_normal_samples"])), (5, 5)) + self.assertNotEqual(min(metrics["planarity_samples"]), + max(metrics["planarity_samples"])) + def test_interval_disjoint_uses_both_subtractions_and_one_tolerance(self): just_abutting = math.nextafter(I0, math.inf) self.assertFalse(mesh.interval_disjoint(P0, P0, I0, I0)) self.assertTrue(mesh.interval_disjoint(P0, P0, just_abutting, just_abutting)) self.assertFalse(mesh.interval_disjoint(P0, P0, I0, math.nextafter(I0, math.inf))) + def test_interval_disjoint_materializes_cut_b_then_cut_a_before_disjunction(self): + calls = [] + with patch.object(mesh, "_FIXED_I0", _SubtractionRecorder(calls)): + self.assertTrue(mesh.interval_disjoint(2.0, -1.0, 1.0, 0.0)) + self.assertEqual(calls, [1.0, 2.0]) + def test_shared_one_classifier_is_exact_and_swap_invariant(self): for name, b0, b1, expected in _fixture_shared_one()[:7]: with self.subTest(name=name): @@ -258,7 +294,7 @@ def setUp(self): def test_closed_box_has_valid_topology_and_geometry(self): report = mesh.validate_topology(len(self.points), self.faces) self.assertEqual((report.edge_count, report.boundary_edge_count, report.euler), (12, 0, 2)) - with self.assertRaises(TypeError): + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): mesh.validate_geometry(self.points, self.faces) def test_topology_rejects_same_direction_edge_and_unused_control(self): @@ -291,9 +327,17 @@ def test_port_continuity_and_fold_are_independent(self): (0.0, 1.0, 0.0), adjacent) self.assertEqual(metrics["orientation"], 1.0) self.assertEqual(metrics["co_normal"], 1.0) - traces = ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))) - reverse = tuple(reversed(traces)) - self.assertTrue(mesh.junction_continuity_metrics(traces, reverse)["opposite_trace_direction"]) + owners = ("domain.a",) + ("domain.b",) * (len(self.faces) - 1) + tags = {vertex: f"tag.{slot}" for slot, vertex in enumerate(self.faces[0])} + continuity = mesh.junction_continuity_metrics( + self.points, self.faces, owners, ("domain.a", "domain.b"), + (dict(tags), dict(tags)), + ) + self.assertTrue(continuity["tag_identity"]) + self.assertTrue(continuity["vertex_id_identity"]) + self.assertTrue(continuity["opposite_trace_direction"]) + self.assertTrue(all(len(record) == 3 for trace in continuity["traces"] + for record in trace)) self.assertLess(mesh.validate_fold((1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 0), 90.0) with self.assertRaisesRegex(ValueError, "co-normal"): mesh.validate_port_loop(loop_points, (0, 1, 2, 3), @@ -307,16 +351,31 @@ def test_port_winding_and_continuity_fail_closed(self): (0, 3, 2, 1), (0.0, 1.0, 0.0), ((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (-1.0, 0.0, 0.0), (0.0, 0.0, 1.0))) - with self.assertRaisesRegex(ValueError, "directions"): + old_trace = ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), + (2, (2.0, 0.0, 0.0))) + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): + mesh.junction_continuity_metrics(old_trace, tuple(reversed(old_trace))) + + owners = ("domain.a",) + ("domain.b",) * (len(self.faces) - 1) + tags = {vertex: f"tag.{slot}" for slot, vertex in enumerate(self.faces[0])} + forged = dict(tags) + tag = forged.pop(self.faces[0][0]) + forged[4] = tag + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "vertex IDs"): + mesh.junction_continuity_metrics( + self.points, self.faces, owners, ("domain.a", "domain.b"), + (dict(tags), forged), + ) + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "independent reference"): mesh.junction_continuity_metrics( - ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))), - ((0, (0.0, 0.0, 0.0)), (1, (1.0, 0.0, 0.0)), (2, (2.0, 0.0, 0.0))), + self.points, self.faces, owners, ("domain.a", "domain.b"), + (dict(forged), dict(forged)), (dict(tags), dict(tags)), ) def test_contract_threshold_and_normalization_knobs_are_not_public(self): loop_points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 1.0), (0.0, 0.0, 1.0)) - with self.assertRaises(TypeError): + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): mesh.validate_port_loop(loop_points, (0, 1, 2, 3), (0.0, 1.0, 0.0)) with self.assertRaisesRegex(ValueError, "exact list or tuple"): @@ -325,19 +384,55 @@ def test_contract_threshold_and_normalization_knobs_are_not_public(self): self.assertFalse(hasattr(mesh, "validate_junction_continuity")) triangles = ((0, 1, 2),) points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) - with self.assertRaises(TypeError): + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): mesh.intersection_diagnostics(points, triangles, scale=1.0) - with self.assertRaises(TypeError): + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): mesh.enumerate_broad_phase_candidates(points, triangles, cap=3) with self.assertRaisesRegex(ValueError, "below"): mesh.validate_fold((1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 2) def test_production_geometry_requires_all_selectors_and_gate_data(self): - with self.assertRaises(TypeError): + with self.assertRaisesRegex(mesh.MeshCorrectnessError, "malformed public input"): mesh.validate_geometry(self.points, self.faces) with self.assertRaisesRegex(ValueError, "required"): mesh.validate_geometry(self.points, self.faces, 0, None, None, None, None, None) + def test_frozen_child_face_catalogs_reject_mutated_level_faces(self): + expected_l1 = ( + (0, 4, 8, 5), (1, 6, 8, 4), (2, 7, 8, 6), (3, 5, 8, 7), + ) + expected_l2 = ( + (0, 9, 21, 10), (4, 17, 21, 9), (8, 18, 21, 17), (5, 10, 21, 18), + (1, 12, 22, 11), (6, 19, 22, 12), (8, 17, 22, 19), (4, 11, 22, 17), + (2, 14, 23, 13), (7, 20, 23, 14), (8, 19, 23, 20), (6, 13, 23, 19), + (3, 15, 24, 16), (5, 18, 24, 15), (8, 20, 24, 18), (7, 16, 24, 20), + ) + self.assertEqual( + mesh.derive_expected_face_catalogs(((0, 1, 2, 3),)), + (((0, 1, 2, 3),), expected_l1, expected_l2), + ) + catalogs = mesh.derive_expected_face_catalogs(self.faces) + for level in (1, 2): + with self.subTest(level=level): + actual = list(catalogs[level]) + actual[0] = tuple(reversed(actual[0])) + vertex_count = max(index for face in catalogs[level] for index in face) + 1 + points = tuple((float(index), 0.0, 0.0) for index in range(vertex_count)) + loops = {f"port.{slot}": tuple(range(3 * slot, 3 * slot + 3)) + for slot in range(5)} + with self.assertRaisesRegex(mesh.MeshCorrectnessError, + "face winding/catalog"): + mesh.validate_geometry( + points, tuple(actual), level, loops, {}, self.faces, {}, + ("owner",) * len(actual), + ) + with self.assertRaisesRegex(mesh.MeshCorrectnessError, + "expected_faces index out of range"): + mesh.validate_geometry( + points, catalogs[level], level, loops, {}, catalogs[level], {}, + ("owner",) * len(catalogs[level]), + ) + class GeometryCountTests(unittest.TestCase): def test_level_zero_count_boundaries_reach_the_next_gate(self): @@ -392,8 +487,8 @@ def test_success_runs_every_mandatory_production_gate(self): def test_topology_and_exact_five_port_gates_fail_in_production(self): faces = list(self.inputs["quads"]) faces[0] = tuple(reversed(faces[0])) - with self.assertRaisesRegex(ValueError, "orientation conflict"): - self._validate(quads=tuple(faces), expected_faces=tuple(faces)) + with self.assertRaisesRegex(ValueError, "face winding/catalog"): + self._validate(quads=tuple(faces)) loops = dict(self.inputs["boundary_loops"]) loops.pop("port.4") @@ -430,31 +525,69 @@ def test_structural_intersection_conormal_and_fold_gates_fail_in_production(self with self.assertRaisesRegex(ValueError, "fold angle"): self._validate(face_owners=tuple(owners)) - def test_each_of_seven_junction_residuals_fails_in_production(self): - for name in sorted(self.inputs["junction_traces"]): + def test_each_of_seven_junctions_rejects_forged_vertex_ids(self): + for name in sorted(self.inputs["junction_inputs"]): with self.subTest(name=name): - traces = dict(self.inputs["junction_traces"]) - first, second = traces[name] - bad_second = list(second) - tag, _ = bad_second[0] - bad_second[0] = (tag, (2.0, 2.0, 2.0)) - traces[name] = (first, tuple(bad_second)) - with self.assertRaisesRegex(ValueError, "coordinate residual"): - self._validate(junction_traces=traces) + junctions = {key: dict(value) + for key, value in self.inputs["junction_inputs"].items()} + first, second = junctions[name]["domain_vertex_tags"] + forged = dict(second) + vertex, tag = next(iter(forged.items())) + del forged[vertex] + forged[next(candidate for candidate in range(len(self.inputs["vertices"])) + if candidate not in second)] = tag + junctions[name]["domain_vertex_tags"] = (dict(first), forged) + with self.assertRaisesRegex(ValueError, "vertex IDs"): + self._validate(junction_inputs=junctions) class ProductionIntersectionFixtureTests(unittest.TestCase): - def _assert_pair(self, name, points_a, points_b, expected, stage): - points, triangles = _pair(points_a, points_b) - report = mesh.intersection_diagnostics( - points, triangles, include_classifications=True) - self.assertTrue(report["pair_policy_complete"], name) - self.assertEqual(report["classifications"], (((0, 1), stage),), name) - actual = "hit" if report["intersection_hit_count"] else "point-only" - self.assertEqual(actual, expected, name) - def test_contract_fixture_matrix(self): - executions = 0 + shared_names = ( + "shared1.offset-d50-point-only", "shared1.coplanar-duplicate-hit", + "shared1.offset-positive-minsub-point-only", "shared1.offset-negative-minsub-point-only", + "shared1.coplanar-disjoint-fans", "shared1.ray-cone-hit", + "shared1.near-coplanar-full-rank-hit", "shared1.transformed-point-only", + "shared1.transformed-hit", "shared1.negative-zero-hit", "shared1.level2-ply-point-only", + ) + suffixes = ("p000", "p001", "p010", "p011", "p100", "p101", "p110", "p111") + general = ( + "shared0.clear-hit-origin", "shared0.clear-hit-translated", + "shared0.sub-I0-contact-origin", "shared0.sub-I0-contact-translated", + "shared0.aabb-disjoint", "shared0.sat-disjoint", "shared0.extreme-small-hit", + "shared0.extreme-large-hit", "normal.boundary-D-reject", "normal.successor-D-accept", + "shared2.opposite-edge-valid", "shared2.same-direction-reject", + "shared3.duplicate-triangle-reject", "triangle-cap.boundary-4096", + "triangle-cap.successor-4097", "candidate-cap.boundary-injected-3", + "candidate-cap.successor-injected-3", + ) + expected_ids = tuple(f"{name}.{suffix}" for name in shared_names + for suffix in suffixes) + general + shared_outcomes = tuple( + outcome + for outcome in ( + "point-only", "hit", "point-only", "point-only", "point-only", + "hit", "hit", "point-only", "hit", "hit", "point-only", + ) + for _ in suffixes + ) + general_outcomes = ( + "hit", "hit", "hit", "hit", "aabb-disjoint", "sat-disjoint", + "hit", "hit", "hard-failure", "pass", "excluded-adjacent", + "hard-failure", "hard-failure", "pass", "hard-failure", "hit", + "hard-failure", + ) + artifact_failure = AssertionError("fixture runner emitted an artifact") + with ( + patch("builtins.open", side_effect=artifact_failure), + patch.object(Path, "open", side_effect=artifact_failure), + patch.object(Path, "mkdir", side_effect=artifact_failure), + patch.object(Path, "touch", side_effect=artifact_failure), + patch.object(Path, "write_bytes", side_effect=artifact_failure), + patch.object(Path, "write_text", side_effect=artifact_failure), + ): + records = mesh.run_production_intersection_fixtures() + self.assertEqual(mesh.MAX_CANDIDATES, 1_000_000) self.assertEqual( mesh.intersection_candidate_threshold_records(), @@ -469,164 +602,13 @@ def test_contract_fixture_matrix(self): for level in range(3) ), ) - for name, b0, b1, expected in _fixture_shared_one(): - if name == "shared1.level2-ply-point-only": - shared = (float.fromhex("0x1.8b59f7e4bf4dfp-7"), float.fromhex("0x1.0a35e0636f7c1p-4"), float.fromhex("0x1.264d28c7c3da4p-4")) - first = [shared, b0, b1] - second = [shared, - (float.fromhex("0x1.7888e87a16156p-6"), float.fromhex("0x1.7eec0987f75cdp-4"), float.fromhex("0x1.d5d88ce274e30p-5")), - (float.fromhex("0x1.8b59f7e4bf4dfp-6"), float.fromhex("0x1.18982604f83a1p-4"), float.fromhex("0x1.07df2315527a3p-4"))] - else: - first, second = _shared_base(b0, b1) - if name == "shared1.transformed-point-only" or name == "shared1.transformed-hit": - translation = (4.0, -2.0, 1.0) - first = [_transform(point, 8.0, translation) for point in first] - second = [_transform(point, 8.0, translation) for point in second] - if name == "shared1.negative-zero-hit": - first = [_negative_zero(point) for point in first] - second = [_negative_zero(point) for point in second] - base_points = tuple(first) + tuple(second[1:]) - base_triangles = ((0, 1, 2), (0, 3, 4)) - for suffix in ("p000", "p001", "p010", "p011", "p100", "p101", "p110", "p111"): - a = list(base_triangles[0]) - b = list(base_triangles[1]) - if suffix[1] == "1": - a, b = b, a - if suffix[2] == "1": - a[1], a[2] = a[2], a[1] - if suffix[3] == "1": - b[1], b[2] = b[2], b[1] - report = mesh.intersection_diagnostics( - base_points, (tuple(a), tuple(b)), include_classifications=True) - self.assertTrue(report["pair_policy_complete"], f"{name}.{suffix}") - self.assertEqual(report["classifications"], (((0, 1), expected),), f"{name}.{suffix}") - actual = "hit" if report["intersection_hit_count"] else "point-only" - self.assertEqual(actual, expected, f"{name}.{suffix}") - executions += 1 - - general = ( - ("shared0.clear-hit-origin", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), - ((0.0, -1.0, 0.0), (HALF, HALF, 0.0), (-HALF, HALF, 0.0)), "hit"), - ("shared0.clear-hit-translated", ((4.0, -2.0, 1.0), (5.0, -2.0, 1.0), (4.0, -1.0, 1.0)), - ((4.0, -3.0, 1.0), (4.5, -1.5, 1.0), (3.5, -1.5, 1.0)), "hit"), - ("shared0.sub-I0-contact-origin", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), - ((0.0, 0.0, float.fromhex("0x1.0000000000000p-34")), (1.0, 0.0, float.fromhex("0x1.0000000000000p-34")), (0.0, 1.0, float.fromhex("0x1.0000000000000p-34"))), "hit"), - ("shared0.sub-I0-contact-translated", ((4.0, -2.0, 1.0), (5.0, -2.0, 1.0), (4.0, -1.0, 1.0)), - ((4.0, -2.0, 1.0 + float.fromhex("0x1.0000000000000p-34")), (5.0, -2.0, 1.0 + float.fromhex("0x1.0000000000000p-34")), (4.0, -1.0, 1.0 + float.fromhex("0x1.0000000000000p-34"))), "hit"), - ("shared0.aabb-disjoint", ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), ((0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (0.0, 1.0, 1.0)), "point-only"), - ("shared0.sat-disjoint", ((0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (0.0, 2.0, 0.0)), ((2.0, 2.0, 0.0), (2.0, 1.5, 0.0), (1.5, 2.0, 0.0)), "point-only"), - ("shared0.extreme-small-hit", tuple(tuple(float(2.0 ** -500 * x) for x in point) for point in ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))), - tuple(tuple(float(2.0 ** -500 * x) for x in point) for point in ((0.0, -1.0, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0))), "hit"), - ("shared0.extreme-large-hit", tuple(tuple(float(2.0 ** 500 * x) for x in point) for point in ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))), - tuple(tuple(float(2.0 ** 500 * x) for x in point) for point in ((0.0, -1.0, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0))), "hit"), - ) - stages = { - "shared0.clear-hit-origin": "hit", - "shared0.clear-hit-translated": "hit", - "shared0.sub-I0-contact-origin": "hit", - "shared0.sub-I0-contact-translated": "hit", - "shared0.aabb-disjoint": "aabb-disjoint", - "shared0.sat-disjoint": "sat-disjoint", - "shared0.extreme-small-hit": "hit", - "shared0.extreme-large-hit": "hit", - } - for name, first, second, expected in general: - self._assert_pair(name, first, second, expected, stages[name]) - executions += 1 - - with self.assertRaisesRegex(ValueError, "normalized triangle normal"): - mesh.intersection_diagnostics(((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, D, 0.0)), ((0, 1, 2),)) - self.assertEqual(mesh.intersection_diagnostics( - ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, float.fromhex("0x1.0000000000000p-45"), 0.0)), ((0, 1, 2),) - )["intersection_hit_count"], 0) - executions += 2 - - valid_shared2 = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0)) - self.assertEqual( - mesh.intersection_diagnostics( - valid_shared2, ((0, 1, 2), (1, 0, 3)), - include_classifications=True, - )["classifications"], - (((0, 1), "excluded-adjacent"),), - ) - executions += 1 - with self.assertRaisesRegex(ValueError, "shared-two"): - mesh.intersection_diagnostics(valid_shared2, ((0, 1, 2), (0, 1, 3))) - executions += 1 - with self.assertRaisesRegex(ValueError, "duplicate triangle"): - mesh.intersection_diagnostics(((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), ((0, 1, 2), (0, 1, 2))) - executions += 1 - - cap_points = [] - cap_triangles = [] - for row in range(4096): - offset = 3 * row - x = float(4 * row) - cap_points.extend(((x, 0.0, 0.0), (float(x + 1.0), 0.0, 0.0), (x, 1.0, 0.0))) - cap_triangles.append((offset, offset + 1, offset + 2)) - cap_report = mesh.intersection_diagnostics(tuple(cap_points), tuple(cap_triangles)) - self.assertEqual((cap_report["triangle_count"], cap_report["broad_phase_candidate_count"]), (4096, 0)) - pair_count = 4096 * 4095 // 2 - evidence = cap_report["pair_policy_evidence"] - self.assertEqual(cap_report["pair_count"], pair_count) - self.assertEqual( - (evidence["expected_pair_count"], evidence["processed_pair_count"]), - (pair_count, pair_count), - ) - self.assertEqual( - (evidence["first_pair"], evidence["last_pair"]), - ((0, 1), (4094, 4095)), - ) - self.assertEqual( - evidence["class_counts"], - (("aabb-disjoint", pair_count), ("sat-disjoint", 0), - ("hit", 0), ("point-only", 0), ("excluded-adjacent", 0)), - ) - self.assertEqual(evidence["nontrivial_pair_count"], 0) - self.assertEqual(evidence["nontrivial_classifications"], ()) - self.assertFalse(evidence["nontrivial_evidence_truncated"]) - self.assertEqual(cap_report["candidate_pairs"], ()) - self.assertEqual(cap_report["hit_pairs"], ()) - self.assertFalse(cap_report["candidate_pairs_truncated"]) - self.assertFalse(cap_report["hit_pairs_truncated"]) - self.assertIsNone(cap_report["first_hit_pair"]) - self.assertNotIn("classifications", cap_report) - self.assertTrue(cap_report["pair_policy_complete"]) - with self.assertRaisesRegex(ValueError, "classification detail cap"): - mesh.intersection_diagnostics( - tuple(cap_points), tuple(cap_triangles), include_classifications=True) - executions += 1 - with self.assertRaisesRegex(ValueError, "triangle cap"): - mesh.intersection_diagnostics(tuple(cap_points) + ((0.0, 0.0, 0.0), - (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), - tuple(cap_triangles) + ((12288, 12289, 12290),)) - executions += 1 - - candidate_points = tuple(point for _ in range(3) for point in ((0.0, 0.0, 0.0), - (1.0, 0.0, 0.0), - (0.0, 1.0, 0.0))) - candidate_triangles = tuple((3 * row, 3 * row + 1, 3 * row + 2) for row in range(3)) - boundary_report = mesh.intersection_diagnostics( - candidate_points, candidate_triangles, include_classifications=True) - self.assertEqual(boundary_report["candidate_pairs"], ((0, 1), (0, 2), (1, 2))) - self.assertEqual(boundary_report["intersection_hit_count"], 3) - self.assertEqual(boundary_report["hit_pairs"], ((0, 1), (0, 2), (1, 2))) - self.assertEqual(boundary_report["first_hit_pair"], (0, 1)) - self.assertFalse(boundary_report["candidate_pairs_truncated"]) - self.assertFalse(boundary_report["hit_pairs_truncated"]) - self.assertEqual( - boundary_report["classifications"], - (((0, 1), "hit"), ((0, 2), "hit"), ((1, 2), "hit")), - ) - self.assertEqual(mesh._enumerate_fixture_candidates(candidate_points, candidate_triangles, 3), - ((0, 1), (0, 2), (1, 2))) - executions += 1 - with self.assertRaisesRegex(ValueError, "candidate cap"): - mesh._enumerate_fixture_candidates( - candidate_points + ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), - candidate_triangles + ((9, 10, 11),), 3) - executions += 1 - self.assertEqual(executions, 105) + self.assertEqual(len(records), 105) + self.assertEqual(mesh.INTERSECTION_FIXTURE_IDS, expected_ids) + self.assertEqual(tuple(record["fixture_id"] for record in records), expected_ids) + self.assertTrue(all(tuple(record) == ("fixture_id", "outcome") + for record in records)) + self.assertEqual(tuple(record["outcome"] for record in records), + shared_outcomes + general_outcomes) def test_all_hit_diagnostics_keep_exact_counts_and_bounded_pair_evidence(self): triangle = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) @@ -645,7 +627,24 @@ def test_all_hit_diagnostics_keep_exact_counts_and_bounded_pair_evidence(self): self.assertTrue(report["hit_pairs_truncated"]) self.assertEqual(report["candidate_pairs"], report["hit_pairs"]) self.assertTrue(report["pair_policy_complete"]) + evidence = report["pair_policy_evidence"] + self.assertEqual( + (evidence["expected_pair_count"], evidence["processed_pair_count"], + evidence["first_pair"], evidence["last_pair"]), + (pair_count, pair_count, (0, 1), (98, 99)), + ) + self.assertEqual(evidence["class_counts"], ( + ("aabb-disjoint", 0), ("sat-disjoint", 0), ("hit", pair_count), + ("point-only", 0), ("excluded-adjacent", 0), + )) + self.assertEqual(evidence["nontrivial_pair_count"], pair_count) + self.assertEqual(len(evidence["nontrivial_classifications"]), 64) + self.assertEqual(evidence["nontrivial_classifications"][0], ((0, 1), "hit")) + self.assertTrue(evidence["nontrivial_evidence_truncated"]) self.assertNotIn("classifications", report) + with self.assertRaisesRegex(ValueError, "classification detail cap"): + mesh.intersection_diagnostics( + points, triangles, include_classifications=True) def test_candidate_cap_fixture_helper_is_local_and_deterministic(self): points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), diff --git a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py new file mode 100644 index 0000000..0146e2a --- /dev/null +++ b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py @@ -0,0 +1,400 @@ +from __future__ import annotations + +import sys +import unittest +from copy import deepcopy +from dataclasses import replace +from pathlib import Path +from unittest.mock import patch + +HERE = Path(__file__).resolve().parents[1] +REPO = HERE.parents[1] +sys.path.insert(0, str(HERE)) +import anatomy_gates as anatomy +import chart_lineage as chart +import owned_root_surface as surface +import prepared_projection + + +def prepared(): + return prepared_projection.prepare_standard_neutral( + REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" + ) + + +def independent_charts(evaluation): + """Build valid chart ancestry while anatomy remains the unit under test.""" + return chart.build_chart_summary(evaluation, evaluation.cage.formula_records) + + +class CatalogTests(unittest.TestCase): + def test_independent_catalog_counts_and_boundary_inventory(self): + report = surface.validate_catalogs() + self.assertEqual((len(surface.CELL_CATALOG), len(surface.DOMAINS)), (58, 8)) + self.assertEqual((report.vertex_count, report.edge_count, report.face_count), (120, 227, 104)) + self.assertEqual((report.boundary_edge_count, report.boundary_components), (38, 5)) + self.assertEqual(report.euler_characteristic, -3) + self.assertEqual(len(report.extraordinary_controls), 20) + self.assertEqual(len(surface.JUNCTION_INFO), 7) + self.assertEqual(len(surface.PORT_INFO), 5) + + expected_ports = { + "port.neck": ("c057", "c079", "c080", "c081", "c059", "c058"), + "port.left_arm": ("c009", "c012", "c014", "c015", "c016", "c013", "c011", "c010"), + "port.right_arm": ("c112", "c113", "c114", "c116", "c119", "c118", "c117", "c115"), + "port.left_thigh": ("c000", "c001", "c002", "c018", "c040", "c039", "c038", "c017"), + "port.right_thigh": ("c060", "c061", "c062", "c083", "c105", "c104", "c103", "c082"), + } + self.assertEqual({key: value[2] for key, value in surface.PORT_INFO.items()}, expected_ports) + + def test_public_surface_boundary_has_no_chart_or_sample_outputs(self): + ids, faces, ports = surface.symbolic_topology() + self.assertEqual((len(ids), len(faces), len(ports)), (120, 104, 5)) + self.assertEqual(tuple(name for name, _ in ports), surface.PORTS) + self.assertEqual(surface.FACE_RECORDS[0], ("q000", "domain.left_hip", ("c000", "c001", "c004", "c003"))) + self.assertNotIn("_make_chart_records", surface.__dict__) + self.assertNotIn("_attach_samples", surface.__dict__) + + +class SurfaceTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.prepared = prepared() + cls.evaluation = surface.evaluate(cls.prepared) + + def test_formula_candidates_use_prepared_boundary_and_exact_dispatch(self): + with patch.object(surface.prepared_projection, "validate_prepared", + wraps=surface.prepared_projection.validate_prepared) as admitted: + cage = surface.build_cage(self.prepared) + admitted.assert_called_once_with(self.prepared) + self.assertEqual((len(cage.vertices), len(cage.quads), len(cage.formula_records)), (120, 104, 120)) + records = {r["control_id"]: r for r in cage.formula_records} + self.assertEqual(records["c023"]["formula_id"], "formula.axial.j1.interior") + self.assertIn("stations.lower_abdomen.rA", records["c023"]["geometry_dependencies"]) + self.assertNotIn("stations.lower_abdomen.rP", records["c023"]["geometry_dependencies"]) + self.assertNotIn("stations.upper_pelvis.rL", records["c023"]["geometry_dependencies"]) + self.assertEqual(records["c031"]["formula_id"], "formula.shoulder.left") + self.assertNotIn("shoulders.left.start_up", records["c031"]["geometry_dependencies"]) + self.assertNotIn("hips.left.P_s.x", records["c003"]["geometry_dependencies"]) + self.assertIn("hips.left.P_s.x", records["c020"]["geometry_dependencies"]) + self.assertEqual(set(cage.formula_ids), set(surface.FORMULAS)) + + def test_prepared_admission_rejects_malformed_binary64_and_rotation(self): + bad = deepcopy(self.prepared) + bad["stations"]["lower_pelvis"]["C"] = (0, -0.45, 0.0) + with self.assertRaises(prepared_projection.PreparedProjectionError): surface.build_cage(bad) + bad = deepcopy(self.prepared) + bad["parts"][0]["placement"]["rotation_xyzw"][3] = 0.5 + with self.assertRaises(prepared_projection.PreparedProjectionError): surface.build_cage(bad) + + def test_subdivision_has_exact_numeric_topology_incidence_and_lineage(self): + cage, level1, level2 = self.evaluation.cage, *self.evaluation.levels + self.assertEqual([(len(m.vertices), len(m.quads), len(m.triangles)) for m in (cage, level1, level2)], + [(120, 104, 208), (451, 416, 832), (1737, 1664, 3328)]) + self.assertEqual((level1.control_ids[0], level2.control_ids[-1], level2.face_ids[-1]), + ("vertex.L1.v0000", "vertex.L2.v1736", "face.L2.q1663")) + for mesh in (cage, level1, level2): + self.assertFalse(hasattr(mesh, "chart_records")) + self.assertFalse(hasattr(mesh, "transition_records")) + self.assertTrue(all("samples" not in row for row in mesh.vertex_records)) + incidence = surface.subdivision_incidence(cage) + self.assertEqual((len(incidence["edges"]), len(incidence["child_emission"])), (227, 416)) + self.assertEqual(incidence["child_emission"][0], (0, 0, (0, 120, 347, 121))) + self.assertEqual(len(surface.propagate_port_loops(level1)["port.neck"]), 24) + self.assertLessEqual(max(len(r["base_control_contributors"]) for r in level2.vertex_records), 20) + self.assertLessEqual(max(len(r["geometry_dependency_union"]) for r in level2.vertex_records), 54) + self.assertLessEqual(max(len(r["contributor_domains"]) for r in level2.vertex_records), 5) + + def test_contributor_domains_follow_catalog_order_and_forged_topology_fails(self): + cage = self.evaluation.cage + junction = cage.vertex_records[cage.control_ids.index("c021")] + self.assertEqual(junction["contributor_domains"], ("domain.pelvis", "domain.abdomen")) + self.assertEqual(surface.CONTROL_DOMAIN_INCIDENTS["c021"], ("domain.pelvis", "domain.abdomen")) + bad = list(cage.quads); bad[0] = (bad[0][1], bad[0][0], bad[0][2], bad[0][3]) + with self.assertRaises(ValueError): surface.validate_level_structure(replace(cage, quads=tuple(bad)), self.prepared) + + def test_anatomy_rejects_forged_level_zero_triangles(self): + bad = replace(self.evaluation.cage, triangles=self.evaluation.cage.triangles[:-1] + ((0, 1, 2, 3),)) + forged = surface.SurfaceEvaluation(bad, self.evaluation.levels) + with self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(forged, prepared=self.prepared) + + def test_analytic_derivatives_propagate_and_support_is_exact(self): + derivative = surface.analytic_control_derivatives(self.prepared, "hips.left.P_s.x") + self.assertEqual(derivative[self.evaluation.cage.control_ids.index("c003")], (0.0, 0.0, 0.0)) + self.assertEqual(len(surface.predicted_support(self.prepared, "hips.left.P_s.x")), 436) + self.assertEqual(len(surface.predicted_support(self.prepared, "hips.right.P_s.x")), 436) + with self.assertRaises(ValueError): surface.predicted_support(self.prepared, "outside.component") + + def test_analytic_support_ignores_formula_record_dependency_metadata(self): + component = "hips.left.P_s.x" + derivative = surface.analytic_control_derivatives(self.prepared, component) + support = surface.predicted_support(self.prepared, component) + for name, dependencies in (("stripped", []), ("corrupt", ["outside.component"])): + records = deepcopy(surface.formula_candidate_records(self.prepared)) + for record in records: record["geometry_dependencies"] = dependencies + with self.subTest(metadata=name), patch.object(surface, "formula_candidate_records", return_value=records): + self.assertEqual(surface.analytic_control_derivatives(self.prepared, component), derivative) + self.assertEqual(surface.predicted_support(self.prepared, component), support) + with self.assertRaises(ValueError): surface.analytic_control_derivatives(self.prepared, "outside.component") + + def test_all_33_public_perturbations_match_exact_analytic_support(self): + baseline = self.evaluation.levels[1] + original = prepared_projection.canonical_json_bytes(self.prepared) + tolerance = float.fromhex("0x1.c666666666666p-45") + self.assertEqual((len(surface.MUST_AFFECT_PARAMETER_IDS), surface.PERTURBATION_DELTA_M), (33, 0.01)) + for parameter in surface.MUST_AFFECT_PARAMETER_IDS: + with self.subTest(parameter=parameter): + component = surface.MUST_AFFECT_COMPONENTS[parameter]; path = component.split(".") + if path[-1] in "xyz": path[-1] = "xyz".index(path[-1]) + expected = deepcopy(self.prepared); target = expected + for part in path[:-1]: target = target[part] + target[path[-1]] = float(target[path[-1]] + surface.PERTURBATION_DELTA_M) + self.assertEqual(surface.perturb_prepared(self.prepared, parameter), expected) + cage = surface.build_perturbed_cage(self.prepared, parameter) + evaluation = surface.evaluate_perturbation(self.prepared, parameter) + self.assertEqual(cage, evaluation.cage); surface.validate_evaluation(evaluation, expected) + predicted = surface.predicted_support(self.prepared, component) + movement = tuple(sum((evaluation.levels[1].vertices[i][axis] - baseline.vertices[i][axis]) ** 2 for axis in range(3)) ** .5 for i in range(1737)) + observed = tuple(i for i, value in enumerate(movement) if value > tolerance) + self.assertTrue(predicted); self.assertEqual(predicted, observed) + self.assertLessEqual(max((movement[i] for i in range(1737) if i not in predicted), default=0.0), tolerance) + self.assertEqual(prepared_projection.canonical_json_bytes(self.prepared), original) + + def test_l0_lineage_fields_are_independently_admitted(self): + cage = self.evaluation.cage + formula_records = list(deepcopy(cage.formula_records)); formula_records[0]["formula_id"] = "forged" + vertex_records = list(deepcopy(cage.vertex_records)); vertex_records[0]["contributor_domains"] = () + probes = { + "formula_ids": replace(cage, formula_ids=("forged", *cage.formula_ids[1:])), + "dependencies": replace(cage, dependencies=(("forged",), *cage.dependencies[1:])), + "source_stencils": replace(cage, source_stencils=(cage.source_stencils[1], *cage.source_stencils[1:])), + "formula_records": replace(cage, formula_records=tuple(formula_records)), + "vertex_records": replace(cage, vertex_records=tuple(vertex_records)), + } + for name, forged in probes.items(): + with self.subTest(field=name), self.assertRaises(ValueError): surface.validate_level_structure(forged, self.prepared) + with self.subTest(evaluation_field=name), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged, self.evaluation.levels), self.prepared) + + def test_l0_coordinates_are_independently_recomputed_from_prepared(self): + cage = self.evaluation.cage; vertices = list(cage.vertices); records = deepcopy(cage.formula_records) + vertices[0] = (float(vertices[0][0] + .01), *vertices[0][1:]); records[0]["coordinate"][0] = vertices[0][0] + forged = replace(cage, vertices=tuple(vertices), formula_records=tuple(records)) + level1 = surface.subdivide(forged, 1); level2 = surface.subdivide(level1, 2) + evaluation = surface.SurfaceEvaluation(forged, (level1, level2)) + with self.assertRaises(ValueError): surface.validate_level_structure(forged, self.prepared) + with self.assertRaises(ValueError): surface.validate_evaluation(evaluation, self.prepared) + + def test_l1_l2_fields_are_exactly_parent_derived(self): + meshes = [self.evaluation.cage, *self.evaluation.levels] + for level in (1, 2): + mesh = meshes[level]; quads = (mesh.quads[0][1:] + mesh.quads[0][:1], *mesh.quads[1:]) + triangles = tuple(item for face in quads for item in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) + loops = list(mesh.boundary_loops); name, loop = loops[0]; loops[0] = (name, loop[1:] + loop[:1]) + formula_records = list(deepcopy(mesh.formula_records)); formula_records[0]["formula_id"] = "forged" + vertex_records = list(deepcopy(mesh.vertex_records)); vertex_records[0]["vertex_id"] = "forged" + probes = { + "cycles": replace(mesh, quads=quads, triangles=triangles), + "coordinates": replace(mesh, vertices=((mesh.vertices[0][0] + .01, *mesh.vertices[0][1:]), *mesh.vertices[1:])), + "loops": replace(mesh, boundary_loops=tuple(loops)), + "formula_ids": replace(mesh, formula_ids=("forged", *mesh.formula_ids[1:])), + "dependencies": replace(mesh, dependencies=(mesh.dependencies[0] + ("forged",), *mesh.dependencies[1:])), + "formula_records": replace(mesh, formula_records=tuple(formula_records)), + "vertex_records": replace(mesh, vertex_records=tuple(vertex_records)), + "stencils": replace(mesh, source_stencils=(mesh.source_stencils[0] + (mesh.source_stencils[0][0],), *mesh.source_stencils[1:])), + "triangles": replace(mesh, triangles=(mesh.triangles[1], mesh.triangles[0], *mesh.triangles[2:])), + } + for field, child in probes.items(): + with self.subTest(level=level, field=field), self.assertRaises(ValueError): surface.validate_level_structure(child, self.prepared, meshes[level - 1]) + forged = list(meshes); forged[level] = child + with self.subTest(evaluation_level=level, evaluation_field=field), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged[0], tuple(forged[1:])), self.prepared) + + def test_independent_references_reject_coordinated_producer_defects(self): + def bad_formula(prepared, control, producer=surface._formula_for_control): formula, dependencies, point, parameters = producer(prepared, control); return formula, dependencies, (float(point[0] + .01), point[1], point[2]), parameters + with patch.object(surface, "_formula_for_control", side_effect=bad_formula), self.assertRaisesRegex(ValueError, "independent prepared reference"): surface.build_cage(self.prepared) + def bad_subdivision(parent, level, points=None, producer=surface._subdivide_once): child = producer(parent, level, points); vertices = list(child.vertices); vertices[0] = (float(vertices[0][0] + .01), *vertices[0][1:]); return replace(child, vertices=tuple(vertices)) + with patch.object(surface, "_subdivide_once", side_effect=bad_subdivision), self.assertRaisesRegex(ValueError, "parent-derived vertices"): surface.subdivide(self.evaluation.cage, 1) + def bad_record(level, vertex_id, contributors, formulas, producer=surface._record): return producer(level, vertex_id, contributors, formulas) | {"contributor_domains": ()} + with patch.object(surface, "_record", side_effect=bad_record), self.assertRaisesRegex(ValueError, "parent-derived vertex_records"): surface.subdivide(self.evaluation.cage, 1) + + +class ChartLineageTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.prepared = prepared() + cls.evaluation = surface.evaluate(cls.prepared) + cls.formulas = surface.formula_candidate_records(cls.prepared) + cls.summary = chart.build_chart_summary(cls.evaluation, cls.formulas) + + def test_exact_closed_inventory_ids_and_source_boundary(self): + summary = self.summary + self.assertEqual([row["charts"] for row in summary["level_counts"]], [104, 416, 1664]) + self.assertEqual([row["interior_transitions"] for row in summary["level_counts"]], [189, 794, 3252]) + self.assertEqual((len(summary["chart_records"]), len(summary["transition_records"]), + len(summary["vertex_records"])), (2184, 4235, 2308)) + self.assertEqual([sum(row["level"] == level for row in summary["vertex_records"]) + for level in range(3)], [120, 451, 1737]) + self.assertEqual([row["maximum_samples_per_vertex"] for row in summary["level_counts"]], [5, 5, 5]) + level2 = [row["chart_id"] for row in summary["chart_records"] if row["level"] == 2] + self.assertEqual((level2[0], level2[-1]), + ("chart.q000/L2.s0.s0", "chart.q103/L2.s3.s3")) + self.assertEqual(len({item for row in self.formulas + for item in row["geometry_dependencies"]}), 92) + self.assertEqual(len(self.formulas), 120) + self.assertLessEqual(max(len(row["geometry_dependencies"]) for row in self.formulas), 12) + lines = (HERE / "chart_lineage.py").read_text(encoding="utf-8").count("\n") + self.assertIn(lines, range(190, 269)) + self.assertLessEqual(Path(__file__).read_text(encoding="utf-8").count("\n"), 400) + + def test_summary_rejects_closed_schema_duplicate_and_lineage_forgeries(self): + def extra(value): + value["unexpected"] = None + def open_chart(value): + value["chart_records"][0]["unexpected"] = None + def open_transition(value): + value["transition_records"][0]["unexpected"] = None + def open_vertex(value): + value["vertex_records"][0]["unexpected"] = None + def duplicate_chart(value): + value["chart_records"][0] = value["chart_records"][1] + def rotate_cycle(value): + corners = value["chart_records"][1]["corners"] + value["chart_records"][1]["corners"] = corners[1:] + corners[:1] + def forge_l2_id(value): + value["chart_records"][5]["chart_id"] = "chart.q000/L1.s0/L2.s0" + def forge_uv(value): + value["chart_records"][5]["corners"][0]["u"]["denominator"] = 3 + def duplicate_transition(value): + value["transition_records"][0] = value["transition_records"][1] + def duplicate_vertex(value): + value["vertex_records"][0] = value["vertex_records"][1] + def empty_samples(value): + value["vertex_records"][0]["samples"] = [] + def forge_contributor(value): + value["vertex_records"][-1]["base_control_contributors"] = ["c000"] + probes = (extra, open_chart, open_transition, open_vertex, duplicate_chart, + rotate_cycle, forge_l2_id, forge_uv, duplicate_transition, + duplicate_vertex, empty_samples, forge_contributor) + for mutate in probes: + forged = deepcopy(self.summary) + mutate(forged) + with self.subTest(probe=mutate.__name__), self.assertRaises(chart.ChartLineageError): + chart.validate_chart_summary(forged, self.evaluation, self.formulas) + + def test_formula_inventory_schema_owner_dependency_and_coordinate_forgeries(self): + def extra(value): + value[0]["unexpected"] = None + def duplicate(value): + value[1] = deepcopy(value[0]) + def owner(value): + value[0]["construction_owner"] = "domain.thorax" + def dependencies(value): + value[0]["geometry_dependencies"] = [f"forged.{i}" for i in range(13)] + def dependency_universe(value): + deps = set(value[0]["geometry_dependencies"]) + deps.remove(min(deps)) + deps.add("stations.forged.C.x") + value[0]["geometry_dependencies"] = sorted(deps) + def coordinate(value): + value[0]["coordinate"][0] = float("nan") + for mutate in (extra, duplicate, owner, dependencies, dependency_universe, coordinate): + forged = list(deepcopy(self.formulas)) + mutate(forged) + with self.subTest(probe=mutate.__name__), self.assertRaises(chart.ChartLineageError): + chart.build_chart_summary(self.evaluation, tuple(forged)) + with self.assertRaises(chart.ChartLineageError): + chart.build_chart_summary(self.evaluation, self.formulas[:-1]) + + def test_neutral_topology_and_junction_candidates_are_independently_checked(self): + level1 = self.evaluation.levels[0] + faces = list(level1.quads) + faces[0] = faces[0][1:] + faces[0][:1] + forged = surface.SurfaceEvaluation(self.evaluation.cage, + (replace(level1, quads=tuple(faces)), self.evaluation.levels[1])) + with self.assertRaises(chart.ChartLineageError): + chart.build_chart_summary(forged, self.formulas) + traces = list(deepcopy(surface.junction_trace_inputs())) + traces[0]["base_control_ids"] = traces[0]["base_control_ids"][1:] + with patch.object(surface, "junction_trace_inputs", return_value=tuple(traces)), self.assertRaises(chart.ChartLineageError): + chart.build_chart_summary(self.evaluation, self.formulas) + junction = surface.junction_trace_inputs()[0]["junction_id"] + tags = list(surface.propagate_junction_tags(self.evaluation, junction)) + tags[0] = dict(tags[0]) + tags[0].pop(next(iter(tags[0]))) + with patch.object(surface, "propagate_junction_tags", return_value=tuple(tags)), self.assertRaises(chart.ChartLineageError): + chart.build_chart_summary(self.evaluation, self.formulas) + + def test_chart_uses_public_neutral_inputs_not_private_surface_oracles(self): + with patch.object(surface, "_formula_for_control", side_effect=AssertionError("private oracle")): + rebuilt = chart.build_chart_summary(self.evaluation, self.formulas) + self.assertEqual(rebuilt, self.summary) + source = (HERE / "chart_lineage.py").read_text(encoding="utf-8") + self.assertNotIn("surface._", source) + chart.validate_chart_summary(rebuilt, self.evaluation, self.formulas) + + +class AnatomyTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.prepared = prepared() + cls.evaluation = surface.evaluate(cls.prepared) + cls.charts = independent_charts(cls.evaluation) + + def test_independent_selectors_and_exact_anatomy_inventory(self): + levels = anatomy.validate_evaluated_surface(self.evaluation, self.charts, prepared=self.prepared) + self.assertEqual(len(levels), 3) + self.assertEqual(anatomy.validate_evaluated_surface(self.evaluation, self.charts), levels) + self.assertEqual(len(anatomy.select_trace(self.evaluation, "port.neck", 2, self.charts, prepared=self.prepared)), 24) + measures = anatomy.measure_anatomy(self.evaluation, self.prepared, self.charts) + self.assertEqual(len(measures), 78) + self.assertEqual(len(anatomy.anatomy_threshold_records()), 78) + self.assertEqual(len(anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts)), 78) + self.assertGreater(measures["anatomy.pelvic_lateral_ratio.left.L2"]["omitted_count"], 0) + + def test_forged_chart_ancestry_and_corner_incidence_fail_closed(self): + mutations = [] + records = lambda value, level: [row for row in value["chart_records"] if row["level"] == level] + bad = deepcopy(self.charts); records(bad, 0)[0]["construction_owner"] = "domain.thorax"; mutations.append(bad) + bad = deepcopy(self.charts); records(bad, 2)[0]["base_face_id"] = "q001"; mutations.append(bad) + bad = deepcopy(self.charts); records(bad, 1)[0]["corners"][0]["vertex_id"] = "vertex.L1.v0001"; mutations.append(bad) + bad = deepcopy(self.charts); bad["chart_records"].pop(); mutations.append(bad) + for forged in mutations: + with self.assertRaises(anatomy.AnatomyGateError): anatomy.measure_anatomy(self.evaluation, self.prepared, forged) + + def test_chart_levels_require_exact_bounded_integers(self): + boolean = deepcopy(self.charts); boolean["chart_records"][0]["level"] = False + surplus = deepcopy(self.charts); extra = deepcopy(surplus["chart_records"][-1]) + extra["chart_id"], extra["level"] = "chart.q999/L3.s0.s0.s0", 3; surplus["chart_records"].append(extra) + for name, forged in (("boolean", boolean), ("surplus", surplus)): + with self.subTest(probe=name), self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(self.evaluation, forged, prepared=self.prepared) + + def test_shoulder_selection_uses_face_ancestry_not_vertex_records(self): + altered = [] + for mesh in (self.evaluation.cage, *self.evaluation.levels): + altered.append(replace(mesh, vertex_records=tuple({"base_control_contributors": (), "geometry_dependency_union": (), "contributor_domains": ()} for _ in mesh.vertex_records))) + forged = surface.SurfaceEvaluation(altered[0], tuple(altered[1:])) + original = anatomy.measure_anatomy(self.evaluation, self.prepared, self.charts) + with patch.object(surface, "validate_evaluation", return_value=tuple(altered)): + self.assertEqual(anatomy.measure_anatomy(forged, self.prepared, self.charts), original) + + def test_frozen_thresholds_resist_hostile_runtime_reassignment(self): + expected = anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts), anatomy.run_production_axillary_fixtures() + with patch.object(anatomy, "THRESHOLD", -1e9), patch.object(anatomy, "_TURN", -1e9), patch.object(anatomy, "_STRETCH", 1e9): + self.assertEqual((anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts), anatomy.run_production_axillary_fixtures()), expected) + self.assertEqual((anatomy.evaluate_axillary_scalars(float.fromhex("0x1.9999999999999p-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(1.0, float.fromhex("0x1.4000000000001p+1")).passed), (False, False)) + + +class ProductionAxillaryFixtureTests(unittest.TestCase): + def test_contract_fixture_matrix(self): + rows = anatomy.run_production_axillary_fixtures() + self.assertEqual(len(rows), 13); self.assertEqual(tuple(row["fixture_id"] for row in rows), anatomy.AXILLARY_FIXTURE_IDS) + self.assertEqual([row["outcome"] for row in rows[:3]], ["pass", "pass", "fail"]); self.assertEqual([row["outcome"] for row in rows[3:6]], ["hard-failure"] * 3) + self.assertEqual(rows[6]["stage"], 9); self.assertEqual([row["outcome"] for row in rows[7:]], ["fail", "pass", "pass", "pass", "pass", "fail"]) + + def test_failure_order_and_exact_boundary_comparators(self): + with self.assertRaisesRegex(ValueError, "step 3"): + anatomy.evaluate_axillary_predicate("left", (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) + self.assertEqual((anatomy.evaluate_axillary_scalars(float.fromhex("0x1.9999999999999p-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(float.fromhex("0x1.999999999999ap-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(1.0, float.fromhex("0x1.4000000000001p+1")).passed), (False, True, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py index 9d1e56d..179a49d 100644 --- a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py +++ b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py @@ -308,6 +308,105 @@ def test_fixed_paths_reject_exact_byte_copies(self): for message, kwargs in cases: with self.subTest(message=message), self.assertRaisesRegex(PreparedProjectionError, message): prepare_standard_neutral(**kwargs) + def test_publication_binds_prevalidated_inventory_across_rename(self): + with tempfile.TemporaryDirectory() as directory: + root, raced = Path(directory), False + stage, target = root / "stage", root / "published" + stage.mkdir() + payload = stage / "payload.bin" + payload.write_bytes(b"good") + expected = artifacts.closed_inventory(stage, ("payload.bin",), max_file_bytes=64) + rename = artifacts._rename_no_replace + + def replace_then_rename(parent_fd, source, destination): + nonlocal raced + if source == stage.name and destination == target.name: + payload.write_bytes(b"evil") + raced = True + return rename(parent_fd, source, destination) + + with patch.object(artifacts, "_rename_no_replace", side_effect=replace_then_rename), \ + self.assertRaisesRegex(artifacts.ArtifactSerializationError, "inventory"): + artifacts.publish_no_replace( + stage, target, expected_inventory=expected, max_file_bytes=64) + self.assertTrue(raced) + self.assertFalse(target.exists() or target.is_symlink()) + self.assertEqual(payload.read_bytes(), b"evil") + def test_publication_quarantines_post_rename_replacement_for_file_and_directory(self): + for kind in ("file", "directory"): + with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory: + root, raced = Path(directory), False + stage, target, held = root / "stage", root / "published", root / "held-expected" + if kind == "file": + stage.write_bytes(b"good") + expected = (artifacts.regular_file_record(stage, "payload.bin", max_bytes=64),) + else: + stage.mkdir() + (stage / "payload.bin").write_bytes(b"good") + expected = artifacts.closed_inventory(stage, ("payload.bin",), max_file_bytes=64) + rename = artifacts._rename_no_replace + + def replace_after_rename(parent_fd, source, destination, *, rename=rename, + stage=stage, target=target, held=held, kind=kind): + nonlocal raced + rename(parent_fd, source, destination) + if source == stage.name and destination == target.name: + target.rename(held) + target.write_bytes(b"evil") if kind == "file" else target.mkdir() + raced = True + + with patch.object(artifacts, "_rename_no_replace", side_effect=replace_after_rename), \ + patch.object(artifacts.secrets, "token_hex", return_value="ab" * 8), \ + self.assertRaisesRegex(artifacts.ArtifactSerializationError, "quarantined"): + artifacts.publish_no_replace( + stage, target, expected_inventory=expected, max_file_bytes=64) + quarantined = list(root.glob(".rollback-*")) + self.assertTrue(raced) + self.assertFalse(target.exists() or target.is_symlink()) + self.assertTrue(held.exists()) + self.assertEqual(len(quarantined), 1) + self.assertEqual(quarantined[0].is_dir(), kind == "directory") + recovered = root / "recovered" + self.assertEqual(artifacts.publish_no_replace( + held, recovered, expected_inventory=expected, max_file_bytes=64), recovered) + occupied = root / "occupied" + if kind == "file": occupied.write_bytes(b"unrelated") + else: + occupied.mkdir() + (occupied / "unrelated").write_bytes(b"unrelated") + with self.assertRaises(FileExistsError): + artifacts.publish_no_replace( + recovered, occupied, expected_inventory=expected, max_file_bytes=64) + self.assertEqual((occupied if kind == "file" else occupied / "unrelated").read_bytes(), b"unrelated") + def test_publication_fails_closed_when_parent_is_replaced_after_relative_rename(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + parent, displaced = root / "parent", root / "displaced" + stage, target = parent / "stage", parent / "published" + parent.mkdir() + stage.mkdir() + (stage / "payload.bin").write_bytes(b"good") + expected = artifacts.closed_inventory(stage, ("payload.bin",), max_file_bytes=64) + rename, raced = artifacts._rename_no_replace, False + + def rename_then_replace_parent(parent_fd, source, destination): + nonlocal raced + result = rename(parent_fd, source, destination) + if not raced and source == stage.name and destination == target.name: + parent.rename(displaced) + parent.mkdir() + target.write_bytes(b"wrong") + raced = True + return result + + with patch.object(artifacts, "_rename_no_replace", side_effect=rename_then_replace_parent), \ + self.assertRaisesRegex(artifacts.ArtifactSerializationError, "parent|pathname"): + artifacts.publish_no_replace( + stage, target, expected_inventory=expected, max_file_bytes=64) + self.assertTrue(raced) + self.assertEqual(target.read_bytes(), b"wrong") + self.assertEqual((displaced / "stage" / "payload.bin").read_bytes(), b"good") + self.assertFalse((displaced / "published").exists()) def test_public_constant_reassignment_cannot_redirect_fixed_admission(self): encoded, expected_bindings = canonical_json_bytes(self.prepared), _expected_bindings() with tempfile.TemporaryDirectory() as directory: @@ -335,6 +434,47 @@ def test_public_constant_reassignment_cannot_redirect_fixed_admission(self): projection.prepare_standard_neutral( projection.SOURCE_PATH, contract_path=projection.CONTRACT_PATH, profile_table_path=projection.PROFILE_TABLE_PATH) + def test_station_and_neutral_profile_commitments_resist_coordinated_forgery(self): + stations = list(projection.STATIONS) + stations[0] = ("lower_pelvis", "pelvis", "form_torso_profile_upper_pelvis") + forged_station = copy.deepcopy(self.prepared) + forged_station["stations"]["lower_pelvis"] = copy.deepcopy( + self.prepared["stations"]["upper_pelvis"]) + forged_profile = _mutated( + self.prepared, ("profile_selection", "profile_id"), "forged_neutral") + forged_both = copy.deepcopy(forged_station) + forged_both["profile_selection"]["profile_id"] = "forged_neutral" + with patch.multiple(projection, STATIONS=tuple(stations), + _NEUTRAL_PROFILE="forged_neutral"): + self.assertEqual(projection.prepare_standard_neutral(), self.prepared) + self.assertEqual(projection.source_binding_records(), _expected_bindings()) + for candidate in (forged_station, forged_profile, forged_both): + with self.subTest(candidate=candidate["profile_selection"]["profile_id"]), \ + self.assertRaises(PreparedProjectionError): + projection.validate_prepared(candidate) + def test_adjacent_semantic_authorities_are_immutable_definition_time_commitments(self): + encoded, expected_bindings = canonical_json_bytes(self.prepared), _expected_bindings() + with self.assertRaises(TypeError): + projection._COMMITMENTS["semantic"]["neutral_profile"] = "forged" + poison = _Explosive() + names = ( + "_ADMISSION _ROLES _PATHS _HASHES _SIZES _BINDING_HASHES _SIDECAR_CONTENT " + "_PREPARED_SCHEMA _NEUTRAL_PROFILE _ROTATION _AXES _BASIS_ITEMS _SOURCE_DOCUMENT " + "_SOURCE_CONTRACT _SOURCE_IDENTITY PARTS STATIONS SHOULDER_DIMS HIP_DIMS " + "SHOULDER_SUMS HIP_SUMS SIDE_CONFIGS BODY_COUNTS SOURCE_ROW_FIELDS PROFILE_IDS " + "PROFILE_DIMENSION_KEYS _ADDRESS _B64 _PB64 _IDENTITY_SPEC _PART_SPEC _STATION_SPEC " + "_SHOULDER_SPEC _HIP_SPEC _PREPARED_SPEC _JSON_BYTES _DECODE_JSON _COERCE_BINARY64 " + "_READ_FILE _SHA256_BYTES _COMMITMENTS artifacts json math Path PreparedProjectionError " + "canonical_json_bytes canonical_json_sha256 normalize_source_address" + ).split() + forged = _mutated(self.prepared, ("profile_selection", "profile_id"), "forged") + with patch.multiple(projection, **dict.fromkeys(names, poison)): + self.assertEqual(projection.prepare_standard_neutral(), self.prepared) + self.assertIs(projection.validate_prepared(self.prepared), self.prepared) + self.assertEqual(projection.admit_prepared_bytes(encoded), self.prepared) + self.assertEqual(projection.source_binding_records(), expected_bindings) + with self.assertRaises(PreparedProjectionError): + projection.validate_prepared(forged) def test_fixed_hashes_sidecar_and_sizes_are_independent_literals(self): for path, size, digest in ( (CONTRACT, 173184, CONTRACT_HASH), (SIDECAR, 127, hashlib.sha256(SIDECAR_BYTES).hexdigest()), @@ -355,14 +495,8 @@ def test_source_and_profile_identity_fail_closed_through_byte_seams(self): _admit_source_bytes(json.dumps(source).encode()) profile = _mutated(self.profile_document, ("profiles", 0, "dimension_scales", "arm_radius"), 1001) mutated_profile = json.dumps(profile).encode() - real_read = projection._READ_FILE - - def read_with_mutated_profile(path): - return mutated_profile if Path(path) == PROFILE_TABLE else real_read(path) - - with patch.object(projection, "_READ_FILE", side_effect=read_with_mutated_profile), \ - self.assertRaisesRegex(PreparedProjectionError, "profile identity mismatch"): - prepare_standard_neutral(SOURCE) + with patch.object(projection, "_READ_FILE", side_effect=RuntimeError("redirected")): + self.assertEqual(prepare_standard_neutral(SOURCE), self.prepared) with self.assertRaisesRegex(PreparedProjectionError, "profile identity mismatch"): _admit_profile_bytes(mutated_profile) def test_source_profile_schema_and_selector_boundaries(self): @@ -419,13 +553,8 @@ def test_malformed_public_admissions_normalize_exceptions(self): ): with self.subTest(name=name), self.assertRaises(PreparedProjectionError): validate_prepared(_mutated(self.prepared, path, _Explosive())) - with patch.object(projection, "_DECODE_JSON", side_effect=RecursionError), \ - self.assertRaises(PreparedProjectionError): + with self.assertRaises(PreparedProjectionError): admit_prepared_bytes(b"{}") - with patch.object(projection, "_JSON_BYTES", - side_effect=artifacts.ArtifactSerializationError("forged")), \ - self.assertRaises(PreparedProjectionError): - validate_prepared(self.prepared) for function in (prepare_standard_neutral, source_binding_records): with self.subTest(function=function.__name__), self.assertRaises(PreparedProjectionError): function(_Explosive()) diff --git a/experiments/owned-root-assembly-successor/tests/test_render_export.py b/experiments/owned-root-assembly-successor/tests/test_render_export.py new file mode 100644 index 0000000..1785686 --- /dev/null +++ b/experiments/owned-root-assembly-successor/tests/test_render_export.py @@ -0,0 +1,287 @@ +from __future__ import annotations + +import hashlib +import struct +import sys +import unittest +from copy import deepcopy +from dataclasses import replace +from functools import lru_cache +from io import BytesIO +from pathlib import Path + +HERE = Path(__file__).resolve().parents[1] +REPO = HERE.parents[1] +sys.path.insert(0, str(HERE)) +import owned_root_surface as surface +import prepared_projection +import render_export as render + + +def _prepared(): + return prepared_projection.prepare_standard_neutral( + REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" + ) + + +@lru_cache(maxsize=1) +def _evaluation(): + return surface.evaluate(_prepared()) + + +def _level2(): + return _evaluation().levels[1] + + +@lru_cache(maxsize=1) +def _visibility(): + return render.build_visibility(_level2()) + + +class PLYTests(unittest.TestCase): + def test_exact_quad_header_rows_and_terminal_lf(self): + data = render.ply_bytes( + ((0.0, -0.0, 1e-5), (1.0, 2.0, -1e20), (3.0, 4.0, 5.0), (6.0, 7.0, 8.0)), + ((0, 1, 2, 3),), + ) + expected = ( + b"ply\nformat ascii 1.0\n" + b"element vertex 4\nproperty double x\nproperty double y\nproperty double z\n" + b"element face 1\nproperty list uchar int vertex_indices\nend_header\n" + b"0 0 1.0000000000000001e-5\n1 2 -1e+20\n3 4 5\n6 7 8\n4 0 1 2 3\n" + ) + self.assertEqual(data, expected) + self.assertEqual(data[-1:], b"\n") + self.assertNotIn(b"\r", data) + + def test_mesh_export_preserves_quad_order_and_rejects_mutations(self): + mesh = _level2() + data = render.ply_bytes(mesh) + self.assertIn(b"element vertex 1737\n", data) + self.assertIn(b"element face 1664\n", data) + first_face = b"4 " + b" ".join(str(item).encode("ascii") for item in mesh.quads[0]) + self.assertIn(b"\n" + first_face + b"\n", data) + with self.assertRaises(render.RenderExportError): + render.ply_bytes([(0, 0, 0)], [(0, 0, 0, 0)]) + with self.assertRaises(render.RenderExportError): + render.ply_bytes(((0.0, 0.0, 0.0),), ((0, 1, 2, 3),)) + + def test_ply_rejects_non_binary64_and_non_quad_inputs(self): + points = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) + invalid = ( + ((0, 0.0, 0.0), points[1], points[2], points[3]), + ((float("nan"), 0.0, 0.0), points[1], points[2], points[3]), + ) + for rows in invalid: + with self.subTest(row=rows[0]), self.assertRaises(render.RenderExportError): + render.ply_bytes(rows, ((0, 1, 2, 3),)) + for face in (((0, 1, 2),), ((0, 1, 2, 4),), ((0, 1, True, 3),)): + with self.subTest(face=face), self.assertRaises(render.RenderExportError): + render.ply_bytes(points, face) + +class ConfigTests(unittest.TestCase): + def test_config_is_closed_and_has_exact_literals(self): + config = render.render_config_record() + render.validate_render_config(config) + self.assertEqual(tuple(config), render.CONFIG_KEYS) + self.assertEqual(config["panel_order"], ["front", "side", "45deg"]) + self.assertEqual(config["padding"], 24) + self.assertEqual(config["png_metadata"], {}) + self.assertEqual(config["cameras"][2]["right"][0], 0.7071067811865476) + self.assertEqual(config["cameras"][2]["right"][2], -0.7071067811865475) + self.assertEqual(config["quad_split"], [[0, 1, 2], [0, 2, 3]]) + self.assertEqual(config["png_compress_level"], 9) + self.assertFalse(any(config[key] for key in + ("shading", "lighting", "labels", "outlines", "anti_aliasing", "alpha", "culling"))) + + def test_config_mutation_is_rejected(self): + config = render.render_config_record() + for key, value in (("padding", 25), ("labels", True), ("png_metadata", {"x": 1})): + candidate = deepcopy(config) + candidate[key] = value + with self.subTest(key=key), self.assertRaises(render.RenderExportError): + render.validate_render_config(candidate) + candidate = deepcopy(config) + candidate["extra"] = False + with self.assertRaises(render.RenderExportError): + render.validate_render_config(candidate) + + def test_equal_valued_scalar_type_substitutions_are_rejected_recursively(self): + config = render.render_config_record() + cases = ( + ("padding", ("padding",), 24.0), + ("compress", ("png_compress_level",), 9.0), + ("boolean", ("shading",), 0), + ("camera", ("cameras", 0, "right", 0), 1), + ("palette", ("domain_palette", "domain.pelvis", 0), 214.0), + ) + for label, path, replacement in cases: + candidate, target = deepcopy(config), None + target = candidate + for key in path[:-1]: + target = target[key] + target[path[-1]] = replacement + with self.subTest(label=label), self.assertRaises(render.RenderExportError): + render.validate_render_config(candidate) + + def test_config_factory_returns_independent_closed_values(self): + first = render.render_config_record() + first["cameras"][0]["right"][0] = 99.0 + first["domain_palette"]["domain.pelvis"][0] = 0 + second = render.render_config_record() + render.validate_render_config(second) + self.assertEqual(second["cameras"][0]["right"][0], 1.0) + self.assertEqual(second["domain_palette"]["domain.pelvis"], [214, 83, 83]) + + +class RendererTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mesh = _level2() + + def test_visibility_is_level2_closed_and_shared(self): + visibility = _visibility() + self.assertEqual(len(visibility.owners), 3 * 512 * 512) + self.assertEqual(len(visibility.depths), len(visibility.owners)) + self.assertEqual(len(visibility.triangle_owners), 3328) + self.assertEqual(visibility.triangle_index_sha256, hashlib.sha256( + b"".join(struct.pack(" Date: Sat, 5 Sep 2026 05:23:17 +1200 Subject: [PATCH 14/38] Fix owned-root evidence re-admission --- dev-tools/validation/test_repo_search.sh | 3 +- .../build_owned_root.py | 4 +- .../chart_lineage.py | 1 + .../mesh_correctness.py | 10 ++- .../prepared_projection.py | 48 ++++++------ .../render_export.py | 8 +- .../tests/test_build_owned_root.py | 74 ++++++++++++++++++- .../tests/test_owned_root_surface.py | 8 +- .../tests/test_prepared_projection.py | 34 +++++++++ .../tests/test_render_export.py | 22 ++++++ 10 files changed, 169 insertions(+), 43 deletions(-) diff --git a/dev-tools/validation/test_repo_search.sh b/dev-tools/validation/test_repo_search.sh index b50e9ea..20c4168 100755 --- a/dev-tools/validation/test_repo_search.sh +++ b/dev-tools/validation/test_repo_search.sh @@ -5,7 +5,8 @@ set -euo pipefail repo_root=$(cd -- "$(dirname -- "$0")/../.." && pwd) search_script=$repo_root/dev-tools/repo_search.sh -bash -n "$search_script" "$0" +bash -n "$search_script" +bash -n "$0" tmp_dir=$(mktemp -d -t repo-search-test.XXXXXX) trap 'rm -rf -- "$tmp_dir"' EXIT diff --git a/experiments/owned-root-assembly-successor/build_owned_root.py b/experiments/owned-root-assembly-successor/build_owned_root.py index f90efd6..c06b167 100644 --- a/experiments/owned-root-assembly-successor/build_owned_root.py +++ b/experiments/owned-root-assembly-successor/build_owned_root.py @@ -104,7 +104,7 @@ def _domain_tags(meshes, owners, domains, domain_index, axes, level, surface): def _junction_inputs(surface, evaluation, level, chart_summary=None): meshes = (evaluation.cage, *evaluation.levels); _need(level in range(3), "junction level is outside the frozen three-level universe"); owners = tuple(_chart_owners(mesh, chart_summary) for mesh in meshes); result = {} for junction in surface.JUNCTIONS: - domains, (_drop, axes) = surface.JUNCTION_INFO[junction]; maps = tuple(_domain_tags(meshes, owners, domains, index, axes, level, surface) for index in range(2)); reference = tuple(_domain_tags(meshes, owners, domains, index, axes, level, surface) for index in range(2)); result[junction] = {"incident_domains": domains, "domain_vertex_tags": maps, "expected_domain_vertex_tags": reference} + domains, (_drop, axes) = surface.JUNCTION_INFO[junction]; maps = tuple(_domain_tags(meshes, owners, domains, index, axes, level, surface) for index in range(2)); reference_map = surface.propagate_junction_tags(evaluation, junction)[level]; reference = tuple(dict(reference_map) for _ in domains); result[junction] = {"incident_domains": domains, "domain_vertex_tags": maps, "expected_domain_vertex_tags": reference} return result def _metric_values(mesh): edges = {tuple(sorted((left, face[(slot + 1) % 4]))) for face in mesh.quads for slot, left in enumerate(face)} @@ -351,7 +351,7 @@ def validate_seed_bundle(*, root, seed, identity): _need(gate["schema"] == MANIFEST_SCHEMAS["gate-manifest.json"] and gate["contract_sha256"] == EXPECTED_CONTRACT_SHA256, "gate manifest identity differs"); _manifest_reference(gate["coordinate_manifest"], "gate coordinate reference", "coordinate-manifest.json", record_map["coordinate-manifest.json"]); _validate_gate_manifest(gate) causality = _keys(manifests["causality-manifest.json"], ("schema", "contract_sha256", "input_manifest", "formula_records", "source_bindings", "charts", "perturbations"), "causality manifest") _need(causality["schema"] == MANIFEST_SCHEMAS["causality-manifest.json"] and causality["contract_sha256"] == EXPECTED_CONTRACT_SHA256, "causality manifest identity differs"); _manifest_reference(causality["input_manifest"], "causality input reference", "input-manifest.json", record_map["input-manifest.json"]) - formulas = list(surface.formula_candidate_records(prepared)); _same_json(causality["formula_records"], formulas, "causality formula records"); _same_json(causality["source_bindings"], bindings, "causality source bindings") + formulas = tuple(surface.formula_candidate_records(prepared)); _same_json(causality["formula_records"], formulas, "causality formula records"); _same_json(causality["source_bindings"], bindings, "causality source bindings") evaluation = surface.evaluate(prepared) try: chart.validate_chart_summary(causality["charts"], evaluation, formulas) except Exception as exc: raise BuildError("causality chart summary validation failed") from exc diff --git a/experiments/owned-root-assembly-successor/chart_lineage.py b/experiments/owned-root-assembly-successor/chart_lineage.py index c5eec1e..ae62e35 100644 --- a/experiments/owned-root-assembly-successor/chart_lineage.py +++ b/experiments/owned-root-assembly-successor/chart_lineage.py @@ -120,6 +120,7 @@ def _domain_cycle(boundary, shared): if len(following) != len(shared): _fail("a junction is not a domain boundary cycle") cycle = [min(following)] while following.get(cycle[-1]) != cycle[0] and len(cycle) <= len(shared): + if cycle[-1] not in following: _fail("a junction is not one closed trace") cycle.append(following[cycle[-1]]) if len(cycle) != len(shared) or following.get(cycle[-1]) != cycle[0]: _fail("a junction is not one closed trace") return tuple(cycle) diff --git a/experiments/owned-root-assembly-successor/mesh_correctness.py b/experiments/owned-root-assembly-successor/mesh_correctness.py index 9acfba5..42aed79 100644 --- a/experiments/owned-root-assembly-successor/mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/mesh_correctness.py @@ -386,16 +386,18 @@ def _intersection_inputs(vertices, triangles): return faces, normalized, scale, bounds, tuple(frozenset(face) for face in faces) def _aabb_disjoint(first, second): return any(_interval_disjoint(first[i], first[i + 3], second[i], second[i + 3]) for i in range(3)) def _pair_status(first_index, second_index, faces, normalized, bounds, face_sets): - pair = (first_index, second_index); common = face_sets[first_index].intersection(face_sets[second_index]) + pair = (first_index, second_index) + if _aabb_disjoint(bounds[first_index], bounds[second_index]): return "aabb-disjoint" + first_face = faces[first_index]; second_face = faces[second_index]; common = face_sets[first_index].intersection(face_sets[second_index]) if len(common) == 3: _fail(f"duplicate triangle pair {pair}") if len(common) == 2: - first_edge = _shared_edge_direction(faces[first_index], common); second_edge = _shared_edge_direction(faces[second_index], common) + first_edge = _shared_edge_direction(first_face, common); second_edge = _shared_edge_direction(second_face, common) if first_edge != (second_edge[1], second_edge[0]): _fail(f"shared-two edge direction conflict at pair {pair}") return "excluded-adjacent" if len(common) == 1: if normalized is None: return "shared-one" - return "hit" if _classify_shared_one_triangles(faces[first_index], faces[second_index], normalized) else "point-only" - return "aabb-disjoint" if _aabb_disjoint(bounds[first_index], bounds[second_index]) else "candidate" + return "hit" if _classify_shared_one_triangles(first_face, second_face, normalized) else "point-only" + return "candidate" def _record_pair_policy(triangle_count, first, second, ordinal, stage, class_counts): expected_ordinal = first * (2 * triangle_count - first - 1) // 2 + second - first - 1 if ordinal != expected_ordinal: _fail("intersection pair coverage is not exhaustive reference order") diff --git a/experiments/owned-root-assembly-successor/prepared_projection.py b/experiments/owned-root-assembly-successor/prepared_projection.py index d41eb45..54bba0e 100644 --- a/experiments/owned-root-assembly-successor/prepared_projection.py +++ b/experiments/owned-root-assembly-successor/prepared_projection.py @@ -25,15 +25,9 @@ class PreparedProjectionError(ValueError): EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES = 56984, 29970 # Definition-time immutable admission commitments. Public constants remain # inspectable, but their ordinary reassignment cannot redirect admission. -_ADMISSION = ((CONTRACT_ROLE, SOURCE_ROLE, PROFILE_ROLE), - (CONTRACT_PATH, SIDECAR_PATH, SOURCE_PATH, PROFILE_TABLE_PATH), - (EXPECTED_CONTRACT_SHA256, EXPECTED_SOURCE_SHA256, EXPECTED_PROFILE_TABLE_SHA256), - (173184, 127, EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES), - (EXPECTED_BINDING_COMPONENTS_SHA256, EXPECTED_BINDINGS_SHA256)) +_ADMISSION = ((CONTRACT_ROLE, SOURCE_ROLE, PROFILE_ROLE), (CONTRACT_PATH, SIDECAR_PATH, SOURCE_PATH, PROFILE_TABLE_PATH), (EXPECTED_CONTRACT_SHA256, EXPECTED_SOURCE_SHA256, EXPECTED_PROFILE_TABLE_SHA256), (173184, 127, EXPECTED_SOURCE_BYTES, EXPECTED_PROFILE_BYTES), (EXPECTED_BINDING_COMPONENTS_SHA256, EXPECTED_BINDINGS_SHA256)) _ROLES, _PATHS, _HASHES, _SIZES, _BINDING_HASHES = _ADMISSION -(_JSON_BYTES, _DECODE_JSON, _COERCE_BINARY64, _READ_FILE, _SHA256_BYTES) = ( - artifacts.canonical_json_bytes, artifacts.decode_canonical_json, - artifacts.coerce_binary64, artifacts.read_regular_file, artifacts.sha256_bytes) +(_JSON_BYTES, _DECODE_JSON, _COERCE_BINARY64, _READ_FILE, _SHA256_BYTES) = (artifacts.canonical_json_bytes, artifacts.decode_canonical_json, artifacts.coerce_binary64, artifacts.read_regular_file, artifacts.sha256_bytes) _SIDECAR_CONTENT = artifacts.contract_sidecar_bytes(_HASHES[0]) _PREPARED_SCHEMA = "owned-root-assembly-successor-prepared.v1" _NEUTRAL_PROFILE = "standard_neutral_reference" @@ -44,18 +38,12 @@ class PreparedProjectionError(ValueError): _SOURCE_CONTRACT = (("family", "creature-kernel.body"), ("revision", 1)) _SOURCE_IDENTITY = (("document", _SOURCE_DOCUMENT), ("namespace", "main")) PARTS = (("pelvis", None), ("torso", None), ("neck", None), ("upper_arm", "left"), ("upper_arm", "right"), ("thigh", "left"), ("thigh", "right")) -STATIONS = (("lower_pelvis", "pelvis", "form_torso_profile_lower_pelvis"), ("upper_pelvis", "pelvis", "form_torso_profile_upper_pelvis"), - ("lower_abdomen", "torso", "form_torso_profile_lower_abdomen"), ("waist_abdomen", "torso", "form_torso_profile_waist_abdomen"), - ("upper_abdomen", "torso", "form_torso_profile_upper_abdomen"), ("lower_ribcage", "torso", "form_torso_profile_lower_ribcage"), - ("upper_ribcage_shoulder", "torso", "form_torso_profile_upper_ribcage_shoulder"), ("neck_collar", "neck", "form_head_neck_profile_neck_collar"), - ("neck_upper", "neck", "form_head_neck_profile_neck_upper")) -SHOULDER_DIMS = (("start_lateral", "form_arm_profile_upper_arm_start_lateral_radius"), ("start_up", "form_arm_profile_upper_arm_start_up_radius"), - ("start_forward", "form_arm_profile_upper_arm_start_forward_radius"), ("shoulder_depth", "form_shoulder_depth_radius")) +STATIONS = (("lower_pelvis", "pelvis", "form_torso_profile_lower_pelvis"), ("upper_pelvis", "pelvis", "form_torso_profile_upper_pelvis"), ("lower_abdomen", "torso", "form_torso_profile_lower_abdomen"), ("waist_abdomen", "torso", "form_torso_profile_waist_abdomen"), ("upper_abdomen", "torso", "form_torso_profile_upper_abdomen"), ("lower_ribcage", "torso", "form_torso_profile_lower_ribcage"), ("upper_ribcage_shoulder", "torso", "form_torso_profile_upper_ribcage_shoulder"), ("neck_collar", "neck", "form_head_neck_profile_neck_collar"), ("neck_upper", "neck", "form_head_neck_profile_neck_upper")) +SHOULDER_DIMS = (("start_lateral", "form_arm_profile_upper_arm_start_lateral_radius"), ("start_up", "form_arm_profile_upper_arm_start_up_radius"), ("start_forward", "form_arm_profile_upper_arm_start_forward_radius"), ("shoulder_depth", "form_shoulder_depth_radius")) HIP_DIMS = (("r_x", "form_leg_profile_thigh_start_lateral_radius"), ("r_y", "form_leg_profile_thigh_start_up_radius"), ("r_z", "form_leg_profile_thigh_start_forward_radius")) SHOULDER_SUMS = (("axilla", "form_axilla"), ("peak", "form_shoulder_peak"), ("arm_origin", None)) HIP_SUMS = (("P_s", "form_leg_profile_thigh_start"),) -SIDE_CONFIGS = (("shoulders", "upper_arm", (("axilla", "form_axilla", "form_shoulder_control"), ("peak", "form_shoulder_peak", "form_shoulder_control")), SHOULDER_DIMS), - ("hips", "thigh", (("P_s", "form_leg_profile_thigh_start", "form_leg_profile_control"),), HIP_DIMS)) +SIDE_CONFIGS = (("shoulders", "upper_arm", (("axilla", "form_axilla", "form_shoulder_control"), ("peak", "form_shoulder_peak", "form_shoulder_control")), SHOULDER_DIMS), ("hips", "thigh", (("P_s", "form_leg_profile_thigh_start", "form_leg_profile_control"),), HIP_DIMS)) BODY_COUNTS = {"attachments": 1, "capabilities": 3, "dimensions": 153, "fields": 0, "frames": 16, "joints": 17, "landmarks": 43, "modules": 1, "parts": 18, "regions": 4, "sockets": 2} SOURCE_ROW_FIELDS = {"dimensions": {"owner", "role", "value"}, "frames": {"owner", "role", "transform"}, "landmarks": {"frame", "owner", "position", "role"}} PROFILE_IDS = ("standard_neutral_reference", "compact_broad_short_limb_large_head", "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested") @@ -251,14 +239,16 @@ def _verify_contract(path=_PATHS[0], _c=_COMMITMENTS): contract = _fixed_path(path, paths[0], "contract path") sidecar = _fixed_path(paths[1], paths[1], "contract sidecar path") contract_raw, sidecar_raw = _read(contract, "contract"), _read(sidecar, "contract sidecar") - _need(len(contract_raw) == sizes[0] and operations["sha256_bytes"](contract_raw) == hashes[0], "contract", "identity mismatch") + contract_digest = operations["sha256_bytes"](contract_raw) + _need(len(contract_raw) == sizes[0] and contract_digest == hashes[0], "contract", "identity mismatch") _need(len(sidecar_raw) == sizes[1] and sidecar_raw == _admission["sidecar"], "contract sidecar", "identity mismatch") + return contract_digest def _fixed_inputs(source_path, contract_path, profile_path, _admission=_COMMITMENTS["admission"]): paths = _admission["paths"] - _verify_contract(contract_path) + contract_digest = _verify_contract(contract_path) source = _fixed_path(source_path, paths[2], "source path"); profile = _fixed_path(profile_path, paths[3], "profile table path") admission = _admit_source_bytes(_read(source, "source")); selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")) - return admission, selected, raw, digest + return contract_digest, admission, selected, raw, digest def _select(rows, owner, role, name): match = rows.get((owner, role)) _need(match is not None, f"body.{name}.{role}", "missing required record") @@ -343,11 +333,20 @@ def _build_prepared(admission, profile, profile_raw, profile_digest, _c=_COMMITM def _prepared_apis(_c): fixed, operations = _c["admission"], _c["operations"] shape, structure, build, inputs, need, attempt = _validate_prepared_shape, _validate_prepared_structure, _build_prepared, _fixed_inputs, _need, _attempt + expected_bytes_cache = {} @_public_admission def validate_prepared(prepared): """Admit only the projection freshly derived from the fixed files.""" - value = shape(prepared); expected = build(*inputs(fixed["paths"][2], fixed["paths"][0], fixed["paths"][3])) - need(operations["json_bytes"](value) == operations["json_bytes"](expected), "prepared", "values do not match fixed projection") + value = shape(prepared) + contract_digest, admission, profile, profile_raw, profile_digest = inputs( + fixed["paths"][2], fixed["paths"][0], fixed["paths"][3]) + digest_triple = (contract_digest, admission["sha256"], profile_digest) + expected_bytes = expected_bytes_cache.get(digest_triple) + if expected_bytes is None: + expected_bytes = operations["json_bytes"]( + build(admission, profile, profile_raw, profile_digest)) + expected_bytes_cache[digest_triple] = expected_bytes + need(operations["json_bytes"](value) == expected_bytes, "prepared", "values do not match fixed projection") return value @_public_admission def admit_prepared_bytes(raw): @@ -359,7 +358,8 @@ def admit_prepared_bytes(raw): @_public_admission def prepare_standard_neutral(source_path=fixed["paths"][2], *, contract_path=fixed["paths"][0], profile_table_path=fixed["paths"][3]): """Admit fixed inputs and return the exact standard-neutral object.""" - return build(*inputs(source_path, contract_path, profile_table_path)) + _, admission, profile, profile_raw, profile_digest = inputs(source_path, contract_path, profile_table_path) + return build(admission, profile, profile_raw, profile_digest) return validate_prepared, admit_prepared_bytes, prepare_standard_neutral validate_prepared, admit_prepared_bytes, prepare_standard_neutral = _prepared_apis(_COMMITMENTS) def _pointer(kind, index, axis=None): @@ -421,7 +421,7 @@ def _binding_api(_c): inputs, chains_for_parts, address, suffixes, append, validate = _fixed_inputs, _chains, _a, _station_suffixes, _append_group, _validate_binding_records @_public_admission def source_binding_records(source_path=fixed["paths"][2], *, contract_path=fixed["paths"][0], profile_table_path=fixed["paths"][3]): - admission, _, _, _ = inputs(source_path, contract_path, profile_table_path) + _, admission, _, _, _ = inputs(source_path, contract_path, profile_table_path) parts, bindings, chains = admission["parts"], [], chains_for_parts() for name, role, prefix in semantic["stations"]: owner = address(role) diff --git a/experiments/owned-root-assembly-successor/render_export.py b/experiments/owned-root-assembly-successor/render_export.py index fe50c35..284f30f 100644 --- a/experiments/owned-root-assembly-successor/render_export.py +++ b/experiments/owned-root-assembly-successor/render_export.py @@ -92,10 +92,12 @@ def render_config_record() -> dict[str, Any]: "quad_split": [[0, 1, 2], [0, 2, 3]], "shading": False, "lighting": False, "labels": False, "outlines": False, "anti_aliasing": False, "alpha": False, "culling": False, "pillow_version": "11.1.0", "png_compress_level": 9, "png_optimize": False, "png_metadata": {}, } -def _exact(value: object, expected: object) -> bool: - return type(value) is type(expected) and ((all(type(key) is str for key in value) and set(value) == set(expected) and all(_exact(value[key], item) for key, item in expected.items())) if type(expected) is dict else (len(value) == len(expected) and all(_exact(item, wanted) for item, wanted in zip(value, expected))) if type(expected) is list else value == expected) +def _exact(value: object, expected: object, *, canonical_wire: bool = False) -> bool: + if canonical_wire and type(expected) is float and expected == 0.0: + return (type(value) is float and value == expected) or (type(value) is int and value == 0) + return type(value) is type(expected) and ((all(type(key) is str for key in value) and set(value) == set(expected) and all(_exact(value[key], item, canonical_wire=canonical_wire) for key, item in expected.items())) if type(expected) is dict else (len(value) == len(expected) and all(_exact(item, wanted, canonical_wire=canonical_wire) for item, wanted in zip(value, expected))) if type(expected) is list else value == expected) def validate_render_config(value: object) -> None: - _reject(not _exact(value, render_config_record()), "render_config is not the exact closed record") + _reject(not _exact(value, render_config_record(), canonical_wire=True), "render_config is not the exact closed record") @dataclass(frozen=True) class VisibilityBuffer: owners: tuple[int | None, ...] diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py index 94e2f81..d692c72 100644 --- a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -171,9 +171,9 @@ def test_mesh_adapters_use_independent_topology_and_incident_domain_traces(self) self.assertEqual(mesh.quads, expected[level]) inputs = builder._junction_inputs(surface, evaluation, level, chart_summary) self.assertEqual(set(inputs), set(surface.JUNCTIONS)) - for row in inputs.values(): - self.assertIsNot(row["domain_vertex_tags"][0], row["domain_vertex_tags"][1]) - self.assertIsNot(row["domain_vertex_tags"], row["expected_domain_vertex_tags"]) + for junction, row in inputs.items(): + reference = surface.propagate_junction_tags(evaluation, junction)[level] + self.assertEqual(row["expected_domain_vertex_tags"], (reference, reference)) ownership = builder._ownership_counts(surface, evaluation, chart_api, mesh_api, prepared, formulas, chart_summary, level) self.assertEqual((ownership["unowned_elements"], @@ -191,6 +191,57 @@ def test_mesh_adapters_use_independent_topology_and_incident_domain_traces(self) surface, mesh_api, evaluation, reports, chart_summary) self.assertEqual((len(continuity), len(thresholds)), (144, 144)) + def test_junction_metrics_reject_builder_observation_mismatch(self): + import mesh_correctness as mesh_api + import owned_root_surface as surface + import prepared_projection as prepared_api + import chart_lineage as chart_api + prepared = prepared_api.prepare_standard_neutral() + evaluation = surface.evaluate(prepared) + formulas = tuple(surface.formula_candidate_records(prepared)) + chart_summary = chart_api.build_chart_summary(evaluation, formulas) + level, junction = 1, surface.JUNCTIONS[0] + domains = surface.JUNCTION_INFO[junction][0] + reference = surface.propagate_junction_tags(evaluation, junction)[level] + original_domain_tags = builder._domain_tags + forged_vertex = None + forged_tag = None + + def forge_domain_tags(*args): + nonlocal forged_tag, forged_vertex + meshes, owners, candidate_domains, domain_index, axes, candidate_level, candidate_surface = args + original = original_domain_tags( + meshes, owners, candidate_domains, domain_index, axes, + candidate_level, candidate_surface) + forged = dict(original) + if candidate_domains == domains: + if forged_vertex is None: + forged_vertex = min(original) + base = original[forged_vertex] + delta = 1 + while True: + candidate = ((base[0][0] + delta, base[0][1]), base[1]) + if candidate not in reference.values() and candidate not in original.values(): + forged_tag = candidate + break + delta += 1 + self.assertIn(forged_vertex, original) + self.assertNotIn(forged_tag, original.values()) + forged[forged_vertex] = forged_tag + return forged + + with mock.patch.object(builder, "_domain_tags", side_effect=forge_domain_tags): + inputs = builder._junction_inputs(surface, evaluation, level, chart_summary) + observed_maps = inputs[junction]["domain_vertex_tags"] + self.assertEqual(set(observed_maps[0]), set(observed_maps[1])) + self.assertEqual(observed_maps[0][forged_vertex], observed_maps[1][forged_vertex]) + self.assertNotIn(forged_tag, reference.values()) + mesh = evaluation.levels[level - 1] + with self.assertRaisesRegex(mesh_api.MeshCorrectnessError, "independent reference"): + mesh_api.junction_continuity_metrics( + mesh.vertices, mesh.quads, mesh.face_owners, **inputs[junction] + ) + class StaticAdmissionTests(unittest.TestCase): def test_package_implementation_fits_frozen_physical_loc_caps(self): @@ -237,7 +288,7 @@ def test_builder_binds_publication_inventory_and_never_self_feeds_mesh(self): self.assertNotIn("else mesh.quads", geometry) self.assertIn("derive_expected_face_catalogs(expected)", geometry) self.assertNotIn("reversed", junctions) - self.assertNotIn("propagate_junction_tags", junctions) + self.assertIn("propagate_junction_tags", junctions) class ManagedDispatchTests(unittest.TestCase): @@ -440,6 +491,21 @@ def test_seed_validator_fails_closed_before_mutating_incomplete_bundle(self): identity=identity_fixture()) self.assertEqual(tuple(root.iterdir()), before) + def test_seed_validator_admits_complete_serialized_bundle(self): + requested_seed = os.environ.get("PYTHONHASHSEED") + self.assertIn(requested_seed, ("0", "17", "29"), + "test requires literal PYTHONHASHSEED=0, 17, or 29") + if requested_seed == "0": + return + seed = int(requested_seed) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / f"seed-{seed}" + identity = builder._static_admission() + builder.build_seed(root) + self.assertIsInstance( + builder.validate_seed_bundle(root=root, seed=seed, identity=identity), dict + ) + if __name__ == "__main__": unittest.main() diff --git a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py index 0146e2a..93793ad 100644 --- a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py @@ -15,7 +15,6 @@ import owned_root_surface as surface import prepared_projection - def prepared(): return prepared_projection.prepare_standard_neutral( REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" @@ -215,8 +214,6 @@ def bad_subdivision(parent, level, points=None, producer=surface._subdivide_once with patch.object(surface, "_subdivide_once", side_effect=bad_subdivision), self.assertRaisesRegex(ValueError, "parent-derived vertices"): surface.subdivide(self.evaluation.cage, 1) def bad_record(level, vertex_id, contributors, formulas, producer=surface._record): return producer(level, vertex_id, contributors, formulas) | {"contributor_domains": ()} with patch.object(surface, "_record", side_effect=bad_record), self.assertRaisesRegex(ValueError, "parent-derived vertex_records"): surface.subdivide(self.evaluation.cage, 1) - - class ChartLineageTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -245,6 +242,9 @@ def test_exact_closed_inventory_ids_and_source_boundary(self): self.assertIn(lines, range(190, 269)) self.assertLessEqual(Path(__file__).read_text(encoding="utf-8").count("\n"), 400) + def test_domain_cycle_rejects_disconnected_open_shared_boundary(self): + self.assertRaisesRegex(chart.ChartLineageError, "a junction is not one closed trace", chart._domain_cycle, {(0, 1): (0, 1), (2, 3): (2, 3)}, {(0, 1), (2, 3)}) + def test_summary_rejects_closed_schema_duplicate_and_lineage_forgeries(self): def extra(value): value["unexpected"] = None @@ -394,7 +394,5 @@ def test_failure_order_and_exact_boundary_comparators(self): with self.assertRaisesRegex(ValueError, "step 3"): anatomy.evaluate_axillary_predicate("left", (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) self.assertEqual((anatomy.evaluate_axillary_scalars(float.fromhex("0x1.9999999999999p-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(float.fromhex("0x1.999999999999ap-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(1.0, float.fromhex("0x1.4000000000001p+1")).passed), (False, True, False)) - - if __name__ == "__main__": unittest.main() diff --git a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py index 179a49d..9bc2739 100644 --- a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py +++ b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py @@ -243,6 +243,40 @@ def test_public_validator_is_closed_against_schema_and_value_forgery(self): for name, candidate in cases: with self.subTest(name=name), self.assertRaises(PreparedProjectionError): validate_prepared(candidate) + def test_validator_reuses_expected_projection_bytes_for_same_digest_triple(self): + with patch.object(projection, "_build_prepared", + wraps=projection._build_prepared) as build_prepared: + validate = projection._prepared_apis(projection._COMMITMENTS)[0] + self.assertIs(validate(self.prepared), self.prepared) + self.assertIs(validate(self.prepared), self.prepared) + self.assertEqual(build_prepared.call_count, 1) + def test_validator_rebuilds_for_changed_digest_and_rejects_fixed_input_drift(self): + fixed_inputs = projection._fixed_inputs(SOURCE, CONTRACT, PROFILE_TABLE) + changed_digest = "f" * 64 + changed_inputs = (*fixed_inputs[:4], changed_digest) + changed = copy.deepcopy(self.prepared) + changed["profile_selection"]["profile_table_sha256"] = changed_digest + changed["provenance"]["source_files"][1]["sha256"] = changed_digest + with patch.object(projection, "_fixed_inputs", + side_effect=[fixed_inputs, changed_inputs]): + with patch.object(projection, "_build_prepared", + wraps=projection._build_prepared) as build_prepared: + validate = projection._prepared_apis(projection._COMMITMENTS)[0] + self.assertIs(validate(self.prepared), self.prepared) + self.assertIs(validate(changed), changed) + self.assertEqual(build_prepared.call_count, 2) + drifted = SOURCE.read_bytes().replace(b'"forward": "+z"', b'"forward": "-z"', 1) + calls = [0] + def inputs_with_drift(*args): + if calls[0] == 0: + calls[0] += 1 + return fixed_inputs + projection._admit_source_bytes(drifted) + with patch.object(projection, "_fixed_inputs", side_effect=inputs_with_drift): + validate = projection._prepared_apis(projection._COMMITMENTS)[0] + self.assertIs(validate(self.prepared), self.prepared) + with self.assertRaisesRegex(PreparedProjectionError, "source identity mismatch"): + validate(self.prepared) def test_canonical_prepared_bytes_round_trip_and_rejections(self): encoded = canonical_json_bytes(self.prepared) admitted = admit_prepared_bytes(encoded) diff --git a/experiments/owned-root-assembly-successor/tests/test_render_export.py b/experiments/owned-root-assembly-successor/tests/test_render_export.py index 1785686..a7cd89d 100644 --- a/experiments/owned-root-assembly-successor/tests/test_render_export.py +++ b/experiments/owned-root-assembly-successor/tests/test_render_export.py @@ -13,6 +13,7 @@ HERE = Path(__file__).resolve().parents[1] REPO = HERE.parents[1] sys.path.insert(0, str(HERE)) +import artifact_serialization as artifacts import owned_root_surface as surface import prepared_projection import render_export as render @@ -125,6 +126,27 @@ def test_equal_valued_scalar_type_substitutions_are_rejected_recursively(self): with self.subTest(label=label), self.assertRaises(render.RenderExportError): render.validate_render_config(candidate) + def test_canonical_wire_config_admits_only_zero_float_normalization(self): + config = artifacts.decode_canonical_json( + artifacts.canonical_json_bytes(render.render_config_record()) + ) + self.assertIs(type(config["cameras"][0]["right"][1]), int) + render.validate_render_config(config) + for label, path, replacement in ( + ("type", ("cameras", 0, "right", 0), 1), + ("value", ("padding",), 25)): + candidate, target = deepcopy(config), None + target = candidate + for key in path[:-1]: + target = target[key] + target[path[-1]] = replacement + with self.subTest(label=label), self.assertRaises(render.RenderExportError): + render.validate_render_config(candidate) + candidate = deepcopy(config) + candidate["extra"] = False + with self.assertRaises(render.RenderExportError): + render.validate_render_config(candidate) + def test_config_factory_returns_independent_closed_values(self): first = render.render_config_record() first["cameras"][0]["right"][0] = 99.0 From 09f77a47325975d089c0c2e64eac99aa7dace495 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 11:50:24 +1200 Subject: [PATCH 15/38] Add numeric geometry seam for exact-five activation --- .../ai-delegation-and-review.md | 16 +- docs/project/status.md | 60 +++-- experiments/README.md | 5 +- .../generate_structural_profile_sources.py | 4 +- .../tests/test_structural_profile_sources.py | 36 ++- .../owned-root-assembly-successor/README.md | 91 +++++-- .../anatomy_gates.py | 26 +- .../build_owned_root.py | 40 +-- .../owned_root_surface.py | 233 +++++++----------- .../prepared_projection.py | 152 ++++++++---- .../tests/test_build_owned_root.py | 23 +- .../tests/test_owned_root_surface.py | 146 ++++++----- .../tests/test_prepared_projection.py | 55 +++++ .../tests/test_render_export.py | 9 +- 14 files changed, 532 insertions(+), 364 deletions(-) diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index 6ecac57..84ce099 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -339,12 +339,16 @@ merge authority. ## CodeRabbit and external review -For a substantial PR that is final-review-ready, the main thread launches the -hosted CodeRabbit pass and the committed-diff CLI pass in parallel as one -deliberate cycle. Both review the same clean, immutable pushed OID. Before -launching, the main thread fetches the PR branch, requires a clean worktree, -verifies local `HEAD` equals the remote PR-head OID, and records that OID with -both results. +For a substantial PR, the main thread pushes its first coherent, review-useful +head early enough for external review to run in parallel with later disjoint +work in the same PR. It does not wait for every planned addition to be complete +before starting the review clock. For each review-useful head, the main thread +launches the hosted CodeRabbit pass and the committed-diff CLI pass in parallel +as one deliberate cycle. Both review the same clean, immutable pushed OID. +Before launching, the main thread fetches the PR branch, requires the committed +tree to match the intended review content, verifies local `HEAD` equals the +remote PR-head OID, and records that OID with both results. Uncommitted disjoint +follow-on work may remain local and is not represented as reviewed. The CLI pass supports the hosted pass but cannot satisfy the hosted taper gate. Every changed pushed head receives a fresh hosted-plus-CLI cycle; findings diff --git a/docs/project/status.md b/docs/project/status.md index 60eb640..2c45b76 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -1,6 +1,6 @@ # Project status -Status date: 2026-09-03 (NZST; repository activity is recorded in NZST while +Status date: 2026-09-05 (NZST; repository activity is recorded in NZST while GitHub timestamps are UTC) ## Phase @@ -44,24 +44,52 @@ The required is now frozen and SHA-256-bound at `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`, recorded by its sidecar. Two independent Sol reviews returned `FREEZE` with zero -blockers. The bounded implementation phase is active at +blockers. The bounded implementation phase completed at `correction_round=0`; the builder must reject a missing or mismatched design-contract identity. -Advance only through the documented bounded implementation and internal gates. -Do not add profile branches, hidden skin, render corrections, solvers, distal -body, tail, runtime/deformation, gallery, or exact-five work before credible -standard-neutral evidence. If the required cues remain unclear after the -initial implementation and two shared corrections, reject this candidate; -another representation requires a newly recorded runway rather than an -automatic fallback. - -The named human checkpoint is Ben's appraisal of the exact-five owned-root -assembly, but only after standard neutral passes the unchanged internal gates -and the exact-five evidence is generated. The checkpoint uses fixed front, -side, and three-quarter final-surface renders. Internal metrics and model -reviews do not substitute for Ben's visual judgment. The [terminal seven-ring -outcome](../research/programmatic-root-complex-surface-investigation.md#terminal-outcome-2026-09-03) +The exact neutral evidence baseline is commit +`2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the +96-file publication in logical local cache +`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. It records 121 +tests with zero failures, errors, or skips; the seed gates and cross-seed +comparison passed. The exact `comparison-report.json` SHA-256, obtainable from +the exact sidecar, is +`f87afb2ac517e4fd42ffb04248d97045df016f59d9f6d344d4a45659340b7ab7`. The +direct PNG is +`b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed`, the +lineage PNG is +`19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2`, the +stable manifest is +`3a8c87da8a297fb19f6f07b6ea669bde196e5a43b5609525f639e07fc168235e`, and +the runtime fingerprint is +`c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085`. + +Main-thread visual appraisal found the neutral neck, shoulder/axilla, +pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks +agreed and found no material blocker. The exact-five gate is therefore +unlocked, but no exact-five executable or gallery exists yet. + +The semantics-preserving numeric-only geometry seam now fits the frozen LOC +cap and passes 126 managed tests, both seed gates, and cross-seed comparison. +Its fresh 96-file publication is in logical local cache +`artifact-cache/owned-root-assembly-successor/seam-20260905-1`; all 38 +geometry/perturbation/render roles in each seed are byte-identical to the +pre-seam baseline. The post-seam comparison report SHA-256 is +`912467f8c435932cd685b089911f0141ba2454b5e7a62dcea0501412960b09ea` +and the post-seam stable-manifest SHA-256 is +`56da91b3459f381a85c682844d1b3e25c76a491519847c9ebc2c2e3a7e9b0ed4`. + +Next is the separately SHA-bound activation contract and sibling exact-five +runner/publisher. Do not add a private-internal wrapper, duplicate geometry, +profile-aware branching, geometry correction, or a new representation. + +The named human checkpoint remains Ben's later exact-five gallery appraisal of +the owned-root assembly, but only after standard neutral passes the unchanged +internal gates and the exact-five evidence is generated. The checkpoint uses +fixed front, side, and three-quarter final-surface renders. Internal metrics +and model reviews do not substitute for Ben's visual judgment. The [terminal +seven-ring outcome](../research/programmatic-root-complex-surface-investigation.md#terminal-outcome-2026-09-03) remains historical evidence and is not reactivated. ## Historical failed-candidate runway (2026-09-01) diff --git a/experiments/README.md b/experiments/README.md index 95d97a1..246853f 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -115,8 +115,9 @@ The [owned root assembly successor](owned-root-assembly-successor/README.md) is the unregistered exploratory successor targeting open `RQ-002`, `RQ-012`, `RQ-020`, and `RQ-021`. It is not `EXP-0001`; its candidate-local design contract is frozen and SHA-256-bound, and its bounded implementation phase is -active at `correction_round=0`. It cannot establish a formal technology -outcome, production surface contract, or Stage 1 result. +complete at `correction_round=0`. Its credible neutral evidence unlocks the +separately contracted exact-five activation work; it cannot establish a formal +technology outcome, production surface contract, or Stage 1 result. ## Artifact policy diff --git a/experiments/current-form-surface-preview/generate_structural_profile_sources.py b/experiments/current-form-surface-preview/generate_structural_profile_sources.py index 950872a..2cfa722 100644 --- a/experiments/current-form-surface-preview/generate_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/generate_structural_profile_sources.py @@ -277,9 +277,7 @@ def _integer(value: Any, where: str, *, minimum: int = 0, maximum: int = MAX_SAF def _positive_finite_metre(value: Any, where: str) -> Decimal: """Validate a JSON number as a positive canonical metre value.""" - if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): - raise ProfileGenerationError(f"{where} must be a positive finite metre number") - if isinstance(value, float) and not math.isfinite(value): + if isinstance(value, bool) or isinstance(value, float) or not isinstance(value, (int, Decimal)): raise ProfileGenerationError(f"{where} must be a positive finite metre number") try: decimal = Decimal(str(value)) diff --git a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py index ff236d2..19930a7 100644 --- a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py @@ -78,7 +78,8 @@ def setUp(self) -> None: self.candidate_path = EXPERIMENT / "structural_profile_candidates.json" self.source_path = REPO_ROOT / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" self.candidate = json.loads(self.candidate_path.read_text(encoding="utf-8")) - self.base = json.loads(self.source_path.read_text(encoding="utf-8")) + self.base_json = json.loads(self.source_path.read_text(encoding="utf-8")) + self.base = generator.load_json(self.source_path, "authored source") self.output_dir = self.root / "sources" generator.write_sources(self.candidate_path, self.source_path, self.output_dir) self.sources = { @@ -267,6 +268,35 @@ def test_active_profile_write_preserves_decimal_tokens_at_half_millimetre(self) ) ) + def test_active_generation_rejects_float_before_precision_can_change_ties_to_even(self) -> None: + dimension_role = "form_head_neck_profile_cranium_crown_forward_radius" + where = "test.dimension" + self.assertEqual(generator._positive_finite_metre(1, where), Decimal("1")) + self.assertEqual(generator._positive_finite_metre(Decimal("0.65"), where), Decimal("0.65")) + + precise_source = copy.deepcopy(self.base) + precise_dimension = next( + dimension + for dimension in precise_source["body"]["dimensions"] # type: ignore[index] + if dimension["owner"] == address("head") and dimension["role"] == dimension_role # type: ignore[index] + ) + precise_dimension["value"] = Decimal("0.6500000000000000001") # type: ignore[index] + precise_outputs = generator.generate_sources(copy.deepcopy(self.candidate), precise_source) + precise_compact = next( + output for output in precise_outputs if output["source"]["document"].endswith("__compact_broad_short_limb_large_head") + ) + self.assertEqual(self.dimension(precise_compact, "head", dimension_role), 0.813) + + float_source = copy.deepcopy(self.base) + float_dimension = next( + dimension + for dimension in float_source["body"]["dimensions"] # type: ignore[index] + if dimension["owner"] == address("head") and dimension["role"] == dimension_role # type: ignore[index] + ) + float_dimension["value"] = 0.65 # type: ignore[index] + with self.assertRaisesRegex(generator.ProfileGenerationError, "positive finite metre number"): + generator.generate_sources(copy.deepcopy(self.candidate), float_source) + def test_generated_dimensions_remain_positive_finite_canonical_metres(self) -> None: for profile_id, document in self.sources.items(): with self.subTest(profile=profile_id): @@ -517,7 +547,7 @@ def test_profile_inequalities_and_tail_style_contrast_are_real_source_difference "stylized_digitigrade_biped_authored_form__structural_profile__" "standard_neutral_reference" ) - expected_neutral = copy.deepcopy(self.base) + expected_neutral = copy.deepcopy(self.base_json) expected_neutral["source"]["document"] = expected_document # type: ignore[index] for module in expected_neutral["body"]["modules"]: # type: ignore[index] module["declaration"]["document"] = expected_document # type: ignore[index] @@ -676,7 +706,7 @@ def rejected(candidate: dict[str, object], label: str) -> None: self.assertEqual(len(bounded_stages), 1) self.assertEqual(list(bounded_stages[0].iterdir()), []) - same_identity_source = copy.deepcopy(self.base) + same_identity_source = copy.deepcopy(self.base_json) same_identity_source["extensions"] = ["lineage-mismatch"] same_identity_path = self.root / "same-identity-different-source.json" same_identity_path.write_bytes(generator.canonical_source_bytes(same_identity_source)) diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 417db34..223e96e 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -1,11 +1,11 @@ # Owned root assembly successor -Status: bounded experiment-local successor implementation phase; frozen, -SHA-256-bound, non-normative +Status: standard-neutral execution complete; frozen, SHA-256-bound, +non-normative -Experiment lifecycle: planned +Experiment lifecycle: finished -Evidence closure: open +Evidence closure: complete Technology outcome: none @@ -13,7 +13,7 @@ Owner: Creature Kernel main Sol thread; Ben retains direction and acceptance Date started: 2026-09-03 -Date completed: — +Date completed: 2026-09-05 Research questions: canonical open `RQ-002`, `RQ-012`, `RQ-020`, and `RQ-021` in the [open-questions registry](../../docs/research/open-questions.md). This @@ -26,18 +26,19 @@ returned `FREEZE` with zero blockers Design contract SHA-256: `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490` -`correction_round=0`: initial implementation phase; at most two shared -correction rounds remain available after the initial build +`correction_round=0`: initial implementation completed; at most two shared +correction rounds remain available ## Status and authority This is the frozen candidate contract and bounded implementation phase for one new, standard-neutral experiment. It is the successor direction authorized after the seven-ring candidate in PR #125 reached its three-round stop rule. -It remains an unaccepted experiment-local candidate: it does not accept a +It remains an unaccepted experiment-local candidate: the neutral result +supports proceeding to the unchanged exact-five gate, but does not establish a production schema, architecture, topology, supported morphology promise, or -technology outcome. It does not reactivate a parked workstream or satisfy the -DR-0013 Stage 1 proof. +permanent technology choice. It does not reactivate a parked workstream or +satisfy the DR-0013 Stage 1 proof. The previous candidate is evidence, not a foundation to transplant. Its seven-ring topology, projection, formulas, macros, IDs, thresholds, and @@ -45,6 +46,47 @@ anatomy-specific tests are archive/reimplementation candidates under the ledger below. Representation-independent utilities may be reused only after the focused audit required here. +## Current execution state + +The exact neutral evidence baseline is commit +`2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the +96-file publication in logical local cache +`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. It records 121 +tests with zero failures, errors, or skips; the seed gates and cross-seed +comparison passed. + +The exact `comparison-report.json` SHA-256, obtainable from the exact +`comparison-report.sha256` sidecar, is +`f87afb2ac517e4fd42ffb04248d97045df016f59d9f6d344d4a45659340b7ab7`. The +direct PNG is +`b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed`, the +lineage PNG is +`19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2`, the +stable manifest is +`3a8c87da8a297fb19f6f07b6ea669bde196e5a43b5609525f639e07fc168235e`, and +the runtime fingerprint is +`c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085`. + +Main-thread visual appraisal found the neutral neck, shoulder/axilla, +pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks +agreed and found no material blocker. The exact-five gate is therefore +unlocked, but no exact-five executable or gallery exists yet. The named human +checkpoint remains Ben's later exact-five gallery appraisal. + +The semantics-preserving numeric-only geometry seam now fits the frozen LOC +cap and passes 126 managed tests, both seed gates, and cross-seed comparison. +Its fresh 96-file publication is in logical local cache +`artifact-cache/owned-root-assembly-successor/seam-20260905-1`; all 38 +geometry/perturbation/render roles in each seed are byte-identical to the +pre-seam baseline. The post-seam comparison report SHA-256 is +`912467f8c435932cd685b089911f0141ba2454b5e7a62dcea0501412960b09ea` +and the post-seam stable-manifest SHA-256 is +`56da91b3459f381a85c682844d1b3e25c76a491519847c9ebc2c2e3a7e9b0ed4`. + +Next is the separately SHA-bound activation contract and sibling exact-five +runner/publisher. Do not add a private-internal wrapper, duplicate geometry, +profile-aware branching, geometry correction, or a new representation. + ## Protocol This is an unregistered exploratory experiment. No comparative, accounting, @@ -115,11 +157,10 @@ decimal arithmetic, quantizes to the nearest millimetre using ties-to-even, and emits canonical metres. Before execution, the launcher records both active source hashes and stops on source drift rather than silently using a new input. -This is a metadata/hash rebaseline only. Standard-neutral geometry is expected -to remain unchanged, and the historical source/evidence is not rewritten. The -design contract is now frozen and SHA-256-bound; this README activates the -bounded implementation phase but does not claim that implementation evidence -or successor execution results exist. +The source change is a metadata/hash rebaseline only: standard-neutral input +ownership remains intact, and historical source/evidence is not rewritten. +The design contract is frozen and SHA-256-bound; the completed neutral +execution and its evidence are recorded below. The prepared input may contain only source-derived frames, named landmarks, section measurements, derived scalar parameters, module state, and provenance. @@ -521,21 +562,23 @@ does not authorize promotion into production code or canonical architecture. ## Results, limitations, and conclusion -No result exists yet. Execution is activated at `correction_round=0`; until a -run closes evidence, lifecycle remains `planned`, evidence closure remains -`open`, and technology outcome remains `none`. +The standard-neutral execution completed at `correction_round=0` against the +exact baseline above. Its 96-file publication, 121-test clean result, passed +seed gates, and passed cross-seed comparison permit proceeding to the unchanged +exact-five gate. No exact-five executable or gallery exists yet. The trial is limited to one standard-neutral root assembly. It does not test the exact-five profiles, optional modules, tails, hands, feet, faces, distal anatomy, posing, skeleton runtime, deformation, simulation, engine adapters, -or production packaging. A positive result would only justify the next -recorded investigation and human checkpoint. +or production packaging. This positive result does not approve production use; +it only unlocks the next recorded investigation and human checkpoint. ## Recommended follow-up -Implement only the standard-neutral candidate within the frozen contract, -using its recorded interface curves, patch/junction layout, port orientations, -subdivision support, continuity and fold measures, candidate-specific -geometric measures, causal perturbations, and exact reproduction command. Do +Implement the semantics-preserving numeric-only geometry seam, then revalidate +the exact-neutral bytes and evidence against the baseline above. Separately, +prepare the SHA-bound activation contract and sibling exact-five +runner/publisher. Do not add a private-internal wrapper, duplicate geometry, +profile-aware branching, geometry correction, or a new representation, and do not edit canonical specifications or production architecture as part of this experiment. diff --git a/experiments/owned-root-assembly-successor/anatomy_gates.py b/experiments/owned-root-assembly-successor/anatomy_gates.py index bff2ec9..774da8c 100644 --- a/experiments/owned-root-assembly-successor/anatomy_gates.py +++ b/experiments/owned-root-assembly-successor/anatomy_gates.py @@ -72,16 +72,16 @@ def _chart_levels(charts, levels): result.append(tuple(checked)) if len(result) != 3 or len(seen) != sum(len(row) for row in result): _fail("chart ancestry is not a three-level sequence") return tuple(result) -def validate_evaluated_surface(value, chart_summary=None, *, prepared=None): - try: levels = surface.validate_evaluation(value, prepared) +def validate_evaluated_surface(value, geometry, chart_summary=None): + try: levels = surface.validate_evaluation(value, geometry) except (ValueError, IndexError, TypeError) as exc: _fail("evaluated surface admission is invalid", str(exc)) for level, mesh in enumerate(levels): if (len(mesh.vertices), len(mesh.quads), len(surface.topology_incidence(mesh))) != LEVEL_COUNTS[level]: _fail("evaluated surface count mismatch", f"L{level}") if chart_summary is not None: _chart_levels(chart_summary, levels) return levels -def _context(value, prepared, chart_summary): +def _context(value, geometry, chart_summary): if chart_summary is None: _fail("chart ancestry is required for anatomy selectors") - levels = validate_evaluated_surface(value, prepared=prepared); return levels, _chart_levels(chart_summary, levels) + levels = validate_evaluated_surface(value, geometry); return levels, _chart_levels(chart_summary, levels) def _actual_feature_edges(mesh, charts, feature, expected=None): edges = _edges(mesh) if feature in PORTS: @@ -128,8 +128,8 @@ def _trace(levels, charts, feature, level): tags = _feature_tags(levels, charts, feature, level); result = {tag: tuple(levels[level].vertices[index]) for index, tag in tags.items()} if len(result) != len(tags): _fail("ambiguous anatomy selector", feature) return dict(sorted(result.items())) -def select_trace(value, feature, level=2, chart_summary=None, *, prepared=None): - levels, charts = _context(value, prepared, chart_summary); return _trace(levels, charts, feature, level) +def select_trace(value, geometry, feature, level=2, chart_summary=None): + levels, charts = _context(value, geometry, chart_summary); return _trace(levels, charts, feature, level) def _vec(value, name): if not isinstance(value, (tuple, list)) or len(value) != 3 or any(type(x) is not float or not isfinite(x) for x in value): raise ValueError(f"{name} must be a finite binary64 vector3") return tuple(value) @@ -197,7 +197,7 @@ def _span(points, axis): return max(p[axis] for p in points) - min(p[axis] for p def _pair(a, b, name): if not a or set(a) != set(b): _fail("anatomy traces are missing or unequal", name) return [(tag, a[tag], b[tag]) for tag in sorted(a)] -def _side(out, levels, charts, level, side, neck_y, prepared): +def _side(out, levels, charts, level, side, neck_y, geometry): shoulder = _trace(levels, charts, f"junction.thorax__{side}_shoulder", level); arm = _trace(levels, charts, f"port.{side}_arm", level); prefix = "anatomy." _put(out, prefix + f"arm_port_descent.{side}.L{level}", [neck_y - p[1] for p in arm.values()]) owners = tuple(c["construction_owner"] for c in charts[level]); points = {i for fi, face in enumerate(levels[level].quads) if owners[fi] == f"domain.{side}_shoulder" for i in face} @@ -213,17 +213,17 @@ def _side(out, levels, charts, level, side, neck_y, prepared): _put(out, prefix + f"axillary_inboard_recess.{side}.L{level}", [sign * (o[0] - j[0]) for _, j, o in paired]); _put(out, prefix + f"axillary_downward_recess.{side}.L{level}", [o[1] - j[1] for _, j, o in paired]) hip = _trace(levels, charts, f"junction.pelvis__{side}_hip", level); thigh = _trace(levels, charts, f"port.{side}_thigh", level); paired = _pair(hip, thigh, "pelvic wrap"); _put(out, prefix + f"pelvic_vertical_wrap.{side}.L{level}", [j[1] - p[1] for _, j, p in paired]) - ps_x = prepared["hips"][side]["P_s"][0]; ratios = [abs(j[0] - ps_x) / abs(p[0] - ps_x) for _, j, p in paired if p[0] - ps_x != 0.0]; omitted = len(paired) - len(ratios) + ps_x = surface.geometry_component(geometry, f"hips.{side}.P_s.x"); ratios = [abs(j[0] - ps_x) / abs(p[0] - ps_x) for _, j, p in paired if p[0] - ps_x != 0.0]; omitted = len(paired) - len(ratios) if not ratios: _fail("pelvic lateral ratio has no nonzero denominators", side) _put(out, prefix + f"pelvic_lateral_ratio.{side}.L{level}", ratios, "ge", "dimensionless", omitted) _put(out, prefix + f"front_depth_wrap.{side}.L{level}", [j[2] - p[2] for tag, j, p in paired if tag[1] > 1], "ge", "m"); _put(out, prefix + f"back_depth_wrap.{side}.L{level}", [p[2] - j[2] for tag, j, p in paired if tag[1] < 1], "ge", "m") _put(out, prefix + f"clearance.{side}_axilla.L{level}", [min(_span(tuple(arm.values()), 1), _span(tuple(arm.values()), 2))]) -def measure_anatomy(value, prepared, chart_summary=None): - levels, charts = _context(value, prepared, chart_summary); out = {} +def measure_anatomy(value, geometry, chart_summary=None): + levels, charts = _context(value, geometry, chart_summary); out = {} for level in range(3): neck = _trace(levels, charts, "port.neck", level); neck_junction = _trace(levels, charts, "junction.thorax__neck", level); paired = _pair(neck, neck_junction, "neck exposure") _put(out, f"anatomy.neck_exposure.L{level}", [port[1] - junction[1] for _, port, junction in paired]); neck_y = min(p[1] for p in neck.values()) - for side in ("left", "right"): _side(out, levels, charts, level, side, neck_y, prepared) + for side in ("left", "right"): _side(out, levels, charts, level, side, neck_y, geometry) left_hip, right_hip = _trace(levels, charts, "junction.pelvis__left_hip", level), _trace(levels, charts, "junction.pelvis__right_hip", level); left_thigh, right_thigh = _trace(levels, charts, "port.left_thigh", level), _trace(levels, charts, "port.right_thigh", level) _put(out, f"anatomy.clearance.neck.L{level}", [min(_span(tuple(neck.values()), 0), _span(tuple(neck.values()), 2))]); _put(out, f"anatomy.clearance.groin.L{level}", [min(p[0] for p in right_hip.values()) - max(p[0] for p in left_hip.values())]); _put(out, f"anatomy.clearance.medial_thigh.L{level}", [min(p[0] for p in right_thigh.values()) - max(p[0] for p in left_thigh.values())]) if len(out) != 78: _fail("anatomy inventory is not exactly 78 measures", len(out)) @@ -234,8 +234,8 @@ def anatomy_threshold_records(): ids = [f"anatomy.neck_exposure.L{l}" for l in range(3)] + [f"anatomy.{m}.{s}.L{l}" for m in ANATOMY_METRICS for s in ("left", "right") for l in range(3)] + [f"anatomy.clearance.{c}.L{l}" for c in CLEARANCES for l in range(3)]; result = [] for key in sorted(ids): relation, bound, unit = _spec(key); result.append({"threshold_id": f"threshold.{key}", "relation": relation, "lower": bound if relation == "ge" else None, "upper": bound if relation == "le" else None, "unit": unit}) return result -def anatomy_gate_records(value, prepared, chart_summary=None): - measures = measure_anatomy(value, prepared, chart_summary); failures = [] +def anatomy_gate_records(value, geometry, chart_summary=None): + measures = measure_anatomy(value, geometry, chart_summary); failures = [] for key, item in measures.items(): relation, bound, _ = _spec(key); valid = item["maximum"] <= bound if relation == "le" else item["minimum"] >= bound failures.extend((key,) if not valid else ()) diff --git a/experiments/owned-root-assembly-successor/build_owned_root.py b/experiments/owned-root-assembly-successor/build_owned_root.py index c06b167..1b651fc 100644 --- a/experiments/owned-root-assembly-successor/build_owned_root.py +++ b/experiments/owned-root-assembly-successor/build_owned_root.py @@ -132,14 +132,14 @@ def _fold_samples(mesh, surface, junction, level, mesh_api): for slot, left in enumerate(face): uses.setdefault(tuple(sorted((left, face[(slot + 1) % 4]))), []).append(face_index) owners = frozenset(surface.JUNCTION_INFO[junction][0]) values = tuple(mesh_api.fold_angle_degrees(mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[0]]), mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[1]])) for faces in uses.values() if len(faces) == 2 and frozenset(mesh.face_owners[i] for i in faces) == owners); _need(bool(values), f"no fold samples for {junction} at L{level}"); return values -def _ownership_counts(surface, evaluation, chart_api, mesh_api, prepared, formulas, summary, level): +def _ownership_counts(surface, evaluation, chart_api, mesh_api, geometry_input, formulas, summary, level): mesh = (evaluation.cage, *evaluation.levels)[level]; uses = _edge_uses(mesh); expected_counts = LEVEL_COUNTS[level]; _need((len(mesh.control_ids), len(mesh.quads), len(uses), len(surface.PORTS)) == (expected_counts[0], expected_counts[2], expected_counts[1], 5) and sum((expected_counts[0], expected_counts[2], expected_counts[1], 5)) == (456, 1742, 6810)[level], f"ownership element universe changed at L{level}") edges = tuple(uses); keys = tuple(("vertex", value) for value in mesh.control_ids) + tuple(("face", value) for value in mesh.face_ids) + tuple(("edge", value) for value in edges) + tuple(("boundary", value) for value in surface.PORTS); required = {key: ("construction", "lineage") if level == 0 and key[0] == "vertex" else ("lineage",) if key[0] == "vertex" else ("chart",) if key[0] == "face" else ("classification",) if key[0] == "edge" else ("boundary",) for key in keys}; expected = chart_api.build_chart_summary(evaluation, formulas); formula_by_id = {row["control_id"]: row for row in formulas}; expected_vertices = {(row["level"], row["vertex_id"]): row for row in expected["vertex_records"]}; expected_faces = {(row["level"], row["face_id"]): row for row in expected["chart_records"]}; records = [( ("vertex", row["control_id"]), "construction", row == formula_by_id.get(row["control_id"]) ) for row in evaluation.cage.formula_records] if level == 0 else [] records.extend((("vertex", row["vertex_id"]), "lineage", row == expected_vertices.get((level, row["vertex_id"]))) for row in summary["vertex_records"] if row["level"] == level); records.extend((("face", row["face_id"]), "chart", row == expected_faces.get((level, row["face_id"]))) for row in summary["chart_records"] if row["level"] == level) owners = mesh.face_owners; junction_edges = {} for junction in surface.JUNCTIONS: domains = surface.JUNCTION_INFO[junction][0]; cycle = _junction_cycles(mesh, owners, domains)[0]; junction_edges[frozenset(domains)] = {tuple(sorted((left, cycle[(slot + 1) % len(cycle)]))) for slot, left in enumerate(cycle)} - boundary = {edge for edge, faces in uses.items() if len(faces) == 1}; records.extend(_edge_candidates(uses, owners, boundary, junction_edges)); records.extend((("boundary", port), "boundary", all(edge in boundary for edge in {tuple(sorted((left, loop[(slot + 1) % len(loop)]))) for slot, left in enumerate(loop)}) and len(boundary) == sum(len({tuple(sorted((left, loop[(slot + 1) % len(loop)]))) for slot, left in enumerate(values)}) for _, values in mesh.boundary_loops)) for port, loop in mesh.boundary_loops) + boundary = {edge for edge, faces in uses.items() if len(faces) == 1}; records.extend(_edge_candidates(uses, owners, boundary, junction_edges)); records.extend((("boundary", port), "boundary", all(edge in boundary for edge in {tuple(sorted((left, loop[(slot + 1) % len(loop)]))) for slot, left in enumerate(loop)}) and len(boundary) == sum(len({tuple(sorted((left, values[(slot + 1) % len(values)]))) for slot, left in enumerate(values)}) for _, values in mesh.boundary_loops)) for port, loop in mesh.boundary_loops) return mesh_api.classify_ownership_records(keys, required, tuple(records)) def _invalid_counts(mesh, report, edges, triangles, ownership, surface): return {"duplicate_vertex_ids": len(mesh.control_ids) - len(set(mesh.control_ids)), "duplicate_face_ids": len(mesh.face_ids) - len(set(mesh.face_ids)), "degenerate_faces": sum(triangles[2 * index] <= 0.0 or triangles[2 * index + 1] <= 0.0 for index in range(len(mesh.quads))), "zero_length_edges": sum(value == 0.0 for value in edges), "non_manifold_edges": report["topology"].non_manifold_edges, "orientation_conflicts": report["topology"].orientation_conflicts, "unowned_elements": ownership["unowned_elements"], "overowned_elements": ownership["overowned_elements"], "accidental_boundary_components": abs(report["topology"].boundary_components - len(surface.PORTS))} @@ -159,11 +159,11 @@ def _continuity(surface, mesh_api, evaluation, reports, chart_summary=None): for port, metric in reports[level]["port_metrics"].items(): count = len(dict(mesh.boundary_loops)[port]); _need(len(metric["planarity_samples"]) == count and len(metric["co_normal_samples"]) == count, f"port sample cardinality changed for {port} at L{level}"); values = (("orientation", (metric["orientation"],), "ge", .99, None, "dimensionless"), ("planarity", metric["planarity_samples"], "le", None, mesh_api.T, "m"), ("area_ratio", (metric["area_ratio"],), "ge", .0001, None, "dimensionless"), ("co_normal", metric["co_normal_samples"], "ge", .80, None, "dimensionless")); [_sample_gate(gates, thresholds, f"continuity.{port}.L{level}.{name}", samples, relation, lower, upper, unit) for name, samples, relation, lower, upper, unit in values] return gates, thresholds -def _geometry(surface, mesh_api, chart, anatomy, prepared): +def _geometry(surface, mesh_api, chart, anatomy, geometry_input): axillary = anatomy.run_production_axillary_fixtures(); _need(len(axillary) == 13 and tuple(row["fixture_id"] for row in axillary) == anatomy.AXILLARY_FIXTURE_IDS, "axillary production fixture suite did not execute its exact 13 IDs") runner = getattr(mesh_api, "run_production_intersection_fixtures", None); _need(runner is not None, "missing required public API: mesh_correctness.run_production_intersection_fixtures (105 cases)") fixtures = runner(); _need(len(fixtures) == 105 and tuple(row["fixture_id"] for row in fixtures) == mesh_api.INTERSECTION_FIXTURE_IDS, "intersection production fixture suite did not execute its exact 105 IDs") - evaluation = surface.evaluate(prepared); meshes = (evaluation.cage, *evaluation.levels); formulas = tuple(surface.formula_candidate_records(prepared)); chart_summary = chart.build_chart_summary(evaluation, formulas); chart.validate_chart_summary(chart_summary, evaluation, formulas); anatomy.validate_evaluated_surface(evaluation, chart_summary); anatomy_rows = tuple(anatomy.anatomy_gate_records(evaluation, prepared, chart_summary)) + evaluation = surface.evaluate(geometry_input); meshes = (evaluation.cage, *evaluation.levels); formulas = tuple(surface.formula_candidate_records(geometry_input)); chart_summary = chart.build_chart_summary(evaluation, formulas); chart.validate_chart_summary(chart_summary, evaluation, formulas); anatomy.validate_evaluated_surface(evaluation, geometry_input, chart_summary); anatomy_rows = tuple(anatomy.anatomy_gate_records(evaluation, geometry_input, chart_summary)) expected = tuple(tuple(int(control[1:]) for control in row[2]) for row in surface.FACE_RECORDS); derived = mesh_api.derive_expected_face_catalogs(expected); _need(tuple(len(rows) for rows in derived) == (104, 416, 1664), "independently derived expected topology differs") reports, intersection_reports = [], [] for level, mesh in enumerate(meshes): @@ -174,7 +174,7 @@ def _geometry(surface, mesh_api, chart, anatomy, prepared): [_put(structural, thresholds, _bool(f"structural.L{level}.surface_boolean.{name}")) for name in "connected orientable outward_wound boundary_components_match_ports".split()] [(_put(structural, thresholds, _bool(f"structural.L{level}.finite.{name}")), structural[-1].__setitem__("sample_count", count)) for name, count in (("coordinates", 3 * len(mesh.vertices)), ("quad_normals", 3 * len(mesh.quads)), ("triangle_areas", len(triangles)), ("quad_areas", len(quads)))] [_put(structural, thresholds, _gate(f"structural.L{level}.floor.{name}", len(values), min(values), max(values), "ge", mesh_api.STRUCTURAL_FLOORS[level][name], None, "m" if name == "edge_length" else "m2")) for name, values in (("edge_length", edge), ("triangle_area", triangles), ("quad_area", quads))] - invalid_values = _invalid_counts(mesh, report, edge, triangles, _ownership_counts(surface, evaluation, chart, mesh_api, prepared, formulas, chart_summary, level), surface); [_put(structural, thresholds, _gate(f"structural.L{level}.invalid_count.{name}", 1, invalid_values[name], invalid_values[name], "eq", 0, 0, "count")) for name in invalid] + invalid_values = _invalid_counts(mesh, report, edge, triangles, _ownership_counts(surface, evaluation, chart, mesh_api, geometry_input, formulas, chart_summary, level), surface); [_put(structural, thresholds, _gate(f"structural.L{level}.invalid_count.{name}", 1, invalid_values[name], invalid_values[name], "eq", 0, 0, "count")) for name in invalid] [_put(structural, thresholds, _gate(f"structural.L{level}.chart.{name}", 1, chart_counts[level][name], chart_counts[level][name], "eq", chart_counts[level][name], chart_counts[level][name], "count")) for name in ("charts", "interior_transitions", "maximum_samples_per_vertex")] for name, limit in (("base_control_contributors", 20), ("dependency_union_keys", 54), ("contributor_domains", 5)): rows = [row for row in chart_summary["vertex_records"] if row["level"] == 2]; field = {"base_control_contributors": "base_control_contributors", "dependency_union_keys": "geometry_dependency_union", "contributor_domains": "contributor_domains"}[name]; value = max(len(row[field]) for row in rows); row, threshold = _gate(f"structural.L2.lineage_cap.{name}", 1737, value, value, "le", None, limit, "count"); structural.append(row); thresholds.append(threshold) @@ -189,15 +189,17 @@ def _support_hash(indices): if tuple(sorted(set(values))) != values or any(type(index) is not int or not 0 <= index < 1737 for index in values): _fail("support indices are not ascending level-2 indices") payload = b"CKSUPPORTv1\0\2" + struct.pack("= 0.0 else posterior) * signed_power(q)) -def _reference_control_coordinate(prepared, control): +def _reference_control_coordinate(geometry, control): i, j, k = COORDINATE_BY_CONTROL[control]; q = float(k - 1) if j in (6, 7) and i in (2, 3): - row = prepared["stations"]["neck_collar" if j == 6 else "neck_upper"] + row = _station_record(geometry, "neck_collar" if j == 6 else "neck_upper") return _reference_e(row["C"], 2.0 * (float(i) - 2.5), q, row["rL"], row["rA"], row["rP"], 2.2) if j in (4, 5, 6) and i in (0, 1, 4, 5): - side = "left" if i < 2 else "right"; sign = -1.0 if side == "left" else 1.0; a = 1 - i if side == "left" else i - 4; v = (float(j) - 4.0) / 2.0; row = prepared["shoulders"][side] + side = "left" if i < 2 else "right"; sign = -1.0 if side == "left" else 1.0; a = 1 - i if side == "left" else i - 4; v = (float(j) - 4.0) / 2.0; row = _shoulder(geometry, side) inner = tuple((1.0 - v) * row["axilla"][axis] + v * row["peak"][axis] for axis in range(3)); outer = (row["arm_origin"][0] + sign * row["start_lateral"], row["arm_origin"][1] + (2.0 * v - 1.0) * row["start_up"] * .5, row["arm_origin"][2]) center = tuple((1.0 - float(a)) * inner[axis] + float(a) * outer[axis] for axis in range(3)); inner_depth = .75 * row["start_forward"] if v == 0.0 else row["shoulder_depth"]; depth = (1.0 - float(a)) * inner_depth + float(a) * row["start_forward"] return _reference_e(center, 0.0, q, 0.0, depth, depth, 2.2) if j in (-1, 0): - side = "left" if i <= 2 else "right"; row = prepared["hips"][side]; u = float(i) - (1.0 if side == "left" else 4.0); ps = row["P_s"] + side = "left" if i <= 2 else "right"; row = _hip(geometry, side); u = float(i) - (1.0 if side == "left" else 4.0); ps = row["P_s"] if j == -1: return (ps[0] + u * row["r_x"], ps[1], ps[2] + q * row["r_z"]) - low = prepared["stations"]["lower_pelvis"]; distance = low["C"][1] - ps[1]; maximum_x = low["rL"] - abs(ps[0] - low["C"][0]); hc = row["r_y"] + .25 * (distance - row["r_y"]); hs = .70 * hc + low = _station_record(geometry, "lower_pelvis"); distance = low["C"][1] - ps[1]; maximum_x = low["rL"] - abs(ps[0] - low["C"][0]); hc = row["r_y"] + .25 * (distance - row["r_y"]); hs = .70 * hc jf = row["r_z"] + .20 * (low["rA"] - row["r_z"]); jb = row["r_z"] + .20 * (low["rP"] - row["r_z"]) - return (ps[0] + u * (row["r_x"] + (maximum_x - row["r_x"])), ps[1] + hs + (hc - hs) * (1.0 - u * u), ps[2] + .20 * (low["C"][2] - ps[2]) + (jf if q >= 0.0 else jb) * q) + j0z = (1.0 - .20) * ps[2] + .20 * low["C"][2] + return (ps[0] + u * (row["r_x"] + (maximum_x - row["r_x"])), ps[1] + hs + (hc - hs) * (1.0 - u * u), j0z + (jf if q >= 0.0 else jb) * q) if j == 1: - row = prepared["stations"]["upper_pelvis"] if i in (0, 5) else prepared["stations"]["lower_abdomen"]; u = (float(i) - 2.5) / 2.5 - center = row["C"] if i in (0, 5) else (row["C"][0], (prepared["stations"]["upper_pelvis"]["C"][1] + row["C"][1]) / 2.0, row["C"][2]) + row = _station_record(geometry, "upper_pelvis" if i in (0, 5) else "lower_abdomen"); u = (float(i) - 2.5) / 2.5 + center = row["C"] if i in (0, 5) else (row["C"][0], (_station_record(geometry, "upper_pelvis")["C"][1] + row["C"][1]) / 2.0, row["C"][2]) return _reference_e(center, u, q, row["rL"], row["rA"], row["rP"], 2.6) u = (float(i) - 2.5) / 1.5 if j == 5: - low, high = (prepared["stations"][name] for name in ("lower_ribcage", "upper_ribcage_shoulder")); center = tuple((low["C"][axis] + high["C"][axis]) / 2.0 for axis in range(3)); radii = tuple((low[name] + high[name]) / 2.0 for name in ("rL", "rA", "rP")) + low, high = (_station_record(geometry, name) for name in ("lower_ribcage", "upper_ribcage_shoulder")); center = tuple((low["C"][axis] + high["C"][axis]) / 2.0 for axis in range(3)); radii = tuple((low[name] + high[name]) / 2.0 for name in ("rL", "rA", "rP")) else: - row = prepared["stations"][("waist_abdomen", "upper_abdomen", "lower_ribcage")[j - 2]]; center, radii = row["C"], (row["rL"], row["rA"], row["rP"]) + row = _station_record(geometry, ("waist_abdomen", "upper_abdomen", "lower_ribcage")[j - 2]); center, radii = row["C"], (row["rL"], row["rA"], row["rP"]) return _reference_e(center, u, q, *radii, 2.6) -def _validate_cage_lineage(mesh, prepared): +def _validate_cage_lineage(mesh, geometry): if type(mesh.formula_records) is not tuple: raise ValueError("L0 formula records are not a tuple") - reference_vertices = tuple(tuple(float(x) for x in _reference_control_coordinate(prepared, control)) for control in CONTROL_IDS) - if mesh.vertices != reference_vertices: raise ValueError("L0 vertices differ from independent prepared reference") + reference_vertices = tuple(tuple(float(x) for x in _reference_control_coordinate(geometry, control)) for control in CONTROL_IDS) + if mesh.vertices != reference_vertices: raise ValueError("L0 vertices differ from independent numeric reference") ledger = [] for index, (control, record) in enumerate(zip(CONTROL_IDS, mesh.formula_records)): if type(record) is not dict or set(record) != set(_FORMULA_RECORD_FIELDS): raise ValueError(f"L0 formula record schema mismatch at {index}") - if type(record["coordinate"]) is not list or len(record["coordinate"]) != 3 or any(type(value) is not float or not isfinite(value) for value in record["coordinate"]) or record["coordinate"] != list(reference_vertices[index]): raise ValueError(f"L0 formula coordinate differs from independent prepared reference at {index}") + if type(record["coordinate"]) is not list or len(record["coordinate"]) != 3 or any(type(value) is not float or not isfinite(value) for value in record["coordinate"]) or record["coordinate"] != list(reference_vertices[index]): raise ValueError(f"L0 formula coordinate differs from independent numeric reference at {index}") ledger.append({field: record[field] for field in _FORMULA_RECORD_FIELDS[:-1]}) if sha256(repr(tuple(ledger)).encode("ascii")).hexdigest() != _FORMULA_LEDGER_SHA256: raise ValueError("L0 formula ledger differs from the frozen contract") if mesh.formula_ids != tuple(record["formula_id"] for record in mesh.formula_records) or mesh.dependencies != tuple(tuple(record["geometry_dependencies"]) for record in mesh.formula_records): raise ValueError("L0 formula projections disagree with formula records") @@ -243,7 +258,6 @@ def _validate_level_shape(mesh): expected_triangles = tuple(t for face in mesh.quads for t in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) if mesh.triangles != expected_triangles: raise ValueError(f"L{mesh.level} triangle catalog mismatch") return report -def _mesh_difference(actual, expected): return next((field for field in Mesh.__dataclass_fields__ if getattr(actual, field) != getattr(expected, field)), None) def _reference_subdivision(parent, level): uses = _check_faces(parent.quads, len(parent.vertices)); edges = tuple(sorted(uses)); boundary, around, incident = defaultdict(set), defaultdict(list), defaultdict(list) for face_index, face in enumerate(parent.quads): @@ -279,21 +293,18 @@ def lineage(index, source): def _validate_derived_level(mesh, parent): report = _validate_level_shape(mesh) if type(parent) is not Mesh or parent.level != mesh.level - 1: raise ValueError(f"L{mesh.level} requires its immediately preceding parent") - _validate_level_shape(parent); expected = _reference_subdivision(parent, mesh.level); difference = _mesh_difference(mesh, expected) + _validate_level_shape(parent); expected = _reference_subdivision(parent, mesh.level); difference = next((field for field in Mesh.__dataclass_fields__ if getattr(mesh, field) != getattr(expected, field)), None) if difference is not None: raise ValueError(f"L{mesh.level} differs from its parent-derived {difference}") return report -def _validate_level_structure_admitted(mesh, prepared, parent=None): +def _validate_level_structure_numeric(mesh, geometry, parent=None): report = _validate_level_shape(mesh) if mesh.level == 0: if parent is not None: raise ValueError("level 0 cannot have a parent") - _validate_cage_lineage(mesh, prepared); return report - if type(parent) is Mesh and parent.level == 0: _validate_cage_lineage(parent, prepared) + _validate_cage_lineage(mesh, geometry); return report + if type(parent) is Mesh and parent.level == 0: _validate_cage_lineage(parent, geometry) return _validate_derived_level(mesh, parent) -def validate_level_structure(mesh, prepared=None, parent=None): - cage = mesh if type(mesh) is Mesh and mesh.level == 0 else parent if type(parent) is Mesh and parent.level == 0 else None - prepared = _infer_surface_prepared(cage) if prepared is None and cage is not None else prepared - if prepared is None: raise ValueError("prepared input is required when no L0 cage is available") - _admit_surface_prepared(prepared); return _validate_level_structure_admitted(mesh, prepared, parent) +def validate_level_structure(mesh, geometry, parent=None): + validate_geometry_components(geometry); return _validate_level_structure_numeric(mesh, geometry, parent) def _evaluation_meshes(value): if type(value) is SurfaceEvaluation: cage, levels = value.cage, value.levels elif isinstance(value, Mapping) and set(value) == {"cage", "levels"}: cage, levels = value["cage"], value["levels"] @@ -301,10 +312,8 @@ def _evaluation_meshes(value): else: raise ValueError("evaluation requires cage and levels 0 through 2") if type(levels) is not tuple or len(levels) != 2: raise ValueError("evaluation requires two derived levels") return (cage, *levels) -def validate_evaluation(value, prepared=None): - meshes = _evaluation_meshes(value) - prepared = _infer_surface_prepared(meshes[0]) if prepared is None else prepared; _admit_surface_prepared(prepared) - _validate_level_structure_admitted(meshes[0], prepared); _validate_level_structure_admitted(meshes[1], prepared, meshes[0]); _validate_level_structure_admitted(meshes[2], prepared, meshes[1]) +def validate_evaluation(value, geometry): + meshes = _evaluation_meshes(value); validate_geometry_components(geometry); _validate_level_structure_numeric(meshes[0], geometry); _validate_level_structure_numeric(meshes[1], geometry, meshes[0]); _validate_level_structure_numeric(meshes[2], geometry, meshes[1]) return meshes def topology_incidence(mesh): uses = _check_faces(mesh.quads, len(mesh.vertices)); return tuple({"edge": edge, "incident_faces": tuple(u[0] for u in uses[edge]), "slots": tuple(u[3] for u in uses[edge])} for edge in sorted(uses)) @@ -312,16 +321,20 @@ def level_topology(mesh): return {"level": mesh.level, "vertex_ids": mesh.control_ids, "face_ids": mesh.face_ids, "face_owners": mesh.face_owners, "faces": mesh.quads, "edges": topology_incidence(mesh), "boundary_loops": mesh.boundary_loops, "triangles": mesh.triangles} def _component_dependencies(name, u, q): return {f"stations.{name}.C.{axis}" for axis in "xyz"} | ({f"stations.{name}.rL"} if u != 0.0 else set()) | ({f"stations.{name}.rA"} if q > 0.0 else set()) | ({f"stations.{name}.rP"} if q < 0.0 else set()) -def _station(prepared, name): - row = prepared["stations"][name]; return row["C"], row["rL"], row["rA"], row["rP"] -def _formula_for_control(prepared, control_id): +def _station_record(geometry, name): + prefix = f"stations.{name}"; return {"C": _geometry_vector(geometry, prefix + ".C"), "rL": _geometry_value(geometry, prefix + ".rL"), "rA": _geometry_value(geometry, prefix + ".rA"), "rP": _geometry_value(geometry, prefix + ".rP")} +def _shoulder(geometry, side): + prefix = f"shoulders.{side}"; return {name: _geometry_vector(geometry, prefix + "." + name) for name in ("axilla", "peak", "arm_origin")} | {name: _geometry_value(geometry, prefix + "." + name) for name in ("start_lateral", "start_up", "start_forward", "shoulder_depth")} +def _hip(geometry, side): + prefix = f"hips.{side}"; return {"P_s": _geometry_vector(geometry, prefix + ".P_s")} | {name: _geometry_value(geometry, prefix + "." + name) for name in ("r_x", "r_y", "r_z")} +def _formula_for_control(geometry, control_id): i, j, k = COORDINATE_BY_CONTROL[control_id]; q = float(k - 1) if j in (6, 7) and i in (2, 3): - name = "neck_collar" if j == 6 else "neck_upper"; C, rl, ra, rp = _station(prepared, name); u = _mul(2.0, _sub(float(i), 2.5)); point = _e(C, u, q, rl, ra, rp, 2.2) + name = "neck_collar" if j == 6 else "neck_upper"; row = _station_record(geometry, name); C, rl, ra, rp = row["C"], row["rL"], row["rA"], row["rP"]; u = _mul(2.0, _sub(float(i), 2.5)); point = _e(C, u, q, rl, ra, rp, 2.2) deps = _component_dependencies(name, u, q); formula = "formula.neck.stem"; params = {"i": i, "j": j, "k": k, "u": u, "q": q, "n": 2.2, "station_selector": name} elif j in (4, 5, 6) and i in (0, 1, 4, 5): side = "left" if i < 2 else "right"; sign = -1 if side == "left" else 1 - a = 1 - i if side == "left" else i - 4; v = _div(_sub(float(j), 4.0), 2.0); row = prepared["shoulders"][side] + a = 1 - i if side == "left" else i - 4; v = _div(_sub(float(j), 4.0), 2.0); row = _shoulder(geometry, side) inner = _vlerp(row["axilla"], row["peak"], v); outer = _vadd(row["arm_origin"], (_mul(float(sign), row["start_lateral"]), _mul(_mul(_sub(_mul(2.0, v), 1.0), row["start_up"]), .5), 0.0)); inner_depth = _mul(.75, row["start_forward"]) if v == 0.0 else row["shoulder_depth"] depth = _add(_mul(float(1 - a), inner_depth), _mul(float(a), row["start_forward"])); point = _e(_vlerp(inner, outer, float(a)), 0.0, q, 0.0, depth, depth, 2.2); deps = set() if a == 0: @@ -335,39 +348,39 @@ def _formula_for_control(prepared, control_id): if q != 0: deps.add(f"shoulders.{side}.start_forward") formula = f"formula.shoulder.{side}"; params = {"i": i, "j": j, "k": k, "side": side, "a": float(a), "v": v, "q": q, "sign": sign} elif j in (-1, 0): - side = "left" if i <= 2 else "right"; row = prepared["hips"][side]; u = _sub(float(i), 1.0 if side == "left" else 4.0) + side = "left" if i <= 2 else "right"; row = _hip(geometry, side); u = _sub(float(i), 1.0 if side == "left" else 4.0) if j == -1: point = (_add(row["P_s"][0], _mul(u, row["r_x"])), row["P_s"][1], _add(row["P_s"][2], _mul(q, row["r_z"]))) deps = {f"hips.{side}.P_s.{x}" for x in "xyz"} | ({f"hips.{side}.r_x"} if u != 0 else set()) | ({f"hips.{side}.r_z"} if q != 0 else set()) else: - low = prepared["stations"]["lower_pelvis"]; ps = row["P_s"]; D = _sub(low["C"][1], ps[1]); Mx = _sub(low["rL"], abs(_sub(ps[0], low["C"][0]))); Hc = _add(row["r_y"], _mul(.25, _sub(D, row["r_y"]))); Hs = _mul(.70, Hc); Jx = _add(row["r_x"], _sub(Mx, row["r_x"])) + low = _station_record(geometry, "lower_pelvis"); ps = row["P_s"]; D = _sub(low["C"][1], ps[1]); Mx = _sub(low["rL"], abs(_sub(ps[0], low["C"][0]))); Hc = _add(row["r_y"], _mul(.25, _sub(D, row["r_y"]))); Hs = _mul(.70, Hc); Jx = _add(row["r_x"], _sub(Mx, row["r_x"])) Jf = _add(row["r_z"], _mul(.20, _sub(low["rA"], row["r_z"]))); Jb = _add(row["r_z"], _mul(.20, _sub(low["rP"], row["r_z"]))); J0z = _lerp(ps[2], low["C"][2], .20); Qz = _mul(Jf if q >= 0 else Jb, q) point = (_add(ps[0], _mul(u, Jx)), _add(_add(ps[1], Hs), _mul(_sub(Hc, Hs), _sub(1., _mul(u, u)))), _add(J0z, Qz)) deps = {f"hips.{side}.P_s.y", f"hips.{side}.P_s.z", f"hips.{side}.r_y", "stations.lower_pelvis.C.y", "stations.lower_pelvis.C.z"} | ({f"hips.{side}.P_s.x"} if not ((side == "left" and u == -1.) or (side == "right" and u == 1.)) else set()) | ({"stations.lower_pelvis.rL", "stations.lower_pelvis.C.x"} if u != 0 else set()) | ({f"hips.{side}.r_z", "stations.lower_pelvis.rA"} if q > 0 else {f"hips.{side}.r_z", "stations.lower_pelvis.rP"} if q < 0 else set()) formula = f"formula.hip.{side}"; params = {"i": i, "j": j, "k": k, "side": side, "u": u, "q": q} else: if j == 1 and i in (0, 5): - name, d = "upper_pelvis", 2.5; C, rl, ra, rp = _station(prepared, name); u = _div(_sub(float(i), 2.5), d); point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(name, u, q); formula = "formula.axial.j1.edge"; selector = name + name, d = "upper_pelvis", 2.5; row = _station_record(geometry, name); C, rl, ra, rp = row["C"], row["rL"], row["rA"], row["rP"]; u = _div(_sub(float(i), 2.5), d); point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(name, u, q); formula = "formula.axial.j1.edge"; selector = name elif j == 1: - low, up = prepared["stations"]["lower_abdomen"], prepared["stations"]["upper_pelvis"]; d = 2.5; u = _div(_sub(float(i), 2.5), d); C = (low["C"][0], _div(_add(up["C"][1], low["C"][1]), 2.), low["C"][2]); point = _e(C, u, q, low["rL"], low["rA"], low["rP"], 2.6) + low, up = _station_record(geometry, "lower_abdomen"), _station_record(geometry, "upper_pelvis"); d = 2.5; u = _div(_sub(float(i), 2.5), d); C = (low["C"][0], _div(_add(up["C"][1], low["C"][1]), 2.), low["C"][2]); point = _e(C, u, q, low["rL"], low["rA"], low["rP"], 2.6) deps = _component_dependencies("lower_abdomen", u, q) | {"stations.upper_pelvis.C.y"}; formula = "formula.axial.j1.interior"; selector = "virtual.upper_pelvis_y__lower_abdomen" else: d = 1.5; u = _div(_sub(float(i), 2.5), d) if j == 5: - low, up = prepared["stations"]["lower_ribcage"], prepared["stations"]["upper_ribcage_shoulder"]; C = tuple(_div(_add(low["C"][x], up["C"][x]), 2.) for x in range(3)); radii = tuple(_div(_add(low[x], up[x]), 2.) for x in ("rL", "rA", "rP")); selector = "virtual.lower_ribcage__upper_ribcage_shoulder" + low, up = _station_record(geometry, "lower_ribcage"), _station_record(geometry, "upper_ribcage_shoulder"); C = tuple(_div(_add(low["C"][x], up["C"][x]), 2.) for x in range(3)); radii = tuple(_div(_add(low[x], up[x]), 2.) for x in ("rL", "rA", "rP")); selector = "virtual.lower_ribcage__upper_ribcage_shoulder" point = _e(C, u, q, *radii, 2.6); deps = {f"stations.{name}.C.{x}" for name in ("lower_ribcage", "upper_ribcage_shoulder") for x in "xyz"} if u != 0: deps.update(f"stations.{name}.rL" for name in ("lower_ribcage", "upper_ribcage_shoulder")) if q > 0: deps.update(f"stations.{name}.rA" for name in ("lower_ribcage", "upper_ribcage_shoulder")) if q < 0: deps.update(f"stations.{name}.rP" for name in ("lower_ribcage", "upper_ribcage_shoulder")) else: - selector = {2: "waist_abdomen", 3: "upper_abdomen", 4: "lower_ribcage"}[j]; C, rl, ra, rp = _station(prepared, selector); point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(selector, u, q) + selector = {2: "waist_abdomen", 3: "upper_abdomen", 4: "lower_ribcage"}[j]; row = _station_record(geometry, selector); C, rl, ra, rp = row["C"], row["rL"], row["rA"], row["rP"]; point = _e(C, u, q, rl, ra, rp, 2.6); deps = _component_dependencies(selector, u, q) formula = "formula.axial.station" params = {"i": i, "j": j, "k": k, "u": u, "q": q, "d": float(d), "n": 2.6, "station_selector": selector} return formula, tuple(sorted(deps)), tuple(point), params -def _formula_candidate_records_admitted(prepared): - return tuple({"control_id": control, "lattice_key": list(COORDINATE_BY_CONTROL[control]), "formula_id": formula, "construction_owner": CONTROL_OWNERS[control], "index_parameters": params, "geometry_dependencies": list(deps), "coordinate": [float(x) for x in point]} for control in CONTROL_IDS for formula, deps, point, params in (_formula_for_control(prepared, control),)) -def formula_candidate_records(prepared): - prepared_projection.validate_prepared(prepared); return _formula_candidate_records_admitted(prepared) +def _formula_candidate_records_numeric(geometry): + return tuple({"control_id": control, "lattice_key": list(COORDINATE_BY_CONTROL[control]), "formula_id": formula, "construction_owner": CONTROL_OWNERS[control], "index_parameters": params, "geometry_dependencies": list(deps), "coordinate": [float(x) for x in point]} for control in CONTROL_IDS for formula, deps, point, params in (_formula_for_control(geometry, control),)) +def formula_candidate_records(geometry): + validate_geometry_components(geometry); return _formula_candidate_records_numeric(geometry) def _record(level, vertex_id, contributors, formulas): controls = tuple(sorted(set(contributors), key=lambda x: int(x[1:]))); deps = tuple(sorted({d for c in controls for d in formulas[int(c[1:])]["geometry_dependencies"]})) contributing = {domain for c in controls for domain in (JUNCTION_INFO[CONTROL_OWNERS[c]][0] if CONTROL_OWNERS[c].startswith("junction.") else (CONTROL_OWNERS[c],))}; domains = tuple(domain for domain in DOMAINS if domain in contributing) @@ -414,14 +427,12 @@ def propagate_junction_tags(mesh, junction): def _half_tag(left, right): numerator = left[0] * right[1] + right[0] * left[1]; denominator = 2 * left[1] * right[1]; common = gcd(abs(numerator), denominator) return numerator // common, denominator // common -def _build_cage_admitted(prepared): - records = _formula_candidate_records_admitted(prepared); quads = tuple(tuple(int(c[1:]) for c in f[2]) for f in FACE_RECORDS) +def build_cage(geometry): + validate_geometry_components(geometry); records = _formula_candidate_records_numeric(geometry); quads = tuple(tuple(int(c[1:]) for c in f[2]) for f in FACE_RECORDS) loops = tuple((name, tuple(int(c[1:]) for c in info[2])) for name, info in PORT_INFO.items()) triangles = tuple(t for f in quads for t in ((f[0], f[1], f[2]), (f[0], f[2], f[3]))) mesh = Mesh(tuple(tuple(r["coordinate"]) for r in records), quads, CONTROL_IDS, tuple(r["formula_id"] for r in records), tuple(tuple(r["geometry_dependencies"]) for r in records), loops, triangles, 0, tuple(f[0] for f in FACE_RECORDS), tuple(f[1] for f in FACE_RECORDS), records, tuple(_record(0, c, (c,), records) for c in CONTROL_IDS), tuple((i,) for i in range(120))) - _validate_level_structure_admitted(mesh, prepared); return mesh -def build_cage(prepared): - prepared_projection.validate_prepared(prepared); return _build_cage_admitted(prepared) + _validate_level_structure_numeric(mesh, geometry); return mesh def _subdivide_once(mesh, level, points=None): if type(level) is not int or level not in (1, 2) or mesh.level != level - 1: raise ValueError("subdivision level must follow level 0,1 order") inc = subdivision_incidence(mesh); uses, edges, boundary, faces, incident_edges = _incidence(mesh); points = mesh.vertices if points is None else points @@ -452,68 +463,11 @@ def subdivide(mesh, level=1): for target in range(mesh.level + 1, level + 1): parent = result; result = _subdivide_once(parent, target); _validate_derived_level(result, parent) return result -def _evaluate_cage(cage, prepared): - level1 = subdivide(cage, 1); level2 = subdivide(level1, 2); evaluation = SurfaceEvaluation(cage, (level1, level2)); validate_evaluation(evaluation, prepared); return evaluation -def evaluate(prepared, levels=2): +def _evaluate_cage(cage, geometry): + level1 = subdivide(cage, 1); level2 = subdivide(level1, 2); evaluation = SurfaceEvaluation(cage, (level1, level2)); validate_evaluation(evaluation, geometry); return evaluation +def evaluate(geometry, levels=2): if type(levels) is not int or levels != 2: raise ValueError("the frozen neutral surface evaluates exactly two levels") - return _evaluate_cage(build_cage(prepared), prepared) -_MUST_AFFECT = ( - ("left.r_y", "hips.left.r_y"), ("right.r_y", "hips.right.r_y"), ("lower_pelvis.L_y", "stations.lower_pelvis.C.y"), ("lower_pelvis.C_z", "stations.lower_pelvis.C.z"), ("left.r_x", "hips.left.r_x"), ("right.r_x", "hips.right.r_x"), - ("lower_pelvis.R_x", "stations.lower_pelvis.rL"), ("left.r_z", "hips.left.r_z"), ("right.r_z", "hips.right.r_z"), ("lower_pelvis.R_f", "stations.lower_pelvis.rA"), ("lower_pelvis.R_b", "stations.lower_pelvis.rP"), - ("left.thigh_start_x", "hips.left.P_s.x"), ("left.thigh_start_y", "hips.left.P_s.y"), ("left.thigh_start_z", "hips.left.P_s.z"), ("right.thigh_start_x", "hips.right.P_s.x"), ("right.thigh_start_y", "hips.right.P_s.y"), ("right.thigh_start_z", "hips.right.P_s.z"), - ("neck_collar.C_y", "stations.neck_collar.C.y"), ("neck_collar.rL", "stations.neck_collar.rL"), ("neck_upper.C_y", "stations.neck_upper.C.y"), ("neck_upper.rL", "stations.neck_upper.rL"), - ("left.axilla_x", "shoulders.left.axilla.x"), ("left.axilla_y", "shoulders.left.axilla.y"), ("right.axilla_x", "shoulders.right.axilla.x"), ("right.axilla_y", "shoulders.right.axilla.y"), ("left.peak_y", "shoulders.left.peak.y"), ("right.peak_y", "shoulders.right.peak.y"), - ("left.start_lateral", "shoulders.left.start_lateral"), ("right.start_lateral", "shoulders.right.start_lateral"), ("left.start_up", "shoulders.left.start_up"), ("right.start_up", "shoulders.right.start_up"), - ("left.shoulder_depth", "shoulders.left.shoulder_depth"), ("right.shoulder_depth", "shoulders.right.shoulder_depth")) -MUST_AFFECT_PARAMETER_IDS = tuple(parameter for parameter, _ in _MUST_AFFECT) -MUST_AFFECT_COMPONENTS = dict(_MUST_AFFECT) -_MUST_AFFECT_PATHS = {parameter: tuple("xyz".index(axis) if len(axis) == 1 and axis in "xyz" else axis for axis in component.split(".")) for parameter, component in _MUST_AFFECT} -_PERTURBATION_DELTA = float.fromhex("0x1.47ae147ae147bp-7") -PERTURBATION_DELTA_M = _PERTURBATION_DELTA -def _path_get(value, path): - for key in path: value = value[key] - return value -def _path_set(value, path, replacement): _path_get(value, path[:-1])[path[-1]] = replacement -def _admit_surface_prepared(prepared): - try: - prepared_projection.validate_prepared(prepared); return prepared - except prepared_projection.PreparedProjectionError: - canonical = prepared_projection.prepare_standard_neutral(); canonical_bytes = prepared_projection.canonical_json_bytes(canonical); matches = 0 - for path in _MUST_AFFECT_PATHS.values(): - try: - baseline, candidate = _path_get(canonical, path), _path_get(prepared, path) - if type(candidate) is not float or candidate != float(baseline + _PERTURBATION_DELTA): continue - restored = copy.deepcopy(prepared); _path_set(restored, path, baseline); matches += prepared_projection.canonical_json_bytes(restored) == canonical_bytes - except (KeyError, IndexError, TypeError, ValueError, OverflowError): continue - if matches != 1: raise - return prepared -def _surface_prepared_candidates(): - canonical = prepared_projection.prepare_standard_neutral(); yield canonical - for path in _MUST_AFFECT_PATHS.values(): - candidate = copy.deepcopy(canonical); baseline = _path_get(candidate, path); _path_set(candidate, path, float(baseline + _PERTURBATION_DELTA)); yield candidate -def _infer_surface_prepared(cage): - if type(cage) is not Mesh: raise ValueError("prepared inference requires an L0 cage") - matches = [] - for candidate in _surface_prepared_candidates(): - try: _validate_cage_lineage(cage, candidate) - except (ValueError, TypeError, IndexError): continue - matches.append(candidate) - if len(matches) != 1: raise ValueError("L0 cage does not identify exactly one frozen prepared input") - return matches[0] -def perturb_prepared(prepared, parameter_id): - if type(parameter_id) is not str or parameter_id not in _MUST_AFFECT_PATHS: raise ValueError("parameter_id is not one of the 33 frozen must-affect parameters") - prepared_projection.validate_prepared(prepared); path = _MUST_AFFECT_PATHS[parameter_id]; component = MUST_AFFECT_COMPONENTS[parameter_id]; baseline = _path_get(prepared, path) - if type(baseline) is not float or not isfinite(baseline): raise ValueError(f"{component} is not binary64") - candidate = copy.deepcopy(prepared); changed = float(baseline + _PERTURBATION_DELTA); _path_set(candidate, path, changed) - if _path_get(candidate, path) != changed: raise ValueError("perturbation did not change its selected component") - restored = copy.deepcopy(candidate); _path_set(restored, path, baseline) - if prepared_projection.canonical_json_bytes(restored) != prepared_projection.canonical_json_bytes(prepared): raise ValueError("perturbation changed more than its selected component") - return candidate -def build_perturbed_cage(prepared, parameter_id): return _build_cage_admitted(perturb_prepared(prepared, parameter_id)) -def evaluate_perturbation(prepared, parameter_id, levels=2): - if type(levels) is not int or levels != 2: raise ValueError("the frozen surface evaluates exactly two levels") - candidate = perturb_prepared(prepared, parameter_id); return _evaluate_cage(_build_cage_admitted(candidate), candidate) -evaluate_perturbed = evaluate_perturbation + return _evaluate_cage(build_cage(geometry), geometry) @dataclass(frozen=True) class _Dual: value: float @@ -529,34 +483,25 @@ def __rtruediv__(self, other): return _Dual(_value(other) / self.value, (_deriva def __abs__(self): return _Dual(abs(self.value), self.derivative if self.value > 0 else -self.derivative if self.value < 0 else 0.0) def _value(x): return x.value if isinstance(x, _Dual) else x def _derivative(x): return x.derivative if isinstance(x, _Dual) else Fraction(0) -def _analytic_components(prepared): - source = {record["prepared_component"] for record in prepared_projection.source_binding_records()}; formula = {dependency for control in CONTROL_IDS for dependency in _formula_for_control(prepared, control)[1]} - if not formula <= source: raise ValueError("formula authority names a component outside frozen source bindings") +def _analytic_components(geometry): + formula = {dependency for control in CONTROL_IDS for dependency in _formula_for_control(geometry, control)[1]} + if not formula <= set(GEOMETRY_COMPONENT_IDS): raise ValueError("formula authority names a component outside the numeric carrier") return formula -def analytic_control_derivatives(prepared, component): - _admit_surface_prepared(prepared) - if component not in _analytic_components(prepared): raise ValueError(f"unknown prepared component: {component}") - dual = copy.deepcopy(prepared); parts = component.split("/") if "/" in component else component.split("."); leaf = parts[-1] - if leaf in "xyz" and len(parts) >= 2: - target = dual - for part in parts[:-2]: target = target[part] - vector = list(target[parts[-2]]); vector["xyz".index(leaf)] = _Dual(vector["xyz".index(leaf)], Fraction(1)); target[parts[-2]] = tuple(vector) - else: - target = dual - for part in parts[:-1]: target = target[part] - target[leaf] = _Dual(target[leaf], Fraction(1)) +def analytic_control_derivatives(geometry, component): + validate_geometry_components(geometry) + if component not in _analytic_components(geometry): raise ValueError(f"unknown geometry component: {component}") + dual = list(geometry.values); index = _GEOMETRY_INDEX[component]; dual[index] = _Dual(dual[index], Fraction(1)); dual = tuple(dual) result = [] for control in CONTROL_IDS: _, _, point, _ = _formula_for_control(dual, control); result.append(tuple(_derivative(x) for x in point)) return tuple(result) -def _propagate_values(mesh, values, level): return _subdivide_once(mesh, level, values).vertices def propagate_derivative(mesh, derivatives, level=2): if len(derivatives) != len(mesh.vertices): raise ValueError("derivative vector count mismatch") result, current = tuple(tuple(_rational(x) for x in p) for p in derivatives), mesh - for target in range(mesh.level + 1, level + 1): result = _propagate_values(current, result, target); current = subdivide(current, target) + for target in range(mesh.level + 1, level + 1): result = _subdivide_once(current, target, result).vertices; current = subdivide(current, target) return result -def predicted_support(prepared, component): cage = build_cage(prepared); derivative = analytic_control_derivatives(prepared, component); level2 = propagate_derivative(cage, derivative, 2); return tuple(i for i, point in enumerate(level2) if any(value != 0.0 for value in point)) +def predicted_support(geometry, component): cage = build_cage(geometry); derivative = analytic_control_derivatives(geometry, component); level2 = propagate_derivative(cage, derivative, 2); return tuple(i for i, point in enumerate(level2) if any(value != 0.0 for value in point)) analytic_derivative_support = predicted_support causal_support = predicted_support validate_topology, build_surface = validate_catalogs, build_cage -__all__ = ["CELL_CATALOG", "CONTROL_BY_COORDINATE", "CONTROL_DOMAIN_INCIDENTS", "CONTROL_IDS", "CONTROL_JUNCTION_INCIDENTS", "CONTROL_OWNERS", "COORDINATE_BY_CONTROL", "DOMAINS", "EDGE_RECORDS", "FACE_CATALOG", "FACE_RECORDS", "FORMULAS", "JUNCTIONS", "JUNCTION_INFO", "JUNCTION_TRACES", "MUST_AFFECT_COMPONENTS", "MUST_AFFECT_PARAMETER_IDS", "PERTURBATION_DELTA_M", "PORTS", "PORT_INFO", "SPECIAL_CASE_IDS", "Mesh", "SurfaceEvaluation", "analytic_control_derivatives", "analytic_derivative_support", "build_cage", "build_perturbed_cage", "causal_support", "evaluate", "evaluate_perturbation", "evaluate_perturbed", "formula_candidate_records", "junction_trace_inputs", "level_topology", "perturb_prepared", "predicted_support", "propagate_derivative", "propagate_junction_tags", "propagate_port_loops", "subdivide", "subdivision_incidence", "symbolic_topology", "topology_incidence", "validate_catalogs", "validate_evaluation", "validate_level_structure"] +__all__ = ["CELL_CATALOG", "CONTROL_BY_COORDINATE", "CONTROL_DOMAIN_INCIDENTS", "CONTROL_IDS", "CONTROL_JUNCTION_INCIDENTS", "CONTROL_OWNERS", "COORDINATE_BY_CONTROL", "DOMAINS", "EDGE_RECORDS", "FACE_CATALOG", "FACE_RECORDS", "FORMULAS", "GEOMETRY_COMPONENT_IDS", "GeometryComponents", "JUNCTIONS", "JUNCTION_INFO", "JUNCTION_TRACES", "PORTS", "PORT_INFO", "SPECIAL_CASE_IDS", "Mesh", "SurfaceEvaluation", "analytic_control_derivatives", "analytic_derivative_support", "build_cage", "causal_support", "evaluate", "formula_candidate_records", "geometry_component", "junction_trace_inputs", "level_topology", "predicted_support", "propagate_derivative", "propagate_junction_tags", "propagate_port_loops", "subdivide", "subdivision_incidence", "symbolic_topology", "topology_incidence", "validate_catalogs", "validate_evaluation", "validate_geometry_components", "validate_level_structure"] diff --git a/experiments/owned-root-assembly-successor/prepared_projection.py b/experiments/owned-root-assembly-successor/prepared_projection.py index 54bba0e..5a60180 100644 --- a/experiments/owned-root-assembly-successor/prepared_projection.py +++ b/experiments/owned-root-assembly-successor/prepared_projection.py @@ -1,13 +1,15 @@ """Closed section-2 source admission and standard-neutral projection.""" +import copy import json import math from functools import wraps from pathlib import Path from types import MappingProxyType - import artifact_serialization as artifacts - - +try: + from owned_root_surface import GEOMETRY_COMPONENT_IDS as _GEOMETRY_COMPONENT_IDS, GeometryComponents +except ImportError: # pragma: no cover + from .owned_root_surface import GEOMETRY_COMPONENT_IDS as _GEOMETRY_COMPONENT_IDS, GeometryComponents class PreparedProjectionError(ValueError): """A source, profile, or prepared-input boundary failed closed.""" ROOT = Path(__file__).resolve().parents[2] @@ -57,14 +59,10 @@ class PreparedProjectionError(ValueError): _SHOULDER_SPEC.update({field: ("vector", 3) for field in ("axilla", "peak", "arm_origin")}) _HIP_SPEC = {"P_s": ("vector", 3), **{field: _PB64 for field, _ in HIP_DIMS}} _PREPARED_SPEC = { - "schema": str, "contract": _IDENTITY_SPEC, "source": _IDENTITY_SPEC, - "profile_selection": {"profile_id": str, "profile_table_path": str, "profile_table_sha256": str, - "dimensions": {key: _B64 for key in PROFILE_DIMENSION_KEYS}}, - "basis": {key: str for key, _ in _BASIS_ITEMS}, - "parts": ("list", len(PARTS), _PART_SPEC), - "stations": {name: _STATION_SPEC for name, _, _ in STATIONS}, - "shoulders": {side: _SHOULDER_SPEC for side in ("left", "right")}, - "hips": {side: _HIP_SPEC for side in ("left", "right")}, + "schema": str, "contract": _IDENTITY_SPEC, "source": _IDENTITY_SPEC, "profile_selection": {"profile_id": str, "profile_table_path": str, "profile_table_sha256": str, + "dimensions": {key: _B64 for key in PROFILE_DIMENSION_KEYS}}, + "basis": {key: str for key, _ in _BASIS_ITEMS}, "parts": ("list", len(PARTS), _PART_SPEC), "stations": {name: _STATION_SPEC for name, _, _ in STATIONS}, + "shoulders": {side: _SHOULDER_SPEC for side in ("left", "right")}, "hips": {side: _HIP_SPEC for side in ("left", "right")}, "provenance": {"source_files": ("list", 2, {"path": str, "sha256": str, "bytes": int})}, } def _freeze(value): @@ -185,16 +183,13 @@ def _fixed_scalars(value, items, where): def _validate_source_document(source, _semantic=_COMMITMENTS["semantic"]): _keys(source, {"contract", "source", "basis", "profiles", "body", "extensions"}, "source") _fixed_scalars(source["contract"], _semantic["source_contract"], "source.contract") - identity = _obj(source["source"], "source.source") - _keys(identity, {"document", "namespace", "dependencies"}, "source.source") + identity = _obj(source["source"], "source.source"); _keys(identity, {"document", "namespace", "dependencies"}, "source.source") for key, expected in _semantic["source_identity"]: _literal(identity[key], expected, f"source.source.{key}") _need(type(identity["dependencies"]) is list and not identity["dependencies"], "source.dependencies", "not empty") - _fixed_scalars(source["basis"], _semantic["basis"], "source.basis") - _fixed_scalars(source["profiles"], (("semantic_numeric", "ck.numeric-frame.r1"),), "source.profiles") + _fixed_scalars(source["basis"], _semantic["basis"], "source.basis"); _fixed_scalars(source["profiles"], (("semantic_numeric", "ck.numeric-frame.r1"),), "source.profiles") _need(type(source["extensions"]) is list and not source["extensions"], "source.extensions", "not empty") - body = _obj(source["body"], "source.body") - _keys(body, _semantic["body_counts"], "source.body") + body = _obj(source["body"], "source.body"); _keys(body, _semantic["body_counts"], "source.body") valid_counts = all(type(body[name]) is list and len(body[name]) == count for name, count in _semantic["body_counts"].items()) _need(valid_counts, "source.body", "wrong required record counts") parts = {} @@ -204,16 +199,14 @@ def _validate_source_document(source, _semantic=_COMMITMENTS["semantic"]): _source_transform(row["placement"], f"{where}.placement") _obj(row["containment"], f"{where}.containment") parts[address] = row, index - dimensions, _ = _validate_selector_rows(body["dimensions"], "dimensions"); frames, _ = _validate_selector_rows(body["frames"], "frames") - landmarks, references = _validate_selector_rows(body["landmarks"], "landmarks") + dimensions, _ = _validate_selector_rows(body["dimensions"], "dimensions"); frames, _ = _validate_selector_rows(body["frames"], "frames"); landmarks, references = _validate_selector_rows(body["landmarks"], "landmarks") _need(references <= set(frames), "source.body.landmarks", "missing referenced frame") return parts, frames, landmarks, dimensions def _admit_source_bytes(raw, _admission=_COMMITMENTS["admission"]): source, digest = _decode_source_json(raw, "source") _need(len(raw) == _admission["sizes"][2] and digest == _admission["hashes"][1], "source", "source identity mismatch") parts, frames, landmarks, dimensions = _validate_source_document(source) - return {"parts": parts, "frames": frames, "landmarks": landmarks, - "dimensions": dimensions, "bytes": raw, "sha256": digest} + return {"parts": parts, "frames": frames, "landmarks": landmarks, "dimensions": dimensions, "bytes": raw, "sha256": digest} def _validate_profile_table(table, _c=_COMMITMENTS): admission, semantic = _c["admission"], _c["semantic"] _keys(table, {"base_source", "canonicalization", "format", "profiles", "transform"}, "profile table") @@ -236,19 +229,15 @@ def _admit_profile_bytes(raw, _admission=_COMMITMENTS["admission"]): def _verify_contract(path=_PATHS[0], _c=_COMMITMENTS): _admission, operations = _c["admission"], _c["operations"] paths, hashes, sizes = _admission["paths"], _admission["hashes"], _admission["sizes"] - contract = _fixed_path(path, paths[0], "contract path") - sidecar = _fixed_path(paths[1], paths[1], "contract sidecar path") + contract = _fixed_path(path, paths[0], "contract path"); sidecar = _fixed_path(paths[1], paths[1], "contract sidecar path") contract_raw, sidecar_raw = _read(contract, "contract"), _read(sidecar, "contract sidecar") contract_digest = operations["sha256_bytes"](contract_raw) _need(len(contract_raw) == sizes[0] and contract_digest == hashes[0], "contract", "identity mismatch") _need(len(sidecar_raw) == sizes[1] and sidecar_raw == _admission["sidecar"], "contract sidecar", "identity mismatch") return contract_digest def _fixed_inputs(source_path, contract_path, profile_path, _admission=_COMMITMENTS["admission"]): - paths = _admission["paths"] - contract_digest = _verify_contract(contract_path) - source = _fixed_path(source_path, paths[2], "source path"); profile = _fixed_path(profile_path, paths[3], "profile table path") - admission = _admit_source_bytes(_read(source, "source")); selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")) - return contract_digest, admission, selected, raw, digest + paths = _admission["paths"]; contract_digest = _verify_contract(contract_path) + source = _fixed_path(source_path, paths[2], "source path"); profile = _fixed_path(profile_path, paths[3], "profile table path"); admission = _admit_source_bytes(_read(source, "source")); selected, raw, digest = _admit_profile_bytes(_read(profile, "profile table")); return contract_digest, admission, selected, raw, digest def _select(rows, owner, role, name): match = rows.get((owner, role)) _need(match is not None, f"body.{name}.{role}", "missing required record") @@ -291,7 +280,6 @@ def _walk(value, spec, where, *, wire, _c=_COMMITMENTS): if wire: value[index] = converted return value def _validate_prepared_structure(prepared, *, wire=False, _spec=_COMMITMENTS["prepared_spec"]): return _walk(prepared, _spec, "prepared", wire=wire) -def _validate_prepared_shape(prepared): return _validate_prepared_structure(prepared) def _chains(): pelvis, torso, neck = _a("pelvis"), _a("torso"), _a("neck") result = {pelvis: (pelvis,), torso: (pelvis, torso), neck: (pelvis, torso, neck)} @@ -329,17 +317,16 @@ def _build_prepared(admission, profile, profile_raw, profile_digest, _c=_COMMITM "shoulders": sides["shoulders"], "hips": sides["hips"], "provenance": {"source_files": _source_files(admission["sha256"], len(admission["bytes"]), profile_digest, len(profile_raw))}, } - return _validate_prepared_shape(prepared) + return _validate_prepared_structure(prepared) def _prepared_apis(_c): fixed, operations = _c["admission"], _c["operations"] - shape, structure, build, inputs, need, attempt = _validate_prepared_shape, _validate_prepared_structure, _build_prepared, _fixed_inputs, _need, _attempt + shape, structure, build, inputs, need, attempt = _validate_prepared_structure, _validate_prepared_structure, _build_prepared, _fixed_inputs, _need, _attempt expected_bytes_cache = {} @_public_admission def validate_prepared(prepared): """Admit only the projection freshly derived from the fixed files.""" value = shape(prepared) - contract_digest, admission, profile, profile_raw, profile_digest = inputs( - fixed["paths"][2], fixed["paths"][0], fixed["paths"][3]) + contract_digest, admission, profile, profile_raw, profile_digest = inputs(fixed["paths"][2], fixed["paths"][0], fixed["paths"][3]) digest_triple = (contract_digest, admission["sha256"], profile_digest) expected_bytes = expected_bytes_cache.get(digest_triple) if expected_bytes is None: @@ -392,8 +379,7 @@ def _validate_binding_records(records, _c=_COMMITMENTS): _runtime_address(address, f"{where}.source_addresses[{address_index}]") for pointer_index, pointer in enumerate(pointers): _text(pointer, f"{where}.source_pointers[{pointer_index}]") - _need(len(set(components)) == 92 and components == sorted(components, key=str.encode), - "source bindings", "wrong component order or uniqueness") + _need(len(set(components)) == 92 and components == sorted(components, key=str.encode), "source bindings", "wrong component order or uniqueness") hashes, operations = _c["admission"]["binding_hashes"], _c["operations"] _need(operations["sha256_bytes"](operations["json_bytes"](components)) == hashes[0], "source bindings", "component universe mismatch") _need(operations["sha256_bytes"](operations["json_bytes"](records)) == hashes[1], "source bindings", "mapping mismatch") @@ -402,8 +388,7 @@ def _append_sum(bindings, admission, parts, chains, component, owner, landmark_r chain, landmark_index = chains[owner], None if landmark_role is not None: landmark_index = _select(admission["landmarks"], owner, landmark_role, "landmarks")[1] - derivation = ("source.world-landmark-axis-sum.v1" if landmark_role - else "source.world-placement-axis-sum.v1") + derivation = "source.world-landmark-axis-sum.v1" if landmark_role else "source.world-placement-axis-sum.v1" for axis, name in enumerate(_axes): pointers = [_pointer("part", parts[item][1], axis) for item in chain] if landmark_index is not None: @@ -414,8 +399,7 @@ def _append_group(bindings, admission, parts, chains, prefix, owner, sums, dimen _append_sum(bindings, admission, parts, chains, f"{prefix}.{field}", owner, landmark) for field, role in dimensions: _, index = _dimension(admission, owner, role) - bindings.append(_bind(f"{prefix}.{field}", "source.dimension-value.v1", - (owner,), (_pointer("dimension", index),))) + bindings.append(_bind(f"{prefix}.{field}", "source.dimension-value.v1", (owner,), (_pointer("dimension", index),))) def _binding_api(_c): fixed, semantic = _c["admission"], _c["semantic"] inputs, chains_for_parts, address, suffixes, append, validate = _fixed_inputs, _chains, _a, _station_suffixes, _append_group, _validate_binding_records @@ -434,15 +418,83 @@ def source_binding_records(source_path=fixed["paths"][2], *, contract_path=fixed return source_binding_records source_binding_records = _binding_api(_COMMITMENTS) build_source_binding_records = source_binding_records +def _geometry_value(prepared, component): + path = component.split("."); value = prepared + for field in path[:-1]: value = value[field] + return value["xyz".index(path[-1])] if path[-1] in "xyz" and len(path[-1]) == 1 else value[path[-1]] +_MUST_AFFECT = ( + ("left.r_y", "hips.left.r_y"), ("right.r_y", "hips.right.r_y"), + ("lower_pelvis.L_y", "stations.lower_pelvis.C.y"), + ("lower_pelvis.C_z", "stations.lower_pelvis.C.z"), + ("left.r_x", "hips.left.r_x"), ("right.r_x", "hips.right.r_x"), + ("lower_pelvis.R_x", "stations.lower_pelvis.rL"), + ("left.r_z", "hips.left.r_z"), ("right.r_z", "hips.right.r_z"), + ("lower_pelvis.R_f", "stations.lower_pelvis.rA"), + ("lower_pelvis.R_b", "stations.lower_pelvis.rP"), + ("left.thigh_start_x", "hips.left.P_s.x"), + ("left.thigh_start_y", "hips.left.P_s.y"), + ("left.thigh_start_z", "hips.left.P_s.z"), + ("right.thigh_start_x", "hips.right.P_s.x"), + ("right.thigh_start_y", "hips.right.P_s.y"), + ("right.thigh_start_z", "hips.right.P_s.z"), + ("neck_collar.C_y", "stations.neck_collar.C.y"), + ("neck_collar.rL", "stations.neck_collar.rL"), + ("neck_upper.C_y", "stations.neck_upper.C.y"), + ("neck_upper.rL", "stations.neck_upper.rL"), + ("left.axilla_x", "shoulders.left.axilla.x"), + ("left.axilla_y", "shoulders.left.axilla.y"), + ("right.axilla_x", "shoulders.right.axilla.x"), + ("right.axilla_y", "shoulders.right.axilla.y"), + ("left.peak_y", "shoulders.left.peak.y"), + ("right.peak_y", "shoulders.right.peak.y"), + ("left.start_lateral", "shoulders.left.start_lateral"), + ("right.start_lateral", "shoulders.right.start_lateral"), + ("left.start_up", "shoulders.left.start_up"), + ("right.start_up", "shoulders.right.start_up"), + ("left.shoulder_depth", "shoulders.left.shoulder_depth"), + ("right.shoulder_depth", "shoulders.right.shoulder_depth"), +) +MUST_AFFECT_PARAMETER_IDS = tuple(parameter for parameter, _ in _MUST_AFFECT) +MUST_AFFECT_COMPONENTS = MappingProxyType(dict(_MUST_AFFECT)) +_PERTURBATION_DELTA = float.fromhex("0x1.47ae147ae147bp-7") +PERTURBATION_DELTA_M = _PERTURBATION_DELTA +def _selector_path(component): + path = component.split(".") + return tuple((*path[:-1], "xyz".index(path[-1]))) if path[-1] in "xyz" and len(path[-1]) == 1 else tuple(path) +def _path_get(value, path): + for field in path: value = value[field] + return value +def _geometry_apis(_ids=_GEOMETRY_COMPONENT_IDS, _carrier=GeometryComponents, + _validate=validate_prepared, _bindings=source_binding_records, + _read=_geometry_value, _required=_need): + ids, carrier, validate, bindings, read, required = tuple(_ids), _carrier, _validate, _bindings, _read, _required + selectors = tuple((parameter, component, _selector_path(component)) for parameter, component in _MUST_AFFECT) + delta = _PERTURBATION_DELTA + def project_value(value): + records = bindings() + required(tuple(record["prepared_component"] for record in records) == ids, + "geometry projection", "component universe differs from source bindings") + return carrier(tuple(read(value, component) for component in ids)) + @_public_admission + def project_geometry(prepared): + """Convert the admitted neutral prepared object to identity-free numbers.""" + return project_value(validate(prepared)) + @_public_admission + def project_perturbed_geometry(prepared, parameter_id): + """Admit one literal prepared-input perturbation, then project it.""" + value = validate(prepared) + if type(parameter_id) is not str: raise PreparedProjectionError("parameter_id is not one frozen selector") + matches = tuple((component, path) for parameter, component, path in selectors if parameter == parameter_id) + if len(matches) != 1: raise PreparedProjectionError("parameter_id does not resolve exactly one frozen selector") + component, path = matches[0]; candidate = copy.deepcopy(value); baseline = _path_get(value, path) + if type(baseline) is not float or not math.isfinite(baseline): raise PreparedProjectionError(f"{component} is not binary64") + changed = float(baseline + delta); _path_get(candidate, path[:-1])[path[-1]] = changed + if _path_get(candidate, path) != changed: raise PreparedProjectionError("perturbation did not change its selected component") + restored = copy.deepcopy(candidate); _path_get(restored, path[:-1])[path[-1]] = baseline + if _JSON_BYTES(restored) != _JSON_BYTES(value): raise PreparedProjectionError("perturbation changed more than its selected component") + return project_value(candidate) + return project_geometry, project_perturbed_geometry +project_geometry, project_perturbed_geometry = _geometry_apis() canonical_json_bytes = _JSON_BYTES -def _sha_api(operations): - def canonical_json_sha256(value): return operations["sha256_bytes"](operations["json_bytes"](value)) - return canonical_json_sha256 -canonical_json_sha256 = _sha_api(_COMMITMENTS["operations"]) -__all__ = [ - "EXPECTED_CONTRACT_SHA256", "EXPECTED_PROFILE_TABLE_SHA256", - "EXPECTED_SOURCE_SHA256", "PreparedProjectionError", - "admit_prepared_bytes", "build_source_binding_records", "canonical_json_bytes", - "canonical_json_sha256", "normalize_source_address", - "prepare_standard_neutral", "source_binding_records", "validate_prepared", -] +def canonical_json_sha256(value): return _COMMITMENTS["operations"]["sha256_bytes"](_COMMITMENTS["operations"]["json_bytes"](value)) +__all__ = ["EXPECTED_CONTRACT_SHA256", "EXPECTED_PROFILE_TABLE_SHA256", "EXPECTED_SOURCE_SHA256", "GeometryComponents", "PreparedProjectionError", "admit_prepared_bytes", "build_source_binding_records", "canonical_json_bytes", "canonical_json_sha256", "normalize_source_address", "MUST_AFFECT_COMPONENTS", "MUST_AFFECT_PARAMETER_IDS", "PERTURBATION_DELTA_M", "prepare_standard_neutral", "project_geometry", "project_perturbed_geometry", "source_binding_records", "validate_prepared"] diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py index d692c72..6cd1d3a 100644 --- a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -1,5 +1,6 @@ from __future__ import annotations +import inspect import copy import hashlib import inspect @@ -39,6 +40,16 @@ def identity_fixture(): class FrozenInventoryTests(unittest.TestCase): + def test_causality_perturbation_crosses_prepared_boundary(self): + source = inspect.getsource(builder._causality) + self.assertIn("project_perturbed_geometry", source) + self.assertNotIn("surface.evaluate_perturbation", source) + self.assertNotIn("surface.perturb_geometry", source) + + def test_boundary_inventory_uses_each_inner_loop_successor(self): + source = inspect.getsource(builder._ownership_counts) + self.assertIn("values[(slot + 1) % len(values)]", source) + def test_contract_identity_and_private_roles_are_closed(self): self.assertEqual(len(builder.PARAMETER_IDS), 33) self.assertEqual(len(builder.SURFACE_ROLES), 3) @@ -158,8 +169,9 @@ def test_mesh_adapters_use_independent_topology_and_incident_domain_traces(self) import prepared_projection as prepared_api import chart_lineage as chart_api prepared = prepared_api.prepare_standard_neutral() - evaluation = surface.evaluate(prepared) - formulas = tuple(surface.formula_candidate_records(prepared)) + geometry_input = prepared_api.project_geometry(prepared) + evaluation = surface.evaluate(geometry_input) + formulas = tuple(surface.formula_candidate_records(geometry_input)) chart_summary = chart_api.build_chart_summary(evaluation, formulas) base_faces = tuple(tuple(int(control[1:]) for control in row[2]) for row in surface.FACE_RECORDS) @@ -175,7 +187,7 @@ def test_mesh_adapters_use_independent_topology_and_incident_domain_traces(self) reference = surface.propagate_junction_tags(evaluation, junction)[level] self.assertEqual(row["expected_domain_vertex_tags"], (reference, reference)) ownership = builder._ownership_counts(surface, evaluation, chart_api, mesh_api, - prepared, formulas, chart_summary, level) + geometry_input, formulas, chart_summary, level) self.assertEqual((ownership["unowned_elements"], ownership["overowned_elements"]), (0, 0)) for junction in surface.JUNCTIONS: @@ -197,8 +209,9 @@ def test_junction_metrics_reject_builder_observation_mismatch(self): import prepared_projection as prepared_api import chart_lineage as chart_api prepared = prepared_api.prepare_standard_neutral() - evaluation = surface.evaluate(prepared) - formulas = tuple(surface.formula_candidate_records(prepared)) + geometry_input = prepared_api.project_geometry(prepared) + evaluation = surface.evaluate(geometry_input) + formulas = tuple(surface.formula_candidate_records(geometry_input)) chart_summary = chart_api.build_chart_summary(evaluation, formulas) level, junction = 1, surface.JUNCTIONS[0] domains = surface.JUNCTION_INFO[junction][0] diff --git a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py index 93793ad..ba2e92e 100644 --- a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py @@ -14,13 +14,10 @@ import chart_lineage as chart import owned_root_surface as surface import prepared_projection - def prepared(): return prepared_projection.prepare_standard_neutral( REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" ) - - def independent_charts(evaluation): """Build valid chart ancestry while anatomy remains the unit under test.""" return chart.build_chart_summary(evaluation, evaluation.cage.formula_records) @@ -59,13 +56,13 @@ class SurfaceTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.prepared = prepared() - cls.evaluation = surface.evaluate(cls.prepared) + cls.geometry = prepared_projection.project_geometry(cls.prepared) + cls.evaluation = surface.evaluate(cls.geometry) - def test_formula_candidates_use_prepared_boundary_and_exact_dispatch(self): - with patch.object(surface.prepared_projection, "validate_prepared", - wraps=surface.prepared_projection.validate_prepared) as admitted: - cage = surface.build_cage(self.prepared) - admitted.assert_called_once_with(self.prepared) + def test_formula_candidates_use_numeric_boundary_and_exact_dispatch(self): + with patch.object(surface, "validate_geometry_components", wraps=surface.validate_geometry_components) as admitted: + cage = surface.build_cage(self.geometry) + admitted.assert_called_once_with(self.geometry) self.assertEqual((len(cage.vertices), len(cage.quads), len(cage.formula_records)), (120, 104, 120)) records = {r["control_id"]: r for r in cage.formula_records} self.assertEqual(records["c023"]["formula_id"], "formula.axial.j1.interior") @@ -78,14 +75,31 @@ def test_formula_candidates_use_prepared_boundary_and_exact_dispatch(self): self.assertIn("hips.left.P_s.x", records["c020"]["geometry_dependencies"]) self.assertEqual(set(cage.formula_ids), set(surface.FORMULAS)) - def test_prepared_admission_rejects_malformed_binary64_and_rotation(self): - bad = deepcopy(self.prepared) - bad["stations"]["lower_pelvis"]["C"] = (0, -0.45, 0.0) - with self.assertRaises(prepared_projection.PreparedProjectionError): surface.build_cage(bad) - bad = deepcopy(self.prepared) - bad["parts"][0]["placement"]["rotation_xyzw"][3] = 0.5 - with self.assertRaises(prepared_projection.PreparedProjectionError): surface.build_cage(bad) - + def test_surface_rejects_prepared_identity_and_nonexact_numeric_carriers(self): + source = (HERE / "owned_root_surface.py").read_text(encoding="utf-8") + self.assertNotIn("prepared_projection", source); self.assertNotIn("_admit_surface", source); self.assertNotIn("perturb", source) + self.assertEqual(tuple(surface.GeometryComponents.__slots__), ("values",)) + charts = independent_charts(self.evaluation) + functions = ( + (surface.build_cage, ()), (surface.evaluate, ()), + (surface.formula_candidate_records, ()), + (surface.geometry_component, ("stations.lower_pelvis.C.x",)), + (surface.analytic_control_derivatives, ("hips.left.P_s.x",)), + (surface.predicted_support, ("hips.left.P_s.x",)), + (surface.validate_level_structure, (self.evaluation.cage,)), + (surface.validate_evaluation, (self.evaluation,)), + (anatomy.validate_evaluated_surface, (self.evaluation, charts)), + (anatomy.select_trace, (self.evaluation, "port.neck", 2, charts)), + ) + for bad in (self.prepared, {"profile_id": "standard_neutral_reference"}, self.geometry.values): + for function, suffix in functions: + args = (bad, *suffix) if function not in (surface.validate_level_structure, surface.validate_evaluation, anatomy.validate_evaluated_surface, anatomy.select_trace) else (*suffix[:1], bad, *suffix[1:]) + with self.subTest(value=type(bad).__name__, function=function.__name__), self.assertRaises(ValueError): function(*args) + for values in (([0.0] * 92), ((0.0,) * 91), ((0.0,) * 91 + (1,)), ((0.0,) * 91 + (float("nan"),))): + forged = surface.GeometryComponents(self.geometry.values); object.__setattr__(forged, "values", values) + with self.subTest(values=type(values).__name__, length=len(values)), self.assertRaises(ValueError): surface.validate_geometry_components(forged) + for values in ((0.0,) * 91, (0.0,) * 91 + (0,), (0.0,) * 91 + (float("nan"),)): + with self.assertRaises(ValueError): surface.GeometryComponents(values) def test_subdivision_has_exact_numeric_topology_incidence_and_lineage(self): cage, level1, level2 = self.evaluation.cage, *self.evaluation.levels self.assertEqual([(len(m.vertices), len(m.quads), len(m.triangles)) for m in (cage, level1, level2)], @@ -110,54 +124,31 @@ def test_contributor_domains_follow_catalog_order_and_forged_topology_fails(self self.assertEqual(junction["contributor_domains"], ("domain.pelvis", "domain.abdomen")) self.assertEqual(surface.CONTROL_DOMAIN_INCIDENTS["c021"], ("domain.pelvis", "domain.abdomen")) bad = list(cage.quads); bad[0] = (bad[0][1], bad[0][0], bad[0][2], bad[0][3]) - with self.assertRaises(ValueError): surface.validate_level_structure(replace(cage, quads=tuple(bad)), self.prepared) + with self.assertRaises(ValueError): surface.validate_level_structure(replace(cage, quads=tuple(bad)), self.geometry) def test_anatomy_rejects_forged_level_zero_triangles(self): bad = replace(self.evaluation.cage, triangles=self.evaluation.cage.triangles[:-1] + ((0, 1, 2, 3),)) forged = surface.SurfaceEvaluation(bad, self.evaluation.levels) - with self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(forged, prepared=self.prepared) + with self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(forged, self.geometry) def test_analytic_derivatives_propagate_and_support_is_exact(self): - derivative = surface.analytic_control_derivatives(self.prepared, "hips.left.P_s.x") + derivative = surface.analytic_control_derivatives(self.geometry, "hips.left.P_s.x") self.assertEqual(derivative[self.evaluation.cage.control_ids.index("c003")], (0.0, 0.0, 0.0)) - self.assertEqual(len(surface.predicted_support(self.prepared, "hips.left.P_s.x")), 436) - self.assertEqual(len(surface.predicted_support(self.prepared, "hips.right.P_s.x")), 436) - with self.assertRaises(ValueError): surface.predicted_support(self.prepared, "outside.component") + self.assertEqual(len(surface.predicted_support(self.geometry, "hips.left.P_s.x")), 436) + self.assertEqual(len(surface.predicted_support(self.geometry, "hips.right.P_s.x")), 436) + with self.assertRaises(ValueError): surface.predicted_support(self.geometry, "outside.component") def test_analytic_support_ignores_formula_record_dependency_metadata(self): component = "hips.left.P_s.x" - derivative = surface.analytic_control_derivatives(self.prepared, component) - support = surface.predicted_support(self.prepared, component) + derivative = surface.analytic_control_derivatives(self.geometry, component) + support = surface.predicted_support(self.geometry, component) for name, dependencies in (("stripped", []), ("corrupt", ["outside.component"])): - records = deepcopy(surface.formula_candidate_records(self.prepared)) + records = deepcopy(surface.formula_candidate_records(self.geometry)) for record in records: record["geometry_dependencies"] = dependencies with self.subTest(metadata=name), patch.object(surface, "formula_candidate_records", return_value=records): - self.assertEqual(surface.analytic_control_derivatives(self.prepared, component), derivative) - self.assertEqual(surface.predicted_support(self.prepared, component), support) - with self.assertRaises(ValueError): surface.analytic_control_derivatives(self.prepared, "outside.component") - - def test_all_33_public_perturbations_match_exact_analytic_support(self): - baseline = self.evaluation.levels[1] - original = prepared_projection.canonical_json_bytes(self.prepared) - tolerance = float.fromhex("0x1.c666666666666p-45") - self.assertEqual((len(surface.MUST_AFFECT_PARAMETER_IDS), surface.PERTURBATION_DELTA_M), (33, 0.01)) - for parameter in surface.MUST_AFFECT_PARAMETER_IDS: - with self.subTest(parameter=parameter): - component = surface.MUST_AFFECT_COMPONENTS[parameter]; path = component.split(".") - if path[-1] in "xyz": path[-1] = "xyz".index(path[-1]) - expected = deepcopy(self.prepared); target = expected - for part in path[:-1]: target = target[part] - target[path[-1]] = float(target[path[-1]] + surface.PERTURBATION_DELTA_M) - self.assertEqual(surface.perturb_prepared(self.prepared, parameter), expected) - cage = surface.build_perturbed_cage(self.prepared, parameter) - evaluation = surface.evaluate_perturbation(self.prepared, parameter) - self.assertEqual(cage, evaluation.cage); surface.validate_evaluation(evaluation, expected) - predicted = surface.predicted_support(self.prepared, component) - movement = tuple(sum((evaluation.levels[1].vertices[i][axis] - baseline.vertices[i][axis]) ** 2 for axis in range(3)) ** .5 for i in range(1737)) - observed = tuple(i for i, value in enumerate(movement) if value > tolerance) - self.assertTrue(predicted); self.assertEqual(predicted, observed) - self.assertLessEqual(max((movement[i] for i in range(1737) if i not in predicted), default=0.0), tolerance) - self.assertEqual(prepared_projection.canonical_json_bytes(self.prepared), original) + self.assertEqual(surface.analytic_control_derivatives(self.geometry, component), derivative) + self.assertEqual(surface.predicted_support(self.geometry, component), support) + with self.assertRaises(ValueError): surface.analytic_control_derivatives(self.geometry, "outside.component") def test_l0_lineage_fields_are_independently_admitted(self): cage = self.evaluation.cage @@ -171,8 +162,8 @@ def test_l0_lineage_fields_are_independently_admitted(self): "vertex_records": replace(cage, vertex_records=tuple(vertex_records)), } for name, forged in probes.items(): - with self.subTest(field=name), self.assertRaises(ValueError): surface.validate_level_structure(forged, self.prepared) - with self.subTest(evaluation_field=name), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged, self.evaluation.levels), self.prepared) + with self.subTest(field=name), self.assertRaises(ValueError): surface.validate_level_structure(forged, self.geometry) + with self.subTest(evaluation_field=name), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged, self.evaluation.levels), self.geometry) def test_l0_coordinates_are_independently_recomputed_from_prepared(self): cage = self.evaluation.cage; vertices = list(cage.vertices); records = deepcopy(cage.formula_records) @@ -180,8 +171,8 @@ def test_l0_coordinates_are_independently_recomputed_from_prepared(self): forged = replace(cage, vertices=tuple(vertices), formula_records=tuple(records)) level1 = surface.subdivide(forged, 1); level2 = surface.subdivide(level1, 2) evaluation = surface.SurfaceEvaluation(forged, (level1, level2)) - with self.assertRaises(ValueError): surface.validate_level_structure(forged, self.prepared) - with self.assertRaises(ValueError): surface.validate_evaluation(evaluation, self.prepared) + with self.assertRaises(ValueError): surface.validate_level_structure(forged, self.geometry) + with self.assertRaises(ValueError): surface.validate_evaluation(evaluation, self.geometry) def test_l1_l2_fields_are_exactly_parent_derived(self): meshes = [self.evaluation.cage, *self.evaluation.levels] @@ -203,23 +194,29 @@ def test_l1_l2_fields_are_exactly_parent_derived(self): "triangles": replace(mesh, triangles=(mesh.triangles[1], mesh.triangles[0], *mesh.triangles[2:])), } for field, child in probes.items(): - with self.subTest(level=level, field=field), self.assertRaises(ValueError): surface.validate_level_structure(child, self.prepared, meshes[level - 1]) + with self.subTest(level=level, field=field), self.assertRaises(ValueError): surface.validate_level_structure(child, self.geometry, meshes[level - 1]) forged = list(meshes); forged[level] = child - with self.subTest(evaluation_level=level, evaluation_field=field), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged[0], tuple(forged[1:])), self.prepared) + with self.subTest(evaluation_level=level, evaluation_field=field), self.assertRaises(ValueError): surface.validate_evaluation(surface.SurfaceEvaluation(forged[0], tuple(forged[1:])), self.geometry) def test_independent_references_reject_coordinated_producer_defects(self): - def bad_formula(prepared, control, producer=surface._formula_for_control): formula, dependencies, point, parameters = producer(prepared, control); return formula, dependencies, (float(point[0] + .01), point[1], point[2]), parameters - with patch.object(surface, "_formula_for_control", side_effect=bad_formula), self.assertRaisesRegex(ValueError, "independent prepared reference"): surface.build_cage(self.prepared) + def bad_formula(geometry, control, producer=surface._formula_for_control): formula, dependencies, point, parameters = producer(geometry, control); return formula, dependencies, (float(point[0] + .01), point[1], point[2]), parameters + with patch.object(surface, "_formula_for_control", side_effect=bad_formula), self.assertRaisesRegex(ValueError, "independent numeric reference"): surface.build_cage(self.geometry) def bad_subdivision(parent, level, points=None, producer=surface._subdivide_once): child = producer(parent, level, points); vertices = list(child.vertices); vertices[0] = (float(vertices[0][0] + .01), *vertices[0][1:]); return replace(child, vertices=tuple(vertices)) with patch.object(surface, "_subdivide_once", side_effect=bad_subdivision), self.assertRaisesRegex(ValueError, "parent-derived vertices"): surface.subdivide(self.evaluation.cage, 1) def bad_record(level, vertex_id, contributors, formulas, producer=surface._record): return producer(level, vertex_id, contributors, formulas) | {"contributor_domains": ()} with patch.object(surface, "_record", side_effect=bad_record), self.assertRaisesRegex(ValueError, "parent-derived vertex_records"): surface.subdivide(self.evaluation.cage, 1) + def test_independent_hip_reference_uses_frozen_lerp_order(self): + values = list(self.geometry.values) + for component in ("hips.left.P_s.z", "stations.lower_pelvis.C.z"): values[surface.GEOMETRY_COMPONENT_IDS.index(component)] = .1 + actual = surface._reference_control_coordinate(surface.GeometryComponents(tuple(values)), "c004")[2]; frozen = (1.0 - .20) * .1 + .20 * .1 + self.assertEqual(actual, frozen); self.assertNotEqual(frozen, .1 + .20 * (.1 - .1)) class ChartLineageTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.prepared = prepared() - cls.evaluation = surface.evaluate(cls.prepared) - cls.formulas = surface.formula_candidate_records(cls.prepared) + cls.geometry = prepared_projection.project_geometry(cls.prepared) + cls.evaluation = surface.evaluate(cls.geometry) + cls.formulas = surface.formula_candidate_records(cls.geometry) cls.summary = chart.build_chart_summary(cls.evaluation, cls.formulas) def test_exact_closed_inventory_ids_and_source_boundary(self): @@ -336,18 +333,19 @@ class AnatomyTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.prepared = prepared() - cls.evaluation = surface.evaluate(cls.prepared) + cls.geometry = prepared_projection.project_geometry(cls.prepared) + cls.evaluation = surface.evaluate(cls.geometry) cls.charts = independent_charts(cls.evaluation) def test_independent_selectors_and_exact_anatomy_inventory(self): - levels = anatomy.validate_evaluated_surface(self.evaluation, self.charts, prepared=self.prepared) + levels = anatomy.validate_evaluated_surface(self.evaluation, self.geometry, self.charts) self.assertEqual(len(levels), 3) - self.assertEqual(anatomy.validate_evaluated_surface(self.evaluation, self.charts), levels) - self.assertEqual(len(anatomy.select_trace(self.evaluation, "port.neck", 2, self.charts, prepared=self.prepared)), 24) - measures = anatomy.measure_anatomy(self.evaluation, self.prepared, self.charts) + self.assertEqual(anatomy.validate_evaluated_surface(self.evaluation, self.geometry, self.charts), levels) + self.assertEqual(len(anatomy.select_trace(self.evaluation, self.geometry, "port.neck", 2, self.charts)), 24) + measures = anatomy.measure_anatomy(self.evaluation, self.geometry, self.charts) self.assertEqual(len(measures), 78) self.assertEqual(len(anatomy.anatomy_threshold_records()), 78) - self.assertEqual(len(anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts)), 78) + self.assertEqual(len(anatomy.anatomy_gate_records(self.evaluation, self.geometry, self.charts)), 78) self.assertGreater(measures["anatomy.pelvic_lateral_ratio.left.L2"]["omitted_count"], 0) def test_forged_chart_ancestry_and_corner_incidence_fail_closed(self): @@ -358,28 +356,28 @@ def test_forged_chart_ancestry_and_corner_incidence_fail_closed(self): bad = deepcopy(self.charts); records(bad, 1)[0]["corners"][0]["vertex_id"] = "vertex.L1.v0001"; mutations.append(bad) bad = deepcopy(self.charts); bad["chart_records"].pop(); mutations.append(bad) for forged in mutations: - with self.assertRaises(anatomy.AnatomyGateError): anatomy.measure_anatomy(self.evaluation, self.prepared, forged) + with self.assertRaises(anatomy.AnatomyGateError): anatomy.measure_anatomy(self.evaluation, self.geometry, forged) def test_chart_levels_require_exact_bounded_integers(self): boolean = deepcopy(self.charts); boolean["chart_records"][0]["level"] = False surplus = deepcopy(self.charts); extra = deepcopy(surplus["chart_records"][-1]) extra["chart_id"], extra["level"] = "chart.q999/L3.s0.s0.s0", 3; surplus["chart_records"].append(extra) for name, forged in (("boolean", boolean), ("surplus", surplus)): - with self.subTest(probe=name), self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(self.evaluation, forged, prepared=self.prepared) + with self.subTest(probe=name), self.assertRaises(anatomy.AnatomyGateError): anatomy.validate_evaluated_surface(self.evaluation, self.geometry, forged) def test_shoulder_selection_uses_face_ancestry_not_vertex_records(self): altered = [] for mesh in (self.evaluation.cage, *self.evaluation.levels): altered.append(replace(mesh, vertex_records=tuple({"base_control_contributors": (), "geometry_dependency_union": (), "contributor_domains": ()} for _ in mesh.vertex_records))) forged = surface.SurfaceEvaluation(altered[0], tuple(altered[1:])) - original = anatomy.measure_anatomy(self.evaluation, self.prepared, self.charts) + original = anatomy.measure_anatomy(self.evaluation, self.geometry, self.charts) with patch.object(surface, "validate_evaluation", return_value=tuple(altered)): - self.assertEqual(anatomy.measure_anatomy(forged, self.prepared, self.charts), original) + self.assertEqual(anatomy.measure_anatomy(forged, self.geometry, self.charts), original) def test_frozen_thresholds_resist_hostile_runtime_reassignment(self): - expected = anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts), anatomy.run_production_axillary_fixtures() + expected = anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.geometry, self.charts), anatomy.run_production_axillary_fixtures() with patch.object(anatomy, "THRESHOLD", -1e9), patch.object(anatomy, "_TURN", -1e9), patch.object(anatomy, "_STRETCH", 1e9): - self.assertEqual((anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.prepared, self.charts), anatomy.run_production_axillary_fixtures()), expected) + self.assertEqual((anatomy.anatomy_threshold_records(), anatomy.anatomy_gate_records(self.evaluation, self.geometry, self.charts), anatomy.run_production_axillary_fixtures()), expected) self.assertEqual((anatomy.evaluate_axillary_scalars(float.fromhex("0x1.9999999999999p-5"), 1.0).passed, anatomy.evaluate_axillary_scalars(1.0, float.fromhex("0x1.4000000000001p+1")).passed), (False, False)) diff --git a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py index 9bc2739..83e4850 100644 --- a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py +++ b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py @@ -3,6 +3,7 @@ import copy import hashlib +import inspect import json import runpy import sys @@ -32,7 +33,11 @@ import artifact_serialization as artifacts import prepared_projection as projection from prepared_projection import ( + MUST_AFFECT_COMPONENTS, + MUST_AFFECT_PARAMETER_IDS, + PERTURBATION_DELTA_M, PreparedProjectionError, + GeometryComponents, _admit_profile_bytes, _admit_source_bytes, _validate_binding_records, @@ -44,6 +49,8 @@ canonical_json_sha256, normalize_source_address, prepare_standard_neutral, + project_perturbed_geometry, + project_geometry, source_binding_records, validate_prepared, ) @@ -141,11 +148,59 @@ def setUpClass(cls): cls.source_document = json.loads(SOURCE.read_bytes()) cls.profile_document = json.loads(PROFILE_TABLE.read_bytes()) cls.prepared = prepare_standard_neutral(SOURCE) + cls.geometry = project_geometry(cls.prepared) def assert_runtime_vector(self, value, length=3): self.assertIs(type(value), list) self.assertEqual(len(value), length) self.assertTrue(all(type(item) is float for item in value)) + def test_public_geometry_carrier_is_exact_numeric_only_projection(self): + geometry = self.geometry + self.assertIs(type(geometry), GeometryComponents) + self.assertEqual(tuple(GeometryComponents.__slots__), ("values",)) + self.assertEqual(len(geometry.values), 92) + self.assertTrue(all(type(value) is float for value in geometry.values)) + self.assertFalse(hasattr(geometry, "__dict__")) + components = tuple(row["prepared_component"] for row in source_binding_records()) + expected = [] + for component in components: + path = component.split("."); value = self.prepared + for field in path[:-1]: value = value[field] + expected.append(value["xyz".index(path[-1])] if path[-1] in "xyz" and len(path[-1]) == 1 else value[path[-1]]) + self.assertEqual(geometry.values, tuple(expected)) + for excluded in ("profile_id", "contract", "source", "parts", "provenance", "path", "sha256", "label", "scale"): + self.assertFalse(hasattr(geometry, excluded)) + for path, replacement in ((('profile_selection', 'profile_id'), 'forged'), (('stations', 'lower_pelvis', 'rL'), 1.51)): + with self.subTest(path=path), self.assertRaises(PreparedProjectionError): project_geometry(_mutated(self.prepared, path, replacement)) + self.assertEqual(tuple(inspect.signature(project_geometry).parameters), ("prepared",)) + self.assertIsNone(project_geometry.__defaults__) + self.assertIsNone(project_geometry.__kwdefaults__) + with patch.object(projection, "validate_prepared", side_effect=AssertionError("caller-overridable dependency")), patch.object(projection, "source_binding_records", side_effect=AssertionError("caller-overridable dependency")): + self.assertEqual(project_geometry(self.prepared), geometry) + def test_projection_order_is_proved_with_asymmetric_sentinels(self): + components = tuple(row["prepared_component"] for row in source_binding_records()) + sentinels = {component: float(index + 0.125) for index, component in enumerate(components)} + projector, _ = projection._geometry_apis( + _ids=components, + _validate=lambda value: value, + _read=lambda value, component: sentinels[component], + _bindings=lambda: [{"prepared_component": component} for component in components], + ) + projected = projector({"sentinel": True}) + self.assertEqual(projected.values, tuple(sentinels[component] for component in components)) + self.assertEqual(len(set(projected.values)), 92) + def test_project_perturbed_geometry_copies_one_prepared_scalar_before_projection(self): + original = canonical_json_bytes(self.prepared) + for parameter in MUST_AFFECT_PARAMETER_IDS: + with self.subTest(parameter=parameter): + component = MUST_AFFECT_COMPONENTS[parameter] + index = projection._GEOMETRY_COMPONENT_IDS.index(component) + expected = list(self.geometry.values); expected[index] = float(expected[index] + PERTURBATION_DELTA_M) + self.assertEqual(project_perturbed_geometry(self.prepared, parameter).values, tuple(expected)) + self.assertEqual(canonical_json_bytes(self.prepared), original) + for bad in ("unknown", "left.r_y.extra", 1): + with self.subTest(parameter=bad), self.assertRaises(PreparedProjectionError): project_perturbed_geometry(self.prepared, bad) + with self.assertRaises(PreparedProjectionError): project_perturbed_geometry(self.geometry, MUST_AFFECT_PARAMETER_IDS[0]) def test_complete_prepared_schema_values_and_runtime_types(self): prepared = self.prepared self.assertEqual(set(prepared), { diff --git a/experiments/owned-root-assembly-successor/tests/test_render_export.py b/experiments/owned-root-assembly-successor/tests/test_render_export.py index a7cd89d..a4ad4d6 100644 --- a/experiments/owned-root-assembly-successor/tests/test_render_export.py +++ b/experiments/owned-root-assembly-successor/tests/test_render_export.py @@ -19,15 +19,14 @@ import render_export as render -def _prepared(): - return prepared_projection.prepare_standard_neutral( - REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" - ) +def _geometry(): + prepared = prepared_projection.prepare_standard_neutral(REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json") + return prepared_projection.project_geometry(prepared) @lru_cache(maxsize=1) def _evaluation(): - return surface.evaluate(_prepared()) + return surface.evaluate(_geometry()) def _level2(): From b13d2d094def39fe05698822a1207264a062f461 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 13:26:51 +1200 Subject: [PATCH 16/38] Optimize owned-root evidence execution --- .../owned-root-assembly-investigation.md | 9 +- .../owned-root-assembly-successor/README.md | 33 ++++---- .../anatomy_gates.py | 52 ++++++------ .../build_owned_root.py | 2 +- .../mesh_correctness.py | 4 +- .../owned_root_surface.py | 12 +-- .../render_export.py | 8 +- .../tests/test_build_owned_root.py | 82 +++++++++++-------- .../tests/test_mesh_correctness.py | 20 +++-- .../tests/test_owned_root_surface.py | 26 +++--- .../tests/test_render_export.py | 16 ++-- 11 files changed, 151 insertions(+), 113 deletions(-) diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index 07a3300..2768368 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -135,9 +135,12 @@ by the existing which records that matching contract SHA-256. The implementation README records two completed independent FREEZE reviews. The builder must require that identity and reject a missing file or any mismatch before admitting inputs or -producing output. The bounded implementation is next under this frozen -contract; no implementation result is implied. This research record remains -experiment-local, non-authoritative evidence and direction context. +producing output. This paragraph originally described the pre-implementation +state; the bounded standard-neutral implementation is now complete at +`correction_round=0`, with its authoritative evidence and remaining work +recorded in the experiment README and `docs/project/status.md`. This research +record remains experiment-local, non-authoritative evidence and direction +context. The frozen design contract covers every item in the preflight below and sets finite caps for total junction count and interface cardinality; chart, formula, diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 223e96e..682347f 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -26,8 +26,9 @@ returned `FREEZE` with zero blockers Design contract SHA-256: `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490` -`correction_round=0`: initial implementation completed; at most two shared -correction rounds remain available +`correction_round=0`: the initial implementation phase is complete. A separate +budget of at most two shared correction rounds remains available; none has been +consumed. ## Status and authority @@ -73,15 +74,15 @@ agreed and found no material blocker. The exact-five gate is therefore unlocked, but no exact-five executable or gallery exists yet. The named human checkpoint remains Ben's later exact-five gallery appraisal. -The semantics-preserving numeric-only geometry seam now fits the frozen LOC -cap and passes 126 managed tests, both seed gates, and cross-seed comparison. -Its fresh 96-file publication is in logical local cache -`artifact-cache/owned-root-assembly-successor/seam-20260905-1`; all 38 -geometry/perturbation/render roles in each seed are byte-identical to the -pre-seam baseline. The post-seam comparison report SHA-256 is -`912467f8c435932cd685b089911f0141ba2454b5e7a62dcea0501412960b09ea` -and the post-seam stable-manifest SHA-256 is -`56da91b3459f381a85c682844d1b3e25c76a491519847c9ebc2c2e3a7e9b0ed4`. +The semantics-preserving numeric-only geometry seam and correction batch fit +the frozen LOC caps and pass 132 managed tests, both seed gates, and cross-seed +comparison. The current 96-file publication is in logical local cache +`artifact-cache/owned-root-assembly-successor/correction-batch-20260905-2`; +all 38 geometry/perturbation/render roles in each seed are byte-identical to +both the seam and pre-seam baselines. The current comparison report SHA-256 is +`433cefd54ef00703441fe47d3cf952c281f30724f192b4bc9469eba6aa00a15c` +and the current stable-manifest SHA-256 is +`873ded1c775af5d411fc9ddb9030f47bcf4eee99e44a25fec5b3793d0fc9fce5`. Next is the separately SHA-bound activation contract and sibling exact-five runner/publisher. Do not add a private-internal wrapper, duplicate geometry, @@ -250,7 +251,9 @@ which records matching SHA-256 implementation README records two completed independent FREEZE reviews. The builder must require that identity, hash the file before admitting source inputs, and reject a missing file or mismatch without producing an artifact. -The bounded implementation phase is active under this frozen contract. +The bounded implementation phase is complete under this frozen contract at +`correction_round=0`. The separate budget of at most two shared correction +rounds remains available and unused. The frozen design contract fixes all details needed to make the candidate reproducible without inventing them during coding: @@ -575,9 +578,9 @@ it only unlocks the next recorded investigation and human checkpoint. ## Recommended follow-up -Implement the semantics-preserving numeric-only geometry seam, then revalidate -the exact-neutral bytes and evidence against the baseline above. Separately, -prepare the SHA-bound activation contract and sibling exact-five +The semantics-preserving numeric-only geometry seam is implemented and +revalidated against the baseline above. Separately, prepare the SHA-bound +activation contract and sibling exact-five runner/publisher. Do not add a private-internal wrapper, duplicate geometry, profile-aware branching, geometry correction, or a new representation, and do not edit canonical specifications or production architecture as part of this diff --git a/experiments/owned-root-assembly-successor/anatomy_gates.py b/experiments/owned-root-assembly-successor/anatomy_gates.py index 774da8c..56a0959 100644 --- a/experiments/owned-root-assembly-successor/anatomy_gates.py +++ b/experiments/owned-root-assembly-successor/anatomy_gates.py @@ -101,35 +101,37 @@ def _actual_feature_edges(mesh, charts, feature, expected=None): return result def _base_feature_edges(feature, mesh): ids = surface.PORT_INFO[feature][2] if feature in PORTS else surface.JUNCTION_TRACES[feature]; indexes = {name: i for i, name in enumerate(mesh.control_ids)}; cycle = tuple(indexes[name] for name in ids); return {tuple(sorted((a, cycle[(i + 1) % len(cycle)]))) for i, a in enumerate(cycle)} -def _feature_edges(levels, charts, feature, target): - selected = _base_feature_edges(feature, levels[0]); actual = _actual_feature_edges(levels[0], charts[0], feature, selected) - if selected != actual: _fail("incidence selector disagrees with catalog", f"{feature}:L0") - for level in range(1, target + 1): - parent = levels[level - 1]; incidence = surface.subdivision_incidence(parent); edge_point = dict(incidence["edge_point_indices"]); expected = set() - for a, b in selected: mid = edge_point[(a, b)]; expected.update((tuple(sorted((a, mid))), tuple(sorted((mid, b))))) +def _new_selector_cache(): return {"incidence": {}, "feature_edges": {}} +def _cached_incidence(levels, level, cache): return cache["incidence"][level] if level in cache["incidence"] else cache["incidence"].setdefault(level, surface.subdivision_incidence(levels[level])) +def _feature_edge_levels(levels, charts, feature, target, cache=None): + cache = _new_selector_cache() if cache is None else cache; cached = cache["feature_edges"].setdefault(feature, []) + if not cached: selected = _base_feature_edges(feature, levels[0]); actual = _actual_feature_edges(levels[0], charts[0], feature, selected); _fail("incidence selector disagrees with catalog", f"{feature}:L0") if selected != actual else cached.append(frozenset(selected)) + for level in range(len(cached), target + 1): + incidence = _cached_incidence(levels, level - 1, cache); edge_point = dict(incidence["edge_point_indices"]); expected = set() + for a, b in cached[-1]: mid = edge_point[(a, b)]; expected.update((tuple(sorted((a, mid))), tuple(sorted((mid, b))))) actual = _actual_feature_edges(levels[level], charts[level], feature, expected) - if expected != actual: _fail("propagated incidence selector disagrees with catalog", f"{feature}:L{level}") - selected = expected - return selected + _fail("propagated incidence selector disagrees with catalog", f"{feature}:L{level}") if expected != actual else cached.append(frozenset(expected)) + return tuple(set(edges) for edges in cached[:target + 1]) +def _feature_edges(levels, charts, feature, target, cache=None): return _feature_edge_levels(levels, charts, feature, target, cache)[target] def _tag(control, feature): coords = surface.COORDINATE_BY_CONTROL[control]; axes = (0, 2) if feature in PORTS and feature in ("port.neck", "port.left_thigh", "port.right_thigh") else (1, 2) if feature in PORTS else tuple(0 if x == "i" else 1 if x == "j" else 2 for x in DROPS[feature][1]); return tuple(Fraction(coords[a]) for a in axes) -def _feature_tags(levels, charts, feature, target): - base = {c: _tag(levels[0].control_ids[c], feature) for edge in _feature_edges(levels, charts, feature, 0) for c in edge}; tags = base +def _feature_tags(levels, charts, feature, target, cache=None): + cache = _new_selector_cache() if cache is None else cache; edge_levels = _feature_edge_levels(levels, charts, feature, target, cache) + base = {c: _tag(levels[0].control_ids[c], feature) for edge in edge_levels[0] for c in edge}; tags = base for level in range(1, target + 1): - parent = levels[level - 1]; incidence = surface.subdivision_incidence(parent); edge_points = dict(incidence["edge_point_indices"]) - out = {i: tag for i, tag in tags.items()} - for edge in _feature_edges(levels, charts, feature, level - 1): out[edge_points[edge]] = tuple((tags[edge[0]][a] + tags[edge[1]][a]) / 2 for a in range(2)) - expected = {v for edge in _feature_edges(levels, charts, feature, level) for v in edge} + edge_points = dict(_cached_incidence(levels, level - 1, cache)["edge_point_indices"]); out = {i: tag for i, tag in tags.items()} + for edge in edge_levels[level - 1]: out[edge_points[edge]] = tuple((tags[edge[0]][a] + tags[edge[1]][a]) / 2 for a in range(2)) + expected = {v for edge in edge_levels[level] for v in edge} if set(out) != expected: _fail("feature tag propagation mismatch", f"{feature}:L{level}") tags = out return tags -def _trace(levels, charts, feature, level): +def _trace(levels, charts, feature, level, cache=None): if feature not in PORTS + JUNCTIONS or level not in range(3): _fail("unknown anatomy selector", feature) - tags = _feature_tags(levels, charts, feature, level); result = {tag: tuple(levels[level].vertices[index]) for index, tag in tags.items()} + tags = _feature_tags(levels, charts, feature, level, cache); result = {tag: tuple(levels[level].vertices[index]) for index, tag in tags.items()} if len(result) != len(tags): _fail("ambiguous anatomy selector", feature) return dict(sorted(result.items())) def select_trace(value, geometry, feature, level=2, chart_summary=None): - levels, charts = _context(value, geometry, chart_summary); return _trace(levels, charts, feature, level) + levels, charts = _context(value, geometry, chart_summary); return _trace(levels, charts, feature, level, _new_selector_cache()) def _vec(value, name): if not isinstance(value, (tuple, list)) or len(value) != 3 or any(type(x) is not float or not isfinite(x) for x in value): raise ValueError(f"{name} must be a finite binary64 vector3") return tuple(value) @@ -197,8 +199,8 @@ def _span(points, axis): return max(p[axis] for p in points) - min(p[axis] for p def _pair(a, b, name): if not a or set(a) != set(b): _fail("anatomy traces are missing or unequal", name) return [(tag, a[tag], b[tag]) for tag in sorted(a)] -def _side(out, levels, charts, level, side, neck_y, geometry): - shoulder = _trace(levels, charts, f"junction.thorax__{side}_shoulder", level); arm = _trace(levels, charts, f"port.{side}_arm", level); prefix = "anatomy." +def _side(out, levels, charts, level, side, neck_y, geometry, cache=None): + shoulder = _trace(levels, charts, f"junction.thorax__{side}_shoulder", level, cache); arm = _trace(levels, charts, f"port.{side}_arm", level, cache); prefix = "anatomy." _put(out, prefix + f"arm_port_descent.{side}.L{level}", [neck_y - p[1] for p in arm.values()]) owners = tuple(c["construction_owner"] for c in charts[level]); points = {i for fi, face in enumerate(levels[level].quads) if owners[fi] == f"domain.{side}_shoulder" for i in face} _put(out, prefix + f"shoulder_surface_descent.{side}.L{level}", [neck_y - levels[level].vertices[i][1] for i in sorted(points)]) @@ -211,7 +213,7 @@ def _side(out, levels, charts, level, side, neck_y, geometry): _put(out, prefix + f"axillary_turn_depth.{side}.L{level}", [x.turn_depth for x in axillary]); _put(out, prefix + f"axillary_path_stretch.{side}.L{level}", [x.path_stretch for x in axillary], "le", "dimensionless") paired = _pair({t: p for t, p in shoulder.items() if 4 <= t[0] <= 5}, {t: p for t, p in arm.items() if 4 <= t[0] <= 5}, "axillary recess"); sign = 1 if side == "right" else -1 _put(out, prefix + f"axillary_inboard_recess.{side}.L{level}", [sign * (o[0] - j[0]) for _, j, o in paired]); _put(out, prefix + f"axillary_downward_recess.{side}.L{level}", [o[1] - j[1] for _, j, o in paired]) - hip = _trace(levels, charts, f"junction.pelvis__{side}_hip", level); thigh = _trace(levels, charts, f"port.{side}_thigh", level); paired = _pair(hip, thigh, "pelvic wrap"); + hip = _trace(levels, charts, f"junction.pelvis__{side}_hip", level, cache); thigh = _trace(levels, charts, f"port.{side}_thigh", level, cache); paired = _pair(hip, thigh, "pelvic wrap"); _put(out, prefix + f"pelvic_vertical_wrap.{side}.L{level}", [j[1] - p[1] for _, j, p in paired]) ps_x = surface.geometry_component(geometry, f"hips.{side}.P_s.x"); ratios = [abs(j[0] - ps_x) / abs(p[0] - ps_x) for _, j, p in paired if p[0] - ps_x != 0.0]; omitted = len(paired) - len(ratios) if not ratios: _fail("pelvic lateral ratio has no nonzero denominators", side) @@ -219,12 +221,12 @@ def _side(out, levels, charts, level, side, neck_y, geometry): _put(out, prefix + f"front_depth_wrap.{side}.L{level}", [j[2] - p[2] for tag, j, p in paired if tag[1] > 1], "ge", "m"); _put(out, prefix + f"back_depth_wrap.{side}.L{level}", [p[2] - j[2] for tag, j, p in paired if tag[1] < 1], "ge", "m") _put(out, prefix + f"clearance.{side}_axilla.L{level}", [min(_span(tuple(arm.values()), 1), _span(tuple(arm.values()), 2))]) def measure_anatomy(value, geometry, chart_summary=None): - levels, charts = _context(value, geometry, chart_summary); out = {} + levels, charts = _context(value, geometry, chart_summary); out = {}; cache = _new_selector_cache() for level in range(3): - neck = _trace(levels, charts, "port.neck", level); neck_junction = _trace(levels, charts, "junction.thorax__neck", level); paired = _pair(neck, neck_junction, "neck exposure") + neck = _trace(levels, charts, "port.neck", level, cache); neck_junction = _trace(levels, charts, "junction.thorax__neck", level, cache); paired = _pair(neck, neck_junction, "neck exposure") _put(out, f"anatomy.neck_exposure.L{level}", [port[1] - junction[1] for _, port, junction in paired]); neck_y = min(p[1] for p in neck.values()) - for side in ("left", "right"): _side(out, levels, charts, level, side, neck_y, geometry) - left_hip, right_hip = _trace(levels, charts, "junction.pelvis__left_hip", level), _trace(levels, charts, "junction.pelvis__right_hip", level); left_thigh, right_thigh = _trace(levels, charts, "port.left_thigh", level), _trace(levels, charts, "port.right_thigh", level) + for side in ("left", "right"): _side(out, levels, charts, level, side, neck_y, geometry, cache) + left_hip, right_hip = _trace(levels, charts, "junction.pelvis__left_hip", level, cache), _trace(levels, charts, "junction.pelvis__right_hip", level, cache); left_thigh, right_thigh = _trace(levels, charts, "port.left_thigh", level, cache), _trace(levels, charts, "port.right_thigh", level, cache) _put(out, f"anatomy.clearance.neck.L{level}", [min(_span(tuple(neck.values()), 0), _span(tuple(neck.values()), 2))]); _put(out, f"anatomy.clearance.groin.L{level}", [min(p[0] for p in right_hip.values()) - max(p[0] for p in left_hip.values())]); _put(out, f"anatomy.clearance.medial_thigh.L{level}", [min(p[0] for p in right_thigh.values()) - max(p[0] for p in left_thigh.values())]) if len(out) != 78: _fail("anatomy inventory is not exactly 78 measures", len(out)) return out diff --git a/experiments/owned-root-assembly-successor/build_owned_root.py b/experiments/owned-root-assembly-successor/build_owned_root.py index 1b651fc..fc1e0f8 100644 --- a/experiments/owned-root-assembly-successor/build_owned_root.py +++ b/experiments/owned-root-assembly-successor/build_owned_root.py @@ -167,7 +167,7 @@ def _geometry(surface, mesh_api, chart, anatomy, geometry_input): expected = tuple(tuple(int(control[1:]) for control in row[2]) for row in surface.FACE_RECORDS); derived = mesh_api.derive_expected_face_catalogs(expected); _need(tuple(len(rows) for rows in derived) == (104, 416, 1664), "independently derived expected topology differs") reports, intersection_reports = [], [] for level, mesh in enumerate(meshes): - inputs = _junction_inputs(surface, evaluation, level, chart_summary); reports.append(mesh_api.validate_geometry(mesh.vertices, mesh.quads, level, dict(mesh.boundary_loops), _directions(surface), expected, inputs, mesh.face_owners)); intersection_reports.append(mesh_api.intersection_diagnostics(mesh.vertices, mesh.triangles)) + inputs = _junction_inputs(surface, evaluation, level, chart_summary); report = mesh_api.validate_geometry(mesh.vertices, mesh.quads, level, dict(mesh.boundary_loops), _directions(surface), expected, inputs, mesh.face_owners); reports.append(report); intersection_reports.append(report["intersection_report"]) structural, thresholds = [], []; invalid = "duplicate_vertex_ids duplicate_face_ids degenerate_faces zero_length_edges non_manifold_edges orientation_conflicts unowned_elements overowned_elements accidental_boundary_components".split(); chart_counts = {row["level"]: row for row in chart_summary["level_counts"]} for level, (mesh, report) in enumerate(zip(meshes, reports)): edge, triangles, quads = _metric_values(mesh); top = report["topology"]; [_put(structural, thresholds, _gate(f"structural.L{level}.count.{name}", 1, value, value, "eq", value, value, "count")) for name, value in zip(("vertices", "edges", "quads", "triangles", "boundary_edges"), (len(mesh.vertices), top.edge_count, len(mesh.quads), len(mesh.triangles), top.boundary_edge_count))] diff --git a/experiments/owned-root-assembly-successor/mesh_correctness.py b/experiments/owned-root-assembly-successor/mesh_correctness.py index 42aed79..6d9e797 100644 --- a/experiments/owned-root-assembly-successor/mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/mesh_correctness.py @@ -528,7 +528,7 @@ def validate_geometry(vertices, quads, level, boundary_loops, port_directions, e if len(loops) != 5: _fail("exactly 5 boundary loops are required") topology = _topology_report(len(points), faces, loops, _expected_face_catalogs(expected_base_faces)[level]); owners = _face_owners(face_owners, len(faces)); incidence = _edge_incidence(faces) edge_lengths = tuple(_norm_vec(_sub_vec(points[b], points[a])) for a, b in incidence) - triangles = tuple((face[0], face[1], face[2]) for face in faces) + tuple((face[0], face[2], face[3]) for face in faces) + triangles = tuple(triangle for face in faces for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) triangle_areas = tuple(0.5 * _norm_vec(_triangle_normal(face, points)) for face in triangles); quad_data = tuple(_quad_data(face, points) for face in faces); quad_areas = tuple(value[0] for value in quad_data) if any(not math.isfinite(value) for value in edge_lengths + triangle_areas + quad_areas): _fail("structural metrics must be finite") floor = _STRUCTURAL_FLOORS[level] @@ -542,7 +542,7 @@ def validate_geometry(vertices, quads, level, boundary_loops, port_directions, e junctions = _validate_junction_inputs(junction_inputs) residuals = tuple((name, _junction_continuity_metrics(points, faces, owners, row["incident_domains"], row["domain_vertex_tags"], row.get("expected_domain_vertex_tags"))["coordinate_residual"]) for name, row in junctions.items()) fold_count = _run_fold_gates(incidence, owners, quad_normals, level) - return {"topology": topology, "edge_length_min": min(edge_lengths), "triangle_area_min": min(triangle_areas), "quad_area_min": min(quad_areas), "intersection_hit_count": 0, "port_count": len(loops), "port_metrics": port_metrics, "fold_count": fold_count, "junction_count": len(junctions), "junction_residuals": residuals} + return {"topology": topology, "edge_length_min": min(edge_lengths), "triangle_area_min": min(triangle_areas), "quad_area_min": min(quad_areas), "intersection_hit_count": 0, "intersection_report": intersection, "port_count": len(loops), "port_metrics": port_metrics, "fold_count": fold_count, "junction_count": len(junctions), "junction_residuals": residuals} def intersection_candidate_threshold_records(): return tuple(dict(record) for record in _THRESHOLD_RECORDS) def _normalize_public(function): diff --git a/experiments/owned-root-assembly-successor/owned_root_surface.py b/experiments/owned-root-assembly-successor/owned_root_surface.py index d42353a..0d85f16 100644 --- a/experiments/owned-root-assembly-successor/owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/owned_root_surface.py @@ -399,9 +399,9 @@ def subdivision_incidence(mesh): stencils = tuple((i, *sorted(boundary[i])) if i in boundary else tuple(v for fi in sorted(faces[i]) for v in mesh.quads[fi]) for i in range(V)) edge_stencils = tuple((edge, tuple(edge) + tuple(v for fi, *_ in sorted(uses[edge]) for v in mesh.quads[fi])) for edge in edges) face_stencils = tuple((fi, tuple(mesh.quads[fi])) for fi in range(Q)) - edge_indices = tuple((edge, V + i) for i, edge in enumerate(edges)); face_indices = tuple((fi, V + E + fi) for fi in range(Q)) - children = tuple((fi, corner, (face[corner], edge_indices[edges.index(tuple(sorted((face[corner], face[(corner + 1) % 4]))))][1], V + E + fi, edge_indices[edges.index(tuple(sorted((face[(corner - 1) % 4], face[corner]))))][1])) for fi, face in enumerate(mesh.quads) for corner in range(4)) - propagated = tuple((name, tuple(item for i, v in enumerate(loop) for item in (v, edge_indices[edges.index(tuple(sorted((v, loop[(i + 1) % len(loop)]))))][1])) ) for name, loop in mesh.boundary_loops) + edge_indices = tuple((edge, V + i) for i, edge in enumerate(edges)); edge_index = dict(edge_indices); face_indices = tuple((fi, V + E + fi) for fi in range(Q)) + children = tuple((fi, corner, (face[corner], edge_index[tuple(sorted((face[corner], face[(corner + 1) % 4])))], V + E + fi, edge_index[tuple(sorted((face[(corner - 1) % 4], face[corner])))])) for fi, face in enumerate(mesh.quads) for corner in range(4)) + propagated = tuple((name, tuple(item for i, v in enumerate(loop) for item in (v, edge_index[tuple(sorted((v, loop[(i + 1) % len(loop)])))]))) for name, loop in mesh.boundary_loops) return {"source_level": mesh.level, "target_level": mesh.level + 1, "edges": tuple((e, tuple(u[0] for u in uses[e])) for e in edges), "boundary_edges": tuple(e for e in edges if len(uses[e]) == 1), "vertex_stencils": stencils, "edge_stencils": edge_stencils, "face_stencils": face_stencils, "edge_point_indices": edge_indices, "face_point_indices": face_indices, "child_emission": children, "propagated_port_loops": propagated} def propagate_port_loops(mesh): return dict(subdivision_incidence(mesh)["propagated_port_loops"]) @@ -445,11 +445,11 @@ def _subdivide_once(mesh, level, points=None): fs = sorted(faces[i]); es = sorted(incident_edges[i]); n = len(fs); F = tuple(_div(_ordered(face_points[f][a] for f in fs), float(n)) for a in range(3)); R = tuple(_div(_ordered(_div(_add(points[x][a], points[y][a]), 2.) for x, y in es), float(len(es))) for a in range(3)) t0 = tuple(_mul(2., x) for x in R); t1 = tuple(_add(F[a], t0[a]) for a in range(3)); t2 = tuple(_mul(float(n - 3), point[a]) for a in range(3)); value = tuple(_div(_add(t1[a], t2[a]), float(n)) for a in range(3)); formula = "subdivision.interior-vertex" vertices.append(value); formulas.append(formula); base = _contributors(mesh, source); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) - for edge in edges: + for edge_position, edge in enumerate(edges): a, b = edge if len(uses[edge]) == 1: value = tuple(_div(_add(points[a][x], points[b][x]), 2.) for x in range(3)); formula = "subdivision.boundary-edge" else: f0, f1 = sorted(u[0] for u in uses[edge]); value = tuple(_div(_add(_add(_add(points[a][x], points[b][x]), face_points[f0][x]), face_points[f1][x]), 4.) for x in range(3)); formula = "subdivision.interior-edge" - vertices.append(value); formulas.append(formula); base = _contributors(mesh, inc["edge_stencils"][edges.index(edge)][1]); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) + vertices.append(value); formulas.append(formula); base = _contributors(mesh, inc["edge_stencils"][edge_position][1]); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) for fi, face in enumerate(mesh.quads): vertices.append(face_points[fi]); formulas.append("subdivision.face-point"); base = _contributors(mesh, face); deps.append(tuple(sorted({d for c in base for d in mesh.formula_records[int(c[1:])]["geometry_dependencies"]}))) quads = tuple(child[2] for child in inc["child_emission"]); face_ids = tuple(f"face.L{level}.q{i:04d}" for i in range(len(quads))); owners = tuple(mesh.face_owners[fi] for fi, _, _ in inc["child_emission"]); loops = inc["propagated_port_loops"]; ids = tuple(f"vertex.L{level}.v{i:04d}" for i in range(len(vertices))) @@ -480,7 +480,7 @@ def __mul__(self, other): return _Dual(self.value * _value(other), self.derivati def __rmul__(self, other): return self * other def __truediv__(self, other): return _Dual(self.value / _value(other), (self.derivative * _rational(_value(other)) - _rational(self.value) * _derivative(other)) / (_rational(_value(other)) ** 2)) def __rtruediv__(self, other): return _Dual(_value(other) / self.value, (_derivative(other) * _rational(self.value) - _rational(_value(other)) * self.derivative) / (_rational(self.value) ** 2)) - def __abs__(self): return _Dual(abs(self.value), self.derivative if self.value > 0 else -self.derivative if self.value < 0 else 0.0) + def __abs__(self): return _Dual(abs(self.value), self.derivative if self.value > 0 else -self.derivative if self.value < 0 else Fraction(0)) def _value(x): return x.value if isinstance(x, _Dual) else x def _derivative(x): return x.derivative if isinstance(x, _Dual) else Fraction(0) def _analytic_components(geometry): diff --git a/experiments/owned-root-assembly-successor/render_export.py b/experiments/owned-root-assembly-successor/render_export.py index 284f30f..9273263 100644 --- a/experiments/owned-root-assembly-successor/render_export.py +++ b/experiments/owned-root-assembly-successor/render_export.py @@ -179,11 +179,9 @@ def build_visibility(mesh: object) -> VisibilityBuffer: degenerate += count base = panel_index * WIDTH * HEIGHT for row in range(HEIGHT): - for column in range(WIDTH): - for triangle_index, c0, c1 in rows[row]: - if not c0 <= column <= c1: - continue - (_ax, _ay, za, _bx, _by, zb, cx, cy, zc, n0a, n0c, n1a, n1c, denominator, _, _) = records[triangle_index] + for triangle_index, c0, c1 in rows[row]: + (_ax, _ay, za, _bx, _by, zb, cx, cy, zc, n0a, n0c, n1a, n1c, denominator, _, _) = records[triangle_index] + for column in range(c0, c1 + 1): px, py = _fl(column + 0.5), _fl(row + 0.5) n0 = _fl(_fl(n0a * _fl(px - cx)) + _fl(n0c * _fl(py - cy))) w0 = _fl(n0 / denominator) diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py index 6cd1d3a..29a87c6 100644 --- a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -10,13 +10,9 @@ import tempfile import unittest from unittest import mock - - PACKAGE = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PACKAGE)) import build_owned_root as builder # noqa: E402 - - def identity_fixture(): runtime = {"schema": "owned-root-assembly-successor-runtime.v2", "fixture": "focused"} runtime_bytes = builder.artifacts.canonical_json_bytes(runtime) @@ -37,8 +33,6 @@ def identity_fixture(): "runtime_fingerprint_sha256": builder.artifacts.sha256_bytes(runtime_bytes), "implementation_files": records, } - - class FrozenInventoryTests(unittest.TestCase): def test_causality_perturbation_crosses_prepared_boundary(self): source = inspect.getsource(builder._causality) @@ -59,7 +53,6 @@ def test_contract_identity_and_private_roles_are_closed(self): self.assertEqual(len(set(builder.ARTIFACT_ROLES)), 47) self.assertEqual(builder.RUN_REPORT_GATES[0], "seed.1.identity") self.assertEqual(builder.RUN_REPORT_GATES[-1], "seed.6.serialization") - def test_parameter_to_ply_mapping_is_literal_and_reversible(self): expected = ( "perturb-left-r_y.ply", "perturb-right-r_y.ply", @@ -86,8 +79,6 @@ def test_roles_are_sorted_only_at_schema_boundaries(self): self.assertNotEqual(builder.ARTIFACT_ROLES, tuple(sorted(builder.ARTIFACT_ROLES))) self.assertEqual(builder._order(builder.ARTIFACT_ROLES), tuple(sorted(builder.ARTIFACT_ROLES))) self.assertEqual(builder._order(builder.IMPLEMENTATION_ROLES), tuple(sorted(builder.IMPLEMENTATION_ROLES))) - - class SupportAndGateTests(unittest.TestCase): def test_support_hash_uses_the_frozen_header_and_u32_indices(self): indices = (0, 4, 1736) @@ -112,7 +103,6 @@ def test_gate_records_have_the_closed_contract_shape(self): 1, 1, 1, "eq", 0, 0, "count") self.assertEqual(failed["outcome"], "fail") with self.assertRaises(builder.BuildError): builder._validate_gate(failed, zero, "hostile") - def _synthetic_continuity(self, residual_samples, fold_samples): counts = (2, 4, 8) meshes = tuple(mock.Mock(vertices=(), quads=(), face_owners=(), @@ -255,7 +245,48 @@ def forge_domain_tags(*args): mesh.vertices, mesh.quads, mesh.face_owners, **inputs[junction] ) - + def test_anatomy_turn_depth_keeps_metre_unit_and_selector_cache_is_exact(self): + import anatomy_gates as anatomy + import chart_lineage as chart_api + import owned_root_surface as surface + import prepared_projection as prepared_api + prepared = prepared_api.prepare_standard_neutral() + geometry = prepared_api.project_geometry(prepared) + evaluation = surface.evaluate(geometry) + charts = chart_api.build_chart_summary( + evaluation, tuple(surface.formula_candidate_records(geometry)) + ) + with mock.patch.object( + anatomy.surface, "subdivision_incidence", + wraps=anatomy.surface.subdivision_incidence) as incidence: + actual = anatomy.measure_anatomy(evaluation, geometry, charts) + self.assertEqual( + builder.artifacts.sha256_bytes(builder.artifacts.canonical_json_bytes(actual)), + "7d656aea745f23cb86ec0ba6177496e6eb92df8e71333e20419fec982c1853c1", + ) + self.assertEqual(incidence.call_count, 2) + self.assertEqual(tuple(call.args[0].level for call in incidence.call_args_list), (0, 1)) + turn_key = "anatomy.axillary_turn_depth.left.L0" + self.assertEqual(actual[turn_key]["unit"], "m") + thresholds = {row["threshold_id"]: row for row in anatomy.anatomy_threshold_records()} + self.assertEqual(thresholds[f"threshold.{turn_key}"]["unit"], "m") + def test_geometry_reuses_each_complete_validation_intersection_report(self): + import anatomy_gates as anatomy; import chart_lineage as chart_api + import mesh_correctness as mesh_api; import owned_root_surface as surface + import prepared_projection as prepared_api + geometry_input = prepared_api.project_geometry(prepared_api.prepare_standard_neutral()) + fixtures = tuple({"fixture_id": fixture_id, "outcome": "pass"} for fixture_id in mesh_api.INTERSECTION_FIXTURE_IDS) + observed = [] + original = mesh_api.intersection_diagnostics + def capture(*args): + observed.append(original(*args)) + return observed[-1] + with mock.patch.object(mesh_api, "run_production_intersection_fixtures", return_value=fixtures), mock.patch.object(mesh_api, "intersection_diagnostics", side_effect=capture) as diagnostic: + result = builder._geometry(surface, mesh_api, chart_api, anatomy, geometry_input) + meshes = (result["evaluation"].cage, *result["evaluation"].levels) + self.assertEqual(diagnostic.call_count, 3) + self.assertEqual(tuple(call.args[1] for call in diagnostic.call_args_list), tuple(candidate.triangles for candidate in meshes)) + self.assertEqual(tuple(report["intersection_report"] for report in result["reports"]), tuple(observed)) class StaticAdmissionTests(unittest.TestCase): def test_package_implementation_fits_frozen_physical_loc_caps(self): counts = {"production": 0, "tests": 0} @@ -300,10 +331,10 @@ def test_builder_binds_publication_inventory_and_never_self_feeds_mesh(self): publication.index("publish_no_replace")) self.assertNotIn("else mesh.quads", geometry) self.assertIn("derive_expected_face_catalogs(expected)", geometry) + self.assertNotIn("intersection_diagnostics", geometry) + self.assertIn('report["intersection_report"]', geometry) self.assertNotIn("reversed", junctions) self.assertIn("propagate_junction_tags", junctions) - - class ManagedDispatchTests(unittest.TestCase): def test_invalid_command_does_not_enter_admission(self): with mock.patch.object(builder, "_static_admission") as admission: @@ -336,8 +367,6 @@ def flatten(value): "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix", ids ) self.assertEqual(len(ids), len(tests)) - - class PublicValidatorTests(unittest.TestCase): def receipt(self, path): identity = identity_fixture() @@ -360,7 +389,6 @@ def receipt(self, path): "unexpected_successes": 0}, } return identity, value - def report(self, root, seed=17): identity = identity_fixture() stable = {"role_path": "stable-manifest.json", "bytes": 123, @@ -390,7 +418,6 @@ def report(self, root, seed=17): for gate in builder.RUN_REPORT_GATES], } return identity, value - def test_three_required_validator_exports_are_callable(self): self.assertTrue(callable(builder.validate_managed_test_receipt)) self.assertTrue(callable(builder.validate_seed_bundle)) @@ -504,21 +531,12 @@ def test_seed_validator_fails_closed_before_mutating_incomplete_bundle(self): identity=identity_fixture()) self.assertEqual(tuple(root.iterdir()), before) - def test_seed_validator_admits_complete_serialized_bundle(self): - requested_seed = os.environ.get("PYTHONHASHSEED") - self.assertIn(requested_seed, ("0", "17", "29"), - "test requires literal PYTHONHASHSEED=0, 17, or 29") - if requested_seed == "0": - return - seed = int(requested_seed) + def test_seed_builder_rejects_managed_test_seed_without_mutation(self): + self.assertEqual(os.environ.get("PYTHONHASHSEED"), "0") with tempfile.TemporaryDirectory() as directory: - root = Path(directory) / f"seed-{seed}" - identity = builder._static_admission() - builder.build_seed(root) - self.assertIsInstance( - builder.validate_seed_bundle(root=root, seed=seed, identity=identity), dict - ) - - + root = Path(directory) / "seed-17" + with self.assertRaisesRegex(builder.BuildError, "literal PYTHONHASHSEED"): + builder.build_seed(root) + self.assertFalse(root.exists()) if __name__ == "__main__": unittest.main() diff --git a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py index f0e78ff..d560142 100644 --- a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py @@ -6,26 +6,20 @@ from importlib import import_module from pathlib import Path from unittest.mock import patch - PACKAGE = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PACKAGE)) mesh = import_module("mesh_correctness") - - P0 = float.fromhex("0x0.0p+0") ONE = float.fromhex("0x1.0000000000000p+0") D50 = float.fromhex("0x1.0000000000000p-50") MIN_SUBNORMAL = float.fromhex("0x0.0000000000001p-1022") D = float.fromhex("0x1.0000000000000p-46") I0 = float.fromhex("0x1.b7cdfd9d7bdbbp-34") - def _shared_base(b0=(ONE, P0, P0), b1=(P0, ONE, P0)): shared = (P0, P0, P0) a0 = (ONE, P0, P0) a1 = (P0, ONE, P0) return [shared, a0, a1], [shared, b0, b1] - - def _count_fixture(quad_count, control_count=128): points = tuple((float(index), 0.0, 0.0) for index in range(control_count)) faces = [] @@ -468,7 +462,12 @@ def _validate(self, **changes): return mesh.validate_geometry(**{**self.inputs, **changes}) def test_success_runs_every_mandatory_production_gate(self): - report = self._validate() + with patch.object(mesh, "intersection_diagnostics", wraps=mesh.intersection_diagnostics) as diagnostic: + report = self._validate() + canonical = tuple(triangle for face in self.inputs["quads"] for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))) + diagnostic.assert_called_once() + self.assertEqual(diagnostic.call_args.args[1], canonical) + self.assertEqual(report["intersection_report"], mesh.intersection_diagnostics(self.inputs["vertices"], canonical)) floor = mesh.STRUCTURAL_FLOORS[0] self.assertEqual(report["topology"].boundary_components, 5) self.assertEqual(report["intersection_hit_count"], 0) @@ -542,6 +541,13 @@ def test_each_of_seven_junctions_rejects_forged_vertex_ids(self): class ProductionIntersectionFixtureTests(unittest.TestCase): + def test_interleaved_quad_triangles_preserve_published_pair_order(self): + points = ((0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (0.0, 2.0, 0.0), (10.0, 0.0, 0.0), (12.0, 0.0, 0.0), (10.0, 2.0, 0.0), (0.5, 0.5, -1.0), (0.5, 0.5, 1.0), (1.0, 0.5, 0.0), (20.0, 0.0, 0.0), (22.0, 0.0, 0.0), (20.0, 2.0, 0.0)) + first, second, third, fourth = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)) + interleaved = mesh.intersection_diagnostics(points, (first, second, third, fourth)) + grouped = mesh.intersection_diagnostics(points, (first, third, second, fourth)) + self.assertEqual(interleaved["first_hit_pair"], (0, 2)) + self.assertEqual(grouped["first_hit_pair"], (0, 1)) def test_contract_fixture_matrix(self): shared_names = ( "shared1.offset-d50-point-only", "shared1.coplanar-duplicate-hit", diff --git a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py index ba2e92e..43ebf27 100644 --- a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py @@ -6,12 +6,11 @@ from dataclasses import replace from pathlib import Path from unittest.mock import patch - HERE = Path(__file__).resolve().parents[1] REPO = HERE.parents[1] sys.path.insert(0, str(HERE)) import anatomy_gates as anatomy -import chart_lineage as chart +import chart_lineage as chart; import mesh_correctness as mesh_api import owned_root_surface as surface import prepared_projection def prepared(): @@ -21,8 +20,6 @@ def prepared(): def independent_charts(evaluation): """Build valid chart ancestry while anatomy remains the unit under test.""" return chart.build_chart_summary(evaluation, evaluation.cage.formula_records) - - class CatalogTests(unittest.TestCase): def test_independent_catalog_counts_and_boundary_inventory(self): report = surface.validate_catalogs() @@ -50,8 +47,6 @@ def test_public_surface_boundary_has_no_chart_or_sample_outputs(self): self.assertEqual(surface.FACE_RECORDS[0], ("q000", "domain.left_hip", ("c000", "c001", "c004", "c003"))) self.assertNotIn("_make_chart_records", surface.__dict__) self.assertNotIn("_attach_samples", surface.__dict__) - - class SurfaceTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -117,7 +112,12 @@ def test_subdivision_has_exact_numeric_topology_incidence_and_lineage(self): self.assertLessEqual(max(len(r["base_control_contributors"]) for r in level2.vertex_records), 20) self.assertLessEqual(max(len(r["geometry_dependency_union"]) for r in level2.vertex_records), 54) self.assertLessEqual(max(len(r["contributor_domains"]) for r in level2.vertex_records), 5) - + def test_subdivision_edge_map_preserves_legacy_order_and_reference_bytes(self): + for mesh_item in (self.evaluation.cage, self.evaluation.levels[0]): + edges = tuple(sorted({tuple(sorted((face[corner], face[(corner + 1) % 4]))) for face in mesh_item.quads for corner in range(4)})); V, E = len(mesh_item.vertices), len(edges); edge_points = {edge: V + index for index, edge in enumerate(edges)} + children = tuple((fi, corner, (face[corner], edge_points[tuple(sorted((face[corner], face[(corner + 1) % 4])))], V + E + fi, edge_points[tuple(sorted((face[(corner - 1) % 4], face[corner])))])) for fi, face in enumerate(mesh_item.quads) for corner in range(4)); loops = tuple((name, tuple(item for i, vertex in enumerate(loop) for item in (vertex, edge_points[tuple(sorted((vertex, loop[(i + 1) % len(loop)])))]))) for name, loop in mesh_item.boundary_loops) + incidence = surface.subdivision_incidence(mesh_item); candidate = surface._subdivide_once(mesh_item, mesh_item.level + 1); reference = surface._reference_subdivision(mesh_item, mesh_item.level + 1) + with self.subTest(level=mesh_item.level): self.assertEqual(incidence["edge_point_indices"], tuple((edge, edge_points[edge]) for edge in edges)); self.assertEqual(incidence["child_emission"], children); self.assertEqual(incidence["propagated_port_loops"], loops); self.assertEqual(candidate, reference) def test_contributor_domains_follow_catalog_order_and_forged_topology_fails(self): cage = self.evaluation.cage junction = cage.vertex_records[cage.control_ids.index("c021")] @@ -137,7 +137,14 @@ def test_analytic_derivatives_propagate_and_support_is_exact(self): self.assertEqual(len(surface.predicted_support(self.geometry, "hips.left.P_s.x")), 436) self.assertEqual(len(surface.predicted_support(self.geometry, "hips.right.P_s.x")), 436) with self.assertRaises(ValueError): surface.predicted_support(self.geometry, "outside.component") - + def test_dual_abs_zero_preserves_exact_fraction_subgradient(self): + result = abs(surface._Dual(0.0, surface.Fraction(7, 9))); self.assertEqual((result.value, result.derivative), (0.0, surface.Fraction(0))); self.assertIs(type(result.derivative), surface.Fraction) + def test_all_33_numeric_perturbations_match_exact_analytic_support(self): + parameters = prepared_projection.MUST_AFFECT_PARAMETER_IDS; self.assertEqual(len(parameters), 33) + for parameter in parameters: + component = prepared_projection.MUST_AFFECT_COMPONENTS[parameter]; predicted = surface.predicted_support(self.geometry, component); perturbed = prepared_projection.project_perturbed_geometry(self.prepared, parameter); actual = surface.evaluate(perturbed).levels[1]; reference_cage = surface.build_cage(perturbed); reference_level1 = surface._reference_subdivision(reference_cage, 1); reference = surface._reference_subdivision(reference_level1, 2) + movement = tuple(mesh_api.norm(mesh_api.sub(candidate, baseline)) for baseline, candidate in zip(self.evaluation.levels[1].vertices, actual.vertices)); observed = tuple(i for i, value in enumerate(movement) if value > mesh_api.T) + with self.subTest(parameter=parameter): self.assertTrue(predicted); self.assertEqual(actual, reference); self.assertGreaterEqual(max(movement[i] for i in predicted), float.fromhex("0x1.d14e3bcd35a85p-11")); self.assertEqual(observed, predicted) def test_analytic_support_ignores_formula_record_dependency_metadata(self): component = "hips.left.P_s.x" derivative = surface.analytic_control_derivatives(self.geometry, component) @@ -235,9 +242,6 @@ def test_exact_closed_inventory_ids_and_source_boundary(self): for item in row["geometry_dependencies"]}), 92) self.assertEqual(len(self.formulas), 120) self.assertLessEqual(max(len(row["geometry_dependencies"]) for row in self.formulas), 12) - lines = (HERE / "chart_lineage.py").read_text(encoding="utf-8").count("\n") - self.assertIn(lines, range(190, 269)) - self.assertLessEqual(Path(__file__).read_text(encoding="utf-8").count("\n"), 400) def test_domain_cycle_rejects_disconnected_open_shared_boundary(self): self.assertRaisesRegex(chart.ChartLineageError, "a junction is not one closed trace", chart._domain_cycle, {(0, 1): (0, 1), (2, 3): (2, 3)}, {(0, 1), (2, 3)}) diff --git a/experiments/owned-root-assembly-successor/tests/test_render_export.py b/experiments/owned-root-assembly-successor/tests/test_render_export.py index a4ad4d6..f060c73 100644 --- a/experiments/owned-root-assembly-successor/tests/test_render_export.py +++ b/experiments/owned-root-assembly-successor/tests/test_render_export.py @@ -22,8 +22,6 @@ def _geometry(): prepared = prepared_projection.prepare_standard_neutral(REPO / "examples/body-documents/stylized-digitigrade-biped-authored-form.json") return prepared_projection.project_geometry(prepared) - - @lru_cache(maxsize=1) def _evaluation(): return surface.evaluate(_geometry()) @@ -277,13 +275,19 @@ def test_png_is_rgb_metadata_free_and_fixed_size(self): self.assertEqual((image.mode, image.size, image.format), ("RGB", (512, 1536), "PNG")) self.assertEqual(image.getbbox(), (0, 0, 512, 1536)) def test_row_candidates_are_bounded_and_triangle_ordered(self): - screen = ((0.0, 0.0, 0.0), (4.0, 0.0, 1.0), (0.0, 4.0, 2.0), (4.0, 4.0, 3.0)) - records, rows, degenerate = render._panel_candidates(screen, ((0, 1, 2), (0, 2, 3))) - self.assertEqual((len(records), degenerate), (2, 0)) + screen = ((0.0, 0.0, 0.0), (4.0, 0.0, 1.0), (0.0, 4.0, 2.0), (4.0, 4.0, 3.0)); clipped = ((-100.0, 10.0, 0.0), (600.0, 10.0, 1.0), (-100.0, 20.0, 2.0), (600.0, 20.0, 3.0)) + records, rows, degenerate = render._panel_candidates(screen, ((0, 1, 2), (0, 2, 3))); clipped_records, clipped_rows, clipped_degenerate = render._panel_candidates(clipped, ((0, 1, 2), (0, 2, 3))); rows += clipped_rows + self.assertEqual((len(records), degenerate), (2, 0)); self.assertEqual((len(clipped_records), clipped_degenerate), (2, 0)); self.assertIn((0, render.WIDTH - 1), {(c0, c1) for row in clipped_rows for _, c0, c1 in row}) for row in rows: candidates = [item[0] for item in row] self.assertEqual(candidates, sorted(candidates)) - + for _triangle_index, c0, c1 in row: + self.assertGreaterEqual(c0, 0) + self.assertLessEqual(c1, render.WIDTH - 1) + self.assertLessEqual(c0, c1) + source = __import__("inspect").getsource(render.build_visibility) + self.assertIn("for column in range(c0, c1 + 1)", source) + self.assertNotIn("for column in range(WIDTH)", source) def test_png_has_only_frozen_chunks_and_lineage_domain_colours(self): direct, lineage, visibility = render.render_pair_bytes(self.mesh) def chunks(data): From d079b812d3fde96eee80098f8e8683f491b803d6 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 14:21:43 +1200 Subject: [PATCH 17/38] Freeze exact-five activation candidate --- docs/project/status.md | 20 +- .../owned-root-assembly-investigation.md | 12 +- .../generate_structural_profile_sources.py | 5 +- .../tests/test_structural_profile_sources.py | 8 + .../owned-root-assembly-successor/README.md | 15 +- .../exact-five-activation-contract.md | 967 ++++++++++++++++++ .../exact-five-activation-contract.sha256 | 1 + .../owned_root_surface.py | 1 + .../tests/test_owned_root_surface.py | 8 +- 9 files changed, 1012 insertions(+), 25 deletions(-) create mode 100644 experiments/owned-root-assembly-successor/exact-five-activation-contract.md create mode 100644 experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 diff --git a/docs/project/status.md b/docs/project/status.md index 2c45b76..5d2060f 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -70,15 +70,17 @@ pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks agreed and found no material blocker. The exact-five gate is therefore unlocked, but no exact-five executable or gallery exists yet. -The semantics-preserving numeric-only geometry seam now fits the frozen LOC -cap and passes 126 managed tests, both seed gates, and cross-seed comparison. -Its fresh 96-file publication is in logical local cache -`artifact-cache/owned-root-assembly-successor/seam-20260905-1`; all 38 -geometry/perturbation/render roles in each seed are byte-identical to the -pre-seam baseline. The post-seam comparison report SHA-256 is -`912467f8c435932cd685b089911f0141ba2454b5e7a62dcea0501412960b09ea` -and the post-seam stable-manifest SHA-256 is -`56da91b3459f381a85c682844d1b3e25c76a491519847c9ebc2c2e3a7e9b0ed4`. +The semantics-preserving numeric-only geometry seam and change batch fit the +frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed +comparison. The batch changes no shared formula or tunable and all 38 payloads +remain byte-identical, so it consumes no correction round. The current 96-file +publication is in logical local cache +`artifact-cache/owned-root-assembly-successor/correction-batch-20260905-4`; +all 38 geometry/perturbation/render roles in each seed are byte-identical to +both the seam and pre-seam baselines. The current comparison report SHA-256 is +`fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a` +and the current stable-manifest SHA-256 is +`1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. Next is the separately SHA-bound activation contract and sibling exact-five runner/publisher. Do not add a private-internal wrapper, duplicate geometry, diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index 2768368..23b70a3 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -26,10 +26,11 @@ metres. The active candidate-table binding is `experiments/current-form-surface-preview/structural_profile_candidates.json` with SHA-256 -`a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. This is -a source/hash metadata rebaseline only: standard-neutral geometry is expected -to remain unchanged. Historical source and evidence remain untouched; this -record does not claim that the successor implementation is complete. +`a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640`. This +paragraph records only the source/hash metadata rebaseline: standard-neutral +geometry was expected, and is now proven, to remain unchanged. Historical +source and evidence remain untouched. The successor-neutral implementation is +complete; exact-five activation and its later human checkpoint remain active. ## Research-question mapping @@ -185,7 +186,8 @@ profile expansion. ## Execution order and stop rule -The next implementation work proceeds in this order: +The work proceeds in this order; items 1 through 5 are complete and item 6 is +active: 1. audit the terminal candidate's utilities for representation-independent reuse; diff --git a/experiments/current-form-surface-preview/generate_structural_profile_sources.py b/experiments/current-form-surface-preview/generate_structural_profile_sources.py index 2cfa722..5e5f893 100644 --- a/experiments/current-form-surface-preview/generate_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/generate_structural_profile_sources.py @@ -148,9 +148,12 @@ def _restore_json_number_types(value: Any, path: tuple[str | int, ...] = ()) -> if _is_active_dimension_value_path(path): return value try: - return float(value) + number = float(value) except (OverflowError, ValueError) as exc: raise ProfileGenerationError("JSON number cannot be represented as a host float") from exc + if value != 0 and number == 0: + raise ProfileGenerationError("nonzero JSON number underflows to host float zero") + return number if isinstance(value, list): return [_restore_json_number_types(item, path + (index,)) for index, item in enumerate(value)] if isinstance(value, dict): diff --git a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py index 19930a7..d77e50d 100644 --- a/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py +++ b/experiments/current-form-surface-preview/tests/test_structural_profile_sources.py @@ -268,6 +268,14 @@ def test_active_profile_write_preserves_decimal_tokens_at_half_millimetre(self) ) ) + def test_load_json_with_bytes_rejects_nonzero_float_underflow(self) -> None: + for label, token in (("positive", "1e-4000"), ("negative", "-1e-4000")): + with self.subTest(label=label): + source_path = self.root / f"{label}-underflow.json" + source_path.write_bytes(f'{{"ordinary": {token}}}\n'.encode("ascii")) + with self.assertRaisesRegex(generator.ProfileGenerationError, "not finite UTF-8 JSON"): + generator.load_json_with_bytes(source_path, f"{label} underflow source") + def test_active_generation_rejects_float_before_precision_can_change_ties_to_even(self) -> None: dimension_role = "form_head_neck_profile_cranium_crown_forward_radius" where = "test.dimension" diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 682347f..6925389 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -74,15 +74,18 @@ agreed and found no material blocker. The exact-five gate is therefore unlocked, but no exact-five executable or gallery exists yet. The named human checkpoint remains Ben's later exact-five gallery appraisal. -The semantics-preserving numeric-only geometry seam and correction batch fit -the frozen LOC caps and pass 132 managed tests, both seed gates, and cross-seed -comparison. The current 96-file publication is in logical local cache -`artifact-cache/owned-root-assembly-successor/correction-batch-20260905-2`; +The semantics-preserving numeric-only geometry seam and change batch fit the +frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed +comparison. This is not a correction round under [Correction stop](#correction-stop): +it changes no shared construction formula or tunable, and all 38 published +roles remain byte-identical, so the two-round budget remains unused. The +current 96-file publication is in logical local cache +`artifact-cache/owned-root-assembly-successor/correction-batch-20260905-4`; all 38 geometry/perturbation/render roles in each seed are byte-identical to both the seam and pre-seam baselines. The current comparison report SHA-256 is -`433cefd54ef00703441fe47d3cf952c281f30724f192b4bc9469eba6aa00a15c` +`fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a` and the current stable-manifest SHA-256 is -`873ded1c775af5d411fc9ddb9030f47bcf4eee99e44a25fec5b3793d0fc9fce5`. +`1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. Next is the separately SHA-bound activation contract and sibling exact-five runner/publisher. Do not add a private-internal wrapper, duplicate geometry, diff --git a/experiments/owned-root-assembly-successor/exact-five-activation-contract.md b/experiments/owned-root-assembly-successor/exact-five-activation-contract.md new file mode 100644 index 0000000..d3e3320 --- /dev/null +++ b/experiments/owned-root-assembly-successor/exact-five-activation-contract.md @@ -0,0 +1,967 @@ +# Owned root assembly successor exact-five activation contract + +Status: Proposed additive experiment-local execution contract; freeze-pending; +implementation not claimed + +Authority: this document is permitted only by section 14 of the frozen +`design-contract.md` and the experiment README. It is not product, +specification, architecture, Stage 1, production, or technology acceptance. + +## 1. Scope, authority, and fail-closed rule + +This contract proposes only the exact-five numeric expansion of the completed +owned-root standard-neutral experiment. It defines selection, projection, +execution, comparison, and publication around the existing neutral geometry +representation. It does not change that representation. + +This draft and its sidecar identify the exact candidate bytes submitted for +review. They do not record acceptance or a completed freeze. The authoritative +geometry contract remains +`experiments/owned-root-assembly-successor/design-contract.md`, exactly 173184 +bytes at SHA-256 +`3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`. +Every topology, formula, tunable, threshold, gate, subdivision stencil, +ownership rule, causality rule, PLY encoding, and renderer rule is incorporated +unchanged. `correction_round` remains `0`. If accepted, this additive freeze +consumes zero geometry corrections. + +Any missing, duplicate, unknown, additional, reordered, byte-drifted, +noncanonical, non-finite, ambiguously selected, or differently derived input, +record, component, gate, artifact, or implementation role rejects before +publication. A failed run publishes nothing. There is no warning, skipped +profile, fallback profile, partial success, best-effort output, or caller +override. + +The following are forbidden: profile-specific corrections; profile-aware +topology, formulas, tunables, thresholds, gates, subdivision, ownership, +causality, or rendering; a second or hidden surface; a new prepared or geometry +representation; post-generation coordinate edits; remeshing; solving; +optimization; render-only correction; distal anatomy; tail work; optional +module expansion; and any production claim. Profile labels, IDs, source +pointers, profile pointers, provenance, and branch decisions MUST NOT enter +surface logic. + +## 2. Exact identities and ordered profiles + +The fixed input records are: + +```text +activation contract: + experiments/owned-root-assembly-successor/exact-five-activation-contract.md +activation sidecar: + experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 +design contract: + experiments/owned-root-assembly-successor/design-contract.md + bytes 173184 + sha256 3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490 +authored source: + examples/body-documents/stylized-digitigrade-biped-authored-form.json + bytes 56984 + sha256 82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14 +profile table: + experiments/current-form-surface-preview/structural_profile_candidates.json + bytes 29970 + sha256 a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640 +profile transform source: + experiments/current-form-surface-preview/generate_structural_profile_sources.py +neutral projection source: + experiments/owned-root-assembly-successor/prepared_projection.py +neutral builder source: + experiments/owned-root-assembly-successor/build_owned_root.py +``` + +The exact existing semantics-bearing dependencies admitted from the post-seam +evidence are: + +```text +experiments/owned-root-assembly-successor/anatomy_gates.py + bytes 25674 sha256 0c4b5f7812141a4cd7c7107655e578044355dfef5dbda6574bbb63bc359a2ff4 +experiments/owned-root-assembly-successor/artifact_serialization.py + bytes 27977 sha256 3837928e4b987c65fd773e540f7db502f5d9a0b4c5940b95c923953754fdf7d4 +experiments/owned-root-assembly-successor/build_owned_root.py + bytes 78268 sha256 713cbf967bf2e0e233bae0c3506199fdc9a6ed71418edbd8dbf9b75beeee4045 +experiments/owned-root-assembly-successor/chart_lineage.py + bytes 18263 sha256 01fdd09e8e0bb6d31851f0c7af711d90b313e36a012dbe3d71415a0468c31efc +experiments/owned-root-assembly-successor/mesh_correctness.py + bytes 51035 sha256 4104b70e70e958a469125d1fff544e20fee44b784bf7915d8e724e63d4f39db1 +experiments/owned-root-assembly-successor/owned_root_surface.py + bytes 58732 sha256 c982d889fee30e2efea881b5725170740bc8afa2a883aa3dc4623941cd3e2a22 +experiments/owned-root-assembly-successor/prepared_projection.py + bytes 39646 sha256 58637097a350332db40368a027347ec395192880aa6ba4782c7d523e5b288190 +experiments/owned-root-assembly-successor/render_export.py + bytes 15933 sha256 bc251ea3f3f3cb1aa5ea66bfc4f79a82f86191e76bacb9a3c4f58e64883c4780 +experiments/current-form-surface-preview/generate_structural_profile_sources.py + bytes 54437 sha256 009be817cd2ec2db663b668fb5c9bdfa7296936283322e59d7a145e3d3cfec62 +experiments/current-form-surface-preview/structural_atomic_publish.py + bytes 10489 sha256 5e648b3a1a3519afdf0fc1f2f1ecfe6fe7f1c58130f71fd2c8ee4317e2f282b5 +experiments/current-form-surface-preview/surface_preview_launcher.sh + bytes 6582 sha256 3e18da2d361029a16558757d9727150d54c4d691b35c6a2a21b5b51cb7785190 +experiments/current-form-surface-preview/requirements.txt + bytes 49 sha256 69a3ce10b1f993d7913f02ca187eabb8d367abf214662ffa2132feacbdeedbec +``` + +The first eight records are the existing neutral runtime semantics used by the +activation. The profile generator and its direct local import own the admitted +profile-transform semantics. The launcher and requirements own the managed +runtime. Missing, additional, changed, or substituted records reject before +source admission. The post-seam stable-manifest identity additionally binds +the complete existing fifteen-file neutral implementation and test package; +this additive contract does not restate or weaken that closed identity. + +The four new additive files in section 9 are an exact allowlist. Because they +do not yet exist, this Proposed contract does not prehash them. At execution +each is admitted as a regular `file_record`; the exact sorted four-record array +is included in every profile-seed evidence file and final evidence. The +additive implementation MUST independently bind the exact activation-contract +SHA-256 in its public launcher and runner, in addition to validating the +sidecar. It MUST bind every fixed record above before source admission. The +sidecar grammar is section 12. + +The sole admitted profile order is: + +```text +0 standard_neutral_reference +1 compact_broad_short_limb_large_head +2 tall_narrow_long_legged +3 slender_long_limb +4 stocky_broad_chested +``` + +The profile table MUST have exactly its existing five rows in this order. Each +row MUST have exactly `dimension_scales`, `id`, `label`, and +`part_placements`; IDs and labels MUST be nonempty and unique. Transform +signatures, defined as the sorted complete placement map paired with the sorted +complete scale map, MUST be pairwise distinct. Selection is by one exact ID +match after the complete table has passed admission. Zero or multiple matches, +an unknown requested ID, index-only selection, label selection, reordered +rows, duplicate IDs or labels, or a transform-signature collision rejects. +The launcher itself requests no profile; it always executes all five in the +fixed order. + +The post-seam neutral baseline identity is: + +```text +exact local root: + /home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4 +comparison-report.json: + bytes 24640 + sha256 fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a +comparison-report.sha256: + bytes 89 + sha256 27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac +stable-manifest.json sha256, identically in seed 17 and seed 29: + 1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa +direct.png sha256: + b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed +lineage.png sha256: + 19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2 +runtime fingerprint sha256: + c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085 +``` + +The public launcher uses that exact absolute baseline path; it is not a caller +argument. The retained reports correctly preserve their original staging +paths, so the current path-bound `build_owned_root.validate_seed_bundle` and +`compare_two_seed_outputs.outer_publication_inventory` APIs MUST NOT be called +on this relocated publication and their private helpers MUST NOT be imported. + +Instead, before creating profile staging, the launcher and publisher perform +one exact activation-local, path-neutral byte admission. Using stable, +no-follow reads, reject symlinks, external hardlinks, special nodes, unexpected +or empty directories, size-cap violations, or anything except the exact outer +directories `seed-17`, `seed-29`, and `comparison`. Require exactly 47 unique +canonical roles from `build_owned_root.ARTIFACT_ROLES` in each seed and exactly +`comparison-report.json` plus its sidecar in `comparison`, for 96 files total. +The exact 45 stable roles are that 47-role tuple minus only `report.json` and +`report.sha256`, sorted by UTF-8 bytes. + +The comparison report bytes and sidecar MUST match the fixed hash above and +the existing closed comparison-report schema. Require outcome `success`; the +fixed runtime fingerprint; the exact comparator implementation record; exact +excluded roles `report.json` and `report.sha256`; seed bundles in order 17 then +29; and exactly 45 sorted, unique stable comparison records. Every stable +record MUST match the byte count and SHA-256 of the same current role in both +seed directories. Each seed-bundle record for its report, report sidecar, and +stable manifest MUST match the current file with its exact prefixed role; each +report sidecar MUST hash its report; and both stable manifests MUST have the +fixed identical hash above. + +Decode and validate the embedded neutral managed-test receipt path-neutrally: +the exact existing closed schema, contract/runtime/15-file implementation +identities, required-test IDs, exactly 134 executed passing tests, and all six +failure/skip counters zero. Validate each report as canonical closed JSON with +the correct seed, success outcome, runtime hash, stable-manifest reference, +phase order, and six all-pass gates. Historical path fields remain provenance: +require their own internal agreement, canonical absoluteness, correct seed +basename and staging relationship, but never equality to the relocated root. +After its fixed hash matches, validate each stable manifest as canonical closed +JSON with the design-contract identity, recipe, runtime, 15-file identity, and +five exact manifest references. Re-admit the complete 96-file baseline after +all payload comparisons and copies to close the read window. + +This proves narrowly that every retained byte is identical to the exact bytes +certified by the fixed pre-rename comparison report; it is not a general or +fresh semantic validator for arbitrary neutral output. A matching headline +hash without the complete admission above is insufficient. + +Standard-neutral regression equality covers exactly these 38 +implementation-independent payload roles and no others: the three baseline +surface PLYs, all 33 perturbation PLYs, `direct.png`, and `lineage.png`. +Manifests, prepared input, reports, sidecars, receipts, recipes, and other +records that bind implementation files are explicitly excluded. Each of the +38 exact records is taken from the admitted post-seam comparison report and +must match both baseline seeds. This contract does not claim that an +exact-five implementation or run exists. + +## 3. Closed profile-table admission + +The active transform rules are the exact data and selector semantics of the +frozen profile table and the active-five mode of +`generate_structural_profile_sources.py`. The table has exactly the five rows +above, exactly the existing 37 positive integer `dimension_scales` keys per +row, and exactly the existing 18 typed `part_placements` keys per row. Every +scale is an integer in `1..10000`; every placement is exactly three integers, +each in `-1000000000..1000000000`. The table's `dimension_groups`, +`placement_targets`, `preserved_controls`, `reference_edges`, and +`rotation_policy` objects are closed and are admitted exactly as implemented +by that source. No caller may supply a replacement transform table. + +Every source dimension MUST match exactly one dimension group, and every group +MUST match at least one source dimension. Every source part MUST match exactly +one placement target, and every profile's placement map MUST cover every and +only those targets. Typed address keys use exactly +`namespace|kind|comma-separated-anchors|role`; malformed or unknown addresses +reject. Source part, landmark, frame, and dimension selection uses the unique +normalized-address rules of design-contract sections 2.2 through 2.4. + +All source rotations in parts, frames, joints, sockets, and attachments MUST +be the authored identity rotation `[0,0,0,1]` and MUST be copied unchanged. +All landmark positions, frame transforms, joint frames, socket frames, and +attachment offsets MUST be copied unchanged. Part placements are replaced +only by the selected row's complete placement map. Attachment equations, +containment, the declared reference edge, bilateral neutral-pose symmetry, +axial centerline, and shoulder-root/neck-base alignment MUST pass after +replacement. Tail data is validated only because it is in the frozen table; +it is excluded before the 92-component projection and MUST NOT be constructed, +tested as geometry, rendered, or published by this activation. + +For `standard_neutral_reference`, every scale MUST equal `1000` and every +placement vector MUST equal its authored-source vector. Any difference rejects. + +## 4. Exact decimal projection into 92 numbers + +### 4.1 Numeric rule + +For each selected source dimension decimal token `v` in metres and its unique +selected integer-permille scale `s`, parse `v` as an exact finite positive +decimal, not binary64. Compute with sufficient decimal precision to make the +following multiplication exact: + +```text +scaled_millimetres = Decimal(v) * Decimal(s) +q = scaled_millimetres rounded to an integer with ROUND_HALF_EVEN +projected_metres_decimal = q / Decimal(1000) +``` + +Thus a discarded fractional millimetre less than `0.5` rounds down, greater +than `0.5` rounds up, and exactly `0.5` rounds to the even integer millimetre. +There is no preliminary binary64 conversion, `/1000` source reinterpretation, +double rounding, truncation, stochastic rounding, or profile exception. +Convert the final exact decimal metre value to finite Python `float` only after +quantization. It MUST round-trip through `Decimal(str(float_value))` to the +exact projected decimal; otherwise reject. Positive source dimensions that +quantize to zero, overflow, or become non-finite reject. + +Selected placement vectors are exact integer metres from the profile row. +Convert each used placement coordinate directly to finite Python `float`. +Local landmark coordinates remain the unchanged authored finite binary64 +metres. World sums use the exact containment chains and binary64 primitive +order in design-contract section 2.3. No placement value is scaled by a +dimension factor. + +The standard-neutral row executes this same rule. Its resulting 92-number +carrier MUST produce the exact 38 payload roles named in section 2 +byte-identically to both admitted post-seam baseline seed bundles. +Implementation-bearing manifests are not compared. Failure is a seam +regression and rejects the entire exact-five publication. + +No profile-local prepared semantic object, prepared-input artifact, or second +prepared schema exists in this activation. The runner validates the fixed +source and complete profile table, selects one exact row, applies the admitted +profile transform to an invocation-local copy, and projects that validated +copy directly into the existing `GeometryComponents` carrier while producing +the evidence records below. The profile-local copy is neither passed across +the geometry seam nor serialized. This direct projector is activation-local +selection/projection logic, not a new geometry or prepared representation. + +### 4.2 Component order and mapping + +The existing `GeometryComponents` carrier and its exact 92-ID order are +unchanged: + +```text +stations..C.x, .C.y, .C.z, .rL, .rA, .rP + for lower_pelvis, upper_pelvis, lower_abdomen, waist_abdomen, + upper_abdomen, lower_ribcage, upper_ribcage_shoulder, + neck_collar, neck_upper 54 +shoulders..axilla.x, .y, .z, peak.x, .y, .z, + arm_origin.x, .y, .z, start_lateral, start_up, + start_forward, shoulder_depth + for left, right 26 +hips..P_s.x, .y, .z, r_x, r_y, r_z + for left, right 12 + total 92 +``` + +Projection first creates a profile-local copy of the admitted source by the +rules above, then executes the existing unique selectors and aliases. The +closed mapping from the 92 components to profile data is: + +| component family | profile placement input | dimension-scale group | +| --- | --- | --- | +| pelvis/torso station `C` | complete owner containment chain | none; local landmark unchanged | +| pelvis/torso station `rL` | none | `body_profile_lateral` | +| pelvis/torso station `rA`,`rP` | none | `body_profile_depth` | +| neck station `C` | pelvis, torso, neck chain | none; local landmark unchanged | +| neck station `rL` | none | `neck_profile_lateral` | +| neck station `rA`,`rP` | none | `neck_profile_forward` | +| shoulder `axilla`,`peak` | pelvis, torso, selected upper-arm chain | none; local landmarks unchanged | +| shoulder `arm_origin` | pelvis, torso, selected upper-arm chain | none | +| shoulder `start_lateral` | none | `arm_profile_lateral` | +| shoulder `start_up` | none | `arm_profile_up` | +| shoulder `start_forward` | none | `arm_profile_forward` | +| shoulder `shoulder_depth` | none | `arm_shoulder` | +| hip `P_s` | pelvis and selected thigh chain | none; local landmark unchanged | +| hip `r_x` | none | `leg_profile_lateral` | +| hip `r_y` | none | `leg_profile_up` | +| hip `r_z` | none | `leg_profile_forward` | + +Every one of the 92 projected components has exactly one closed +`projection_binding_record`: + +```text +{ + prepared_component: one exact GeometryComponents ID, + derivation_id: one of + "profile.dimension-permille-half-even-mm.v1", + "profile.world-placement-axis-sum.v1", + "profile.world-landmark-axis-sum.v1", + source_addresses: nonempty sorted unique address_tuple array, + source_pointers: nonempty sorted unique canonical RFC-6901 pointer array, + profile_pointers: nonempty sorted unique canonical RFC-6901 pointer array +} +``` + +The source pointers are exactly the design-contract section-2.4 pointers. For +a scaled dimension, `profile_pointers` contains exactly +`/profiles//dimension_scales/`. For a world placement +sum it contains the matching pointer for every placement in the fixed chain: +`/profiles//part_placements//`. +For a world landmark sum it contains those placement pointers plus the source +landmark pointer remains in `source_pointers`; no profile landmark pointer is +invented. A dimension record retains its source dimension pointer and adds its +one scale pointer. RFC-6901 escaping is `~` to `~0` and `/` to `~1`; profile +indices and axis indices use unsigned base-10 without leading zeroes. Arrays +sort by UTF-8 bytes. Empty, duplicate, missing, extra, differently grouped, or +pointer-inconsistent bindings reject. + +The projected value crosses the geometry seam as only +`GeometryComponents(tuple_of_92_finite_binary64_values)`. Geometry MUST consume +only that existing 92-number geometry carrier. It MUST never receive or read +the authored JSON, generated profile JSON, profile table, prepared semantic +object, profile ID, index, label, pointer, provenance, or selection result. +The surface API accepts that carrier and nothing profile-shaped. Static and +managed tests MUST prove that those forbidden objects cannot be passed to or +observed by `owned_root_surface.py`, anatomy gates, mesh checks, subdivision, +causality, PLY serialization, or rendering. Dispatch on a projected numeric +value to infer a profile is equally forbidden. + +## 5. Unchanged geometry and per-profile gates + +For each profile and each seed, construction executes the design contract +without alteration: exact topology ID +`owned-root-58-cell-120-control-104-quad.v1`; 120 controls; 104 base quads; +the same eight nonempty domains, seven junctions, five ports, eight formula +IDs, nine special-case IDs, two subdivision levels, ownership and chart +catalogs, thresholds, and renderer ID +`owned-root-raster-pillow-11.1.0.v1`. Level counts remain exactly: + +```text +level 0: 120 vertices, 227 edges, 104 quads, 208 triangles, 38 boundary edges +level 1: 451 vertices, 870 edges, 416 quads, 832 triangles, 76 boundary edges +level 2: 1737 vertices, 3404 edges, 1664 quads, 3328 triangles, 152 boundary edges +``` + +Every profile independently runs the six ordered seed-local groups in design +contract section 13. Every exact gate and threshold inventory remains closed: +122 structural, 144 continuity, 78 anatomy, and 12 intersection gate results, +with 357 threshold records. Every result MUST pass its unchanged threshold. +No profile aggregate, average, ranking, exception, relaxed threshold, or +visual judgment can replace one failed gate. + +Randomness is forbidden. Nevertheless, every profile MUST execute in two +fresh processes, once with literal `PYTHONHASHSEED=17` and once with literal +`PYTHONHASHSEED=29`. Missing, ambient, `0`, or any other seed rejects. The two +seeds are a hash-order determinism challenge only and MUST NOT be consumed as +random or geometry input. For each profile, every stable value and ephemeral +artifact byte sequence MUST be identical across seeds, including the ordered +92 values, projection bindings, three surface PLYs, 33 +perturbation PLYs, gate data, causality data, and two PNGs. Run-local paths, +timestamps, and timings are excluded from equality but remain validated. + +## 6. Exact 33 copied-component causality gates + +For every profile under both seeds, independently execute all 33 existing +must-affect parameters in this exact order and with these exact selectors: + +```text +left.r_y -> hips.left.r_y +right.r_y -> hips.right.r_y +lower_pelvis.L_y -> stations.lower_pelvis.C.y +lower_pelvis.C_z -> stations.lower_pelvis.C.z +left.r_x -> hips.left.r_x +right.r_x -> hips.right.r_x +lower_pelvis.R_x -> stations.lower_pelvis.rL +left.r_z -> hips.left.r_z +right.r_z -> hips.right.r_z +lower_pelvis.R_f -> stations.lower_pelvis.rA +lower_pelvis.R_b -> stations.lower_pelvis.rP +left.thigh_start_x -> hips.left.P_s.x +left.thigh_start_y -> hips.left.P_s.y +left.thigh_start_z -> hips.left.P_s.z +right.thigh_start_x -> hips.right.P_s.x +right.thigh_start_y -> hips.right.P_s.y +right.thigh_start_z -> hips.right.P_s.z +neck_collar.C_y -> stations.neck_collar.C.y +neck_collar.rL -> stations.neck_collar.rL +neck_upper.C_y -> stations.neck_upper.C.y +neck_upper.rL -> stations.neck_upper.rL +left.axilla_x -> shoulders.left.axilla.x +left.axilla_y -> shoulders.left.axilla.y +right.axilla_x -> shoulders.right.axilla.x +right.axilla_y -> shoulders.right.axilla.y +left.peak_y -> shoulders.left.peak.y +right.peak_y -> shoulders.right.peak.y +left.start_lateral -> shoulders.left.start_lateral +right.start_lateral -> shoulders.right.start_lateral +left.start_up -> shoulders.left.start_up +right.start_up -> shoulders.right.start_up +left.shoulder_depth -> shoulders.left.shoulder_depth +right.shoulder_depth -> shoulders.right.shoulder_depth +``` + +Each perturbation copies that profile's validated 92-value tuple, adds exactly +binary64 `+0.01 m` (`float.fromhex("0x1.47ae147ae147bp-7")`) to the one selected +component, proves by exact tuple restoration that no other component changed, +wraps the copied tuple in a fresh identity-free `GeometryComponents` carrier, +and builds a fresh level-2 surface. The perturbation does not modify the source +or profile table and does not re-run profile projection with a changed scale. + +For every perturbation, all design-contract section-9 obligations remain +exact: nonempty analytic predicted support; predicted and observed support +sets and `CKSUPPORTv1` hashes equal; maximum movement at least +`0x1.d14e3bcd35a85p-11 m`; off-support movement at most the unchanged `T`; +436 supported vertices for each thigh-start-x case; unchanged topology, IDs, +formulas, ownership, lineage, and quads; and level-2 PLY bytes different from +that profile's baseline. Every perturbation PLY is ephemeral, capped at 2 MiB, +hashed into stable evidence, compared across seeds, and removed before final +publication. There are exactly `5 * 2 * 33 = 330` perturbation executions and +no committed perturbation binary. + +## 7. Activation-local bundle and evidence schemas + +All JSON uses the design-contract section-10.1 canonical JSON and binary64 +rules: closed schema before use, duplicate-key rejection, schema-aware zero +coercion, exact canonical re-encoding, no BOM, and no trailing LF. Hashes are +lowercase SHA-256 of exact raw bytes. `file_record`, `manifest_ref`, +`gate_result`, `threshold_record`, and `timing_record` retain their existing +meanings. + +### 7.0 Additive managed-test receipt + +Before any profile build, `exact_five_runner.py` executes its private +`--internal-managed-tests --receipt ABSENT_CANONICAL_PATH` mode under literal +`PYTHONHASHSEED=0`. The receipt is canonical JSON with schema +`owned-root-assembly-successor-exact-five-managed-test-receipt.v1` and exactly: + +```text +{ + schema, outcome: exactly "success", + invocation: { + environment: exactly ["PYTHONHASHSEED=0"], + implementation_role: exactly + "experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py", + mode: exactly "managed-tests" + }, + activation_contract: file_record, + design_contract: file_record, + existing_dependencies: exact sorted 12-file dependency array from section 2, + additive_implementation_files: exact sorted four-file file_record array, + runtime: exact design-contract runtime_fingerprint, + runtime_fingerprint_sha256: hex64, + executed_test_ids: sorted nonempty unique string array, + required_test_ids: exact sorted array listed below, + results: { + tests_run: exactly the executed_test_ids count, + failures: 0, errors: 0, skipped: 0, + expected_failures: 0, unexpected_successes: 0 + } +} +``` + +The exact required IDs are: + +```text +test_exact_five_activation.ExactFiveActivationTests.test_all_33_selectors_copy_one_component +test_exact_five_activation.ExactFiveActivationTests.test_atomic_failure_has_no_partial_publication +test_exact_five_activation.ExactFiveActivationTests.test_decimal_half_even_boundaries +test_exact_five_activation.ExactFiveActivationTests.test_final_evidence_schema_and_19_file_closure +test_exact_five_activation.ExactFiveActivationTests.test_geometry_receives_only_components +test_exact_five_activation.ExactFiveActivationTests.test_neutral_projection_preserves_38_payloads +test_exact_five_activation.ExactFiveActivationTests.test_profile_seed_bundle_schema_and_closure +test_exact_five_activation.ExactFiveActivationTests.test_profile_table_closed_and_exact_order +test_exact_five_activation.ExactFiveActivationTests.test_profile_table_rejects_duplicate_keys_and_signatures +test_exact_five_activation.ExactFiveActivationTests.test_projection_has_exact_92_bindings +test_exact_five_activation.ExactFiveActivationTests.test_seed_dispatch_is_exact +test_exact_five_activation.ExactFiveActivationTests.test_static_identity_and_allowlist +``` + +Every required ID occurs exactly once in `executed_test_ids`; additional +discovered IDs are allowed only when they are also recorded, unique, and pass. +The runner compares all fixed and implementation identities before and after +test execution. Any changed identity, missing required ID, nonzero result, +skip, expected failure, unexpected success, malformed receipt, or receipt +path that already exists rejects before any profile output is created. +The launcher validates and retains the exact canonical receipt bytes. The +publisher independently reads the unchanged invocation-owned file, validates +the same closed object and identities, embeds the complete decoded object and +its raw-byte SHA-256 in final evidence, and never rewrites the receipt. + +### 7.1 Exact 42-file profile/seed bundle + +Each of the ten profile/seed executions seals exactly 42 files: + +```text +surface-level-0.ply +surface-level-1.ply +surface-level-2.ply +the exact 33 perturb-.ply roles from section 6, replacing every + "." in the parameter ID with "-" and changing no underscore +direct.png +lineage.png +profile-seed-evidence.json +profile-seed-evidence.sha256 +run-report.json +run-report.sha256 +``` + +The first 38 roles are the payload set. The stable cross-seed set is exactly +those 38 payloads plus `profile-seed-evidence.json` and +`profile-seed-evidence.sha256`, for 40 roles. `run-report.json` and +`run-report.sha256` are the only excluded run-local roles. The evidence has no +seed, path, timestamp, timing, or temporary value, so its bytes and sidecar +MUST match across seeds. + +`profile-seed-evidence.json` has schema +`owned-root-assembly-successor-profile-seed-evidence.v1` and exactly: + +```text +{ + schema, outcome: exactly "success", + activation_contract: file_record, + design_contract: file_record, + source: file_record, + profile_table: file_record, + existing_dependencies: exact sorted 12-file dependency array listed in + section 2, + additive_implementation_files: exact sorted four-file file_record array, + runtime: exact design-contract runtime_fingerprint, + runtime_fingerprint_sha256: hex64, + profile_id, profile_index, + selection: {profile_pointer, profile_row_sha256, + dimension_scales_sha256, part_placements_sha256}, + projected_values: array of exactly 92 projected_value_record in + GeometryComponents order, + projected_carrier: {bytes, sha256} for the canonical 92-value array, + projection_bindings: array of exactly 92 projection_binding_record sorted + by prepared_component, + levels: array in level order 0,1,2 of exactly { + level, counts: level_count_record, + coordinate_bytes, coordinate_sha256, + triangle_index_bytes, triangle_index_sha256, + ply: file_record + }, + thresholds: sorted array of exactly 357 threshold_record, + gates: { + structural: sorted 122 gate_result array, + continuity: sorted 144 gate_result array, + anatomy: sorted 78 gate_result array, + intersection: sorted 12 gate_result array + }, + causality: sorted array of exactly 33 causality_evidence records, + renders: { + renderer_id, render_config_sha256, visibility_sha256, + direct: file_record, lineage: file_record, + same_surface_positions_sha256, same_surface_triangles_sha256 + }, + payloads: sorted array of exactly 38 file_record, + invariants: { + topology_equal_to_neutral: exactly true, + formulas_equal_to_neutral: exactly true, + tunables_equal_to_neutral: exactly true, + thresholds_equal_to_neutral: exactly true, + gate_inventory_equal_to_neutral: exactly true, + subdivision_equal_to_neutral: exactly true, + ownership_equal_to_neutral: exactly true, + causality_rules_equal_to_neutral: exactly true, + renderer_equal_to_neutral: exactly true + } +} +``` + +A `projected_value_record` is exactly +`{prepared_component,value:binary64,source_pointers,profile_pointers}` and MUST +agree with its binding. `projected_carrier` is exactly the byte count and +SHA-256 of canonical JSON encoding of the array of the 92 `value` fields in +`GeometryComponents` order. The runner computes it from the carrier; the +publisher reconstructs those bytes from `projected_values`, validates the +record, and therefore compares the exact carrier across seeds through the +already-stable evidence file. It is not a file record and adds no bundle role. +A `causality_evidence` record is exactly the existing +design-contract perturbation record, including its payload `file_record`. +The three level records expose all PLY, coordinate, and triangle-index hashes. +The evidence exposes every projection/source pointer, all 92 values, all gate +results, all 33 causality records, render identities, and the complete payload +inventory without embedding binary bytes. + +The profile/seed `run-report.json` has schema +`owned-root-assembly-successor-profile-seed-run-report.v1`. It contains exactly +the profile ID and index, seed 17 or 29, literal private invocation, output and +staging paths, interpreter path, UTC start/finish values, the seven ordered +phase timings `identity`, `selection-projection`, `catalogs`, +`geometry-gates`, `causality`, `serialization`, and `total-before-seal`, +runtime fingerprint hash, a `manifest_ref` to +`profile-seed-evidence.json`, and the six existing all-pass seed gate results. +Its sidecar uses section 12. The report MUST NOT be referenced by evidence. + +### 7.2 Cross-seed and post-seam comparison + +For each profile, the publisher compares the two closed 42-file bundles and +requires byte equality of exactly the 40 stable roles. It validates both run +reports and sidecars separately and excludes them from equality. A comparison +record is exactly `{role_path,bytes,sha256}` and records the one common byte +count and hash after both seed files have been proven equal. + +For standard neutral only, the publisher additionally compares exactly the 38 +payload records against the same roles in seed 17 and seed 29 of the admitted +post-seam baseline. Every byte count and hash MUST agree. It never compares the +activation evidence, sidecars, reports, or any neutral manifest. + +### 7.3 Final exact-five evidence and run report + +`exact-five-evidence.json` has schema +`owned-root-assembly-successor-exact-five-evidence.v1` and exactly: + +```text +{ + schema, outcome: exactly "success", + activation_contract: file_record, + design_contract: file_record, + source: file_record, + profile_table: file_record, + existing_dependencies: exact sorted 12-file dependency array listed in + section 2, + additive_implementation_files: exact sorted four-file file_record array, + managed_tests: { + receipt_sha256: SHA-256 of the exact canonical receipt bytes, + receipt: complete decoded section-7.0 managed-test receipt object + }, + neutral_baseline: { + absolute_path: exactly the section-2 path, + comparison_report: file_record, + stable_manifest_sha256: hex64, + runtime_fingerprint_sha256: hex64, + payload_comparisons: sorted array of exactly 38 comparison_record + }, + runtime: exact design-contract runtime_fingerprint, + runtime_fingerprint_sha256: hex64, + profile_order: exact five-ID array, + profiles: array in profile order of exactly five { + profile_id, profile_index, + evidence: complete decoded profile-seed-evidence object, + stable_cross_seed_comparisons: sorted array of exactly 40 comparison_record, + neutral_payload_comparisons: exactly 38 comparison_record for profile 0, + exactly empty for profiles 1..4 + }, + payloads: sorted array of exactly 15 public file_record +} +``` + +The final evidence contains only backward references to the 15 already sealed +public payloads and the already completed managed-test receipt. It does not +contain a record for itself, its sidecar, the final run report, or the report +sidecar. `managed_tests.receipt_sha256` MUST match the canonical bytes of its +embedded complete receipt object before the temporary receipt is removed. The +embedded profile evidence preserves all +projection pointers, 92 values, three-level hashes, gate results, causality +records with ephemeral perturbation PLY hashes, render identities, and +comparisons after the profile/seed bundles are removed. Its +managed-test receipt does not claim publication or passage of the section-11 +gate; the launcher establishes those after the final rename. + +The final `run-report.json` has schema +`owned-root-assembly-successor-exact-five-run-report.v1` and exactly: + +```text +{ + schema, outcome: exactly "success", + literal_invocation: {environment: exactly ["PYTHONHASHSEED=0"], + argv: exact public argv array}, + output_path, staging_path, python_executable_path: canonical absolute paths, + neutral_baseline_path: exactly the section-2 absolute path, + started_utc, finished_utc: fixed-format UTC strings, + timings: ordered nonnegative timing_record array for identity, managed-tests, + baseline-admission, profile-seed-builds, comparison, + staging-seal, total-before-seal, + activation_contract_sha256, design_contract_sha256, + runtime_fingerprint_sha256: hex64, + evidence: manifest_ref for exact-five-evidence.json, + evidence_sidecar: file_record for exact-five-evidence.sha256, + payloads: sorted array of exactly 15 file_record, + profile_seed_runs: array in profile order and seed order of exactly ten { + profile_id, seed, outcome:"success", evidence_sha256:hex64}, + gates: array in exact ID order of exactly 21 all-pass Boolean gate_result + records +} +``` + +The final report is created only after the evidence sidecar exists and points +backward to the payloads, evidence, and evidence sidecar. It contains no +record for itself or its own sidecar. Run-local values occur only in reports. +The 21 gate IDs are `exact-five.run.01.identity`, +`exact-five.run.02.managed-tests`, +`exact-five.run.03.baseline-admission`, IDs 04 through 13 for the ten +profile/seed builds in profile order and seed order 17 then 29, IDs 14 through +18 for the five profile cross-seed comparisons in profile order, +`exact-five.run.19.standard-neutral-payload-equality`, +`exact-five.run.20.evidence-graph`, and +`exact-five.run.21.staging-seal`. Each observes integer 1 against +`gate.boolean-pass`. None claims that the later launcher-owned rename has +already occurred. + +## 8. Exact public inventory and acyclic publication graph + +The publisher's successful staging root contains exactly 19 regular files and +no symlinks, hardlinks, sockets, devices, FIFOs, empty directories, or +additional entries: + +```text +standard_neutral_reference/surface-level-2.ply +standard_neutral_reference/direct.png +standard_neutral_reference/lineage.png +compact_broad_short_limb_large_head/surface-level-2.ply +compact_broad_short_limb_large_head/direct.png +compact_broad_short_limb_large_head/lineage.png +tall_narrow_long_legged/surface-level-2.ply +tall_narrow_long_legged/direct.png +tall_narrow_long_legged/lineage.png +slender_long_limb/surface-level-2.ply +slender_long_limb/direct.png +slender_long_limb/lineage.png +stocky_broad_chested/surface-level-2.ply +stocky_broad_chested/direct.png +stocky_broad_chested/lineage.png +exact-five-evidence.json +exact-five-evidence.sha256 +run-report.json +run-report.sha256 +``` + +The one-way final hash graph is exact: + +```text +managed-test receipt + 15 payloads -> exact-five-evidence.json +exact-five-evidence.json -> exact-five-evidence.sha256 +15 payloads + evidence + evidence sidecar -> run-report.json +run-report.json -> run-report.sha256 +``` + +No node hashes itself or a descendant. The launcher re-admits the exact graph +and 19-file closure after the publisher seals staging. PLY and PNG bytes remain +unchanged from design-contract sections 10.4 and 10.5. Each PNG is one +metadata-free 512x1536 RGB image containing front, side, and 45-degree panels +in that order; direct and lineage images use identical level-2 positions, +triangles, visibility, and camera calculation. + +All 15 payloads remain external/local under the repository artifact policy and +MUST NOT be committed by this activation. The ten 42-file profile/seed +bundles, levels 0 and 1, 330 perturbation PLYs, and managed-test receipt are +invocation-owned ephemeral material. They remain until the final evidence and +report are sealed, then the launcher removes only its exact staging inputs +before publication. A cleanup or closed-inventory failure rejects publication. + +## 9. Entrypoints and ordered execution + +The future sibling implementation package is exactly +`experiments/owned-root-assembly-successor-exact-five/`; placing executable +files under the neutral package is forbidden because that package has its own +closed 15-file implementation allowlist. The exact additive allowlist is: + +```text +experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh +experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py +experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py +experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py +``` + +This is the complete sibling package source inventory. A gallery adapter is a +later, separate implementation and is not admitted, predeclared, or counted by +this contract. + +The only public command, from repository root, is: + +```bash +PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --output ABSENT_PATH +``` + +`ABSENT_PATH` MUST be a canonical absolute path without empty, `.` or `..` +components. It and every invocation-owned sibling staging path MUST be absent. +The launcher accepts exactly those two arguments in that order, requires +literal seed `0`, uses only the fixed section-2 baseline path, binds all +identities and the exact four-file allowlist before source admission, and +creates no output on failure. + +The launcher uses the existing pinned +`surface_preview_launcher.sh` and requirements/runtime-v2 environment. In an +invocation-owned absent staging root it performs, in order: + +1. Invoke `exact_five_runner.py --internal-managed-tests --receipt + ` under `PYTHONHASHSEED=0`; require the exact + section-7.0 canonical success receipt and no skipped, expected-failure, or + unexpected-success result. +2. Fully admit the retained neutral baseline. +3. For each profile in exact order, invoke `exact_five_runner.py --profile + --output ` first with + `PYTHONHASHSEED=17`, then with `PYTHONHASHSEED=29`. +4. Invoke `exact_five_publisher.py` under `PYTHONHASHSEED=0` with exactly the + fixed baseline root, ten sealed sibling bundle paths in fixed profile/seed + order, the managed-test receipt, and one absent staging-publication path. + These are private fixed-shape arguments, not a public interface. +5. The publisher re-admits every bundle, validates all schemas and gates, + performs every cross-seed and neutral-baseline comparison, creates and seals + the exact 19-file staging tree, and re-admits that sealed tree. It returns + success without deleting inputs or publishing the final path. +6. The launcher independently re-admits the sealed staging tree, removes only + its exact invocation-owned ephemeral bundle and receipt paths, verifies that + cleanup did not alter the sealed tree, performs the sole final no-replace + rename to `ABSENT_PATH`, and returns success only when that rename succeeds. + +The runner owns profile-table admission, unique selection, decimal projection, +the identity-free 92-number handoff, unchanged geometry execution, all gates, +and sealing one closed ephemeral 42-file bundle. Its private managed-test mode +accepts only literal seed 0 and the exact section-7.0 arguments. Its private +profile-build mode accepts only one of the five exact IDs and only seed 17 or +29. It cannot publish public evidence or invoke the publisher. The publisher +cannot construct geometry, project a +profile, rerun a failed gate, rewrite a bundle, or choose a preferred seed; it +only admits, compares, summarizes, seals, and re-admits the staging +publication. It cannot rename to the public target or clean staging. The +launcher alone owns final cleanup and publication. All three independently +bind the contract, fixed sources, implementation files, and runtime. + +The managed tests MUST include closed-table rejection, duplicate-key +rejection, unique profile/source selection, all 92 binding/pointer mappings, +decimal half-even boundary cases, neutral projection equality, identity-only +geometry API shape, both exact seeds for all profiles, all 33 copied-component +selectors, evidence schema/cardinalities, exact 19-file closure, sidecar +grammar, and atomic no-partial-output failure tests. Tests do not replace any +runtime gate. + +## 10. Resource and cardinality caps + +These are hard maxima, not implementation targets: + +```text +profiles: exactly 5 +hash-seed processes: exactly 2 per profile, values 17 and 29 +ephemeral seed bundles: exactly 10, each exactly 42 files +stable cross-seed roles per profile: exactly 40 +payload roles per profile/seed: exactly 38 +geometry components: exactly 92 per profile +projection bindings: exactly 92 per profile +geometry gate results: exactly 356 per profile per seed +threshold records: exactly 357 per profile per seed +causality perturbations: exactly 33 per profile per seed +perturbation executions: exactly 330 +published files: exactly 19 +published level-2 PLYs: exactly 5, <=2 MiB each +published PNGs: exactly 10, 786432 pixels and <=2 MiB each +ephemeral surface or perturbation PLY: <=2 MiB each +exact-five-evidence.json: <=16 MiB +run-report.json: <=2 MiB +each sidecar: <=256 bytes +each staging evidence file or receipt: <=16 MiB +complete staging root: <=512 MiB +complete published root: <=32 MiB +runtime JSON: <=64 KiB +each additive implementation file: <=4 MiB +additive non-test physical LOC: <=1600 +additive test physical LOC: <=1200 +``` + +Physical LOC is measured with GNU `wc -l` over the exact allowlist, separating +the first three files from the test file. Existing neutral implementation LOC +is not charged again and MUST remain byte-identical to its admitted post-seam +identity throughout an invocation. There is no wall-clock or RSS pass gate. + +## 11. Technical-to-visual gate + +The exact technical-to-visual gate passes only after the publisher has sealed +and re-admitted one exact 19-file staging root and the launcher has atomically +published that unchanged root, with all of the following true: fixed +identities match; managed tests pass; all five profiles pass every unchanged +technical gate under both seeds; all 33 causality gates pass for every +profile/seed; all 40-role cross-seed comparisons are byte-equal; standard neutral is +byte-equal to all 38 payload roles in both admitted post-seam baseline seed +bundles; the public evidence is complete and canonical; and the direct and +lineage renders are proven to use the same evaluated surface. + +Only then may a gallery present the five profiles in section-2 order, standard +neutral first. For each profile it MUST show the published direct final skin +and same-surface lineage diagnostic, preserving the fixed front, side, and +three-quarter panels. It may not crop away a panel, substitute a mesh, add an +x-ray structure, relight, smooth, recolour the direct skin, or regenerate an +image. The exact files and hashes presented MUST be those in +`exact-five-evidence.json`. + +The resulting checkpoint is Ben's retained visual judgment of the exact +artifact set: whether the neck, shoulder/axilla, pelvic-wrap, and downward +thigh-root cues remain credible across all five profiles and whether this +representation is worth extending. Internal metrics, model reviews, technical +gate success, or one convincing profile do not substitute for that judgment. +No merge, product promise, architecture acceptance, distal anatomy, tail work, +or further representation work follows without Ben's explicit direction. + +## 12. Sidecars and disposition + +Every sidecar is one ASCII, LF-terminated `sha256sum` line with exactly two +spaces: + +```text +<64 lowercase hex> +``` + +The repository sidecar role is exactly +`experiments/owned-root-assembly-successor/exact-five-activation-contract.md`. +Each ephemeral bundle sidecar names exactly `profile-seed-evidence.json` or +`run-report.json`. Final sidecars name exactly `exact-five-evidence.json` and +`run-report.json`. No BOM, extra line, absolute path, or alternate spelling is +admitted. + +This Proposed document defines an implementation-ready, freeze-pending +activation protocol. It does not +claim that the sibling implementation, post-seam exact-five evidence, gallery, +or human acceptance exists. Any need to change neutral geometry, introduce a +profile-specific rule, exceed a cap, alter the 19-file inventory, or weaken a +gate rejects this activation and returns to the main thread for a new recorded +decision. diff --git a/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 b/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 new file mode 100644 index 0000000..39c741e --- /dev/null +++ b/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 @@ -0,0 +1 @@ +ee97f8a5677b4b43abfeb9a3603b81788bff3bfc3b014188ecb50367f97e8542 experiments/owned-root-assembly-successor/exact-five-activation-contract.md diff --git a/experiments/owned-root-assembly-successor/owned_root_surface.py b/experiments/owned-root-assembly-successor/owned_root_surface.py index 0d85f16..c784557 100644 --- a/experiments/owned-root-assembly-successor/owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/owned_root_surface.py @@ -415,6 +415,7 @@ def propagate_junction_tags(mesh, junction): if junction not in JUNCTIONS: raise ValueError("unknown junction") trace = _junction_evidence()[junction]["trace"]; meshes = (mesh.cage, *mesh.levels) if hasattr(mesh, "cage") else tuple(mesh) if isinstance(mesh, (list, tuple)) else (mesh,) if not meshes or len(meshes) > 3: raise ValueError("junction tag propagation requires levels 0 through 2") + if type(meshes[0]) is not Mesh or meshes[0].level != 0: raise ValueError("junction tag propagation requires a level-0 mesh as the first sequence item") axes = JUNCTION_INFO[junction][1][1]; index = {c: i for i, c in enumerate(meshes[0].control_ids)} cycle = tuple(index[c] for c in trace); selected = {tuple(sorted((a, cycle[(i + 1) % len(cycle)]))) for i, a in enumerate(cycle)} tags = {i: tuple((COORDINATE_BY_CONTROL[meshes[0].control_ids[i]][{"i": 0, "j": 1, "k": 2}[axis]], 1) for axis in axes) for i in {v for edge in selected for v in edge}} diff --git a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py index 43ebf27..29cd6aa 100644 --- a/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py +++ b/experiments/owned-root-assembly-successor/tests/test_owned_root_surface.py @@ -30,7 +30,6 @@ def test_independent_catalog_counts_and_boundary_inventory(self): self.assertEqual(len(report.extraordinary_controls), 20) self.assertEqual(len(surface.JUNCTION_INFO), 7) self.assertEqual(len(surface.PORT_INFO), 5) - expected_ports = { "port.neck": ("c057", "c079", "c080", "c081", "c059", "c058"), "port.left_arm": ("c009", "c012", "c014", "c015", "c016", "c013", "c011", "c010"), @@ -39,7 +38,6 @@ def test_independent_catalog_counts_and_boundary_inventory(self): "port.right_thigh": ("c060", "c061", "c062", "c083", "c105", "c104", "c103", "c082"), } self.assertEqual({key: value[2] for key, value in surface.PORT_INFO.items()}, expected_ports) - def test_public_surface_boundary_has_no_chart_or_sample_outputs(self): ids, faces, ports = surface.symbolic_topology() self.assertEqual((len(ids), len(faces), len(ports)), (120, 104, 5)) @@ -53,7 +51,6 @@ def setUpClass(cls): cls.prepared = prepared() cls.geometry = prepared_projection.project_geometry(cls.prepared) cls.evaluation = surface.evaluate(cls.geometry) - def test_formula_candidates_use_numeric_boundary_and_exact_dispatch(self): with patch.object(surface, "validate_geometry_components", wraps=surface.validate_geometry_components) as admitted: cage = surface.build_cage(self.geometry) @@ -69,7 +66,6 @@ def test_formula_candidates_use_numeric_boundary_and_exact_dispatch(self): self.assertNotIn("hips.left.P_s.x", records["c003"]["geometry_dependencies"]) self.assertIn("hips.left.P_s.x", records["c020"]["geometry_dependencies"]) self.assertEqual(set(cage.formula_ids), set(surface.FORMULAS)) - def test_surface_rejects_prepared_identity_and_nonexact_numeric_carriers(self): source = (HERE / "owned_root_surface.py").read_text(encoding="utf-8") self.assertNotIn("prepared_projection", source); self.assertNotIn("_admit_surface", source); self.assertNotIn("perturb", source) @@ -137,6 +133,10 @@ def test_analytic_derivatives_propagate_and_support_is_exact(self): self.assertEqual(len(surface.predicted_support(self.geometry, "hips.left.P_s.x")), 436) self.assertEqual(len(surface.predicted_support(self.geometry, "hips.right.P_s.x")), 436) with self.assertRaises(ValueError): surface.predicted_support(self.geometry, "outside.component") + def test_standalone_level1_junction_tags_raise_value_error(self): + self.assertRaisesRegex(ValueError, "level-0 mesh", surface.propagate_junction_tags, self.evaluation.levels[0], surface.JUNCTIONS[0]); self.assertRaisesRegex(ValueError, "level-0 mesh", surface.propagate_junction_tags, self.evaluation.levels, surface.JUNCTIONS[0]) + def test_standalone_level2_junction_tags_raise_value_error(self): + with self.assertRaisesRegex(ValueError, "level-0 mesh"): surface.propagate_junction_tags(self.evaluation.levels[1], surface.JUNCTIONS[0]) def test_dual_abs_zero_preserves_exact_fraction_subgradient(self): result = abs(surface._Dual(0.0, surface.Fraction(7, 9))); self.assertEqual((result.value, result.derivative), (0.0, surface.Fraction(0))); self.assertIs(type(result.derivative), surface.Fraction) def test_all_33_numeric_perturbations_match_exact_analytic_support(self): From f3d7a5c897c5ee1c8de49c682d6c2cf8203ab859 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 14:47:59 +1200 Subject: [PATCH 18/38] Freeze exact-five execution contract --- docs/project/status.md | 14 +- .../owned-root-assembly-successor/README.md | 16 +- .../exact-five-activation-contract.md | 187 +++++++++++++----- .../exact-five-activation-contract.sha256 | 2 +- 4 files changed, 156 insertions(+), 63 deletions(-) diff --git a/docs/project/status.md b/docs/project/status.md index 5d2060f..ed53862 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -48,10 +48,11 @@ blockers. The bounded implementation phase completed at `correction_round=0`; the builder must reject a missing or mismatched design-contract identity. -The exact neutral evidence baseline is commit +The retained pre-seam neutral evidence baseline is commit `2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the 96-file publication in logical local cache -`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. It records 121 +`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. That historical +publication records 121 tests with zero failures, errors, or skips; the seed gates and cross-seed comparison passed. The exact `comparison-report.json` SHA-256, obtainable from the exact sidecar, is @@ -82,9 +83,12 @@ both the seam and pre-seam baselines. The current comparison report SHA-256 is and the current stable-manifest SHA-256 is `1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. -Next is the separately SHA-bound activation contract and sibling exact-five -runner/publisher. Do not add a private-internal wrapper, duplicate geometry, -profile-aware branching, geometry correction, or a new representation. +The exact-five activation contract is frozen at SHA-256 +`a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49`; +two independent Sol reviews returned `FREEZE` with no blockers. Next is its +sibling exact-five runner/publisher. Do not add a private-internal wrapper, +duplicate geometry, profile-aware branching, geometry correction, or a new +representation. The named human checkpoint remains Ben's later exact-five gallery appraisal of the owned-root assembly, but only after standard neutral passes the unchanged diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 6925389..927fa25 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -49,10 +49,11 @@ the focused audit required here. ## Current execution state -The exact neutral evidence baseline is commit +The retained pre-seam neutral evidence baseline is commit `2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the 96-file publication in logical local cache -`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. It records 121 +`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. That historical +publication records 121 tests with zero failures, errors, or skips; the seed gates and cross-seed comparison passed. @@ -87,9 +88,12 @@ both the seam and pre-seam baselines. The current comparison report SHA-256 is and the current stable-manifest SHA-256 is `1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. -Next is the separately SHA-bound activation contract and sibling exact-five -runner/publisher. Do not add a private-internal wrapper, duplicate geometry, -profile-aware branching, geometry correction, or a new representation. +The exact-five activation contract is frozen at SHA-256 +`a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49`; +two independent Sol reviews returned `FREEZE` with no blockers. Next is its +sibling exact-five runner/publisher. Do not add a private-internal wrapper, +duplicate geometry, profile-aware branching, geometry correction, or a new +representation. ## Protocol @@ -569,7 +573,7 @@ does not authorize promotion into production code or canonical architecture. ## Results, limitations, and conclusion The standard-neutral execution completed at `correction_round=0` against the -exact baseline above. Its 96-file publication, 121-test clean result, passed +retained pre-seam baseline above. Its 96-file publication, 121-test clean result, passed seed gates, and passed cross-seed comparison permit proceeding to the unchanged exact-five gate. No exact-five executable or gallery exists yet. diff --git a/experiments/owned-root-assembly-successor/exact-five-activation-contract.md b/experiments/owned-root-assembly-successor/exact-five-activation-contract.md index d3e3320..aaea6b6 100644 --- a/experiments/owned-root-assembly-successor/exact-five-activation-contract.md +++ b/experiments/owned-root-assembly-successor/exact-five-activation-contract.md @@ -141,8 +141,6 @@ fixed order. The post-seam neutral baseline identity is: ```text -exact local root: - /home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4 comparison-report.json: bytes 24640 sha256 fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a @@ -159,14 +157,20 @@ runtime fingerprint sha256: c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085 ``` -The public launcher uses that exact absolute baseline path; it is not a caller -argument. The retained reports correctly preserve their original staging -paths, so the current path-bound `build_owned_root.validate_seed_bundle` and +The baseline path is a caller-supplied locator, never identity or stable +evidence. The public launcher requires `--baseline-root BASELINE_ROOT`, where +`BASELINE_ROOT` is an existing canonical absolute directory disjoint from the +output and every invocation staging path. Any identity-equivalent relocation +is admitted; any content drift rejects through the complete checks below. The +retained reports correctly preserve their original staging paths, so the +current path-bound `build_owned_root.validate_seed_bundle` and `compare_two_seed_outputs.outer_publication_inventory` APIs MUST NOT be called on this relocated publication and their private helpers MUST NOT be imported. -Instead, before creating profile staging, the launcher and publisher perform -one exact activation-local, path-neutral byte admission. Using stable, +Instead, the launcher performs one exact activation-local, path-neutral byte +admission before creating profile staging, and the publisher independently +repeats it before creating public staging after all ten profile bundles exist. +Using stable, no-follow reads, reject symlinks, external hardlinks, special nodes, unexpected or empty directories, size-cap violations, or anything except the exact outer directories `seed-17`, `seed-29`, and `comparison`. Require exactly 47 unique @@ -296,8 +300,8 @@ selection/projection logic, not a new geometry or prepared representation. ### 4.2 Component order and mapping -The existing `GeometryComponents` carrier and its exact 92-ID order are -unchanged: +The existing `GeometryComponents` carrier and its exact 92-ID family inventory +are unchanged: ```text stations..C.x, .C.y, .C.z, .rL, .rA, .rP @@ -313,6 +317,14 @@ hips..P_s.x, .y, .z, r_x, r_y, r_z total 92 ``` +The displayed family order above is descriptive, not positional. The sole +carrier order is the frozen implementation's exact +`GEOMETRY_COMPONENT_IDS`: form the complete 92-ID inventory above and sort it +globally by UTF-8 bytes. Thus all `hips.*` IDs precede all `shoulders.*` IDs, +which precede all `stations.*` IDs. Projection, `projected_values`, carrier +bytes, binding records, and component-index causality selectors MUST all use +that one global order; no family-local or table-display order is permitted. + Projection first creates a profile-local copy of the admitted source by the rules above, then executes the existing unique selectors and aliases. The closed mapping from the 92 components to profile data is: @@ -357,10 +369,10 @@ a scaled dimension, `profile_pointers` contains exactly `/profiles//dimension_scales/`. For a world placement sum it contains the matching pointer for every placement in the fixed chain: `/profiles//part_placements//`. -For a world landmark sum it contains those placement pointers plus the source -landmark pointer remains in `source_pointers`; no profile landmark pointer is -invented. A dimension record retains its source dimension pointer and adds its -one scale pointer. RFC-6901 escaping is `~` to `~0` and `/` to `~1`; profile +For a world landmark sum, `profile_pointers` contains exactly those placement +pointers. The source landmark pointer remains in `source_pointers`; no profile +landmark pointer is invented. A dimension record retains its source dimension +pointer and adds its one scale pointer. RFC-6901 escaping is `~` to `~0` and `/` to `~1`; profile indices and axis indices use unsigned base-10 without leading zeroes. Arrays sort by UTF-8 bytes. Empty, duplicate, missing, extra, differently grouped, or pointer-inconsistent bindings reject. @@ -600,7 +612,11 @@ MUST match across seeds. }, causality: sorted array of exactly 33 causality_evidence records, renders: { - renderer_id, render_config_sha256, visibility_sha256, + renderer_id, + render_config: exact render_export.render_config_record object, + render_config_sha256, + visibility: exact render_export.visibility_record object, + visibility_sha256, direct: file_record, lineage: file_record, same_surface_positions_sha256, same_surface_triangles_sha256 }, @@ -627,6 +643,30 @@ SHA-256 of canonical JSON encoding of the array of the 92 `value` fields in publisher reconstructs those bytes from `projected_values`, validates the record, and therefore compares the exact carrier across seeds through the already-stable evidence file. It is not a file record and adds no bundle role. +A selection hash always means SHA-256 of canonical JSON bytes: the complete +selected profile row for `profile_row_sha256`, its complete +`dimension_scales` object for `dimension_scales_sha256`, and its complete +`part_placements` object for `part_placements_sha256`. The publisher locates +the row again by the exact profile ID and index in the admitted fixed table, +recreates all three preimages, and requires all three hashes. +`profile_pointer` MUST equal `/profiles/` with the index written +as unsigned base-10 without leading zeroes, and resolving that pointer in the +admitted table MUST produce that same selected complete row. + +`render_config_sha256` is SHA-256 of canonical JSON bytes of the adjacent +complete `render_config` object; the publisher validates that object through +`render_export.validate_render_config` and recreates the hash. +`visibility_sha256` is SHA-256 of canonical JSON bytes of the adjacent complete +`visibility` object returned by `render_export.visibility_record`; the +publisher requires its exact closed keys and recreates the hash. +`same_surface_positions_sha256` MUST equal the level-2 `coordinate_sha256`. +`same_surface_triangles_sha256` MUST equal both the level-2 +`triangle_index_sha256` and `visibility.triangle_index_sha256`. The runner MUST +obtain `direct`, `lineage`, and the one shared visibility value from exactly +one `render_export.render_pair_bytes(level_2_mesh)` call; separately rebuilding +either image or its visibility is forbidden. These relations bind both image +records to one admitted level-2 surface without embedding the raster buffer. + A `causality_evidence` record is exactly the existing design-contract perturbation record, including its payload `file_record`. The three level records expose all PLY, coordinate, and triangle-index hashes. @@ -677,7 +717,6 @@ activation evidence, sidecars, reports, or any neutral manifest. receipt: complete decoded section-7.0 managed-test receipt object }, neutral_baseline: { - absolute_path: exactly the section-2 path, comparison_report: file_record, stable_manifest_sha256: hex64, runtime_fingerprint_sha256: hex64, @@ -718,11 +757,12 @@ The final `run-report.json` has schema literal_invocation: {environment: exactly ["PYTHONHASHSEED=0"], argv: exact public argv array}, output_path, staging_path, python_executable_path: canonical absolute paths, - neutral_baseline_path: exactly the section-2 absolute path, + neutral_baseline_path: exactly the caller-supplied canonical BASELINE_ROOT, started_utc, finished_utc: fixed-format UTC strings, timings: ordered nonnegative timing_record array for identity, managed-tests, - baseline-admission, profile-seed-builds, comparison, - staging-seal, total-before-seal, + launcher-baseline-admission, profile-seed-builds, + publisher-baseline-admission, comparison, pre-report-closure, + total-before-seal, activation_contract_sha256, design_contract_sha256, runtime_fingerprint_sha256: hex64, evidence: manifest_ref for exact-five-evidence.json, @@ -735,19 +775,57 @@ The final `run-report.json` has schema } ``` -The final report is created only after the evidence sidecar exists and points -backward to the payloads, evidence, and evidence sidecar. It contains no -record for itself or its own sidecar. Run-local values occur only in reports. -The 21 gate IDs are `exact-five.run.01.identity`, -`exact-five.run.02.managed-tests`, -`exact-five.run.03.baseline-admission`, IDs 04 through 13 for the ten -profile/seed builds in profile order and seed order 17 then 29, IDs 14 through -18 for the five profile cross-seed comparisons in profile order, -`exact-five.run.19.standard-neutral-payload-equality`, -`exact-five.run.20.evidence-graph`, and -`exact-five.run.21.staging-seal`. Each observes integer 1 against -`gate.boolean-pass`. None claims that the later launcher-owned rename has -already occurred. +Before invoking the publisher, the launcher creates one canonical closed +`owned-root-assembly-successor-exact-five-launcher-context.v1` temporary record +containing exactly the public `literal_invocation`, `output_path`, +`neutral_baseline_path`, and the first four timing records in the order +`identity`, `managed-tests`, `launcher-baseline-admission`, and +`profile-seed-builds`. The publisher admits that record and copies those exact +values into the final report. It independently measures the next three phases. +`total-before-seal` is exactly the arithmetic sum, in binary64 list order, of +the preceding seven timing seconds; it is not an inferred wall-clock interval. + +The final report is created only after the evidence sidecar exists and the +publisher has re-admitted the exact 17-file pre-report closure: 15 payloads, +evidence, and evidence sidecar. The `publisher-baseline-admission` timing and gate record +only the publisher's independent admission performed before public staging; +the launcher's earlier pre-profile admission is reported only by the distinct +`launcher-baseline-admission` timing copied from the launcher-context record +and does not satisfy or replace the publisher's gate. The +`pre-report-closure` timing and gate record only that 17-file admission. The +report contains no record for itself or its own sidecar. After writing the +report and sidecar, the publisher re-admits the exact 19-file staging closure; +that necessarily later fact is not asserted inside the report. The launcher +then independently repeats the 19-file admission. Run-local values occur only +in reports. +The 21 gate IDs, in exact order, are: + +```text +exact-five.run.01.identity +exact-five.run.02.managed-tests +exact-five.run.03.publisher-baseline-admission +exact-five.run.04.profile.standard_neutral_reference.seed-17 +exact-five.run.05.profile.standard_neutral_reference.seed-29 +exact-five.run.06.profile.compact_broad_short_limb_large_head.seed-17 +exact-five.run.07.profile.compact_broad_short_limb_large_head.seed-29 +exact-five.run.08.profile.tall_narrow_long_legged.seed-17 +exact-five.run.09.profile.tall_narrow_long_legged.seed-29 +exact-five.run.10.profile.slender_long_limb.seed-17 +exact-five.run.11.profile.slender_long_limb.seed-29 +exact-five.run.12.profile.stocky_broad_chested.seed-17 +exact-five.run.13.profile.stocky_broad_chested.seed-29 +exact-five.run.14.profile.standard_neutral_reference.cross-seed +exact-five.run.15.profile.compact_broad_short_limb_large_head.cross-seed +exact-five.run.16.profile.tall_narrow_long_legged.cross-seed +exact-five.run.17.profile.slender_long_limb.cross-seed +exact-five.run.18.profile.stocky_broad_chested.cross-seed +exact-five.run.19.standard-neutral-payload-equality +exact-five.run.20.evidence-graph +exact-five.run.21.pre-report-closure +``` + +Each observes integer 1 against `gate.boolean-pass`. None claims that the +later launcher-owned rename has already occurred. ## 8. Exact public inventory and acyclic publication graph @@ -782,7 +860,7 @@ The one-way final hash graph is exact: ```text managed-test receipt + 15 payloads -> exact-five-evidence.json exact-five-evidence.json -> exact-five-evidence.sha256 -15 payloads + evidence + evidence sidecar -> run-report.json +launcher context + 15 payloads + evidence + evidence sidecar -> run-report.json run-report.json -> run-report.sha256 ``` @@ -795,8 +873,8 @@ triangles, visibility, and camera calculation. All 15 payloads remain external/local under the repository artifact policy and MUST NOT be committed by this activation. The ten 42-file profile/seed -bundles, levels 0 and 1, 330 perturbation PLYs, and managed-test receipt are -invocation-owned ephemeral material. They remain until the final evidence and +bundles, levels 0 and 1, 330 perturbation PLYs, managed-test receipt, and +launcher-context record are invocation-owned ephemeral material. They remain until the final evidence and report are sealed, then the launcher removes only its exact staging inputs before publication. A cleanup or closed-inventory failure rejects publication. @@ -821,15 +899,16 @@ this contract. The only public command, from repository root, is: ```bash -PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --output ABSENT_PATH +PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --baseline-root BASELINE_ROOT --output ABSENT_PATH ``` -`ABSENT_PATH` MUST be a canonical absolute path without empty, `.` or `..` -components. It and every invocation-owned sibling staging path MUST be absent. -The launcher accepts exactly those two arguments in that order, requires -literal seed `0`, uses only the fixed section-2 baseline path, binds all -identities and the exact four-file allowlist before source admission, and -creates no output on failure. +`BASELINE_ROOT` MUST be the existing canonical absolute directory described in +section 2. `ABSENT_PATH` MUST be a canonical absolute path without empty, `.` +or `..` components. It and every invocation-owned sibling staging path MUST be +absent and disjoint from `BASELINE_ROOT`. The launcher accepts exactly those +four arguments in that order, requires literal seed `0`, treats the baseline +path only as a locator, binds all identities and the exact four-file allowlist +before source admission, and creates no output on failure. The launcher uses the existing pinned `surface_preview_launcher.sh` and requirements/runtime-v2 environment. In an @@ -839,22 +918,26 @@ invocation-owned absent staging root it performs, in order: ` under `PYTHONHASHSEED=0`; require the exact section-7.0 canonical success receipt and no skipped, expected-failure, or unexpected-success result. -2. Fully admit the retained neutral baseline. +2. Fully admit `BASELINE_ROOT` and record the + `launcher-baseline-admission` timing. 3. For each profile in exact order, invoke `exact_five_runner.py --profile --output ` first with `PYTHONHASHSEED=17`, then with `PYTHONHASHSEED=29`. -4. Invoke `exact_five_publisher.py` under `PYTHONHASHSEED=0` with exactly the - fixed baseline root, ten sealed sibling bundle paths in fixed profile/seed - order, the managed-test receipt, and one absent staging-publication path. - These are private fixed-shape arguments, not a public interface. +4. Seal the exact launcher-context record defined in section 7.3, then invoke + `exact_five_publisher.py` under `PYTHONHASHSEED=0` with exactly + `BASELINE_ROOT`, ten sealed sibling bundle paths in fixed profile/seed + order, the managed-test receipt, the launcher-context record, and one absent + staging-publication path. These are private fixed-shape arguments, not a + public interface. 5. The publisher re-admits every bundle, validates all schemas and gates, performs every cross-seed and neutral-baseline comparison, creates and seals the exact 19-file staging tree, and re-admits that sealed tree. It returns success without deleting inputs or publishing the final path. 6. The launcher independently re-admits the sealed staging tree, removes only - its exact invocation-owned ephemeral bundle and receipt paths, verifies that - cleanup did not alter the sealed tree, performs the sole final no-replace - rename to `ABSENT_PATH`, and returns success only when that rename succeeds. + its exact invocation-owned ephemeral bundle, receipt, and launcher-context + paths, verifies that cleanup did not alter the sealed tree, performs the sole + final no-replace rename to `ABSENT_PATH`, and returns success only when that + rename succeeds. The runner owns profile-table admission, unique selection, decimal projection, the identity-free 92-number handoff, unchanged geometry execution, all gates, @@ -874,8 +957,9 @@ rejection, unique profile/source selection, all 92 binding/pointer mappings, decimal half-even boundary cases, neutral projection equality, identity-only geometry API shape, both exact seeds for all profiles, all 33 copied-component selectors, evidence schema/cardinalities, exact 19-file closure, sidecar -grammar, and atomic no-partial-output failure tests. Tests do not replace any -runtime gate. +grammar, an identity-equivalent relocated-baseline success case, baseline +content-drift rejection, and atomic no-partial-output failure tests. Tests do +not replace any runtime gate. ## 10. Resource and cardinality caps @@ -904,6 +988,7 @@ each staging evidence file or receipt: <=16 MiB complete staging root: <=512 MiB complete published root: <=32 MiB runtime JSON: <=64 KiB +launcher-context record: <=64 KiB each additive implementation file: <=4 MiB additive non-test physical LOC: <=1600 additive test physical LOC: <=1200 diff --git a/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 b/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 index 39c741e..54a1d1d 100644 --- a/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 +++ b/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256 @@ -1 +1 @@ -ee97f8a5677b4b43abfeb9a3603b81788bff3bfc3b014188ecb50367f97e8542 experiments/owned-root-assembly-successor/exact-five-activation-contract.md +a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49 experiments/owned-root-assembly-successor/exact-five-activation-contract.md From 95c14a0b5a1bb4a19d68d3dc08174b7c59d39088 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 5 Sep 2026 17:08:41 +1200 Subject: [PATCH 19/38] Add fail-closed exact-five activation tooling --- .../publish_exact_five_gallery.py | 711 ++++++++++++++++ .../tests/test_exact_five_gallery.py | 268 ++++++ .../ai-delegation-and-review.md | 28 +- docs/project/status.md | 48 +- .../exact_five_launcher.sh | 139 ++++ .../exact_five_publisher.py | 615 ++++++++++++++ .../exact_five_runner.py | 688 ++++++++++++++++ .../tests/test_exact_five_activation.py | 761 ++++++++++++++++++ .../owned-root-assembly-successor/README.md | 106 ++- .../correction-round-1-preflight-trigger.json | 1 + 10 files changed, 3316 insertions(+), 49 deletions(-) create mode 100644 dev-tools/visual-review/publish_exact_five_gallery.py create mode 100644 dev-tools/visual-review/tests/test_exact_five_gallery.py create mode 100755 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh create mode 100644 experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py create mode 100644 experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py create mode 100644 experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py create mode 100644 experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json diff --git a/dev-tools/visual-review/publish_exact_five_gallery.py b/dev-tools/visual-review/publish_exact_five_gallery.py new file mode 100644 index 0000000..b94422c --- /dev/null +++ b/dev-tools/visual-review/publish_exact_five_gallery.py @@ -0,0 +1,711 @@ +#!/usr/bin/env python3 +"""Publish the already-sealed exact-five PNGs as a disposable review gallery.""" + +from __future__ import annotations + +import argparse +import hashlib +import math +import struct +import tempfile +import zlib +from pathlib import Path +import sys +from typing import Any, NoReturn + + +VISUAL_REVIEW_ROOT = Path(__file__).resolve().parent +REPOSITORY_ROOT = VISUAL_REVIEW_ROOT.parents[1] +EXACT_FIVE_ROOT = REPOSITORY_ROOT / "experiments" / "owned-root-assembly-successor-exact-five" +NEUTRAL_ROOT = REPOSITORY_ROOT / "experiments" / "owned-root-assembly-successor" +if str(VISUAL_REVIEW_ROOT) not in sys.path: + sys.path.insert(0, str(VISUAL_REVIEW_ROOT)) +if str(EXACT_FIVE_ROOT) not in sys.path: + sys.path.insert(0, str(EXACT_FIVE_ROOT)) +if str(NEUTRAL_ROOT) not in sys.path: + sys.path.insert(0, str(NEUTRAL_ROOT)) + +import common # noqa: E402 +from common import ValidationError, canonical_json # noqa: E402 +from publish import PublishError, publish_session # noqa: E402 +import artifact_serialization as artifacts # noqa: E402 +import exact_five_publisher as exact_five # noqa: E402 + + +class ExactFiveGalleryError(RuntimeError): + """A bounded, fail-closed exact-five gallery error.""" + + +REVIEW_ID = "owned-root-assembly-successor-exact-five-gallery" +TITLE = "Exact-five owned-root assembly visual review" +DESCRIPTION = ( + "Disposable visual review of the frozen exact-five surface render pairs. " + "Publishing this gallery records no decision; Ben's appraisal of this exact " + "candidate remains the merge checkpoint." +) +INSTRUCTIONS = ( + "For each ordered profile, compare the direct render with its lineage render. " + "The standard neutral reference is first. Appraise the visible form and " + "whether the two render paths agree. The gallery itself does not imply " + "acceptance; Ben's approval or qualified feedback is required before merge." +) +PNG_WIDTH = 512 +PNG_HEIGHT = 1536 +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +MAX_PNG_BYTES = 2 * 1024 * 1024 +MAX_JSON_BYTES = 16 * 1024 * 1024 + + +def _fail(message: str) -> NoReturn: + raise ExactFiveGalleryError(message) + + +def _keys(value: Any, required: set[str], where: str) -> dict[str, Any]: + if not isinstance(value, dict) or not required <= set(value): + missing = sorted(required - set(value)) if isinstance(value, dict) else sorted(required) + _fail(f"{where} is missing required field(s): {', '.join(missing)}") + return value + + +def _closed_keys(value: Any, expected: set[str], where: str) -> dict[str, Any]: + result = _keys(value, expected, where) + if set(result) != expected: + _fail(f"{where} has unexpected field(s): {', '.join(sorted(set(result) - expected))}") + return result + + +def _sha256(value: Any, where: str) -> str: + if not isinstance(value, str) or len(value) != 64 or any(char not in "0123456789abcdef" for char in value): + _fail(f"{where} is not lowercase SHA-256") + return value + + +def _record(value: Any, where: str) -> dict[str, Any]: + result = _closed_keys(value, {"role_path", "bytes", "sha256"}, where) + try: + artifacts.validate_role_path(result["role_path"]) + except Exception as exc: + raise ExactFiveGalleryError(f"{where}.role_path is invalid") from exc + if type(result["bytes"]) is not int or result["bytes"] < 0: + _fail(f"{where}.bytes is invalid") + _sha256(result["sha256"], f"{where}.sha256") + return result + + +def _publisher_check(callback: Any, *args: Any) -> Any: + try: + return callback(*args) + except Exception as exc: + raise ExactFiveGalleryError(f"exact-five semantic admission failed: {exc}") from exc + + +def _local_record(record: dict[str, Any], role: str, where: str) -> dict[str, Any]: + result = _record(record, where) + if result["role_path"] != role: + _fail(f"{where} has the wrong role") + return result + + +def _same_file_identity(left: dict[str, Any], right: dict[str, Any]) -> bool: + return left["bytes"] == right["bytes"] and left["sha256"] == right["sha256"] + + +PROFILE_EVIDENCE_KEYS = { + "schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", + "existing_dependencies", "additive_implementation_files", "runtime", + "runtime_fingerprint_sha256", "profile_id", "profile_index", "selection", + "projected_values", "projected_carrier", "projection_bindings", "levels", "thresholds", + "gates", "causality", "renders", "payloads", "invariants", +} +INVARIANTS = { + "topology_equal_to_neutral": True, + "formulas_equal_to_neutral": True, + "tunables_equal_to_neutral": True, + "thresholds_equal_to_neutral": True, + "gate_inventory_equal_to_neutral": True, + "subdivision_equal_to_neutral": True, + "ownership_equal_to_neutral": True, + "causality_rules_equal_to_neutral": True, + "renderer_equal_to_neutral": True, +} +GATE_CARDINALITIES = {"structural": 122, "continuity": 144, "anatomy": 78, "intersection": 12} + + +def _validate_managed_tests(value: Any, identity: dict[str, Any]) -> None: + managed = _closed_keys(value, {"receipt_sha256", "receipt"}, "managed tests") + receipt = managed["receipt"] + receipt_raw = artifacts.canonical_json_bytes(receipt) + if managed["receipt_sha256"] != artifacts.sha256_bytes(receipt_raw): + _fail("managed-test receipt hash differs") + _publisher_check( + exact_five._new_receipt, + receipt, + receipt_raw, + Path("managed-test-receipt.json"), + identity, + ) + + +def _validate_profile_evidence( + root: Path, + profile: dict[str, Any], + index: int, + identity: dict[str, Any], + table: list[dict[str, Any]], + public_records: dict[str, dict[str, Any]], + frozen_thresholds: list[dict[str, Any]] | None, + frozen_gate_ids: dict[str, list[str]] | None, +) -> tuple[list[dict[str, Any]], dict[str, list[str]], dict[str, dict[str, Any]], bytes]: + profile_id = exact_five.PROFILES[index] + _closed_keys( + profile, + {"profile_id", "profile_index", "evidence", "stable_cross_seed_comparisons", "neutral_payload_comparisons"}, + f"profile {profile_id}", + ) + if profile["profile_id"] != profile_id or profile["profile_index"] != index: + _fail(f"profile {profile_id} identity/order differs") + nested = _closed_keys(profile["evidence"], PROFILE_EVIDENCE_KEYS, f"profile {profile_id} evidence") + if not ( + nested["schema"] == "owned-root-assembly-successor-profile-seed-evidence.v1" + and nested["outcome"] == "success" + and nested["profile_id"] == profile_id + and nested["profile_index"] == index + and nested["activation_contract"] == identity["activation"] + and nested["design_contract"] == identity["design"] + and nested["source"] == identity["source"] + and nested["profile_table"] == identity["profile"] + and nested["existing_dependencies"] == identity["dependencies"] + and nested["additive_implementation_files"] == identity["additive_files"] + and nested["runtime"] == identity["runtime"] + and nested["runtime_fingerprint_sha256"] == identity["runtime_sha"] + ): + _fail(f"profile {profile_id} frozen provenance differs") + + row = table[index] + selection = _closed_keys( + nested["selection"], + {"profile_pointer", "profile_row_sha256", "dimension_scales_sha256", "part_placements_sha256"}, + f"profile {profile_id} selection", + ) + expected_selection = { + "profile_pointer": f"/profiles/{index}", + "profile_row_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row)), + "dimension_scales_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["dimension_scales"])), + "part_placements_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["part_placements"])), + } + if selection != expected_selection: + _fail(f"profile {profile_id} selection does not bind the frozen profile row") + + values, bindings = nested["projected_values"], nested["projection_bindings"] + if not ( + isinstance(values, list) and isinstance(bindings, list) + and [item.get("prepared_component") for item in values if isinstance(item, dict)] == list(exact_five.COMPONENT_IDS) + and [item.get("prepared_component") for item in bindings if isinstance(item, dict)] == list(exact_five.COMPONENT_IDS) + ): + _fail(f"profile {profile_id} projection inventory differs") + for position, (value, binding) in enumerate(zip(values, bindings)): + _closed_keys(value, {"prepared_component", "value", "source_pointers", "profile_pointers"}, f"profile {profile_id} projected value {position}") + _closed_keys(binding, {"prepared_component", "derivation_id", "source_addresses", "source_pointers", "profile_pointers"}, f"profile {profile_id} projection binding {position}") + try: + binary_value = artifacts.coerce_binary64(value["value"], label="projected value") + except Exception as exc: + raise ExactFiveGalleryError(f"profile {profile_id} projected value {position} is invalid") from exc + if not ( + value["prepared_component"] == binding["prepared_component"] + and binary_value == value["value"] + and value["source_pointers"] == binding["source_pointers"] + and value["profile_pointers"] == binding["profile_pointers"] + and binding["derivation_id"] in ( + "profile.dimension-permille-half-even-mm.v1", + "profile.world-placement-axis-sum.v1", + "profile.world-landmark-axis-sum.v1", + ) + ): + _fail(f"profile {profile_id} projection binding {position} differs") + _publisher_check(exact_five._pointers, value["source_pointers"], "source pointers") + _publisher_check(exact_five._pointers, value["profile_pointers"], "profile pointers") + _publisher_check(exact_five._addresses, binding["source_addresses"], "source addresses") + if not all(pointer.startswith(f"/profiles/{index}/") for pointer in value["profile_pointers"]): + _fail(f"profile {profile_id} projection selects another profile") + carrier_raw = artifacts.canonical_json_bytes([item["value"] for item in values]) + if nested["projected_carrier"] != {"bytes": len(carrier_raw), "sha256": artifacts.sha256_bytes(carrier_raw)}: + _fail(f"profile {profile_id} projected carrier differs") + + nested_payloads = nested["payloads"] + if not isinstance(nested_payloads, list) or [item.get("role_path") if isinstance(item, dict) else None for item in nested_payloads] != list(exact_five.PAYLOAD_ROLES): + _fail(f"profile {profile_id} payload inventory differs") + payload_map = {item["role_path"]: _record(item, f"profile {profile_id} payload") for item in nested_payloads} + + levels = nested["levels"] + if not isinstance(levels, list) or [item.get("level") if isinstance(item, dict) else None for item in levels] != [0, 1, 2]: + _fail(f"profile {profile_id} level inventory differs") + for level, level_row in enumerate(levels): + _closed_keys(level_row, {"level", "counts", "coordinate_bytes", "coordinate_sha256", "triangle_index_bytes", "triangle_index_sha256", "ply"}, f"profile {profile_id} level {level}") + counts = exact_five.neutral.LEVEL_COUNTS[level] + expected_counts = {"level": level, "vertices": counts[0], "edges": counts[1], "quads": counts[2], "triangles": counts[3], "boundary_edges": counts[4]} + local_role = f"surface-level-{level}.ply" + if level_row["counts"] != expected_counts or level_row["ply"] != payload_map[local_role]: + _fail(f"profile {profile_id} level {level} identity differs") + if type(level_row["coordinate_bytes"]) is not int or level_row["coordinate_bytes"] <= 0 or type(level_row["triangle_index_bytes"]) is not int or level_row["triangle_index_bytes"] <= 0: + _fail(f"profile {profile_id} level {level} digest sizes differ") + _sha256(level_row["coordinate_sha256"], "coordinate hash") + _sha256(level_row["triangle_index_sha256"], "triangle hash") + if level == 2: + public = public_records[f"{profile_id}/{local_role}"] + if not _same_file_identity(level_row["ply"], public): + _fail(f"profile {profile_id} public PLY is not bound to level 2") + _, _, coordinates, triangles = _publisher_check( + exact_five._ply_digest, root / profile_id / local_role, f"{profile_id}/{local_role}", 2 + ) + if coordinates != {"bytes": level_row["coordinate_bytes"], "sha256": level_row["coordinate_sha256"]} or triangles != {"bytes": level_row["triangle_index_bytes"], "sha256": level_row["triangle_index_sha256"]}: + _fail(f"profile {profile_id} public PLY geometry digest differs") + + thresholds = nested["thresholds"] + if frozen_thresholds is None: + _publisher_check(exact_five._threshold_shape, thresholds, "profile thresholds") + frozen_thresholds = thresholds + else: + _publisher_check(exact_five._thresholds, thresholds, frozen_thresholds, "profile thresholds") + gates = _closed_keys(nested["gates"], set(GATE_CARDINALITIES), f"profile {profile_id} gates") + gate_ids = {group: [item.get("gate_id") if isinstance(item, dict) else None for item in gates[group]] for group in GATE_CARDINALITIES} + if any(len(gates[group]) != count for group, count in GATE_CARDINALITIES.items()): + _fail(f"profile {profile_id} gate cardinality differs") + if frozen_gate_ids is not None and gate_ids != frozen_gate_ids: + _fail(f"profile {profile_id} gate inventory differs from neutral") + for group in GATE_CARDINALITIES: + _publisher_check(exact_five._gate_rows, gates[group], gate_ids[group], thresholds, f"profile {profile_id} {group}") + + causality = nested["causality"] + expected_parameters = sorted(exact_five.CAUSAL_COMPONENTS, key=str.encode) + if not isinstance(causality, list) or [item.get("parameter_id") if isinstance(item, dict) else None for item in causality] != expected_parameters: + _fail(f"profile {profile_id} causality inventory differs") + for position, item in enumerate(causality): + _closed_keys(item, {"parameter_id", "prepared_component", "delta_m", "support_level", "predicted_support_count", "observed_support_count", "predicted_support_sha256", "observed_support_sha256", "maximum_movement_m", "artifact"}, f"profile {profile_id} causality {position}") + parameter = item["parameter_id"] + artifact_role = f"perturb-{parameter.replace('.', '-')}.ply" + movement = item["maximum_movement_m"] + if not ( + item["prepared_component"] == exact_five.CAUSAL_COMPONENTS[parameter] + and item["delta_m"] == 0.01 and item["support_level"] == 2 + and type(item["predicted_support_count"]) is int + and 0 < item["predicted_support_count"] <= 1737 + and item["predicted_support_count"] == item["observed_support_count"] + and item["predicted_support_sha256"] == item["observed_support_sha256"] + and type(movement) is float and math.isfinite(movement) + and movement >= float.fromhex("0x1.d14e3bcd35a85p-11") + and item["artifact"] == payload_map[artifact_role] + ): + _fail(f"profile {profile_id} causality {position} differs") + _sha256(item["predicted_support_sha256"], "causality support hash") + + renders = _closed_keys(nested["renders"], {"renderer_id", "render_config", "render_config_sha256", "visibility", "visibility_sha256", "direct", "lineage", "same_surface_positions_sha256", "same_surface_triangles_sha256"}, f"profile {profile_id} renders") + _publisher_check(exact_five.render.validate_render_config, renders["render_config"]) + visibility = _closed_keys(renders["visibility"], {"level", "triangle_count", "triangle_index_sha256", "rule"}, f"profile {profile_id} visibility") + if not ( + renders["renderer_id"] == "owned-root-raster-pillow-11.1.0.v1" + and renders["render_config_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(renders["render_config"])) + and renders["visibility_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(visibility)) + and visibility == {"level": 2, "triangle_count": 3328, "triangle_index_sha256": levels[2]["triangle_index_sha256"], "rule": "larger-depth-then-lower-triangle-index"} + and renders["same_surface_positions_sha256"] == levels[2]["coordinate_sha256"] + and renders["same_surface_triangles_sha256"] == levels[2]["triangle_index_sha256"] + and renders["direct"] == payload_map["direct.png"] + and renders["lineage"] == payload_map["lineage.png"] + ): + _fail(f"profile {profile_id} render/surface identity differs") + if nested["invariants"] != INVARIANTS: + _fail(f"profile {profile_id} invariant evidence differs") + + for render_kind in ("direct", "lineage"): + local = renders[render_kind] + public_role = f"{profile_id}/{render_kind}.png" + public = public_records[public_role] + if not _same_file_identity(local, public): + _fail(f"profile {profile_id} {render_kind} render is not bound to the public PNG") + data = _validate_png(root / public_role, public_role) + if len(data) != public["bytes"] or hashlib.sha256(data).hexdigest() != public["sha256"]: + _fail(f"profile {profile_id} {render_kind} PNG changed after evidence admission") + + nested_raw = artifacts.canonical_json_bytes(nested) + nested_record = {"role_path": "profile-seed-evidence.json", "bytes": len(nested_raw), "sha256": artifacts.sha256_bytes(nested_raw)} + nested_sidecar = f"{nested_record['sha256']} profile-seed-evidence.json\n".encode("ascii") + expected_stable = dict(payload_map) + expected_stable["profile-seed-evidence.json"] = nested_record + expected_stable["profile-seed-evidence.sha256"] = {"role_path": "profile-seed-evidence.sha256", "bytes": len(nested_sidecar), "sha256": artifacts.sha256_bytes(nested_sidecar)} + stable = profile["stable_cross_seed_comparisons"] + if not isinstance(stable, list) or [item.get("role_path") if isinstance(item, dict) else None for item in stable] != list(exact_five.BUNDLE_STABLE_ROLES): + _fail(f"profile {profile_id} stable comparison inventory differs") + if stable != [expected_stable[role] for role in exact_five.BUNDLE_STABLE_ROLES]: + _fail(f"profile {profile_id} stable comparisons are not bound to seed evidence") + return frozen_thresholds, gate_ids, payload_map, nested_raw + + +def _read_json(path: Path, where: str, *, max_bytes: int = MAX_JSON_BYTES) -> tuple[dict[str, Any], bytes]: + try: + raw = artifacts.read_regular_file(path, max_bytes=max_bytes) + value = artifacts.decode_canonical_json(raw) + except Exception as exc: + raise ExactFiveGalleryError(f"{where} is not canonical JSON") from exc + if not isinstance(value, dict): + _fail(f"{where} is not an object") + return value, raw + + +def _validate_png(path: Path, role: str) -> bytes: + try: + data = artifacts.read_regular_file(path, max_bytes=MAX_PNG_BYTES) + except Exception as exc: + raise ExactFiveGalleryError(f"{role} cannot be read") from exc + if not data.startswith(PNG_SIGNATURE): + _fail(f"{role} is not a PNG") + offset = len(PNG_SIGNATURE) + chunk_names: list[bytes] = [] + idat = bytearray() + while offset < len(data): + if len(data) - offset < 12: + _fail(f"{role} has a truncated PNG chunk") + length = struct.unpack(">I", data[offset : offset + 4])[0] + chunk_type = data[offset + 4 : offset + 8] + end = offset + 12 + length + if end > len(data): + _fail(f"{role} has a truncated PNG payload") + payload = data[offset + 8 : offset + 8 + length] + expected_crc = struct.unpack(">I", data[offset + 8 + length : end])[0] + if zlib.crc32(chunk_type + payload) & 0xFFFFFFFF != expected_crc: + _fail(f"{role} has an invalid PNG CRC") + chunk_names.append(chunk_type) + if chunk_type == b"IHDR": + if len(payload) != 13: + _fail(f"{role} has an invalid IHDR") + width, height, depth, colour, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", payload + ) + if (width, height, depth, colour, compression, filtering, interlace) != ( + PNG_WIDTH, + PNG_HEIGHT, + 8, + 2, + 0, + 0, + 0, + ): + _fail(f"{role} PNG dimensions or colour format differ") + elif chunk_type == b"IDAT": + idat.extend(payload) + elif chunk_type == b"IEND": + if length != 0 or end != len(data): + _fail(f"{role} has trailing or malformed IEND data") + else: + _fail(f"{role} contains unexpected PNG chunk {chunk_type!r}") + offset = end + if chunk_type == b"IEND": + break + if chunk_names != [b"IHDR", b"IDAT", b"IEND"] or not idat: + _fail(f"{role} has an incomplete PNG structure") + try: + decompressor = zlib.decompressobj() + decoded = decompressor.decompress(bytes(idat), PNG_HEIGHT * (1 + PNG_WIDTH * 3) + 1) + except zlib.error as exc: + raise ExactFiveGalleryError(f"{role} contains invalid image data") from exc + expected_raw_bytes = PNG_HEIGHT * (1 + PNG_WIDTH * 3) + if ( + len(decoded) != expected_raw_bytes + or decompressor.unconsumed_tail + or decompressor.unused_data + or not decompressor.eof + or any(decoded[index] > 4 for index in range(0, len(decoded), PNG_WIDTH * 3 + 1)) + ): + _fail(f"{role} contains invalid RGB scanline data") + return data + + +def _refuse_existing_destination(reviews_root: Path, review_id: str) -> None: + if reviews_root.is_symlink() or not reviews_root.is_dir(): + _fail("reviews root must already exist as a regular directory") + destination = reviews_root / review_id + if destination.is_symlink(): + _fail("refusing existing destination symlink") + if destination.exists(): + _fail("refusing to overwrite existing destination") + + +def validate_exact_five_root(root: Path) -> tuple[dict[str, Any], dict[str, Any], dict[str, dict[str, Any]], bytes, bytes]: + """Re-admit the sealed public root without invoking any generator.""" + + root = root.absolute() + identity = _publisher_check(exact_five._static) + table = _publisher_check(exact_five._table, identity) + try: + inventory = artifacts.closed_inventory(root, exact_five.PUBLIC_ROLES, max_file_bytes=MAX_JSON_BYTES) + except Exception as exc: + raise ExactFiveGalleryError(f"exact-five root is not the closed public layout: {exc}") from exc + by_role = {item["role_path"]: item for item in inventory} + evidence, evidence_raw = _read_json(root / "exact-five-evidence.json", "exact-five evidence") + sidecar = artifacts.read_regular_file(root / "exact-five-evidence.sha256", max_bytes=256) + expected_sidecar = f"{artifacts.sha256_bytes(evidence_raw)} exact-five-evidence.json\n".encode("ascii") + if sidecar != expected_sidecar: + _fail("exact-five evidence sidecar does not bind the evidence bytes") + report, report_raw = _read_json(root / "run-report.json", "exact-five run report", max_bytes=2 * 1024 * 1024) + report_sidecar = artifacts.read_regular_file(root / "run-report.sha256", max_bytes=256) + if report_sidecar != f"{artifacts.sha256_bytes(report_raw)} run-report.json\n".encode("ascii"): + _fail("exact-five run-report sidecar does not bind the report bytes") + + _closed_keys(evidence, { + "schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", + "existing_dependencies", "additive_implementation_files", "managed_tests", "neutral_baseline", + "runtime", "runtime_fingerprint_sha256", "profile_order", "profiles", "payloads", + }, "exact-five evidence") + if not ( + evidence["schema"] == "owned-root-assembly-successor-exact-five-evidence.v1" + and evidence["outcome"] == "success" + and evidence["activation_contract"] == identity["activation"] + and evidence["design_contract"] == identity["design"] + and evidence["source"] == identity["source"] + and evidence["profile_table"] == identity["profile"] + and evidence["existing_dependencies"] == identity["dependencies"] + and evidence["additive_implementation_files"] == identity["additive_files"] + and evidence["runtime"] == identity["runtime"] + and evidence["runtime_fingerprint_sha256"] == identity["runtime_sha"] + ): + _fail("exact-five evidence is not a successful exact-five publication") + if evidence["profile_order"] != list(exact_five.PROFILES): + _fail("exact-five evidence profile order is not neutral-first") + _validate_managed_tests(evidence["managed_tests"], identity) + + neutral = _closed_keys( + evidence["neutral_baseline"], + {"comparison_report", "stable_manifest_sha256", "runtime_fingerprint_sha256", "payload_comparisons"}, + "neutral baseline", + ) + comparison = _local_record(neutral["comparison_report"], "comparison-report.json", "neutral comparison report") + if not ( + comparison["sha256"] == exact_five.BASELINE_REPORT_SHA + and neutral["stable_manifest_sha256"] == exact_five.BASELINE_STABLE_SHA + and neutral["runtime_fingerprint_sha256"] == identity["runtime_sha"] + ): + _fail("neutral baseline frozen identity differs") + neutral_comparisons = neutral["payload_comparisons"] + if not isinstance(neutral_comparisons, list) or [item.get("role_path") if isinstance(item, dict) else None for item in neutral_comparisons] != list(exact_five.PAYLOAD_ROLES): + _fail("neutral baseline payload comparison inventory differs") + for position, item in enumerate(neutral_comparisons): + _record(item, f"neutral payload comparison {position}") + + _closed_keys(report, { + "schema", "outcome", "literal_invocation", "output_path", "staging_path", "python_executable_path", + "neutral_baseline_path", "started_utc", "finished_utc", "timings", "activation_contract_sha256", + "design_contract_sha256", "runtime_fingerprint_sha256", "evidence", "evidence_sidecar", "payloads", + "profile_seed_runs", "gates", + }, "exact-five run report") + if not ( + report["schema"] == "owned-root-assembly-successor-exact-five-run-report.v1" + and report["outcome"] == "success" + and report["activation_contract_sha256"] == exact_five.ACTIVATION_SHA + and report["design_contract_sha256"] == exact_five.DESIGN_SHA + and report["runtime_fingerprint_sha256"] == identity["runtime_sha"] + ): + _fail("exact-five run report is not successful") + evidence_record = by_role["exact-five-evidence.json"] + evidence_ref = {**evidence_record, "schema": evidence["schema"]} + if ( + report["evidence"] != evidence_ref + or report["evidence_sidecar"] != by_role["exact-five-evidence.sha256"] + or report["payloads"] != evidence["payloads"] + ): + _fail("exact-five run report does not bind the evidence inventory") + + payloads = evidence["payloads"] + if not isinstance(payloads, list) or [item.get("role_path") if isinstance(item, dict) else None for item in payloads] != list(exact_five.PUBLIC_PAYLOAD_ROLES): + _fail("exact-five evidence payload inventory is not the frozen public order") + for index, item in enumerate(payloads): + item_record = _record(item, f"exact-five evidence.payloads[{index}]") + if by_role.get(item_record["role_path"]) != item_record: + _fail(f"exact-five evidence payload is not bound to the root: {item_record['role_path']}") + + profiles = evidence["profiles"] + if not isinstance(profiles, list) or len(profiles) != len(exact_five.PROFILES): + _fail("exact-five evidence does not contain five profiles") + png_records: dict[str, dict[str, Any]] = {} + frozen_thresholds: list[dict[str, Any]] | None = None + frozen_gate_ids: dict[str, list[str]] | None = None + nested_raw_by_profile: dict[str, bytes] = {} + for index, profile in enumerate(profiles): + profile_id = exact_five.PROFILES[index] + frozen_thresholds, admitted_gate_ids, payload_map, nested_raw = _validate_profile_evidence( + root, profile, index, identity, table, by_role, frozen_thresholds, frozen_gate_ids + ) + if frozen_gate_ids is None: + frozen_gate_ids = admitted_gate_ids + nested_raw_by_profile[profile_id] = nested_raw + neutral_rows = profile["neutral_payload_comparisons"] + if index == 0: + if neutral_rows != neutral_comparisons or neutral_rows != [payload_map[role] for role in exact_five.PAYLOAD_ROLES]: + _fail("standard-neutral payload comparisons do not bind the neutral profile") + elif neutral_rows != []: + _fail(f"profile {profile_id} unexpectedly carries neutral payload comparisons") + for render_kind in ("direct", "lineage"): + role = f"{profile_id}/{render_kind}.png" + png_records[role] = by_role[role] + expected_seed_runs = [ + { + "profile_id": profile["profile_id"], + "seed": seed, + "outcome": "success", + "evidence_sha256": artifacts.sha256_bytes( + nested_raw_by_profile[profile["profile_id"]] + ), + } + for profile in profiles + for seed in exact_five.SEEDS + ] + if report["profile_seed_runs"] != expected_seed_runs: + _fail("exact-five run report profile/seed inventory is not bound to evidence") + final_gate_ids = tuple(getattr(exact_five, "FINAL_GATE_IDS", ())) + expected_final_gates = [ + {"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} + for gate in final_gate_ids + ] + if not final_gate_ids: + final_gate_ids = tuple( + ["exact-five.run.01.identity", "exact-five.run.02.managed-tests", "exact-five.run.03.publisher-baseline-admission"] + + [f"exact-five.run.{4 + index * 2 + offset:02d}.profile.{profile}.seed-{seed}" for index, profile in enumerate(exact_five.PROFILES) for offset, seed in enumerate(exact_five.SEEDS)] + + [f"exact-five.run.{14 + index:02d}.profile.{profile}.cross-seed" for index, profile in enumerate(exact_five.PROFILES)] + + ["exact-five.run.19.standard-neutral-payload-equality", "exact-five.run.20.evidence-graph", "exact-five.run.21.pre-report-closure"] + ) + expected_final_gates = [ + {"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} + for gate in final_gate_ids + ] + if report["gates"] != expected_final_gates: + _fail("exact-five final gate inventory is not the frozen all-pass set") + return evidence, report, png_records, evidence_raw, report_raw + + +def _profile_title(profile_id: str) -> str: + return profile_id.replace("_", " ").title() + + +def _build_review_manifest( + exact_root: Path, + review_id: str, + evidence: dict[str, Any], + report: dict[str, Any], + png_records: dict[str, dict[str, Any]], + evidence_raw: bytes, + report_raw: bytes, +) -> tuple[dict[str, Any], dict[str, dict[str, int | str]]]: + groups: list[dict[str, Any]] = [] + expected_sources: dict[str, dict[str, int | str]] = {} + for profile_id in exact_five.PROFILES: + items: list[dict[str, Any]] = [] + for render_kind in ("direct", "lineage"): + item_id = f"{profile_id}__{render_kind}" + role = f"{profile_id}/{render_kind}.png" + artifact = png_records[role] + item = { + "id": item_id, + "title": render_kind.title(), + "source": str((exact_root / role).absolute()), + "description": f"{render_kind.title()} exact-five render for the {_profile_title(profile_id)} profile.", + "metadata": { + "profile_id": profile_id, + "render_kind": render_kind, + "artifact": {**artifact, "width": PNG_WIDTH, "height": PNG_HEIGHT, "mode": "RGB"}, + "exact_five_evidence_sha256": artifacts.sha256_bytes(evidence_raw), + "exact_five_run_report_sha256": artifacts.sha256_bytes(report_raw), + }, + } + items.append(item) + expected_sources[item_id] = {"bytes": artifact["bytes"], "sha256": artifact["sha256"]} + groups.append({ + "id": profile_id, + "title": _profile_title(profile_id), + "description": "Compare the direct and lineage renders for this exact-five profile.", + "selection_mode": "none", + "items": items, + }) + review = { + "schema_version": 1, + "id": review_id, + "title": TITLE, + "description": DESCRIPTION, + "instructions": INSTRUCTIONS, + "kind": "image", + "subject_context": { + "authored_summary": { + "text": "Five ordered exact-five profiles, each shown as direct and lineage renders of the already-published surface." + }, + "descriptor_snapshot": { + "format": evidence["schema"], + "profile_order": list(exact_five.PROFILES), + "render_order": ["direct", "lineage"], + "image_count": 10, + "canvas": {"width": PNG_WIDTH, "height": PNG_HEIGHT, "mode": "RGB"}, + "exact_five_evidence_sha256": artifacts.sha256_bytes(evidence_raw), + "exact_five_run_report_sha256": artifacts.sha256_bytes(report_raw), + "activation_contract_sha256": ( + evidence.get("activation_contract", {}).get("sha256") + if isinstance(evidence.get("activation_contract"), dict) + else None + ), + }, + "provenance": { + "source": "already-published exact-five public root", + "evidence_sha256": artifacts.sha256_bytes(evidence_raw), + "run_report_sha256": artifacts.sha256_bytes(report_raw), + }, + }, + "groups": groups, + } + return review, expected_sources + + +def publish_exact_five_gallery( + reviews_root: Path, + exact_root: Path, + *, + review_id: str = REVIEW_ID, +) -> dict[str, Any]: + try: + review_id = common.validate_id(review_id, "review id") + except ValidationError as exc: + _fail(str(exc)) + _refuse_existing_destination(reviews_root, review_id) + exact_root = exact_root.absolute() + evidence, report, png_records, evidence_raw, report_raw = validate_exact_five_root(exact_root) + review, expected_sources = _build_review_manifest( + exact_root, review_id, evidence, report, png_records, evidence_raw, report_raw + ) + try: + with tempfile.TemporaryDirectory(prefix="ck-exact-five-gallery-") as temporary: + manifest_path = Path(temporary) / "review-manifest.json" + manifest_path.write_text(canonical_json(review), encoding="utf-8", newline="\n") + summary = publish_session( + reviews_root, + manifest_path, + expected_sources=expected_sources, + ) + except (ValidationError, PublishError, OSError) as exc: + raise ExactFiveGalleryError(f"could not publish exact-five gallery: {exc}") from exc + return {**summary, "kind": "exact-five-gallery", "profiles": len(exact_five.PROFILES), "images": 2 * len(exact_five.PROFILES)} + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", required=True, type=Path, help="existing visual-review root") + parser.add_argument("--exact-five-root", required=True, type=Path, help="already-published exact-five public root") + parser.add_argument("--id", dest="review_id", default=REVIEW_ID) + return parser + + +def main(argv: list[str] | None = None) -> int: + try: + args = _parser().parse_args(argv) + summary = publish_exact_five_gallery(args.root, args.exact_five_root, review_id=args.review_id) + except (ExactFiveGalleryError, ValidationError, PublishError, OSError) as exc: + print(f"publish-exact-five-gallery failed: {exc}", file=sys.stderr) + return 2 + print(canonical_json(summary), end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/visual-review/tests/test_exact_five_gallery.py b/dev-tools/visual-review/tests/test_exact_five_gallery.py new file mode 100644 index 0000000..c921b51 --- /dev/null +++ b/dev-tools/visual-review/tests/test_exact_five_gallery.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Focused tests for the sealed exact-five visual-review gallery adapter.""" + +from __future__ import annotations + +import hashlib +import json +import shutil +import struct +import sys +import tempfile +import unittest +import zlib +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve() +REPOSITORY_ROOT = HERE.parents[3] +VISUAL_REVIEW_ROOT = HERE.parents[1] +EXACT_FIVE_ROOT = REPOSITORY_ROOT / "experiments" / "owned-root-assembly-successor-exact-five" +NEUTRAL_ROOT = REPOSITORY_ROOT / "experiments" / "owned-root-assembly-successor" +sys.path.insert(0, str(VISUAL_REVIEW_ROOT)) +sys.path.insert(0, str(EXACT_FIVE_ROOT)) +sys.path.insert(0, str(NEUTRAL_ROOT)) + +import artifact_serialization as artifacts # noqa: E402 +import exact_five_publisher as exact_five # noqa: E402 +import publish_exact_five_gallery as adapter # noqa: E402 + + +def _chunk(kind: bytes, payload: bytes) -> bytes: + return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF) + + +def _png(colour: tuple[int, int, int]) -> bytes: + raw = b"".join(b"\x00" + bytes(colour) * adapter.PNG_WIDTH for _ in range(adapter.PNG_HEIGHT)) + header = struct.pack(">IIBBBBB", adapter.PNG_WIDTH, adapter.PNG_HEIGHT, 8, 2, 0, 0, 0) + return adapter.PNG_SIGNATURE + _chunk(b"IHDR", header) + _chunk(b"IDAT", zlib.compress(raw, 9)) + _chunk(b"IEND", b"") + + +def _ply() -> bytes: + vertex_count, _, quad_count, _, _ = exact_five.neutral.LEVEL_COUNTS[2] + lines = ["ply", "format ascii 1.0", f"element vertex {vertex_count}", "property double x", "property double y", "property double z", f"element face {quad_count}", "property list uchar int vertex_indices", "end_header"] + lines.extend(f"{index}.0 0.0 0.0" for index in range(vertex_count)) + lines.extend(f"4 {index % (vertex_count - 3)} {index % (vertex_count - 3) + 1} {index % (vertex_count - 3) + 2} {index % (vertex_count - 3) + 3}" for index in range(quad_count)) + return ("\n".join(lines) + "\n").encode("ascii") + + +class ExactFiveGalleryTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory(prefix="ck-exact-five-gallery-tests-") + self.root = Path(self.temp.name) + self.exact_root = self.root / "exact-five" + self.reviews_root = self.root / "reviews" + self.exact_root.mkdir() + self.reviews_root.mkdir() + self.identity = self._identity() + self.table = [{"id": profile, "label": profile, "dimension_scales": {"scale": 1000 + index}, "part_placements": {"part": [index, 0, 0]}} for index, profile in enumerate(exact_five.PROFILES)] + self._write_exact_root() + + def tearDown(self) -> None: + self.temp.cleanup() + + @staticmethod + def _record(role: str, data: bytes) -> dict[str, object]: + return {"role_path": role, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()} + + @staticmethod + def _fixed_record(role: str, sha256: str) -> dict[str, object]: + return {"role_path": role, "bytes": 1, "sha256": sha256} + + def _identity(self) -> dict[str, object]: + runtime = {"implementation": "CPython", "version": "3.10.12", "platform": "Linux", "packages": {"Pillow": "11.1.0", "numpy": "2.2.6", "scikit-image": "0.25.2"}} + comparator = self._fixed_record(exact_five.COMPARATOR_ROLE, "2" * 64) + return { + "activation": self._fixed_record(exact_five.ACTIVATION_ROLE, exact_five.ACTIVATION_SHA), + "design": self._fixed_record(exact_five.DESIGN_ROLE, exact_five.DESIGN_SHA), + "source": self._fixed_record(exact_five.SOURCE_ROLE, exact_five.SOURCE_SHA), + "profile": self._fixed_record(exact_five.PROFILE_ROLE, exact_five.PROFILE_SHA), + "dependencies": [self._fixed_record("dependency.py", "1" * 64)], + "neutral_files": [comparator], "additive_files": [self._fixed_record(exact_five.PUBLISHER_ROLE, "3" * 64)], + "runtime": runtime, "runtime_raw": artifacts.canonical_json_bytes(runtime), + "runtime_sha": exact_five.RUNTIME_SHA, "comparator": comparator, + } + + def _projection(self, profile_index: int) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + values, bindings = [], [] + for component in exact_five.COMPONENT_IDS: + source_pointers = [f"/source/{component.replace('.', '/')}"] + profile_pointers = [f"/profiles/{profile_index}/dimension_scales/scale"] + values.append({"prepared_component": component, "value": 1.0, "source_pointers": source_pointers, "profile_pointers": profile_pointers}) + bindings.append({"prepared_component": component, "derivation_id": "profile.dimension-permille-half-even-mm.v1", "source_addresses": [["document", ["body"], component, "value"]], "source_pointers": source_pointers, "profile_pointers": profile_pointers}) + return values, bindings + + @staticmethod + def _thresholds_and_gates() -> tuple[list[dict[str, object]], dict[str, list[dict[str, object]]]]: + gates: dict[str, list[dict[str, object]]] = {} + prefixes = {"structural": "a", "continuity": "b", "anatomy": "c", "intersection": "d"} + thresholds: list[dict[str, object]] = [] + for group, count in adapter.GATE_CARDINALITIES.items(): + rows = [] + for index in range(count): + gate_id = f"{prefixes[group]}.{index:03d}" + threshold_id = f"threshold.{gate_id}" + thresholds.append({"threshold_id": threshold_id, "relation": "ge", "lower": 0, "upper": None, "unit": "score"}) + rows.append({"gate_id": gate_id, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": threshold_id}) + gates[group] = rows + thresholds.append({"threshold_id": "threshold.z.extra", "relation": "eq", "lower": 1, "upper": 1, "unit": "flag"}) + return sorted(thresholds, key=lambda row: str(row["threshold_id"]).encode()), gates + + def _managed_tests(self) -> dict[str, object]: + executed = sorted(exact_five.NEW_REQUIRED, key=str.encode) + receipt = { + "schema": "owned-root-assembly-successor-exact-five-managed-test-receipt.v1", "outcome": "success", + "invocation": {"environment": ["PYTHONHASHSEED=0"], "implementation_role": exact_five.RUNNER_ROLE, "mode": "managed-tests"}, + "activation_contract": self.identity["activation"], "design_contract": self.identity["design"], + "existing_dependencies": self.identity["dependencies"], "additive_implementation_files": self.identity["additive_files"], + "runtime": self.identity["runtime"], "runtime_fingerprint_sha256": self.identity["runtime_sha"], + "executed_test_ids": executed, "required_test_ids": list(exact_five.NEW_REQUIRED), + "results": {"tests_run": len(executed), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}, + } + raw = artifacts.canonical_json_bytes(receipt) + return {"receipt_sha256": artifacts.sha256_bytes(raw), "receipt": receipt} + + def _write_exact_root(self, *, invalid_ply: bool = False) -> None: + thresholds, gates = self._thresholds_and_gates() + public_records: dict[str, dict[str, object]] = {} + nested_profiles: list[dict[str, object]] = [] + base_ply = _ply() + if invalid_ply: + base_ply = base_ply.replace(b"format ascii 1.0", b"format ascii 1.1", 1) + neutral_payloads: list[dict[str, object]] | None = None + for index, profile_id in enumerate(exact_five.PROFILES): + profile_root = self.exact_root / profile_id + profile_root.mkdir() + (profile_root / "surface-level-2.ply").write_bytes(base_ply) + direct, lineage = _png((30 + index, 60, 90)), _png((90, 60 + index, 30)) + (profile_root / "direct.png").write_bytes(direct) + (profile_root / "lineage.png").write_bytes(lineage) + for role, data in (("surface-level-2.ply", base_ply), ("direct.png", direct), ("lineage.png", lineage)): + public_records[f"{profile_id}/{role}"] = self._record(f"{profile_id}/{role}", data) + local: dict[str, dict[str, object]] = {} + for role in exact_five.PAYLOAD_ROLES: + data = direct if role == "direct.png" else lineage if role == "lineage.png" else base_ply if role == "surface-level-2.ply" else f"{profile_id}:{role}".encode() + local[role] = self._record(role, data) + if neutral_payloads is None: + neutral_payloads = [local[role] for role in exact_five.PAYLOAD_ROLES] + if invalid_ply: + coordinate, triangles = {"bytes": 1, "sha256": "4" * 64}, {"bytes": 1, "sha256": "5" * 64} + else: + _, _, coordinate, triangles = exact_five._ply_digest(profile_root / "surface-level-2.ply", "surface-level-2.ply", 2) + levels = [] + for level in range(3): + counts = exact_five.neutral.LEVEL_COUNTS[level] + coordinates = coordinate if level == 2 else {"bytes": 1, "sha256": str(6 + level) * 64} + indices = triangles if level == 2 else {"bytes": 1, "sha256": str(8 + level) * 64} + levels.append({"level": level, "counts": {"level": level, "vertices": counts[0], "edges": counts[1], "quads": counts[2], "triangles": counts[3], "boundary_edges": counts[4]}, "coordinate_bytes": coordinates["bytes"], "coordinate_sha256": coordinates["sha256"], "triangle_index_bytes": indices["bytes"], "triangle_index_sha256": indices["sha256"], "ply": local[f"surface-level-{level}.ply"]}) + values, bindings = self._projection(index) + carrier_raw = artifacts.canonical_json_bytes([row["value"] for row in values]) + row = self.table[index] + selection = {"profile_pointer": f"/profiles/{index}", "profile_row_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row)), "dimension_scales_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["dimension_scales"])), "part_placements_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["part_placements"]))} + causality = [] + for parameter in sorted(exact_five.CAUSAL_COMPONENTS, key=str.encode): + role = f"perturb-{parameter.replace('.', '-')}.ply" + causality.append({"parameter_id": parameter, "prepared_component": exact_five.CAUSAL_COMPONENTS[parameter], "delta_m": 0.01, "support_level": 2, "predicted_support_count": 1, "observed_support_count": 1, "predicted_support_sha256": "a" * 64, "observed_support_sha256": "a" * 64, "maximum_movement_m": 0.001, "artifact": local[role]}) + config = exact_five.render.render_config_record() + visibility = {"level": 2, "triangle_count": 3328, "triangle_index_sha256": levels[2]["triangle_index_sha256"], "rule": "larger-depth-then-lower-triangle-index"} + nested = { + "schema": "owned-root-assembly-successor-profile-seed-evidence.v1", "outcome": "success", + "activation_contract": self.identity["activation"], "design_contract": self.identity["design"], "source": self.identity["source"], "profile_table": self.identity["profile"], + "existing_dependencies": self.identity["dependencies"], "additive_implementation_files": self.identity["additive_files"], "runtime": self.identity["runtime"], "runtime_fingerprint_sha256": self.identity["runtime_sha"], + "profile_id": profile_id, "profile_index": index, "selection": selection, "projected_values": values, + "projected_carrier": {"bytes": len(carrier_raw), "sha256": artifacts.sha256_bytes(carrier_raw)}, "projection_bindings": bindings, + "levels": levels, "thresholds": thresholds, "gates": gates, "causality": causality, + "renders": {"renderer_id": "owned-root-raster-pillow-11.1.0.v1", "render_config": config, "render_config_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(config)), "visibility": visibility, "visibility_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(visibility)), "direct": local["direct.png"], "lineage": local["lineage.png"], "same_surface_positions_sha256": levels[2]["coordinate_sha256"], "same_surface_triangles_sha256": levels[2]["triangle_index_sha256"]}, + "payloads": [local[role] for role in exact_five.PAYLOAD_ROLES], "invariants": dict(adapter.INVARIANTS), + } + nested_raw = artifacts.canonical_json_bytes(nested) + evidence_record = self._record("profile-seed-evidence.json", nested_raw) + sidecar_raw = f"{evidence_record['sha256']} profile-seed-evidence.json\n".encode() + stable_map = dict(local) + stable_map["profile-seed-evidence.json"] = evidence_record + stable_map["profile-seed-evidence.sha256"] = self._record("profile-seed-evidence.sha256", sidecar_raw) + nested_profiles.append({"profile_id": profile_id, "profile_index": index, "evidence": nested, "stable_cross_seed_comparisons": [stable_map[role] for role in exact_five.BUNDLE_STABLE_ROLES], "neutral_payload_comparisons": neutral_payloads if index == 0 else []}) + assert neutral_payloads is not None + payloads = [public_records[role] for role in exact_five.PUBLIC_PAYLOAD_ROLES] + evidence = { + "schema": "owned-root-assembly-successor-exact-five-evidence.v1", "outcome": "success", + "activation_contract": self.identity["activation"], "design_contract": self.identity["design"], "source": self.identity["source"], "profile_table": self.identity["profile"], + "existing_dependencies": self.identity["dependencies"], "additive_implementation_files": self.identity["additive_files"], "managed_tests": self._managed_tests(), + "neutral_baseline": {"comparison_report": self._fixed_record("comparison-report.json", exact_five.BASELINE_REPORT_SHA), "stable_manifest_sha256": exact_five.BASELINE_STABLE_SHA, "runtime_fingerprint_sha256": self.identity["runtime_sha"], "payload_comparisons": neutral_payloads}, + "runtime": self.identity["runtime"], "runtime_fingerprint_sha256": self.identity["runtime_sha"], "profile_order": list(exact_five.PROFILES), "profiles": nested_profiles, "payloads": payloads, + } + evidence_raw = artifacts.canonical_json_bytes(evidence) + (self.exact_root / "exact-five-evidence.json").write_bytes(evidence_raw) + evidence_sidecar = f"{hashlib.sha256(evidence_raw).hexdigest()} exact-five-evidence.json\n".encode() + (self.exact_root / "exact-five-evidence.sha256").write_bytes(evidence_sidecar) + final_gate_ids = (["exact-five.run.01.identity", "exact-five.run.02.managed-tests", "exact-five.run.03.publisher-baseline-admission"] + [f"exact-five.run.{4 + index * 2 + offset:02d}.profile.{profile}.seed-{seed}" for index, profile in enumerate(exact_five.PROFILES) for offset, seed in enumerate(exact_five.SEEDS)] + [f"exact-five.run.{14 + index:02d}.profile.{profile}.cross-seed" for index, profile in enumerate(exact_five.PROFILES)] + ["exact-five.run.19.standard-neutral-payload-equality", "exact-five.run.20.evidence-graph", "exact-five.run.21.pre-report-closure"]) + report = { + "schema": "owned-root-assembly-successor-exact-five-run-report.v1", "outcome": "success", "literal_invocation": {"environment": ["PYTHONHASHSEED=0"], "argv": [exact_five.LAUNCHER_ROLE]}, + "output_path": str(self.exact_root), "staging_path": str(self.exact_root.parent / ".stage"), "python_executable_path": sys.executable, "neutral_baseline_path": str(self.root / "baseline"), + "started_utc": "2026-01-01T00:00:00.000000Z", "finished_utc": "2026-01-01T00:00:01.000000Z", "timings": [], + "activation_contract_sha256": exact_five.ACTIVATION_SHA, "design_contract_sha256": exact_five.DESIGN_SHA, "runtime_fingerprint_sha256": self.identity["runtime_sha"], + "evidence": {**self._record("exact-five-evidence.json", evidence_raw), "schema": evidence["schema"]}, "evidence_sidecar": self._record("exact-five-evidence.sha256", evidence_sidecar), "payloads": payloads, + "profile_seed_runs": [{"profile_id": profile["profile_id"], "seed": seed, "outcome": "success", "evidence_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(profile["evidence"]))} for profile in nested_profiles for seed in exact_five.SEEDS], + "gates": [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in final_gate_ids], + } + report_raw = artifacts.canonical_json_bytes(report) + (self.exact_root / "run-report.json").write_bytes(report_raw) + (self.exact_root / "run-report.sha256").write_bytes(f"{hashlib.sha256(report_raw).hexdigest()} run-report.json\n".encode()) + + def _publish(self, review_id: str) -> dict[str, object]: + with mock.patch.object(adapter.exact_five, "_static", return_value=self.identity), mock.patch.object(adapter.exact_five, "_table", return_value=self.table): + return adapter.publish_exact_five_gallery(self.reviews_root, self.exact_root, review_id=review_id) + + def _reseal_evidence(self, evidence: dict[str, object]) -> None: + evidence_raw = artifacts.canonical_json_bytes(evidence) + (self.exact_root / "exact-five-evidence.json").write_bytes(evidence_raw) + sidecar = f"{hashlib.sha256(evidence_raw).hexdigest()} exact-five-evidence.json\n".encode() + (self.exact_root / "exact-five-evidence.sha256").write_bytes(sidecar) + report = json.loads((self.exact_root / "run-report.json").read_text()) + report["evidence"] = {**self._record("exact-five-evidence.json", evidence_raw), "schema": evidence["schema"]} + report["evidence_sidecar"] = self._record("exact-five-evidence.sha256", sidecar) + report_raw = artifacts.canonical_json_bytes(report) + (self.exact_root / "run-report.json").write_bytes(report_raw) + (self.exact_root / "run-report.sha256").write_bytes(f"{hashlib.sha256(report_raw).hexdigest()} run-report.json\n".encode()) + + def test_publishes_real_report_manifest_ref_and_five_ordered_pairs(self) -> None: + result = self._publish("exact-five-gallery-test") + self.assertEqual(result["images"], 10) + review = json.loads((self.reviews_root / "exact-five-gallery-test" / "review.json").read_text()) + self.assertEqual([group["id"] for group in review["groups"]], list(exact_five.PROFILES)) + self.assertIn("merge checkpoint", review["description"]) + for profile_id, group in zip(exact_five.PROFILES, review["groups"]): + self.assertEqual([item["id"] for item in group["items"]], [f"{profile_id}__direct", f"{profile_id}__lineage"]) + + def test_rejects_self_consistently_resealed_tampered_provenance(self) -> None: + evidence = json.loads((self.exact_root / "exact-five-evidence.json").read_text()) + evidence["design_contract"]["sha256"] = "f" * 64 + self._reseal_evidence(evidence) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "publication|provenance"): + self._publish("tampered-provenance") + self.assertFalse((self.reviews_root / "tampered-provenance").exists()) + + def test_rejects_self_consistently_recorded_invalid_ply(self) -> None: + shutil.rmtree(self.exact_root) + self.exact_root.mkdir() + self._write_exact_root(invalid_ply=True) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "PLY|semantic admission"): + self._publish("invalid-ply") + self.assertFalse((self.reviews_root / "invalid-ply").exists()) + + def test_rejects_png_tampering_against_exact_five_evidence(self) -> None: + path = self.exact_root / exact_five.PROFILES[0] / "direct.png" + data = bytearray(path.read_bytes()) + data[-20] ^= 1 + path.write_bytes(data) + with self.assertRaises(adapter.ExactFiveGalleryError): + self._publish("tampered") + + def test_rejects_extra_root_file_before_publishing(self) -> None: + (self.exact_root / "unexpected.bin").write_bytes(b"extra") + with self.assertRaises(adapter.ExactFiveGalleryError): + self._publish("extra-file") + + +if __name__ == "__main__": + raise SystemExit(unittest.main()) diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index 84ce099..e6a20bc 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -112,8 +112,24 @@ lane is not activated, these passes are not required. when its breadth and authority boundaries require it. Use Luna-xhigh for narrow convergence, implementation, or bounded technical review when that better fits the corpus. -- `gpt-5.6-sol` at `high` requires explicit human approval and is the absolute - subagent ceiling. Sol above medium is never implicit. +- `gpt-5.6-sol` at `high` or above requires explicit human approval. Sol above + medium is never implicit. +- Astra-high is an exceptional advisory route for direction adjudication, + difficult 3D or visual reasoning, or a high-consequence technical impasse + when Astra can materially improve the path. Astra advises; the main thread + still synthesizes and integrates, and Ben retains all product, architecture, + quality, and other human decisions. +- Before every Astra call, the main thread announces the purpose and bounded + scope to Ben. For one major checkpoint or decision batch, one primary Astra + call plus at most one adversarial follow-up is allowed without another + permission round. Additional calls require Ben's explicit approval. The + main thread reports Astra use and its material recommendations in the + handoff so Ben can see what informed the path. +- Astra-max/ultra, Astra as an orchestrator, and routine Astra use are + explicit-approval-only. Astra is not used for mechanical patches, ordinary + tests or CI, CodeRabbit, bookkeeping, or as a throughput substitute for + Luna. Promotional or reset capacity is temporary availability, not durable + policy or authority. - Terra is not a normal routing tier. ### Luna max admission gate @@ -298,7 +314,13 @@ The risk-scaled levels are: fresh passes with distinct named lenses, normally Sol at `medium` for foundational work. -More than `Double`, or Sol above `medium`, requires explicit human approval. +More than `Double` still requires explicit human approval, and Sol above +`medium` remains explicit-approval-only. Astra-high follows its separate +exceptional-use limit in [Model routing](#model-routing): at most one primary +call and one adversarial follow-up per major checkpoint or decision batch +without further permission. An Astra recommendation is advisory and cannot +accept a direction, DR, contract, or human checkpoint. + A material change to a proposal, constraints, alternatives, or consequences makes older reviews stale. When `Double` remains justified, the current revision normally receives two new passes. `Double` is one pass per reviewer diff --git a/docs/project/status.md b/docs/project/status.md index ed53862..ffc13f6 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -48,7 +48,7 @@ blockers. The bounded implementation phase completed at `correction_round=0`; the builder must reject a missing or mismatched design-contract identity. -The retained pre-seam neutral evidence baseline is commit +Historical round-0 neutral evidence is retained at commit `2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the 96-file publication in logical local cache `artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. That historical @@ -68,8 +68,16 @@ the runtime fingerprint is Main-thread visual appraisal found the neutral neck, shoulder/axilla, pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks -agreed and found no material blocker. The exact-five gate is therefore -unlocked, but no exact-five executable or gallery exists yet. +agreed and found no material blocker. The exact-five gate was therefore +unlocked. The local exact-five runner, publisher, launcher, focused tests, and +gallery adapter now exist. Projection across all five profiles is exact, and +focused non-success-path tests pass, but publication remains fail-closed: +four non-neutral profiles fail the unchanged gates. The canonical trigger +evidence is +`experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json` +(21,714 bytes; SHA-256 +`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with +39 observed failure records and ten profile/seed reproductions. The semantics-preserving numeric-only geometry seam and change batch fit the frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed @@ -85,16 +93,30 @@ and the current stable-manifest SHA-256 is The exact-five activation contract is frozen at SHA-256 `a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49`; -two independent Sol reviews returned `FREEZE` with no blockers. Next is its -sibling exact-five runner/publisher. Do not add a private-internal wrapper, -duplicate geometry, profile-aware branching, geometry correction, or a new -representation. - -The named human checkpoint remains Ben's later exact-five gallery appraisal of -the owned-root assembly, but only after standard neutral passes the unchanged -internal gates and the exact-five evidence is generated. The checkpoint uses -fixed front, side, and three-quarter final-surface renders. Internal metrics -and model reviews do not substitute for Ben's visual judgment. The [terminal +two independent Sol reviews returned `FREEZE` with no blockers. The exact-five +execution surface is present locally, but its fail-closed publication is not a +success result. Outside the bounded correction authorized below, do not add a +private-internal wrapper, duplicate geometry, profile-aware branching, +geometry correction, or a new representation. + +Ben explicitly authorized one bounded dimension-driven shared shoulder/hip +correction within the existing welded representation, preceded by feasibility. +No profile exceptions, clamps, gate or threshold relaxation, topology, +ownership, renderer, subdivision, or representation change is authorized. +Shoulder feasibility found a dimension-driven candidate that passes exact five +and coherent diagnostics. Hip feasibility found the frozen formula/support +restriction insufficient; Astra-high recommended exactly one bounded +deterministic fixed-topology pre-filter trial using already-admitted adjacent +station inputs. That advice is advisory evidence, not accepted architecture. +If the trial requires profile fitting, clamps, overshoot, topology or ownership +change, cap excess, or still fails required cases, stop rather than refreeze. +No formula has been accepted or implemented. + +The named human checkpoint remains Ben's exact-five gallery appraisal of the +owned-root assembly, but the fail-closed publication must first produce the +appraisable gallery evidence. The checkpoint uses fixed front, side, and +three-quarter final-surface renders. Internal metrics and model reviews do not +substitute for Ben's visual judgment. The [terminal seven-ring outcome](../research/programmatic-root-complex-surface-investigation.md#terminal-outcome-2026-09-03) remains historical evidence and is not reactivated. diff --git a/experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh b/experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh new file mode 100755 index 0000000..5600045 --- /dev/null +++ b/experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +set -euo pipefail + +ACTIVATION_SHA256="a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49" +DESIGN_SHA256="3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +SOURCE_SHA256="82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +PROFILE_SHA256="a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +BASELINE_REPORT_SHA256="fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a" +BASELINE_REPORT_SIDECAR_SHA256="27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac" +BASELINE_MANIFEST_SHA256="1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa" +RUNTIME_SHA256="c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" +SCRIPT_DIR="$(CDPATH='' cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(CDPATH='' cd -P -- "$SCRIPT_DIR/../.." && pwd)" +CURRENT_LAUNCHER="$REPO_ROOT/experiments/current-form-surface-preview/surface_preview_launcher.sh" +RUNNER_ROLE="experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py" +PUBLISHER_ROLE="experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py" +EXACT_PACKAGE="$REPO_ROOT/experiments/owned-root-assembly-successor-exact-five" +error() { printf 'exact-five-launcher: error: %s\n' "$*" >&2; exit 1; } +now_ns() { date +%s%N; } +disjoint() { [[ "$1" != "$2" && "$1" != "$2"/* && "$2" != "$1"/* ]]; } +remove_owned() { local p ok=0; for p in "$@"; do if [[ -L "$p" ]]; then ok=1; elif [[ -d "$p" ]]; then rm -rf -- "$p" || ok=1; elif [[ -e "$p" ]]; then rm -f -- "$p" || ok=1; fi; done; return "$ok"; } +cleanup() { local status=$?; trap - EXIT; if (( status != 0 )); then remove_owned "${BUNDLES[@]}" "${PROFILE_DIRS[@]}" "$RECEIPT" "$CONTEXT" "$PUBLIC_STAGE" || status=1; [[ -z "$INVOCATION_ROOT" || ! -d "$INVOCATION_ROOT" || -L "$INVOCATION_ROOT" ]] || rmdir -- "$INVOCATION_ROOT" 2>/dev/null || status=1; fi; exit "$status"; } +BUNDLES=(); PROFILE_DIRS=(); RECEIPT=""; CONTEXT=""; INVOCATION_ROOT=""; PUBLIC_STAGE="" +trap cleanup EXIT; trap 'exit 1' HUP INT TERM +[[ "${PYTHONHASHSEED-}" == 0 ]] || error 'public invocation requires literal PYTHONHASHSEED=0' +[[ $# == 4 && $1 == --baseline-root && $3 == --output ]] || error 'usage: PYTHONHASHSEED=0 exact_five_launcher.sh --baseline-root BASELINE_ROOT --output ABSENT_PATH' +BASELINE_ROOT="$2"; OUTPUT="$4" +[[ "$BASELINE_ROOT" == /* && "$BASELINE_ROOT" != / && -d "$BASELINE_ROOT" && ! -L "$BASELINE_ROOT" && "$(realpath -e -- "$BASELINE_ROOT")" == "$BASELINE_ROOT" ]] || error 'BASELINE_ROOT must be an existing canonical absolute directory' +[[ "$OUTPUT" == /* && "$(realpath -m -- "$OUTPUT")" == "$OUTPUT" && ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || error 'ABSENT_PATH must be a canonical absolute absent path' +OUTPUT_PARENT="$(dirname -- "$OUTPUT")"; [[ -d "$OUTPUT_PARENT" && ! -L "$OUTPUT_PARENT" && "$(realpath -e -- "$OUTPUT_PARENT")" == "$OUTPUT_PARENT" && -w "$OUTPUT_PARENT" ]] || error 'output parent must be an existing canonical writable directory' +FS_TYPE="$(df -P -T -- "$OUTPUT_PARENT" | awk 'NR == 2 {print $2}')"; case "$FS_TYPE" in ''|9p|drvfs|fuseblk|cifs|smb|smb2|smb3|ntfs|ntfs3|vfat|exfat|fat|fat32) error 'output parent must be native Linux storage';; esac +disjoint "$BASELINE_ROOT" "$OUTPUT_PARENT" || error 'BASELINE_ROOT must be disjoint from output and staging paths' +FIXED=( + "experiments/owned-root-assembly-successor/exact-five-activation-contract.md|-|$ACTIVATION_SHA256" + "experiments/owned-root-assembly-successor/design-contract.md|173184|$DESIGN_SHA256" + "examples/body-documents/stylized-digitigrade-biped-authored-form.json|56984|$SOURCE_SHA256" + "experiments/current-form-surface-preview/structural_profile_candidates.json|29970|$PROFILE_SHA256" + "experiments/owned-root-assembly-successor/anatomy_gates.py|25674|0c4b5f7812141a4cd7c7107655e578044355dfef5dbda6574bbb63bc359a2ff4" + "experiments/owned-root-assembly-successor/artifact_serialization.py|27977|3837928e4b987c65fd773e540f7db502f5d9a0b4c5940b95c923953754fdf7d4" + "experiments/owned-root-assembly-successor/build_owned_root.py|78268|713cbf967bf2e0e233bae0c3506199fdc9a6ed71418edbd8dbf9b75beeee4045" + "experiments/owned-root-assembly-successor/chart_lineage.py|18263|01fdd09e8e0bb6d31851f0c7af711d90b313e36a012dbe3d71415a0468c31efc" + "experiments/owned-root-assembly-successor/mesh_correctness.py|51035|4104b70e70e958a469125d1fff544e20fee44b784bf7915d8e724e63d4f39db1" + "experiments/owned-root-assembly-successor/owned_root_surface.py|58732|c982d889fee30e2efea881b5725170740bc8afa2a883aa3dc4623941cd3e2a22" + "experiments/owned-root-assembly-successor/prepared_projection.py|39646|58637097a350332db40368a027347ec395192880aa6ba4782c7d523e5b288190" + "experiments/owned-root-assembly-successor/render_export.py|15933|bc251ea3f3f3cb1aa5ea66bfc4f79a82f86191e76bacb9a3c4f58e64883c4780" + "experiments/current-form-surface-preview/generate_structural_profile_sources.py|54437|009be817cd2ec2db663b668fb5c9bdfa7296936283322e59d7a145e3d3cfec62" + "experiments/current-form-surface-preview/structural_atomic_publish.py|10489|5e648b3a1a3519afdf0fc1f2f1ecfe6fe7f1c58130f71fd2c8ee4317e2f282b5" + "experiments/current-form-surface-preview/surface_preview_launcher.sh|6582|3e18da2d361029a16558757d9727150d54c4d691b35c6a2a21b5b51cb7785190" + "experiments/current-form-surface-preview/requirements.txt|49|69a3ce10b1f993d7913f02ca187eabb8d367abf214662ffa2132feacbdeedbec" +) +for spec in "${FIXED[@]}"; do IFS='|' read -r role bytes digest <<< "$spec"; path="$REPO_ROOT/$role"; [[ -f "$path" && ! -L "$path" ]] || error "fixed file is not regular: $role"; [[ "$bytes" == - || "$(stat -c %s -- "$path")" == "$bytes" ]] || error "fixed byte count drift: $role"; [[ "$(sha256sum -- "$path" | awk '{print $1}')" == "$digest" ]] || error "fixed SHA-256 drift: $role"; done +for sidecar in "$REPO_ROOT/experiments/owned-root-assembly-successor/design-contract.sha256" "$REPO_ROOT/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256"; do [[ -f "$sidecar" && ! -L "$sidecar" ]] || error 'contract sidecar is not regular'; done +cmp -s <(printf '%s experiments/owned-root-assembly-successor/design-contract.md\n' "$DESIGN_SHA256") "$REPO_ROOT/experiments/owned-root-assembly-successor/design-contract.sha256" || error 'design-contract sidecar drift' +cmp -s <(printf '%s experiments/owned-root-assembly-successor/exact-five-activation-contract.md\n' "$ACTIVATION_SHA256") "$REPO_ROOT/experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256" || error 'activation-contract sidecar drift' +[[ -d "$EXACT_PACKAGE" && ! -L "$EXACT_PACKAGE" && -d "$EXACT_PACKAGE/tests" && ! -L "$EXACT_PACKAGE/tests" ]] || error 'exact-five package is incomplete' +EXPECTED_FILES="$(printf '%s\n' 'f exact_five_launcher.sh' 'f exact_five_publisher.py' 'f exact_five_runner.py' 'f tests/test_exact_five_activation.py' | LC_ALL=C sort)"; ACTUAL_FILES="$(LC_ALL=C find -P "$EXACT_PACKAGE" \( -type f -o -type l \) \( -name '*.py' -o -name '*.sh' \) -printf '%y %P\n' | LC_ALL=C sort)"; [[ "$ACTUAL_FILES" == "$EXPECTED_FILES" ]] || error 'exact-five source inventory drift' +for role in exact_five_launcher.sh exact_five_runner.py exact_five_publisher.py tests/test_exact_five_activation.py; do path="$EXACT_PACKAGE/$role"; [[ -f "$path" && ! -L "$path" && $(stat -c %s -- "$path") -le 4000000 ]] || error "additive file is invalid: $role"; done +NON_TEST_LOC=$(( $(wc -l < "$EXACT_PACKAGE/exact_five_launcher.sh") + $(wc -l < "$EXACT_PACKAGE/exact_five_runner.py") + $(wc -l < "$EXACT_PACKAGE/exact_five_publisher.py") )); TEST_LOC=$(wc -l < "$EXACT_PACKAGE/tests/test_exact_five_activation.py"); [[ $NON_TEST_LOC -le 1600 && $TEST_LOC -le 1200 ]] || error 'additive physical LOC cap exceeded' + +pinned() { local seed="$1"; shift; PYTHONHASHSEED="$seed" "$CURRENT_LAUNCHER" - "$@" <<'PY' +import importlib, importlib.metadata, importlib.util, math, os, re, stat, sys +from pathlib import Path +mode, repo = sys.argv[1], Path(sys.argv[2]) +def bad(message): raise SystemExit("exact-five launcher: " + message) +def canon(value): return type(value) is str and value.startswith("/") and os.path.normpath(value) == value and "//" not in value +def keys(value, names): return isinstance(value, dict) and set(value) == set(names) +def record(path, role, cap=4 * 1024 * 1024): + import artifact_serialization as a + return a.regular_file_record(path, role, max_bytes=cap) +def sidecar(raw, payload, name): + import artifact_serialization as a + if raw != f"{a.sha256_bytes(payload)} {name}\n".encode("ascii"): bad(name + " sidecar drift") +if mode == "runtime": + if (sys.implementation.name, sys.version_info[:3], sys.platform, getattr(sys.implementation, "cache_tag", None)) != ("cpython", (3, 10, 12), "linux", "cpython-310"): bad("runtime is not pinned CPython 3.10.12 Linux") + for name, version in (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")): + if importlib.metadata.version(name) != version: bad("runtime distribution drift: " + name) + for name in ("math", "zlib"): + module, spec = importlib.import_module(name), importlib.util.find_spec(name) + if getattr(module, "__file__", None) is not None or spec is None or spec.origin != "built-in": bad("built-in module admission failed: " + name) + raise SystemExit(0) +sys.path.insert(0, str(repo / "experiments/owned-root-assembly-successor")) +import artifact_serialization as a +def json_file(path, cap=2 * 1024 * 1024): return a.decode_canonical_json(a.read_regular_file(path, max_bytes=cap)) +def baseline(root): + import build_owned_root as b + roles, stable_roles = tuple(b.ARTIFACT_ROLES), tuple(sorted(set(b.ARTIFACT_ROLES) - {"report.json", "report.sha256"}, key=lambda x: x.encode())) + entries = list(os.scandir(root)); names = sorted(x.name for x in entries); expected = ["comparison", "seed-17", "seed-29"] + if names != expected or any(not (root / n).is_dir() or (root / n).is_symlink() for n in expected): bad("baseline outer inventory drift") + maps = {} + for seed in (17, 29): + rows = list(a.closed_inventory(root / f"seed-{seed}", roles, max_file_bytes=8 * 1024 * 1024)); maps[seed] = {x["role_path"]: x for x in rows} + if len(rows) != 47 or any(x["bytes"] > (8 if x["role_path"] == "causality-manifest.json" else 2) * 1024 * 1024 for x in rows): bad("baseline seed size or inventory drift") + comp = root / "comparison"; crows = list(a.closed_inventory(comp, ("comparison-report.json", "comparison-report.sha256"), max_file_bytes=2 * 1024 * 1024)); raw = a.read_regular_file(comp / "comparison-report.json", max_bytes=2 * 1024 * 1024); sc = a.read_regular_file(comp / "comparison-report.sha256", max_bytes=128) + expected_report, expected_sidecar, expected_manifest, expected_runtime = sys.argv[4:8] + if len(raw) != 24640 or a.sha256_bytes(raw) != expected_report or len(sc) != 89 or a.sha256_bytes(sc) != expected_sidecar or sc != f"{expected_report} comparison-report.json\n".encode(): bad("baseline comparison identity drift") + report = a.decode_canonical_json(raw); comp_record = record(repo / "experiments/owned-root-assembly-successor/compare_two_seed_outputs.py", "experiments/owned-root-assembly-successor/compare_two_seed_outputs.py") + if not keys(report, ("schema", "outcome", "comparator", "runtime_fingerprint_sha256", "managed_test_receipt", "seed_bundles", "stable_comparisons", "excluded_run_local_roles")) or report["schema"] != "owned-root-assembly-successor-comparison-report.v1" or report["outcome"] != "success" or report["comparator"] != comp_record or report["runtime_fingerprint_sha256"] != expected_runtime or report["excluded_run_local_roles"] != ["report.json", "report.sha256"]: bad("baseline comparison schema or identity drift") + receipt = report["managed_test_receipt"]; impl = [record(repo / role, role) for role in sorted(b.IMPLEMENTATION_ROLES, key=lambda x: x.encode())]; results = receipt.get("results", {}); invocation = receipt.get("literal_invocation", {}); argv = invocation.get("argv", []) + if not keys(receipt, ("schema", "outcome", "literal_invocation", "contract_sha256", "runtime_fingerprint_sha256", "implementation_files", "executed_test_ids", "required_test_ids", "results")) or receipt["schema"] != "owned-root-assembly-successor-managed-test-receipt.v1" or receipt["outcome"] != "success" or receipt["contract_sha256"] != "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" or receipt["runtime_fingerprint_sha256"] != "c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" or receipt["implementation_files"] != impl or receipt["required_test_ids"] != list(b.REQUIRED_TEST_IDS) or not keys(invocation, ("environment", "argv")) or receipt["executed_test_ids"] != sorted(set(receipt["executed_test_ids"]), key=lambda x: x.encode()) or len(receipt["executed_test_ids"]) != 134 or not all(receipt["executed_test_ids"].count(x) == 1 for x in b.REQUIRED_TEST_IDS) or not (invocation.get("environment") == ["PYTHONHASHSEED=0"] and len(argv) == 4 and argv[:3] == ["experiments/owned-root-assembly-successor/build_owned_root.py", "--internal-managed-tests", "--receipt"] and canon(argv[3]) and Path(argv[3]).name == "managed-test-receipt.json") or not (keys(results, ("tests_run", "failures", "errors", "skipped", "expected_failures", "unexpected_successes")) and results == {"tests_run": 134, "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}): bad("baseline managed receipt drift") + comparisons = report["stable_comparisons"] + if [x.get("role_path") for x in comparisons] != list(stable_roles) or len(report["seed_bundles"]) != 2: bad("baseline stable comparison inventory drift") + for index, seed in enumerate((17, 29)): + sm = root / f"seed-{seed}" / "stable-manifest.json"; stable = json_file(sm); mr = maps[seed]; recipe = stable.get("recipe_id"); expected_refs = {field: (role, "owned-root-assembly-successor-" + field.removesuffix("_manifest") + "-manifest.v1") for field, role in (("input_manifest", "input-manifest.json"), ("coordinate_manifest", "coordinate-manifest.json"), ("gate_manifest", "gate-manifest.json"), ("causality_manifest", "causality-manifest.json"), ("render_manifest", "render-manifest.json"))} + if len(mr) != 47 or mr["stable-manifest.json"]["sha256"] != expected_manifest or not keys(stable, ("schema", "contract_sha256", "recipe_id", "runtime", "implementation_files", "input_manifest", "coordinate_manifest", "gate_manifest", "causality_manifest", "render_manifest", "artifact_hashes")) or stable["schema"] != "owned-root-assembly-successor-stable-manifest.v1" or stable["contract_sha256"] != "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" or not isinstance(recipe, str) or len(recipe) != 64 or stable["implementation_files"] != impl or a.sha256_bytes(a.canonical_json_bytes(stable["runtime"])) != expected_runtime or stable["artifact_hashes"] != [mr[x] for x in sorted(b.STABLE_ARTIFACT_ROLES, key=lambda x: x.encode())] or any(stable[field] != {"role_path": role, "bytes": mr[role]["bytes"], "sha256": mr[role]["sha256"], "schema": schema} for field, (role, schema) in expected_refs.items()): bad("baseline stable manifest drift") + rp = root / f"seed-{seed}" / "report.json"; rv = json_file(rp); rr = maps[seed]; inv = rv.get("literal_invocation", {}); args = inv.get("argv", []); out, stage, exe = (Path(rv.get(x, "")) for x in ("output_path", "staging_path", "python_executable_path")); timings = rv.get("timings", []); gates = rv.get("gates", []) + if not keys(rv, ("schema", "outcome", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "stable_manifest", "gates")) or rv["schema"] != "owned-root-assembly-successor-run-report.v1" or rv["outcome"] != "success" or type(rv["seed"]) is not int or rv["seed"] != seed or rv["runtime_fingerprint_sha256"] != "c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" or not (keys(inv, ("environment", "argv")) and all(canon(str(x)) for x in (out, stage, exe)) and out.name == f"seed-{seed}" and stage.parent == out.parent and stage.name.startswith(f".{out.name}.stage-") and inv.get("environment") == [f"PYTHONHASHSEED={seed}"] and args == ["experiments/owned-root-assembly-successor/build_owned_root.py", "--output", str(out)] and re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z", rv["started_utc"]) and re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z", rv["finished_utc"]) and rv["finished_utc"] >= rv["started_utc"]) or not (isinstance(timings, list) and all(keys(x, ("phase", "seconds")) and type(x["seconds"]) is float and math.isfinite(x["seconds"]) and x["seconds"] >= 0 for x in timings)) or [x.get("phase") for x in timings] != list(b.RUN_PHASES) or rv["stable_manifest"] != {"role_path": "stable-manifest.json", "bytes": rr["stable-manifest.json"]["bytes"], "sha256": rr["stable-manifest.json"]["sha256"], "schema": "owned-root-assembly-successor-stable-manifest.v1"} or rv["gates"] != [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in b.RUN_REPORT_GATES]: bad("baseline run report drift") + sidecar(a.read_regular_file(root / f"seed-{seed}" / "report.sha256", max_bytes=128), a.read_regular_file(rp, max_bytes=2 * 1024 * 1024), "report.json") + expected_bundle = {"seed": seed, "role_path": f"seed-{seed}", "stable_manifest": {"role_path": f"seed-{seed}/stable-manifest.json", "bytes": rr["stable-manifest.json"]["bytes"], "sha256": rr["stable-manifest.json"]["sha256"], "schema": "owned-root-assembly-successor-stable-manifest.v1"}, "report": {**rr["report.json"], "role_path": f"seed-{seed}/report.json"}, "report_sidecar": {**rr["report.sha256"], "role_path": f"seed-{seed}/report.sha256"}} + if report["seed_bundles"][index] != expected_bundle or any(mr[x] != y for x, y in zip(stable_roles, comparisons)): bad("baseline comparison record drift") + if len(crows) + sum(len(m) for m in maps.values()) != 96 or any(list(a.closed_inventory(root / f"seed-{seed}", roles, max_file_bytes=8 * 1024 * 1024)) != list(maps[seed].values()) for seed in (17, 29)) or list(a.closed_inventory(comp, ("comparison-report.json", "comparison-report.sha256"), max_file_bytes=2 * 1024 * 1024)) != crows: bad("baseline closed inventory changed during admission") +baseline(Path(sys.argv[3])) if mode == "baseline" else None +if mode == "context": + path, base, output = map(Path, sys.argv[3:6]); ns = [int(x) for x in sys.argv[6:14]]; pairs = zip(ns[::2], ns[1::2]); value = {"schema": "owned-root-assembly-successor-exact-five-launcher-context.v1", "literal_invocation": {"environment": ["PYTHONHASHSEED=0"], "argv": ["experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh", "--baseline-root", str(base), "--output", str(output)]}, "output_path": str(output), "neutral_baseline_path": str(base), "timings": [{"phase": phase, "seconds": float(end - start) / 1e9} for phase, (start, end) in zip(("identity", "managed-tests", "launcher-baseline-admission", "profile-seed-builds"), pairs)]}; raw = a.canonical_json_bytes(value); len(raw) <= 64 * 1024 or bad("launcher context exceeds size cap"); a.write_bytes_no_replace(path, raw) +def final_tree(stage, destination, expected_digest, publish, baseline_root): + profiles = ["standard_neutral_reference", "compact_broad_short_limb_large_head", "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested"]; roles = [f"{p}/{name}" for p in profiles for name in ("surface-level-2.ply", "direct.png", "lineage.png")] + ["exact-five-evidence.json", "exact-five-evidence.sha256", "run-report.json", "run-report.sha256"]; rows = list(a.closed_inventory(stage, roles, max_file_bytes=16 * 1024 * 1024)); rm = {x["role_path"]: x for x in rows}; total = sum(x["bytes"] for x in rows) + if len(rows) != 19 or total > 32 * 1024 * 1024 or any(x["bytes"] > (16 if x["role_path"] == "exact-five-evidence.json" else 2) * 1024 * 1024 for x in rows): bad("sealed publication inventory or size drift") + eraw = a.read_regular_file(stage / "exact-five-evidence.json", max_bytes=16 * 1024 * 1024); rraw = a.read_regular_file(stage / "run-report.json", max_bytes=2 * 1024 * 1024); evidence = a.decode_canonical_json(eraw); report = a.decode_canonical_json(rraw); payloads = sorted((rm[x] for x in roles if "/" in x), key=lambda x: x["role_path"].encode()) + if not keys(evidence, ("schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", "existing_dependencies", "additive_implementation_files", "managed_tests", "neutral_baseline", "runtime", "runtime_fingerprint_sha256", "profile_order", "profiles", "payloads")) or evidence["schema"] != "owned-root-assembly-successor-exact-five-evidence.v1" or evidence["outcome"] != "success" or evidence["profile_order"] != profiles or evidence["payloads"] != payloads or not keys(report, ("schema", "outcome", "literal_invocation", "output_path", "staging_path", "python_executable_path", "neutral_baseline_path", "started_utc", "finished_utc", "timings", "activation_contract_sha256", "design_contract_sha256", "runtime_fingerprint_sha256", "evidence", "evidence_sidecar", "payloads", "profile_seed_runs", "gates")) or report["schema"] != "owned-root-assembly-successor-exact-five-run-report.v1" or report["outcome"] != "success" or report["activation_contract_sha256"] != "a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49" or report["design_contract_sha256"] != "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" or report["runtime_fingerprint_sha256"] != "c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" or report["neutral_baseline_path"] != str(baseline_root) or report["payloads"] != payloads or report["evidence"] != {"role_path": "exact-five-evidence.json", "bytes": rm["exact-five-evidence.json"]["bytes"], "sha256": rm["exact-five-evidence.json"]["sha256"], "schema": evidence["schema"]} or report["evidence_sidecar"] != rm["exact-five-evidence.sha256"] or len(report["profile_seed_runs"]) != 10 or len(report["gates"]) != 21: bad("final evidence graph drift") + sidecar(a.read_regular_file(stage / "exact-five-evidence.sha256", max_bytes=256), eraw, "exact-five-evidence.json"); sidecar(a.read_regular_file(stage / "run-report.sha256", max_bytes=256), rraw, "run-report.json"); digest = a.sha256_bytes(a.canonical_json_bytes(rows)); + if publish: + if digest != expected_digest: bad("sealed tree changed during exact cleanup") + a.publish_no_replace(stage, destination, rows, max_file_bytes=16 * 1024 * 1024) + else: print(digest) +if mode == "final-check": final_tree(Path(sys.argv[3]), Path(sys.argv[4]), "", False, Path(sys.argv[5])) +if mode == "final-publish": final_tree(Path(sys.argv[3]), Path(sys.argv[4]), sys.argv[5], True, Path(sys.argv[6])) +PY +} + +cd -- "$REPO_ROOT"; IDENTITY_START="$(now_ns)"; pinned 0 runtime "$REPO_ROOT"; IDENTITY_END="$(now_ns)" +TOKEN="$(tr -d '-' < /proc/sys/kernel/random/uuid 2>/dev/null || true)"; [[ -n "$TOKEN" ]] || TOKEN="$RANDOM$RANDOM"; INVOCATION_ROOT="$OUTPUT_PARENT/.exact-five-$TOKEN"; PUBLIC_STAGE="$OUTPUT_PARENT/.exact-five-public-$TOKEN"; RECEIPT="$INVOCATION_ROOT/managed-test-receipt.json"; CONTEXT="$INVOCATION_ROOT/launcher-context.json"; [[ ! -e "$INVOCATION_ROOT" && ! -L "$INVOCATION_ROOT" && ! -e "$PUBLIC_STAGE" && ! -L "$PUBLIC_STAGE" ]] || error 'selected staging path is occupied'; BUNDLES=() +MANAGED_START="$(now_ns)"; CK_EXACT_FIVE_BASELINE_ROOT="$BASELINE_ROOT" PYTHONHASHSEED=0 "$CURRENT_LAUNCHER" "$REPO_ROOT/$RUNNER_ROLE" --internal-managed-tests --receipt "$RECEIPT"; MANAGED_END="$(now_ns)"; [[ -f "$RECEIPT" && ! -L "$RECEIPT" && -d "$INVOCATION_ROOT" ]] || error 'managed tests did not seal their receipt' +BASELINE_START="$(now_ns)"; pinned 0 baseline "$REPO_ROOT" "$BASELINE_ROOT" "$BASELINE_REPORT_SHA256" "$BASELINE_REPORT_SIDECAR_SHA256" "$BASELINE_MANIFEST_SHA256" "$RUNTIME_SHA256"; BASELINE_END="$(now_ns)" +PROFILES=(standard_neutral_reference compact_broad_short_limb_large_head tall_narrow_long_legged slender_long_limb stocky_broad_chested); PROFILE_START="$(now_ns)" +for profile_index in 0 1 2 3 4; do profile="${PROFILES[$profile_index]}"; profile_dir="$INVOCATION_ROOT/profile-$profile_index"; mkdir -m 700 -- "$profile_dir"; PROFILE_DIRS+=("$profile_dir"); for seed in 17 29; do bundle="$profile_dir/seed-$seed"; BUNDLES+=("$bundle"); [[ ! -e "$bundle" && ! -L "$bundle" ]] || error 'profile bundle path is occupied'; PYTHONHASHSEED="$seed" "$CURRENT_LAUNCHER" "$REPO_ROOT/$RUNNER_ROLE" --profile "$profile" --output "$bundle"; done; done +PROFILE_END="$(now_ns)"; pinned 0 context "$REPO_ROOT" "$CONTEXT" "$BASELINE_ROOT" "$OUTPUT" "$IDENTITY_START" "$IDENTITY_END" "$MANAGED_START" "$MANAGED_END" "$BASELINE_START" "$BASELINE_END" "$PROFILE_START" "$PROFILE_END" +PYTHONHASHSEED=0 "$CURRENT_LAUNCHER" "$REPO_ROOT/$PUBLISHER_ROLE" "$BASELINE_ROOT" "${BUNDLES[@]}" "$RECEIPT" "$CONTEXT" "$PUBLIC_STAGE" +[[ -d "$PUBLIC_STAGE" && ! -L "$PUBLIC_STAGE" ]] || error 'publisher did not seal the public staging tree'; SEALED_DIGEST="$(pinned 0 final-check "$REPO_ROOT" "$PUBLIC_STAGE" "$OUTPUT" "$BASELINE_ROOT" | tail -n 1)" +remove_owned "${BUNDLES[@]}" "${PROFILE_DIRS[@]}" "$RECEIPT" "$CONTEXT" || error 'exact ephemeral cleanup failed'; [[ ! -e "$INVOCATION_ROOT" || -L "$INVOCATION_ROOT" ]] || rmdir -- "$INVOCATION_ROOT" || error 'invocation staging root remained after exact cleanup' +pinned 0 final-publish "$REPO_ROOT" "$PUBLIC_STAGE" "$OUTPUT" "$SEALED_DIGEST" "$BASELINE_ROOT" diff --git a/experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py b/experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py new file mode 100644 index 0000000..9268f68 --- /dev/null +++ b/experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py @@ -0,0 +1,615 @@ +"""Path-neutral publisher for the frozen exact-five activation.""" +from __future__ import annotations + +import importlib.metadata +import importlib.util +import io +import json +import locale +import math +import os +import platform +import re +import struct +import sys +import sysconfig +import time +import datetime +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +NEUTRAL = ROOT / "experiments/owned-root-assembly-successor" +PACKAGE = ROOT / "experiments/owned-root-assembly-successor-exact-five" +sys.path.insert(0, str(NEUTRAL)) +import artifact_serialization as artifacts # noqa: E402 +import build_owned_root as neutral # noqa: E402 +import render_export as render # noqa: E402 + +ACTIVATION_ROLE = "experiments/owned-root-assembly-successor/exact-five-activation-contract.md" +ACTIVATION_SHA = "a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49" +DESIGN_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +DESIGN_SHA = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +SOURCE_SHA = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" +PROFILE_SHA = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +RUNTIME_SHA = "c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" +BASELINE_REPORT_SHA = "fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a" +BASELINE_REPORT_SIDE_SHA = "27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac" +BASELINE_STABLE_SHA = "1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa" +BUILDER_ROLE = "experiments/owned-root-assembly-successor/build_owned_root.py" +COMPARATOR_ROLE = "experiments/owned-root-assembly-successor/compare_two_seed_outputs.py" +LAUNCHER_ROLE = "experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh" +RUNNER_ROLE = "experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py" +PUBLISHER_ROLE = "experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py" +ADDITIVE_ROLES = tuple(sorted((LAUNCHER_ROLE, RUNNER_ROLE, PUBLISHER_ROLE, + "experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py"), key=str.encode)) +PROFILES = ("standard_neutral_reference", "compact_broad_short_limb_large_head", "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested") +SEEDS = (17, 29) +PAYLOAD_ROLES = tuple(sorted(set(neutral.ARTIFACT_ROLES) - {"input-manifest.json", "coordinate-manifest.json", "gate-manifest.json", "causality-manifest.json", "render-manifest.json", "stable-manifest.json", "prepared-input.json", "report.json", "report.sha256"}, key=str.encode)) +BASELINE_STABLE_ROLES = tuple(sorted(set(neutral.ARTIFACT_ROLES) - {"report.json", "report.sha256"}, key=str.encode)) +BUNDLE_ROLES = tuple(sorted((*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256", "run-report.json", "run-report.sha256"), key=str.encode)) +BUNDLE_STABLE_ROLES = tuple(sorted((*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256"), key=str.encode)) +PUBLIC_PAYLOAD_ROLES = tuple(sorted(tuple(f"{profile}/surface-level-2.ply" for profile in PROFILES) + tuple(f"{profile}/{role}" for profile in PROFILES for role in ("direct.png", "lineage.png")), key=str.encode)) +PUBLIC_ROLES = tuple(sorted((*PUBLIC_PAYLOAD_ROLES, "exact-five-evidence.json", "exact-five-evidence.sha256", "run-report.json", "run-report.sha256"), key=str.encode)) +PRE_REPORT_ROLES = tuple(sorted((*PUBLIC_PAYLOAD_ROLES, "exact-five-evidence.json", "exact-five-evidence.sha256"), key=str.encode)) +BASELINE_ROLES = tuple(sorted((*[f"seed-{seed}/{role}" for seed in SEEDS for role in neutral.ARTIFACT_ROLES], "comparison/comparison-report.json", "comparison/comparison-report.sha256"), key=str.encode)) +COMPONENT_IDS = tuple(sorted(tuple(f"stations.{station}.{field}" for station in ("lower_pelvis", "upper_pelvis", "lower_abdomen", "waist_abdomen", "upper_abdomen", "lower_ribcage", "upper_ribcage_shoulder", "neck_collar", "neck_upper") for field in ("C.x", "C.y", "C.z", "rL", "rA", "rP")) + tuple(f"shoulders.{side}.{field}" for side in ("left", "right") for field in ("axilla.x", "axilla.y", "axilla.z", "peak.x", "peak.y", "peak.z", "arm_origin.x", "arm_origin.y", "arm_origin.z", "start_lateral", "start_up", "start_forward", "shoulder_depth")) + tuple(f"hips.{side}.{field}" for side in ("left", "right") for field in ("P_s.x", "P_s.y", "P_s.z", "r_x", "r_y", "r_z")), key=str.encode)) +CAUSAL_COMPONENTS = {"left.r_y": "hips.left.r_y", "right.r_y": "hips.right.r_y", "lower_pelvis.L_y": "stations.lower_pelvis.C.y", "lower_pelvis.C_z": "stations.lower_pelvis.C.z", "left.r_x": "hips.left.r_x", "right.r_x": "hips.right.r_x", "lower_pelvis.R_x": "stations.lower_pelvis.rL", "left.r_z": "hips.left.r_z", "right.r_z": "hips.right.r_z", "lower_pelvis.R_f": "stations.lower_pelvis.rA", "lower_pelvis.R_b": "stations.lower_pelvis.rP", "left.thigh_start_x": "hips.left.P_s.x", "left.thigh_start_y": "hips.left.P_s.y", "left.thigh_start_z": "hips.left.P_s.z", "right.thigh_start_x": "hips.right.P_s.x", "right.thigh_start_y": "hips.right.P_s.y", "right.thigh_start_z": "hips.right.P_s.z", "neck_collar.C_y": "stations.neck_collar.C.y", "neck_collar.rL": "stations.neck_collar.rL", "neck_upper.C_y": "stations.neck_upper.C.y", "neck_upper.rL": "stations.neck_upper.rL", "left.axilla_x": "shoulders.left.axilla.x", "left.axilla_y": "shoulders.left.axilla.y", "right.axilla_x": "shoulders.right.axilla.x", "right.axilla_y": "shoulders.right.axilla.y", "left.peak_y": "shoulders.left.peak.y", "right.peak_y": "shoulders.right.peak.y", "left.start_lateral": "shoulders.left.start_lateral", "right.start_lateral": "shoulders.right.start_lateral", "left.start_up": "shoulders.left.start_up", "right.start_up": "shoulders.right.start_up", "left.shoulder_depth": "shoulders.left.shoulder_depth", "right.shoulder_depth": "shoulders.right.shoulder_depth"} +EXPECTED_DEPS = {"experiments/owned-root-assembly-successor/anatomy_gates.py": (25674, "0c4b5f7812141a4cd7c7107655e578044355dfef5dbda6574bbb63bc359a2ff4"), "experiments/owned-root-assembly-successor/artifact_serialization.py": (27977, "3837928e4b987c65fd773e540f7db502f5d9a0b4c5940b95c923953754fdf7d4"), "experiments/owned-root-assembly-successor/build_owned_root.py": (78268, "713cbf967bf2e0e233bae0c3506199fdc9a6ed71418edbd8dbf9b75beeee4045"), "experiments/owned-root-assembly-successor/chart_lineage.py": (18263, "01fdd09e8e0bb6d31851f0c7af711d90b313e36a012dbe3d71415a0468c31efc"), "experiments/owned-root-assembly-successor/mesh_correctness.py": (51035, "4104b70e70e958a469125d1fff544e20fee44b784bf7915d8e724e63d4f39db1"), "experiments/owned-root-assembly-successor/owned_root_surface.py": (58732, "c982d889fee30e2efea881b5725170740bc8afa2a883aa3dc4623941cd3e2a22"), "experiments/owned-root-assembly-successor/prepared_projection.py": (39646, "58637097a350332db40368a027347ec395192880aa6ba4782c7d523e5b288190"), "experiments/owned-root-assembly-successor/render_export.py": (15933, "bc251ea3f3f3cb1aa5ea66bfc4f79a82f86191e76bacb9a3c4f58e64883c4780"), "experiments/current-form-surface-preview/generate_structural_profile_sources.py": (54437, "009be817cd2ec2db663b668fb5c9bdfa7296936283322e59d7a145e3d3cfec62"), "experiments/current-form-surface-preview/structural_atomic_publish.py": (10489, "5e648b3a1a3519afdf0fc1f2f1ecfe6fe7f1c58130f71fd2c8ee4317e2f282b5"), "experiments/current-form-surface-preview/surface_preview_launcher.sh": (6582, "3e18da2d361029a16558757d9727150d54c4d691b35c6a2a21b5b51cb7785190"), "experiments/current-form-surface-preview/requirements.txt": (49, "69a3ce10b1f993d7913f02ca187eabb8d367abf214662ffa2132feacbdeedbec")} +OLD_REQUIRED = ("test_mesh_correctness.ProductionIntersectionFixtureTests.test_contract_fixture_matrix", "test_owned_root_surface.ProductionAxillaryFixtureTests.test_contract_fixture_matrix") +NEW_REQUIRED = ("test_exact_five_activation.ExactFiveActivationTests.test_all_33_selectors_copy_one_component", "test_exact_five_activation.ExactFiveActivationTests.test_atomic_failure_has_no_partial_publication", "test_exact_five_activation.ExactFiveActivationTests.test_decimal_half_even_boundaries", "test_exact_five_activation.ExactFiveActivationTests.test_final_evidence_schema_and_19_file_closure", "test_exact_five_activation.ExactFiveActivationTests.test_geometry_receives_only_components", "test_exact_five_activation.ExactFiveActivationTests.test_neutral_projection_preserves_38_payloads", "test_exact_five_activation.ExactFiveActivationTests.test_profile_seed_bundle_schema_and_closure", "test_exact_five_activation.ExactFiveActivationTests.test_profile_table_closed_and_exact_order", "test_exact_five_activation.ExactFiveActivationTests.test_profile_table_rejects_duplicate_keys_and_signatures", "test_exact_five_activation.ExactFiveActivationTests.test_projection_has_exact_92_bindings", "test_exact_five_activation.ExactFiveActivationTests.test_seed_dispatch_is_exact", "test_exact_five_activation.ExactFiveActivationTests.test_static_identity_and_allowlist") +SHA = re.compile(r"[0-9a-f]{64}\Z") +UTC = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\Z") + + +class PublisherError(ValueError): + pass + + +def _need(condition, message): + if not condition: + raise PublisherError(message) + + +def _keys(value, expected, label): + _need(type(value) is dict and set(value) == set(expected), f"{label} has non-closed keys") + return value + + +def _hex(value, label): + _need(type(value) is str and SHA.fullmatch(value) is not None, f"{label} is not lowercase SHA-256") + return value + + +def _abs(value, label): + _need(type(value) is str and value and Path(value).is_absolute() and os.path.normpath(value) == value and "//" not in value, f"{label} is not canonical absolute") + return Path(value) + + +def _fr(value, label, role=None): + _keys(value, ("role_path", "bytes", "sha256"), label) + try: + artifacts.validate_role_path(value["role_path"]) + except Exception as exc: + raise PublisherError(f"{label} has an invalid role") from exc + _need(role is None or value["role_path"] == role, f"{label} has the wrong role") + _need(type(value["bytes"]) is int and value["bytes"] >= 0, f"{label} has an invalid byte count") + _hex(value["sha256"], f"{label}.sha256") + return value + + +def _record(path, role, cap=4 * 1024 * 1024): + return artifacts.regular_file_record(path, role, max_bytes=cap) + + +def _json(path, cap=16 * 1024 * 1024): + raw = artifacts.read_regular_file(path, max_bytes=cap) + try: + value = artifacts.decode_canonical_json(raw) + except Exception as exc: + raise PublisherError(f"{path} is not canonical JSON") from exc + _need(type(value) is dict, f"{path} is not an object") + return value, raw + + +def _same_record(path, role, expected, cap=16 * 1024 * 1024): + actual = _record(path, role, cap) + _need(actual == expected, f"{role} changed after inventory") + return actual + + +def _sidecar(raw, payload, name): + _need(raw == f"{artifacts.sha256_bytes(payload)} {name}\n".encode("ascii"), f"{name} sidecar is invalid") + + +def _now(): + return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def _bounded(value, label, limit=128): + _need(type(value) is str and len(value.encode("utf-8")) <= limit, f"{label} is not bounded") + return value + + +def _pointers(value, label): + _need(type(value) is list and value and value == sorted(set(value), key=str.encode), f"{label} is not sorted and unique") + for pointer in value: + _need(type(pointer) is str and pointer.startswith("/") and "//" not in pointer and not re.search(r"~(?![01])", pointer), f"{label} contains an invalid RFC-6901 pointer") + + +def _addresses(value, label): + encoded = [artifacts.canonical_json_bytes(item) for item in value] if type(value) is list else [] + _need(type(value) is list and value and len(encoded) == len(set(encoded)) and encoded == sorted(encoded), f"{label} is not sorted and unique") + for address in value: + _need(type(address) is list and len(address) == 4 and type(address[0]) is str and address[0] and type(address[1]) is list and all(type(anchor) is str and anchor for anchor in address[1]) and type(address[2]) is str and address[2] and type(address[3]) is str and address[3], f"{label} contains an invalid address tuple") + + +def _artifact_caps(records, evidence_role=None, large_role=None, total_limit=None): + for row in records: + role = row["role_path"].split("/", 1)[-1] + cap = 16 * 1024 * 1024 if role == evidence_role else 8 * 1024 * 1024 if large_role and role == large_role else 2 * 1024 * 1024 + if role.endswith(".sha256"): + cap = 256 + _need(row["bytes"] <= cap, f"artifact exceeds its cap: {row['role_path']}") + if total_limit is not None: + _need(sum(row["bytes"] for row in records) <= total_limit, "artifact root exceeds its cap") + + +def _png(path, role): + raw = artifacts.read_regular_file(path, max_bytes=2 * 1024 * 1024) + try: + from PIL import Image + image = Image.open(io.BytesIO(raw)) + _need(image.format == "PNG" and image.mode == "RGB" and image.size == (512, 1536) and not image.info, f"{role} PNG metadata differs") + image.verify() + except PublisherError: + raise + except Exception as exc: + raise PublisherError(f"{role} PNG is invalid") from exc + + +def _ply_digest(path, role, level): + raw = artifacts.read_regular_file(path, max_bytes=2 * 1024 * 1024) + vertices_count, _, quads_count, _, _ = neutral.LEVEL_COUNTS[level] + try: + lines = raw.decode("ascii").splitlines() + except UnicodeDecodeError as exc: + raise PublisherError(f"{role} is not ASCII PLY") from exc + header = ["ply", "format ascii 1.0", f"element vertex {vertices_count}", "property double x", "property double y", "property double z", f"element face {quads_count}", "property list uchar int vertex_indices", "end_header"] + _need(b"\r" not in raw and raw.endswith(b"\n") and lines[:9] == header and len(lines) == 9 + vertices_count + quads_count, f"{role} PLY framing differs") + try: + vertices = tuple(tuple(float(item) for item in lines[9 + i].split()) for i in range(vertices_count)) + quads = tuple(tuple(int(item) for item in lines[9 + vertices_count + i].split()[1:]) for i in range(quads_count)) + except (IndexError, ValueError) as exc: + raise PublisherError(f"{role} PLY rows are invalid") from exc + _need(all(len(row) == 3 and all(math.isfinite(item) for item in row) for row in vertices) and all(len(row) == 4 and 0 <= min(row) and max(row) < vertices_count and len(set(row)) == 4 and lines[9 + vertices_count + i].split()[:1] == ["4"] for i, row in enumerate(quads)), f"{role} PLY geometry rows differ") + triangles = tuple(item for a, b, c, d in quads for item in ((a, b, c), (a, c, d))) + coordinates, indices = artifacts.coordinate_hash_bytes(vertices), artifacts.triangle_index_hash_bytes(triangles) + return raw, quads, {"bytes": len(coordinates), "sha256": artifacts.sha256_bytes(coordinates)}, {"bytes": len(indices), "sha256": artifacts.sha256_bytes(indices)} + + +def _runtime(launcher, requirements): + _need((platform.python_implementation(), platform.python_version(), platform.system(), getattr(sys.implementation, "cache_tag", None)) == ("CPython", "3.10.12", "Linux", "cpython-310"), "runtime is not the pinned CPython/Linux runtime") + direct = (("numpy", "2.2.6"), ("scikit-image", "0.25.2"), ("pillow", "11.1.0")) + resolved = (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")) + for name, version in (*direct, *resolved): + try: + observed = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError as exc: + raise PublisherError(f"missing runtime distribution: {name}") from exc + _need(observed == version, f"runtime distribution drift: {name}") + builtins = [] + for name in ("math", "zlib"): + module, spec = __import__(name), importlib.util.find_spec(name) + _need(getattr(module, "__file__", None) is None and spec is not None and spec.origin == "built-in", f"{name} is not a built-in") + versions = (None, None) if name == "math" else (_bounded(module.ZLIB_VERSION, "zlib compile"), _bounded(module.ZLIB_RUNTIME_VERSION, "zlib runtime")) + builtins.append({"module_name": name, "__file__": None, "find_spec_origin": "built-in", "compile_version": versions[0], "runtime_version": versions[1]}) + python = {"implementation": "CPython", "version": "3.10.12", "build": _bounded(" ".join(platform.python_build()), "python build"), "compiler": _bounded(platform.python_compiler(), "python compiler"), "cache_tag": "cpython-310", "abiflags": _bounded(sys.abiflags, "python abiflags"), "soabi": _bounded(sysconfig.get_config_var("SOABI"), "python soabi")} + libc_name, libc_version = platform.libc_ver() + platform_value = {"system": platform.system(), "release": platform.release(), "version": platform.version(), "machine": platform.machine(), "pointer_bits": 8 * struct.calcsize("P"), "byteorder": sys.byteorder, "libc_name": libc_name, "libc_version": libc_version} + for key in ("system", "release", "version", "machine", "libc_name", "libc_version"): + platform_value[key] = _bounded(platform_value[key], f"platform.{key}") + _need(platform_value["byteorder"] in ("little", "big") and platform_value["pointer_bits"] > 0, "platform is not admitted") + locale_value = {"active": _bounded(locale.setlocale(locale.LC_ALL, None), "locale.active", 512), "preferred_encoding": _bounded(locale.getpreferredencoding(False), "locale.preferred_encoding", 512)} + value = {"schema": "owned-root-assembly-successor-runtime.v2", "python": python, "platform": platform_value, "locale": locale_value, "managed_launcher": launcher, "requirements": requirements, "direct_distributions": [{"name": n, "version": v} for n, v in direct], "resolved_distributions": [{"name": n, "version": v} for n, v in resolved], "builtin_modules": builtins} + raw = artifacts.canonical_json_bytes(value) + _need(len(raw) <= 64 * 1024, "runtime JSON exceeds its cap") + return value, raw, artifacts.sha256_bytes(raw) + + +def _source_records(package, expected): + found = [] + for directory, dirs, files in os.walk(package, followlinks=False): + _need(not any((Path(directory) / name).is_symlink() for name in dirs), "implementation package contains a symlink directory") + found.extend((Path(directory) / name).relative_to(ROOT).as_posix() for name in files if name.endswith((".py", ".sh"))) + found = tuple(sorted(found, key=str.encode)) + expected = tuple(sorted(expected, key=str.encode)) + _need(found == expected, f"implementation source allowlist differs: {found}") + return [_record(ROOT / role, role) for role in expected] + + +def _static(): + _need(os.environ.get("PYTHONHASHSEED") == "0", "publisher requires literal PYTHONHASHSEED=0") + activation = _record(ROOT / ACTIVATION_ROLE, ACTIVATION_ROLE) + _need(activation["sha256"] == ACTIVATION_SHA, "activation contract identity differs") + sidecar = _record(ROOT / "experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256", "experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256", 256) + _need(artifacts.read_regular_file(ROOT / sidecar["role_path"], max_bytes=256) == f"{ACTIVATION_SHA} experiments/owned-root-assembly-successor/exact-five-activation-contract.md\n".encode("ascii"), "activation sidecar differs") + design, source, profile = (_record(ROOT / role, role) for role in (DESIGN_ROLE, SOURCE_ROLE, PROFILE_ROLE)) + _need(artifacts.read_regular_file(ROOT / "experiments/owned-root-assembly-successor/design-contract.sha256", max_bytes=256) == f"{DESIGN_SHA} {DESIGN_ROLE}\n".encode("ascii"), "design sidecar differs") + _need((design["bytes"], design["sha256"]) == (173184, DESIGN_SHA) and (source["bytes"], source["sha256"]) == (56984, SOURCE_SHA) and (profile["bytes"], profile["sha256"]) == (29970, PROFILE_SHA), "fixed source identity differs") + deps = [] + for role, fixed in sorted(EXPECTED_DEPS.items(), key=lambda pair: pair[0].encode()): + actual = _record(ROOT / role, role, 4 * 1024 * 1024 if not role.endswith("requirements.txt") else 64 * 1024) + _need((actual["bytes"], actual["sha256"]) == fixed, f"fixed dependency drift: {role}") + deps.append(actual) + neutral_files = _source_records(NEUTRAL, neutral.IMPLEMENTATION_ROLES) + additive_files = _source_records(PACKAGE, ADDITIVE_ROLES) + launcher = next(row for row in deps if row["role_path"] == "experiments/current-form-surface-preview/surface_preview_launcher.sh") + requirements = next(row for row in deps if row["role_path"] == "experiments/current-form-surface-preview/requirements.txt") + _need(artifacts.read_regular_file(ROOT / requirements["role_path"], max_bytes=64 * 1024) == b"numpy==2.2.6\nscikit-image==0.25.2\nPillow==11.1.0\n", "requirements are not pinned") + runtime, runtime_raw, runtime_sha = _runtime(launcher, requirements) + _need(runtime_sha == RUNTIME_SHA, "runtime fingerprint differs") + return {"activation": activation, "design": design, "source": source, "profile": profile, "dependencies": deps, "neutral_files": neutral_files, "additive_files": additive_files, "runtime": runtime, "runtime_raw": runtime_raw, "runtime_sha": runtime_sha, "comparator": next(row for row in neutral_files if row["role_path"] == COMPARATOR_ROLE)} + + +def _table(identity): + raw = artifacts.read_regular_file(ROOT / PROFILE_ROLE, max_bytes=4 * 1024 * 1024) + try: + table = json.loads(raw.decode("utf-8"), object_pairs_hook=lambda pairs: _unique_pairs(pairs)) + except Exception as exc: + raise PublisherError("profile table is not valid JSON") from exc + _need(type(table) is dict and type(table.get("profiles")) is list and [row.get("id") for row in table["profiles"]] == list(PROFILES), "profile table order differs") + for index, row in enumerate(table["profiles"]): + _keys(row, ("dimension_scales", "id", "label", "part_placements"), f"profile[{index}]") + _need(type(row["label"]) is str and row["label"] and type(row["dimension_scales"]) is dict and len(row["dimension_scales"]) == 37 and type(row["part_placements"]) is dict and len(row["part_placements"]) == 18, f"profile[{index}] shape differs") + _need(all(type(v) is int and 1 <= v <= 10000 for v in row["dimension_scales"].values()), f"profile[{index}] scale differs") + _need(all(type(v) is list and len(v) == 3 and all(type(n) is int and -1000000000 <= n <= 1000000000 for n in v) for v in row["part_placements"].values()), f"profile[{index}] placement differs") + _need(identity["profile"]["sha256"] == PROFILE_SHA, "profile table identity differs") + return table["profiles"] + + +def _unique_pairs(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate key: {key}") + result[key] = value + return result + + +def _manifest_ref(value, label, role, record, schema=None): + _keys(value, ("role_path", "bytes", "sha256", "schema"), label) + artifacts.validate_role_path(value["role_path"]) + _need(type(value["bytes"]) is int and value["bytes"] >= 0, f"{label} has an invalid byte count") + _hex(value["sha256"], f"{label}.sha256") + _need(value["role_path"] == role and value["bytes"] == record["bytes"] and value["sha256"] == record["sha256"] and (schema is None or value["schema"] == schema), f"{label} does not reference the admitted record") + + +def _thresholds(value, expected, label): + _need(type(value) is list and [row.get("threshold_id") if type(row) is dict else None for row in value] == [row["threshold_id"] for row in expected], f"{label} threshold order differs") + for index, row in enumerate(value): + _keys(row, ("threshold_id", "relation", "lower", "upper", "unit"), f"{label}[{index}]") + _need(value == expected, f"{label} differs from the frozen neutral inventory") + + +def _threshold_shape(value, label): + _need(type(value) is list and len(value) == 357, f"{label} threshold cardinality differs") + ids = [] + for index, row in enumerate(value): + _keys(row, ("threshold_id", "relation", "lower", "upper", "unit"), f"{label}[{index}]") + _need(type(row["threshold_id"]) is str and row["threshold_id"], f"{label}[{index}] threshold ID differs") + _need(row["relation"] in ("eq", "ge", "gt", "le", "lt", "range") and type(row["unit"]) is str and row["unit"], f"{label}[{index}] threshold type differs") + for bound in (row["lower"], row["upper"]): + _need(bound is None or (type(bound) in (int, float) and math.isfinite(float(bound))), f"{label}[{index}] threshold bound differs") + relation, lower, upper = row["relation"], row["lower"], row["upper"] + _need((relation == "eq" and lower is not None and upper is not None and lower == upper) or (relation in ("ge", "gt") and lower is not None and upper is None) or (relation in ("le", "lt") and lower is None and upper is not None) or (relation == "range" and lower is not None and upper is not None and lower <= upper), f"{label}[{index}] threshold bounds do not match relation") + ids.append(row["threshold_id"]) + _need(ids == sorted(set(ids), key=str.encode), f"{label} thresholds are not sorted and unique") + + +def _gate_rows(rows, expected_ids, thresholds, label): + _need(type(rows) is list and [row.get("gate_id") if type(row) is dict else None for row in rows] == expected_ids, f"{label} gate inventory differs") + threshold_map = {row["threshold_id"]: row for row in thresholds} + for index, row in enumerate(rows): + _keys(row, ("gate_id", "outcome", "sample_count", "observed_min", "observed_max", "threshold_id"), f"{label}[{index}]") + threshold = threshold_map.get(row["threshold_id"]) + _need(row["outcome"] == "pass" and row["threshold_id"] == f"threshold.{row['gate_id']}" and threshold is not None and type(row["sample_count"]) is int and row["sample_count"] >= 1, f"{label}[{index}] is not all-pass evidence") + low, high = row["observed_min"], row["observed_max"] + _need(type(low) in (int, float) and type(high) in (int, float) and math.isfinite(float(low)) and math.isfinite(float(high)) and low <= high, f"{label}[{index}] observations are invalid") + relation, lower, upper = threshold["relation"], threshold["lower"], threshold["upper"] + passes = (low == lower and high == upper) if relation == "eq" else low >= lower if relation == "ge" else low > lower if relation == "gt" else high <= upper if relation == "le" else high < upper if relation == "lt" else low >= lower and high <= upper + _need(passes, f"{label}[{index}] fails its threshold") + + +def _manifest_graph(root, records, identity, stable): + def get(role): + value, raw = _json(root / role) + _need(_same_record(root / role, role, records[role]) == records[role], f"{role} changed") + return value, raw + input_value, _ = get("input-manifest.json") + _keys(input_value, ("schema", "contract_sha256", "source", "profile_table", "profile_id", "prepared_input", "source_bindings", "runtime", "implementation_files", "recipe_id"), "input manifest") + _need(input_value["schema"] == "owned-root-assembly-successor-input-manifest.v1" and input_value["contract_sha256"] == DESIGN_SHA and input_value["source"] == identity["source"] and input_value["profile_table"] == identity["profile"] and input_value["profile_id"] == "standard_neutral_reference" and input_value["runtime"] == identity["runtime"] and input_value["implementation_files"] == identity["neutral_files"] and type(input_value["source_bindings"]) is list and len(input_value["source_bindings"]) == 92 and type(input_value["recipe_id"]) is str and SHA.fullmatch(input_value["recipe_id"]) and input_value["recipe_id"] == stable["recipe_id"], "input manifest identity differs") + _fr(input_value["prepared_input"], "input prepared", "prepared-input.json") + coordinate, _ = get("coordinate-manifest.json") + _keys(coordinate, ("schema", "contract_sha256", "input_manifest", "counts", "coordinate_hashes", "triangle_index_hashes", "surface_artifacts"), "coordinate manifest") + counts = [{"level": i, "vertices": n[0], "edges": n[1], "quads": n[2], "triangles": n[3], "boundary_edges": n[4]} for i, n in enumerate(neutral.LEVEL_COUNTS)] + _need(coordinate["schema"] == "owned-root-assembly-successor-coordinate-manifest.v1" and coordinate["contract_sha256"] == DESIGN_SHA and coordinate["counts"] == counts and len(coordinate["coordinate_hashes"]) == 3 and len(coordinate["triangle_index_hashes"]) == 3 and coordinate["surface_artifacts"] == [records[r] for r in sorted(neutral.SURFACE_ROLES, key=str.encode)], "coordinate manifest differs") + _manifest_ref(coordinate["input_manifest"], "coordinate input", "input-manifest.json", records["input-manifest.json"], "owned-root-assembly-successor-input-manifest.v1") + gate, _ = get("gate-manifest.json") + _keys(gate, ("schema", "contract_sha256", "coordinate_manifest", "thresholds", "structural", "continuity", "anatomy", "intersection"), "gate manifest") + _need(gate["schema"] == "owned-root-assembly-successor-gate-manifest.v1" and gate["contract_sha256"] == DESIGN_SHA, "gate manifest identity differs") + _manifest_ref(gate["coordinate_manifest"], "gate coordinate", "coordinate-manifest.json", records["coordinate-manifest.json"], coordinate["schema"]) + _need(len(gate["structural"]) == 122 and len(gate["continuity"]) == 144 and len(gate["anatomy"]) == 78 and len(gate["intersection"]) == 12 and len(gate["thresholds"]) == 357, "gate cardinality differs") + thresholds = gate["thresholds"] + _threshold_shape(thresholds, "gate") + ids = {group: [row["gate_id"] for row in gate[group]] for group in ("structural", "continuity", "anatomy", "intersection")} + for group in ids: + _gate_rows(gate[group], ids[group], thresholds, group) + causality, _ = get("causality-manifest.json") + _keys(causality, ("schema", "contract_sha256", "input_manifest", "formula_records", "source_bindings", "charts", "perturbations"), "causality manifest") + _need(causality["schema"] == "owned-root-assembly-successor-causality-manifest.v1" and causality["contract_sha256"] == DESIGN_SHA and len(causality["formula_records"]) == 120 and len(causality["source_bindings"]) == 92 and type(causality["charts"]) is dict and len(causality["perturbations"]) == 33, "causality manifest differs") + _manifest_ref(causality["input_manifest"], "causality input", "input-manifest.json", records["input-manifest.json"], input_value["schema"]) + render_value, _ = get("render-manifest.json") + _keys(render_value, ("schema", "contract_sha256", "coordinate_manifest", "render_config", "visibility", "artifacts"), "render manifest") + _need(render_value["schema"] == "owned-root-assembly-successor-render-manifest.v1" and render_value["contract_sha256"] == DESIGN_SHA and render_value["artifacts"] == [records[r] for r in sorted(("direct.png", "lineage.png"), key=str.encode)], "render manifest differs") + _manifest_ref(render_value["coordinate_manifest"], "render coordinate", "coordinate-manifest.json", records["coordinate-manifest.json"], coordinate["schema"]) + render.validate_render_config(render_value["render_config"]) + _keys(render_value["visibility"], ("level", "triangle_count", "triangle_index_sha256", "rule"), "render visibility") + _need(render_value["visibility"]["level"] == 2 and render_value["visibility"]["triangle_count"] == 3328 and render_value["visibility"]["rule"] == "larger-depth-then-lower-triangle-index", "render visibility differs") + return thresholds, ids + + +def _old_receipt(receipt, identity): + _keys(receipt, ("schema", "outcome", "literal_invocation", "contract_sha256", "runtime_fingerprint_sha256", "implementation_files", "executed_test_ids", "required_test_ids", "results"), "neutral receipt") + _need(receipt["schema"] == "owned-root-assembly-successor-managed-test-receipt.v1" and receipt["outcome"] == "success" and receipt["contract_sha256"] == DESIGN_SHA and receipt["runtime_fingerprint_sha256"] == identity["runtime_sha"] and receipt["implementation_files"] == identity["neutral_files"], "neutral receipt identity differs") + invocation = _keys(receipt["literal_invocation"], ("environment", "argv"), "neutral receipt invocation") + argv = invocation["argv"] + _need(invocation["environment"] == ["PYTHONHASHSEED=0"] and type(argv) is list and len(argv) == 4 and argv[:3] == [BUILDER_ROLE, "--internal-managed-tests", "--receipt"] and _abs(argv[3], "neutral receipt path").name == "managed-test-receipt.json", "neutral receipt invocation differs") + executed = receipt["executed_test_ids"] + _need(type(executed) is list and len(executed) == 134 and executed == sorted(set(executed), key=str.encode) and all(type(v) is str and v for v in executed) and receipt["required_test_ids"] == list(OLD_REQUIRED) and all(executed.count(v) == 1 for v in OLD_REQUIRED), "neutral receipt tests differ") + _need(receipt["results"] == {"tests_run": 134, "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}, "neutral receipt result differs") + + +def _baseline(path, identity): + root = _abs(str(path), "baseline root") + rows = artifacts.closed_inventory(root, BASELINE_ROLES, max_file_bytes=8 * 1024 * 1024) + records = {row["role_path"]: row for row in rows} + _artifact_caps(rows, large_role="causality-manifest.json", total_limit=32 * 1024 * 1024) + _need(records["comparison/comparison-report.json"]["sha256"] == BASELINE_REPORT_SHA and records["comparison/comparison-report.sha256"]["sha256"] == BASELINE_REPORT_SIDE_SHA and records["comparison/comparison-report.sha256"]["bytes"] == 89, "baseline comparison identity differs") + report, raw = _json(root / "comparison/comparison-report.json") + _same_record(root / "comparison/comparison-report.json", "comparison/comparison-report.json", records["comparison/comparison-report.json"]) + _sidecar(artifacts.read_regular_file(root / "comparison/comparison-report.sha256", max_bytes=256), raw, "comparison-report.json") + _keys(report, ("schema", "outcome", "comparator", "runtime_fingerprint_sha256", "managed_test_receipt", "seed_bundles", "stable_comparisons", "excluded_run_local_roles"), "comparison report") + _need(report["schema"] == "owned-root-assembly-successor-comparison-report.v1" and report["outcome"] == "success" and report["comparator"] == identity["comparator"] and report["runtime_fingerprint_sha256"] == identity["runtime_sha"] and report["excluded_run_local_roles"] == ["report.json", "report.sha256"], "comparison report identity differs") + _old_receipt(report["managed_test_receipt"], identity) + _need(type(report["stable_comparisons"]) is list and [row.get("role_path") for row in report["stable_comparisons"]] == list(BASELINE_STABLE_ROLES), "baseline stable comparison inventory differs") + for row, role in zip(report["stable_comparisons"], BASELINE_STABLE_ROLES): + _fr(row, f"baseline comparison {role}") + _need(row == records[f"seed-17/{role}"] | {"role_path": role} and row == records[f"seed-29/{role}"] | {"role_path": role}, f"baseline comparison differs: {role}") + thresholds = ids = None + bundles = report["seed_bundles"] + _need(type(bundles) is list and len(bundles) == 2, "baseline bundle inventory differs") + for index, seed in enumerate(SEEDS): + prefix = f"seed-{seed}" + stable, _ = _json(root / prefix / "stable-manifest.json") + _need(records[f"{prefix}/stable-manifest.json"]["sha256"] == BASELINE_STABLE_SHA, f"{prefix} stable manifest identity differs") + _keys(stable, ("schema", "contract_sha256", "recipe_id", "runtime", "implementation_files", "input_manifest", "coordinate_manifest", "gate_manifest", "causality_manifest", "render_manifest", "artifact_hashes"), f"{prefix} stable manifest") + _need(stable["schema"] == "owned-root-assembly-successor-stable-manifest.v1" and stable["contract_sha256"] == DESIGN_SHA and stable["runtime"] == identity["runtime"] and stable["implementation_files"] == identity["neutral_files"] and type(stable["recipe_id"]) is str and SHA.fullmatch(stable["recipe_id"]), f"{prefix} stable identity differs") + thresholds, ids = _manifest_graph(root / prefix, {role: records[f"{prefix}/{role}"] for role in neutral.ARTIFACT_ROLES}, identity, stable) + for field, role in (("input_manifest", "input-manifest.json"), ("coordinate_manifest", "coordinate-manifest.json"), ("gate_manifest", "gate-manifest.json"), ("causality_manifest", "causality-manifest.json"), ("render_manifest", "render-manifest.json")): + _manifest_ref(stable[field], f"{prefix} {field}", role, records[f"{prefix}/{role}"], f"owned-root-assembly-successor-{role.removesuffix('.json').replace('-manifest', '')}-manifest.v1") + _need(stable["artifact_hashes"] == [{**records[f"{prefix}/{role}"], "role_path": role} for role in sorted(neutral.STABLE_ARTIFACT_ROLES, key=str.encode)], f"{prefix} stable artifacts differ") + expected_bundle = {"seed": seed, "role_path": prefix, "stable_manifest": {"role_path": f"{prefix}/stable-manifest.json", "bytes": records[f"{prefix}/stable-manifest.json"]["bytes"], "sha256": records[f"{prefix}/stable-manifest.json"]["sha256"], "schema": stable["schema"]}, "report": {**records[f"{prefix}/report.json"], "role_path": f"{prefix}/report.json"}, "report_sidecar": {**records[f"{prefix}/report.sha256"], "role_path": f"{prefix}/report.sha256"}} + _need(bundles[index] == expected_bundle, f"{prefix} comparison bundle differs") + run_report, report_raw = _json(root / prefix / "report.json") + _keys(run_report, ("schema", "outcome", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "stable_manifest", "gates"), f"{prefix} report") + _need(run_report["schema"] == "owned-root-assembly-successor-run-report.v1" and run_report["outcome"] == "success" and run_report["seed"] == seed and run_report["runtime_fingerprint_sha256"] == identity["runtime_sha"], f"{prefix} report identity differs") + output_path = _abs(run_report["output_path"], f"{prefix} output") + staging_path = _abs(run_report["staging_path"], f"{prefix} staging") + _need(run_report["stable_manifest"] == expected_bundle["stable_manifest"] and run_report["literal_invocation"] == {"environment": [f"PYTHONHASHSEED={seed}"], "argv": [BUILDER_ROLE, "--output", run_report["output_path"]]} and output_path.name == prefix and staging_path.parent == output_path.parent and staging_path.name.startswith(f".{output_path.name}.stage-"), f"{prefix} report paths differ") + _abs(run_report["python_executable_path"], f"{prefix} Python") + _need(UTC.fullmatch(run_report["started_utc"]) and UTC.fullmatch(run_report["finished_utc"]) and run_report["finished_utc"] >= run_report["started_utc"] and [row.get("phase") for row in run_report["timings"]] == list(neutral.RUN_PHASES) and all(_keys(row, ("phase", "seconds"), f"{prefix} timing") and type(row["seconds"]) is float and math.isfinite(row["seconds"]) and row["seconds"] >= 0.0 for row in run_report["timings"]) and run_report["gates"] == [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in neutral.RUN_REPORT_GATES], f"{prefix} report stages differ") + _sidecar(artifacts.read_regular_file(root / prefix / "report.sha256", max_bytes=256), report_raw, "report.json") + return {"root": root, "records": records, "report": report, "thresholds": thresholds, "gate_ids": ids, "comparison_record": {"role_path": "comparison-report.json", "bytes": records["comparison/comparison-report.json"]["bytes"], "sha256": records["comparison/comparison-report.json"]["sha256"]}} + + +def _bundle(path, profile, seed, identity, thresholds, gate_ids, table): + root = _abs(str(path), f"{profile}/{seed} bundle") + _need(root.name == f"seed-{seed}" and root.is_dir(), "bundle path is not a seed directory") + rows = artifacts.closed_inventory(root, BUNDLE_ROLES, max_file_bytes=8 * 1024 * 1024) + records = {row["role_path"]: row for row in rows} + _artifact_caps(rows, evidence_role="profile-seed-evidence.json") + _png(root / "direct.png", "direct.png") + _png(root / "lineage.png", "lineage.png") + evidence, evidence_raw = _json(root / "profile-seed-evidence.json") + _sidecar(artifacts.read_regular_file(root / "profile-seed-evidence.sha256", max_bytes=256), evidence_raw, "profile-seed-evidence.json") + _keys(evidence, ("schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", "existing_dependencies", "additive_implementation_files", "runtime", "runtime_fingerprint_sha256", "profile_id", "profile_index", "selection", "projected_values", "projected_carrier", "projection_bindings", "levels", "thresholds", "gates", "causality", "renders", "payloads", "invariants"), "profile evidence") + _need(evidence["schema"] == "owned-root-assembly-successor-profile-seed-evidence.v1" and evidence["outcome"] == "success" and evidence["profile_id"] == profile and evidence["profile_index"] == PROFILES.index(profile) and evidence["activation_contract"] == identity["activation"] and evidence["design_contract"] == identity["design"] and evidence["source"] == identity["source"] and evidence["profile_table"] == identity["profile"] and evidence["existing_dependencies"] == identity["dependencies"] and evidence["additive_implementation_files"] == identity["additive_files"] and evidence["runtime"] == identity["runtime"] and evidence["runtime_fingerprint_sha256"] == identity["runtime_sha"], f"{profile}/{seed} evidence identity differs") + row = table[evidence["profile_index"]] + selection = _keys(evidence["selection"], ("profile_pointer", "profile_row_sha256", "dimension_scales_sha256", "part_placements_sha256"), "selection") + _need(selection["profile_pointer"] == f"/profiles/{evidence['profile_index']}" and selection["profile_row_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(row)) and selection["dimension_scales_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["dimension_scales"])) and selection["part_placements_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["part_placements"])), "selection hashes differ") + _need(evidence["projected_values"] and [item.get("prepared_component") for item in evidence["projected_values"]] == list(COMPONENT_IDS) and len(evidence["projected_values"]) == 92, "projected values differ") + bindings = evidence["projection_bindings"] + _need(type(bindings) is list and [item.get("prepared_component") for item in bindings] == list(COMPONENT_IDS) and len(bindings) == 92, "projection bindings differ") + for index, (value, binding) in enumerate(zip(evidence["projected_values"], bindings)): + _keys(value, ("prepared_component", "value", "source_pointers", "profile_pointers"), f"projected value {index}") + _keys(binding, ("prepared_component", "derivation_id", "source_addresses", "source_pointers", "profile_pointers"), f"binding {index}") + _need(value["prepared_component"] == binding["prepared_component"] and artifacts.coerce_binary64(value["value"], label="projected value") == value["value"] and value["source_pointers"] == binding["source_pointers"] and value["profile_pointers"] == binding["profile_pointers"] and binding["derivation_id"] in ("profile.dimension-permille-half-even-mm.v1", "profile.world-placement-axis-sum.v1", "profile.world-landmark-axis-sum.v1"), f"binding {index} differs") + _pointers(value["source_pointers"], f"binding {index} source pointers") + _pointers(value["profile_pointers"], f"binding {index} profile pointers") + _addresses(binding["source_addresses"], f"binding {index} source addresses") + _need(all(pointer.startswith(f"/profiles/{evidence['profile_index']}/") for pointer in value["profile_pointers"]), f"binding {index} selects another profile") + carrier = _keys(evidence["projected_carrier"], ("bytes", "sha256"), "projected carrier") + carrier_raw = artifacts.canonical_json_bytes([row["value"] for row in evidence["projected_values"]]) + _need(carrier == {"bytes": len(carrier_raw), "sha256": artifacts.sha256_bytes(carrier_raw)}, "projected carrier differs") + levels = evidence["levels"] + _need(type(levels) is list and [item.get("level") for item in levels] == [0, 1, 2], "level inventory differs") + level_digests = {} + for level, item in enumerate(levels): + _keys(item, ("level", "counts", "coordinate_bytes", "coordinate_sha256", "triangle_index_bytes", "triangle_index_sha256", "ply"), f"level {level}") + expected = neutral.LEVEL_COUNTS[level] + _need(item["counts"] == {"level": level, "vertices": expected[0], "edges": expected[1], "quads": expected[2], "triangles": expected[3], "boundary_edges": expected[4]} and item["ply"] == records[f"surface-level-{level}.ply"], f"level {level} differs") + _need(type(item["coordinate_bytes"]) is int and item["coordinate_bytes"] > 0 and type(item["triangle_index_bytes"]) is int and item["triangle_index_bytes"] > 0, f"level {level} hashes differ") + _hex(item["coordinate_sha256"], f"level {level} coordinate hash") + _hex(item["triangle_index_sha256"], f"level {level} triangle hash") + level_digests[level] = _ply_digest(root / f"surface-level-{level}.ply", f"surface-level-{level}.ply", level) + _need(item["coordinate_bytes"] == level_digests[level][2]["bytes"] and item["coordinate_sha256"] == level_digests[level][2]["sha256"] and item["triangle_index_bytes"] == level_digests[level][3]["bytes"] and item["triangle_index_sha256"] == level_digests[level][3]["sha256"], f"level {level} coordinate identity differs") + _thresholds(evidence["thresholds"], thresholds, "profile thresholds") + gates = _keys(evidence["gates"], ("structural", "continuity", "anatomy", "intersection"), "profile gates") + for group in gates: + _gate_rows(gates[group], gate_ids[group], thresholds, f"profile {group}") + causality = evidence["causality"] + _need(type(causality) is list and [item.get("parameter_id") for item in causality] == sorted(CAUSAL_COMPONENTS, key=str.encode) and len(causality) == 33, "causality inventory differs") + for index, item in enumerate(causality): + _keys(item, ("parameter_id", "prepared_component", "delta_m", "support_level", "predicted_support_count", "observed_support_count", "predicted_support_sha256", "observed_support_sha256", "maximum_movement_m", "artifact"), f"causality {index}") + parameter = item["parameter_id"] + _need(item["prepared_component"] == CAUSAL_COMPONENTS[parameter] and item["delta_m"] == 0.01 and item["support_level"] == 2 and type(item["predicted_support_count"]) is int and item["predicted_support_count"] == item["observed_support_count"] and item["predicted_support_count"] > 0 and item["predicted_support_count"] <= 1737 and item["predicted_support_sha256"] == item["observed_support_sha256"] and _hex(item["predicted_support_sha256"], "support hash") and type(item["maximum_movement_m"]) is float and math.isfinite(item["maximum_movement_m"]) and item["maximum_movement_m"] >= float.fromhex("0x1.d14e3bcd35a85p-11") and item["artifact"] == records[f"perturb-{parameter.replace('.', '-')}.ply"], f"causality {index} differs") + perturb_raw, perturb_quads, _, _ = _ply_digest(root / f"perturb-{parameter.replace('.', '-')}.ply", f"perturb-{parameter.replace('.', '-')}.ply", 2) + _need(perturb_quads == level_digests[2][1] and perturb_raw != level_digests[2][0], f"causality {index} topology or byte movement differs") + renders = _keys(evidence["renders"], ("renderer_id", "render_config", "render_config_sha256", "visibility", "visibility_sha256", "direct", "lineage", "same_surface_positions_sha256", "same_surface_triangles_sha256"), "profile renders") + _need(renders["renderer_id"] == "owned-root-raster-pillow-11.1.0.v1" and renders["render_config_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(renders["render_config"])) and renders["direct"] == records["direct.png"] and renders["lineage"] == records["lineage.png"], "profile render identity differs") + render.validate_render_config(renders["render_config"]) + _keys(renders["visibility"], ("level", "triangle_count", "triangle_index_sha256", "rule"), "profile visibility") + _need(renders["visibility"]["level"] == 2 and renders["visibility"]["triangle_count"] == 3328 and renders["visibility"]["rule"] == "larger-depth-then-lower-triangle-index" and renders["visibility_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(renders["visibility"])) and renders["same_surface_positions_sha256"] == levels[2]["coordinate_sha256"] and renders["same_surface_triangles_sha256"] == levels[2]["triangle_index_sha256"] == renders["visibility"]["triangle_index_sha256"], "profile surface binding differs") + _need(evidence["payloads"] == [records[role] for role in PAYLOAD_ROLES] and evidence["invariants"] == {"topology_equal_to_neutral": True, "formulas_equal_to_neutral": True, "tunables_equal_to_neutral": True, "thresholds_equal_to_neutral": True, "gate_inventory_equal_to_neutral": True, "subdivision_equal_to_neutral": True, "ownership_equal_to_neutral": True, "causality_rules_equal_to_neutral": True, "renderer_equal_to_neutral": True}, "profile payload or invariant identity differs") + run_report, run_raw = _json(root / "run-report.json") + _keys(run_report, ("schema", "outcome", "profile_id", "profile_index", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "manifest_ref", "gates"), "profile run report") + _need(run_report["schema"] == "owned-root-assembly-successor-profile-seed-run-report.v1" and run_report["outcome"] == "success" and run_report["profile_id"] == profile and run_report["profile_index"] == PROFILES.index(profile) and run_report["seed"] == seed and run_report["runtime_fingerprint_sha256"] == identity["runtime_sha"] and run_report["output_path"] == str(root) and run_report["literal_invocation"] == {"environment": [f"PYTHONHASHSEED={seed}"], "argv": [RUNNER_ROLE, "--profile", profile, "--output", str(root)]}, "profile report identity differs") + profile_staging = _abs(run_report["staging_path"], "profile staging") + _abs(run_report["python_executable_path"], "profile Python") + _need(profile_staging.parent == root.parent and profile_staging.name.startswith(f".{root.name}.stage-") and UTC.fullmatch(run_report["started_utc"]) and UTC.fullmatch(run_report["finished_utc"]) and run_report["finished_utc"] >= run_report["started_utc"] and [item.get("phase") for item in run_report["timings"]] == ["identity", "selection-projection", "catalogs", "geometry-gates", "causality", "serialization", "total-before-seal"] and all(_keys(item, ("phase", "seconds"), "profile timing") and type(item["seconds"]) is float and math.isfinite(item["seconds"]) and item["seconds"] >= 0.0 for item in run_report["timings"]), "profile report timings differ") + _need(run_report["gates"] == [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in neutral.RUN_REPORT_GATES], "profile report gates differ") + _manifest_ref(run_report["manifest_ref"], "profile evidence reference", "profile-seed-evidence.json", records["profile-seed-evidence.json"], evidence["schema"]) + _sidecar(artifacts.read_regular_file(root / "run-report.sha256", max_bytes=256), run_raw, "run-report.json") + return {"root": root, "records": records, "evidence": evidence} + + +def _compare(left, right, roles): + result = [] + for role in roles: + lraw = artifacts.read_regular_file(left["root"] / role, max_bytes=8 * 1024 * 1024) + rraw = artifacts.read_regular_file(right["root"] / role, max_bytes=8 * 1024 * 1024) + _need(left["records"][role] == {"role_path": role, "bytes": len(lraw), "sha256": artifacts.sha256_bytes(lraw)} and right["records"][role] == {"role_path": role, "bytes": len(rraw), "sha256": artifacts.sha256_bytes(rraw)} and lraw == rraw, f"cross-seed role differs: {role}") + result.append({"role_path": role, "bytes": len(lraw), "sha256": artifacts.sha256_bytes(lraw)}) + return result + + +def _context(path, baseline): + value, raw = _json(path, 64 * 1024) + _keys(value, ("schema", "literal_invocation", "output_path", "neutral_baseline_path", "timings"), "launcher context") + output = _abs(value["output_path"], "output path") + _need(value["schema"] == "owned-root-assembly-successor-exact-five-launcher-context.v1" and value["output_path"] == str(output) and value["neutral_baseline_path"] == str(baseline) and value["literal_invocation"] == {"environment": ["PYTHONHASHSEED=0"], "argv": [LAUNCHER_ROLE, "--baseline-root", str(baseline), "--output", str(output)]}, "launcher context identity differs") + _need([item.get("phase") for item in value["timings"]] == ["identity", "managed-tests", "launcher-baseline-admission", "profile-seed-builds"] and all(_keys(item, ("phase", "seconds"), "launcher timing") and type(item["seconds"]) is float and math.isfinite(item["seconds"]) and item["seconds"] >= 0.0 for item in value["timings"]), "launcher context timings differ") + _need(raw == artifacts.canonical_json_bytes(value), "launcher context is not canonical") + return value + + +def _new_receipt(value, raw, path, identity): + _need(raw == artifacts.canonical_json_bytes(value), "managed-test receipt is not canonical") + _keys(value, ("schema", "outcome", "invocation", "activation_contract", "design_contract", "existing_dependencies", "additive_implementation_files", "runtime", "runtime_fingerprint_sha256", "executed_test_ids", "required_test_ids", "results"), "activation receipt") + _need(value["schema"] == "owned-root-assembly-successor-exact-five-managed-test-receipt.v1" and value["outcome"] == "success" and value["activation_contract"] == identity["activation"] and value["design_contract"] == identity["design"] and value["existing_dependencies"] == identity["dependencies"] and value["additive_implementation_files"] == identity["additive_files"] and value["runtime"] == identity["runtime"] and value["runtime_fingerprint_sha256"] == identity["runtime_sha"], "activation receipt identity differs") + invocation = _keys(value["invocation"], ("environment", "implementation_role", "mode"), "activation invocation") + _need(invocation == {"environment": ["PYTHONHASHSEED=0"], "implementation_role": RUNNER_ROLE, "mode": "managed-tests"}, "activation invocation differs") + executed = value["executed_test_ids"] + _need(type(executed) is list and executed and executed == sorted(set(executed), key=str.encode) and all(type(item) is str and item for item in executed) and value["required_test_ids"] == list(NEW_REQUIRED) and all(executed.count(item) == 1 for item in NEW_REQUIRED), "activation test inventory differs") + results = _keys(value["results"], ("tests_run", "failures", "errors", "skipped", "expected_failures", "unexpected_successes"), "activation test results") + _need(all(type(count) is int for count in results.values()) and results == {"tests_run": len(executed), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}, "activation test result differs") + _need(path.name == "managed-test-receipt.json", "receipt path role differs") + return value + + +def publish(baseline_root, bundle_paths, receipt_path, context_path, staging_path): + identity = _static() + baseline = _abs(str(baseline_root), "baseline root") + stage = _abs(str(staging_path), "publication staging") + context = _context(_abs(str(context_path), "launcher context"), baseline) + output = _abs(context["output_path"], "output path") + _need(not os.path.lexists(stage) and not os.path.lexists(output), "publication or final output already exists") + _need(stage != baseline and not (stage in baseline.parents or baseline in stage.parents), "staging overlaps baseline") + _need(len(bundle_paths) == 10, "publisher requires exactly ten bundle paths") + all_inputs = [_abs(str(path), "bundle path") for path in (*bundle_paths, receipt_path, context_path)] + _need(len(set(all_inputs)) == len(all_inputs), "publisher inputs are not unique") + for path in all_inputs: + _need(path != baseline and not (path in baseline.parents or baseline in path.parents) and path != stage and not (path in stage.parents or stage in path.parents) and path != output and not (path in output.parents or output in path.parents), "publisher paths are not disjoint") + _need(output != baseline and not (output in baseline.parents or baseline in output.parents) and output != stage and not (output in stage.parents or stage in output.parents), "publisher paths are not disjoint") + start = time.perf_counter() + baseline_a = _baseline(baseline, identity) + baseline_seconds = float(time.perf_counter() - start) + receipt_value, receipt_raw = _json(receipt_path, 16 * 1024 * 1024) + receipt = _new_receipt(receipt_value, receipt_raw, _abs(str(receipt_path), "receipt"), identity) + table = _table(identity) + bundle_values = [] + comparison_values = [] + compare_start = time.perf_counter() + for index, profile in enumerate(PROFILES): + for seed in SEEDS: + bundle_values.append(_bundle(bundle_paths[index * 2 + (seed == 29)], profile, seed, identity, baseline_a["thresholds"], baseline_a["gate_ids"], table)) + comparison_values.append(_compare(bundle_values[-2], bundle_values[-1], BUNDLE_STABLE_ROLES)) + neutral_comparisons = [row for row in baseline_a["report"]["stable_comparisons"] if row["role_path"] in PAYLOAD_ROLES] + _need([row["role_path"] for row in neutral_comparisons] == list(PAYLOAD_ROLES), "standard-neutral comparison inventory differs") + for role, expected in zip(PAYLOAD_ROLES, neutral_comparisons): + left = bundle_values[0]["records"][role] + _need(left == expected, f"standard-neutral payload differs: {role}") + os.mkdir(stage) + public_payloads = [] + for profile, bundle in zip(PROFILES, bundle_values[::2]): + os.mkdir(stage / profile) + for role in ("surface-level-2.ply", "direct.png", "lineage.png"): + data = artifacts.read_regular_file(bundle["root"] / role, max_bytes=2 * 1024 * 1024) + artifacts.write_bytes_no_replace(stage / profile / role, data) + public_payloads.append(_record(stage / profile / role, f"{profile}/{role}", 2 * 1024 * 1024)) + baseline_b = _baseline(baseline, identity) + _need(baseline_a["records"] == baseline_b["records"], "baseline changed during publication") + post_neutral_comparisons = [row for row in baseline_b["report"]["stable_comparisons"] if row["role_path"] in PAYLOAD_ROLES] + _need(post_neutral_comparisons == neutral_comparisons, "post-seam neutral comparison differs") + neutral_comparisons = post_neutral_comparisons + comparison_seconds = float(time.perf_counter() - compare_start) + managed_tests = {"receipt_sha256": artifacts.sha256_bytes(receipt_raw), "receipt": receipt} + profiles = [{"profile_id": profile, "profile_index": index, "evidence": bundle_values[index * 2]["evidence"], "stable_cross_seed_comparisons": comparison_values[index], "neutral_payload_comparisons": neutral_comparisons if index == 0 else []} for index, profile in enumerate(PROFILES)] + evidence = {"schema": "owned-root-assembly-successor-exact-five-evidence.v1", "outcome": "success", "activation_contract": identity["activation"], "design_contract": identity["design"], "source": identity["source"], "profile_table": identity["profile"], "existing_dependencies": identity["dependencies"], "additive_implementation_files": identity["additive_files"], "managed_tests": managed_tests, "neutral_baseline": {"comparison_report": baseline_b["comparison_record"], "stable_manifest_sha256": BASELINE_STABLE_SHA, "runtime_fingerprint_sha256": identity["runtime_sha"], "payload_comparisons": neutral_comparisons}, "runtime": identity["runtime"], "runtime_fingerprint_sha256": identity["runtime_sha"], "profile_order": list(PROFILES), "profiles": profiles, "payloads": sorted(public_payloads, key=lambda row: row["role_path"].encode())} + evidence_raw = artifacts.canonical_json_bytes(evidence) + artifacts.write_bytes_no_replace(stage / "exact-five-evidence.json", evidence_raw) + evidence_record = _record(stage / "exact-five-evidence.json", "exact-five-evidence.json", 16 * 1024 * 1024) + evidence_sidecar = f"{artifacts.sha256_bytes(evidence_raw)} exact-five-evidence.json\n".encode("ascii") + artifacts.write_bytes_no_replace(stage / "exact-five-evidence.sha256", evidence_sidecar) + _sidecar(artifacts.read_regular_file(stage / "exact-five-evidence.sha256", max_bytes=256), evidence_raw, "exact-five-evidence.json") + pre_start = time.perf_counter() + pre_records = artifacts.closed_inventory(stage, PRE_REPORT_ROLES, max_file_bytes=16 * 1024 * 1024) + _artifact_caps(pre_records, evidence_role="exact-five-evidence.json") + _need(len(pre_records) == 17, "pre-report closure is not exactly 17 files") + pre_seconds = float(time.perf_counter() - pre_start) + timings = [*context["timings"], {"phase": "publisher-baseline-admission", "seconds": baseline_seconds}, {"phase": "comparison", "seconds": comparison_seconds}, {"phase": "pre-report-closure", "seconds": pre_seconds}] + timings.append({"phase": "total-before-seal", "seconds": float(sum(item["seconds"] for item in timings))}) + gate_ids = ("exact-five.run.01.identity", "exact-five.run.02.managed-tests", "exact-five.run.03.publisher-baseline-admission", *tuple(f"exact-five.run.{4 + index * 2 + offset:02d}.profile.{profile}.seed-{seed}" for index, profile in enumerate(PROFILES) for offset, seed in enumerate(SEEDS)), *tuple(f"exact-five.run.{14 + index:02d}.profile.{profile}.cross-seed" for index, profile in enumerate(PROFILES)), "exact-five.run.19.standard-neutral-payload-equality", "exact-five.run.20.evidence-graph", "exact-five.run.21.pre-report-closure") + gates = [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in gate_ids] + started_utc, finished_utc = _now(), _now() + report = {"schema": "owned-root-assembly-successor-exact-five-run-report.v1", "outcome": "success", "literal_invocation": context["literal_invocation"], "output_path": context["output_path"], "staging_path": str(stage), "python_executable_path": os.path.abspath(sys.executable), "neutral_baseline_path": str(baseline), "started_utc": started_utc, "finished_utc": finished_utc, "timings": timings, "activation_contract_sha256": ACTIVATION_SHA, "design_contract_sha256": DESIGN_SHA, "runtime_fingerprint_sha256": identity["runtime_sha"], "evidence": {"role_path": "exact-five-evidence.json", "bytes": evidence_record["bytes"], "sha256": evidence_record["sha256"], "schema": "owned-root-assembly-successor-exact-five-evidence.v1"}, "evidence_sidecar": {"role_path": "exact-five-evidence.sha256", "bytes": len(evidence_sidecar), "sha256": artifacts.sha256_bytes(evidence_sidecar)}, "payloads": sorted(public_payloads, key=lambda row: row["role_path"].encode()), "profile_seed_runs": [{"profile_id": profile, "seed": seed, "outcome": "success", "evidence_sha256": bundle_values[index * 2 + (seed == 29)]["records"]["profile-seed-evidence.json"]["sha256"]} for index, profile in enumerate(PROFILES) for seed in SEEDS], "gates": gates} + report_raw = artifacts.canonical_json_bytes(report) + artifacts.write_bytes_no_replace(stage / "run-report.json", report_raw) + report_sidecar = f"{artifacts.sha256_bytes(report_raw)} run-report.json\n".encode("ascii") + artifacts.write_bytes_no_replace(stage / "run-report.sha256", report_sidecar) + _sidecar(artifacts.read_regular_file(stage / "run-report.sha256", max_bytes=256), report_raw, "run-report.json") + final_records = artifacts.closed_inventory(stage, PUBLIC_ROLES, max_file_bytes=16 * 1024 * 1024) + _artifact_caps(final_records, evidence_role="exact-five-evidence.json", total_limit=32 * 1024 * 1024) + _need(len(final_records) == 19, "final staging closure is not exactly 19 files") + return stage + + +def main(argv=None): + values = sys.argv[1:] if argv is None else argv + try: + _need(len(values) == 14, "publisher requires baseline, ten bundles, receipt, context, and staging paths") + paths = [_abs(value, "publisher path") for value in values] + _need(paths[0].is_dir() and paths[11].name == "managed-test-receipt.json" and paths[12].name == "launcher-context.json", "publisher input roles differ") + _need([paths[1 + index].name for index in range(10)] == ["seed-17", "seed-29"] * 5, "publisher bundle order differs") + _need(not os.path.lexists(paths[13]), "publication staging path is not absent") + publish(paths[0], paths[1:11], paths[11], paths[12], paths[13]) + except Exception as exc: + print(f"exact-five publisher: error: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py b/experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py new file mode 100644 index 0000000..f9fbf0c --- /dev/null +++ b/experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py @@ -0,0 +1,688 @@ +"""Private managed-test and profile/seed runner for the frozen exact-five gate.""" +from __future__ import annotations + +import datetime +import importlib.metadata +import importlib.util +import json +import locale +import math +import os +import platform +import re +import shutil +import struct +import sys +import sysconfig +import tempfile +import time +import unittest +import zlib +from decimal import Decimal, ROUND_HALF_EVEN, localcontext +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +NEUTRAL = ROOT / "experiments/owned-root-assembly-successor" +PROFILE_PACKAGE = ROOT / "experiments/current-form-surface-preview" +TESTS = ROOT / "experiments/owned-root-assembly-successor-exact-five/tests" +for _module_path in (str(NEUTRAL), str(PROFILE_PACKAGE)): + if _module_path not in sys.path: + sys.path.insert(0, _module_path) + +import anatomy_gates as anatomy +import artifact_serialization as artifacts +import chart_lineage as chart +import generate_structural_profile_sources as profiles +import mesh_correctness as mesh_api +import owned_root_surface as surface +import prepared_projection as neutral_projection +import render_export as render + +ACTIVATION_ROLE = "experiments/owned-root-assembly-successor/exact-five-activation-contract.md" +ACTIVATION_SIDECAR_ROLE = "experiments/owned-root-assembly-successor/exact-five-activation-contract.sha256" +DESIGN_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" +RUNNER_ROLE = "experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py" +EXPECTED_ACTIVATION_SHA256 = "a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49" +EXPECTED_DESIGN_SHA256 = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +EXPECTED_SOURCE_SHA256 = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +EXPECTED_PROFILE_SHA256 = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +RUNTIME_SHA256 = "c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085" +PROFILE_IDS = ( + "standard_neutral_reference", "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", "slender_long_limb", "stocky_broad_chested", +) +PARAMETER_IDS = tuple(neutral_projection.MUST_AFFECT_PARAMETER_IDS) +PROFILE_SEEDS = (17, 29) +MUST_AFFECT_PARAMETER_IDS = PARAMETER_IDS +MUST_AFFECT_COMPONENTS = neutral_projection.MUST_AFFECT_COMPONENTS +SURFACE_ROLES = tuple(f"surface-level-{level}.ply" for level in range(3)) +PERTURBATION_ROLES = tuple(f"perturb-{name.replace('.', '-')}.ply" for name in PARAMETER_IDS) +PAYLOAD_ROLES = (*SURFACE_ROLES, *PERTURBATION_ROLES, "direct.png", "lineage.png") +BUNDLE_ROLES = (*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256", "run-report.json", "run-report.sha256") +STABLE_ROLES = tuple(sorted((*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256"))) +PUBLIC_ROLES = tuple(f"{profile}/{role}" for profile in PROFILE_IDS for role in ("surface-level-2.ply", "direct.png", "lineage.png")) + ("exact-five-evidence.json", "exact-five-evidence.sha256", "run-report.json", "run-report.sha256") +PINNED_LAUNCHER_ROLE = "experiments/current-form-surface-preview/surface_preview_launcher.sh" +FINAL_GATE_IDS = tuple("""exact-five.run.01.identity +exact-five.run.02.managed-tests +exact-five.run.03.publisher-baseline-admission +exact-five.run.04.profile.standard_neutral_reference.seed-17 +exact-five.run.05.profile.standard_neutral_reference.seed-29 +exact-five.run.06.profile.compact_broad_short_limb_large_head.seed-17 +exact-five.run.07.profile.compact_broad_short_limb_large_head.seed-29 +exact-five.run.08.profile.tall_narrow_long_legged.seed-17 +exact-five.run.09.profile.tall_narrow_long_legged.seed-29 +exact-five.run.10.profile.slender_long_limb.seed-17 +exact-five.run.11.profile.slender_long_limb.seed-29 +exact-five.run.12.profile.stocky_broad_chested.seed-17 +exact-five.run.13.profile.stocky_broad_chested.seed-29 +exact-five.run.14.profile.standard_neutral_reference.cross-seed +exact-five.run.15.profile.compact_broad_short_limb_large_head.cross-seed +exact-five.run.16.profile.tall_narrow_long_legged.cross-seed +exact-five.run.17.profile.slender_long_limb.cross-seed +exact-five.run.18.profile.stocky_broad_chested.cross-seed +exact-five.run.19.standard-neutral-payload-equality +exact-five.run.20.evidence-graph +exact-five.run.21.pre-report-closure""".splitlines()) +LEVEL_COUNTS = ((120, 227, 104, 208, 38), (451, 870, 416, 832, 76), (1737, 3404, 1664, 3328, 152)) +PHASES = ("identity", "selection-projection", "catalogs", "geometry-gates", "causality", "serialization", "total-before-seal") +RUN_GATES = tuple(f"seed.{index}.{name}" for index, name in enumerate(("identity", "prepared-input", "catalogs", "geometry-gates", "causality", "serialization"), 1)) +ADDITIVE_ROLES = tuple(sorted(( + "experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh", + RUNNER_ROLE, + "experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py", + "experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py", +), key=str.encode)) +DEPENDENCIES = tuple(sorted(( + ("experiments/owned-root-assembly-successor/anatomy_gates.py", 25674, "0c4b5f7812141a4cd7c7107655e578044355dfef5dbda6574bbb63bc359a2ff4"), + ("experiments/owned-root-assembly-successor/artifact_serialization.py", 27977, "3837928e4b987c65fd773e540f7db502f5d9a0b4c5940b95c923953754fdf7d4"), + ("experiments/owned-root-assembly-successor/build_owned_root.py", 78268, "713cbf967bf2e0e233bae0c3506199fdc9a6ed71418edbd8dbf9b75beeee4045"), + ("experiments/owned-root-assembly-successor/chart_lineage.py", 18263, "01fdd09e8e0bb6d31851f0c7af711d90b313e36a012dbe3d71415a0468c31efc"), + ("experiments/owned-root-assembly-successor/mesh_correctness.py", 51035, "4104b70e70e958a469125d1fff544e20fee44b784bf7915d8e724e63d4f39db1"), + ("experiments/owned-root-assembly-successor/owned_root_surface.py", 58732, "c982d889fee30e2efea881b5725170740bc8afa2a883aa3dc4623941cd3e2a22"), + ("experiments/owned-root-assembly-successor/prepared_projection.py", 39646, "58637097a350332db40368a027347ec395192880aa6ba4782c7d523e5b288190"), + ("experiments/owned-root-assembly-successor/render_export.py", 15933, "bc251ea3f3f3cb1aa5ea66bfc4f79a82f86191e76bacb9a3c4f58e64883c4780"), + ("experiments/current-form-surface-preview/generate_structural_profile_sources.py", 54437, "009be817cd2ec2db663b668fb5c9bdfa7296936283322e59d7a145e3d3cfec62"), + ("experiments/current-form-surface-preview/structural_atomic_publish.py", 10489, "5e648b3a1a3519afdf0fc1f2f1ecfe6fe7f1c58130f71fd2c8ee4317e2f282b5"), + ("experiments/current-form-surface-preview/surface_preview_launcher.sh", 6582, "3e18da2d361029a16558757d9727150d54c4d691b35c6a2a21b5b51cb7785190"), + ("experiments/current-form-surface-preview/requirements.txt", 49, "69a3ce10b1f993d7913f02ca187eabb8d367abf214662ffa2132feacbdeedbec"), +), key=lambda row: row[0].encode())) +EXPECTED_DEPENDENCY_ROLES = tuple(row[0] for row in DEPENDENCIES) +ADDITIVE_IMPLEMENTATION_ROLES = ADDITIVE_ROLES +REQUIRED_TEST_IDS = tuple(sorted("""test_exact_five_activation.ExactFiveActivationTests.test_all_33_selectors_copy_one_component +test_exact_five_activation.ExactFiveActivationTests.test_atomic_failure_has_no_partial_publication +test_exact_five_activation.ExactFiveActivationTests.test_decimal_half_even_boundaries +test_exact_five_activation.ExactFiveActivationTests.test_final_evidence_schema_and_19_file_closure +test_exact_five_activation.ExactFiveActivationTests.test_geometry_receives_only_components +test_exact_five_activation.ExactFiveActivationTests.test_neutral_projection_preserves_38_payloads +test_exact_five_activation.ExactFiveActivationTests.test_profile_seed_bundle_schema_and_closure +test_exact_five_activation.ExactFiveActivationTests.test_profile_table_closed_and_exact_order +test_exact_five_activation.ExactFiveActivationTests.test_profile_table_rejects_duplicate_keys_and_signatures +test_exact_five_activation.ExactFiveActivationTests.test_projection_has_exact_92_bindings +test_exact_five_activation.ExactFiveActivationTests.test_seed_dispatch_is_exact +test_exact_five_activation.ExactFiveActivationTests.test_static_identity_and_allowlist""".splitlines(), key=str.encode)) +_SHA256 = re.compile(r"[0-9a-f]{64}\Z") +_RUNTIME_DISTS = (("imageio", "2.37.4"), ("lazy-loader", "0.5"), ("networkx", "3.4.2"), ("numpy", "2.2.6"), ("packaging", "26.3"), ("pillow", "11.1.0"), ("scikit-image", "0.25.2"), ("scipy", "1.15.3"), ("tifffile", "2025.5.10")) + + +class ExactFiveError(ValueError): + """A frozen exact-five admission, build, gate, or sealing failure.""" + + +def _need(condition: bool, message: str) -> None: + if not condition: + raise ExactFiveError(message) + + +def _ordered(values): + return sorted(values, key=lambda value: value.encode("utf-8")) + + +def _record(role: str, expected_bytes: int | None = None, expected_hash: str | None = None) -> dict[str, Any]: + path = ROOT / role + _need(not path.is_symlink() and path.is_file(), f"missing or non-regular fixed file: {role}") + record = artifacts.regular_file_record(path, role, max_bytes=4 * 1024 * 1024) + _need(expected_bytes is None or record["bytes"] == expected_bytes, f"byte count mismatch: {role}") + _need(expected_hash is None or record["sha256"] == expected_hash, f"SHA-256 mismatch: {role}") + return record + + +def _runtime(launcher: dict[str, Any], requirements: dict[str, Any]) -> dict[str, Any]: + _need((platform.python_implementation(), platform.python_version(), getattr(sys.implementation, "cache_tag", None)) == ("CPython", "3.10.12", "cpython-310"), "runtime is not pinned CPython 3.10.12") + distributions = [] + for name, expected in _RUNTIME_DISTS: + try: + actual = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError as exc: + raise ExactFiveError(f"missing distribution: {name}=={expected}") from exc + _need(actual == expected, f"distribution drift: {name}=={actual}") + distributions.append({"name": name, "version": actual}) + builtins = [] + for name in ("math", "zlib"): + module, spec = __import__(name), importlib.util.find_spec(name) + _need(getattr(module, "__file__", None) is None and spec is not None and spec.origin == "built-in", f"{name} is not built-in") + compile_version, runtime_version = (None, None) if name == "math" else (zlib.ZLIB_VERSION, zlib.ZLIB_RUNTIME_VERSION) + builtins.append({"module_name": name, "__file__": None, "find_spec_origin": "built-in", "compile_version": compile_version, "runtime_version": runtime_version}) + libc_name, libc_version = platform.libc_ver() + runtime = { + "schema": "owned-root-assembly-successor-runtime.v2", + "python": {"implementation": "CPython", "version": "3.10.12", "build": " ".join(platform.python_build()), "compiler": platform.python_compiler(), "cache_tag": "cpython-310", "abiflags": getattr(sys, "abiflags", ""), "soabi": sysconfig.get_config_var("SOABI")}, + "platform": {"system": platform.system(), "release": platform.release(), "version": platform.version(), "machine": platform.machine(), "pointer_bits": 8 * struct.calcsize("P"), "byteorder": sys.byteorder, "libc_name": libc_name, "libc_version": libc_version}, + "locale": {"active": locale.setlocale(locale.LC_ALL, None), "preferred_encoding": locale.getpreferredencoding(False)}, + "managed_launcher": launcher, "requirements": requirements, + "direct_distributions": [next(row for row in distributions if row["name"] == name) for name in ("numpy", "scikit-image", "pillow")], + "resolved_distributions": distributions, "builtin_modules": builtins, + } + _need(runtime["platform"]["system"] == "Linux" and type(runtime["python"]["soabi"]) is str, "runtime platform is not admitted") + raw = artifacts.canonical_json_bytes(runtime) + _need(len(raw) <= 64 * 1024 and artifacts.sha256_bytes(raw) == RUNTIME_SHA256, "runtime fingerprint mismatch") + return runtime + + +def static_admission() -> dict[str, Any]: + """Bind every frozen input, dependency, additive source, and runtime.""" + activation = _record(ACTIVATION_ROLE, 53777, EXPECTED_ACTIVATION_SHA256) + expected_sidecar = f"{EXPECTED_ACTIVATION_SHA256} {ACTIVATION_ROLE}\n".encode("ascii") + _need(artifacts.read_regular_file(ROOT / ACTIVATION_SIDECAR_ROLE, max_bytes=256) == expected_sidecar, "activation sidecar mismatch") + design = _record(DESIGN_ROLE, 173184, EXPECTED_DESIGN_SHA256) + source = _record(SOURCE_ROLE, 56984, EXPECTED_SOURCE_SHA256) + table = _record(PROFILE_ROLE, 29970, EXPECTED_PROFILE_SHA256) + dependencies = tuple(_record(*row) for row in DEPENDENCIES) + package = ROOT / "experiments/owned-root-assembly-successor-exact-five" + found = [] + for directory, subdirectories, filenames in os.walk(package, followlinks=False): + _need(not Path(directory).is_symlink(), "additive package contains a symlink directory") + for name in filenames: + path = Path(directory) / name + if path.suffix in (".py", ".sh"): + _need(not path.is_symlink(), "additive package contains a symlink source") + found.append(path.relative_to(ROOT).as_posix()) + subdirectories[:] = [name for name in subdirectories if not (Path(directory) / name).is_symlink()] + _need(tuple(_ordered(found)) == ADDITIVE_ROLES, "additive implementation allowlist mismatch") + additive = tuple(_record(role) for role in ADDITIVE_ROLES) + production_loc = sum(artifacts.read_regular_file(ROOT / row["role_path"]).count(b"\n") for row in additive if "/tests/" not in row["role_path"]) + test_loc = sum(artifacts.read_regular_file(ROOT / row["role_path"]).count(b"\n") for row in additive if "/tests/" in row["role_path"]) + _need(production_loc <= 1600 and test_loc <= 1200, f"additive LOC cap exceeded: production={production_loc}, tests={test_loc}") + launcher = next(row for row in dependencies if row["role_path"].endswith("surface_preview_launcher.sh")) + requirements = next(row for row in dependencies if row["role_path"].endswith("requirements.txt")) + _need(artifacts.read_regular_file(ROOT / requirements["role_path"]) == b"numpy==2.2.6\nscikit-image==0.25.2\nPillow==11.1.0\n", "requirements drift") + runtime = _runtime(launcher, requirements) + return {"activation_contract": activation, "design_contract": design, "source": source, "profile_table": table, "existing_dependencies": dependencies, "additive_implementation_files": additive, "runtime": runtime, "runtime_fingerprint_sha256": RUNTIME_SHA256} + + +def run_managed_tests(receipt_path: str | os.PathLike[str]) -> dict[str, Any]: + _need(os.environ.get("PYTHONHASHSEED") == "0", "managed tests require literal PYTHONHASHSEED=0") + receipt = Path(receipt_path) + _need(receipt.is_absolute() and os.path.normpath(str(receipt)) == str(receipt) and not os.path.lexists(receipt), "receipt must be canonical, absolute, and absent") + _need(not receipt.parent.is_symlink() and receipt.parent.parent.is_dir() and (not receipt.parent.exists() or receipt.parent.is_dir()), "receipt parent is not staging-safe") + before = static_admission() + sys.path.insert(0, str(TESTS)) + try: + suite = unittest.TestLoader().discover(str(TESTS), pattern="test_*.py") + def flatten(node): + for item in node: + yield from flatten(item) if isinstance(item, unittest.TestSuite) else (item,) + tests = tuple(flatten(suite)); ids = tuple(test.id() for test in tests) + _need(ids and len(ids) == len(set(ids)) and all(ids.count(required) == 1 for required in REQUIRED_TEST_IDS), "managed discovery missed a required exact-five test") + result = unittest.TestResult(); suite.run(result) + finally: + if sys.path and sys.path[0] == str(TESTS): + sys.path.pop(0) + after = static_admission() + _need(artifacts.canonical_json_bytes(before) == artifacts.canonical_json_bytes(after), "identity changed during managed tests") + _need(result.testsRun == len(ids) and not (result.failures or result.errors or result.skipped or result.expectedFailures or result.unexpectedSuccesses), "managed tests did not all pass") + value = {"schema": "owned-root-assembly-successor-exact-five-managed-test-receipt.v1", "outcome": "success", "invocation": {"environment": ["PYTHONHASHSEED=0"], "implementation_role": RUNNER_ROLE, "mode": "managed-tests"}, "activation_contract": after["activation_contract"], "design_contract": after["design_contract"], "existing_dependencies": list(after["existing_dependencies"]), "additive_implementation_files": list(after["additive_implementation_files"]), "runtime": after["runtime"], "runtime_fingerprint_sha256": RUNTIME_SHA256, "executed_test_ids": _ordered(ids), "required_test_ids": list(REQUIRED_TEST_IDS), "results": {"tests_run": len(ids), "failures": 0, "errors": 0, "skipped": 0, "expected_failures": 0, "unexpected_successes": 0}} + raw = artifacts.canonical_json_bytes(value); _need(len(raw) <= 16 * 1024 * 1024, "managed-test receipt exceeds 16 MiB") + receipt.parent.mkdir(exist_ok=True); artifacts.write_bytes_no_replace(receipt, raw) + return value + + +def project_decimal_metres(token: int | Decimal, scale: int) -> tuple[Decimal, float]: + """Apply the exact permille, half-even millimetre projection rule.""" + _need(type(scale) is int and 1 <= scale <= 10000 and not isinstance(token, bool) and isinstance(token, (int, Decimal)), "invalid decimal projection input") + value = Decimal(token) + _need(value.is_finite() and value > 0, "source dimension is not finite and positive") + with localcontext() as context: + context.prec = max(context.prec, len(value.as_tuple().digits) + len(str(scale)) + 2) + q = (value * Decimal(scale)).to_integral_value(rounding=ROUND_HALF_EVEN) + projected = q / Decimal(1000) + _need(projected > 0 and projected.is_finite(), "dimension quantized to zero or non-finite") + number = float(projected) + _need(math.isfinite(number) and Decimal(str(number)) == projected, "projected decimal cannot round-trip through binary64") + return projected, number + + +def _pointer_get(root: Any, pointer: str) -> Any: + _need(pointer.startswith("/") and pointer != "/", "invalid canonical pointer") + value = root + for token in pointer[1:].split("/"): + token = token.replace("~1", "/").replace("~0", "~") + value = value[int(token)] if type(value) is list and token.isdigit() and (token == "0" or not token.startswith("0")) else value[token] + return value + + +def _escape_pointer(value: str) -> str: + return value.replace("~", "~0").replace("/", "~1") + + +def _dimension_group(component: str) -> str: + if component.startswith("stations."): + neck = component.split(".")[1] in ("neck_collar", "neck_upper") + return ("neck_profile_lateral" if component.endswith(".rL") else "neck_profile_forward") if neck else ("body_profile_lateral" if component.endswith(".rL") else "body_profile_depth") + if component.startswith("shoulders."): + return {"start_lateral": "arm_profile_lateral", "start_up": "arm_profile_up", "start_forward": "arm_profile_forward", "shoulder_depth": "arm_shoulder"}[component.rsplit(".", 1)[1]] + return {"r_x": "leg_profile_lateral", "r_y": "leg_profile_up", "r_z": "leg_profile_forward"}[component.rsplit(".", 1)[1]] + + +def validate_profile_table(table: dict[str, Any]) -> dict[str, Any]: + """Validate the complete closed active-five table against the fixed source.""" + source, raw = profiles.load_json_with_bytes(ROOT / SOURCE_ROLE, "authored source") + _need(artifacts.sha256_bytes(raw) == EXPECTED_SOURCE_SHA256, "fixed source identity mismatch") + profiles.generate_sources(table, source, mode=profiles.DEFAULT_GENERATION_MODE) + return table + + +def admit_profile_table(raw: bytes) -> dict[str, Any]: + """Admit only the exact fixed canonical profile-table bytes.""" + _need(type(raw) is bytes and len(raw) == 29970 and artifacts.sha256_bytes(raw) == EXPECTED_PROFILE_SHA256, "profile table identity mismatch") + def pairs(items): + value = dict(items); _need(len(value) == len(items), "profile table contains a duplicate key"); return value + try: + table = json.loads(raw.decode("utf-8"), object_pairs_hook=pairs, parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token))) + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError, TypeError, ValueError) as exc: + raise ExactFiveError("profile table is not strict finite UTF-8 JSON") from exc + _need(type(table) is dict, "profile table is not an object") + return validate_profile_table(table) + + +def select_profile(table: dict[str, Any], profile_id: str) -> dict[str, Any]: + """Select one exact ID only after complete-table validation.""" + validate_profile_table(table); _need(type(profile_id) is str and profile_id in PROFILE_IDS, "unknown exact profile ID") + matches = [(index, row) for index, row in enumerate(table["profiles"]) if row["id"] == profile_id] + _need(len(matches) == 1, "profile selection is not unique") + return {"id": profile_id, "index": matches[0][0], "row": matches[0][1]} + + +def project_profile(profile_id: str, source: dict[str, Any] | None = None, table: dict[str, Any] | None = None) -> dict[str, Any]: + """Validate all five transforms, select one exact row, and form 92 numbers.""" + _need(type(profile_id) is str and profile_id in PROFILE_IDS, "unknown exact profile ID") + if source is None: + source, source_raw = profiles.load_json_with_bytes(ROOT / SOURCE_ROLE, "authored source") + _need(artifacts.sha256_bytes(source_raw) == EXPECTED_SOURCE_SHA256, "fixed source identity mismatch") + if table is None: + table, table_raw = profiles.load_json_with_bytes(ROOT / PROFILE_ROLE, "profile table") + _need(artifacts.sha256_bytes(table_raw) == EXPECTED_PROFILE_SHA256, "fixed profile table identity mismatch") + generated = profiles.generate_sources(table, source, mode=profiles.DEFAULT_GENERATION_MODE) + rows = table.get("profiles") if type(table) is dict else None + _need(type(rows) is list and len(rows) == 5 and tuple(row.get("id") for row in rows if type(row) is dict) == PROFILE_IDS, "profile order is not exact") + matches = [(index, row) for index, row in enumerate(rows) if row["id"] == profile_id] + _need(len(matches) == 1, "profile selection is not unique") + profile_index, row = matches[0]; transformed = generated[profile_index] + bindings, projected_values, values = [], [], [] + source_bindings = neutral_projection.source_binding_records() + _need(tuple(item["prepared_component"] for item in source_bindings) == tuple(surface.GEOMETRY_COMPONENT_IDS), "neutral binding component universe drift") + for original in source_bindings: + component, source_pointers = original["prepared_component"], list(original["source_pointers"]) + if original["derivation_id"] == "source.dimension-value.v1": + group = _dimension_group(component); scale = row["dimension_scales"][group] + projected, number = project_decimal_metres(_pointer_get(source, source_pointers[0]), scale) + _need(Decimal(str(_pointer_get(transformed, source_pointers[0]))) == projected, f"profile generator disagrees for {component}") + profile_pointers = [f"/profiles/{profile_index}/dimension_scales/{_escape_pointer(group)}"] + derivation = "profile.dimension-permille-half-even-mm.v1" + else: + part_pointers = sorted((pointer for pointer in source_pointers if pointer.startswith("/body/parts/")), key=lambda pointer: int(pointer.split("/")[3])) + landmark_pointers = [pointer for pointer in source_pointers if pointer.startswith("/body/landmarks/")] + _need(len(landmark_pointers) == (1 if "landmark" in original["derivation_id"] else 0), f"sum pointer inventory differs for {component}") + number = 0.0 + for pointer in part_pointers: + value = _pointer_get(transformed, pointer); _need(type(value) is int and abs(value) <= 1_000_000_000, "placement is not a bounded exact integer") + number = number + float(value) + for pointer in landmark_pointers: + number = number + float(_pointer_get(transformed, pointer)) + _need(math.isfinite(number), f"world sum is non-finite for {component}") + profile_pointers = [] + for pointer in part_pointers: + pieces = pointer.split("/"); part_index, axis = int(pieces[3]), int(pieces[-1]) + key = profiles.address_key(source["body"]["parts"][part_index]["address"]) + profile_pointers.append(f"/profiles/{profile_index}/part_placements/{_escape_pointer(key)}/{axis}") + derivation = "profile.world-landmark-axis-sum.v1" if landmark_pointers else "profile.world-placement-axis-sum.v1" + profile_pointers = _ordered(profile_pointers) + binding = {"prepared_component": component, "derivation_id": derivation, "source_addresses": original["source_addresses"], "source_pointers": source_pointers, "profile_pointers": profile_pointers} + record = {"prepared_component": component, "value": number, "source_pointers": source_pointers, "profile_pointers": profile_pointers} + bindings.append(binding); projected_values.append(record); values.append(number) + _need(len(bindings) == 92 and len({row["prepared_component"] for row in bindings}) == 92, "projection is not exactly 92 unique bindings") + carrier = surface.GeometryComponents(tuple(values)); surface.validate_geometry_components(carrier) + carrier_raw = artifacts.canonical_json_bytes(list(carrier.values)) + selection = {"profile_pointer": f"/profiles/{profile_index}", "profile_row_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row)), "dimension_scales_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["dimension_scales"])), "part_placements_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(row["part_placements"]))} + return {"profile_id": profile_id, "profile_index": profile_index, "selection": selection, "carrier": carrier, "projected_values": projected_values, "projected_carrier": {"bytes": len(carrier_raw), "sha256": artifacts.sha256_bytes(carrier_raw)}, "projection_bindings": bindings} + + +def _gate(gate_id, count, minimum, maximum, relation, lower, upper, unit): + threshold = {"threshold_id": f"threshold.{gate_id}", "relation": relation, "lower": lower, "upper": upper, "unit": unit} + passed = minimum == lower and maximum == upper if relation == "eq" else minimum >= lower if relation == "ge" else maximum <= upper if relation == "le" else maximum < upper + return {"gate_id": gate_id, "outcome": "pass" if passed else "fail", "sample_count": count, "observed_min": minimum, "observed_max": maximum, "threshold_id": threshold["threshold_id"]}, threshold + + +def _put(rows, thresholds, pair): + rows.append(pair[0]); thresholds.append(pair[1]) + + +def _bool(gate_id): + return _gate(gate_id, 1, 1, 1, "eq", 1, 1, "boolean") + + +def _directions(): + vectors = {"+X": (1.0, 0.0, 0.0), "-X": (-1.0, 0.0, 0.0), "+Y": (0.0, 1.0, 0.0), "-Y": (0.0, -1.0, 0.0)} + return {name: vectors[info[1]] for name, info in surface.PORT_INFO.items()} + + +def _chart_owners(mesh, summary): + rows = [row for row in summary["chart_records"] if row["level"] == mesh.level]; owners = {} + for row in rows: + _need(row["face_id"] not in owners, "duplicate chart face ownership"); owners[row["face_id"]] = row["construction_owner"] + _need(len(rows) == len(mesh.face_ids) and set(owners) == set(mesh.face_ids), "chart face incidence is incomplete") + return tuple(owners[face_id] for face_id in mesh.face_ids) + + +def _junction_cycles(mesh, owners, domains): + uses = {} + for face_index, face in enumerate(mesh.quads): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4]; uses.setdefault(tuple(sorted((left, right))), []).append((owners[face_index], left, right)) + result = [] + for domain in domains: + following = {} + for rows in uses.values(): + if len(rows) == 2 and frozenset(row[0] for row in rows) == frozenset(domains): + selected = [row for row in rows if row[0] == domain]; _need(len(selected) == 1 and selected[0][1] not in following, "junction trace is not unique"); following[selected[0][1]] = selected[0][2] + _need(following, "junction trace is empty"); start = current = min(following); cycle = [] + while current not in cycle: + cycle.append(current); _need(current in following, "junction trace is open"); current = following[current] + _need(current == start and len(cycle) == len(following), "junction trace is not one cycle"); result.append(tuple(cycle)) + return tuple(result) + + +def _half_tag(left, right): + numerator = left[0] * right[1] + right[0] * left[1]; denominator = 2 * left[1] * right[1]; common = math.gcd(abs(numerator), denominator) + return numerator // common, denominator // common + + +def _domain_tags(meshes, owners, domains, domain_index, axes, level): + axis_index = {"i": 0, "j": 1, "k": 2}; cycles = tuple(_junction_cycles(mesh, owner, domains)[domain_index] for mesh, owner in zip(meshes[:level + 1], owners[:level + 1])) + tags = {vertex: tuple((surface.COORDINATE_BY_CONTROL[meshes[0].control_ids[vertex]][axis_index[axis]], 1) for axis in axes) for vertex in cycles[0]} + for current in range(1, level + 1): + points = dict(surface.subdivision_incidence(meshes[current - 1])["edge_point_indices"]); previous = cycles[current - 1]; out = {vertex: tags[vertex] for vertex in cycles[current] if vertex in tags} + for slot, left in enumerate(previous): + right = previous[(slot + 1) % len(previous)]; point = points.get(tuple(sorted((left, right)))); _need(point is not None, "junction midpoint absent"); out[point] = tuple(_half_tag(tags[left][axis], tags[right][axis]) for axis in range(2)) + _need(set(out) == set(cycles[current]), "junction tag incidence incomplete"); tags = out + return dict(sorted(tags.items())) + + +def _junction_inputs(evaluation, level, summary): + meshes = (evaluation.cage, *evaluation.levels); owners = tuple(_chart_owners(mesh, summary) for mesh in meshes); result = {} + for junction in surface.JUNCTIONS: + domains, (_drop, axes) = surface.JUNCTION_INFO[junction] + maps = tuple(_domain_tags(meshes, owners, domains, index, axes, level) for index in range(2)); reference = tuple(dict(surface.propagate_junction_tags(evaluation, junction)[level]) for _ in domains) + result[junction] = {"incident_domains": domains, "domain_vertex_tags": maps, "expected_domain_vertex_tags": reference} + return result + + +def _metrics(mesh): + edges = {tuple(sorted((left, face[(slot + 1) % 4]))) for face in mesh.quads for slot, left in enumerate(face)} + sub = lambda a, b: tuple(a[i] - b[i] for i in range(3)); cross = lambda a, b: (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); norm = lambda value: math.sqrt(sum(item * item for item in value)) + edge_values = tuple(norm(sub(mesh.vertices[right], mesh.vertices[left])) for left, right in sorted(edges)); triangles, quads = [], [] + for face in mesh.quads: + a, b, c, d = (mesh.vertices[index] for index in face); areas = (0.5 * norm(cross(sub(b, a), sub(c, a))), 0.5 * norm(cross(sub(c, a), sub(d, a)))); triangles.extend(areas); quads.append(sum(areas)) + return edge_values, tuple(triangles), tuple(quads) + + +def _edge_uses(mesh): + uses = {} + for face_index, face in enumerate(mesh.quads): + for slot, left in enumerate(face): + uses.setdefault(tuple(sorted((left, face[(slot + 1) % 4]))), []).append(face_index) + return uses + + +def _ownership_counts(evaluation, formulas, summary, components, level): + mesh = (evaluation.cage, *evaluation.levels)[level]; uses = _edge_uses(mesh); expected = LEVEL_COUNTS[level] + _need((len(mesh.control_ids), len(mesh.quads), len(uses), len(surface.PORTS)) == (expected[0], expected[2], expected[1], 5), "ownership universe changed") + edges = tuple(uses); keys = tuple(("vertex", value) for value in mesh.control_ids) + tuple(("face", value) for value in mesh.face_ids) + tuple(("edge", value) for value in edges) + tuple(("boundary", value) for value in surface.PORTS) + required = {key: ("construction", "lineage") if level == 0 and key[0] == "vertex" else ("lineage",) if key[0] == "vertex" else ("chart",) if key[0] == "face" else ("classification",) if key[0] == "edge" else ("boundary",) for key in keys} + expected_summary = chart.build_chart_summary(evaluation, formulas); formula_by_id = {row["control_id"]: row for row in formulas}; expected_vertices = {(row["level"], row["vertex_id"]): row for row in expected_summary["vertex_records"]}; expected_faces = {(row["level"], row["face_id"]): row for row in expected_summary["chart_records"]} + records = [(("vertex", row["control_id"]), "construction", row == formula_by_id.get(row["control_id"])) for row in evaluation.cage.formula_records] if level == 0 else [] + records.extend((("vertex", row["vertex_id"]), "lineage", row == expected_vertices.get((level, row["vertex_id"]))) for row in summary["vertex_records"] if row["level"] == level) + records.extend((("face", row["face_id"]), "chart", row == expected_faces.get((level, row["face_id"]))) for row in summary["chart_records"] if row["level"] == level) + owners, junction_edges = mesh.face_owners, {} + for junction in surface.JUNCTIONS: + domains = surface.JUNCTION_INFO[junction][0]; cycle = _junction_cycles(mesh, owners, domains)[0] + junction_edges[frozenset(domains)] = {tuple(sorted((left, cycle[(slot + 1) % len(cycle)]))) for slot, left in enumerate(cycle)} + boundary = {edge for edge, faces in uses.items() if len(faces) == 1} + for edge, faces in uses.items(): + if len(faces) == 1 and edge in boundary or len(faces) == 2 and owners[faces[0]] == owners[faces[1]] or len(faces) == 2 and edge in junction_edges.get(frozenset(owners[index] for index in faces), ()): + records.append((("edge", edge), "classification", True)) + records.extend((("boundary", port), "boundary", all(tuple(sorted((left, loop[(slot + 1) % len(loop)]))) in boundary for slot, left in enumerate(loop)) and len(boundary) == sum(len(values) for _, values in mesh.boundary_loops)) for port, loop in mesh.boundary_loops) + return mesh_api.classify_ownership_records(keys, required, tuple(records)) + + +def _fold_samples(mesh, junction): + uses = _edge_uses(mesh); domains = frozenset(surface.JUNCTION_INFO[junction][0]) + values = tuple(mesh_api.fold_angle_degrees(mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[0]]), mesh_api.quad_normal(mesh.vertices, mesh.quads[faces[1]])) for faces in uses.values() if len(faces) == 2 and frozenset(mesh.face_owners[index] for index in faces) == domains) + _need(values, f"no fold samples for {junction}"); return values + + +def _sample(rows, thresholds, gate_id, values, relation, lower, upper, unit): + values = tuple(values); _need(values and all(math.isfinite(value) for value in values), f"empty/non-finite gate samples: {gate_id}") + _put(rows, thresholds, _gate(gate_id, len(values), min(values), max(values), relation, lower, upper, unit)) + + +def _catalog_gates(): + surface.validate_catalogs(); values = {"selected_cells": 58, "un_capped_faces": 122, "domains": 8, "junctions": 7, "ports": 5, "controls": 120, "base_quads": 104, "base_edges": 227, "base_boundary_edges": 38, "boundary_components": 5, "connected_components": 1, "euler_characteristic": -3, "extraordinary_controls": 20, "special_case_ids": 9, "topology_decision_sites": 3} + booleans = "all_domains_nonempty selected_cell_inventory_exact control_catalog_exact face_catalog_exact junction_catalog_exact port_catalog_exact special_case_catalog_exact base_face_controls_distinct base_edge_use_within_two construction_ownership_complete port_caps_exactly_removed axillary_fixture_suite_complete intersection_fixture_suite_complete".split(); gates, thresholds = [], [] + for name, value in values.items(): + relation, lower, upper = ("le", None, 3) if name == "topology_decision_sites" else ("eq", value, value); _put(gates, thresholds, _gate(f"structural.catalog.{name}", 1, value, value, relation, lower, upper, "dimensionless" if name == "euler_characteristic" else "count")) + for name in booleans: + _put(gates, thresholds, _bool(f"structural.catalog_boolean.{name}")) + return gates, thresholds + + +def run_geometry(components: surface.GeometryComponents) -> dict[str, Any]: + """Run unchanged neutral geometry and gates from only the numeric carrier.""" + _need(type(components) is surface.GeometryComponents, "geometry accepts only GeometryComponents") + surface.validate_geometry_components(components) + axillary, intersections = anatomy.run_production_axillary_fixtures(), mesh_api.run_production_intersection_fixtures() + _need(len(axillary) == 13 and tuple(row["fixture_id"] for row in axillary) == anatomy.AXILLARY_FIXTURE_IDS, "axillary fixtures drift") + _need(len(intersections) == 105 and tuple(row["fixture_id"] for row in intersections) == mesh_api.INTERSECTION_FIXTURE_IDS, "intersection fixtures drift") + evaluation = surface.evaluate(components); meshes = (evaluation.cage, *evaluation.levels); formulas = tuple(surface.formula_candidate_records(components)); summary = chart.build_chart_summary(evaluation, formulas) + chart.validate_chart_summary(summary, evaluation, formulas); anatomy.validate_evaluated_surface(evaluation, components, summary); anatomy_rows = tuple(anatomy.anatomy_gate_records(evaluation, components, summary)) + expected_faces = tuple(tuple(int(control[1:]) for control in row[2]) for row in surface.FACE_RECORDS) + _need(tuple(len(rows) for rows in mesh_api.derive_expected_face_catalogs(expected_faces)) == (104, 416, 1664), "topology derivation drift") + reports = [mesh_api.validate_geometry(mesh.vertices, mesh.quads, level, dict(mesh.boundary_loops), _directions(), expected_faces, _junction_inputs(evaluation, level, summary), mesh.face_owners) for level, mesh in enumerate(meshes)] + structural, thresholds = _catalog_gates(); chart_counts = {row["level"]: row for row in summary["level_counts"]} + invalid_names = "duplicate_vertex_ids duplicate_face_ids degenerate_faces zero_length_edges non_manifold_edges orientation_conflicts unowned_elements overowned_elements accidental_boundary_components".split() + for level, (mesh, report) in enumerate(zip(meshes, reports)): + edges, triangles, quads = _metrics(mesh); topology = report["topology"] + for name, value in zip(("vertices", "edges", "quads", "triangles", "boundary_edges"), (len(mesh.vertices), topology.edge_count, len(mesh.quads), len(mesh.triangles), topology.boundary_edge_count)): + _put(structural, thresholds, _gate(f"structural.L{level}.count.{name}", 1, value, value, "eq", value, value, "count")) + for name in "connected orientable outward_wound boundary_components_match_ports".split(): + _put(structural, thresholds, _bool(f"structural.L{level}.surface_boolean.{name}")) + for name, count in (("coordinates", 3 * len(mesh.vertices)), ("quad_normals", 3 * len(mesh.quads)), ("triangle_areas", len(triangles)), ("quad_areas", len(quads))): + _put(structural, thresholds, _bool(f"structural.L{level}.finite.{name}")); structural[-1]["sample_count"] = count + for name, samples in (("edge_length", edges), ("triangle_area", triangles), ("quad_area", quads)): + _put(structural, thresholds, _gate(f"structural.L{level}.floor.{name}", len(samples), min(samples), max(samples), "ge", mesh_api.STRUCTURAL_FLOORS[level][name], None, "m" if name == "edge_length" else "m2")) + ownership = _ownership_counts(evaluation, formulas, summary, components, level) + invalid = {"duplicate_vertex_ids": len(mesh.control_ids) - len(set(mesh.control_ids)), "duplicate_face_ids": len(mesh.face_ids) - len(set(mesh.face_ids)), "degenerate_faces": sum(triangles[2 * index] <= 0.0 or triangles[2 * index + 1] <= 0.0 for index in range(len(mesh.quads))), "zero_length_edges": sum(value == 0.0 for value in edges), "non_manifold_edges": topology.non_manifold_edges, "orientation_conflicts": topology.orientation_conflicts, "unowned_elements": ownership["unowned_elements"], "overowned_elements": ownership["overowned_elements"], "accidental_boundary_components": abs(topology.boundary_components - len(surface.PORTS))} + for name in invalid_names: + _put(structural, thresholds, _gate(f"structural.L{level}.invalid_count.{name}", 1, invalid[name], invalid[name], "eq", 0, 0, "count")) + for name in ("charts", "interior_transitions", "maximum_samples_per_vertex"): + value = chart_counts[level][name]; _put(structural, thresholds, _gate(f"structural.L{level}.chart.{name}", 1, value, value, "eq", value, value, "count")) + rows = [row for row in summary["vertex_records"] if row["level"] == 2] + for name, field, limit in (("base_control_contributors", "base_control_contributors", 20), ("dependency_union_keys", "geometry_dependency_union", 54), ("contributor_domains", "contributor_domains", 5)): + value = max(len(row[field]) for row in rows); _put(structural, thresholds, _gate(f"structural.L2.lineage_cap.{name}", 1737, value, value, "le", None, limit, "count")) + for name in "recurrence_exact incidence_complete boundary_neighbors_exact face_emission_exact lineage_complete chart_complete transition_complete".split(): + _put(structural, thresholds, _bool(f"structural.subdivision.{name}")) + continuity, continuity_thresholds = [], [] + for level, (mesh, report) in enumerate(zip(meshes, reports)): + inputs = _junction_inputs(evaluation, level, summary) + for junction in surface.JUNCTIONS: + metrics = mesh_api.junction_continuity_metrics(mesh.vertices, mesh.quads, mesh.face_owners, **inputs[junction]); count = len(metrics["traces"][0]); residuals, folds = metrics["coordinate_residual_samples"], _fold_samples(mesh, junction) + _need(len(residuals) == 3 * count and len(folds) == count, "continuity cardinality drift") + for name, samples, relation, lower, upper, unit in (("tag_identity", (1,), "eq", 1, 1, "boolean"), ("opposite_trace_direction", (1,), "eq", 1, 1, "boolean"), ("coordinate_residual", residuals, "le", None, mesh_api.T, "m"), ("fold_angle", folds, "lt", None, (90.0, 60.0, 30.0)[level], "degree")): + _sample(continuity, continuity_thresholds, f"continuity.{junction}.L{level}.{name}", samples, relation, lower, upper, unit) + for port, metric in report["port_metrics"].items(): + count = len(dict(mesh.boundary_loops)[port]); _need(len(metric["planarity_samples"]) == count and len(metric["co_normal_samples"]) == count, "port sample cardinality drift") + for name, samples, relation, lower, upper, unit in (("orientation", (metric["orientation"],), "ge", .99, None, "dimensionless"), ("planarity", metric["planarity_samples"], "le", None, mesh_api.T, "m"), ("area_ratio", (metric["area_ratio"],), "ge", .0001, None, "dimensionless"), ("co_normal", metric["co_normal_samples"], "ge", .80, None, "dimensionless")): + _sample(continuity, continuity_thresholds, f"continuity.{port}.L{level}.{name}", samples, relation, lower, upper, unit) + thresholds.extend(continuity_thresholds); thresholds.extend(anatomy.anatomy_threshold_records()); intersection, intersection_thresholds = [], [] + for level, (mesh, report) in enumerate(zip(meshes, (row["intersection_report"] for row in reports))): + for name, value, relation, lower, upper, unit in (("triangle_count", report["triangle_count"], "eq", len(mesh.triangles), len(mesh.triangles), "count"), ("broad_phase_candidate_count", report["broad_phase_candidate_count"], "le", None, mesh_api.MAX_CANDIDATES, "count"), ("intersection_hit_count", report["intersection_hit_count"], "eq", 0, 0, "count"), ("pair_policy_complete", int(report["pair_policy_complete"]), "eq", 1, 1, "boolean")): + _put(intersection, intersection_thresholds, _gate(f"intersection.L{level}.{name}", 1, value, value, relation, lower, upper, unit)) + thresholds.extend(intersection_thresholds); thresholds.append({"threshold_id": "gate.boolean-pass", "relation": "eq", "lower": 1, "upper": 1, "unit": "dimensionless"}) + _need((len(structural), len(continuity), len(anatomy_rows), len(intersection), len(thresholds)) == (122, 144, 78, 12, 357), "gate inventory is not exact") + all_gates = (*structural, *continuity, *anatomy_rows, *intersection); _need(all(row["outcome"] == "pass" for row in all_gates), "a geometry gate failed") + return {"evaluation": evaluation, "reports": reports, "structural": structural, "continuity": continuity, "anatomy": anatomy_rows, "intersection": intersection, "thresholds": thresholds} + + +def _support_hash(indices) -> str: + values = tuple(indices); _need(values == tuple(sorted(set(values))) and all(type(index) is int and 0 <= index < 1737 for index in values), "invalid support indices") + return artifacts.sha256_bytes(b"CKSUPPORTv1\0\2" + struct.pack(" mesh_api.T); maximum = max(movement) + _need(predicted and actual == predicted and maximum >= float.fromhex("0x1.d14e3bcd35a85p-11") and all(movement[vertex] <= mesh_api.T for vertex in range(1737) if vertex not in predicted), f"support/movement gate failed for {parameter}") + _need(parameter not in ("left.thigh_start_x", "right.thigh_start_x") or len(predicted) == 436, "thigh-x support cardinality drift") + role = f"perturb-{parameter.replace('.', '-')}.ply"; payload = render.ply_bytes(observed); _need(payload != baseline_ply and len(payload) <= 2 * 1024 * 1024, "perturbation PLY gate failed"); payloads[role] = payload + records.append({"parameter_id": parameter, "prepared_component": component, "delta_m": delta, "support_level": 2, "predicted_support_count": len(predicted), "observed_support_count": len(actual), "predicted_support_sha256": _support_hash(predicted), "observed_support_sha256": _support_hash(actual), "maximum_movement_m": maximum, "artifact": None}) + _need(len(records) == 33 and set(payloads) == set(PERTURBATION_ROLES), "causality inventory is not exact") + return records, payloads + + +def _write(path: Path, data: bytes) -> dict[str, Any]: + artifacts.write_bytes_no_replace(path, data) + return artifacts.regular_file_record(path, path.name, max_bytes=16 * 1024 * 1024) + + +def _now() -> str: + return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def _same_admission(left, right) -> bool: + return artifacts.canonical_json_bytes(left) == artifacts.canonical_json_bytes(right) + + +def build_profile_seed(profile_id: str, output_path: str | os.PathLike[str]) -> Path: + """Build and atomically seal one exact 42-file profile/seed bundle.""" + seed = os.environ.get("PYTHONHASHSEED"); _need(seed in ("17", "29"), "profile build requires literal PYTHONHASHSEED=17 or 29") + output = Path(output_path); _need(output.is_absolute() and os.path.normpath(str(output)) == str(output) and not os.path.lexists(output) and output.parent.is_dir(), "output must be canonical, absolute, absent, and parented") + started, clock, stage, timings = _now(), time.perf_counter(), None, [] + try: + mark = time.perf_counter(); admission = static_admission(); timings.append({"phase": "identity", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); source, source_raw = profiles.load_json_with_bytes(ROOT / SOURCE_ROLE, "authored source"); table, table_raw = profiles.load_json_with_bytes(ROOT / PROFILE_ROLE, "profile table") + _need(artifacts.sha256_bytes(source_raw) == EXPECTED_SOURCE_SHA256 and artifacts.sha256_bytes(table_raw) == EXPECTED_PROFILE_SHA256, "source read drift") + projection = project_profile(profile_id, source, table); components = projection["carrier"]; timings.append({"phase": "selection-projection", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); surface.validate_catalogs(); timings.append({"phase": "catalogs", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); geometry = run_geometry(components); timings.append({"phase": "geometry-gates", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); causality, perturbations = run_causality(components, geometry); timings.append({"phase": "causality", "seconds": float(time.perf_counter() - mark)}) + mark = time.perf_counter(); stage = Path(tempfile.mkdtemp(prefix=f".{output.name}.stage-", dir=output.parent)); meshes = (geometry["evaluation"].cage, *geometry["evaluation"].levels); payload_records, level_records = [], [] + for role, mesh, counts in zip(SURFACE_ROLES, meshes, LEVEL_COUNTS): + ply = _write(stage / role, render.ply_bytes(mesh)); payload_records.append(ply); coordinate_raw = artifacts.coordinate_hash_bytes(mesh.vertices); triangle_raw = artifacts.triangle_index_hash_bytes(mesh.triangles) + level_records.append({"level": mesh.level, "counts": {"level": mesh.level, "vertices": counts[0], "edges": counts[1], "quads": counts[2], "triangles": counts[3], "boundary_edges": counts[4]}, "coordinate_bytes": len(coordinate_raw), "coordinate_sha256": artifacts.sha256_bytes(coordinate_raw), "triangle_index_bytes": len(triangle_raw), "triangle_index_sha256": artifacts.sha256_bytes(triangle_raw), "ply": ply}) + for index, role in enumerate(PERTURBATION_ROLES): + record = _write(stage / role, perturbations[role]); payload_records.append(record); causality[index]["artifact"] = record + direct, lineage, visibility = render.render_pair_bytes(meshes[-1]); direct_record, lineage_record = _write(stage / "direct.png", direct), _write(stage / "lineage.png", lineage); payload_records.extend((direct_record, lineage_record)) + payload_records = sorted(payload_records, key=lambda row: row["role_path"].encode()); _need(tuple(row["role_path"] for row in payload_records) == tuple(_ordered(PAYLOAD_ROLES)), "payload inventory drift") + config, visible = render.render_config_record(), render.visibility_record(visibility); render.validate_render_config(config) + evidence = {"schema": "owned-root-assembly-successor-profile-seed-evidence.v1", "outcome": "success", "activation_contract": admission["activation_contract"], "design_contract": admission["design_contract"], "source": admission["source"], "profile_table": admission["profile_table"], "existing_dependencies": list(admission["existing_dependencies"]), "additive_implementation_files": list(admission["additive_implementation_files"]), "runtime": admission["runtime"], "runtime_fingerprint_sha256": RUNTIME_SHA256, "profile_id": profile_id, "profile_index": projection["profile_index"], "selection": projection["selection"], "projected_values": projection["projected_values"], "projected_carrier": projection["projected_carrier"], "projection_bindings": projection["projection_bindings"], "levels": level_records, "thresholds": sorted(geometry["thresholds"], key=lambda row: row["threshold_id"].encode()), "gates": {name: sorted(geometry[name], key=lambda row: row["gate_id"].encode()) for name in ("structural", "continuity", "anatomy", "intersection")}, "causality": sorted(causality, key=lambda row: row["parameter_id"].encode()), "renders": {"renderer_id": "owned-root-raster-pillow-11.1.0.v1", "render_config": config, "render_config_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(config)), "visibility": visible, "visibility_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(visible)), "direct": direct_record, "lineage": lineage_record, "same_surface_positions_sha256": level_records[2]["coordinate_sha256"], "same_surface_triangles_sha256": level_records[2]["triangle_index_sha256"]}, "payloads": payload_records, "invariants": {name: True for name in ("topology_equal_to_neutral", "formulas_equal_to_neutral", "tunables_equal_to_neutral", "thresholds_equal_to_neutral", "gate_inventory_equal_to_neutral", "subdivision_equal_to_neutral", "ownership_equal_to_neutral", "causality_rules_equal_to_neutral", "renderer_equal_to_neutral")}} + _need(visible["triangle_index_sha256"] == level_records[2]["triangle_index_sha256"], "render does not bind the level-2 triangles") + evidence_raw = artifacts.canonical_json_bytes(evidence); _need(len(evidence_raw) <= 16 * 1024 * 1024, "profile evidence exceeds 16 MiB"); _write(stage / "profile-seed-evidence.json", evidence_raw); _write(stage / "profile-seed-evidence.sha256", f"{artifacts.sha256_bytes(evidence_raw)} profile-seed-evidence.json\n".encode("ascii")); timings.append({"phase": "serialization", "seconds": float(time.perf_counter() - mark)}) + _need(_same_admission(admission, static_admission()), "fixed identity changed during profile build") + timings.append({"phase": "total-before-seal", "seconds": float(time.perf_counter() - clock)}); _need(tuple(row["phase"] for row in timings) == PHASES, "timing phase order drift") + report = {"schema": "owned-root-assembly-successor-profile-seed-run-report.v1", "outcome": "success", "profile_id": profile_id, "profile_index": projection["profile_index"], "seed": int(seed), "literal_invocation": {"environment": [f"PYTHONHASHSEED={seed}"], "argv": [RUNNER_ROLE, "--profile", profile_id, "--output", str(output)]}, "output_path": str(output), "staging_path": str(stage), "python_executable_path": os.path.abspath(sys.executable), "started_utc": started, "finished_utc": _now(), "timings": timings, "runtime_fingerprint_sha256": RUNTIME_SHA256, "manifest_ref": {"role_path": "profile-seed-evidence.json", "bytes": len(evidence_raw), "sha256": artifacts.sha256_bytes(evidence_raw), "schema": evidence["schema"]}, "gates": [{"gate_id": gate, "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for gate in RUN_GATES]} + report_raw = artifacts.canonical_json_bytes(report); _need(len(report_raw) <= 2 * 1024 * 1024, "run report exceeds 2 MiB"); _write(stage / "run-report.json", report_raw); _write(stage / "run-report.sha256", f"{artifacts.sha256_bytes(report_raw)} run-report.json\n".encode("ascii")) + inventory = artifacts.closed_inventory(stage, BUNDLE_ROLES, max_file_bytes=16 * 1024 * 1024); _need(len(inventory) == 42 and sum(row["bytes"] for row in inventory) <= 512 * 1024 * 1024, "bundle closure/resource cap failed") + for row in inventory: + limit = 16 * 1024 * 1024 if row["role_path"] == "profile-seed-evidence.json" else 256 if row["role_path"].endswith(".sha256") else 2 * 1024 * 1024 + _need(row["bytes"] <= limit, f"bundle role exceeds cap: {row['role_path']}") + artifacts.publish_no_replace(stage, output, inventory, max_file_bytes=16 * 1024 * 1024); stage = None + return output + except Exception: + if stage is not None and stage.exists() and not stage.is_symlink(): + shutil.rmtree(stage) + raise + + +def validate_profile_seed_bundle(root_path: str | os.PathLike[str], profile_id: str, seed: int) -> dict[str, Any]: + """Re-admit one sealed 42-file bundle without rebuilding geometry.""" + _need(profile_id in PROFILE_IDS and seed in PROFILE_SEEDS, "invalid profile/seed admission") + root = Path(root_path); records = artifacts.closed_inventory(root, BUNDLE_ROLES, max_file_bytes=16 * 1024 * 1024) + _need(len(records) == 42, "bundle does not contain exactly 42 files"); by_role = {row["role_path"]: row for row in records} + def read_json(role, cap): + raw = artifacts.read_regular_file(root / role, max_bytes=cap); value = artifacts.decode_canonical_json(raw) + _need(type(value) is dict and artifacts.canonical_json_bytes(value) == raw, f"{role} is not canonical closed JSON") + return value, raw + evidence, evidence_raw = read_json("profile-seed-evidence.json", 16 * 1024 * 1024); report, report_raw = read_json("run-report.json", 2 * 1024 * 1024) + evidence_keys = {"schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", "existing_dependencies", "additive_implementation_files", "runtime", "runtime_fingerprint_sha256", "profile_id", "profile_index", "selection", "projected_values", "projected_carrier", "projection_bindings", "levels", "thresholds", "gates", "causality", "renders", "payloads", "invariants"} + _need(set(evidence) == evidence_keys and evidence["schema"] == "owned-root-assembly-successor-profile-seed-evidence.v1" and evidence["outcome"] == "success", "profile evidence schema mismatch") + index = PROFILE_IDS.index(profile_id); _need((evidence["profile_id"], evidence["profile_index"]) == (profile_id, index), "profile evidence selection mismatch") + identity = static_admission() + for field in ("activation_contract", "design_contract", "source", "profile_table", "runtime_fingerprint_sha256"): + _need(evidence[field] == identity[field], f"profile evidence {field} mismatch") + _need(evidence["existing_dependencies"] == list(identity["existing_dependencies"]) and evidence["additive_implementation_files"] == list(identity["additive_implementation_files"]) and evidence["runtime"] == identity["runtime"], "profile evidence implementation/runtime mismatch") + components = tuple(surface.GEOMETRY_COMPONENT_IDS); values, bindings = evidence["projected_values"], evidence["projection_bindings"] + _need(type(values) is list and type(bindings) is list and len(values) == len(bindings) == 92 and tuple(row.get("prepared_component") for row in values) == components and tuple(row.get("prepared_component") for row in bindings) == components, "projected value/binding closure mismatch") + carrier_raw = artifacts.canonical_json_bytes([row["value"] for row in values]); _need(evidence["projected_carrier"] == {"bytes": len(carrier_raw), "sha256": artifacts.sha256_bytes(carrier_raw)}, "projected carrier hash mismatch") + selected = project_profile(profile_id); _need(evidence["selection"] == selected["selection"], "selection hash mismatch") + _need(type(evidence["levels"]) is list and [row.get("level") for row in evidence["levels"]] == [0, 1, 2], "level evidence mismatch") + for level, row in enumerate(evidence["levels"]): + _need(row.get("counts") == {"level": level, "vertices": LEVEL_COUNTS[level][0], "edges": LEVEL_COUNTS[level][1], "quads": LEVEL_COUNTS[level][2], "triangles": LEVEL_COUNTS[level][3], "boundary_edges": LEVEL_COUNTS[level][4]} and row.get("ply") == by_role[SURFACE_ROLES[level]], "level record mismatch") + _need(type(evidence["thresholds"]) is list and len(evidence["thresholds"]) == 357 and evidence["thresholds"] == sorted(evidence["thresholds"], key=lambda row: row["threshold_id"].encode()), "threshold closure mismatch") + _need(set(evidence["gates"]) == {"structural", "continuity", "anatomy", "intersection"} and tuple(len(evidence["gates"][name]) for name in ("structural", "continuity", "anatomy", "intersection")) == (122, 144, 78, 12), "gate closure mismatch") + _need(all(row["outcome"] == "pass" for rows in evidence["gates"].values() for row in rows), "sealed evidence contains a failed gate") + _need(type(evidence["causality"]) is list and len(evidence["causality"]) == 33 and [row["parameter_id"] for row in evidence["causality"]] == _ordered(PARAMETER_IDS), "causality closure mismatch") + for row in evidence["causality"]: + _need(row["artifact"] == by_role[f"perturb-{row['parameter_id'].replace('.', '-')}.ply"], "causality artifact mismatch") + expected_payloads = [by_role[role] for role in _ordered(PAYLOAD_ROLES)]; _need(evidence["payloads"] == expected_payloads, "payload record closure mismatch") + renders = evidence["renders"]; config, visible = renders["render_config"], renders["visibility"]; render.validate_render_config(config) + _need(renders["render_config_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(config)) and renders["visibility_sha256"] == artifacts.sha256_bytes(artifacts.canonical_json_bytes(visible)) and renders["direct"] == by_role["direct.png"] and renders["lineage"] == by_role["lineage.png"], "render evidence mismatch") + _need(artifacts.read_regular_file(root / "profile-seed-evidence.sha256", max_bytes=256) == f"{artifacts.sha256_bytes(evidence_raw)} profile-seed-evidence.json\n".encode("ascii"), "evidence sidecar mismatch") + report_keys = {"schema", "outcome", "profile_id", "profile_index", "seed", "literal_invocation", "output_path", "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", "runtime_fingerprint_sha256", "manifest_ref", "gates"} + _need(set(report) == report_keys and report["schema"] == "owned-root-assembly-successor-profile-seed-run-report.v1" and report["outcome"] == "success" and (report["profile_id"], report["profile_index"], report["seed"]) == (profile_id, index, seed), "run report schema/selection mismatch") + _need([row["phase"] for row in report["timings"]] == list(PHASES) and [row["gate_id"] for row in report["gates"]] == list(RUN_GATES) and all(row["outcome"] == "pass" for row in report["gates"]), "run report timing/gate mismatch") + expected_ref = {"role_path": "profile-seed-evidence.json", "bytes": len(evidence_raw), "sha256": artifacts.sha256_bytes(evidence_raw), "schema": evidence["schema"]}; _need(report["manifest_ref"] == expected_ref, "run report evidence reference mismatch") + _need(artifacts.read_regular_file(root / "run-report.sha256", max_bytes=256) == f"{artifacts.sha256_bytes(report_raw)} run-report.json\n".encode("ascii"), "run report sidecar mismatch") + return evidence + + +def main(argv=None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + try: + if argv[:1] == ["--internal-managed-tests"] and len(argv) == 3 and argv[1] == "--receipt": + run_managed_tests(argv[2]); return 0 + if argv[:1] == ["--profile"] and len(argv) == 4 and argv[2] == "--output" and argv[1] in PROFILE_IDS: + build_profile_seed(argv[1], argv[3]); return 0 + raise ExactFiveError("private runner accepts only --internal-managed-tests --receipt ABS or --profile EXACT_ID --output ABS") + except Exception as exc: + print(f"exact_five_runner: error: {exc}", file=sys.stderr); return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py new file mode 100644 index 0000000..d8791cf --- /dev/null +++ b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py @@ -0,0 +1,761 @@ +"""Managed tests for the frozen exact-five activation boundary. + +The test module is intentionally a consumer of the public neutral package and +the public validation surfaces of the exact-five runner/publisher. It does +not import implementation helpers from either package. The runner is +expected to expose the small admission/projection/build validators named +below; those names are the integration seam for the additive package. +""" + +from __future__ import annotations + +import copy +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import contextmanager +from decimal import Decimal +from pathlib import Path + + +HERE = Path(__file__).resolve() +EXACT_PACKAGE = HERE.parents[1] +REPOSITORY = HERE.parents[3] +NEUTRAL_PACKAGE = REPOSITORY / "experiments/owned-root-assembly-successor" +PROFILE_PACKAGE = REPOSITORY / "experiments/current-form-surface-preview" + +sys.path.insert(0, str(EXACT_PACKAGE)) +sys.path.insert(0, str(NEUTRAL_PACKAGE)) +sys.path.insert(0, str(PROFILE_PACKAGE)) + +import artifact_serialization as artifacts # noqa: E402 +import exact_five_publisher as publisher # noqa: E402 +import exact_five_runner as runner # noqa: E402 +import generate_structural_profile_sources as profile_sources # noqa: E402 +import build_owned_root as neutral_builder # noqa: E402 +import compare_two_seed_outputs as neutral_comparator # noqa: E402 +import owned_root_surface as surface # noqa: E402 +import prepared_projection as neutral_projection # noqa: E402 +import render_export as render # noqa: E402 +from unittest.mock import patch # noqa: E402 + + +ACTIVATION_CONTRACT = NEUTRAL_PACKAGE / "exact-five-activation-contract.md" +ACTIVATION_SIDECAR = NEUTRAL_PACKAGE / "exact-five-activation-contract.sha256" +DESIGN_CONTRACT = NEUTRAL_PACKAGE / "design-contract.md" +SOURCE = REPOSITORY / "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_TABLE = PROFILE_PACKAGE / "structural_profile_candidates.json" +PINNED_LAUNCHER = PROFILE_PACKAGE / "surface_preview_launcher.sh" +RUNNER_SCRIPT = EXACT_PACKAGE / "exact_five_runner.py" + +ACTIVATION_ROLE = "experiments/owned-root-assembly-successor/exact-five-activation-contract.md" +DESIGN_ROLE = "experiments/owned-root-assembly-successor/design-contract.md" +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" + +ACTIVATION_SHA256 = "a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49" +DESIGN_SHA256 = "3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490" +SOURCE_SHA256 = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +PROFILE_SHA256 = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +BASELINE_REPORT_SHA256 = "fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a" +BASELINE_MANIFEST_SHA256 = "1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa" + +PROFILE_IDS = ( + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", +) +SEEDS = (17, 29) + +SELECTORS = ( + ("left.r_y", "hips.left.r_y"), + ("right.r_y", "hips.right.r_y"), + ("lower_pelvis.L_y", "stations.lower_pelvis.C.y"), + ("lower_pelvis.C_z", "stations.lower_pelvis.C.z"), + ("left.r_x", "hips.left.r_x"), + ("right.r_x", "hips.right.r_x"), + ("lower_pelvis.R_x", "stations.lower_pelvis.rL"), + ("left.r_z", "hips.left.r_z"), + ("right.r_z", "hips.right.r_z"), + ("lower_pelvis.R_f", "stations.lower_pelvis.rA"), + ("lower_pelvis.R_b", "stations.lower_pelvis.rP"), + ("left.thigh_start_x", "hips.left.P_s.x"), + ("left.thigh_start_y", "hips.left.P_s.y"), + ("left.thigh_start_z", "hips.left.P_s.z"), + ("right.thigh_start_x", "hips.right.P_s.x"), + ("right.thigh_start_y", "hips.right.P_s.y"), + ("right.thigh_start_z", "hips.right.P_s.z"), + ("neck_collar.C_y", "stations.neck_collar.C.y"), + ("neck_collar.rL", "stations.neck_collar.rL"), + ("neck_upper.C_y", "stations.neck_upper.C.y"), + ("neck_upper.rL", "stations.neck_upper.rL"), + ("left.axilla_x", "shoulders.left.axilla.x"), + ("left.axilla_y", "shoulders.left.axilla.y"), + ("right.axilla_x", "shoulders.right.axilla.x"), + ("right.axilla_y", "shoulders.right.axilla.y"), + ("left.peak_y", "shoulders.left.peak.y"), + ("right.peak_y", "shoulders.right.peak.y"), + ("left.start_lateral", "shoulders.left.start_lateral"), + ("right.start_lateral", "shoulders.right.start_lateral"), + ("left.start_up", "shoulders.left.start_up"), + ("right.start_up", "shoulders.right.start_up"), + ("left.shoulder_depth", "shoulders.left.shoulder_depth"), + ("right.shoulder_depth", "shoulders.right.shoulder_depth"), +) + +SURFACE_ROLES = ("surface-level-0.ply", "surface-level-1.ply", "surface-level-2.ply") +PERTURBATION_ROLES = tuple(f"perturb-{parameter.replace('.', '-')}.ply" for parameter, _ in SELECTORS) +PAYLOAD_ROLES = tuple(sorted((*SURFACE_ROLES, *PERTURBATION_ROLES, "direct.png", "lineage.png"), key=lambda value: value.encode("utf-8"))) +BUNDLE_ROLES = tuple(sorted((*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256", "run-report.json", "run-report.sha256"), key=lambda value: value.encode("utf-8"))) +PUBLIC_ROLES = tuple( + f"{profile}/{role}" + for profile in PROFILE_IDS + for role in ("surface-level-2.ply", "direct.png", "lineage.png") +) + ("exact-five-evidence.json", "exact-five-evidence.sha256", "run-report.json", "run-report.sha256") +PUBLIC_ROLES = tuple(sorted(PUBLIC_ROLES, key=lambda value: value.encode("utf-8"))) + +REQUIRED_TEST_IDS = tuple(sorted( + ( + f"test_exact_five_activation.ExactFiveActivationTests.{name}" + for name in ( + "test_all_33_selectors_copy_one_component", + "test_atomic_failure_has_no_partial_publication", + "test_decimal_half_even_boundaries", + "test_final_evidence_schema_and_19_file_closure", + "test_geometry_receives_only_components", + "test_neutral_projection_preserves_38_payloads", + "test_profile_seed_bundle_schema_and_closure", + "test_profile_table_closed_and_exact_order", + "test_profile_table_rejects_duplicate_keys_and_signatures", + "test_projection_has_exact_92_bindings", + "test_seed_dispatch_is_exact", + "test_static_identity_and_allowlist", + ) + ), + key=lambda value: value.encode("utf-8"), +)) + +FINAL_GATE_IDS = ( + "exact-five.run.01.identity", + "exact-five.run.02.managed-tests", + "exact-five.run.03.publisher-baseline-admission", + "exact-five.run.04.profile.standard_neutral_reference.seed-17", + "exact-five.run.05.profile.standard_neutral_reference.seed-29", + "exact-five.run.06.profile.compact_broad_short_limb_large_head.seed-17", + "exact-five.run.07.profile.compact_broad_short_limb_large_head.seed-29", + "exact-five.run.08.profile.tall_narrow_long_legged.seed-17", + "exact-five.run.09.profile.tall_narrow_long_legged.seed-29", + "exact-five.run.10.profile.slender_long_limb.seed-17", + "exact-five.run.11.profile.slender_long_limb.seed-29", + "exact-five.run.12.profile.stocky_broad_chested.seed-17", + "exact-five.run.13.profile.stocky_broad_chested.seed-29", + "exact-five.run.14.profile.standard_neutral_reference.cross-seed", + "exact-five.run.15.profile.compact_broad_short_limb_large_head.cross-seed", + "exact-five.run.16.profile.tall_narrow_long_legged.cross-seed", + "exact-five.run.17.profile.slender_long_limb.cross-seed", + "exact-five.run.18.profile.stocky_broad_chested.cross-seed", + "exact-five.run.19.standard-neutral-payload-equality", + "exact-five.run.20.evidence-graph", + "exact-five.run.21.pre-report-closure", +) + +EXPECTED_DEPENDENCY_ROLES = tuple(sorted(( + "experiments/owned-root-assembly-successor/anatomy_gates.py", + "experiments/owned-root-assembly-successor/artifact_serialization.py", + "experiments/owned-root-assembly-successor/build_owned_root.py", + "experiments/owned-root-assembly-successor/chart_lineage.py", + "experiments/owned-root-assembly-successor/mesh_correctness.py", + "experiments/owned-root-assembly-successor/owned_root_surface.py", + "experiments/owned-root-assembly-successor/prepared_projection.py", + "experiments/owned-root-assembly-successor/render_export.py", + "experiments/current-form-surface-preview/generate_structural_profile_sources.py", + "experiments/current-form-surface-preview/structural_atomic_publish.py", + "experiments/current-form-surface-preview/surface_preview_launcher.sh", + "experiments/current-form-surface-preview/requirements.txt", +), key=lambda value: value.encode("utf-8"))) + + +def _record(path: Path, role: str, *, max_bytes: int | None = None) -> dict[str, object]: + return artifacts.regular_file_record(path, role, max_bytes=max_bytes) + + +def _json(path: Path, *, max_bytes: int | None = None) -> tuple[dict[str, object], bytes]: + raw = artifacts.read_regular_file(path, max_bytes=max_bytes) + value = artifacts.decode_canonical_json(raw) + if not isinstance(value, dict): + raise AssertionError(f"{path} is not a JSON object") + if raw[:3] == b"\xef\xbb\xbf" or raw[-1:] == b"\n" or raw != artifacts.canonical_json_bytes(value): + raise AssertionError(f"{path} is not canonical JSON") + return value, raw + + +def _sidecar(payload: bytes, sidecar: bytes, role: str) -> None: + expected = f"{hashlib.sha256(payload).hexdigest()} {role}\n".encode("ascii") + if sidecar != expected: + raise AssertionError(f"{role} sidecar is not its exact hash line") + + +class ExactFiveActivationTests(unittest.TestCase): + """The exact managed-test inventory named by section 7.0.""" + + @classmethod + def _run_pinned(cls, arguments: list[str], seed: int) -> subprocess.CompletedProcess[str]: + environment = os.environ.copy() + environment["PYTHONHASHSEED"] = str(seed) + return subprocess.run( + [str(PINNED_LAUNCHER), *arguments], + cwd=REPOSITORY, + env=environment, + text=True, + capture_output=True, + check=False, + timeout=300, + ) + + @classmethod + def _baseline(cls) -> Path: + cached = getattr(cls, "_baseline_path", None) + if cached is not None: + return cached + configured = os.environ.get("CK_EXACT_FIVE_BASELINE_ROOT") + if not configured: + raise AssertionError("set CK_EXACT_FIVE_BASELINE_ROOT to the admitted retained baseline root") + output = Path(configured) + if not output.is_absolute() or os.path.normpath(str(output)) != str(output) or output.is_symlink() or not output.is_dir() or output.resolve() != output: + raise AssertionError("CK_EXACT_FIVE_BASELINE_ROOT must be a canonical, regular absolute directory") + report = output / "comparison" / "comparison-report.json" + if hashlib.sha256(report.read_bytes()).hexdigest() != BASELINE_REPORT_SHA256: + raise AssertionError("configured baseline is not the admitted post-seam report") + manifest = output / "seed-17" / "stable-manifest.json" + if hashlib.sha256(manifest.read_bytes()).hexdigest() != BASELINE_MANIFEST_SHA256: + raise AssertionError("configured baseline is not the admitted stable manifest") + cls._baseline_path = output + return output + + @classmethod + def _bundle(cls, profile_id: str = PROFILE_IDS[0], seed: int = SEEDS[0]) -> Path: + cached = getattr(cls, "_bundles", None) + if cached is not None: + return cached[(profile_id, seed)] + holder = tempfile.TemporaryDirectory(prefix="ck-exact-five-bundle-", dir="/tmp") + cls.addClassCleanup(holder.cleanup) + bundles = {} + for profile in PROFILE_IDS: + profile_root = Path(holder.name) / profile + profile_root.mkdir() + for requested_seed in SEEDS: + output = profile_root / f"seed-{requested_seed}" + result = cls._run_pinned([str(RUNNER_SCRIPT), "--profile", profile, "--output", str(output)], requested_seed) + if result.returncode != 0: + raise AssertionError(f"exact-five profile build failed: {result.stderr[-4000:]}") + bundles[(profile, requested_seed)] = output + cls._bundles = bundles + return bundles[(profile_id, seed)] + + @classmethod + def _all_bundles(cls) -> tuple[Path, ...]: + cls._bundle() + return tuple(cls._bundles[(profile, seed)] for profile in PROFILE_IDS for seed in SEEDS) + + @classmethod + def _receipt(cls, path: Path) -> Path: + identity = runner.static_admission() + value = { + "schema": "owned-root-assembly-successor-exact-five-managed-test-receipt.v1", + "outcome": "success", + "invocation": { + "environment": ["PYTHONHASHSEED=0"], + "implementation_role": "experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py", + "mode": "managed-tests", + }, + "activation_contract": identity["activation_contract"], + "design_contract": identity["design_contract"], + "existing_dependencies": list(identity["existing_dependencies"]), + "additive_implementation_files": list(identity["additive_implementation_files"]), + "runtime": identity["runtime"], + "runtime_fingerprint_sha256": identity["runtime_fingerprint_sha256"], + "executed_test_ids": list(REQUIRED_TEST_IDS), + "required_test_ids": list(REQUIRED_TEST_IDS), + "results": { + "tests_run": len(REQUIRED_TEST_IDS), "failures": 0, "errors": 0, + "skipped": 0, "expected_failures": 0, "unexpected_successes": 0, + }, + } + artifacts.write_canonical_json_no_replace(path, value) + return path + + @classmethod + def _context(cls, path: Path, baseline: Path, output: Path) -> Path: + value = { + "schema": "owned-root-assembly-successor-exact-five-launcher-context.v1", + "literal_invocation": { + "environment": ["PYTHONHASHSEED=0"], + "argv": [ + "experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh", + "--baseline-root", str(baseline), "--output", str(output), + ], + }, + "output_path": str(output), + "neutral_baseline_path": str(baseline), + "timings": [{"phase": phase, "seconds": 0.125} for phase in ( + "identity", "managed-tests", "launcher-baseline-admission", "profile-seed-builds" + )], + } + artifacts.write_canonical_json_no_replace(path, value) + return path + + @classmethod + def _publication(cls, baseline: Path | None = None) -> tuple[Path, Path]: + cached = getattr(cls, "_publication_fixture", None) + if cached is not None and baseline is None: + return cached + holder = tempfile.TemporaryDirectory(prefix="ck-exact-five-publication-", dir="/tmp") + cls.addClassCleanup(holder.cleanup) + baseline = baseline or cls._baseline() + root = Path(holder.name) + output = root / "final-output" + receipt = cls._receipt(root / "managed-test-receipt.json") + context = cls._context(root / "launcher-context.json", baseline, output) + staging = root / "publication-staging" + result = publisher.publish(baseline, cls._all_bundles(), receipt, context, staging) + if Path(result) != staging: + raise AssertionError("publisher did not return its sealed staging root") + if baseline == cls._baseline(): + cls._publication_fixture = (staging, root) + return staging, root + + @staticmethod + def _admit_table(raw: bytes) -> dict[str, object]: + value = runner.admit_profile_table(raw) + if not isinstance(value, dict): + raise AssertionError("profile admission did not return a table object") + return value + + @staticmethod + def _projection(profile_id: str) -> dict[str, object]: + source, _ = profile_sources.load_json_with_bytes(SOURCE, "authored source") + table, _ = profile_sources.load_json_with_bytes(PROFILE_TABLE, "profile table") + value = runner.project_profile(profile_id, source, table) + if not isinstance(value, dict): + raise AssertionError("profile projection did not return an evidence object") + return value + + @staticmethod + @contextmanager + def _patched_path_bound_baseline_apis(): + with patch.object( + neutral_builder, + "validate_seed_bundle", + side_effect=AssertionError("relocated admission used the path-bound neutral validator"), + ), patch.object( + neutral_comparator, + "outer_publication_inventory", + side_effect=AssertionError("relocated admission used the path-bound neutral comparator"), + ): + yield + + def test_all_33_selectors_copy_one_component(self): + self.assertEqual(len(SELECTORS), 33) + self.assertEqual(tuple(runner.PARAMETER_IDS), tuple(parameter for parameter, _ in SELECTORS)) + self.assertEqual(dict(neutral_projection.MUST_AFFECT_COMPONENTS), dict(SELECTORS)) + self.assertEqual(tuple(neutral_projection.MUST_AFFECT_PARAMETER_IDS), tuple(parameter for parameter, _ in SELECTORS)) + prepared = neutral_projection.prepare_standard_neutral(SOURCE) + baseline = neutral_projection.project_geometry(prepared) + self.assertEqual(len(baseline.values), 92) + delta = float.fromhex("0x1.47ae147ae147bp-7") + for parameter, component in SELECTORS: + with self.subTest(parameter=parameter): + perturbed = neutral_projection.project_perturbed_geometry(prepared, parameter) + changed = [index for index, (left, right) in enumerate(zip(baseline.values, perturbed.values)) if left != right] + self.assertEqual(len(changed), 1) + self.assertEqual(surface.GEOMETRY_COMPONENT_IDS[changed[0]], component) + self.assertEqual(perturbed.values[changed[0]], baseline.values[changed[0]] + delta) + self.assertEqual(tuple(runner.PERTURBATION_ROLES), PERTURBATION_ROLES) + self.assertEqual(len(runner.PERTURBATION_ROLES), 33) + self.assertEqual(5 * 2 * len(runner.PERTURBATION_ROLES), 330) + + def test_atomic_failure_has_no_partial_publication(self): + with tempfile.TemporaryDirectory(prefix="ck-exact-five-failure-", dir="/tmp") as directory: + root = Path(directory) + output = root / "absent-output" + wrong_seed = self._run_pinned([str(RUNNER_SCRIPT), "--profile", PROFILE_IDS[0], "--output", str(output)], 19) + self.assertNotEqual(wrong_seed.returncode, 0) + self.assertFalse(output.exists() or output.is_symlink()) + + stage = root / "stage" + stage.mkdir() + payload = stage / "payload.bin" + payload.write_bytes(b"admitted") + inventory = artifacts.closed_inventory(stage, ("payload.bin",), max_file_bytes=64) + payload.write_bytes(b"drifted") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.publish_no_replace(stage, output, inventory, max_file_bytes=64) + self.assertFalse(output.exists() or output.is_symlink()) + + invalid_baseline = root / "missing-baseline" + public_output = root / "public-output" + environment = os.environ.copy() + environment["PYTHONHASHSEED"] = "0" + result = subprocess.run( + [str(EXACT_PACKAGE / "exact_five_launcher.sh"), "--baseline-root", str(invalid_baseline), "--output", str(public_output)], + cwd=REPOSITORY, env=environment, text=True, capture_output=True, check=False, timeout=300, + ) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(public_output.exists() or public_output.is_symlink()) + + def test_decimal_half_even_boundaries(self): + source_bytes = SOURCE.read_bytes() + marker = b'"role": "form_head_neck_profile_cranium_crown_forward_radius", "value": 0.65' + self.assertEqual(source_bytes.count(marker), 1) + expected = {"below": 812, "tie": 812, "above": 813} + for label, token in (("below", "0.6499999999999999999"), ("tie", "0.65"), ("above", "0.6500000000000000001")): + with self.subTest(label=label): + projected, number = runner.project_decimal_metres(Decimal(token), 1250) + self.assertEqual(projected, Decimal(expected[label]) / 1000) + self.assertEqual(Decimal(str(number)), projected) + + def test_final_evidence_schema_and_19_file_closure(self): + self.assertEqual(tuple(runner.PROFILE_IDS), PROFILE_IDS) + self.assertEqual(tuple(publisher.SEEDS), SEEDS) + self.assertEqual(tuple(publisher.PUBLIC_ROLES), PUBLIC_ROLES) + self.assertEqual(len(PUBLIC_ROLES), 19) + + baseline = self._baseline() + with tempfile.TemporaryDirectory(prefix="ck-exact-five-relocated-", dir="/tmp") as directory: + relocated = Path(directory) / "relocated-baseline" + shutil.copytree(baseline, relocated) + self.assertTrue(relocated.is_absolute()) + self.assertNotEqual(relocated, baseline) + self.assertNotEqual(relocated.resolve(), baseline.resolve()) + with self._patched_path_bound_baseline_apis(): + staging, publication_root = self._publication(relocated) + records = artifacts.closed_inventory(staging, PUBLIC_ROLES, max_file_bytes=16 * 1024 * 1024) + self.assertEqual(len(records), 19) + by_role = {record["role_path"]: record for record in records} + evidence, evidence_raw = _json(staging / "exact-five-evidence.json", max_bytes=16 * 1024 * 1024) + report, report_raw = _json(staging / "run-report.json", max_bytes=2 * 1024 * 1024) + self.assertEqual(set(evidence), { + "schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", + "existing_dependencies", "additive_implementation_files", "managed_tests", "neutral_baseline", + "runtime", "runtime_fingerprint_sha256", "profile_order", "profiles", "payloads", + }) + self.assertEqual((evidence["schema"], evidence["outcome"], evidence["profile_order"]), ( + "owned-root-assembly-successor-exact-five-evidence.v1", "success", list(PROFILE_IDS) + )) + self.assertEqual(len(evidence["payloads"]), 15) + self.assertEqual(evidence["payloads"], [by_role[role] for role in PUBLIC_ROLES if "/" in role]) + receipt, receipt_raw = _json(publication_root / "managed-test-receipt.json", max_bytes=16 * 1024 * 1024) + self.assertEqual(evidence["managed_tests"], { + "receipt_sha256": artifacts.sha256_bytes(receipt_raw), "receipt": receipt, + }) + neutral = evidence["neutral_baseline"] + self.assertEqual(len(neutral["payload_comparisons"]), 38) + self.assertEqual( + neutral["payload_comparisons"], + [{"role_path": role, **{key: value for key, value in artifacts.regular_file_record(baseline / f"seed-17/{role}", role).items() if key != "role_path"}} for role in PAYLOAD_ROLES], + ) + self.assertEqual(len(evidence["profiles"]), 5) + for index, (profile_id, profile) in enumerate(zip(PROFILE_IDS, evidence["profiles"])): + with self.subTest(profile=profile_id): + self.assertEqual(set(profile), {"profile_id", "profile_index", "evidence", "stable_cross_seed_comparisons", "neutral_payload_comparisons"}) + self.assertEqual((profile["profile_id"], profile["profile_index"]), (profile_id, index)) + self.assertEqual(len(profile["stable_cross_seed_comparisons"]), 40) + self.assertEqual([row["role_path"] for row in profile["stable_cross_seed_comparisons"]], list(BUNDLE_ROLES[:-2])) + self.assertEqual(len(profile["neutral_payload_comparisons"]), 38 if index == 0 else 0) + self.assertNotIn(b"run-report.json", artifacts.canonical_json_bytes(profile["evidence"])) + self.assertEqual(set(report), { + "schema", "outcome", "literal_invocation", "output_path", "staging_path", "python_executable_path", + "neutral_baseline_path", "started_utc", "finished_utc", "timings", "activation_contract_sha256", + "design_contract_sha256", "runtime_fingerprint_sha256", "evidence", "evidence_sidecar", "payloads", + "profile_seed_runs", "gates", + }) + self.assertEqual(report["schema"], "owned-root-assembly-successor-exact-five-run-report.v1") + self.assertEqual(report["neutral_baseline_path"], str(relocated)) + self.assertEqual([row["phase"] for row in report["timings"]], [ + "identity", "managed-tests", "launcher-baseline-admission", "profile-seed-builds", + "publisher-baseline-admission", "comparison", "pre-report-closure", "total-before-seal", + ]) + self.assertEqual(report["payloads"], [by_role[role] for role in PUBLIC_ROLES if "/" in role]) + self.assertEqual([(row["profile_id"], row["seed"]) for row in report["profile_seed_runs"]], [ + (profile, seed) for profile in PROFILE_IDS for seed in SEEDS + ]) + self.assertEqual([row["gate_id"] for row in report["gates"]], list(FINAL_GATE_IDS)) + self.assertTrue(all(row == {"gate_id": row["gate_id"], "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for row in report["gates"])) + self.assertEqual(report["evidence"], { + "role_path": "exact-five-evidence.json", "bytes": len(evidence_raw), + "sha256": artifacts.sha256_bytes(evidence_raw), "schema": evidence["schema"], + }) + self.assertEqual(report["evidence_sidecar"], by_role["exact-five-evidence.sha256"]) + _sidecar(evidence_raw, (staging / "exact-five-evidence.sha256").read_bytes(), "exact-five-evidence.json") + _sidecar(report_raw, (staging / "run-report.sha256").read_bytes(), "run-report.json") + + malformed_missing = Path(directory) / "malformed-missing" + shutil.copytree(staging, malformed_missing) + (malformed_missing / "run-report.sha256").unlink() + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(malformed_missing, PUBLIC_ROLES, max_file_bytes=16 * 1024 * 1024) + malformed_extra = Path(directory) / "malformed-extra" + shutil.copytree(staging, malformed_extra) + (malformed_extra / "unexpected").write_bytes(b"x") + with self.assertRaises(artifacts.ArtifactSerializationError): + artifacts.closed_inventory(malformed_extra, PUBLIC_ROLES, max_file_bytes=16 * 1024 * 1024) + + drifted_payload = relocated / "seed-17" / "surface-level-2.ply" + original_payload = drifted_payload.read_bytes() + drifted_payload.write_bytes(original_payload + b"\n") + self.assertEqual(drifted_payload.read_bytes(), original_payload + b"\n") + output = Path(directory) / "drift-output" + receipt = self._receipt(Path(directory) / "drift-receipt.json") + context = self._context(Path(directory) / "drift-context.json", relocated, output) + drift_stage = Path(directory) / "drift-stage" + with self._patched_path_bound_baseline_apis(), self.assertRaises(ValueError): + publisher.publish(relocated, self._all_bundles(), receipt, context, drift_stage) + self.assertFalse(output.exists() or output.is_symlink() or drift_stage.exists() or drift_stage.is_symlink()) + + def test_geometry_receives_only_components(self): + prepared = neutral_projection.prepare_standard_neutral(SOURCE) + geometry = neutral_projection.project_geometry(prepared) + self.assertIs(type(geometry), surface.GeometryComponents) + self.assertEqual(tuple(surface.GeometryComponents.__slots__), ("values",)) + self.assertEqual(len(geometry.values), 92) + self.assertTrue(all(type(value) is float for value in geometry.values)) + self.assertFalse(hasattr(geometry, "profile_id")) + self.assertFalse(hasattr(geometry, "source")) + self.assertFalse(hasattr(geometry, "provenance")) + surface.validate_geometry_components(geometry) + for forbidden in (prepared, {"profile_id": PROFILE_IDS[1]}, PROFILE_IDS[1], geometry.values): + with self.subTest(forbidden=type(forbidden).__name__), self.assertRaises(ValueError): + surface.evaluate(forbidden) + with self.subTest(runner_input=type(forbidden).__name__), self.assertRaises(ValueError): + runner.run_geometry(forbidden) + with self.assertRaises(ValueError): + surface.validate_geometry_components({"values": geometry.values}) + + def test_neutral_projection_preserves_38_payloads(self): + baseline_root = self._baseline() + prepared = neutral_projection.prepare_standard_neutral(SOURCE) + geometry = neutral_projection.project_geometry(prepared) + evaluation = surface.evaluate(geometry) + actual: dict[str, bytes] = {} + for mesh in (evaluation.cage, *evaluation.levels): + actual[f"surface-level-{mesh.level}.ply"] = render.ply_bytes(mesh) + for parameter, _ in SELECTORS: + mesh = surface.evaluate(neutral_projection.project_perturbed_geometry(prepared, parameter)).levels[1] + actual[f"perturb-{parameter.replace('.', '-')}.ply"] = render.ply_bytes(mesh) + direct, lineage, visibility = render.render_pair_bytes(evaluation.levels[1]) + actual["direct.png"], actual["lineage.png"] = direct, lineage + self.assertEqual(len(actual), 38) + for seed in SEEDS: + seed_root = baseline_root / f"seed-{seed}" + with self.subTest(seed=seed): + for role, payload in actual.items(): + self.assertEqual(payload, (seed_root / role).read_bytes(), role) + self.assertEqual( + artifacts.sha256_bytes(artifacts.canonical_json_bytes(list(geometry.values))), + self._projection(PROFILE_IDS[0])["projected_carrier"]["sha256"], + ) + self.assertEqual(visibility.triangle_index_sha256, artifacts.sha256_bytes(artifacts.triangle_index_hash_bytes(evaluation.levels[1].triangles))) + + def test_profile_seed_bundle_schema_and_closure(self): + bundle = self._bundle() + records = artifacts.closed_inventory(bundle, BUNDLE_ROLES, max_file_bytes=2 * 1024 * 1024) + self.assertEqual(len(records), 42) + self.assertEqual(tuple(record["role_path"] for record in records), tuple(sorted(BUNDLE_ROLES))) + evidence, evidence_raw = _json(bundle / "profile-seed-evidence.json", max_bytes=16 * 1024 * 1024) + report, report_raw = _json(bundle / "run-report.json", max_bytes=2 * 1024 * 1024) + self.assertEqual(set(evidence), { + "schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", + "existing_dependencies", "additive_implementation_files", "runtime", "runtime_fingerprint_sha256", + "profile_id", "profile_index", "selection", "projected_values", "projected_carrier", + "projection_bindings", "levels", "thresholds", "gates", "causality", "renders", "payloads", "invariants", + }) + self.assertEqual(evidence["schema"], "owned-root-assembly-successor-profile-seed-evidence.v1") + self.assertEqual(evidence["outcome"], "success") + self.assertEqual((evidence["profile_id"], evidence["profile_index"]), (PROFILE_IDS[0], 0)) + self.assertEqual(len(evidence["projected_values"]), 92) + self.assertEqual(len(evidence["projection_bindings"]), 92) + self.assertEqual([row["prepared_component"] for row in evidence["projected_values"]], sorted(row["prepared_component"] for row in evidence["projected_values"])) + self.assertEqual([row["prepared_component"] for row in evidence["projection_bindings"]], sorted(row["prepared_component"] for row in evidence["projection_bindings"])) + self.assertEqual(len(evidence["levels"]), 3) + self.assertEqual([row["level"] for row in evidence["levels"]], [0, 1, 2]) + self.assertEqual(len(evidence["thresholds"]), 357) + self.assertEqual(tuple(len(evidence["gates"][name]) for name in ("structural", "continuity", "anatomy", "intersection")), (122, 144, 78, 12)) + self.assertEqual(len(evidence["causality"]), 33) + self.assertEqual([row["parameter_id"] for row in evidence["causality"]], sorted((parameter for parameter, _ in SELECTORS), key=lambda value: value.encode("utf-8"))) + self.assertEqual({row["parameter_id"]: row["prepared_component"] for row in evidence["causality"]}, dict(SELECTORS)) + self.assertTrue(all(row["delta_m"] == 0.01 and row["support_level"] == 2 and row["predicted_support_count"] == row["observed_support_count"] and row["predicted_support_sha256"] == row["observed_support_sha256"] for row in evidence["causality"])) + self.assertEqual(len(evidence["payloads"]), 38) + self.assertEqual(set(evidence["invariants"]), { + "topology_equal_to_neutral", "formulas_equal_to_neutral", "tunables_equal_to_neutral", + "thresholds_equal_to_neutral", "gate_inventory_equal_to_neutral", "subdivision_equal_to_neutral", + "ownership_equal_to_neutral", "causality_rules_equal_to_neutral", "renderer_equal_to_neutral", + }) + self.assertNotIn("run-report.json", evidence_raw.decode("utf-8")) + self.assertEqual(set(report), { + "schema", "outcome", "profile_id", "profile_index", "seed", "literal_invocation", "output_path", + "staging_path", "python_executable_path", "started_utc", "finished_utc", "timings", + "runtime_fingerprint_sha256", "manifest_ref", "gates", + }) + self.assertEqual(report["schema"], "owned-root-assembly-successor-profile-seed-run-report.v1") + self.assertEqual(report["seed"], SEEDS[0]) + self.assertEqual([row["phase"] for row in report["timings"]], ["identity", "selection-projection", "catalogs", "geometry-gates", "causality", "serialization", "total-before-seal"]) + self.assertEqual([row["gate_id"] for row in report["gates"]], list(runner.RUN_GATES)) + self.assertTrue(all(row == {"gate_id": row["gate_id"], "outcome": "pass", "sample_count": 1, "observed_min": 1, "observed_max": 1, "threshold_id": "gate.boolean-pass"} for row in report["gates"])) + self.assertEqual(report["manifest_ref"], { + "role_path": "profile-seed-evidence.json", "bytes": len(evidence_raw), + "sha256": artifacts.sha256_bytes(evidence_raw), "schema": evidence["schema"], + }) + self.assertEqual(report_raw[-1:], b"}") + _sidecar(evidence_raw, (bundle / "profile-seed-evidence.sha256").read_bytes(), "profile-seed-evidence.json") + _sidecar(report_raw, (bundle / "run-report.sha256").read_bytes(), "run-report.json") + self.assertEqual(tuple(runner.BUNDLE_ROLES), BUNDLE_ROLES) + self.assertEqual(tuple(runner.STABLE_ROLES), tuple(sorted((*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256")))) + for profile_id in PROFILE_IDS: + for seed in SEEDS: + with self.subTest(profile=profile_id, seed=seed): + validated = runner.validate_profile_seed_bundle(self._bundle(profile_id, seed), profile_id, seed) + self.assertEqual(validated["profile_id"], profile_id) + + def test_profile_table_closed_and_exact_order(self): + table = self._admit_table(PROFILE_TABLE.read_bytes()) + source, _ = profile_sources.load_json_with_bytes(SOURCE, "authored source") + self.assertEqual(set(table), {"base_source", "canonicalization", "format", "profiles", "transform"}) + rows = table["profiles"] + self.assertEqual([row["id"] for row in rows], list(PROFILE_IDS)) + self.assertEqual(len({row["id"] for row in rows}), 5) + self.assertEqual(len({row["label"] for row in rows}), 5) + self.assertTrue(all(set(row) == {"dimension_scales", "id", "label", "part_placements"} for row in rows)) + self.assertTrue(all(len(row["dimension_scales"]) == 37 for row in rows)) + self.assertTrue(all(len(row["part_placements"]) == 18 for row in rows)) + self.assertEqual(tuple(profile_sources.ACTIVE_PROFILE_IDS), PROFILE_IDS) + self.assertEqual(tuple(runner.PROFILE_IDS), PROFILE_IDS) + for bad in ("unknown", 2, PROFILE_IDS[0] + "\x00"): + with self.subTest(bad=bad), self.assertRaises(ValueError): + runner.project_profile(bad, source, table) + projected = runner.project_profile(PROFILE_IDS[2], source, table) + self.assertEqual(projected["profile_id"], PROFILE_IDS[2]) + self.assertEqual(projected["profile_index"], 2) + + def test_profile_table_rejects_duplicate_keys_and_signatures(self): + raw = PROFILE_TABLE.read_bytes() + duplicate = raw[:-1] + b',"profiles":[]}' + with self.assertRaises(ValueError): + self._admit_table(duplicate) + + table = self._admit_table(raw) + forged = copy.deepcopy(table) + forged["profiles"][1]["dimension_scales"] = copy.deepcopy(forged["profiles"][0]["dimension_scales"]) + forged["profiles"][1]["part_placements"] = copy.deepcopy(forged["profiles"][0]["part_placements"]) + source, _ = profile_sources.load_json_with_bytes(SOURCE, "authored source") + with self.assertRaises(ValueError): + runner.project_profile(PROFILE_IDS[0], source, forged) + + extra = copy.deepcopy(table) + extra["profiles"][0]["forged"] = 1 + with self.assertRaises(ValueError): + runner.project_profile(PROFILE_IDS[0], source, extra) + reordered = copy.deepcopy(table) + reordered["profiles"][0], reordered["profiles"][1] = reordered["profiles"][1], reordered["profiles"][0] + with self.assertRaises(ValueError): + runner.project_profile(PROFILE_IDS[0], source, reordered) + + def test_projection_has_exact_92_bindings(self): + table = self._admit_table(PROFILE_TABLE.read_bytes()) + projection = self._projection(PROFILE_IDS[1]) + values = projection["projected_values"] + bindings = projection["projection_bindings"] + components = tuple(surface.GEOMETRY_COMPONENT_IDS) + self.assertEqual(len(components), 92) + self.assertEqual(components, tuple(sorted(components, key=lambda value: value.encode("utf-8")))) + self.assertEqual(len(values), len(bindings), 92) + self.assertEqual(tuple(row["prepared_component"] for row in values), components) + self.assertEqual(tuple(row["prepared_component"] for row in bindings), components) + selected = table["profiles"][1] + selection = projection["selection"] + self.assertEqual(selection["profile_pointer"], "/profiles/1") + self.assertEqual(selection["profile_row_sha256"], artifacts.sha256_bytes(artifacts.canonical_json_bytes(selected))) + self.assertEqual(selection["dimension_scales_sha256"], artifacts.sha256_bytes(artifacts.canonical_json_bytes(selected["dimension_scales"]))) + self.assertEqual(selection["part_placements_sha256"], artifacts.sha256_bytes(artifacts.canonical_json_bytes(selected["part_placements"]))) + self.assertEqual(projection["projected_carrier"]["bytes"], len(artifacts.canonical_json_bytes([row["value"] for row in values]))) + self.assertEqual(projection["projected_carrier"]["sha256"], artifacts.sha256_bytes(artifacts.canonical_json_bytes([row["value"] for row in values]))) + neutral_bindings = { + row["prepared_component"]: row for row in neutral_projection.source_binding_records(SOURCE) + } + for value, binding in zip(values, bindings): + self.assertEqual(set(value), {"prepared_component", "value", "source_pointers", "profile_pointers"}) + self.assertEqual(set(binding), {"prepared_component", "derivation_id", "source_addresses", "source_pointers", "profile_pointers"}) + self.assertEqual(value["prepared_component"], binding["prepared_component"]) + self.assertEqual(value["source_pointers"], binding["source_pointers"]) + self.assertEqual(value["profile_pointers"], binding["profile_pointers"]) + self.assertEqual(value["source_pointers"], neutral_bindings[value["prepared_component"]]["source_pointers"]) + if binding["derivation_id"] == "profile.dimension-permille-half-even-mm.v1": + self.assertEqual(len(value["profile_pointers"]), 1) + self.assertIn("/dimension_scales/", value["profile_pointers"][0]) + else: + self.assertTrue(value["profile_pointers"]) + self.assertTrue(all("/part_placements/" in pointer for pointer in value["profile_pointers"])) + self.assertEqual(value["source_pointers"], sorted(set(value["source_pointers"]))) + self.assertEqual(value["profile_pointers"], sorted(set(value["profile_pointers"]))) + self.assertTrue(all(pointer.startswith("/body/") for pointer in value["source_pointers"])) + self.assertTrue(all(pointer.startswith("/profiles/1/") for pointer in value["profile_pointers"])) + self.assertTrue(all("//" not in pointer and not any(part.startswith("0") and part != "0" for part in pointer.split("/") if part.isdigit()) for pointer in value["profile_pointers"])) + self.assertTrue(all(row["derivation_id"] in { + "profile.dimension-permille-half-even-mm.v1", "profile.world-placement-axis-sum.v1", "profile.world-landmark-axis-sum.v1" + } for row in bindings)) + + def test_seed_dispatch_is_exact(self): + self.assertEqual(tuple(runner.PROFILE_IDS), PROFILE_IDS) + self.assertEqual(tuple(publisher.SEEDS), SEEDS) + self.assertEqual(tuple(runner.PARAMETER_IDS), tuple(parameter for parameter, _ in SELECTORS)) + self.assertEqual(tuple(runner.PERTURBATION_ROLES), PERTURBATION_ROLES) + with tempfile.TemporaryDirectory(prefix="ck-exact-five-seed-dispatch-", dir="/tmp") as directory: + for seed in (0, 16, 18, 30, 31): + output = Path(directory) / f"{PROFILE_IDS[0]}-{seed}" + result = self._run_pinned([str(RUNNER_SCRIPT), "--profile", PROFILE_IDS[0], "--output", str(output)], seed) + with self.subTest(profile=PROFILE_IDS[0], seed=seed): + self.assertNotEqual(result.returncode, 0) + self.assertFalse(output.exists() or output.is_symlink()) + + def test_static_identity_and_allowlist(self): + self.assertEqual(hashlib.sha256(ACTIVATION_CONTRACT.read_bytes()).hexdigest(), ACTIVATION_SHA256) + self.assertEqual(ACTIVATION_SIDECAR.read_bytes(), f"{ACTIVATION_SHA256} {ACTIVATION_ROLE}\n".encode("ascii")) + self.assertEqual(_record(DESIGN_CONTRACT, DESIGN_ROLE)["sha256"], DESIGN_SHA256) + self.assertEqual(_record(SOURCE, SOURCE_ROLE)["sha256"], SOURCE_SHA256) + self.assertEqual(_record(PROFILE_TABLE, PROFILE_ROLE)["sha256"], PROFILE_SHA256) + self.assertEqual(runner.EXPECTED_ACTIVATION_SHA256, ACTIVATION_SHA256) + self.assertEqual(runner.EXPECTED_DESIGN_SHA256, DESIGN_SHA256) + self.assertEqual(runner.EXPECTED_SOURCE_SHA256, SOURCE_SHA256) + self.assertEqual(runner.EXPECTED_PROFILE_SHA256, PROFILE_SHA256) + self.assertEqual(len(REQUIRED_TEST_IDS), 12) + self.assertEqual(tuple(runner.REQUIRED_TEST_IDS), REQUIRED_TEST_IDS) + self.assertEqual(tuple(row[0] for row in runner.DEPENDENCIES), EXPECTED_DEPENDENCY_ROLES) + expected_files = { + "experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh", + "experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py", + "experiments/owned-root-assembly-successor-exact-five/exact_five_publisher.py", + "experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py", + } + found = set() + for directory, subdirectories, filenames in os.walk(EXACT_PACKAGE, followlinks=False): + subdirectories[:] = [name for name in subdirectories if not (Path(directory) / name).is_symlink()] + for filename in filenames: + path = Path(directory) / filename + if path.suffix in (".py", ".sh"): + self.assertFalse(path.is_symlink(), path) + found.add(path.relative_to(REPOSITORY).as_posix()) + self.assertEqual(found, expected_files) + self.assertEqual(tuple(runner.ADDITIVE_ROLES), tuple(sorted(expected_files, key=lambda value: value.encode("utf-8")))) + self.assertEqual(tuple(sorted(runner.PAYLOAD_ROLES, key=lambda value: value.encode("utf-8"))), PAYLOAD_ROLES) + self.assertEqual(tuple(sorted(runner.BUNDLE_ROLES, key=lambda value: value.encode("utf-8"))), BUNDLE_ROLES) + self.assertEqual(tuple(publisher.PUBLIC_ROLES), PUBLIC_ROLES) + self.assertEqual(tuple(runner.PROFILE_PACKAGE.parts[-2:]), ("experiments", "current-form-surface-preview")) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 927fa25..4913ee0 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -1,7 +1,7 @@ # Owned root assembly successor -Status: standard-neutral execution complete; frozen, SHA-256-bound, -non-normative +Status: standard-neutral execution complete; exact-five attempt fail-closed; +frozen, SHA-256-bound, non-normative Experiment lifecycle: finished @@ -36,10 +36,10 @@ This is the frozen candidate contract and bounded implementation phase for one new, standard-neutral experiment. It is the successor direction authorized after the seven-ring candidate in PR #125 reached its three-round stop rule. It remains an unaccepted experiment-local candidate: the neutral result -supports proceeding to the unchanged exact-five gate, but does not establish a -production schema, architecture, topology, supported morphology promise, or -permanent technology choice. It does not reactivate a parked workstream or -satisfy the DR-0013 Stage 1 proof. +unlocked the unchanged exact-five gate, but the exact-five attempt is +fail-closed and does not establish a production schema, architecture, +topology, supported morphology promise, or permanent technology choice. It +does not reactivate a parked workstream or satisfy the DR-0013 Stage 1 proof. The previous candidate is evidence, not a foundation to transplant. Its seven-ring topology, projection, formulas, macros, IDs, thresholds, and @@ -49,7 +49,7 @@ the focused audit required here. ## Current execution state -The retained pre-seam neutral evidence baseline is commit +Historical round-0 neutral evidence is retained at commit `2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the 96-file publication in logical local cache `artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. That historical @@ -71,9 +71,16 @@ the runtime fingerprint is Main-thread visual appraisal found the neutral neck, shoulder/axilla, pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks -agreed and found no material blocker. The exact-five gate is therefore -unlocked, but no exact-five executable or gallery exists yet. The named human -checkpoint remains Ben's later exact-five gallery appraisal. +agreed and found no material blocker. The exact-five gate was therefore +unlocked. The local exact-five runner, publisher, launcher, focused tests, and +gallery adapter now exist. Projection across all five profiles is exact, and +focused non-success-path tests pass, but publication remains fail-closed: +four non-neutral profiles fail the unchanged gates. The canonical trigger +evidence is +`experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json` +(21,714 bytes; SHA-256 +`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with +39 observed failure records and ten profile/seed reproductions. The semantics-preserving numeric-only geometry seam and change batch fit the frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed @@ -90,10 +97,24 @@ and the current stable-manifest SHA-256 is The exact-five activation contract is frozen at SHA-256 `a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49`; -two independent Sol reviews returned `FREEZE` with no blockers. Next is its -sibling exact-five runner/publisher. Do not add a private-internal wrapper, -duplicate geometry, profile-aware branching, geometry correction, or a new -representation. +two independent Sol reviews returned `FREEZE` with no blockers. The exact-five +execution surface is present locally, but its fail-closed publication is not a +success result. Outside the bounded correction authorized below, do not add a +private-internal wrapper, duplicate geometry, profile-aware branching, +geometry correction, or a new representation. + +Ben explicitly authorized one bounded dimension-driven shared shoulder/hip +correction within the existing welded representation, preceded by feasibility. +No profile exceptions, clamps, gate or threshold relaxation, topology, +ownership, renderer, subdivision, or representation change is authorized. +Shoulder feasibility found a dimension-driven candidate that passes exact five +and coherent diagnostics. Hip feasibility found the frozen formula/support +restriction insufficient; Astra-high recommended exactly one bounded +deterministic fixed-topology pre-filter trial using already-admitted adjacent +station inputs. That advice is advisory evidence, not accepted architecture. +If the trial requires profile fitting, clamps, overshoot, topology or ownership +change, cap excess, or still fails required cases, stop rather than refreeze. +No formula has been accepted or implemented. ## Protocol @@ -129,9 +150,10 @@ credible. ## Decision impact -A credible neutral result, after all technical gates, permits an unchanged -exact-five profile run and a later human checkpoint about whether this -representation is worth extending. It does not approve production use. +A credible neutral result, after all technical gates, permitted the unchanged +exact-five profile run and the later human checkpoint about whether this +representation is worth extending. The exact-five attempt is fail-closed, and +it does not approve production use. An uncured neutral failure rejects this candidate. It does not reject programmatic or hybrid surfaces globally. A materially different @@ -572,23 +594,41 @@ does not authorize promotion into production code or canonical architecture. ## Results, limitations, and conclusion -The standard-neutral execution completed at `correction_round=0` against the -retained pre-seam baseline above. Its 96-file publication, 121-test clean result, passed -seed gates, and passed cross-seed comparison permit proceeding to the unchanged -exact-five gate. No exact-five executable or gallery exists yet. - -The trial is limited to one standard-neutral root assembly. It does not test -the exact-five profiles, optional modules, tails, hands, feet, faces, distal -anatomy, posing, skeleton runtime, deformation, simulation, engine adapters, -or production packaging. This positive result does not approve production use; -it only unlocks the next recorded investigation and human checkpoint. +The standard-neutral execution completed at `correction_round=0`. The current +post-seam correction-batch publication identified above contains 96 files, +passes 134 managed tests, both seed gates, and cross-seed comparison, and keeps +all 38 payload roles byte-identical to the retained pre-seam baseline. This is +historical round-0 neutral evidence; it unlocked the unchanged exact-five +gate. + +The exact-five execution surface now exists locally and projection across all +five profiles is exact. Focused non-success-path tests pass. No successful +exact-five publication is claimed: four non-neutral profiles fail the +unchanged gates, so publication remains fail-closed. The canonical trigger +evidence is +`results/correction-round-1-preflight-trigger.json` (21,714 bytes; SHA-256 +`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with +39 observed failure records and ten profile/seed reproductions. + +The initial trial was limited to one standard-neutral root assembly. The +subsequent exact-five attempt covers the five profile projections and unchanged +gates only; it does not cover optional modules, tails, hands, feet, faces, +distal anatomy, posing, skeleton runtime, deformation, simulation, engine +adapters, or production packaging. The exact-five result is fail-closed and +does not approve production use. ## Recommended follow-up The semantics-preserving numeric-only geometry seam is implemented and -revalidated against the baseline above. Separately, prepare the SHA-bound -activation contract and sibling exact-five -runner/publisher. Do not add a private-internal wrapper, duplicate geometry, -profile-aware branching, geometry correction, or a new representation, and do -not edit canonical specifications or production architecture as part of this -experiment. +revalidated against the historical baseline above. Ben has authorized exactly +one bounded dimension-driven shared shoulder/hip correction within the existing +welded representation, preceded by feasibility. Shoulder feasibility found a +candidate that passes exact five and coherent diagnostics. Hip feasibility found +the frozen formula/support restriction insufficient; Astra-high's recommendation +is advisory evidence for exactly one bounded deterministic fixed-topology +pre-filter trial using already-admitted adjacent station inputs, not accepted +architecture. If that trial requires profile fitting, clamps, overshoot, +topology or ownership change, cap excess, or still fails required cases, stop +rather than refreeze. No formula has been accepted or implemented. The human +checkpoint remains Ben's exact-five gallery appraisal, and any PR must remain +unmerged until his explicit approval. diff --git a/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json b/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json new file mode 100644 index 0000000..5d81e45 --- /dev/null +++ b/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json @@ -0,0 +1 @@ +{"authorization":"Ben authorized one bounded correction round within the existing shared-surface representation, preceded by feasibility evidence.","candidate":"dimension-driven-shared-attachment-correction","limitations":["This is pre-correction trigger evidence, not a proposed formula and not evidence that round 1 will pass.","The public exact-five launcher did not complete its full ten-bundle, cross-seed, causality, publication, or gallery suite.","The profile/seed runner passed the standard-neutral profile but rejected the four non-neutral profiles before successful bundles could be sealed.","The metrics are mechanical geometry/anatomy evidence; they do not replace visual appraisal and do not claim universal morphology support.","Round-0 implementation and evidence remain historical and must be regenerated if the shared construction changes."],"limits":{"formula_recommendation_in_this_record":false,"gate_change":false,"hidden_or_duplicate_surface":false,"new_representation":false,"port_or_ownership_change":false,"profile_id_or_label_in_geometry":false,"profile_specific_branch_or_exception":false,"profile_specific_geometry":false,"renderer_change":false,"solver_optimizer_remesher_or_render_offset":false,"subdivision_change":false,"threshold_change":false,"topology_change":false},"neutral_result":{"all_unchanged_geometry_and_anatomy_gates":"not_failed_in_metric_collection","co_normal_threshold":0.8,"observed_failures":0,"profile_id":"standard_neutral_reference","profile_index":0},"observed_failures":[{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360806,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360805,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360814,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360817,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.6760110294117647,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.6760110294117643,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__left_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695751693,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"continuity","gate_id":"continuity.junction.pelvis__right_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695749178,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595129,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__abdomen.L0.fold_angle","observed_max":91.31293023554761,"observed_min":33.087900440787394,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":10,"threshold":90.0,"threshold_relation":"lt","unit":"degree"}],"permitted_scope":{"domains":["domain.left_hip","domain.left_shoulder","domain.right_hip","domain.right_shoulder"],"formula_ids":["formula.hip.left","formula.hip.right","formula.shoulder.left","formula.shoulder.right"],"kind":"one shared dimension-driven attachment-construction correction","mechanical_consequences":["update affected executable/reference formulas together","update derived dependency, derivative, support, and identity records","regenerate neutral evidence","revalidate and refreeze only after two fresh independent reviews"],"required_property":"derive each attachment from the existing adjoining-region inputs and preserve one welded shared surface with source-level causal effect"},"prior_design_contract":{"bytes":173184,"correction_round":0,"role_path":"experiments/owned-root-assembly-successor/design-contract.md","sha256":"3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490"},"prior_round":0,"profile_table":{"bytes":29970,"profiles":[{"id":"standard_neutral_reference","index":0},{"id":"compact_broad_short_limb_large_head","index":1},{"id":"tall_narrow_long_legged","index":2},{"id":"slender_long_limb","index":3},{"id":"stocky_broad_chested","index":4}],"role_path":"experiments/current-form-surface-preview/structural_profile_candidates.json","sha256":"a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640"},"repository":{"revision":"f3d7a5c897c5ee1c8de49c682d6c2cf8203ab859","worktree":"/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor"},"reproduction":{"pinned_launcher":"experiments/current-form-surface-preview/surface_preview_launcher.sh","profile_seed_invocations":[{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output /tmp/ck-r1-repro-standard-17","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output /tmp/ck-r1-repro-standard-29","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output /tmp/ck-r1-repro2-0-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output /tmp/ck-r1-repro2-0-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output /tmp/ck-r1-repro2-1-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output /tmp/ck-r1-repro2-1-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output /tmp/ck-r1-repro2-2-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output /tmp/ck-r1-repro2-2-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output /tmp/ck-r1-repro2-3-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output /tmp/ck-r1-repro2-3-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":29}],"public_exact_five":{"command":"PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --baseline-root /home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4 --output /tmp/ck-r1-public-rejection","exit_code":1,"observed_stderr":"exact_five_runner: error: managed tests did not all pass","output_exists":false}},"retained_baseline":{"comparison_report":{"bytes":24640,"role_path":"comparison/comparison-report.json","sha256":"fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a"},"comparison_report_sidecar":{"bytes":89,"role_path":"comparison/comparison-report.sha256","sha256":"27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac"},"outer_file_count":96,"payload_identities":[{"bytes":6556,"role_path":"seed-17/direct.png","sha256":"b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed"},{"bytes":8444,"role_path":"seed-17/lineage.png","sha256":"19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2"}],"root":"/home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4","runtime_fingerprint_sha256":"c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085","stable_manifests":[{"bytes":6367,"role_path":"seed-17/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"},{"bytes":6367,"role_path":"seed-29/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"}]},"schema":"owned-root-assembly-successor.correction-round-1-preflight-trigger.v1","source":{"bytes":56984,"role_path":"examples/body-documents/stylized-digitigrade-biped-authored-form.json","sha256":"82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14"},"status":"authorized_pending_implementation","target_round":1,"verification":{"metric_collection":"completed through project_profile, surface.evaluate, chart.build_chart_summary, anatomy.measure_anatomy, mesh_correctness.port_loop_metrics, and existing fold sampling","metric_collection_seeds":[17,29],"metric_failure_set_identical_across_seeds":true,"public_exact_five_full_suite":"failed before profile publication at managed tests; not a complete exact-five pass","publisher_baseline_function_direct_readmission":"failed with input-manifest.json changed after inventory; this is an orchestration validation limitation, not a geometry gate result","source_profile_and_baseline_identity":"passed through pinned launcher-backed checks"}} \ No newline at end of file From 15479d1fe4c1d5d368998dbc5c616f25ce575a52 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 6 Sep 2026 14:54:12 +1200 Subject: [PATCH 20/38] Clarify worker and overseer orchestration responsibilities --- AGENTS.md | 38 +++-- .../ai-delegation-and-review.md | 150 ++++++++++++++---- 2 files changed, 147 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cbd8af3..3edfb81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,10 +72,17 @@ Ben retains decisions about: - large or otherwise irreversible trade-offs; and - acceptance or rejection of product and direction-setting decision records. -The main Sol thread owns planning, task decomposition, synthesis, integration, -consolidated validation, Git and pull-request operations, review orchestration, -external effects, and final repository judgment. It escalates whenever work -would change a retained human boundary. +The Main Worker role owns routine planning and decomposition, implementation +and integration, direct visual inspection, consolidated validation, Git and +review operations, external effects, and final repository judgment within the +recorded runway. The explicitly assigned Overseer role provides concise +prioritization and coordination, reviews consequential evidence, and makes +direction recommendations; it does not replace Ben's decision authority. +These are roles rather than model identities. Persistent Astra use applies +only to Ben's explicitly recorded task/role assignment and its authorized +scope and duration; it grants no permission for other or new tasks or +extensions. Ben's retained boundaries above remain unchanged; this split adds +no serial permission gate or merge/descendant authority. Routine, reversible technical implementation may proceed autonomously within a recorded runway. This includes implementation details, defect resolution, @@ -84,11 +91,14 @@ deterministic or numeric algorithms, and reversible dependencies or tools when they remain inside canonical boundaries. The reasoning for a consequential technical choice remains durable in its owner document. +The Main Worker and Overseer delegate routine reading, writing, and tests by +default; they retain technical reasoning, decisive evidence inspection, and +narrow source-ambiguity review, and do not duplicate bulk investigations. Subagents are bounded executors, investigators, or reviewers. They may collect evidence, implement settled technical work, and challenge proposals, but they never decide product or architecture direction. They do not spawn descendants -unless the main thread explicitly authorizes a narrowly bounded exception. The -main thread inspects, integrates, and disposes of delegated work; the detailed +unless the Main Worker explicitly authorizes a narrowly bounded exception. The +Main Worker inspects, integrates, and disposes of delegated work; the detailed workflow defines the exception and routing response. ## Runway and merge control @@ -179,10 +189,18 @@ Read the named owner before taking the corresponding action: read [the experiments workflow](experiments/README.md), the relevant experiment README, and use the required launcher named there. 6. When operational friction is unexpected and recurring or likely reusable, - subagents return a concise `AI observation candidate`. The main thread - searches the inbox narrowly, deduplicates it, and writes a durable record - only for an evidenced recurring or reusable pattern. A maintenance round - consumes, resolves, promotes, or retains inbox entries. + executors return a concise, evidenced `AI observation candidate`. The + [AI delegation and review workflow](docs/developer-workflows/ai-delegation-and-review.md#operational-observations) + defines the access-authorized routing: the Main Worker is the default + durable-record writer and deduplication owner when access is authorized, + subject to its explicit inbox restrictions; the Overseer adjudicates + escalated recurring coordination and instruction patterns and commissions + bounded fixes. Selective process-improvement stewardship follows the linked + workflow; neither role grants access to the protected inbox, and the inbox + is not authority over this workflow. Severe blockers may escalate + immediately. A matching candidate remains a recurrence rather than a + duplicate; no second backlog, inbox-zero obligation, or always-on reading + is created. 7. When resuming from another session, worktree, or stale state, read [current-handover](docs/project/current-handover.md) as a live-check pointer; it never overrides the Active runway or a canonical authority. diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index e6a20bc..f2d716e 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -12,24 +12,37 @@ merge gates, observation escalation, and subagent handoff. `AGENTS.md` remains the always-on repository safety and authority kernel; this document supplies the conditional procedure when its trigger applies. -## Main-thread ownership +## Main Worker and Overseer ownership -The main `gpt-5.6-sol` thread owns: +The Main Worker role owns: - discussion with the human project owner; -- planning and decomposition into bounded steps; +- routine planning and decomposition into bounded steps; - synthesis of product, architecture, research, and review evidence; - assignment and integration of delegated work; +- direct visual inspection; - consolidated validation; -- Git, branch, commit, pull-request, and merge operations; +- Git, branch, commit, pull-request, and merge operations under Runway and + merge control; - CI and review orchestration; - external effects; and - final repository decisions and recommendations. -Subagents are bounded executors, evidence gatherers, hands-on operators, or -independent reviewers; they do not make product or architecture decisions. -Reviewers recommend; the human decision owner accepts, rejects, or changes a -direction. The main thread owns integration and final disposition. +The explicitly assigned Overseer role provides concise prioritization and +coordination, reviews consequential evidence, and makes direction +recommendations. Ben's retained boundaries in `AGENTS.md` remain unchanged. +Main Worker and Overseer are roles rather than model identities. Persistent +Astra use applies only to Ben's explicitly recorded task/role assignment and +its authorized scope and duration; it grants no permission for other or new +tasks or extensions. There is no serial permission gate between them, and this +split adds no merge or descendant authority. + +The Main Worker and Overseer delegate routine reading, writing, and tests by +default; they retain technical reasoning, decisive evidence inspection, and +narrow source-ambiguity review, and do not duplicate bulk investigations. +Executors and independent reviewers do not make product or architecture +decisions. Reviewers recommend; Ben accepts, rejects, or changes a direction. +The Main Worker owns integration and final disposition. The recorded `Active runway` in `docs/project/status.md` is the destination for autonomous progress. The main thread may advance direct, internal, @@ -39,9 +52,10 @@ checkpoint with an internal tooling, evidence, governance, or infrastructure milestone. Routine technical choices inside an accepted boundary may be settled by the -main thread, including implementation details, deterministic or numeric -algorithms, diagnostics, status plumbing, build integrity, code and test -organization, and reversible dependencies or tools. The main thread records +Main Worker within the active runway, including implementation details, +deterministic or numeric algorithms, diagnostics, status plumbing, build +integrity, code and test organization, and reversible dependencies or tools. +The Main Worker records reasoning in the appropriate durable document when the choice warrants it. It classifies findings as follows: @@ -50,6 +64,22 @@ It classifies findings as follows: - implementation- or evidence-dependent: record the trigger and defer; and - speculative hardening without a present need: do not build it now. +### Coordination, status, and yields + +Status and feedback replies steer the active mandate; they do not by +themselves pause or terminate it. Reports are nonblocking and do not require +an acknowledgement loop. A real yield states the scoped reason, continuation +owner, and actual continuation mechanism. Sending a message does not guarantee +that it wakes the recipient. Explicit pauses and named human checkpoints +remain authoritative. + +The Main Worker continues independent authorized work while a scoped +consequential decision is pending unless Ben explicitly pauses that work. The +Overseer may select and direct bounded experimental next steps already within +Ben's recorded runway. Ben retains product and architecture acceptance and all +retained boundaries; routine technical progress does not require human +permission at every step or an obligatory extra review. + Detailed decision-record states, acceptance prerequisites, review records, and the acceptance operation remain owned by `docs/decisions/README.md`. This workflow does not accept a DR, change a canonical product or architecture @@ -57,6 +87,31 @@ contract, or grant a subagent authority that the canonical owner does not have. Unaccepted material remains labelled `Candidate`, `Proposed`, `Under Review`, or `provisional`, as appropriate to its state. +## Cost-aware Main Worker orchestration + +Before beginning a multi-step execution task, the Main Worker delegates a +bounded step when it is independently runnable. Settled implementation, test +writing, tool operation, monitoring, and evidence collection—including +inventories and hashes—belong to Luna by default, especially while the Main +Worker is an explicitly authorized Astra run. The Main Worker keeps technical +reasoning, scope and test selection, integration decisions, and direct +consequential geometry/vision inspection; it need not perform a worker's bulk +operations itself. + +The Main Worker must not drift into a worker's job because tools are available +or because the work can be labelled verification. Review is targeted inspection +of decisive diffs and evidence, not repeated scans or execution. Delegated +validation execution may satisfy consolidated checks when the Main Worker +inspects and accepts the result. While useful independent work remains, +dispatch it before long local reading or polling; do not create slot quotas, +makework, or fill idle lanes. Exceptions are limited to trivial +latency-sensitive reads/edits or reasoning genuinely inseparable from Main +work, not broad loopholes. Do not duplicate worker scans or tests, or +repeatedly poll without a concrete need. This adds no rigid command budgets or +approval gates. “Main Worker” and “Overseer” are roles, not model names; +existing model authorization, routing, and human boundaries remain unchanged, +and this does not grant global Astra orchestration. + ## Batches and research passes The main thread groups related product, direction-setting, architecture-boundary, @@ -124,7 +179,10 @@ lane is not activated, these passes are not required. call plus at most one adversarial follow-up is allowed without another permission round. Additional calls require Ben's explicit approval. The main thread reports Astra use and its material recommendations in the - handoff so Ben can see what informed the path. + handoff so Ben can see what informed the path. These announcement and + separate-call cap rules apply to advisory Astra invocations, not every turn + of a Ben-authorized persistent Astra Main Worker or Overseer; they do not + authorize a global Astra orchestrator. - Astra-max/ultra, Astra as an orchestrator, and routine Astra use are explicit-approval-only. Astra is not used for mechanical patches, ordinary tests or CI, CodeRabbit, bookkeeping, or as a throughput substitute for @@ -190,6 +248,10 @@ focused investigation or research, mechanical edits, settled implementation, focused tests, hands-on trials, and fresh review. Keep a trivial single-read local when delegation overhead costs more than it saves. Delegate one bounded step at a time; the main thread chooses the next step after inspecting it. +For capture-before-geometry work, tests or helpers that calculate candidate +vertices or faces (for example `_append_ear`) are geometry and remain blocked +until the executor has captured the source; implementation-only delegates may +run syntax or static checks, but not those helper tests. A bounded subagent must not spawn descendants unless the main thread explicitly authorizes a specifically bounded nested delegation. If a Luna task appears @@ -231,10 +293,11 @@ write permission by implication. Validation is a closed allowlist. A worker runs only commands named in its prompt; when none are named, it reports validation as `deferred`. The main -thread performs consolidated validation after integration. A worker stops when -its deliverable and named checks are complete. It does not add cleanup, -unrequested wording or structural audits, substitute different validation, or -start a continuation or retry loop. +thread owns consolidated validation after integration: it may delegate +execution or collection of named checks, then inspects and accepts the results. +A worker stops when its deliverable and named checks are complete. It does not +add cleanup, unrequested wording or structural audits, substitute different +validation, or start a continuation or retry loop. Unless an exact action is delegated with any required human authorization, a worker does not inspect or alter Git, pull-request, CI, review, deployment, or @@ -379,7 +442,8 @@ main thread does not push or mutate the remote PR head. It may prepare local fixes without presenting them as reviewed. After both results complete, the main thread verifies each finding, fixes or -explicitly dispositions it, runs the required local and CI checks, and pushes +explicitly dispositions it, ensures the required local and CI checks are run, +and pushes the next head only when the result is ready for a new cycle. Hosted taper is reached when a fresh hosted pass produces no new material findings, or only repeats, non-actionable findings, disproportionate suggestions, or @@ -423,25 +487,49 @@ does not mutate another project. ## Operational observations -Every worker reports unexpected operational friction that forces a retry, +Every executor reports unexpected operational friction that forces a retry, workaround, or changed tool path. The report includes the command or tool category, exact error, attempt count, workaround, and what is known versus inferred about the cause. Qualifying friction is unexpected, evidenced, and recurring, reusable, or likely to save future retries or work rounds. -When qualifying friction occurs, the main thread searches -`docs/project/ai-observations.md` narrowly for a matching pattern, deduplicates -against existing entries, and records only a recurring or reusable evidenced -pattern before the round closes. A matching entry is reported as a recurrence, -not duplicated or silently bypassed. A subagent returns a concise `AI -observation candidate` unless it has explicitly exclusive inbox ownership; -the main thread is the default writer so parallel write scopes remain disjoint. - -Ordinary work does not read the inbox. Existing entries are changed only in an -intentional tooling or instruction-maintenance round. That round resolves, -promotes, or removes entries deliberately. A repeated issue closes through a -concrete bounded fix to a repository wrapper, preflight, active instruction, -or other available tool path; restating the observation is not closure. +The protected `docs/project/ai-observations.md` is the durable-record owner. +The Main Worker is the default durable-record writer and deduplication owner +when access is authorized, subject to this workflow's explicit inbox +restrictions. The Overseer adjudicates escalated recurring coordination and +instruction patterns and commissions bounded fixes. Neither role grants access +to the protected inbox, and the inbox is not authority over this workflow. +Severe blockers may escalate immediately. Executors return concise, evidenced +`AI observation candidate` reports; a matching candidate is reported as a +recurrence rather than duplicated or silently bypassed. Ordinary work does not +read the inbox, and no second backlog, inbox-zero obligation, or always-on +reading is created. Existing-entry changes remain limited to the intentional +tooling or instruction-maintenance round and its explicit access restrictions. +Future cleanup is explicitly authorized maintenance only; it addresses entries +whose evidence is resolved, obsolete, or disproved, preserves unrelated and +concurrent entries, and does not create an inbox-zero obligation. + +### Selective process-improvement stewardship + +At meaningful existing oversight or checkpoint boundaries, the explicitly +assigned Overseer selectively considers worthwhile batches of reported process, +tooling, evidence, validation, or context-efficiency improvement candidates. +The Overseer may delegate bounded, authorized fact gathering, grouping, and +evidence checks, then personally judges a compact shortlist for usefulness, +priority, and scope before commissioning the Main Worker or an executor. This +is not a timer, fixed cadence, whole-inbox scan, second backlog, or new suite. + +Recurrence is a signal, not a prerequisite for an obvious, evidenced, +low-cost, reusable improvement. A same-task bug remains immediate +implementation work rather than an observation. Weigh expected benefit against +implementation and maintenance cost, and prefer existing tools. Existing +authorized reversible fixes may proceed; retained-human decisions go to Ben. +This role does not grant protected-inbox access: stewardship uses reported +candidates or separately access-authorized material. + +A repeated issue closes through a concrete bounded fix to a repository wrapper, +preflight, active instruction, or other available tool path; restating the +observation is not closure. ## Subagent handoff From c33f093a6181c6540a3ba9726ea32aded310c09e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 6 Sep 2026 16:03:21 +1200 Subject: [PATCH 21/38] Validate exact-five gallery provenance and stable role ordering --- .../publish_exact_five_gallery.py | 150 +++++++++++++++--- .../tests/test_exact_five_gallery.py | 92 ++++++++++- .../tests/test_exact_five_activation.py | 10 +- 3 files changed, 224 insertions(+), 28 deletions(-) diff --git a/dev-tools/visual-review/publish_exact_five_gallery.py b/dev-tools/visual-review/publish_exact_five_gallery.py index b94422c..e83e59e 100644 --- a/dev-tools/visual-review/publish_exact_five_gallery.py +++ b/dev-tools/visual-review/publish_exact_five_gallery.py @@ -6,6 +6,8 @@ import argparse import hashlib import math +import os +import re import struct import tempfile import zlib @@ -54,6 +56,17 @@ class ExactFiveGalleryError(RuntimeError): PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" MAX_PNG_BYTES = 2 * 1024 * 1024 MAX_JSON_BYTES = 16 * 1024 * 1024 +FINAL_TIMING_PHASES = ( + "identity", + "managed-tests", + "launcher-baseline-admission", + "profile-seed-builds", + "publisher-baseline-admission", + "comparison", + "pre-report-closure", + "total-before-seal", +) +UTC_TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\Z") def _fail(message: str) -> NoReturn: @@ -110,6 +123,69 @@ def _same_file_identity(left: dict[str, Any], right: dict[str, Any]) -> bool: return left["bytes"] == right["bytes"] and left["sha256"] == right["sha256"] +def _canonical_absolute(value: Any, where: str) -> Path: + if ( + type(value) is not str + or not value + or not Path(value).is_absolute() + or os.path.normpath(value) != value + or "//" in value + ): + _fail(f"{where} is not canonical absolute") + return Path(value) + + +def _validate_final_report(report: dict[str, Any], root: Path) -> Path: + output_path = _canonical_absolute(report["output_path"], "exact-five output path") + staging_path = _canonical_absolute(report["staging_path"], "exact-five staging path") + _canonical_absolute(report["python_executable_path"], "exact-five Python executable") + baseline_path = _canonical_absolute(report["neutral_baseline_path"], "neutral baseline path") + overlaps = lambda left, right: left == right or left in right.parents or right in left.parents + if ( + output_path != root + or staging_path == output_path + or staging_path.parent != output_path.parent + or not staging_path.name.startswith(".exact-five-public-") + or overlaps(baseline_path, output_path) + or overlaps(baseline_path, staging_path) + ): + _fail("exact-five final report paths do not bind the published root") + + expected_invocation = { + "environment": ["PYTHONHASHSEED=0"], + "argv": [ + exact_five.LAUNCHER_ROLE, + "--baseline-root", + str(baseline_path), + "--output", + str(output_path), + ], + } + if report["literal_invocation"] != expected_invocation: + _fail("exact-five final report invocation differs") + + if ( + type(report["started_utc"]) is not str + or type(report["finished_utc"]) is not str + or UTC_TIMESTAMP.fullmatch(report["started_utc"]) is None + or UTC_TIMESTAMP.fullmatch(report["finished_utc"]) is None + or report["finished_utc"] < report["started_utc"] + ): + _fail("exact-five final report timestamps differ") + timings = report["timings"] + if not isinstance(timings, list) or [ + item.get("phase") if isinstance(item, dict) else None for item in timings + ] != list(FINAL_TIMING_PHASES): + _fail("exact-five final report timing phases differ") + for index, item in enumerate(timings): + _closed_keys(item, {"phase", "seconds"}, f"exact-five timing {index}") + if type(item["seconds"]) is not float or not math.isfinite(item["seconds"]) or item["seconds"] < 0.0: + _fail(f"exact-five timing {index} is invalid") + if timings[-1]["seconds"] != sum(item["seconds"] for item in timings[:-1]): + _fail("exact-five final report total timing differs") + return baseline_path + + PROFILE_EVIDENCE_KEYS = { "schema", "outcome", "activation_contract", "design_contract", "source", "profile_table", "existing_dependencies", "additive_implementation_files", "runtime", @@ -153,9 +229,9 @@ def _validate_profile_evidence( identity: dict[str, Any], table: list[dict[str, Any]], public_records: dict[str, dict[str, Any]], - frozen_thresholds: list[dict[str, Any]] | None, - frozen_gate_ids: dict[str, list[str]] | None, -) -> tuple[list[dict[str, Any]], dict[str, list[str]], dict[str, dict[str, Any]], bytes]: + neutral_thresholds: list[dict[str, Any]], + neutral_gate_ids: dict[str, list[str]], +) -> tuple[dict[str, Any], bytes]: profile_id = exact_five.PROFILES[index] _closed_keys( profile, @@ -261,19 +337,21 @@ def _validate_profile_evidence( _fail(f"profile {profile_id} public PLY geometry digest differs") thresholds = nested["thresholds"] - if frozen_thresholds is None: - _publisher_check(exact_five._threshold_shape, thresholds, "profile thresholds") - frozen_thresholds = thresholds - else: - _publisher_check(exact_five._thresholds, thresholds, frozen_thresholds, "profile thresholds") + _publisher_check(exact_five._thresholds, thresholds, neutral_thresholds, "profile thresholds") gates = _closed_keys(nested["gates"], set(GATE_CARDINALITIES), f"profile {profile_id} gates") gate_ids = {group: [item.get("gate_id") if isinstance(item, dict) else None for item in gates[group]] for group in GATE_CARDINALITIES} if any(len(gates[group]) != count for group, count in GATE_CARDINALITIES.items()): _fail(f"profile {profile_id} gate cardinality differs") - if frozen_gate_ids is not None and gate_ids != frozen_gate_ids: + if gate_ids != neutral_gate_ids: _fail(f"profile {profile_id} gate inventory differs from neutral") for group in GATE_CARDINALITIES: - _publisher_check(exact_five._gate_rows, gates[group], gate_ids[group], thresholds, f"profile {profile_id} {group}") + _publisher_check( + exact_five._gate_rows, + gates[group], + neutral_gate_ids[group], + neutral_thresholds, + f"profile {profile_id} {group}", + ) causality = nested["causality"] expected_parameters = sorted(exact_five.CAUSAL_COMPONENTS, key=str.encode) @@ -336,7 +414,7 @@ def _validate_profile_evidence( _fail(f"profile {profile_id} stable comparison inventory differs") if stable != [expected_stable[role] for role in exact_five.BUNDLE_STABLE_ROLES]: _fail(f"profile {profile_id} stable comparisons are not bound to seed evidence") - return frozen_thresholds, gate_ids, payload_map, nested_raw + return payload_map, nested_raw def _read_json(path: Path, where: str, *, max_bytes: int = MAX_JSON_BYTES) -> tuple[dict[str, Any], bytes]: @@ -358,11 +436,15 @@ def _validate_png(path: Path, role: str) -> bytes: if not data.startswith(PNG_SIGNATURE): _fail(f"{role} is not a PNG") offset = len(PNG_SIGNATURE) - chunk_names: list[bytes] = [] idat = bytearray() + seen_ihdr = False + seen_idat = False + seen_iend = False while offset < len(data): if len(data) - offset < 12: _fail(f"{role} has a truncated PNG chunk") + if seen_iend: + _fail(f"{role} has data after IEND") length = struct.unpack(">I", data[offset : offset + 4])[0] chunk_type = data[offset + 4 : offset + 8] end = offset + 12 + length @@ -372,8 +454,9 @@ def _validate_png(path: Path, role: str) -> bytes: expected_crc = struct.unpack(">I", data[offset + 8 + length : end])[0] if zlib.crc32(chunk_type + payload) & 0xFFFFFFFF != expected_crc: _fail(f"{role} has an invalid PNG CRC") - chunk_names.append(chunk_type) if chunk_type == b"IHDR": + if seen_ihdr or seen_idat: + _fail(f"{role} has a non-contiguous or duplicate IHDR") if len(payload) != 13: _fail(f"{role} has an invalid IHDR") width, height, depth, colour, compression, filtering, interlace = struct.unpack( @@ -389,17 +472,22 @@ def _validate_png(path: Path, role: str) -> bytes: 0, ): _fail(f"{role} PNG dimensions or colour format differ") + seen_ihdr = True elif chunk_type == b"IDAT": + if not seen_ihdr or seen_iend: + _fail(f"{role} has an out-of-order IDAT") idat.extend(payload) + seen_idat = True elif chunk_type == b"IEND": - if length != 0 or end != len(data): + if not seen_ihdr or not seen_idat or seen_iend or length != 0 or end != len(data): _fail(f"{role} has trailing or malformed IEND data") + seen_iend = True else: _fail(f"{role} contains unexpected PNG chunk {chunk_type!r}") offset = end if chunk_type == b"IEND": break - if chunk_names != [b"IHDR", b"IDAT", b"IEND"] or not idat: + if not (seen_ihdr and seen_idat and seen_iend) or not idat: _fail(f"{role} has an incomplete PNG structure") try: decompressor = zlib.decompressobj() @@ -503,6 +591,23 @@ def validate_exact_five_root(root: Path) -> tuple[dict[str, Any], dict[str, Any] and report["runtime_fingerprint_sha256"] == identity["runtime_sha"] ): _fail("exact-five run report is not successful") + baseline_path = _validate_final_report(report, root) + baseline = _publisher_check(exact_five._baseline, baseline_path, identity) + if neutral["comparison_report"] != baseline["comparison_record"]: + _fail("neutral baseline comparison report is not bound to the admitted baseline") + if any( + baseline["records"][f"seed-{seed}/stable-manifest.json"]["sha256"] + != neutral["stable_manifest_sha256"] + for seed in exact_five.SEEDS + ): + _fail("neutral baseline stable manifest is not bound to the admitted baseline") + baseline_payload_comparisons = [ + row + for row in baseline["report"]["stable_comparisons"] + if row["role_path"] in exact_five.PAYLOAD_ROLES + ] + if neutral_comparisons != baseline_payload_comparisons: + _fail("neutral baseline payload comparisons are not bound to the admitted baseline") evidence_record = by_role["exact-five-evidence.json"] evidence_ref = {**evidence_record, "schema": evidence["schema"]} if ( @@ -524,16 +629,19 @@ def validate_exact_five_root(root: Path) -> tuple[dict[str, Any], dict[str, Any] if not isinstance(profiles, list) or len(profiles) != len(exact_five.PROFILES): _fail("exact-five evidence does not contain five profiles") png_records: dict[str, dict[str, Any]] = {} - frozen_thresholds: list[dict[str, Any]] | None = None - frozen_gate_ids: dict[str, list[str]] | None = None nested_raw_by_profile: dict[str, bytes] = {} for index, profile in enumerate(profiles): profile_id = exact_five.PROFILES[index] - frozen_thresholds, admitted_gate_ids, payload_map, nested_raw = _validate_profile_evidence( - root, profile, index, identity, table, by_role, frozen_thresholds, frozen_gate_ids + payload_map, nested_raw = _validate_profile_evidence( + root, + profile, + index, + identity, + table, + by_role, + baseline["thresholds"], + baseline["gate_ids"], ) - if frozen_gate_ids is None: - frozen_gate_ids = admitted_gate_ids nested_raw_by_profile[profile_id] = nested_raw neutral_rows = profile["neutral_payload_comparisons"] if index == 0: diff --git a/dev-tools/visual-review/tests/test_exact_five_gallery.py b/dev-tools/visual-review/tests/test_exact_five_gallery.py index c921b51..d4706c3 100644 --- a/dev-tools/visual-review/tests/test_exact_five_gallery.py +++ b/dev-tools/visual-review/tests/test_exact_five_gallery.py @@ -32,10 +32,19 @@ def _chunk(kind: bytes, payload: bytes) -> bytes: return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF) -def _png(colour: tuple[int, int, int]) -> bytes: +def _png(colour: tuple[int, int, int], *, split_idat: bool = False, separator: bool = False) -> bytes: raw = b"".join(b"\x00" + bytes(colour) * adapter.PNG_WIDTH for _ in range(adapter.PNG_HEIGHT)) header = struct.pack(">IIBBBBB", adapter.PNG_WIDTH, adapter.PNG_HEIGHT, 8, 2, 0, 0, 0) - return adapter.PNG_SIGNATURE + _chunk(b"IHDR", header) + _chunk(b"IDAT", zlib.compress(raw, 9)) + _chunk(b"IEND", b"") + compressed = zlib.compress(raw, 9) + if not split_idat: + idat = _chunk(b"IDAT", compressed) + else: + midpoint = len(compressed) // 2 + idat = _chunk(b"IDAT", compressed[:midpoint]) + if separator: + idat += _chunk(b"tEXt", b"not permitted between IDAT chunks") + idat += _chunk(b"IDAT", compressed[midpoint:]) + return adapter.PNG_SIGNATURE + _chunk(b"IHDR", header) + idat + _chunk(b"IEND", b"") def _ply() -> bytes: @@ -195,11 +204,25 @@ def _write_exact_root(self, *, invalid_ply: bool = False) -> None: (self.exact_root / "exact-five-evidence.json").write_bytes(evidence_raw) evidence_sidecar = f"{hashlib.sha256(evidence_raw).hexdigest()} exact-five-evidence.json\n".encode() (self.exact_root / "exact-five-evidence.sha256").write_bytes(evidence_sidecar) + self.baseline_admission = { + "comparison_record": self._fixed_record("comparison-report.json", exact_five.BASELINE_REPORT_SHA), + "records": { + f"seed-{seed}/stable-manifest.json": self._fixed_record( + f"seed-{seed}/stable-manifest.json", exact_five.BASELINE_STABLE_SHA + ) + for seed in exact_five.SEEDS + }, + "report": {"stable_comparisons": neutral_payloads}, + "thresholds": thresholds, + "gate_ids": { + group: [row["gate_id"] for row in rows] for group, rows in gates.items() + }, + } final_gate_ids = (["exact-five.run.01.identity", "exact-five.run.02.managed-tests", "exact-five.run.03.publisher-baseline-admission"] + [f"exact-five.run.{4 + index * 2 + offset:02d}.profile.{profile}.seed-{seed}" for index, profile in enumerate(exact_five.PROFILES) for offset, seed in enumerate(exact_five.SEEDS)] + [f"exact-five.run.{14 + index:02d}.profile.{profile}.cross-seed" for index, profile in enumerate(exact_five.PROFILES)] + ["exact-five.run.19.standard-neutral-payload-equality", "exact-five.run.20.evidence-graph", "exact-five.run.21.pre-report-closure"]) report = { - "schema": "owned-root-assembly-successor-exact-five-run-report.v1", "outcome": "success", "literal_invocation": {"environment": ["PYTHONHASHSEED=0"], "argv": [exact_five.LAUNCHER_ROLE]}, - "output_path": str(self.exact_root), "staging_path": str(self.exact_root.parent / ".stage"), "python_executable_path": sys.executable, "neutral_baseline_path": str(self.root / "baseline"), - "started_utc": "2026-01-01T00:00:00.000000Z", "finished_utc": "2026-01-01T00:00:01.000000Z", "timings": [], + "schema": "owned-root-assembly-successor-exact-five-run-report.v1", "outcome": "success", "literal_invocation": {"environment": ["PYTHONHASHSEED=0"], "argv": [exact_five.LAUNCHER_ROLE, "--baseline-root", str(self.root / "baseline"), "--output", str(self.exact_root)]}, + "output_path": str(self.exact_root), "staging_path": str(self.exact_root.parent / ".exact-five-public-test"), "python_executable_path": sys.executable, "neutral_baseline_path": str(self.root / "baseline"), + "started_utc": "2026-01-01T00:00:00.000000Z", "finished_utc": "2026-01-01T00:00:01.000000Z", "timings": [{"phase": phase, "seconds": 1.0} for phase in adapter.FINAL_TIMING_PHASES[:-1]] + [{"phase": adapter.FINAL_TIMING_PHASES[-1], "seconds": 7.0}], "activation_contract_sha256": exact_five.ACTIVATION_SHA, "design_contract_sha256": exact_five.DESIGN_SHA, "runtime_fingerprint_sha256": self.identity["runtime_sha"], "evidence": {**self._record("exact-five-evidence.json", evidence_raw), "schema": evidence["schema"]}, "evidence_sidecar": self._record("exact-five-evidence.sha256", evidence_sidecar), "payloads": payloads, "profile_seed_runs": [{"profile_id": profile["profile_id"], "seed": seed, "outcome": "success", "evidence_sha256": artifacts.sha256_bytes(artifacts.canonical_json_bytes(profile["evidence"]))} for profile in nested_profiles for seed in exact_five.SEEDS], @@ -210,7 +233,7 @@ def _write_exact_root(self, *, invalid_ply: bool = False) -> None: (self.exact_root / "run-report.sha256").write_bytes(f"{hashlib.sha256(report_raw).hexdigest()} run-report.json\n".encode()) def _publish(self, review_id: str) -> dict[str, object]: - with mock.patch.object(adapter.exact_five, "_static", return_value=self.identity), mock.patch.object(adapter.exact_five, "_table", return_value=self.table): + with mock.patch.object(adapter.exact_five, "_static", return_value=self.identity), mock.patch.object(adapter.exact_five, "_table", return_value=self.table), mock.patch.object(adapter.exact_five, "_baseline", return_value=self.baseline_admission): return adapter.publish_exact_five_gallery(self.reviews_root, self.exact_root, review_id=review_id) def _reseal_evidence(self, evidence: dict[str, object]) -> None: @@ -225,6 +248,11 @@ def _reseal_evidence(self, evidence: dict[str, object]) -> None: (self.exact_root / "run-report.json").write_bytes(report_raw) (self.exact_root / "run-report.sha256").write_bytes(f"{hashlib.sha256(report_raw).hexdigest()} run-report.json\n".encode()) + def _reseal_report(self, report: dict[str, object]) -> None: + report_raw = artifacts.canonical_json_bytes(report) + (self.exact_root / "run-report.json").write_bytes(report_raw) + (self.exact_root / "run-report.sha256").write_bytes(f"{hashlib.sha256(report_raw).hexdigest()} run-report.json\n".encode()) + def test_publishes_real_report_manifest_ref_and_five_ordered_pairs(self) -> None: result = self._publish("exact-five-gallery-test") self.assertEqual(result["images"], 10) @@ -263,6 +291,58 @@ def test_rejects_extra_root_file_before_publishing(self) -> None: with self.assertRaises(adapter.ExactFiveGalleryError): self._publish("extra-file") + def test_admits_consecutive_split_idat_chunks(self) -> None: + path = self.exact_root / "split-idat.png" + path.write_bytes(_png((31, 62, 93), split_idat=True)) + self.assertEqual(adapter._validate_png(path, "split-idat"), path.read_bytes()) + + def test_rejects_noncontiguous_split_idat_chunks(self) -> None: + path = self.exact_root / "malformed-split-idat.png" + path.write_bytes(_png((31, 62, 93), split_idat=True, separator=True)) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "unexpected PNG chunk"): + adapter._validate_png(path, "malformed-split-idat") + + def test_rejects_profiles_that_agree_with_each_other_but_not_neutral_baseline(self) -> None: + evidence = json.loads((self.exact_root / "exact-five-evidence.json").read_text()) + for profile in evidence["profiles"]: + thresholds = [] + for threshold in profile["evidence"]["thresholds"]: + rewritten = dict(threshold) + rewritten["threshold_id"] = "threshold.alt." + threshold["threshold_id"].removeprefix("threshold.") + thresholds.append(rewritten) + profile["evidence"]["thresholds"] = sorted(thresholds, key=lambda row: row["threshold_id"].encode()) + for rows in profile["evidence"]["gates"].values(): + for row in rows: + row["gate_id"] = "alt." + row["gate_id"] + row["threshold_id"] = "threshold." + row["gate_id"] + self._reseal_evidence(evidence) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "profile thresholds"): + self._publish("neutral-baseline-mismatch") + self.assertFalse((self.reviews_root / "neutral-baseline-mismatch").exists()) + + def test_rejects_report_with_unbound_invocation(self) -> None: + report = json.loads((self.exact_root / "run-report.json").read_text()) + report["literal_invocation"]["argv"][-1] = str(self.root / "wrong-output") + self._reseal_report(report) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "final report invocation"): + self._publish("unbound-report") + self.assertFalse((self.reviews_root / "unbound-report").exists()) + + def test_rejects_unbound_report_paths_and_timings(self) -> None: + original = json.loads((self.exact_root / "run-report.json").read_text()) + mutations = { + "output path": lambda report: report.__setitem__("output_path", str(self.root / "wrong-output")), + "staging path": lambda report: report.__setitem__("staging_path", str(self.exact_root)), + "timing phases": lambda report: report["timings"].__setitem__(0, {"phase": "wrong", "seconds": 1.0}), + } + for label, mutate in mutations.items(): + with self.subTest(label=label): + report = json.loads(json.dumps(original)) + mutate(report) + self._reseal_report(report) + with self.assertRaisesRegex(adapter.ExactFiveGalleryError, "final report"): + self._publish(f"unbound-{label.replace(' ', '-')}") + if __name__ == "__main__": raise SystemExit(unittest.main()) diff --git a/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py index d8791cf..9543cad 100644 --- a/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py +++ b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py @@ -460,13 +460,21 @@ def test_final_evidence_schema_and_19_file_closure(self): neutral["payload_comparisons"], [{"role_path": role, **{key: value for key, value in artifacts.regular_file_record(baseline / f"seed-17/{role}", role).items() if key != "role_path"}} for role in PAYLOAD_ROLES], ) + expected_stable_roles = tuple(sorted( + (*PAYLOAD_ROLES, "profile-seed-evidence.json", "profile-seed-evidence.sha256"), + key=lambda value: value.encode("utf-8"), + )) + self.assertEqual(expected_stable_roles, tuple(runner.STABLE_ROLES)) + self.assertEqual(len(expected_stable_roles), 40) + self.assertNotIn("run-report.json", expected_stable_roles) + self.assertNotIn("run-report.sha256", expected_stable_roles) self.assertEqual(len(evidence["profiles"]), 5) for index, (profile_id, profile) in enumerate(zip(PROFILE_IDS, evidence["profiles"])): with self.subTest(profile=profile_id): self.assertEqual(set(profile), {"profile_id", "profile_index", "evidence", "stable_cross_seed_comparisons", "neutral_payload_comparisons"}) self.assertEqual((profile["profile_id"], profile["profile_index"]), (profile_id, index)) self.assertEqual(len(profile["stable_cross_seed_comparisons"]), 40) - self.assertEqual([row["role_path"] for row in profile["stable_cross_seed_comparisons"]], list(BUNDLE_ROLES[:-2])) + self.assertEqual([row["role_path"] for row in profile["stable_cross_seed_comparisons"]], list(expected_stable_roles)) self.assertEqual(len(profile["neutral_payload_comparisons"]), 38 if index == 0 else 0) self.assertNotIn(b"run-report.json", artifacts.canonical_json_bytes(profile["evidence"])) self.assertEqual(set(report), { From e9e9e130af52623aa06e36339f93fb3fcec7f873 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 6 Sep 2026 16:55:30 +1200 Subject: [PATCH 22/38] Reject malformed gallery inventories and assert projection counts --- .../publish_exact_five_gallery.py | 4 ++-- .../tests/test_exact_five_gallery.py | 18 ++++++++++++++++++ .../tests/test_exact_five_activation.py | 4 +++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/dev-tools/visual-review/publish_exact_five_gallery.py b/dev-tools/visual-review/publish_exact_five_gallery.py index e83e59e..b02fc92 100644 --- a/dev-tools/visual-review/publish_exact_five_gallery.py +++ b/dev-tools/visual-review/publish_exact_five_gallery.py @@ -275,8 +275,8 @@ def _validate_profile_evidence( values, bindings = nested["projected_values"], nested["projection_bindings"] if not ( isinstance(values, list) and isinstance(bindings, list) - and [item.get("prepared_component") for item in values if isinstance(item, dict)] == list(exact_five.COMPONENT_IDS) - and [item.get("prepared_component") for item in bindings if isinstance(item, dict)] == list(exact_five.COMPONENT_IDS) + and [item.get("prepared_component") if isinstance(item, dict) else None for item in values] == list(exact_five.COMPONENT_IDS) + and [item.get("prepared_component") if isinstance(item, dict) else None for item in bindings] == list(exact_five.COMPONENT_IDS) ): _fail(f"profile {profile_id} projection inventory differs") for position, (value, binding) in enumerate(zip(values, bindings)): diff --git a/dev-tools/visual-review/tests/test_exact_five_gallery.py b/dev-tools/visual-review/tests/test_exact_five_gallery.py index d4706c3..ff3a4d5 100644 --- a/dev-tools/visual-review/tests/test_exact_five_gallery.py +++ b/dev-tools/visual-review/tests/test_exact_five_gallery.py @@ -291,6 +291,24 @@ def test_rejects_extra_root_file_before_publishing(self) -> None: with self.assertRaises(adapter.ExactFiveGalleryError): self._publish("extra-file") + def test_rejects_none_entries_in_inventory_lists_without_publishing(self) -> None: + original = json.loads((self.exact_root / "exact-five-evidence.json").read_text()) + mutations = { + "projected-values": lambda evidence: evidence["profiles"][0]["evidence"]["projected_values"].append(None), + "projection-bindings": lambda evidence: evidence["profiles"][0]["evidence"]["projection_bindings"].append(None), + "profile-payloads": lambda evidence: evidence["profiles"][0]["evidence"]["payloads"].append(None), + "public-payloads": lambda evidence: evidence["payloads"].append(None), + } + for label, mutate in mutations.items(): + with self.subTest(label=label): + evidence = json.loads(json.dumps(original)) + mutate(evidence) + self._reseal_evidence(evidence) + review_id = f"none-{label}" + with self.assertRaises(adapter.ExactFiveGalleryError): + self._publish(review_id) + self.assertFalse((self.reviews_root / review_id).exists()) + def test_admits_consecutive_split_idat_chunks(self) -> None: path = self.exact_root / "split-idat.png" path.write_bytes(_png((31, 62, 93), split_idat=True)) diff --git a/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py index 9543cad..84cb1cb 100644 --- a/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py +++ b/experiments/owned-root-assembly-successor-exact-five/tests/test_exact_five_activation.py @@ -681,7 +681,9 @@ def test_projection_has_exact_92_bindings(self): components = tuple(surface.GEOMETRY_COMPONENT_IDS) self.assertEqual(len(components), 92) self.assertEqual(components, tuple(sorted(components, key=lambda value: value.encode("utf-8")))) - self.assertEqual(len(values), len(bindings), 92) + self.assertEqual(len(values), len(bindings)) + self.assertEqual(len(values), 92) + self.assertEqual(len(bindings), 92) self.assertEqual(tuple(row["prepared_component"] for row in values), components) self.assertEqual(tuple(row["prepared_component"] for row in bindings), components) selected = table["profiles"][1] From 4ae0a5c8176c60791248ad6eb5e52dc657a2dd34 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 6 Sep 2026 17:17:31 +1200 Subject: [PATCH 23/38] Refresh source-bound gallery context fingerprint --- .../visual-review/tests/test_surface_preview_publication.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/visual-review/tests/test_surface_preview_publication.py b/dev-tools/visual-review/tests/test_surface_preview_publication.py index 7674c05..245318b 100644 --- a/dev-tools/visual-review/tests/test_surface_preview_publication.py +++ b/dev-tools/visual-review/tests/test_surface_preview_publication.py @@ -3287,7 +3287,7 @@ def test_current_shape_compact_producer_fits_final_descriptor_context(self) -> N self.assertEqual(subject_context_size, 8_848) self.assertEqual( hashlib.sha256(subject_context_json.encode("utf-8")).hexdigest(), - "aa31709ee1f71ca9899ecd7fadf0a0476722b12e9c305d37e3303919b133f4d7", + "5afd7cd43cb5fd41ef61d621be9aecc9e14fdb3356ff463ddb98f335da22c20e", ) self.assertLessEqual(subject_context_size, common.MAX_CONTEXT_JSON) self.assertEqual( From 488df3037a987cb7069c63444943d9e19191ad31 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 19:56:09 +1200 Subject: [PATCH 24/38] Integrate gallery comparisons and close out owned-root evidence --- .../src/provisional_form_inspection.rs | 3 +- dev-tools/visual-review/README.md | 74 ++- dev-tools/visual-review/browser_trial.ps1 | 185 ++++++++ dev-tools/visual-review/static/app.js | 442 +++++++++++++++++- dev-tools/visual-review/static/style.css | 9 +- .../tests/test_browser_trial.ps1 | 126 +++++ .../visual-review/tests/test_visual_review.py | 316 ++++++++++++- docs/project/README.md | 3 + docs/project/current-handover.md | 128 ++++- docs/project/stacked-integration-ledger.md | 157 +++++++ docs/project/status.md | 206 ++++---- docs/research/README.md | 9 +- experiments/README.md | 19 +- .../owned-root-assembly-successor/README.md | 78 ++-- .../prepared_projection.py | 8 +- .../render_export.py | 4 +- .../correction-round-1-preflight-trigger.json | 2 +- .../tests/test_build_owned_root.py | 1 - .../tests/test_mesh_correctness.py | 2 +- .../tests/test_prepared_projection.py | 25 +- .../tests/test_prepared_projection.py | 2 +- 21 files changed, 1560 insertions(+), 239 deletions(-) create mode 100644 dev-tools/visual-review/browser_trial.ps1 create mode 100644 dev-tools/visual-review/tests/test_browser_trial.ps1 create mode 100644 docs/project/stacked-integration-ledger.md diff --git a/crates/creature-kernel-cli/src/provisional_form_inspection.rs b/crates/creature-kernel-cli/src/provisional_form_inspection.rs index 5867173..8cbf1fd 100644 --- a/crates/creature-kernel-cli/src/provisional_form_inspection.rs +++ b/crates/creature-kernel-cli/src/provisional_form_inspection.rs @@ -9,7 +9,7 @@ use creature_kernel_core::body_document::{ResourceProfile, Status as AdmissionStatus}; use creature_kernel_core::frame::RigidTransform; -use creature_kernel_core::numeric::{NormalizedBinary64, decimal_to_binary64}; +use creature_kernel_core::numeric::NormalizedBinary64; use creature_kernel_core::provisional_form_preview::{ MAX_PROVISIONAL_PERMILLE, ProvisionalFormPreview, ProvisionalFormPreviewError, ProvisionalPlacementFailureKind, ProvisionalShape, ProvisionalSourceFailureKind, @@ -3271,6 +3271,7 @@ fn cli_diagnostic(code: &str, message: impl Into) -> Value { #[cfg(test)] mod tests { use super::*; + use creature_kernel_core::numeric::decimal_to_binary64; use creature_kernel_core::provisional_json::{Value, json}; fn example() -> Vec { diff --git a/dev-tools/visual-review/README.md b/dev-tools/visual-review/README.md index ec64ff0..af2fbcc 100644 --- a/dev-tools/visual-review/README.md +++ b/dev-tools/visual-review/README.md @@ -36,11 +36,17 @@ listener; OS, WSL, container, and firewall forwarding are outside its scope and may still be required for another device to connect. Do not enable this mode on an untrusted network. -Within one expanded image comparison, switching between that group's items by -click, Previous/Next, or Left/Right preserves the current zoom and pan so paired -images remain directly comparable. Closing the comparison and opening a -different group starts from its own fitted view; viewport state does not cross -group boundaries. +Within one expanded image comparison, the Switch model group control uses a +non-empty `metadata.comparison_key` and changes to the unique matching item in +the next eligible group. Previous/Next stays within the current published pack; +Left/Right switches to the older/newer published pack containing the unique +item with the exact non-empty `metadata.comparison_identity`. Missing identities +are skipped and ambiguous matches stop with an explanation. Successful group +and pack image replacements preserve the current zoom and pan; a failed image +or pack load leaves the displayed image, pack context, viewport, and focus in +place. Pending group or pack transitions disable within-pack controls and image +activation until the replacement commits atomically. Closing the comparison and +opening another group starts from that group's fitted view. For a structural-only review, build the checked-in CLI and publish the checked-in biped example through the bounded wrapper: @@ -192,31 +198,49 @@ refuses to overwrite an existing session. ## Windows browser/CDP fallback -Use the T3 collaborative preview first for browser navigation, inspection, -interaction, screenshots, and recordings. If it is unavailable and a Windows -Chrome/CDP fallback is required, send a readable PowerShell script through the -stdin-only launcher: - -```bash -dev-tools/visual-review/powershell-stdin.sh <<'POWERSHELL' -$ErrorActionPreference = 'Stop' -Invoke-RestMethod -Uri 'http://127.0.0.1:9222/json/version' | - ConvertTo-Json -Depth 4 -POWERSHELL +Browser navigation, interaction, screenshots, and recordings for the current +comparison-gallery trial are stopped. The direct invocation incident supplied +an empty profile and debug port `0` to Chrome (recorded PID `8932`) because the +WSL environment variables were absent; later UNC-profile attempts on ports +`9230`, `9231`, and `9232` also exited. Main found no matching task processes +or listeners, and did not touch an ordinary Chrome process or tab because its +provenance was unknown. Popup text was not captured. + +The supported fallback now begins with a readable, non-launching preflight: + +```powershell +& .\dev-tools\visual-review\browser_trial.ps1 ` + -BrowserPath 'C:\Program Files\Google\Chrome\Application\chrome.exe' ` + -ProfilePath 'C:\Temp\pr127-gallery-task-001' ` + -DebugPort 9234 ``` -The launcher accepts no arguments and invokes `powershell.exe` with exactly -`-NoProfile -NonInteractive -File -`; stdin is forwarded unchanged. Do not use -`-EncodedCommand`, Base64, or another obfuscated payload. Opaque automation can -be blocked or misclassified and then surface as a misleading launch error. -Keeping the script readable preserves inspection and diagnosis. +The default `Plan` mode validates an explicit native Windows `.exe` path, a +fresh non-empty absolute profile directory, and a debug port from `1` through +`65535`, then prints the exact isolated command without starting a process. +It does not read WSL environment variables, search for an executable, use an +ordinary profile, or accept UNC/WSL paths. `-Mode Launch` is the explicit launch +path; it requires the same validation, uses `--headless=new`, `--noerrdialogs`, +`--user-data-dir`, and loopback-only remote debugging, and emits a command/PID/ +ownership receipt for cleanup. Keep the complete invocation in one PowerShell +script scope so a validation error exits before any later stdin statement can +run. The launch path was not exercised in this repair. + +The stdin-only launcher accepts no arguments and invokes `powershell.exe` with +exactly `-NoProfile -NonInteractive -File -`; stdin is forwarded unchanged. +Do not use `-EncodedCommand`, Base64, or an obfuscated payload. The Windows +non-intrusion property is not proven by this preflight. A future real trial +needs separate evidence and an explicit cleanup receipt. Do not rediscover or depend on a host-local `ck-playwright-node` installation: it is not repository-owned and its CommonJS/ESM resolution behavior is not a -supported workflow. Use T3, or the readable PowerShell/CDP fallback above. If -the browser route rejects a native WSL `file:///home/...` workspace URI before -launch, report that failure once and switch to the fallback; retrying the same -route supplies no new evidence. +supported workflow. Prefer an already-available isolated route. A native WSL +`file:///home/...` workspace rejection stops that route; it does not authorize +an automatic Windows fallback or retry. Automated testing must create no visible +desktop windows, tabs, consoles, focus changes, prompts, or popups. Establish +that property and fresh-profile isolation before a real invocation. If no +small, reliable method is available, defer real-browser coverage and report +the limitation rather than building new launcher infrastructure. For automated comparison-gallery trials, use the control's exact accessible name (for example `Show next image`) when roles overlap. Before a coordinate diff --git a/dev-tools/visual-review/browser_trial.ps1 b/dev-tools/visual-review/browser_trial.ps1 new file mode 100644 index 0000000..ec666cd --- /dev/null +++ b/dev-tools/visual-review/browser_trial.ps1 @@ -0,0 +1,185 @@ +[CmdletBinding()] +param( + [string]$BrowserPath, + [string]$ProfilePath, + [string]$DebugPort = '0', + [string]$Mode = 'Plan', + [switch]$Library +) + +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' + +function Assert-NativeWindowsLiteralPath { + param( + [string]$Value, + [string]$Name, + [switch]$Profile + ) + + if ([string]::IsNullOrWhiteSpace($Value)) { + throw "$Name is required and must be a non-empty native Windows path" + } + if ($Value -match '[*?\[\]"]') { + throw "$Name must be an explicit literal path without wildcards or quotes" + } + if ($Value -match '^\\\\') { + throw "$Name must not be a UNC or WSL path" + } + if ($Value -notmatch '^[A-Za-z]:[\\/]') { + throw "$Name must be an absolute native Windows path such as C:\Temp\name" + } + if ($Value -match '(^|[\\/])\.\.?([\\/]|$)') { + throw "$Name must not contain relative path components" + } + if ($Profile -and $Value -match '^[A-Za-z]:[\\/]$') { + throw "$Name must identify a new profile directory, not a drive root" + } +} + +function ConvertTo-WindowsArgument { + param([string]$Value) + + if ($Value -notmatch '\s') { + return $Value + } + $escaped = $Value -replace '(\\*)$', '$1$1' + return '"' + $escaped + '"' +} + +function ConvertTo-WindowsArgumentLine { + param([string[]]$Arguments) + + return (($Arguments | ForEach-Object { + ConvertTo-WindowsArgument -Value $_ + }) -join ' ') +} + +function ConvertTo-WindowsCommandLine { + param( + [string]$Executable, + [string[]]$Arguments + ) + + $argumentLine = ConvertTo-WindowsArgumentLine -Arguments $Arguments + return ((ConvertTo-WindowsArgument -Value $Executable) + ' ' + $argumentLine) +} + +function Invoke-BrowserTrial { + [CmdletBinding()] + param( + [string]$BrowserPath, + [string]$ProfilePath, + [int]$DebugPort = 0, + [ValidateSet('Plan', 'Launch')] + [string]$Mode = 'Plan', + [scriptblock]$ProcessStarter, + [scriptblock]$ProfileExists, + [scriptblock]$ExecutableExists + ) + + Assert-NativeWindowsLiteralPath -Value $BrowserPath -Name 'BrowserPath' + if ($BrowserPath -notmatch '(?i)\.exe$') { + throw 'BrowserPath must name an explicit .exe file' + } + Assert-NativeWindowsLiteralPath -Value $ProfilePath -Name 'ProfilePath' -Profile + if ($DebugPort -lt 1 -or $DebugPort -gt 65535) { + throw 'DebugPort must be an integer from 1 through 65535' + } + + if ($null -eq $ProfileExists) { + $ProfileExists = { + param([string]$Path) + Test-Path -LiteralPath $Path + } + } + if (& $ProfileExists $ProfilePath) { + throw "ProfilePath already exists; provide a fresh task-owned directory: $ProfilePath" + } + + $arguments = @( + '--headless=new' + '--noerrdialogs' + '--no-first-run' + '--no-default-browser-check' + '--remote-debugging-address=127.0.0.1' + "--remote-debugging-port=$DebugPort" + "--user-data-dir=$ProfilePath" + 'about:blank' + ) + $argumentLine = ConvertTo-WindowsArgumentLine -Arguments $arguments + $command = ConvertTo-WindowsCommandLine -Executable $BrowserPath -Arguments $arguments + $plan = [ordered]@{ + mode = 'plan' + browser = $BrowserPath + profile = $ProfilePath + cdp_port = $DebugPort + arguments = $arguments + argument_line = $argumentLine + command = $command + launch = $false + } + + if ($Mode -eq 'Plan') { + return [pscustomobject]$plan + } + + if ($null -eq $ExecutableExists) { + $ExecutableExists = { + param([string]$Path) + Test-Path -LiteralPath $Path -PathType Leaf + } + } + if (-not (& $ExecutableExists $BrowserPath)) { + throw "BrowserPath does not exist as a file: $BrowserPath" + } + if ($null -eq $ProcessStarter) { + $ProcessStarter = { + param( + [string]$Executable, + [string]$ArgumentLine + ) + Start-Process -FilePath $Executable -ArgumentList $ArgumentLine -PassThru + } + } + + $handoff = @(& $ProcessStarter $BrowserPath $argumentLine) + if ($handoff.Count -ne 1 -or $null -eq $handoff[0]) { + throw 'Browser launch did not return exactly one owned process handle' + } + $idProperty = $handoff[0].PSObject.Properties['Id'] + $processId = 0 + if ($null -eq $idProperty -or -not [int]::TryParse([string]$idProperty.Value, [ref]$processId) -or $processId -lt 1) { + throw 'Browser launch returned no valid process ID; refusing an unowned handoff' + } + + $receipt = [ordered]@{ + mode = 'launch' + browser = $BrowserPath + profile = $ProfilePath + cdp_port = $DebugPort + arguments = $arguments + argument_line = $argumentLine + command = $command + pid = $processId + ownership = [ordered]@{ + owner = 'visual-review browser_trial.ps1 task' + pid = $processId + cleanup = 'Before termination, verify the current PID, executable, and profile against this receipt; do not terminate by PID alone.' + } + } + return [pscustomobject]$receipt +} + +if (-not $Library -and $MyInvocation.InvocationName -ne '.') { + & { + try { + Invoke-BrowserTrial -BrowserPath $BrowserPath -ProfilePath $ProfilePath -DebugPort $DebugPort -Mode $Mode | + ConvertTo-Json -Depth 6 + } + catch { + Write-Error $_ -ErrorAction Continue + $Host.SetShouldExit(1) + } + } +} diff --git a/dev-tools/visual-review/static/app.js b/dev-tools/visual-review/static/app.js index a5078ff..f39e815 100644 --- a/dev-tools/visual-review/static/app.js +++ b/dev-tools/visual-review/static/app.js @@ -123,6 +123,91 @@ return description ? title + " — " + description : title; } + function imageComparisonKey(item) { + if (!isObject(item) || !isObject(item.metadata) || typeof item.metadata.comparison_key !== "string") { + return null; + } + var key = item.metadata.comparison_key.trim(); + return key ? key : null; + } + + function imageComparisonIdentity(item) { + if (!isObject(item) || !isObject(item.metadata) || typeof item.metadata.comparison_identity !== "string") { + return null; + } + var identity = item.metadata.comparison_identity; + if (!identity || identity.trim() !== identity) { + return null; + } + return identity; + } + + function packContextLabel(pack) { + if (!pack) { + return ""; + } + var label = pack.title || pack.id || "Current review"; + if (pack.published_at) { + var published = new Date(pack.published_at); + label += " · Published " + (Number.isNaN(published.getTime()) ? pack.published_at : published.toLocaleString("en-NZ")); + } + return label; + } + + function findPackImage(review, identity) { + if (!review || !Array.isArray(review.groups) || identity === null) { + return { status: "missing" }; + } + var matches = []; + review.groups.forEach(function (group) { + (group.items || []).forEach(function (item, itemIndex) { + if (imageComparisonIdentity(item) === identity) { + matches.push({ groupId: group.id, itemIndex: itemIndex }); + } + }); + }); + if (matches.length === 0) { + return { status: "missing" }; + } + if (matches.length !== 1) { + return { status: "ambiguous" }; + } + return { status: "match", groupId: matches[0].groupId, itemIndex: matches[0].itemIndex }; + } + + function imageItemsByGroupForReview(review) { + var imageItemsByGroup = {}; + review.groups.forEach(function (group) { + imageItemsByGroup[group.id] = group.items.map(function (groupItem) { + var imageItem = {}; + Object.keys(groupItem).forEach(function (key) { imageItem[key] = groupItem[key]; }); + imageItem.source = "/api/reviews/" + encodeURIComponent(review.id) + "/assets/" + groupItem.image.substring("assets/".length).split("/").map(encodeURIComponent).join("/"); + return imageItem; + }); + }); + return imageItemsByGroup; + } + + function comparisonGroupsFor(review, key, imageItemsByGroup) { + if (key === null) { + return []; + } + return review.groups.map(function (group) { + var items = imageItemsByGroup[group.id] || []; + var matchingIndexes = []; + items.forEach(function (item, index) { + if (imageComparisonKey(item) === key) { + matchingIndexes.push(index); + } + }); + return matchingIndexes.length !== 1 ? null : { + groupId: group.id, + items: items, + itemIndex: matchingIndexes[0] + }; + }).filter(function (group) { return group !== null; }); + } + function subjectContextBlock(context) { if (!context) { return null; @@ -3764,6 +3849,12 @@ } function openImage(items, selectedIndex) { + var comparisonResolver = items.comparisonResolver; + var packNavigation = items.packNavigation || null; + var packContext = items.packContext || null; + var initialGroupId = items.initialGroupId; + var activeGroupId = initialGroupId || null; + var comparisonGroups = []; var returnFocus = document.activeElement; var initialIndex = Math.max(0, Math.min(items.length - 1, selectedIndex || 0)); var dialog = node("dialog", null, "image-dialog"); @@ -3772,6 +3863,11 @@ dialog.setAttribute("aria-labelledby", "image-dialog-title"); var header = node("header", null, "image-dialog-header"); header.appendChild(heading); + var packContextLine = node("div", null, "image-pack-context"); + var packLabel = node("span", "", "image-pack-context-label"); + packLabel.setAttribute("aria-live", "polite"); + packLabel.setAttribute("aria-label", "Current published pack"); + packContextLine.appendChild(packLabel); var controls = node("div", null, "image-dialog-controls"); var previous = node("button", "Previous", "image-control image-navigation-control"); @@ -3780,6 +3876,17 @@ var next = node("button", "Next", "image-control image-navigation-control"); next.type = "button"; next.setAttribute("aria-label", "Show next image"); + var switchGroup = node("button", "Switch model group", "image-control image-navigation-control"); + switchGroup.type = "button"; + switchGroup.setAttribute("aria-label", "Switch to the same pose or view in another model group"); + var older = node("button", "Older", "image-control image-navigation-control"); + older.type = "button"; + older.setAttribute("aria-label", "Show the same image in an older published pack"); + older.setAttribute("aria-keyshortcuts", "ArrowLeft"); + var newer = node("button", "Newer", "image-control image-navigation-control"); + newer.type = "button"; + newer.setAttribute("aria-label", "Show the same image in a newer published pack"); + newer.setAttribute("aria-keyshortcuts", "ArrowRight"); var zoomOut = node("button", "Zoom out", "image-control"); zoomOut.type = "button"; zoomOut.setAttribute("aria-label", "Zoom out of image"); @@ -3796,6 +3903,9 @@ positionLabel.setAttribute("role", "status"); controls.appendChild(previous); controls.appendChild(next); + controls.appendChild(switchGroup); + controls.appendChild(older); + controls.appendChild(newer); controls.appendChild(zoomOut); controls.appendChild(zoomIn); controls.appendChild(fit); @@ -3808,6 +3918,7 @@ header.appendChild(controls); header.appendChild(close); dialog.appendChild(header); + dialog.appendChild(packContextLine); var viewport = node("div", null, "image-viewport"); viewport.tabIndex = 0; @@ -3817,7 +3928,7 @@ var image = null; viewport.appendChild(canvas); dialog.appendChild(viewport); - dialog.appendChild(node("p", "Use Previous/Next, the Left/Right arrow keys, click the displayed image, or drag it to compare and pan items. Escape closes the viewer.", "image-dialog-instructions")); + dialog.appendChild(node("p", "Use Previous/Next buttons for items within this pack. Left/Right arrow keys switch to the older/newer matching pack image. Click the displayed image or drag it to compare and pan items. Escape closes the viewer.", "image-dialog-instructions")); var MIN_SCALE = 0.1; var MAX_SCALE = 8; @@ -3827,6 +3938,12 @@ var cleaned = false; var requestedIndex = initialIndex; var displayedIndex = -1; + var displayedItem = null; + var pendingGroupTransition = null; + var pendingPackTransition = null; + var pendingPackSearch = false; + var packSearchToken = 0; + var packNavigationStops = {}; var imageLoadToken = 0; var focusRestoreFrame = null; var suppressNextImageClick = false; @@ -3910,16 +4027,37 @@ zoomTo(scale * (event.deltaY < 0 ? ZOOM_FACTOR : 1 / ZOOM_FACTOR), anchorX, anchorY); } + function activatePackButton(button) { + if (button.disabled) { + return; + } + button.click(); + } + + function isEditableKeyTarget(target) { + if (!target) { + return false; + } + var tagName = target.tagName ? target.tagName.toLowerCase() : ""; + return tagName === "input" || tagName === "textarea" || tagName === "select" || target.isContentEditable; + } + function onKeyDown(event) { if (event.key === "Escape") { event.preventDefault(); closeImageDialog(); } else if (event.key === "ArrowLeft") { + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || isEditableKeyTarget(event.target)) { + return; + } event.preventDefault(); - showItem(requestedIndex - 1, image !== null && document.activeElement === image); + activatePackButton(older); } else if (event.key === "ArrowRight") { + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || isEditableKeyTarget(event.target)) { + return; + } event.preventDefault(); - showItem(requestedIndex + 1, image !== null && document.activeElement === image); + activatePackButton(newer); } else if (event.key === "+" || event.key === "=" || event.key === "Add") { event.preventDefault(); zoomBy(ZOOM_FACTOR); @@ -3973,8 +4111,15 @@ }); } + function imageNavigationBlocked() { + return pendingGroupTransition !== null || pendingPackSearch || pendingPackTransition !== null; + } + function updateImageControls() { var disabled = image === null; + var navigationBlocked = imageNavigationBlocked(); + previous.disabled = navigationBlocked || items.length < 2; + next.disabled = navigationBlocked || items.length < 2; zoomOut.disabled = disabled; zoomIn.disabled = disabled; fit.disabled = disabled; @@ -3984,27 +4129,107 @@ if (displayedIndex < 0) { return "No image displayed"; } - var displayedItem = items[displayedIndex]; - return "Item " + (displayedIndex + 1) + " of " + items.length + ": " + displayedItem.title; + var item = displayedItem || items[displayedIndex]; + return "Item " + (displayedIndex + 1) + " of " + items.length + ": " + item.title; } function updateDisplayedState(statusText) { var headingIndex = displayedIndex >= 0 ? displayedIndex : requestedIndex; heading.textContent = headingIndex >= 0 && headingIndex < items.length ? items[headingIndex].title : "Image comparison"; + packLabel.textContent = packContextLabel(packContext); positionLabel.textContent = displayedPositionText() + (statusText ? " · " + statusText : ""); } + function displayedPackMatch() { + var identity = imageComparisonIdentity(displayedItem); + if (!packContext || !packContext.review || identity === null) { + return null; + } + var match = findPackImage(packContext.review, identity); + if (match.status !== "match" || match.groupId !== activeGroupId || match.itemIndex !== displayedIndex) { + return null; + } + return { identity: identity, match: match }; + } + + function packNavigationStopKey(direction, identity) { + return packContext.id + "\u0000" + identity + "\u0000" + direction; + } + + function rememberPackNavigationStop(direction, identity, status) { + packNavigationStops[packNavigationStopKey(direction, identity)] = status; + } + + function hasPackNavigationStop(direction, identity) { + return Object.prototype.hasOwnProperty.call(packNavigationStops, packNavigationStopKey(direction, identity)); + } + + function packCandidates(direction) { + if (!packNavigation || !Array.isArray(packNavigation.sessions) || !packContext) { + return []; + } + var currentIndex = packNavigation.sessions.findIndex(function (session) { + return session.id === packContext.id; + }); + if (currentIndex < 0) { + return []; + } + var step = direction === "older" ? 1 : -1; + var candidates = []; + for (var index = currentIndex + step; index >= 0 && index < packNavigation.sessions.length; index += step) { + var session = packNavigation.sessions[index]; + if (!session.kind || session.kind === "image") { + candidates.push(session); + } + } + return candidates; + } + + function refreshComparisonNavigation() { + comparisonGroups = typeof comparisonResolver === "function" && displayedItem ? comparisonResolver(displayedItem) : []; + var activeGroupEligible = comparisonGroups.some(function (group) { + return group.groupId === activeGroupId; + }); + var navigationBlocked = imageNavigationBlocked(); + switchGroup.disabled = navigationBlocked || pendingGroupTransition !== null || comparisonGroups.length < 2 || !activeGroupEligible; + var currentPack = displayedPackMatch(); + var hasIdentity = currentPack !== null; + older.disabled = navigationBlocked || !hasIdentity || hasPackNavigationStop("older", currentPack ? currentPack.identity : "") || packCandidates("older").length === 0; + newer.disabled = navigationBlocked || !hasIdentity || hasPackNavigationStop("newer", currentPack ? currentPack.identity : "") || packCandidates("newer").length === 0; + } + function showItem(index, focusImage) { - if (!items.length) { + var targetItems = arguments[2] || items; + var targetGroup = arguments[3] || null; + var targetPack = arguments[4] || null; + var isPackTransition = targetPack !== null && targetItems !== items; + var isGroupTransition = !isPackTransition && targetGroup !== null && targetItems !== items; + if (!isGroupTransition && !isPackTransition && imageNavigationBlocked()) { return; } - requestedIndex = (index + items.length) % items.length; + if (!targetItems.length) { + return; + } + requestedIndex = (index + targetItems.length) % targetItems.length; var targetIndex = requestedIndex; - var item = items[targetIndex]; + var item = targetItems[targetIndex]; + var groupTransition = isGroupTransition ? { groupId: targetGroup.groupId, items: targetItems } : null; + var packTransition = isPackTransition ? { groupId: targetGroup.groupId, items: targetItems, pack: targetPack } : null; + if (groupTransition) { + pendingGroupTransition = groupTransition; + switchGroup.disabled = true; + } + if (packTransition) { + pendingPackTransition = packTransition; + } + if (groupTransition || packTransition) { + refreshComparisonNavigation(); + } var loadToken = ++imageLoadToken; - previous.disabled = items.length < 2; - next.disabled = items.length < 2; - if (image && targetIndex === displayedIndex) { + var navigationBlocked = imageNavigationBlocked(); + previous.disabled = navigationBlocked || targetItems.length < 2; + next.disabled = navigationBlocked || targetItems.length < 2; + if (!isGroupTransition && image && displayedItem === item) { updateDisplayedState(""); if (focusImage) { focusPreservingViewport(image); @@ -4077,14 +4302,21 @@ releasePointerCapture(event); } function showNextImage(event) { - if (event.type === "click" && suppressNextImageClick) { + if (event.type === "keydown" && event.key !== "Enter" && event.key !== " ") { + return; + } + if (imageNavigationBlocked()) { suppressNextImageClick = false; pendingClickViewportState = null; event.preventDefault(); event.stopPropagation(); return; } - if (event.type === "keydown" && event.key !== "Enter" && event.key !== " ") { + if (event.type === "click" && suppressNextImageClick) { + suppressNextImageClick = false; + pendingClickViewportState = null; + event.preventDefault(); + event.stopPropagation(); return; } if (event.type === "keydown") { @@ -4109,15 +4341,35 @@ if (cleaned || loadToken !== imageLoadToken || requestedIndex !== targetIndex) { return; } + if (isGroupTransition && pendingGroupTransition !== groupTransition) { + return; + } + if (isPackTransition && pendingPackTransition !== packTransition) { + return; + } var viewportState = image ? captureViewport() : null; if (image) { canvas.replaceChild(nextImage, image); } else { canvas.appendChild(nextImage); } + if (isGroupTransition) { + items = targetItems; + activeGroupId = groupTransition.groupId; + pendingGroupTransition = null; + } + if (isPackTransition) { + items = targetItems; + activeGroupId = packTransition.groupId; + comparisonResolver = packTransition.pack.comparisonResolver; + packNavigation = packTransition.pack.packNavigation; + packContext = packTransition.pack.packContext; + pendingPackTransition = null; + } image = nextImage; displayedIndex = targetIndex; requestedIndex = targetIndex; + displayedItem = item; updateDisplayedState(""); updateImageControls(); if (viewportState) { @@ -4128,20 +4380,115 @@ if (focusImage) { focusPreservingViewport(image); } + refreshComparisonNavigation(); }); nextImage.addEventListener("error", function () { if (cleaned || loadToken !== imageLoadToken || requestedIndex !== targetIndex) { return; } + if (isGroupTransition && pendingGroupTransition !== groupTransition) { + return; + } + if (isPackTransition && pendingPackTransition !== packTransition) { + return; + } + if (isGroupTransition) { + pendingGroupTransition = null; + } + if (isPackTransition) { + pendingPackTransition = null; + } if (displayedIndex >= 0) { requestedIndex = displayedIndex; } updateDisplayedState("Could not load item " + (targetIndex + 1) + ": " + item.title); updateImageControls(); + refreshComparisonNavigation(); }); nextImage.src = item.source; } + function loadPackDirection(direction) { + var currentPack = displayedPackMatch(); + if (pendingPackSearch || !packNavigation || !packContext || currentPack === null) { + return; + } + var identity = currentPack.identity; + if (hasPackNavigationStop(direction, identity)) { + return; + } + var candidates = packCandidates(direction); + if (!candidates.length) { + return; + } + var token = ++packSearchToken; + pendingPackSearch = true; + updateImageControls(); + refreshComparisonNavigation(); + + function inspectCandidate(index) { + if (cleaned || token !== packSearchToken) { + return; + } + if (index >= candidates.length) { + rememberPackNavigationStop(direction, identity, "missing"); + pendingPackSearch = false; + updateDisplayedState("No matching image in available packs"); + updateImageControls(); + refreshComparisonNavigation(); + return; + } + var session = candidates[index]; + api("/api/reviews/" + encodeURIComponent(session.id)).then(function (data) { + if (cleaned || token !== packSearchToken) { + return; + } + var review = data && data.review ? data.review : data; + var match = findPackImage(review, identity); + if (match.status === "missing") { + inspectCandidate(index + 1); + return; + } + if (match.status === "ambiguous") { + rememberPackNavigationStop(direction, identity, "ambiguous"); + pendingPackSearch = false; + updateDisplayedState("Ambiguous matching image; navigation stopped"); + updateImageControls(); + refreshComparisonNavigation(); + return; + } + var targetGroups = imageItemsByGroupForReview(review); + var targetItems = targetGroups[match.groupId].slice(); + targetItems.comparisonResolver = function (item) { + return comparisonGroupsFor(review, imageComparisonKey(item), targetGroups); + }; + targetItems.packNavigation = packNavigation; + targetItems.packContext = { id: review.id, title: review.title, published_at: session.published_at, review: review }; + pendingPackSearch = false; + showItem( + match.itemIndex, + true, + targetItems, + { groupId: match.groupId }, + { + comparisonResolver: targetItems.comparisonResolver, + packNavigation: packNavigation, + packContext: targetItems.packContext, + }, + ); + }).catch(function (error) { + if (cleaned || token !== packSearchToken) { + return; + } + pendingPackSearch = false; + updateDisplayedState("Could not load pack: " + error.message); + updateImageControls(); + refreshComparisonNavigation(); + }); + } + inspectCandidate(0); + } + function cleanup() { if (cleaned) { return; @@ -4172,8 +4519,33 @@ } close.addEventListener("click", closeImageDialog); - previous.addEventListener("click", function () { showItem(requestedIndex - 1, false); }); - next.addEventListener("click", function () { showItem(requestedIndex + 1, false); }); + previous.addEventListener("click", function () { + if (imageNavigationBlocked()) { + return; + } + showItem(requestedIndex - 1, false); + }); + next.addEventListener("click", function () { + if (imageNavigationBlocked()) { + return; + } + showItem(requestedIndex + 1, false); + }); + older.addEventListener("click", function () { loadPackDirection("older"); }); + newer.addEventListener("click", function () { loadPackDirection("newer"); }); + switchGroup.addEventListener("click", function () { + if (comparisonGroups.length < 2) { + return; + } + var currentGroupIndex = comparisonGroups.findIndex(function (group) { + return group.groupId === activeGroupId; + }); + if (currentGroupIndex < 0) { + return; + } + var target = comparisonGroups[(currentGroupIndex + 1) % comparisonGroups.length]; + showItem(target.itemIndex, true, target.items, target); + }); zoomOut.addEventListener("click", function () { zoomBy(1 / ZOOM_FACTOR); }); zoomIn.addEventListener("click", function () { zoomBy(ZOOM_FACTOR); }); fit.addEventListener("click", fitToViewport); @@ -4193,6 +4565,7 @@ } window.addEventListener("resize", onResize); updateImageControls(); + refreshComparisonNavigation(); showItem(requestedIndex, false); } @@ -4237,6 +4610,16 @@ } var form = node("form"); form.addEventListener("submit", function (event) { event.preventDefault(); saveReview(review, form); }); + var imageItemsByGroup = imageItemsByGroupForReview(review); + var sessionIndex = Array.isArray(data.session_index) ? data.session_index : []; + var currentSession = sessionIndex.find(function (session) { return session.id === review.id; }); + var packNavigation = { sessions: sessionIndex }; + var packContext = { + id: review.id, + title: review.title, + published_at: currentSession ? currentSession.published_at : null, + review: review, + }; review.groups.forEach(function (group) { var section = node("section", null, "review-group"); section.dataset.groupId = group.id; @@ -4247,12 +4630,7 @@ section.appendChild(node("p", group.description)); } var cards = node("div", null, "option-grid"); - var imageItems = group.items.map(function (groupItem) { - var imageItem = {}; - Object.keys(groupItem).forEach(function (key) { imageItem[key] = groupItem[key]; }); - imageItem.source = "/api/reviews/" + encodeURIComponent(review.id) + "/assets/" + groupItem.image.substring("assets/".length).split("/").map(encodeURIComponent).join("/"); - return imageItem; - }); + var imageItems = imageItemsByGroup[group.id]; var selected = (oldResponse && oldResponse.selections[group.id]) || []; group.items.forEach(function (item, itemIndex) { var card = node("article", null, "option-card"); @@ -4265,7 +4643,16 @@ image.alt = imageLabel; image.loading = "lazy"; imageButton.appendChild(image); - imageButton.addEventListener("click", function () { openImage(imageItems, itemIndex); }); + imageButton.addEventListener("click", function () { + imageItems = imageItems.slice(); + imageItems.comparisonResolver = function (item) { + return comparisonGroupsFor(review, imageComparisonKey(item), imageItemsByGroup); + }; + imageItems.packNavigation = packNavigation; + imageItems.packContext = packContext; + imageItems.initialGroupId = group.id; + openImage(imageItems, itemIndex); + }); card.appendChild(imageButton); var body = node("div", null, "option-body"); var itemTitle = node("h3", item.title); @@ -4397,7 +4784,16 @@ addNotice(app, "Not found", "error"); return; } - api("/api/reviews/" + encodeURIComponent(decodeURIComponent(match[1]))).then(renderReview).catch(function (error) { clear(app); addNotice(app, error.message, "error"); }); + api("/api/reviews/" + encodeURIComponent(decodeURIComponent(match[1]))).then(function (data) { + var loadedReview = data && data.review ? data.review : data; + if (!loadedReview || loadedReview.kind === "structure" || loadedReview.kind === "provisional-form") { + return renderReview(data); + } + return api("/api/sessions").catch(function () { return { sessions: [] }; }).then(function (index) { + data.session_index = Array.isArray(index.sessions) ? index.sessions : []; + return renderReview(data); + }); + }).catch(function (error) { clear(app); addNotice(app, error.message, "error"); }); } load(); diff --git a/dev-tools/visual-review/static/style.css b/dev-tools/visual-review/static/style.css index 92c69c6..69f8e17 100644 --- a/dev-tools/visual-review/static/style.css +++ b/dev-tools/visual-review/static/style.css @@ -58,9 +58,10 @@ button.primary { border-color: #3387d5; background: #1768ad; color: #fff; } .error { color: #ffadb7; background: #351820; } .image-dialog { display: flex; flex-direction: column; gap: 0.55rem; width: 96vw; height: 94vh; max-width: 96vw; max-height: 94vh; padding: 0.7rem; overflow: hidden; border: 0; border-radius: 0.5rem; background: #101820; } .image-dialog::backdrop { background: #081018c9; } -.image-dialog-header { display: flex; flex: 0 0 auto; align-items: center; flex-wrap: nowrap; gap: 0.7rem; min-width: 0; } +.image-dialog-header { display: flex; flex: 0 0 auto; align-items: center; flex-wrap: wrap; gap: 0.7rem; min-width: 0; } .image-dialog-title { min-width: 0; flex: 1 1 auto; margin: 0; overflow: hidden; font-size: 1.05rem; text-overflow: ellipsis; white-space: nowrap; } -.image-dialog-controls { display: flex; flex: 0 0 auto; align-items: center; justify-content: center; flex-wrap: nowrap; gap: 0.45rem; margin-left: auto; white-space: nowrap; } +.image-dialog-controls { display: flex; flex: 1 1 40rem; align-items: center; justify-content: flex-start; flex-wrap: wrap; gap: 0.45rem; min-width: 0; margin-left: auto; white-space: normal; } +.image-pack-context { flex: 0 0 auto; width: 100%; min-width: 0; padding: 0.15rem 0.35rem 0.25rem; color: #d2e3f3; font-size: 0.82rem; line-height: 1.35; overflow-wrap: anywhere; white-space: normal; } .image-control { padding: 0.4rem 0.6rem; font-size: 0.86rem; } .image-navigation-control { border-color: #4b86b6; background: #183149; } .image-scale { min-width: 5.5rem; color: #b7c8d9; font-size: 0.82rem; text-align: center; white-space: nowrap; } @@ -75,9 +76,9 @@ button.primary { border-color: #3387d5; background: #1768ad; color: #fff; } .close-dialog { display: block; margin-left: auto; } @media (max-width: 52rem) { - .image-dialog-header { align-items: flex-start; flex-wrap: wrap; } + .image-dialog-header { align-items: flex-start; } .image-dialog-title { flex-basis: calc(100% - 3rem); } - .image-dialog-controls { order: 3; width: 100%; flex-wrap: wrap; justify-content: flex-start; margin-left: 0; white-space: normal; } + .image-dialog-controls { order: 3; width: 100%; flex-basis: auto; margin-left: 0; } } /* Structural inspection is intentionally read-only and text-only. */ diff --git a/dev-tools/visual-review/tests/test_browser_trial.ps1 b/dev-tools/visual-review/tests/test_browser_trial.ps1 new file mode 100644 index 0000000..220a76c --- /dev/null +++ b/dev-tools/visual-review/tests/test_browser_trial.ps1 @@ -0,0 +1,126 @@ +$ErrorActionPreference = 'Stop' + +$trialPath = Join-Path (Get-Location) 'dev-tools\visual-review\browser_trial.ps1' +if (-not (Test-Path -LiteralPath $trialPath -PathType Leaf)) { + throw "browser_trial.ps1 was not found at $trialPath" +} + +$trialSource = Get-Content -LiteralPath $trialPath -Raw +$testBody = @' +$state = [pscustomobject]@{ + launch_calls = 0 + executable = $null + argument_line = $null +} +$fakeStarter = { + param( + [string]$Executable, + [string]$ArgumentLine + ) + $state.launch_calls++ + $state.executable = $Executable + $state.argument_line = $ArgumentLine + [pscustomobject]@{ Id = 4242 } +} +$profileExists = { + param([string]$Path) + $Path -eq 'C:\Temp\pr127-gallery-existing' +} +$executableExists = { + param([string]$Path) + $true +} +$browser = 'C:\Program Files\Google\Chrome\Application\chrome.exe' +$freshProfile = 'C:\Temp\pr127-gallery-plan-001' + +function Assert-RejectedWithoutLaunch { + param( + [string]$Label, + [string]$Profile, + [int]$Port + ) + + $before = $state.launch_calls + $rejected = $false + try { + Invoke-BrowserTrial -BrowserPath $browser -ProfilePath $Profile -DebugPort $Port -Mode Launch ` + -ProcessStarter $fakeStarter -ProfileExists $profileExists -ExecutableExists $executableExists | Out-Null + } + catch { + $rejected = $true + } + if (-not $rejected) { + throw "$Label was accepted" + } + if ($state.launch_calls -ne $before) { + throw "$Label reached the process starter" + } +} + +Assert-RejectedWithoutLaunch -Label 'empty profile' -Profile '' -Port 9234 +Assert-RejectedWithoutLaunch -Label 'port zero' -Profile $freshProfile -Port 0 +Assert-RejectedWithoutLaunch -Label 'UNC profile' -Profile '\\wsl.localhost\Ubuntu-22.04\tmp\pr127-gallery-unc' -Port 9234 +Assert-RejectedWithoutLaunch -Label 'existing profile' -Profile 'C:\Temp\pr127-gallery-existing' -Port 9234 + +$planProfile = 'C:\Temp\pr127 gallery plan-001' +$plan = Invoke-BrowserTrial -BrowserPath $browser -ProfilePath $planProfile -DebugPort 9234 ` + -ProcessStarter $fakeStarter -ProfileExists $profileExists -ExecutableExists $executableExists +if ($plan.mode -ne 'plan' -or $plan.launch -ne $false) { + throw 'the default mode did not return a non-launch plan' +} +if ($state.launch_calls -ne 0) { + throw 'the default plan invoked the process starter' +} +if ($plan.argument_line -notmatch '"--user-data-dir=C:\\Temp\\pr127 gallery plan-001"') { + throw 'the default plan did not preserve a spaced profile as one quoted argument' +} + +$receipt = Invoke-BrowserTrial -BrowserPath $browser -ProfilePath $planProfile -DebugPort 9234 -Mode Launch ` + -ProcessStarter $fakeStarter -ProfileExists $profileExists -ExecutableExists $executableExists +if ($state.launch_calls -ne 1 -or $receipt.pid -ne 4242) { + throw 'the mocked launch did not return its owned process receipt' +} +if ($state.argument_line -ne $receipt.argument_line -or + $state.argument_line -notmatch '"--user-data-dir=C:\\Temp\\pr127 gallery plan-001"') { + throw 'the mocked launch did not receive the exact quoted plan argument line' +} + +Write-Output 'browser trial validation and mocked launch checks passed' +'@ + +$combined = [scriptblock]::Create($trialSource + "`r`n" + $testBody) +& $combined -Library + +$sentinelInput = @' +$ErrorActionPreference = 'Stop' +$source = Get-Content -LiteralPath '__TRIAL_PATH__' -Raw +$trial = [scriptblock]::Create($source) +& $trial -BrowserPath 'C:\Program Files\Google\Chrome\Application\chrome.exe' -ProfilePath '' -DebugPort 9234 +Write-Output 'FAIL_CLOSED_SENTINEL' +'@.Replace('__TRIAL_PATH__', $trialPath) +$sentinelOutput = $sentinelInput | & powershell.exe -NoProfile -NonInteractive -File - 2>&1 +$sentinelExit = $LASTEXITCODE +if ($sentinelExit -eq 0) { + throw 'invalid stdin invocation returned a zero exit status' +} +if ($sentinelOutput -match 'FAIL_CLOSED_SENTINEL') { + throw 'invalid stdin invocation allowed a following statement to run' +} + +$bindingInput = @' +$ErrorActionPreference = 'Stop' +$source = Get-Content -LiteralPath '__TRIAL_PATH__' -Raw +$trial = [scriptblock]::Create($source) +& $trial -BrowserPath 'C:\Program Files\Google\Chrome\Application\chrome.exe' -ProfilePath 'C:\Temp\pr127-gallery-binding' -DebugPort nope +Write-Output 'BINDING_SENTINEL' +'@.Replace('__TRIAL_PATH__', $trialPath) +$bindingOutput = $bindingInput | & powershell.exe -NoProfile -NonInteractive -File - 2>&1 +$bindingExit = $LASTEXITCODE +if ($bindingExit -eq 0) { + throw 'nonnumeric debug port returned a zero exit status' +} +if ($bindingOutput -match 'BINDING_SENTINEL') { + throw 'nonnumeric debug port allowed a following statement to run' +} + +Write-Output 'browser trial fail-closed stdin check passed' diff --git a/dev-tools/visual-review/tests/test_visual_review.py b/dev-tools/visual-review/tests/test_visual_review.py index 4a0c381..6f517fd 100644 --- a/dev-tools/visual-review/tests/test_visual_review.py +++ b/dev-tools/visual-review/tests/test_visual_review.py @@ -1033,15 +1033,15 @@ def test_image_comparator_exposes_group_navigation_and_stale_load_guard(self): css = (HERE / "static" / "style.css").read_text(encoding="utf-8") for contract in ( "function openImage(items, selectedIndex)", - "var imageItems = group.items.map", + "function imageItemsByGroupForReview(review)", "openImage(imageItems, itemIndex);", 'event.key === "ArrowLeft"', 'event.key === "ArrowRight"', "function showItem(index, focusImage)", "function restoreViewport(viewportState)", "function captureViewport()", - "showItem(requestedIndex - 1, image !== null && document.activeElement === image);", - "showItem(requestedIndex + 1, image !== null && document.activeElement === image);", + "activatePackButton(older);", + "activatePackButton(newer);", "showItem(requestedIndex + 1, true);", "showItem(requestedIndex - 1, false);", "showItem(requestedIndex + 1, false);", @@ -1054,8 +1054,13 @@ def test_image_comparator_exposes_group_navigation_and_stale_load_guard(self): "focusPreservingViewport(image);", 'node("button", "Previous"', 'node("button", "Next"', + 'older.setAttribute("aria-keyshortcuts", "ArrowLeft");', + 'newer.setAttribute("aria-keyshortcuts", "ArrowRight");', + 'Use Previous/Next buttons for items within this pack. Left/Right arrow keys switch to the older/newer matching pack image.', + "function activatePackButton(button)", + "function isEditableKeyTarget(target)", + "event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || isEditableKeyTarget(event.target)", "positionLabel.textContent = displayedPositionText()", - 'Use Previous/Next, the Left/Right arrow keys', 'nextImage.addEventListener("click"', 'nextImage.addEventListener("load"', 'nextImage.addEventListener("error"', @@ -1075,14 +1080,307 @@ def test_image_comparator_exposes_group_navigation_and_stale_load_guard(self): for selector in (".image-navigation-control", ".image-position", ".image-dialog-instructions", ".image-dialog img:focus-visible"): self.assertIn(selector, css) - def test_image_comparator_keeps_desktop_header_height_stable(self): + def test_cross_pack_matching_requires_explicit_identity_and_rejects_ambiguity(self): + js = (HERE / "static" / "app.js").read_text(encoding="utf-8") + script = r''' +const fs = require("fs"); +const vm = require("vm"); +const appPath = process.argv[1]; +let source = fs.readFileSync(appPath, "utf8"); +const entrypoint = " load();\n}());"; +source = source.replace(entrypoint, "globalThis.__findPackImage = findPackImage; globalThis.__identity = imageComparisonIdentity;\n}());"); +const context = { document: { getElementById: function () { return null; } }, window: {} }; +vm.runInNewContext(source, context, { filename: appPath }); +const review = JSON.parse(fs.readFileSync(0, "utf8")); +process.stdout.write(JSON.stringify([ + context.__findPackImage(review, "model-v1:human:rest:front-side-rear-three-quarter"), + context.__findPackImage(review, "model-v1:human:missing:front-side-rear-three-quarter"), + context.__findPackImage(review, "model-v1:human:ambiguous:front-side-rear-three-quarter"), + context.__findPackImage(review, "rest"), + context.__identity({metadata: {comparison_identity: " model-v1:human:rest:front-side-rear-three-quarter"}}), + context.__identity({metadata: {comparison_identity: "model-v1:human:rest:front-side-rear-three-quarter"}}) +])); +''' + review = { + "groups": [ + {"id": "human", "items": [{"metadata": {"comparison_identity": "model-v1:human:rest:front-side-rear-three-quarter"}}]}, + {"id": "anthropomorphic", "items": [ + {"metadata": {"comparison_identity": "model-v1:human:ambiguous:front-side-rear-three-quarter"}}, + {"metadata": {"comparison_identity": "model-v1:human:ambiguous:front-side-rear-three-quarter"}}, + ]}, + ] + } + completed = subprocess.run( + ["node", "-e", script, str(HERE / "static" / "app.js")], + input=json.dumps(review), capture_output=True, text=True, check=True, + ) + self.assertEqual(json.loads(completed.stdout), [ + {"status": "match", "groupId": "human", "itemIndex": 0}, + {"status": "missing"}, + {"status": "ambiguous"}, + {"status": "missing"}, + None, + "model-v1:human:rest:front-side-rear-three-quarter", + ]) + self.assertIn("metadata.comparison_identity", js) + self.assertIn("function findPackImage(review, identity)", js) + + def test_cross_pack_navigation_is_modal_atomic_and_uses_displayed_pack_context(self): + js = (HERE / "static" / "app.js").read_text(encoding="utf-8") + for contract in ( + 'node("button", "Older"', + 'node("button", "Newer"', + 'api("/api/sessions")', + 'api("/api/reviews/" + encodeURIComponent(session.id))', + "function loadPackDirection(direction)", + "function packContextLabel(pack)", + "var packNavigation = items.packNavigation || null;", + "var pendingPackTransition = null;", + "var pendingPackSearch = false;", + "var packNavigationStops = {};", + "function displayedPackMatch()", + "function rememberPackNavigationStop(direction, identity, status)", + "function hasPackNavigationStop(direction, identity)", + "rememberPackNavigationStop(direction, identity, \"missing\");", + "rememberPackNavigationStop(direction, identity, \"ambiguous\");", + "pendingGroupTransition !== null || pendingPackSearch || pendingPackTransition !== null", + "packContext.review", + "if (isPackTransition && pendingPackTransition !== packTransition)", + "if (isPackTransition) {\n items = targetItems;", + "packContext = packTransition.pack.packContext;", + 'targetItems.packContext = { id: review.id, title: review.title, published_at: session.published_at, review: review };', + 'updateDisplayedState("Ambiguous matching image; navigation stopped");', + 'updateDisplayedState("No matching image in available packs");', + 'data.session_index = Array.isArray(index.sessions) ? index.sessions : [];', + "var packContextLine = node(\"div\", null, \"image-pack-context\");", + "packContextLine.appendChild(packLabel);", + "dialog.appendChild(packContextLine);", + ): + self.assertIn(contract, js) + self.assertIn("var viewportState = image ? captureViewport() : null;", js) + self.assertIn("restoreViewport(viewportState);", js) + self.assertIn("var returnFocus = document.activeElement", js) css = (HERE / "static" / "style.css").read_text(encoding="utf-8") - self.assertIn("flex-wrap: nowrap", css) + self.assertIn(".image-pack-context", css) + self.assertIn("overflow-wrap: anywhere", css) + self.assertIn("white-space: normal", css) + + def test_pending_group_transition_blocks_within_pack_activation_until_load(self): + js = (HERE / "static" / "app.js").read_text(encoding="utf-8") + script = r''' +const fs = require("fs"); +const vm = require("vm"); +const appPath = process.argv[1]; +let source = fs.readFileSync(appPath, "utf8"); +const entrypoint = " load();\n}());"; +if (source.split(entrypoint).length !== 2) { + throw new Error("unexpected browser app entrypoint"); +} +source = source.replace(entrypoint, " globalThis.__openImage = openImage;\n}());"); + +function Element(tagName) { + this.tagName = tagName.toUpperCase(); + this.children = []; + this.parentNode = null; + this.style = {}; + this.attributes = {}; + this.listeners = {}; + this.className = ""; + this.classList = {add: function () {}, remove: function () {}}; + this.clientWidth = 800; + this.clientHeight = 600; + this.scrollLeft = 0; + this.scrollTop = 0; + this.naturalWidth = 400; + this.naturalHeight = 300; + this.open = false; +} +Element.prototype.appendChild = function (child) { + if (child.parentNode) { + child.parentNode.removeChild(child); + } + this.children.push(child); + child.parentNode = this; + return child; +}; +Element.prototype.removeChild = function (child) { + const index = this.children.indexOf(child); + if (index >= 0) { + this.children.splice(index, 1); + child.parentNode = null; + } + return child; +}; +Element.prototype.replaceChild = function (replacement, child) { + const index = this.children.indexOf(child); + if (index < 0) { + throw new Error("replacement child not found"); + } + if (replacement.parentNode) { + replacement.parentNode.removeChild(replacement); + } + this.children[index] = replacement; + replacement.parentNode = this; + child.parentNode = null; + return child; +}; +Element.prototype.remove = function () { + if (this.parentNode) { + this.parentNode.removeChild(this); + } +}; +Element.prototype.setAttribute = function (name, value) { + this.attributes[name] = String(value); +}; +Element.prototype.getAttribute = function (name) { + return this.attributes[name] || null; +}; +Element.prototype.addEventListener = function (type, listener) { + (this.listeners[type] || (this.listeners[type] = [])).push(listener); +}; +Element.prototype.removeEventListener = function (type, listener) { + this.listeners[type] = (this.listeners[type] || []).filter(function (entry) { return entry !== listener; }); +}; +Element.prototype.dispatchEvent = function (event) { + event.target = this; + event.currentTarget = this; + event.preventDefault = event.preventDefault || function () { event.defaultPrevented = true; }; + event.stopPropagation = event.stopPropagation || function () { event.propagationStopped = true; }; + (this.listeners[event.type] || []).slice().forEach(function (listener) { listener(event); }); + return !event.defaultPrevented; +}; +Element.prototype.click = function () { + this.dispatchEvent({type: "click"}); +}; +Element.prototype.focus = function () { + document.activeElement = this; +}; +Element.prototype.getBoundingClientRect = function () { + return {left: 0, top: 0}; +}; +Element.prototype.showModal = function () { + this.open = true; +}; +Element.prototype.close = function () { + this.open = false; + this.dispatchEvent({type: "close"}); +}; + +const created = []; +const app = new Element("main"); +const document = { + activeElement: app, + body: new Element("body"), + documentElement: {contains: function () { return true; }}, + getElementById: function () { return app; }, + createElement: function (tagName) { + const element = new Element(tagName); + created.push(element); + return element; + }, +}; +document.body.appendChild(app); +const window = { + addEventListener: function () {}, + removeEventListener: function () {}, + requestAnimationFrame: function (callback) { callback(); return 1; }, + cancelAnimationFrame: function () {}, +}; +const context = {document: document, window: window}; +vm.runInNewContext(source, context, {filename: appPath}); + +const current = [ + {title: "Current first", source: "current-first", metadata: {comparison_key: "pose"}}, + {title: "Current second", source: "current-second", metadata: {comparison_key: "other"}}, +]; +const other = [ + {title: "Other first", source: "other-first", metadata: {comparison_key: "other"}}, + {title: "Other second", source: "other-second", metadata: {comparison_key: "other-2"}}, + {title: "Other match", source: "other-match", metadata: {comparison_key: "pose"}}, +]; +const items = current.slice(); +items.initialGroupId = "current"; +items.comparisonResolver = function () { + return [ + {groupId: "current", items: current, itemIndex: 0}, + {groupId: "other", items: other, itemIndex: 2}, + ]; +}; +context.__openImage(items, 0); +const images = function () { + return created.filter(function (element) { return element.tagName === "IMG"; }); +}; +images()[0].dispatchEvent({type: "load"}); +const buttons = function (label) { + return created.find(function (element) { return element.tagName === "BUTTON" && element.textContent === label; }); +}; +const switchGroup = buttons("Switch model group"); +const previous = buttons("Previous"); +const next = buttons("Next"); +switchGroup.click(); +if (!previous.disabled || !next.disabled) { + throw new Error("within-pack controls remained enabled during group transition"); +} +const pendingImage = images()[1]; +if (!pendingImage || pendingImage.src !== "other-match") { + throw new Error("group transition did not create the expected pending image"); +} +const imageCount = images().length; +const activationEvents = [ + {type: "click"}, + {type: "keydown", key: "Enter"}, + {type: "keydown", key: " "}, +]; +activationEvents.forEach(function (event) { + images()[0].dispatchEvent(event); + if (!event.defaultPrevented || !event.propagationStopped) { + throw new Error("within-pack activation was not blocked during group transition"); + } +}); +[ + {type: "keydown", key: "Tab"}, + {type: "keydown", key: "Escape"}, +].forEach(function (event) { + images()[0].dispatchEvent(event); + if (event.defaultPrevented || event.propagationStopped) { + throw new Error("non-activation key was blocked during group transition"); + } +}); +previous.click(); +next.click(); +if (images().length !== imageCount) { + throw new Error("within-pack activation replaced the pending group transition"); +} +pendingImage.dispatchEvent({type: "load"}); +if (pendingImage.parentNode === null || pendingImage.src !== "other-match" || previous.disabled || next.disabled) { + throw new Error("group transition did not commit atomically after the winning load"); +} +process.stdout.write("pending group transition remained atomic"); +''' + completed = subprocess.run( + ["node", "-e", script, str(HERE / "static" / "app.js")], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(completed.returncode, 0, completed.stderr) + self.assertEqual(completed.stdout, "pending group transition remained atomic") + for contract in ( + "function imageNavigationBlocked()", + "if (!isGroupTransition && !isPackTransition && imageNavigationBlocked())", + "var navigationBlocked = imageNavigationBlocked();", + "if (imageNavigationBlocked()) {", + ): + self.assertIn(contract, js) + + def test_image_comparator_wraps_controls_at_intrinsic_widths(self): + css = (HERE / "static" / "style.css").read_text(encoding="utf-8") + self.assertIn("flex-wrap: wrap", css) + self.assertIn("flex: 1 1 40rem", css) self.assertIn("flex: 1 1 auto", css) self.assertIn("text-overflow: ellipsis", css) - self.assertIn("white-space: nowrap", css) + self.assertIn("white-space: normal", css) self.assertIn("@media (max-width: 52rem)", css) - self.assertIn("flex-wrap: wrap", css) def test_image_comparator_names_requested_item_during_initial_load(self): js = (HERE / "static" / "app.js").read_text(encoding="utf-8") @@ -1224,7 +1522,7 @@ def test_image_viewer_pointer_drag_preserves_click_navigation_contract(self): self.assertIn("cursor: grabbing", css) self.assertIn("touch-action: none", css) self.assertIn("-webkit-user-drag: none", css) - self.assertIn("click the displayed image, or drag it", js) + self.assertIn("Click the displayed image or drag it", js) def test_image_click_restores_pointerdown_viewport_before_switch(self): js = (HERE / "static" / "app.js").read_text(encoding="utf-8") diff --git a/docs/project/README.md b/docs/project/README.md index 5229c68..ce7319a 100644 --- a/docs/project/README.md +++ b/docs/project/README.md @@ -20,6 +20,9 @@ not define product or architecture contracts. - [AI observations](ai-observations.md) – conditional short-lived inbox for reusable AI tooling, harness, and operational-friction lessons; not ordinary work guidance. +- [Provisional stacked integration ledger](stacked-integration-ledger.md) – + current local packaging inventory and three-layer candidate stack; it owns + packaging status only. Roadmap horizons are planning tools, not promises. Concrete activation triggers are preferred over dates while research uncertainty is high. diff --git a/docs/project/current-handover.md b/docs/project/current-handover.md index cf97048..dfbe4ca 100644 --- a/docs/project/current-handover.md +++ b/docs/project/current-handover.md @@ -4,15 +4,131 @@ This pointer owns no project state. The [Active runway](status.md#active-runway) in `status.md` is authoritative for current continuation; this file only helps with live verification and navigation. +## Resumed runway — 2026-09-08 + +Ben explicitly resumed the exact paused runway through the Overseer on +2026-09-08. The fail-closed PowerShell/stdin invocation repair has now passed +parser, mocks, and both non-launching stdin sentinels (empty-profile and +nonnumeric-port), with both rejected-input child processes exiting nonzero and no trailing sentinel; quoted-argument +preview and fake handoff match, and no execution-policy mutation occurred. +Main's follow-up changed only cleanup-receipt guidance to require current-PID, +executable, and profile verification; no algorithm changed. Revalidate the +pause snapshot and these status pointers before continuing the lowest +integration lane: PR #127 plus up to two dependent follow-ups, with each layer +below 100 changed files. PR #127 currently has 57 prospective paths; the two +planned follow-ups are approximately 87 and 84 paths. Packaging and review remain primary, and upper-work must not +delay the lower lane. A genuine final-review-ready clean immutable head may then +receive the hosted and committed-diff CLI review cycle together. Current +real-browser coverage is deferred; no browser repair or setup lane remains +active. No local native Chromium or Playwright was available; the setup attempt +installed only npm Playwright 1.63.0 packages at +`/home/ben/.cache/pr127-native-browser-IFXwYI`, with no browser download or +launch and no new infrastructure or launcher project. Windows-side execution is +not permanently prohibited, but any future coverage must be provably hidden and +profile-isolated and create no visible Windows desktop windows, tabs, consoles, +focus changes, or popups. Real Windows launch and nonintrusion remain +unverified. No additional broad waiver is granted. Previous source/CLI gallery +hash-based validation remains retained evidence. PR #127's concrete +control-plane gate remains with Ben; this handover grants no merge +authorization. The pause record below is historical. + +## Historical pause snapshot — 2026-09-07 + +Ben explicitly requested a pause at the next safe boundary. All delegates have +returned; no further task, browser action, implementation, commit, push, or +review is authorized during the pause. + +- Integration checkout: `/home/ben/src/creature-kernel-worktrees/pr127-integration`, + branch `codex/pr127-integration`, HEAD + `4ae0a5c8176c60791248ad6eb5e52dc657a2dd34`. There are 21 dirty paths + (18 tracked modifications and 3 untracked files), with nothing staged. +- Upper checkout: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor`, + branch `codex/owned-root-assembly-successor`, same HEAD; 181 dirty paths + (17 tracked modifications, 164 untracked), nothing staged. Protected + `docs/project/ai-observations.md` remains present and untouched/unread. +- No commit, push, hosted/CLI review cycle, merge, or pelvis implementation + began during this integration turn. PR #127 remains at the last verified + 51-file draft head above. The unpublished PR-body draft is + `/tmp/pr127-integration-body.md`; it still contains pending wording. +- Gallery corrections, historical closeout, CLI import correction, and frozen + LOC-preserving reflow are complete locally. Validation details are in + [integration evidence](status.md#layer-1-integration-evidence-2026-09-07). + The active pelvis Rev2 recipe/review prerequisite is complete in the upper + checkout; its implementation and geometry execution remain unstarted. +- Browser invocation repair is **partial and must not be used to launch**. + `dev-tools/visual-review/browser_trial.ps1`, its mocked + `tests/test_browser_trial.ps1`, and the tool README were written. Parser, + mocked input rejection/default-plan, documentation, and whitespace checks + passed, but a separate invalid-input sentinel probe **failed**: script + `exit 1` did not prevent later stdin statements under `powershell.exe -File -`. + The README's claimed stdin termination is therefore not established. + Script SHA-256 is + `de771290fcdf93d982193d0ac5eb8c38dd61930e53acaca4ce5d800cf371237e`; + mocked-test SHA-256 is + `8538796228bb1b6128cdb7acb5711cd1b955ac59b540e99951b7487ca8620d3a`. +- No delegate command remains running. Final cleanup found no task Chrome + process or listener on ports 9223/9230/9231/9232/9234. Main's browser-owner + exec session 96240 exited. Trial server PID 2210318 is absent and port 46493 + is closed. Pre-existing listener `0.0.0.0:8765` remains untouched. Any tabs + handed to ordinary Chrome by the empty-profile launch remain unattributed; + ordinary Chrome was not touched during cleanup. +- Final pause-pointer edits were not followed by another validation command, + in accordance with Ben's pause. Earlier reported checks cover their recorded + revisions only. + +**First action after Ben resumes:** inspect the partial invocation catch path +and reproduce the non-launching stdin sentinel failure, then make termination +fail closed (the worker proposed host-level `SetShouldExit(1)`, still unverified). +Run parser/mocked/sentinel checks without launching a browser, correct the +README's claim, and rerun documentation/whitespace validation. Only then finish +the draft integration package, refresh exact PR head/file count, and consider +the pending immutable-head review cycle. Real-browser evidence and whole-PR +human merge authority remain unsatisfied; no browser retry is implicit. + ## Last-known context -The following values are expected last-known context and are explicitly -untrusted until verified live: +The following values are expected last-known context for this Layer 1 +integration checkout and are explicitly untrusted until verified live: + +- Checkout/worktree: `/home/ben/src/creature-kernel-worktrees/pr127-integration` +- Branch: `codex/pr127-integration` +- Pull request: PR #127 is an open draft; Main supplied base + `db5f11efff124d500d875f7839c53fee9a75f395`, head + `4ae0a5c8176c60791248ad6eb5e52dc657a2dd34`, and 51 changed files +- Copied stage ledger identity: `docs/project/stacked-integration-ledger.md`, + SHA-256 `c3c34a7f8f5ee2a5ab45913e46f7edef4380a4fc0bfb7d93cfa120a63442d3ba`, + 8,659 bytes +- Copied historical trigger identity: `experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json`, + SHA-256 `e7e272f24653e53164ba82b7bc8651cce51f72406ad157205b894bc957bc9d62`, + 22,161 bytes + +The original active development checkout remains +`/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` on +`codex/owned-root-assembly-successor`; pelvis source work continues there and +was not edited by this integration layer. + +## Layer 1 integration destination + +This checkout packages and tests the historical owned-root and gallery fixes +under the three-PR stack. The four stage-specific documentation overlays record +historical closeout and navigation only; captured regression checks change no +construction and publish no candidate. No parked experiment is reactivated. +The current continuation is the integrated +coarse-to-anatomical whole-character Active runway. Later lower/body paths are +follow-up stack material and remain prose-only until their files arrive here. + +PR #127 and the supplied head remain pending CI, independent review, hosted and +CLI checks, and human control-plane gates. This handover grants no merge +authorization. The current integration checks and consolidated review remain +pending. -- Checkout: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` -- Worktree: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` -- Branch: `codex/owned-root-assembly-successor` -- Pull request: PR #127 is an open draft for `codex/owned-root-assembly-successor` +Focused integration results and their capture paths are recorded in +[Layer 1 integration evidence](status.md#layer-1-integration-evidence-2026-09-07). +Ben stopped browser launches after the trial method caused visible Chrome +errors and failed tabs. Browser coverage remains incomplete; continue with +non-browser checks and the bounded invocation repair. Do not resume the old +launch scripts or a GUI fallback. No task browser processes/debug listeners +remained at cleanup, and the disposable trial gallery server was stopped. ## Live verification checklist diff --git a/docs/project/stacked-integration-ledger.md b/docs/project/stacked-integration-ledger.md new file mode 100644 index 0000000..2a326a6 --- /dev/null +++ b/docs/project/stacked-integration-ledger.md @@ -0,0 +1,157 @@ +# Provisional stacked integration ledger + +Status: provisional local packaging record + +Captured at: 2026-09-07T18:15:40.632513+12:00 (NZST) + +Worktree: `/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` + +Branch: `codex/owned-root-assembly-successor` + +This ledger records the current checkout inventory for packaging discussion. It +does not establish runway authority, merge authority, or an execution/acceptance +result. Local layer counts are checkout deltas only; prospective PR counts must +also account for files already present in the PR head and for repeated +stage-specific documentation overlays. + +## Local baseline + +`git status --short --untracked-files=all` reported 181 paths: 17 modified +tracked paths (16 eligible and one protected), and 164 eligible untracked +paths. The protected path, `docs/project/ai-observations.md`, was excluded +without reading, staging, editing, or assigning it. The 180 eligible paths +include the new ledger itself as a changed file. Preserved unrelated +modifications remain visible in Layer 1 but are marked relevance-pending and +are not automatically authorized for integration. + +The filesystem scan found 37 ignored `__pycache__/*.pyc` files under the +scanned experiment and tool roots. They are cache artifacts and are excluded. +No binary or generated artifact path appeared in the status inventory after +that exclusion. Referenced `/home/ben/.cache` snapshots, renders, transcripts, +and manifests are outside this worktree and are not counted. Evidence JSON, +Markdown, source, and tests that are present in the worktree remain counted. + +Each manifest hash below is SHA-256 over sorted eligible relative paths and +their individual SHA-256 values, one `path\0file-hash\n` record per path. Layer +1 counts the ledger path, while its digest excludes that self-referential file; +the other layer digests include every listed path. This gives a reproducible +local identity without pasting hundreds of file hashes. + +## Three-layer candidate stack + +The causal order is the existing PR127 baseline, lower connected-leg/source +prerequisites, then the active foundation and body integration. All counts in +the table are local checkout deltas and sum to all 180 eligible paths. + +| Layer | Purpose and path set | Local delta | Headroom to 90 | Local manifest SHA-256 | +| --- | --- | ---: | ---: | --- | +| 1 | Existing tracked delta plus this ledger: all 16 eligible modified tracked paths (listed below) and `docs/project/stacked-integration-ledger.md` | 17 | 73 | `3677c96f96cc6bfdd50d9753f7a011489541ae872704174444b0e322040b7de7`* | +| 2 | Pelvis source experiments (35) plus lower connected-leg runner/source/check prerequisites, active foot/tail/calf paths, and standalone arm/head builders/tests (48 connected paths) | 83 | 7 | `0bd9074f6126901bf7bd0774bdbe02ba5470d14a80b97a1fd2ddc71c5170df19` | +| 3 | Remaining connected-leg foundation providers, body assembly/configs, pelvis support, torso/chest, and arm/head refinement paths (80 connected paths) | 80 | 10 | `99ef576357dbe98143f5fde9682131931fb800bdd3c7c07cb4a4079d4fc811c4` | + +The Layer 1 digest is marked with `*` because the ledger is counted as a +changed file but omitted from its own digest to avoid a self-referential hash. + +Layer 1's 16 pre-existing eligible modified tracked paths are +`dev-tools/visual-review/{static/app.js,static/style.css,tests/test_visual_review.py}` +(3), `docs/project/{README.md,current-handover.md,status.md}` (3), +`docs/research/README.md` and `experiments/README.md` (2), all seven status +paths under `experiments/owned-root-assembly-successor/`, and +`experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py`. +Preserved unrelated changes in this set are relevance-pending; they are not +automatically authorized for integration. + +Main supplied the current PR127 baseline evidence: OPEN DRAFT, base +`main` at `db5f11efff124d500d875f7839c53fee9a75f395`, head +`4ae0a5c8176c60791248ad6eb5e52dc657a2dd34`, and 51 changed files. Fourteen of +those remote paths overlap Layer 1's local delta. The three local-only paths +are `dev-tools/visual-review/static/style.css`, `docs/project/README.md`, and +this ledger, giving a provisional 54-path PR127 total if no other path is +added. This is current-head evidence supplied by Main, not a guarantee at the +future packaging boundary. A changed PR127 head or additional existing paths +could consume the remaining Layer 1 headroom, so recheck the exact head before +materialization; repeated documentation overlays must be counted again in each +follow-up PR. + +Layer 2's 48 connected paths are: the lower shared set +`{README.md,protocol.json,hip_source.py,perturbations.py,inputs.json,binding.py, +checks.py,construction.py,root_source.py,runner.py,captured_tests.py, +collision_broadphase.py,example-brief.md}` plus the nine corresponding +`tests/test_{binding,captured_tests,checks,collision_broadphase,construction, +hip_source,perturbations,root_source,runner}.py` paths (22); standalone +`arm_construction.py`, `head_construction.py`, and their construction tests +(4); all foot paths and tests (17); all tail paths and its test (4); and +`005-calf-measurement.md` (1). The three pelvis experiment directories add 35. + +The pelvis source directories and connected pelvis foundation paths are active +while Main continues the pelvis work. Their counts and hashes are therefore a +timestamped local snapshot and must be refreshed at the next clean packaging +boundary; no freeze or pause is requested. + +Import inspection supports this boundary: `runner.py` has no module-level +`body_assembly` import and dynamically loads optional features, so a default +leg-only runner is plausible before the body feature layer, but it remains +unverified. Foot modules import the lower construction/runner helpers; tail +imports construction; arm/head construction modules are standalone. No +execution or numerical calculation was performed. + +Layer 3's 80 connected paths are grouped as: pelvis foundation/support (19), +abdomen foundation/provider/evidence (9), thorax foundation/contract/evidence +(12), torso refinement (10), chest evidence (4), arm refinement (4), head +refinement (4), and body assembly/config variants/tests (18). Keeping these +together supplies the abdomen/thorax/provider/body-assembly dependencies +required by the pelvis foundation. In particular, body configs and +`body_assembly.py` remain above the lower runner layer; no config is treated as +active merely because it is present. + +The lower and foundation follow-ups may each need roughly four repeated +documentation paths (`connected-leg-assembly/README.md`, project +status/handover/index material, and related experiment indexes). Budgeting +those overlays gives planning totals of about 87 for Layer 2 and 84 for Layer +3. Do not copy a later final README/status wholesale into an earlier layer; +materialize stage-specific overlays only after their referenced paths exist. + +## Placement and retention decisions + +All 180 eligible local paths are assigned above; there are no omissions or +deletions. The prior 22-path foot/tail/calf set is deliberately included in +Layer 2 because the body configuration and anthropomorphic path depend on it. +The five body-only shared paths moved above the lower layer are +`body_assembly.py`, `tests/test_body_assembly.py`, `body-config.json`, +`body-junction-integration-config.json`, and +`body-refinement-internal-config.json`; the remaining body configs stay with +Layer 3 as well because they select foundation and refinement inputs. + +Layer 3's 80-file local delta leaves ten files before the nominal alert and +about six after its recurring documentation overlay. Layer 2 leaves seven +before the alert and about three after its overlay. Alert the Main Worker if +dependency closure or overlays exceed that space; consolidate only with an +approved retention decision that preserves causal records and provenance. +These counts are local-delta packaging estimates, not summed PR changed-file +counts. + +## Conditional packaging priority + +At the 2026-09-08 integration boundary, Main rechecked PR #127: its open draft +still has head `4ae0a5c8176c60791248ad6eb5e52dc657a2dd34`, base +`db5f11efff124d500d875f7839c53fee9a75f395`, and 51 remote changed files. +The isolated `codex/pr127-integration` working candidate has **57 prospective +PR paths**, including the six additions relative to that published path set: +the gallery README, browser preflight script and mocked test, gallery CSS, +project index, and this ledger. The existing CLI import correction overlaps +the published path set. Protected inbox contents remain excluded. This +materialization count supersedes the earlier 54-path estimate for Layer 1; +the timestamped upper-layer inventory and approximately 87/84 follow-up +budgets remain planning evidence. Browser repair validation is non-launching, +and real-browser coverage remains incomplete. + +When the lowest layer is clean and final-review-ready, the recorded priority is +one hosted CodeRabbit cycle together with the committed CLI cycle on the same +immutable pushed OID. Do not mutate that head while hosted review runs; safe +upper-layer work may continue, with rebasing or retargeting only after the +lower layer merges and applicable gates are satisfied. This is a conditional +future priority, not an immediate external action or a new authority grant. + +Validation for this documentation change is run after the index link is added: +`python3 dev-tools/validation/validate_docs.py` and +`dev-tools/validation/check_worktree_whitespace.sh`. diff --git a/docs/project/status.md b/docs/project/status.md index ffc13f6..56e8a82 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -1,6 +1,6 @@ # Project status -Status date: 2026-09-05 (NZST; repository activity is recorded in NZST while +Status date: 2026-09-08 (NZST; repository activity is recorded in NZST while GitHub timestamps are UTC) ## Phase @@ -14,111 +14,113 @@ governs what resumes next. ## Active runway +**RESUMED on 2026-09-08 at Ben's explicit request relayed by the Overseer.** +Resume the exact paused runway. The fail-closed PowerShell/stdin invocation +repair has now passed parser, mocks, and both non-launching stdin sentinels +(empty-profile and nonnumeric-port), with both rejected-input child processes exiting nonzero and no trailing sentinel; +quoted-argument preview and fake handoff match, and no execution-policy +mutation occurred. Main's follow-up changed only cleanup-receipt guidance to +require current-PID, executable, and profile verification; no algorithm changed. +Revalidate this pause snapshot and the current handover before continuing the +lowest integration lane: +PR #127 currently has 57 prospective paths; its two planned follow-ups are +approximately 87 and 84 paths, each below 100 changed files. Packaging and review remain primary, and +upper-work must not delay that lower lane. A genuine final-review-ready clean +immutable head is required before the hosted and committed-diff CLI review cycle +runs together. Current real-browser coverage is deferred; no browser repair or +setup lane remains active. No local native Chromium or Playwright was available; +the setup attempt installed only npm Playwright 1.63.0 packages at +`/home/ben/.cache/pr127-native-browser-IFXwYI`, with no browser download or +launch and no new infrastructure or launcher project. Windows-side execution is +not permanently prohibited, but any future coverage must be provably hidden and +profile-isolated and create no visible Windows desktop windows, tabs, consoles, +focus changes, or popups. Real Windows launch and nonintrusion remain +unverified. No additional broad waiver is granted. Previous source/CLI gallery +hash-based validation remains retained evidence. This status grants no merge +authorization; PR #127's concrete control-plane gate remains with Ben. The +paused snapshot is preserved as historical record in the [current +handover](current-handover.md#historical-pause-snapshot-2026-09-07). + This section is the sole current continuation source for the repository. Later status sections are reference history or task-specific state only; they may preserve evidence but do not redefine current continuation. -### Owned root assembly successor - -The Ben-authorized, experiment-local successor is the bounded [owned root -assembly investigation](../research/owned-root-assembly-investigation.md). -It tests one welded standard-neutral root surface using exactly eight named, -nonempty domain interiors under the hard `<=8` cap, five open ports, at most -128 controls and 120 base quads, two subdivision levels, and at most two shared -correction rounds. Construction ownership, semantic causality, and -evaluated-surface contributor/chart lineage remain separate; every output must -be owned or have a declared junction or contributor record. - -The successor uses the authored `neck_upper` and `upper_abdomen` controls; its -oriented interfaces, patch layout, port orientation, extraordinary -placement/valence, continuity, normal/fold bounds, subdivision support, -causality matrix, and locality perturbations are frozen before rendering. It -replaces the old port-span anatomy gates with candidate-specific checks for -neck exposure, shoulder descent, axillary concavity, pelvic wrap, and -downward thigh-root orientation. Direct skin and ownership diagnostics must -be renders of the same evaluated surface, and categorical colour cannot stand -in for causality. - -The required -`experiments/owned-root-assembly-successor/design-contract.md` freeze artifact -is now frozen and SHA-256-bound at -`3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490`, recorded -by its sidecar. Two independent Sol reviews returned `FREEZE` with zero -blockers. The bounded implementation phase completed at -`correction_round=0`; the builder must reject a missing or mismatched -design-contract identity. - -Historical round-0 neutral evidence is retained at commit -`2efd0b28c492423630b2fed3930da23f1b69bd9b`. The main public evidence is the -96-file publication in logical local cache -`artifact-cache/owned-root-assembly-successor/2efd0b28-main-1`. That historical -publication records 121 -tests with zero failures, errors, or skips; the seed gates and cross-seed -comparison passed. The exact `comparison-report.json` SHA-256, obtainable from -the exact sidecar, is -`f87afb2ac517e4fd42ffb04248d97045df016f59d9f6d344d4a45659340b7ab7`. The -direct PNG is -`b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed`, the -lineage PNG is -`19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2`, the -stable manifest is -`3a8c87da8a297fb19f6f07b6ea669bde196e5a43b5609525f639e07fc168235e`, and -the runtime fingerprint is -`c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085`. - -Main-thread visual appraisal found the neutral neck, shoulder/axilla, -pelvic-wrap, and thigh-root cues credible. Two independent Sol vision checks -agreed and found no material blocker. The exact-five gate was therefore -unlocked. The local exact-five runner, publisher, launcher, focused tests, and -gallery adapter now exist. Projection across all five profiles is exact, and -focused non-success-path tests pass, but publication remains fail-closed: -four non-neutral profiles fail the unchanged gates. The canonical trigger -evidence is -`experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json` -(21,714 bytes; SHA-256 -`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with -39 observed failure records and ten profile/seed reproductions. - -The semantics-preserving numeric-only geometry seam and change batch fit the -frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed -comparison. The batch changes no shared formula or tunable and all 38 payloads -remain byte-identical, so it consumes no correction round. The current 96-file -publication is in logical local cache -`artifact-cache/owned-root-assembly-successor/correction-batch-20260905-4`; -all 38 geometry/perturbation/render roles in each seed are byte-identical to -both the seam and pre-seam baselines. The current comparison report SHA-256 is -`fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a` -and the current stable-manifest SHA-256 is -`1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. - -The exact-five activation contract is frozen at SHA-256 -`a5c38645c810efb24e79297fb7c8049f0f59529f37a67c18a5a728a7119f0d49`; -two independent Sol reviews returned `FREEZE` with no blockers. The exact-five -execution surface is present locally, but its fail-closed publication is not a -success result. Outside the bounded correction authorized below, do not add a -private-internal wrapper, duplicate geometry, profile-aware branching, -geometry correction, or a new representation. - -Ben explicitly authorized one bounded dimension-driven shared shoulder/hip -correction within the existing welded representation, preceded by feasibility. -No profile exceptions, clamps, gate or threshold relaxation, topology, -ownership, renderer, subdivision, or representation change is authorized. -Shoulder feasibility found a dimension-driven candidate that passes exact five -and coherent diagnostics. Hip feasibility found the frozen formula/support -restriction insufficient; Astra-high recommended exactly one bounded -deterministic fixed-topology pre-filter trial using already-admitted adjacent -station inputs. That advice is advisory evidence, not accepted architecture. -If the trial requires profile fitting, clamps, overshoot, topology or ownership -change, cap excess, or still fails required cases, stop rather than refreeze. -No formula has been accepted or implemented. - -The named human checkpoint remains Ben's exact-five gallery appraisal of the -owned-root assembly, but the fail-closed publication must first produce the -appraisable gallery evidence. The checkpoint uses fixed front, side, and -three-quarter final-surface renders. Internal metrics and model reviews do not -substitute for Ben's visual judgment. The [terminal -seven-ring outcome](../research/programmatic-root-complex-surface-investigation.md#terminal-outcome-2026-09-03) -remains historical evidence and is not reactivated. +### Integrated coarse-to-anatomical whole-character runway + +The current runway is active under Ben's authorization relayed through the +Overseer on 2026-09-06. Main and Overseer may progress through an integrated +coarse whole character and the first integrated anatomical refinement for both +calibrated human and anthropomorphic contexts. The next named Ben checkpoint is +a coherent, recognizable simplified whole character at rest and in restrained +combined poses, with useful proportions and major masses plus displayed +movement driven by real source, frame, and binding data. Internal milestones, +individual limbs, trials, and poses do not substitute for that checkpoint, and +this remains experimental evidence rather than a product, specification, or +architecture adoption. + +This Layer 1 integration checkout packages and tests the historical owned-root +and gallery fixes from PR #127. Main supplied the current draft head +`4ae0a5c8176c60791248ad6eb5e52dc657a2dd34` against base +`db5f11efff124d500d875f7839c53fee9a75f395`; CI, independent review, hosted and +CLI checks, and human control-plane gates remain pending. This status records no +merge authorization. The stage ledger is +[stacked-integration-ledger.md](stacked-integration-ledger.md). + +The owned-root assembly and exact-five attempt below are stopped, superseded +historical evidence. Lower/body experiments and the active pelvis source work +are follow-up stack material; those directories are not present in this Layer 1 +checkout. Pelvis development continues in +`/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` on +`codex/owned-root-assembly-successor`. This integration layer runs captured +regression checks without changing construction or publishing a new candidate; +no parked experiment is reactivated. + +## Layer 1 integration evidence (2026-09-07) + +The local gallery correction passed 58 focused tests, including delayed group +transition and Tab/Escape propagation checks. A fresh independent first-use +CLI trial confirmed the documented success, canonical-metre off-grid +rejection, missing-file diagnostics, and help. Its pretty-printed test copy +hit the existing source byte limit; a compact copy reached the intended +dimension rejection. This is source-inspection evidence, not creature quality. + +A separate fresh non-browser adversarial trial exercised the production +comparator through a temporary Node VM/fake-DOM harness. All six bounded +scenarios passed: cross-pack identity/context, missing-match skipping, +ambiguity stops, delayed group activation, image/pack failure preservation, +and Tab/Escape plus stale-result handling. The harness and result are retained +at `/tmp/pr127-nonbrowser-trial-itKBKF`; the reviewed application SHA-256 is +`a1f525d04d806142512d90f2de99e525bf6a5020c3f389a7a459484c021cb864`. +Fake-DOM results do not establish real event propagation, focus, or rendering. + +Captured Python validation is retained outside Git under +`/home/ben/.cache/pr127-lower-validation-56kvdu76`. The 111-file source +manifest was recorded before imports and stayed unchanged after execution. +The structural source check passed; 44 predecessor checks passed; 118 of 119 +owned-root checks passed initially. The failure exposed the frozen production +line cap; after a formatting-only repair, the test line cap also failed. +Both failures remain in the original logs. The final affected 27-check +selection passed from the fresh capture +`/home/ben/.cache/pr127-lower-validation-49ndbc5u`, with production/test +counts of 3,400/2,600 and no changed cap or gate. The intermediate capture is +`/home/ben/.cache/pr127-lower-validation-bw37o9xt`. Each capture contains its +command manifest and logs. No public experiment builder was invoked. + +CLI formatting, Clippy with warnings denied, and 76 tests passed after moving +a test-only import out of production scope. Repository-search checks and both +CLI source-inspection commands passed. These focused checks do not upgrade the +historical full-suite failure baseline or establish a new geometry result. + +Ben stopped browser trials after the setup method caused visible Chrome +errors and failed tabs. One launch passed an empty profile and debug port zero, +so it may have handed tabs to the ordinary session. No task browser process or +debug listener remained at the final cleanup check; ordinary Chrome was not +modified because such tabs could not be safely attributed. Popup text was not +captured. Setup and cleanup evidence remains at +`/tmp/pr127-gallery-fixture-001`. Browser rendering, real focus/viewport +behavior, and intermediate-width layout are unverified. This coverage gap is +not a waived review or merge gate. Further browser launches are stopped while +the bounded invocation is repaired and checked without launching a browser. ## Historical failed-candidate runway (2026-09-01) diff --git a/docs/research/README.md b/docs/research/README.md index 221b6b7..13f80b8 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -27,10 +27,11 @@ hypotheses, references, and research context. it is non-normative, blocks exact-five continuation, and does not activate DR-0009/0010 or replace DR-0013 Stage 1 proof. - [Owned root assembly investigation](owned-root-assembly-investigation.md) — a - Ben-authorized, experiment-local successor direction whose design is frozen - and whose bounded implementation is active, using explicit domain/junction - ownership; it is non-normative, remains bounded by the Active runway, and - leads to the later exact-five human checkpoint. + Ben-authorized, experiment-local successor direction whose design and + recorded implementation/evidence are historical pointers. It is + non-normative; see the [Active runway](../project/status.md#active-runway) for + current continuation rather than treating this entry as an active + implementation state or a substitute for current evidence. - [Numeric and frame profile experiment design](numeric-frame-profile-experiment.md) — planned and unregistered evidence for numeric admission, exact dyadic/ULP boundaries, deterministic normalization and offline half-chord derivation, diff --git a/experiments/README.md b/experiments/README.md index 246853f..61860e4 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -2,7 +2,11 @@ Status: Active workflow; EXP-0002 remains planned with open evidence closure and technology outcome `none`; its phase-one attempt-001 evidence is complete -and passed, while broader experiment obligations remain open. +and passed, while broader experiment obligations remain open. The owned-root +assembly successor is closed historical evidence. Current continuation is the +integrated coarse-to-anatomical whole-character runway in the +[Active runway](../docs/project/status.md#active-runway); lower/body experiments +are follow-up stack material and are not present in this Layer 1 checkout. Experiments provide reproducible evidence for research questions and decisions. They do not become product or architecture contracts automatically. Research @@ -112,12 +116,13 @@ experiment-local launcher are not product, Stage 1, production, or formal surface-comparison authority. The [owned root assembly successor](owned-root-assembly-successor/README.md) -is the unregistered exploratory successor targeting open `RQ-002`, `RQ-012`, -`RQ-020`, and `RQ-021`. It is not `EXP-0001`; its candidate-local design -contract is frozen and SHA-256-bound, and its bounded implementation phase is -complete at `correction_round=0`. Its credible neutral evidence unlocks the -separately contracted exact-five activation work; it cannot establish a formal -technology outcome, production surface contract, or Stage 1 result. +is a finished, stopped, and superseded historical experiment targeting open +`RQ-002`, `RQ-012`, `RQ-020`, and `RQ-021`. It is not `EXP-0001`; its +candidate-local design contract is frozen and SHA-256-bound, and its shared +correction budget is closed unused. Its neutral evidence and fail-closed +exact-five attempt remain historical; they cannot establish a formal technology +outcome, production surface contract, or Stage 1 result, and they do not +reactivate the experiment. ## Artifact policy diff --git a/experiments/owned-root-assembly-successor/README.md b/experiments/owned-root-assembly-successor/README.md index 4913ee0..39b6998 100644 --- a/experiments/owned-root-assembly-successor/README.md +++ b/experiments/owned-root-assembly-successor/README.md @@ -1,7 +1,7 @@ # Owned root assembly successor -Status: standard-neutral execution complete; exact-five attempt fail-closed; -frozen, SHA-256-bound, non-normative +Status: stopped and superseded historical candidate; exact-five attempt +fail-closed; frozen, SHA-256-bound, non-normative Experiment lifecycle: finished @@ -26,20 +26,18 @@ returned `FREEZE` with zero blockers Design contract SHA-256: `3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490` -`correction_round=0`: the initial implementation phase is complete. A separate -budget of at most two shared correction rounds remains available; none has been -consumed. +`correction_round=0`: the initial implementation phase is complete. The +separate budget of at most two shared correction rounds is closed unused. ## Status and authority -This is the frozen candidate contract and bounded implementation phase for one -new, standard-neutral experiment. It is the successor direction authorized -after the seven-ring candidate in PR #125 reached its three-round stop rule. -It remains an unaccepted experiment-local candidate: the neutral result -unlocked the unchanged exact-five gate, but the exact-five attempt is -fail-closed and does not establish a production schema, architecture, -topology, supported morphology promise, or permanent technology choice. It -does not reactivate a parked workstream or satisfy the DR-0013 Stage 1 proof. +This is the historical closeout for one frozen, standard-neutral experiment. +The bounded budget is closed unused after the candidate was stopped and +superseded. Its neutral result and fail-closed exact-five attempt remain +experiment-local evidence; they do not establish a production schema, +architecture, topology, supported morphology promise, or permanent technology +choice, and do not satisfy the DR-0013 Stage 1 proof. No readmission or parked +experiment reactivation follows from this record. The previous candidate is evidence, not a foundation to transplant. Its seven-ring topology, projection, formulas, macros, IDs, thresholds, and @@ -78,21 +76,21 @@ focused non-success-path tests pass, but publication remains fail-closed: four non-neutral profiles fail the unchanged gates. The canonical trigger evidence is `experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json` -(21,714 bytes; SHA-256 -`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with +(22,161 bytes; SHA-256 +`e7e272f24653e53164ba82b7bc8651cce51f72406ad157205b894bc957bc9d62`), with 39 observed failure records and ten profile/seed reproductions. The semantics-preserving numeric-only geometry seam and change batch fit the frozen LOC caps and pass 134 managed tests, both seed gates, and cross-seed comparison. This is not a correction round under [Correction stop](#correction-stop): it changes no shared construction formula or tunable, and all 38 published -roles remain byte-identical, so the two-round budget remains unused. The -current 96-file publication is in logical local cache +roles remain byte-identical, so the two-round budget is closed unused. The +retained 96-file publication is in logical local cache `artifact-cache/owned-root-assembly-successor/correction-batch-20260905-4`; all 38 geometry/perturbation/render roles in each seed are byte-identical to -both the seam and pre-seam baselines. The current comparison report SHA-256 is +both the seam and pre-seam baselines. The retained comparison report SHA-256 is `fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a` -and the current stable-manifest SHA-256 is +and the retained stable-manifest SHA-256 is `1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa`. The exact-five activation contract is frozen at SHA-256 @@ -282,7 +280,7 @@ builder must require that identity, hash the file before admitting source inputs, and reject a missing file or mismatch without producing an artifact. The bounded implementation phase is complete under this frozen contract at `correction_round=0`. The separate budget of at most two shared correction -rounds remains available and unused. +rounds is closed unused. The frozen design contract fixes all details needed to make the candidate reproducible without inventing them during coding: @@ -594,7 +592,7 @@ does not authorize promotion into production code or canonical architecture. ## Results, limitations, and conclusion -The standard-neutral execution completed at `correction_round=0`. The current +The standard-neutral execution completed at `correction_round=0`. The retained post-seam correction-batch publication identified above contains 96 files, passes 134 managed tests, both seed gates, and cross-seed comparison, and keeps all 38 payload roles byte-identical to the retained pre-seam baseline. This is @@ -606,8 +604,8 @@ five profiles is exact. Focused non-success-path tests pass. No successful exact-five publication is claimed: four non-neutral profiles fail the unchanged gates, so publication remains fail-closed. The canonical trigger evidence is -`results/correction-round-1-preflight-trigger.json` (21,714 bytes; SHA-256 -`6ab89cc92b87e9c549d864b2e5162f653d892ef6fc68faf46bc9ce57780ef62b`), with +`results/correction-round-1-preflight-trigger.json` (22,161 bytes; SHA-256 +`e7e272f24653e53164ba82b7bc8651cce51f72406ad157205b894bc957bc9d62`), with 39 observed failure records and ten profile/seed reproductions. The initial trial was limited to one standard-neutral root assembly. The @@ -617,18 +615,26 @@ distal anatomy, posing, skeleton runtime, deformation, simulation, engine adapters, or production packaging. The exact-five result is fail-closed and does not approve production use. +The canonical trigger identity is the historical +`results/correction-round-1-preflight-trigger.json` file at 22,161 bytes with +SHA-256 +`e7e272f24653e53164ba82b7bc8651cce51f72406ad157205b894bc957bc9d62`. It has +39 observed failure records and ten profile/seed reproductions, but it does +not establish an identical failure set across seeds. Public execution stopped +at managed tests before baseline admission. An undocumented publisher +readmission attempt is retained only as an unverified orchestration limitation, +not as positive evidence. Valid neutral evidence and these proof limits remain +historical; no claims about tails, distal anatomy, optional modules, posing, +runtime, or production packaging are added here. + ## Recommended follow-up -The semantics-preserving numeric-only geometry seam is implemented and -revalidated against the historical baseline above. Ben has authorized exactly -one bounded dimension-driven shared shoulder/hip correction within the existing -welded representation, preceded by feasibility. Shoulder feasibility found a -candidate that passes exact five and coherent diagnostics. Hip feasibility found -the frozen formula/support restriction insufficient; Astra-high's recommendation -is advisory evidence for exactly one bounded deterministic fixed-topology -pre-filter trial using already-admitted adjacent station inputs, not accepted -architecture. If that trial requires profile fitting, clamps, overshoot, -topology or ownership change, cap excess, or still fails required cases, stop -rather than refreeze. No formula has been accepted or implemented. The human -checkpoint remains Ben's exact-five gallery appraisal, and any PR must remain -unmerged until his explicit approval. +This experiment is stopped and superseded historical evidence. The current +continuation is the integrated coarse-to-anatomical whole-character runway in +the [Active runway](../../docs/project/status.md#active-runway); lower/body +experiments are follow-up stack material and are not present in this Layer 1 +checkout. The next Ben checkpoint is a coherent recognizable whole character +at rest and in restrained combined poses for both calibrated contexts, with +source, frame, and binding-driven movement. This Layer 1 package performs +captured regression checks without changing construction or publishing a new +candidate, and does not reactivate this experiment. diff --git a/experiments/owned-root-assembly-successor/prepared_projection.py b/experiments/owned-root-assembly-successor/prepared_projection.py index 5a60180..e2ad293 100644 --- a/experiments/owned-root-assembly-successor/prepared_projection.py +++ b/experiments/owned-root-assembly-successor/prepared_projection.py @@ -328,6 +328,7 @@ def validate_prepared(prepared): value = shape(prepared) contract_digest, admission, profile, profile_raw, profile_digest = inputs(fixed["paths"][2], fixed["paths"][0], fixed["paths"][3]) digest_triple = (contract_digest, admission["sha256"], profile_digest) + need(digest_triple == fixed["hashes"], "prepared", "fixed input identity changed") expected_bytes = expected_bytes_cache.get(digest_triple) if expected_bytes is None: expected_bytes = operations["json_bytes"]( @@ -464,9 +465,8 @@ def _selector_path(component): def _path_get(value, path): for field in path: value = value[field] return value -def _geometry_apis(_ids=_GEOMETRY_COMPONENT_IDS, _carrier=GeometryComponents, - _validate=validate_prepared, _bindings=source_binding_records, - _read=_geometry_value, _required=_need): +def _geometry_apis(_ids=_GEOMETRY_COMPONENT_IDS, _carrier=GeometryComponents, _validate=validate_prepared, + _bindings=source_binding_records, _read=_geometry_value, _required=_need, _json_bytes=_COMMITMENTS["operations"]["json_bytes"]): ids, carrier, validate, bindings, read, required = tuple(_ids), _carrier, _validate, _bindings, _read, _required selectors = tuple((parameter, component, _selector_path(component)) for parameter, component in _MUST_AFFECT) delta = _PERTURBATION_DELTA @@ -491,7 +491,7 @@ def project_perturbed_geometry(prepared, parameter_id): changed = float(baseline + delta); _path_get(candidate, path[:-1])[path[-1]] = changed if _path_get(candidate, path) != changed: raise PreparedProjectionError("perturbation did not change its selected component") restored = copy.deepcopy(candidate); _path_get(restored, path[:-1])[path[-1]] = baseline - if _JSON_BYTES(restored) != _JSON_BYTES(value): raise PreparedProjectionError("perturbation changed more than its selected component") + if _json_bytes(restored) != _json_bytes(value): raise PreparedProjectionError("perturbation changed more than its selected component") return project_value(candidate) return project_geometry, project_perturbed_geometry project_geometry, project_perturbed_geometry = _geometry_apis() diff --git a/experiments/owned-root-assembly-successor/render_export.py b/experiments/owned-root-assembly-successor/render_export.py index 9273263..b01177b 100644 --- a/experiments/owned-root-assembly-successor/render_export.py +++ b/experiments/owned-root-assembly-successor/render_export.py @@ -143,8 +143,8 @@ def _panel_candidates(screen: tuple[tuple[float, float, float], ...], triangles) records.append(None) degenerate += 1 continue - c0, c1 = max(0, math.floor(min(ax, bx, cx) - 0.5) - 1), min(511, math.ceil(max(ax, bx, cx) - 0.5) + 1) - r0, r1 = max(0, math.floor(min(ay, by, cy) - 0.5) - 1), min(511, math.ceil(max(ay, by, cy) - 0.5) + 1) + c0, c1 = max(0, math.floor(min(ax, bx, cx) - 0.5) - 1), min(WIDTH - 1, math.ceil(max(ax, bx, cx) - 0.5) + 1) + r0, r1 = max(0, math.floor(min(ay, by, cy) - 0.5) - 1), min(HEIGHT - 1, math.ceil(max(ay, by, cy) - 0.5) + 1) records.append((ax, ay, za, bx, by, zb, cx, cy, zc, d0, d2, _fl(cy - ay), _fl(ax - cx), denominator, c0, c1)) for row in range(r0, r1 + 1): rows[row].append((triangle_index, c0, c1)) diff --git a/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json b/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json index 5d81e45..41b53ac 100644 --- a/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json +++ b/experiments/owned-root-assembly-successor/results/correction-round-1-preflight-trigger.json @@ -1 +1 @@ -{"authorization":"Ben authorized one bounded correction round within the existing shared-surface representation, preceded by feasibility evidence.","candidate":"dimension-driven-shared-attachment-correction","limitations":["This is pre-correction trigger evidence, not a proposed formula and not evidence that round 1 will pass.","The public exact-five launcher did not complete its full ten-bundle, cross-seed, causality, publication, or gallery suite.","The profile/seed runner passed the standard-neutral profile but rejected the four non-neutral profiles before successful bundles could be sealed.","The metrics are mechanical geometry/anatomy evidence; they do not replace visual appraisal and do not claim universal morphology support.","Round-0 implementation and evidence remain historical and must be regenerated if the shared construction changes."],"limits":{"formula_recommendation_in_this_record":false,"gate_change":false,"hidden_or_duplicate_surface":false,"new_representation":false,"port_or_ownership_change":false,"profile_id_or_label_in_geometry":false,"profile_specific_branch_or_exception":false,"profile_specific_geometry":false,"renderer_change":false,"solver_optimizer_remesher_or_render_offset":false,"subdivision_change":false,"threshold_change":false,"topology_change":false},"neutral_result":{"all_unchanged_geometry_and_anatomy_gates":"not_failed_in_metric_collection","co_normal_threshold":0.8,"observed_failures":0,"profile_id":"standard_neutral_reference","profile_index":0},"observed_failures":[{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360806,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360805,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360814,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360817,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.6760110294117647,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.6760110294117643,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__left_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695751693,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"continuity","gate_id":"continuity.junction.pelvis__right_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695749178,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595129,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__abdomen.L0.fold_angle","observed_max":91.31293023554761,"observed_min":33.087900440787394,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":10,"threshold":90.0,"threshold_relation":"lt","unit":"degree"}],"permitted_scope":{"domains":["domain.left_hip","domain.left_shoulder","domain.right_hip","domain.right_shoulder"],"formula_ids":["formula.hip.left","formula.hip.right","formula.shoulder.left","formula.shoulder.right"],"kind":"one shared dimension-driven attachment-construction correction","mechanical_consequences":["update affected executable/reference formulas together","update derived dependency, derivative, support, and identity records","regenerate neutral evidence","revalidate and refreeze only after two fresh independent reviews"],"required_property":"derive each attachment from the existing adjoining-region inputs and preserve one welded shared surface with source-level causal effect"},"prior_design_contract":{"bytes":173184,"correction_round":0,"role_path":"experiments/owned-root-assembly-successor/design-contract.md","sha256":"3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490"},"prior_round":0,"profile_table":{"bytes":29970,"profiles":[{"id":"standard_neutral_reference","index":0},{"id":"compact_broad_short_limb_large_head","index":1},{"id":"tall_narrow_long_legged","index":2},{"id":"slender_long_limb","index":3},{"id":"stocky_broad_chested","index":4}],"role_path":"experiments/current-form-surface-preview/structural_profile_candidates.json","sha256":"a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640"},"repository":{"revision":"f3d7a5c897c5ee1c8de49c682d6c2cf8203ab859","worktree":"/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor"},"reproduction":{"pinned_launcher":"experiments/current-form-surface-preview/surface_preview_launcher.sh","profile_seed_invocations":[{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output /tmp/ck-r1-repro-standard-17","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output /tmp/ck-r1-repro-standard-29","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output /tmp/ck-r1-repro2-0-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output /tmp/ck-r1-repro2-0-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output /tmp/ck-r1-repro2-1-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output /tmp/ck-r1-repro2-1-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output /tmp/ck-r1-repro2-2-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output /tmp/ck-r1-repro2-2-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output /tmp/ck-r1-repro2-3-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output /tmp/ck-r1-repro2-3-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":29}],"public_exact_five":{"command":"PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --baseline-root /home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4 --output /tmp/ck-r1-public-rejection","exit_code":1,"observed_stderr":"exact_five_runner: error: managed tests did not all pass","output_exists":false}},"retained_baseline":{"comparison_report":{"bytes":24640,"role_path":"comparison/comparison-report.json","sha256":"fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a"},"comparison_report_sidecar":{"bytes":89,"role_path":"comparison/comparison-report.sha256","sha256":"27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac"},"outer_file_count":96,"payload_identities":[{"bytes":6556,"role_path":"seed-17/direct.png","sha256":"b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed"},{"bytes":8444,"role_path":"seed-17/lineage.png","sha256":"19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2"}],"root":"/home/ben/.cache/creature-kernel/owned-root-assembly-successor/correction-batch-20260905-4","runtime_fingerprint_sha256":"c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085","stable_manifests":[{"bytes":6367,"role_path":"seed-17/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"},{"bytes":6367,"role_path":"seed-29/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"}]},"schema":"owned-root-assembly-successor.correction-round-1-preflight-trigger.v1","source":{"bytes":56984,"role_path":"examples/body-documents/stylized-digitigrade-biped-authored-form.json","sha256":"82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14"},"status":"authorized_pending_implementation","target_round":1,"verification":{"metric_collection":"completed through project_profile, surface.evaluate, chart.build_chart_summary, anatomy.measure_anatomy, mesh_correctness.port_loop_metrics, and existing fold sampling","metric_collection_seeds":[17,29],"metric_failure_set_identical_across_seeds":true,"public_exact_five_full_suite":"failed before profile publication at managed tests; not a complete exact-five pass","publisher_baseline_function_direct_readmission":"failed with input-manifest.json changed after inventory; this is an orchestration validation limitation, not a geometry gate result","source_profile_and_baseline_identity":"passed through pinned launcher-backed checks"}} \ No newline at end of file +{"authorization":"Ben authorized one bounded correction round within the existing shared-surface representation, preceded by feasibility evidence.","candidate":"dimension-driven-shared-attachment-correction","limitations":["This is pre-correction trigger evidence, not a proposed formula and not evidence that round 1 will pass.","The public exact-five launcher stopped at managed tests before baseline admission; no complete ten-bundle, cross-seed, causality, publication, or gallery suite was run.","The profile/seed runner passed the standard-neutral profile but rejected the four non-neutral profiles before successful bundles could be sealed.","The metrics are mechanical geometry/anatomy evidence; they do not replace visual appraisal and do not claim universal morphology support.","Round-0 implementation and evidence remain historical and must be regenerated if the shared construction changes."],"limits":{"formula_recommendation_in_this_record":false,"gate_change":false,"hidden_or_duplicate_surface":false,"new_representation":false,"port_or_ownership_change":false,"profile_id_or_label_in_geometry":false,"profile_specific_branch_or_exception":false,"profile_specific_geometry":false,"renderer_change":false,"solver_optimizer_remesher_or_render_offset":false,"subdivision_change":false,"threshold_change":false,"topology_change":false},"neutral_result":{"all_unchanged_geometry_and_anatomy_gates":"not_failed_in_metric_collection","co_normal_threshold":0.8,"observed_failures":0,"profile_id":"standard_neutral_reference","profile_index":0},"observed_failures":[{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9824359163771204,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9819673659444469,"observed_min":0.5000448704318414,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.9820268975411749,"observed_min":0.5000448704318412,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360806,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9936052547897188,"observed_min":0.7539903310360805,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.994228784030396,"observed_min":0.7539903310360814,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360817,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9945365518262832,"observed_min":0.7539903310360809,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":1.0110294117647054,"observed_min":1.0110294117647054,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.6760110294117647,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.6760110294117643,"observed_min":0.7883108476742614,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8825867318755838,"observed_min":0.3445026898419853,"profile_id":"tall_narrow_long_legged","profile_index":2,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L0.co_normal","observed_max":0.9942452765149431,"observed_min":0.6869732592904183,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L1.co_normal","observed_max":0.9970230172826258,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_arm.L2.co_normal","observed_max":0.9970925335383799,"observed_min":0.6869732592904187,"profile_id":"slender_long_limb","profile_index":3,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__left_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695751693,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"continuity","gate_id":"continuity.junction.pelvis__right_hip.L0.fold_angle","observed_max":97.38631369768623,"observed_min":1.4488005695749178,"profile_id":"slender_long_limb","profile_index":3,"sample_count":8,"threshold":90.0,"threshold_relation":"lt","unit":"degree"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L0","observed_max":0.7999999999999998,"observed_min":0.7999999999999998,"profile_id":"slender_long_limb","profile_index":3,"sample_count":6,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L1","observed_max":1.625,"observed_min":0.5687803159441813,"profile_id":"slender_long_limb","profile_index":3,"sample_count":14,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.left.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"anatomy","gate_id":"anatomy.pelvic_lateral_ratio.right.L2","observed_max":1.8843118264295065,"observed_min":0.040088424574552306,"profile_id":"slender_long_limb","profile_index":3,"sample_count":30,"threshold":1.05,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L0.co_normal","observed_max":0.9812769037641295,"observed_min":0.40354127155951336,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":8,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L1.co_normal","observed_max":0.9804825094231879,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":16,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.left_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595129,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.port.right_thigh.L2.co_normal","observed_max":0.980483037677655,"observed_min":0.4035412715595132,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":32,"threshold":0.8,"threshold_relation":"ge","unit":"dimensionless"},{"category":"continuity","gate_id":"continuity.junction.pelvis__abdomen.L0.fold_angle","observed_max":91.31293023554761,"observed_min":33.087900440787394,"profile_id":"stocky_broad_chested","profile_index":4,"sample_count":10,"threshold":90.0,"threshold_relation":"lt","unit":"degree"}],"permitted_scope":{"domains":["domain.left_hip","domain.left_shoulder","domain.right_hip","domain.right_shoulder"],"formula_ids":["formula.hip.left","formula.hip.right","formula.shoulder.left","formula.shoulder.right"],"kind":"one shared dimension-driven attachment-construction correction","mechanical_consequences":["update affected executable/reference formulas together","update derived dependency, derivative, support, and identity records","regenerate neutral evidence","revalidate and refreeze only after two fresh independent reviews"],"required_property":"derive each attachment from the existing adjoining-region inputs and preserve one welded shared surface with source-level causal effect"},"prior_design_contract":{"bytes":173184,"correction_round":0,"role_path":"experiments/owned-root-assembly-successor/design-contract.md","sha256":"3122f0db2235754ed782bd38a88c4d7ad7cc7edbf635d147194f1e93f8556490"},"prior_round":0,"profile_table":{"bytes":29970,"profiles":[{"id":"standard_neutral_reference","index":0},{"id":"compact_broad_short_limb_large_head","index":1},{"id":"tall_narrow_long_legged","index":2},{"id":"slender_long_limb","index":3},{"id":"stocky_broad_chested","index":4}],"role_path":"experiments/current-form-surface-preview/structural_profile_candidates.json","sha256":"a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640"},"repository":{"revision":"f3d7a5c897c5ee1c8de49c682d6c2cf8203ab859","worktree":"REPOSITORY_ROOT"},"reproduction":{"pinned_launcher":"experiments/current-form-surface-preview/surface_preview_launcher.sh","profile_seed_invocations":[{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output OUTPUT_ROOT/ck-r1-repro-standard-17","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile standard_neutral_reference --output OUTPUT_ROOT/ck-r1-repro-standard-29","exit_code":0,"output_exists":true,"profile_id":"standard_neutral_reference","profile_index":0,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output OUTPUT_ROOT/ck-r1-repro2-0-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile compact_broad_short_limb_large_head --output OUTPUT_ROOT/ck-r1-repro2-0-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"compact_broad_short_limb_large_head","profile_index":1,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output OUTPUT_ROOT/ck-r1-repro2-1-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile tall_narrow_long_legged --output OUTPUT_ROOT/ck-r1-repro2-1-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"tall_narrow_long_legged","profile_index":2,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output OUTPUT_ROOT/ck-r1-repro2-2-17","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile slender_long_limb --output OUTPUT_ROOT/ck-r1-repro2-2-29","exit_code":1,"observed_stderr":"exact_five_runner: error: anatomy gates failed: anatomy.pelvic_lateral_ratio.left.L0, anatomy.pelvic_lateral_ratio.left.L1, anatomy.pelvic_lateral_ratio.left.L2, anatomy.pelvic_lateral_ratio.right.L0, anatomy.pelvic_lateral_ratio.right.L1, anatomy.pelvic_lateral_ratio.right.L2","output_exists":false,"profile_id":"slender_long_limb","profile_index":3,"seed":29},{"command":"PYTHONHASHSEED=17 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output OUTPUT_ROOT/ck-r1-repro2-3-17","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":17},{"command":"PYTHONHASHSEED=29 experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/owned-root-assembly-successor-exact-five/exact_five_runner.py --profile stocky_broad_chested --output OUTPUT_ROOT/ck-r1-repro2-3-29","exit_code":1,"observed_stderr":"exact_five_runner: error: port induced co-normal gate failed","output_exists":false,"profile_id":"stocky_broad_chested","profile_index":4,"seed":29}],"public_exact_five":{"command":"PYTHONHASHSEED=0 experiments/owned-root-assembly-successor-exact-five/exact_five_launcher.sh --baseline-root LOGICAL_CACHE/owned-root-assembly-successor/correction-batch-20260905-4 --output OUTPUT_ROOT/ck-r1-public-rejection","exit_code":1,"observed_stderr":"exact_five_runner: error: managed tests did not all pass","output_exists":false},"path_notation":{"repository_root":"REPOSITORY_ROOT","logical_cache":"LOGICAL_CACHE/... (logical identifier, not a literal filesystem path)","output_root":"OUTPUT_ROOT/... (fresh invocation output root; literal absolute path omitted)"}},"retained_baseline":{"comparison_report":{"bytes":24640,"role_path":"comparison/comparison-report.json","sha256":"fe450e9047275c517de297f50b9ed7881c969fd2c315e9714334dcb8d9e68f2a"},"comparison_report_sidecar":{"bytes":89,"role_path":"comparison/comparison-report.sha256","sha256":"27d4941acc57c9a800c2ee76205dd349f401f900d6ed0ee01b3d07925df85dac"},"outer_file_count":96,"payload_identities":[{"bytes":6556,"role_path":"seed-17/direct.png","sha256":"b98d9cf219cad3c60ce43921fc86be7817529fd93448386860738b60110075ed"},{"bytes":8444,"role_path":"seed-17/lineage.png","sha256":"19a006f8f237857d94821894016364dcc446caece3358e9c6da0794a75bf74d2"}],"root":"LOGICAL_CACHE/owned-root-assembly-successor/correction-batch-20260905-4","runtime_fingerprint_sha256":"c19ca9c0b8268504f93513d55f90a0eb63777e566aba06e376b503c5e648f085","stable_manifests":[{"bytes":6367,"role_path":"seed-17/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"},{"bytes":6367,"role_path":"seed-29/stable-manifest.json","sha256":"1b4aaed96671a55ae65dc163fd80db45288daf1b9dc9c91745bf19e414fa7ffa"}]},"schema":"owned-root-assembly-successor.correction-round-1-preflight-trigger.v1","source":{"bytes":56984,"role_path":"examples/body-documents/stylized-digitigrade-biped-authored-form.json","sha256":"82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14"},"status":"authorized_pending_implementation","target_round":1,"verification":{"metric_collection":"completed through project_profile, surface.evaluate, chart.build_chart_summary, anatomy.measure_anatomy, mesh_correctness.port_loop_metrics, and existing fold sampling","metric_collection_seeds":[17,29],"metric_failure_set_identical_across_seeds":"unestablished","public_exact_five_full_suite":"stopped before baseline admission when managed tests did not all pass; not a complete exact-five pass","publisher_baseline_function_direct_readmission":"unverified orchestration limitation only: an undocumented publisher readmission attempt reportedly saw input-manifest.json changed after inventory; not positive evidence and not a geometry gate result","source_profile_identity":"passed through pinned launcher-backed checks","baseline_identity_admission":"not reached because public execution stopped at managed tests"}} \ No newline at end of file diff --git a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py index 29a87c6..bb95980 100644 --- a/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py +++ b/experiments/owned-root-assembly-successor/tests/test_build_owned_root.py @@ -3,7 +3,6 @@ import inspect import copy import hashlib -import inspect import os from pathlib import Path import sys diff --git a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py index d560142..758a1d8 100644 --- a/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py +++ b/experiments/owned-root-assembly-successor/tests/test_mesh_correctness.py @@ -225,7 +225,7 @@ def test_interval_disjoint_materializes_cut_b_then_cut_a_before_disjunction(self self.assertEqual(calls, [1.0, 2.0]) def test_shared_one_classifier_is_exact_and_swap_invariant(self): - for name, b0, b1, expected in _fixture_shared_one()[:7]: + for name, b0, b1, expected in _fixture_shared_one(): with self.subTest(name=name): first, second = _shared_base(b0, b1) shared, a0, a1 = first diff --git a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py index 83e4850..c1d757f 100644 --- a/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py +++ b/experiments/owned-root-assembly-successor/tests/test_prepared_projection.py @@ -33,12 +33,9 @@ import artifact_serialization as artifacts import prepared_projection as projection from prepared_projection import ( - MUST_AFFECT_COMPONENTS, - MUST_AFFECT_PARAMETER_IDS, - PERTURBATION_DELTA_M, - PreparedProjectionError, - GeometryComponents, - _admit_profile_bytes, + MUST_AFFECT_COMPONENTS, MUST_AFFECT_PARAMETER_IDS, + PERTURBATION_DELTA_M, PreparedProjectionError, + GeometryComponents, _admit_profile_bytes, _admit_source_bytes, _validate_binding_records, _validate_profile_table, @@ -201,6 +198,12 @@ def test_project_perturbed_geometry_copies_one_prepared_scalar_before_projection for bad in ("unknown", "left.r_y.extra", 1): with self.subTest(parameter=bad), self.assertRaises(PreparedProjectionError): project_perturbed_geometry(self.prepared, bad) with self.assertRaises(PreparedProjectionError): project_perturbed_geometry(self.geometry, MUST_AFFECT_PARAMETER_IDS[0]) + def test_perturbation_scope_uses_committed_json_operation(self): + parameter = MUST_AFFECT_PARAMETER_IDS[0] + index = projection._GEOMETRY_COMPONENT_IDS.index(MUST_AFFECT_COMPONENTS[parameter]) + expected = list(self.geometry.values); expected[index] = float(expected[index] + PERTURBATION_DELTA_M) + with patch.object(projection, "_JSON_BYTES", side_effect=AssertionError("mutable serializer used")): + self.assertEqual(project_perturbed_geometry(self.prepared, parameter).values, tuple(expected)) def test_complete_prepared_schema_values_and_runtime_types(self): prepared = self.prepared self.assertEqual(set(prepared), { @@ -305,21 +308,19 @@ def test_validator_reuses_expected_projection_bytes_for_same_digest_triple(self) self.assertIs(validate(self.prepared), self.prepared) self.assertIs(validate(self.prepared), self.prepared) self.assertEqual(build_prepared.call_count, 1) - def test_validator_rebuilds_for_changed_digest_and_rejects_fixed_input_drift(self): + def test_validator_rejects_changed_digest_before_cache_insertion_and_fixed_input_drift(self): fixed_inputs = projection._fixed_inputs(SOURCE, CONTRACT, PROFILE_TABLE) changed_digest = "f" * 64 changed_inputs = (*fixed_inputs[:4], changed_digest) - changed = copy.deepcopy(self.prepared) - changed["profile_selection"]["profile_table_sha256"] = changed_digest - changed["provenance"]["source_files"][1]["sha256"] = changed_digest with patch.object(projection, "_fixed_inputs", side_effect=[fixed_inputs, changed_inputs]): with patch.object(projection, "_build_prepared", wraps=projection._build_prepared) as build_prepared: validate = projection._prepared_apis(projection._COMMITMENTS)[0] self.assertIs(validate(self.prepared), self.prepared) - self.assertIs(validate(changed), changed) - self.assertEqual(build_prepared.call_count, 2) + with self.assertRaisesRegex(PreparedProjectionError, "fixed input identity"): + validate(self.prepared) + self.assertEqual(build_prepared.call_count, 1) drifted = SOURCE.read_bytes().replace(b'"forward": "+z"', b'"forward": "-z"', 1) calls = [0] def inputs_with_drift(*args): diff --git a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py index 0d68a25..aade677 100644 --- a/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py +++ b/experiments/programmatic-root-complex-surface/tests/test_prepared_projection.py @@ -145,7 +145,7 @@ def test_consumed_source_rejects_invalid_dimension_values(self): for value, message in cases: with self.subTest(value=value): self.assert_rejected(rf"body\.dimensions\[\d+\]\.value: {message}", lambda source, value=value: source["body"]["dimensions"][self.record_index(source, "dimensions", pelvis, role)].__setitem__("value", value)) - for index in range(153): + for index in range(len(self.source["body"]["dimensions"])): with self.subTest(index=index): self.assert_rejected(rf"body\.dimensions\[{index}\]\.value: expected positive number", lambda source, index=index: source["body"]["dimensions"][index].__setitem__("value", 0)) def test_canonical_metre_dimensions_and_non_dimension_routes(self): From e8c65160fa451b728c3ebad1672fb160e17bfb8c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 20:13:22 +1200 Subject: [PATCH 25/38] Mark superseded investigation historical and correct stack dependencies --- docs/project/current-handover.md | 2 +- docs/project/stacked-integration-ledger.md | 13 +++++++++++++ docs/project/status.md | 2 +- docs/research/owned-root-assembly-investigation.md | 11 ++++++++--- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/project/current-handover.md b/docs/project/current-handover.md index dfbe4ca..d9fecab 100644 --- a/docs/project/current-handover.md +++ b/docs/project/current-handover.md @@ -16,7 +16,7 @@ executable, and profile verification; no algorithm changed. Revalidate the pause snapshot and these status pointers before continuing the lowest integration lane: PR #127 plus up to two dependent follow-ups, with each layer below 100 changed files. PR #127 currently has 57 prospective paths; the two -planned follow-ups are approximately 87 and 84 paths. Packaging and review remain primary, and upper-work must not +planned follow-ups are approximately 92 and 79 paths. Packaging and review remain primary, and upper-work must not delay the lower lane. A genuine final-review-ready clean immutable head may then receive the hosted and committed-diff CLI review cycle together. Current real-browser coverage is deferred; no browser repair or setup lane remains diff --git a/docs/project/stacked-integration-ledger.md b/docs/project/stacked-integration-ledger.md index 2a326a6..88f955c 100644 --- a/docs/project/stacked-integration-ledger.md +++ b/docs/project/stacked-integration-ledger.md @@ -111,6 +111,19 @@ those overlays gives planning totals of about 87 for Layer 2 and 84 for Layer 3. Do not copy a later final README/status wholesale into an earlier layer; materialize stage-specific overlays only after their referenced paths exist. +## Source-only relocation audit — 2026-09-08 + +Main's lower test-read audit identifies five JSON files currently planned in +Layer 3 that belong with Layer 2: `arm-inputs.json`, `head-inputs.json`, +`head-refinement-inputs.json`, `body-junction-integration-config.json`, and +`body-chest-envelope-config.json`. Moving these planned paths changes the +current local Layer 2/3 planning counts from 83/80 to 88/75; with four repeated +documentation paths, the planning totals are about 92/79. This is source-only +planning evidence: no execution, import, or geometry work occurred, and +external snapshot dependencies remain required and unverified. The original +timestamped inventory and manifest hashes above remain historical; this note +does not assert a new measured inventory. + ## Placement and retention decisions All 180 eligible local paths are assigned above; there are no omissions or diff --git a/docs/project/status.md b/docs/project/status.md index 56e8a82..845c3ef 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -24,7 +24,7 @@ require current-PID, executable, and profile verification; no algorithm changed. Revalidate this pause snapshot and the current handover before continuing the lowest integration lane: PR #127 currently has 57 prospective paths; its two planned follow-ups are -approximately 87 and 84 paths, each below 100 changed files. Packaging and review remain primary, and +approximately 92 and 79 paths, each below 100 changed files. Packaging and review remain primary, and upper-work must not delay that lower lane. A genuine final-review-ready clean immutable head is required before the hosted and committed-diff CLI review cycle runs together. Current real-browser coverage is deferred; no browser repair or diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index 23b70a3..3b57876 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -1,13 +1,17 @@ # Owned root assembly investigation -Status: Frozen candidate implementation phase; Ben-authorized bounded -investigation; experiment-local and non-normative +Status: Historical; stopped and superseded candidate plan; experiment-local and +non-normative This is the settled successor plan after the terminal seven-ring candidate in the [programmatic root-complex investigation](programmatic-root-complex-surface-investigation.md). It does not define product behaviour, a production surface contract, canonical Regions or Sockets, a permanent topology, or a backend. It cannot satisfy or replace the DR-0013 Stage 1 proof. DR-0009 and DR-0010 remain parked. +This entire investigation is retained as historical plan and evidence context. +Its frozen implementation phase, exact-five attempt, and named human +checkpoint are superseded and do not authorize further work. Current +continuation is governed solely by the [Active runway](../project/status.md#active-runway). ## Canonical metre repair evidence and boundary @@ -30,7 +34,8 @@ with SHA-256 paragraph records only the source/hash metadata rebaseline: standard-neutral geometry was expected, and is now proven, to remain unchanged. Historical source and evidence remain untouched. The successor-neutral implementation is -complete; exact-five activation and its later human checkpoint remain active. +complete; the exact-five attempt and its later human checkpoint are superseded +historical material and do not authorize continuation. ## Research-question mapping From 3f42a429164e5e639ed7a92b0fe3f58f40db1dd1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 20:36:52 +1200 Subject: [PATCH 26/38] Simplify whole-PR review and scope Overseer instruction maintenance --- .../ai-delegation-and-review.md | 103 ++++++++++-------- .../owned-root-assembly-investigation.md | 4 +- 2 files changed, 59 insertions(+), 48 deletions(-) diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index f2d716e..206bd2c 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -422,59 +422,70 @@ his explicit, recorded authorization before merge. Routine auto-merge, unattended merge loops, administrator bypass, and an unrecorded runway are not merge authority. +Ben has explicitly authorized the assigned Overseer to originate, create, push, +review, and auto-merge only small future instruction-maintenance PRs. An +eligible PR changes only `AGENTS.md` and/or this workflow, and only to update +reusable AI working instructions, links, or routing clarifications; it contains +no runtime code or feature work and does not change product purpose or scope, +product/specification/architecture contracts, the Active runway, retained-human +decisions, morphology or runtime promises, platform, licensing, cost, privacy, +or feature-PR merge authority. A bounded subagent prepares the change under the +normal delegation contract and must not spawn descendants. The Overseer +personally inspects the exact small diff and runs applicable documentation +validation and CI before merging; all ordinary review gates still apply. If an +active PR already owns either file, +integrate through its owner or defer; do not create a competing PR. This +standing authorization is Ben's explicit control-plane approval and merge +authorization only for that future class; it grants no broader authority and +waives no check. A mixed-scope or otherwise ineligible PR remains outside this +class; the Main Worker reports that gate. + ## CodeRabbit and external review For a substantial PR, the main thread pushes its first coherent, review-useful head early enough for external review to run in parallel with later disjoint work in the same PR. It does not wait for every planned addition to be complete -before starting the review clock. For each review-useful head, the main thread -launches the hosted CodeRabbit pass and the committed-diff CLI pass in parallel -as one deliberate cycle. Both review the same clean, immutable pushed OID. -Before launching, the main thread fetches the PR branch, requires the committed -tree to match the intended review content, verifies local `HEAD` equals the -remote PR-head OID, and records that OID with both results. Uncommitted disjoint -follow-on work may remain local and is not represented as reviewed. - -The CLI pass supports the hosted pass but cannot satisfy the hosted taper gate. -Every changed pushed head receives a fresh hosted-plus-CLI cycle; findings -from an earlier OID do not cover a later head. While the hosted pass runs, the -main thread does not push or mutate the remote PR head. It may prepare local -fixes without presenting them as reviewed. - -After both results complete, the main thread verifies each finding, fixes or -explicitly dispositions it, ensures the required local and CI checks are run, -and pushes -the next head only when the result is ready for a new cycle. Hosted taper is -reached when a fresh hosted pass produces no new material findings, or only -repeats, non-actionable findings, disproportionate suggestions, or -out-of-scope items; remaining items have recorded dispositions. After -implementation is complete, three consecutive hosted passes with at most two -new actionable findings each create a presumption that taper has been -reached. Continuing beyond that presumption requires a main-thread-validated -material correctness, contract, evidence-integrity, security, or safety issue. -Formatting/readability, minor test cleanup, speculative hardening, -already-dispositioned repeats, and disproportionate suggestions do not reset -the streak or justify another cycle. The main thread does not fix nonmaterial -suggestions merely to manufacture another review head. After fixing a material -issue, it performs one final exact-head hosted-plus-CLI cycle and repeats only -if that cycle finds another validated material issue. Zero findings is never -the target. - -When warranted, the committed-diff command is -`coderabbit review --agent --committed --base /` against a -fetched remote-tracking base. This supporting command does not replace the -hosted pass, internal review, tests, hands-on trials, CI, or human gates. - -If hosted CodeRabbit is unavailable or rate-limited, the main thread records +before starting the review clock. For each review-useful pushed head, launch the +hosted CodeRabbit pass on the current pushed head and a committed-diff CLI pass +in parallel as one cycle. Keep the remote head immutable while hosted review +runs. Every CLI pass reviews the entire current PR against the actual fetched +PR base; for a stacked PR, use its immediate lower branch as the base. Fetch +that exact base before each pass so the command targets the current whole-PR +diff. A partial, latest-commit-only, selected-path, or previous-delta review is +not a review cycle. + +While hosted review runs, the main thread may continue useful whole-PR CLI +cycles on evolving local commits without waiting for hosted review. Each cycle +has a deliberate, finite purpose; no unattended or empty repeat is allowed. +Fix validated material findings and rerun the affected whole-PR review. Stop +when the candidate and review findings are ready, or when another existing gate +applies. Do not push a local candidate until hosted review of the current pushed +head reaches a terminal state. + +Practical taper is reached when the latest relevant hosted review and latest +whole-PR CLI review produce no new validated material findings, or only repeats, +non-actionable findings, disproportionate suggestions, or out-of-scope items. +The Main Worker judges taper; a raw zero-finding result is unnecessary. Ordinary +validation and CI, finding disposition, independent review, external-review, +checkpoint, and human merge gates still apply. The committed-diff command is +`coderabbit review --agent --committed --base /` with the +actual fetched PR base; it supports but does not replace hosted review, internal +review, tests, hands-on trials, CI, or human gates. +GitHub checks and actual review outputs suffice as operational evidence. Keep +only transient base/head context needed to target running reviews; do not create +ledgers, review evidence documents, routine PR disposition comments, or +persistent OID/command records merely to prove that review occurred. + +If hosted CodeRabbit is unavailable or rate-limited, the main thread reports that outcome honestly and waits for availability while doing safe, non-conflicting work, or stops for an explicit Ben waiver. It does not merge -without the waiver. Keep the immutable-head restriction until the hosted pass -reaches a terminal state. After one bounded wait and one status recheck, -record a service-declared failure or cancellation as terminal. If a stale run -exposes neither a terminal state nor a cancellation route, abandon that pass -as unavailable, record its reviewed OID and outcome, release the restriction, -and treat later output as stale. No unattended polling, automatic retry loop, -or timer continues the cycle. +without the required hosted review or an explicit Ben waiver. Keep the +immutable-head restriction until the hosted pass reaches a terminal state. After +one bounded wait and one status recheck, +recognize a service-declared failure or cancellation as unavailable. If a stale +run exposes neither a terminal state nor a cancellation route, treat that pass +as unavailable, release the restriction, and treat later output as stale. No +unattended polling, automatic retry loop, or timer continues the cycle. Automatic initial and incremental reviews and automatic review/chat responses remain disabled. The main thread may invoke CodeRabbit autonomously under this diff --git a/docs/research/owned-root-assembly-investigation.md b/docs/research/owned-root-assembly-investigation.md index 3b57876..bd93204 100644 --- a/docs/research/owned-root-assembly-investigation.md +++ b/docs/research/owned-root-assembly-investigation.md @@ -191,8 +191,8 @@ profile expansion. ## Execution order and stop rule -The work proceeds in this order; items 1 through 5 are complete and item 6 is -active: +This historical sequence recorded items 1 through 5 as complete at that stage; +item 6 was the conditional next step and is now stopped and superseded: 1. audit the terminal candidate's utilities for representation-independent reuse; From f3295a243d4989cbecfb75b6e319740d8cce8ddc Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 20:44:29 +1200 Subject: [PATCH 27/38] Clarify lightweight Overseer coordination and maintenance authority --- AGENTS.md | 6 ++- .../ai-delegation-and-review.md | 37 +++++++++++-------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3edfb81..f5f9fb0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,8 @@ These are roles rather than model identities. Persistent Astra use applies only to Ben's explicitly recorded task/role assignment and its authorized scope and duration; it grants no permission for other or new tasks or extensions. Ben's retained boundaries above remain unchanged; this split adds -no serial permission gate or merge/descendant authority. +no serial permission gate or merge/descendant authority. The separately scoped +instruction-maintenance exception remains governed by the conditional workflow. Routine, reversible technical implementation may proceed autonomously within a recorded runway. This includes implementation details, defect resolution, @@ -110,7 +111,8 @@ checkpoint explicitly named for Ben's appraisal, or a retained-human boundary, and present that candidate with the judgment Ben is being asked to make. That candidate must not be merged autonomously; it requires Ben's explicit, recorded authorization. An instruction for one PR is not standing authority for later -PRs. +PRs, except the separately scoped instruction-maintenance class expressly +authorized by Ben and recorded in the conditional workflow. Changes to agent authority, workflow routing, merge authority, retained-human boundaries, or the governing runway scope are presented to Ben and require his diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index 206bd2c..ff422ad 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -35,7 +35,15 @@ Main Worker and Overseer are roles rather than model identities. Persistent Astra use applies only to Ben's explicitly recorded task/role assignment and its authorized scope and duration; it grants no permission for other or new tasks or extensions. There is no serial permission gate between them, and this -split adds no merge or descendant authority. +split adds no merge or descendant authority; the separately scoped +instruction-maintenance exception remains governed below. + +At an already applicable merge or checkpoint gate, the Overseer may cheaply +inspect actual review outcomes and check status, verify the agreed taper and +standing user preferences, and catch omitted or forgotten instructions. This +lightweight coordination check does not repeat technical audits or tests, +create new ledgers or proof machinery, or open a routine permission round. +Existing consequential strategic and visual oversight remains unchanged. The Main Worker and Overseer delegate routine reading, writing, and tests by default; they retain technical reasoning, decisive evidence inspection, and @@ -523,20 +531,19 @@ concurrent entries, and does not create an inbox-zero obligation. ### Selective process-improvement stewardship At meaningful existing oversight or checkpoint boundaries, the explicitly -assigned Overseer selectively considers worthwhile batches of reported process, -tooling, evidence, validation, or context-efficiency improvement candidates. -The Overseer may delegate bounded, authorized fact gathering, grouping, and -evidence checks, then personally judges a compact shortlist for usefulness, -priority, and scope before commissioning the Main Worker or an executor. This -is not a timer, fixed cadence, whole-inbox scan, second backlog, or new suite. - -Recurrence is a signal, not a prerequisite for an obvious, evidenced, -low-cost, reusable improvement. A same-task bug remains immediate -implementation work rather than an observation. Weigh expected benefit against -implementation and maintenance cost, and prefer existing tools. Existing -authorized reversible fixes may proceed; retained-human decisions go to Ben. -This role does not grant protected-inbox access: stewardship uses reported -candidates or separately access-authorized material. +assigned Overseer considers reported, evidenced candidates for reusable +process, tooling, evidence, validation, or context-efficiency improvements. +The Overseer may delegate bounded fact gathering and evidence checks, then +personally judge usefulness, priority, and scope before commissioning the Main +Worker or an executor. + +Recurrence is not required for an obvious, evidenced, low-cost improvement; +same-task bugs remain immediate implementation work. Prefer existing tools and +weigh benefit against implementation and maintenance cost. Existing authorized +reversible fixes may proceed; retained-human decisions go to Ben. This +stewardship uses reported or separately access-authorized material, preserves +protected-inbox access restrictions and human boundaries, and creates no fixed +cadence, whole-inbox scan, second backlog, or new suite. A repeated issue closes through a concrete bounded fix to a repository wrapper, preflight, active instruction, or other available tool path; restating the From 7870d696e2065a376d90f1f04fc7c8ff3dc249eb Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 20:53:24 +1200 Subject: [PATCH 28/38] Clarify responsible instruction review and concise handoffs --- .../ai-delegation-and-review.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index ff422ad..f291df5 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -120,6 +120,11 @@ approval gates. “Main Worker” and “Overseer” are roles, not model names; existing model authorization, routing, and human boundaries remain unchanged, and this does not grant global Astra orchestration. +The responsible Main Worker or Overseer may read a short, cohesive instruction +document in full when judging a change. This semantic review is not duplication +of bulk fact gathering: delegate mechanical work, but a summary or isolated +diff cannot replace responsible whole-document assessment. + ## Batches and research passes The main thread groups related product, direction-setting, architecture-boundary, @@ -565,12 +570,7 @@ summary as proof, reconciles interactions, and performs consolidated validation against the integrated result. It does not create an external effect merely because a worker reports completion. -The final handoff is brief and auditable. Use one line per subagent: - -`Subagent: ; model: ; reasoning effort: ; | evidence only>` - -Then provide one validation line covering subagent-scoped and main -consolidated checks, including explicit `deferred` or `unavailable` states. -State the number of subagents used, any explicitly authorized routing -deviation, and any incomplete review coverage. Do not substitute a prose -summary for these auditable lines. +The final handoff is concise and truthful: state the actual changes or evidence, +meaningful validation, unresolved blockers or limitations, and any routing +deviation when relevant. Actual outputs plus concise reporting are sufficient; +no fixed per-agent template or agent count is required. From b9d1cfee15925ec6001291c91d7aaca596a62966 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 21:39:21 +1200 Subject: [PATCH 29/38] Use useful review convergence and chronological count checkpoints --- .../ai-delegation-and-review.md | 71 +++++++++++++++---- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index f291df5..7c1b50e 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -469,25 +469,44 @@ not a review cycle. While hosted review runs, the main thread may continue useful whole-PR CLI cycles on evolving local commits without waiting for hosted review. Each cycle -has a deliberate, finite purpose; no unattended or empty repeat is allowed. -Fix validated material findings and rerun the affected whole-PR review. Stop -when the candidate and review findings are ready, or when another existing gate -applies. Do not push a local candidate until hosted review of the current pushed -head reaches a terminal state. - -Practical taper is reached when the latest relevant hosted review and latest -whole-PR CLI review produce no new validated material findings, or only repeats, -non-actionable findings, disproportionate suggestions, or out-of-scope items. -The Main Worker judges taper; a raw zero-finding result is unnecessary. Ordinary -validation and CI, finding disposition, independent review, external-review, -checkpoint, and human merge gates still apply. The committed-diff command is +has a deliberate, finite purpose; unattended or purposeless repeats are not +allowed. A deliberate second hosted confirmation pass on an unchanged remote +head is allowed to establish consecutive convergence and needs no fake code +edit. Fix validated useful findings and rerun the affected whole-PR review. +Stop when the candidate and review findings are ready, or when another existing +gate applies. Do not push a local candidate until hosted review of the current +pushed head reaches a terminal state. + +Practical taper is reached only when hosted CodeRabbit has stopped finding +meaningful or useful improvements on the actual final candidate. Usually this +means two consecutive hosted passes for that candidate, each producing roughly +0–2 findings, with every finding judged not to be a meaningful or useful +improvement (normally a false positive or tiny wording issue). This is a normal +stopping signal, not an arbitrary mandatory count of clean rounds. A substantive +change makes earlier review stale and requires review of the actual final +candidate. Meaningful or useful improvements include worthwhile correctness +fixes, tests, and maintainability improvements even when nonblocking. The Main +Worker judges usefulness and may reject false, disproportionate, non-actionable, +or out-of-scope suggestions without expanding scope. A raw zero-finding or +“zero material blockers” result, or a large count of prior passes, does not +establish taper by itself. + +The whole-PR CLI runs independently on evolving local commits during the hosted +remote freeze and must also cease yielding accepted useful findings before the +final candidate is ready. This supports the hosted significance judgment +without creating a second mandatory clean-round or zero-finding gate; CLI +convergence cannot replace hosted convergence. Ordinary validation and CI, +finding disposition, independent review, external-review, checkpoint, and +human merge gates still apply. The committed-diff command is `coderabbit review --agent --committed --base /` with the actual fetched PR base; it supports but does not replace hosted review, internal review, tests, hands-on trials, CI, or human gates. GitHub checks and actual review outputs suffice as operational evidence. Keep only transient base/head context needed to target running reviews; do not create -ledgers, review evidence documents, routine PR disposition comments, or -persistent OID/command records merely to prove that review occurred. +ledgers, review evidence documents, or routine PR disposition comments beyond +the count-only checkpoint comments specified in PR reports after each distinct +adjudicated completed hosted or CLI round, or persistent OID/command records +merely to prove that review occurred. If hosted CodeRabbit is unavailable or rate-limited, the main thread reports that outcome honestly and waits for availability while doing safe, @@ -509,6 +528,30 @@ submission of repository content. Review allowances, projects, and external systems are not coordinated or coupled across repositories; the main thread does not mutate another project. +### PR reports + +The PR is the shared reporting record; do not create a separately maintained +review chain. When reporting, read existing PR hosted summaries or threads and +the hosted and CLI count-only checkpoint comments, then present the actual +completion order including late posts, +ask the owner only for meaningful missing or ambiguous counts, and mark missing +evidence. Order PRs by merge priority while respecting dependencies, and state +the purpose, owner, and base, the review chain, and fix status separately from +gaps and readiness. Show each hosted round as `hosted (R/A)` and each CLI round +as `CLI R/A`, where R is raw findings and A is accepted useful findings. +Accepted means judged useful, whether or not blocking; it does not mean fixed. +Distinct completed rounds on the same SHA each count; exclude failed or +rate-limited rounds and include zero-finding rounds. + +After each distinct adjudicated completed hosted or CLI round, check whether its +count snapshot is already present and, if absent, promptly post exactly one +short count-only PR comment. Use `**Hosted: 8 found / 6 accepted**` for hosted +rounds and `**CLI: 8 found / 6 accepted**` for CLI rounds; optionally include +the actual review time in Pacific/Auckland and an abbreviated SHA. Do not +include finding lists, explanations, validation inventories, or fix-tracking +promises in either comment. A read-only PR report does not trigger reviews, +resume work, merge, or routine chat reconstruction. + ## Operational observations Every executor reports unexpected operational friction that forces a retry, From 16d1fd148feaa5f94007ed3857be29cf329ce19a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 8 Sep 2026 22:07:55 +1200 Subject: [PATCH 30/38] Address useful gallery, staging, and validation review findings --- .../src/provisional_form_inspection.rs | 19 +-- .../publish_exact_five_gallery.py | 5 +- dev-tools/visual-review/static/app.js | 23 ++-- .../tests/test_browser_trial.ps1 | 95 +++++++++++-- .../tests/test_exact_five_gallery.py | 15 ++ .../visual-review/tests/test_visual_review.py | 130 +++++++++++++++++- docs/project/stacked-integration-ledger.md | 56 ++++---- docs/project/status.md | 2 +- .../exact_five_launcher.sh | 4 +- .../exact_five_publisher.py | 39 +++++- .../exact_five_runner.py | 20 ++- .../tests/test_exact_five_activation.py | 72 +++++++++- .../build_owned_root.py | 18 +-- .../tests/test_render_export.py | 3 - 14 files changed, 418 insertions(+), 83 deletions(-) diff --git a/crates/creature-kernel-cli/src/provisional_form_inspection.rs b/crates/creature-kernel-cli/src/provisional_form_inspection.rs index 8cbf1fd..d03c618 100644 --- a/crates/creature-kernel-cli/src/provisional_form_inspection.rs +++ b/crates/creature-kernel-cli/src/provisional_form_inspection.rs @@ -1028,14 +1028,17 @@ fn canonical_metres_to_display_permille(value: NormalizedBinary64) -> Result