docs/superpowers/plans/2026-10-19-fold.md

main
fold/docs/superpowers/plans/2026-10-19-fold.md rendered · source · history · blame · raw

2243 lines · 153670 bytes

27 symbols in this file
   1# Fold Implementation Plan
   2
   3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
   4
   5**Goal:** An iOS app that folds traditional origami models under your finger and generates their Yoshizawa–Randlett diagrams from the same data, so the diagram and the model cannot disagree.
   6
   7**Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds and sinks have no rigid path with the flap closed; they are flagged non-rigid and open, pop and close (decision 0002), the pop held to 10% strain on a render mesh. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app.
   8
   9**Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app.
  10
  11**Spec:** `docs/superpowers/specs/2026-10-19-fold-design.md`
  12
  13## Global Constraints
  14
  15- iOS 26 deployment target; Swift 6 language mode.
  16- `TARGETED_DEVICE_FAMILY = "1,2"`; `PRODUCT_BUNDLE_IDENTIFIER = sh.krz.fold`; `DEVELOPMENT_TEAM = ZCNAX3VL9D`; `bundleIdPrefix: sh.krz`.
  17- `FoldKit` targets must not import UIKit or SwiftUI. `Renderer` may import Metal and MetalKit. `foldc` and `foldlint` are macOS executables and never ship in the app.
  18- Models are FOLD 1.2 files (Demaine, Ku and Lang, 2016; `github.com/edemaine/fold`). Standard keys used: `vertices_coords`, `edges_vertices`, `edges_assignment`, `edges_foldAngle`, `faces_vertices`, `faceOrders`, `file_frames`, `frame_parent`, `frame_inherit`, `file_spec`, `file_creator`, `file_classes`, `file_title`, `file_author`.
  19- `edges_assignment` codes: `B` boundary, `M` mountain, `V` valley, `F` flat, `U` unassigned. `C` and `J` are rejected.
  20- `edges_foldAngle` is degrees in −180...180, positive for valley, negative for mountain, 0 for `F`, `U` and `B`.
  21- `faceOrders` triples are `[f, g, s]`; `s = +1` means `f` is above `g` **on the side `g`'s normal points toward**, so the sign is evaluated against the current view direction, not absolutely, and two triples can only be compared after normalising each by its `g`'s folded-state normal. Cycles (after normalising) are rejected.
  22- Faces are convex. FOLD's alternative, splitting faces with `J` edges, is not supported. A crease that ends inside the sheet (a pinch or partial crease) leaves a nonconvex face around its end; split that face with a **subdivision edge** — assigned `F`, flat in every frame, creased by no step, `edges_krz:firstCreasedAtStep` null, never drawn. A step creases an edge when its two faces move differently in that step: each face belongs to the deepest axis whose moving set contains it, or to the fixed group, and the edge is creased when the groups differ. So every edge a fold-and-unfold crosses is creased, not only its axis edge, and needs `edges_krz:firstCreasedAtStep`.
  23- Extension keys: `edges_krz:firstCreasedAtStep` (key frame, inherited), `krz:step` (frames 1…N), `krz:faceOrders_midFold` (frames 1…N).
  24- **Step numbering.** Frame 0 is the key frame (the unfolded sheet); `file_frames[i]` is frame `i + 1`. Step n, counting from 1, takes frame n − 1 to frame n and is recorded in frame n's `krz:step`. Every index called a step — in the format, the validator's defects, `FoldStep.index`, the UI — is this n. Defects about one frame's state say `frame:`; defects about a transition or a step record say `step:`; frame n and step n share the number.
  25- Every frame in `file_frames` carries `frame_parent: 0` and `frame_inherit: true`, and never overrides `edges_vertices` or `faces_vertices`.
  26- **One topology across every frame.** Enforced by the decoder and the validator.
  27- **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label.
  28- **`turnOver` and `rotate` change the coordinates.** Frame n is frame n − 1 rotated about its bounding-box centre; the camera does not move.
  29- Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling.
  30- **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks — carry `nonRigid: true` and a `pop` record, and move by open, pop, close (decision 0002, Task 7b): the flap opens rigidly to 20° from flat by default (decision 0003; 30° before it), the tip pops through on the render mesh, and the flap closes rigidly. The isometry gate does not apply to the pop; the bound does: at most 10% largest edge strain on the render mesh. A step with no rigid motion that is not a reverse fold or sink stops compilation and goes to the author.
  31- Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script.
  32- v1 ships **four** traditional models: the cup, the crane, the sampan and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator.
  33- Every shipped model is produced by `foldc` from a committed crease pattern and fold script, and recompiling them reproduces the shipped file (structurally, coordinates within 1e-12). Hand-edited `.fold` files are not shipped.
  34- The **cup is compiled first**, the crane last. Before the cup exists, tests use the synthetic fixtures below; model-level assertions live in Tasks 8 and 15.
  35- The app never advances the fold parameter on its own.
  36- No network calls. No analytics. No accounts.
  37- Ships on the App Store: privacy manifest, screenshots, and every screen passing Xcode's accessibility audit at the default and largest text size.
  38- Work lands through gitbay merge requests, one per batch of tasks; see *Setup*.
  39
  40## Review Focus
  41
  421. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. The petal fold is one of these (decision 0002).
  432. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Decision 0001 found no case for this rule that staggered windows and the clusters do not cover; removing it is the author's call.
  443. **Coplanar stacked facets, and orbiting underneath.** The depth buffer cannot order coplanar or nearly coplanar facets, and `faceOrders`'s `s` sign reverses when the view crosses `g`'s plane. Stacked facets must not z-fight at any orbit angle or at the start and end of a fold, and the stack must not invert when you orbit under it. Test in Tasks 5 and 10.
  454. **A degenerate drag direction.** When the moving facet's centroid travels nearly along the view direction the drag projection approaches zero and the fold becomes uncontrollable. Test in Task 12.
  465. **A crease the reader has not met yet.** Because frame 0 carries every crease in the sequence, a crease not yet made must not be drawn, and an occluded crease must not be drawn either. Test in Task 9.
  476. **A crease through several layers.** One crease in the script is several coincident edges, one per layer, possibly with opposite fold-angle signs on a flipped layer. Test in Tasks 4 and 7.
  487. **A step with no rigid motion.** An inside reverse fold cannot be made rigidly with the flap closed. It opens, pops and closes, the pop held to 10% strain, the tip landing between the flap's layers. Test in Task 7b.
  49
  50## Synthetic fixtures
  51
  52The engine is tested before the compiler exists, so its fixtures are small sheets whose folded coordinates are integers or halves and can be typed exactly. They live in `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/`, alongside the `fixture(_:)` helper, in a target that only test targets depend on. Task 7 compiles a script for each of the model fixtures and checks the output matches the hand-written file, which pins the compiler's conventions to them.
  53
  54Every fixture except where noted has `file_author: "Traditional"`, an `instruction` on every step, and the default viewpoint `eye [0, 0, 1]`, `up [0, 1, 0]`. Vertex, edge and face numbering below is the numbering in the file.
  55
  56| Fixture | Sheet and creases | Steps |
  57|---|---|---|
  58| `square.fold` | unit square; v0–v3 with 2-element coords; edges e0–e3 all `B`; one face; no frames; no `faceOrders` key; `edges_krz:firstCreasedAtStep` four nulls | none |
  59| `half.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,2), v4 (1,2), v5 (0,2); e0–e5 the boundary in that order, e6 = v1–v4; f0 = [v0,v1,v4,v5], f1 = [v1,v2,v3,v4] | 1: valley fold f1 over f0 about e6, 0 → 180. 2: `turnOver`, vertical. 3: `rotate` 90 |
  60| `mountain.fold` | as `half.fold` | 1: mountain fold f1 behind f0 about e6, 0 → −180 |
  61| `letter.fold` | 3×3; v0 (0,0), v1 (1,0), v2 (2,0), v3 (3,0), v4 (3,3), v5 (2,3), v6 (1,3), v7 (0,3); e0–e7 the boundary, e8 = v1–v6 (x = 1, valley), e9 = v2–v5 (x = 2, mountain); f0 = [v0,v1,v6,v7], f1 = [v1,v2,v5,v6], f2 = [v2,v3,v4,v5] | 1: one step, two axes: f0 valley folds in front of f1, f2 mountain folds behind it. The sets overlap in projection on opposite sides of f1, so frame 1 carries `krz:faceOrders_midFold` |
  62| `letter-sequential.fold` | as `letter.fold`, both creases valley | 1: f0 over f1. 2: f2 over both, `repeatOf: 1` |
  63| `letter-staggered.fold` | as `letter.fold`, both creases valley | 1: one step, two axes: f0 over f1 on window 0…0.5, then f2 over both on 0.5…1. The sets overlap in projection, so frame 1 carries `krz:faceOrders_midFold`, equal to its `faceOrders`. Frame 1 is `letter-sequential.fold`'s frame 2 |
  64| `quarters.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,1), v4 (2,2), v5 (1,2), v6 (0,2), v7 (0,1), v8 (1,1); e0–e7 the boundary, e8 = v1–v8, e9 = v8–v5 (x = 1), e10 = v7–v8, e11 = v8–v3 (y = 1); f0 = [v0,v1,v8,v7], f1 = [v1,v2,v3,v8], f2 = [v8,v3,v4,v5], f3 = [v7,v8,v5,v6] | 1: `foldAndUnfold` on e8, moving f1 and f2, peak 180; frame 1 carries `krz:faceOrders_midFold` with the order at the peak (f1 on f0, f2 on f3). 2: valley fold the top half (f2, f3) down about e10. 3: valley fold the right half of both layers (f1, f2) over about e8 — e8 and e9 are now coincident; e9 is on the flipped layer and ends at −180, `M` |
  65| `occlusion.fold` | 4×4; v0 (0,0), v1 (2,0), v2 (2.5,0), v3 (4,0), v4 (4,4), v5 (2.5,4), v6 (0,4), v7 (0,2); e0–e7 the boundary, e8 = v7–v1 (diagonal), e9 = v2–v5; f0 = [v0,v1,v7], f1 = [v1,v2,v5,v6,v7], f2 = [v2,v3,v4,v5] | 1: valley fold the corner f0 up about e8 (v0 lands on (2,2)). 2: valley fold the strip f2 over about e9 (it lands on x ∈ [1, 2.5], covering part of f0). 3: `turnOver`, vertical, so that step 3's diagram draws frame 2 |
  66
  67Defect fixtures, each a copy of one above with one change:
  68
  69| Fixture | Change |
  70|---|---|
  71| `bad-index.fold` | `square.fold`, e0 references vertex 9 |
  72| `designed-model.fold` | `square.fold`, `file_author: "A. Designer"` |
  73| `topology-in-frame.fold` | `half.fold`, frame 1 carries `edges_vertices` |
  74| `retopologised.fold` | `half.fold`, frame 2 has a seventh vertex |
  75| `stretched-step.fold` | `half.fold`, frame 1's v2 moved to (0.01, 0, 0) |
  76| `angle-200.fold` | `half.fold`, frame 1's e6 at 200 |
  77| `angle-sign.fold` | `half.fold`, frame 1's e6 assigned `V` at −180 |
  78| `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 |
  79| `no-instruction.fold` | `half.fold`, step 1 without `instruction` |
  80| `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` |
  81| `nonrigid-no-pop.fold` | `half.fold`, step 1 with `nonRigid: true` and no `pop` |
  82| `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` |
  83| `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` |
  84| `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) |
  85| `still-face-reorder.fold` | `letter-sequential.fold`, frame 2 reverses the f0–f1 order (both still in step 2) |
  86| `cyclic-order.fold` | `letter-sequential.fold`, frame 2's orders form a cycle over f0, f1, f2 **after normalising** for their normals (f0 and f2 face −z, f1 faces +z in frame 2; `[0,1,1],[1,2,1],[2,0,1]` is not a cycle there) |
  87| `order-against-crease.fold` | `half.fold`, frame 1 puts f0 above f1, which the valley at e6 makes impossible |
  88| `interleaved-folds.fold` | `quarters.fold`, frame 3 swaps f1 and f2, so the folds at e8 (f0, f1) and e9 (f3, f2), coincident on x = 1, interleave instead of nesting |
  89| `face-inside-fold.fold` | `occlusion.fold`, frame 2 puts the strip f2 between f1 and f0, inside the fold at e8 whose line crosses f2's interior |
  90| `nonconvex.fold` | an L-shaped sheet as one face, no frames |
  91
  92### Test helpers
  93
  94Each task adds the helpers its tests use to `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift`, and adds `FoldKitTestSupport`'s target dependencies in `Package.swift` as they appear: `FoldFormat` from Task 1, `Folding` from Task 3, `FoldCompiler` from Task 7.
  95
  96**Units.** Lengths are in the sheet's units. Every length tolerance below 1e-9 is absolute. The isometry tolerances (1e-6) are relative to the sheet's longer side: `sheetSize(file)` times 1e-6.
  97
  98| Task | Helpers |
  99|---|---|
 100| 1 | `fixture(_ name: String) -> URL` |
 101| 2 | — |
 102| 3 | `degreeFourVertex(linear: Bool = false) -> FoldFile`, `degreeFourExactAngle(_ edge: Int, at t: Double) -> Double` |
 103| 4 | `interpolator(_ fixture: String, step: Int) throws -> (FoldFile, FoldInterpolator)`, `maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double` (largest change in a FOLD edge's length against frame 0), `pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool`, `gridSheet(cells: Int) -> FoldFile`, `sheetSize(_ file: FoldFile) -> Double` |
 104| 5 | `interpolatorWithStep(_ fixture: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator)`; `stackedSquarePositions()`, `separatedSquarePositions()`, `threeStackedPositions()` (unit squares at z = 0 and 0, 0 and 1, 0, 0 and 0); `twoSquares()`, `threeSquares()` (their faces) |
 105| 6 | `interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator)`, `interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator)` — both built in code as the tests describe |
 106| 7 | `compiled(_ name: String) throws -> FoldFile` (compiles `<name>.foldscript` against `<name>-cp.fold`), `structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool`, `degreeFourPattern() -> FoldFile` and `degreeFourScript() -> FoldScript` (the same vertex, edge numbering identical to `degreeFourVertex()`'s) |
 107| 7b | `tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool` (the spike's probe at sheet point (2.75, 0.75)), `FoldScript.withOpenAngle(_:step:)`, `FoldScript.withoutSpine(step:)` |
 108| 8 | `script(_ name: String) -> URL`, `pattern(_ name: String) -> URL` (`Models/<name>.foldscript`, `Models/<name>-cp.fold`), `runFoldlint(on: URL) throws -> (exitCode: Int32, output: String)` |
 109| 9 | `diagram(_ fixture: String, step: Int) throws -> Diagram`, `visibleSegmentsOf(_ fixture: String, edge: Int, inFrame: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)]`, `segmentLength(_:)`, `render(_ diagram: Diagram) -> CGImage`, `expectSnapshot(_ image: CGImage, named: String) throws` |
 110| 10 | `renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera, faceColours: [SIMD4<Float>]? = nil) throws -> [SIMD4<Float>]`, `renderStackWithComputedClusters(camera:faceColours:)`, the scene builders the tests name (`Scene` is positions, faces, normals and their `RenderMesh`), `uniqueColours`, `dominantColour`, `cameraAbove()`, `cameraBelow()` |
 111| 12 | `mapping(_ fixture: String, step: Int) throws -> FoldParameterMapping`, `mappingForFoldTowardTheCamera() throws -> FoldParameterMapping` |
 112| 15 | `authoringDoc(_ name: String) -> URL` |
 113
 114---
 115
 116### Setup: repository
 117
 118Done once, before Task 0.
 119
 1201. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`.
 1212. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request.
 1223. Work is batched into ten merge requests, each with one gitbay issue:
 123
 124   | Batch | Tasks | Branch |
 125   |---|---|---|
 126   | A | 0 — interpolation spike | `spike-interpolation` |
 127   | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` |
 128   | B | 1–3 — decoding, validator, steps | `format-and-steps` |
 129   | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` |
 130   | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` |
 131   | E | 9–10 — diagram, renderer | `diagram-and-renderer` |
 132   | F | 11–14 — the app | `app` |
 133   | F2 | 14b — step list, dragging back | `step-access` |
 134   | G | 15, first part — the box | `models` |
 135   | G2 | 15, second part — the crane and the sampan, after decision 0003 | `crane` |
 136
 137   Batches A and A2 merge alone, since Tasks 0 and 0b can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source <branch> --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`.
 1384. If `xcrun metal --version` fails, run `xcodebuild -downloadComponent MetalToolchain`. SwiftPM invokes `metal` for the `.metal` file in Task 10; on 2026-10-19 this machine had no Metal toolchain.
 139
 140---
 141
 142### Task 0: Interpolation model spike
 143
 144**Files:**
 145- Create: `spikes/interpolation/Package.swift` — a macOS executable using `simd` only; not part of FoldKit and never linked into anything
 146- Create: `spikes/interpolation/Sources/Spike/main.swift` and whatever else it needs
 147- Create: `docs/decisions/0001-interpolation-model.md`
 148- Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4 and 7 and Review Focus item 1, and `CLAUDE.md`
 149
 150**Why first.** The design's interpolation — each axis rotates a disjoint moving set about its crease line in the start frame by a linearly interpolated angle — is exact for independent flaps. It is not exact for steps whose faces form closed loops around interior vertices: squash, petal and reverse folds, and the masu's wall-raising step. There the fold angles at a vertex are coupled nonlinearly (at a flat-foldable degree-4 vertex, tan(ρ₁/2) = k·tan(ρ₂/2)), some axes are carried by other moving faces, and vertices shared between moving sets off any axis tear apart partway through the fold even though both end frames are exact. Task 1's `AxisRecord`, Task 3's `FoldAxis`, Task 4's interpolator and Task 7's compiler all encode the answer, so it is measured before any of them exists. The isometry sweep in Task 4 would otherwise only find this in Task 15, on the crane, after everything else is built.
 151
 152**Cases**, each built in code with exact coordinates:
 153
 1541. **Letter fold, both flaps valley.** 3×3 sheet, creases x = 1 and x = 2, both outer thirds folded in front in one step. Under a linear shared parameter, two flaps of equal reach folding toward each other meet at the midline from about 120° on and pass through each other. Draw order cannot fix a collision; this is the control for per-axis scheduling.
 1552. **Letter fold, one valley, one mountain** (`letter.fold`'s geometry). The control for the case the current model handles: expected exact and clean.
 1563. **Generic flat-foldable degree-4 vertex**, sector angles 60°, 80°, 120°, 100° in order, folded from flat to flat-folded in one step. Expected: independent linear angles drift; angles solved for loop closure are exact.
 1574. **Inside reverse fold of a two-layer flap.** A 4×2 rectangle folded in half along y = 1 (the spine), with reverse-fold creases from (2, 1) to (3, 0) and from (2, 1) to (3, 2), the part left of them held still. Question: does any rigid motion take the tip inside the flap with the left part fixed? Hypothesis: none does. With the spine held at 180° the two layers' creases coincide, and the only rigid motion of the tip is to swing about that line as one closed unit, outside the flap. That ends at the same coordinates as the reverse fold, with the wrong layer order. Getting the tip inside requires the flap's layers to open — the "still" part moves. Measure the smallest spine opening for which a rigid path exists, and the peak strain of a non-rigid path if the spine may not open.
 1585. **Petal fold** of the front flap of a preliminary base, built in code by applying the base's folds to a unit square. Measure the drift of independent linear angles, whether solved angles close every loop, and whether the side flaps' axes are carried by the lifted flap.
 159
 160**Candidate models:**
 161
 162- **M1** — the current design: disjoint moving sets, each rotated about its axis in the start frame by a linear angle (a tent for `foldAndUnfold`).
 163- **M2** — a kinematic tree with solved angle curves: an axis may name a parent axis whose motion carries it; each axis's angle is a monotone function of *t*, with its own start and end window on *t* so axes can be staggered; `foldc` solves the curves so every loop of faces around an interior vertex closes, and stores them sampled.
 164- **M3** — decomposition: the script splits the step into sub-steps, each M1 or M2, driven by one continuous drag.
 165- **M4** — non-rigid: per-face rigid transforms at solved sub-keyframes, interpolated between them; isometry is exact only at the sub-keyframes.
 166
 167**Measure**, for every case under every model that applies: the maximum edge-length drift over 1,001 samples of *t*; for M2, the maximum loop-closure residual; the minimum distance between faces that share no edge (negative means they intersect); and for case 4, the answer to the rigid-path question.
 168
 169**Also record:**
 170
 171- For each v1 model, every step that is not a single independent fold — the crane's preliminary-base collapse or squash folds, its petal folds and its inside reverse folds (neck, tail, head); the masu's wall-raising; the sampan's final turn inside out; the cup has none — with the case above that stands in for it and the model that covers it.
 172- Whether the overlapping-moving-sets rule for `krz:faceOrders_midFold` covers anything the end frame's ordering and the near-coplanar clusters (design, *Rendering*) do not. Case 1 suggests the problem with overlapping moving sets is that they collide, which ordering cannot fix. The key's other use, the peak order of a `foldAndUnfold`, is not in question. If the rule has no remaining consumer, recommend removing it, with the evidence; that changes a settled decision and goes to the author.
 173
 174**Exit criteria:**
 175
 176- `docs/decisions/0001-interpolation-model.md` holds the measurements, the model chosen and why.
 177- If every v1 step is covered by a rigid model (M1, M2 or M3): in the same merge request, rewrite the design doc's *Interpolation* section; amend Task 1's `AxisRecord` and tests, Task 3's `FoldAxis`, Task 4's interface and tests (add cases 3–5 to the isometry sweep as fixtures), Task 7's script fields and outputs, and Review Focus item 1; and add the result to `CLAUDE.md`'s *Settled* list.
 178- If some v1 step is covered only by M4, or by nothing: **stop**. Splitting the step, dropping it, shipping a different model and relaxing `CLAUDE.md`'s isometry rule for that step are the author's choices. Do not start Task 1.
 179
 180This is a measurement, not TDD.
 181
 182- [x] **Step 1: Build the spike package and the five cases**
 183- [x] **Step 2: Implement M1 and M2, and M3 and M4 as far as case 4 needs them**
 184- [x] **Step 3: Run and record**
 185
 186Run: `swift run --package-path spikes/interpolation`
 187
 188- [x] **Step 4: Write the decision record and apply the exit criteria**
 189- [x] **Step 5: Commit**
 190
 191```bash
 192git add spikes docs
 193git commit -m "Interpolation model spike and decision record"
 194```
 195
 196---
 197
 198### Task 0b: Non-rigid steps and the remaining coupled steps
 199
 200**Files:**
 201- Modify: `spikes/interpolation` — cases 6–9
 202- Create: `docs/decisions/0002-non-rigid-steps.md`
 203- Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4, 7, 8 and 15, and `CLAUDE.md`
 204
 205**Why.** Decision 0001 found no rigid motion that makes an inside reverse fold with the flap closed, and chose option A: such steps are flagged `nonRigid` and move by a designed non-rigid motion held to a stated strain bound. This task chooses that motion and the bound, and measures the coupled steps 0001 left open. Task 1 encodes the result, so it comes first.
 206
 207**Cases**, continuing 0001's numbering:
 208
 2096. **Reverse fold with bending**, on case 4's flap. Candidates:
 210   - **virtual creases** — extra edges in the flap's layers near the vertex (a fan from it), never drawn, flat in every frame and free to fold during the step. If some number of them gives a rigid path that keeps the flap mostly closed, the step is rigid on a finer mesh: zero gap, and the bend shows as their largest angle. They are subdivision edges in the format, which already allows them.
 211   - **pose interpolation** — per-face transforms through solved intermediate poses (the flap opened to φ, the tip swung through), interpolated between them; strain is the gap.
 212
 213   Measure for each: the largest gap, the largest opening of the flap, the largest virtual-crease angle, and collisions, across φ and the number of virtual creases. 0001 measured naive schedules at 0.24–1.6 of the flap's height; the question is how far a designed motion gets below that.
 2147. **Petal fold, verified.** A bird-base crease pattern with its mountain–valley assignment from a citable source — Lang, *Origami Design Secrets*, or the base folded in Oriedita and exported — recorded with its source. Check it is flat-foldable at every vertex (Kawasaki, and Maekawa against the assignment). Then measure the petal fold as 0001's case 5 did, and check that the inner layers' corners stay down.
 2158. **Sampan, turning inside out.** The crease pattern of the sequence Task 15 will author, with its source. Does any rigid path exist? Rigid (M2), or flagged.
 2169. **Masu, raising the walls.** The traditional masu's crease pattern, walls ending at 90°. Does M2 find a rigid path? Rigid, or flagged.
 217
 218**Exit criteria:**
 219
 220- `docs/decisions/0002-non-rigid-steps.md` holds: the non-rigid model and the data it adds to `krz:step`; the strain metric and the bound the app promises; and, for every v1 step that is not a single independent fold, whether it is rigid (M2) or flagged, with the case that stands in for it.
 221- In the same merge request, apply the result:
 222  - the design doc's *Interpolation* section;
 223  - Task 1 (the non-rigid step's data) and Task 3;
 224  - Task 4, or a task after `foldc` if the path needs its data (it became Task 7b);
 225  - Task 7 (how `foldc` produces a non-rigid step);
 226  - Task 8 (the bound's test for flagged steps);
 227  - Task 15 (which steps are flagged);
 228  - `CLAUDE.md`.
 229- If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0.
 230
 231Applied (decision 0002): the petal fold is rigid; reverse folds and sinks use open, pop, close, which is Task 7b, with the flap opened to 30° from flat by default and a 10% strain bound; the sampan's and the masu's last steps are classified when authored (Task 15).
 232
 233This is a measurement, not TDD.
 234
 235- [x] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources**
 236- [x] **Step 2: Add cases 6–9 to the spike**
 237- [x] **Step 3: Run and record**
 238
 239Run: `swift run -c release --package-path spikes/interpolation`
 240
 241- [x] **Step 4: Write the decision record and apply the exit criteria**
 242- [x] **Step 5: Commit**
 243
 244```bash
 245git add spikes docs
 246git commit -m "Non-rigid steps: model, bound and the remaining coupled steps"
 247```
 248
 249---
 250
 251### Task 1: FOLD decoding, including the extension keys
 252
 253**Files:**
 254- Create: `Packages/FoldKit/Package.swift`
 255- Create: `Packages/FoldKit/Sources/FoldFormat/FoldFile.swift`
 256- Create: `Packages/FoldKit/Sources/FoldFormat/FoldFrame.swift`
 257- Create: `Packages/FoldKit/Sources/FoldFormat/EdgeAssignment.swift`
 258- Create: `Packages/FoldKit/Sources/FoldFormat/StepRecord.swift`
 259- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixture.swift`
 260- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/` — every fixture in *Synthetic fixtures*
 261- Test: `Packages/FoldKit/Tests/FoldFormatTests/DecodingTests.swift`
 262
 263**Interfaces:**
 264- Consumes: nothing.
 265- Produces:
 266  - `enum EdgeAssignment: String, Codable, Sendable { case boundary = "B", mountain = "M", valley = "V", flat = "F", unassigned = "U" }`
 267  - `enum StepKind: String, Codable, Sendable { case fold, foldAndUnfold, turnOver, rotate }`
 268  - `enum StepTechnique: String, Codable, Sendable { case plain, insideReverse, outsideReverse, squash, petal, sink }`
 269  - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }`
 270  - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: [Double]?; let angles: [Double]? }` — `parent` is the index, in the same step's `axes`, of the axis whose motion carries this one; `window` is `[t0, t1]`, default `[0, 1]`; `angles` is a solved curve, the fold angle at 257 evenly spaced points of the window, absent for a linear axis
 271  - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3<Double>; let up: SIMD3<Double> }` — `eye` is the unit direction toward the viewer
 272  - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: PopRecord?; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; a non-rigid step's `axes` still list its creases with their start and end angles, for the diagram and the validator, and its motion is `pop`
 273  - `struct PopRecord: Codable, Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: [Double]; let openAxes: [AxisRecord]; let popped: [SIMD3<Double>]; let closeAxes: [AxisRecord] }` — decision 0002's open, pop, close: `spine` is the flap's spine edges; `openAngle` the spine's fold angle when open (default 30); `phases` the two boundaries on *t* (default `[1/3, 2/3]`); `openAxes` open the flap on `[0, phases[0]]`; `popped` is every vertex's position after the pop; `closeAxes`, relative to `popped`, close it on `[phases[1], 1]`. Axis windows are on the step's whole *t*, as for any axis, so `foldc` writes each opening axis's window inside `[0, phases[0]]` and each closing axis's inside `[phases[1], 1]`
 274  - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }`
 275  - `struct FoldFile: Codable, Sendable { var fileSpec: Double; var fileCreator: String?; var fileTitle: String?; var fileAuthor: String?; var fileClasses: [String]; var edgesVertices: [[Int]]; var facesVertices: [[Int]]; var edgesFirstCreasedAtStep: [Int?]; var frames: [FoldFrame] }` — `frames[0]` is the key frame, `frames[n]` is frame n
 276  - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1`
 277  - `init (FoldFile).init(contentsOf url: URL) throws`
 278  - `enum FoldError: Error, Equatable, Sendable { case unsupportedAssignment(String); case malformedCoordinate(vertex: Int); case missingStepRecord(step: Int); case topologyInFrame(frame: Int); case missingFrameInheritance(frame: Int) }`
 279  - `func fixture(_ name: String) -> URL` in `FoldKitTestSupport`
 280
 281`edgesVertices` and `facesVertices` live on `FoldFile`, not `FoldFrame`, because the spec fixes one topology for every frame. Decoding them per-frame would make the invariant expressible-but-violable; hoisting them makes it structural, and a frame that carries either is a decoding error. `vertices_coords` entries may be 2- or 3-element arrays; decode 2-element as z = 0.
 282
 283The key frame is FOLD's top level, mixed with the `file_` keys, so `FoldFile` needs a hand-written `init(from:)` and `encode(to:)`: frame 0 from the top level, frames 1…N from `file_frames`, each of which must carry `frame_parent: 0` and `frame_inherit: true` and is written with them. Keys an exported crease pattern may lack decode to defaults: `edges_foldAngle` to zeros, `faceOrders` to empty, `edges_krz:firstCreasedAtStep` to nulls, `file_title` and `file_author` to nil, `file_classes` to empty. That lets `foldc` read crease patterns with the same decoder; the validator, not the decoder, decides what a shipped model must have.
 284
 285Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26)`. Library products `FoldFormat`, `Folding`, `Notation`, `Renderer`, `Models`; executables `foldlint` and `foldc`; a test target per library; and `FoldKitTestSupport`, a plain target with `resources: [.copy("Fixtures")]` that only test targets depend on.
 286
 287- [ ] **Step 1: Write the failing tests**
 288
 289```swift
 290@Test func decodesUnitSquareWithFourBoundaryEdges() throws {
 291    let f = try FoldFile(contentsOf: fixture("square.fold"))
 292    #expect(f.frames[0].verticesCoords.count == 4)
 293    #expect(f.frames[0].edgesAssignment.allSatisfy { $0 == .boundary })
 294    #expect(f.stepCount == 0)
 295}
 296
 297@Test func topologyLivesOnTheFileNotTheFrame() throws {
 298    let f = try FoldFile(contentsOf: fixture("square.fold"))
 299    #expect(f.edgesVertices.count == 4)
 300    #expect(f.facesVertices.count == 1)
 301}
 302
 303@Test func aFrameCarryingTopologyIsRejected() {
 304    #expect(throws: FoldError.topologyInFrame(frame: 1)) {
 305        try FoldFile(contentsOf: fixture("topology-in-frame.fold"))
 306    }
 307}
 308
 309@Test func decodesTwoElementCoordsAsZeroZ() throws {
 310    #expect(try FoldFile(contentsOf: fixture("square.fold")).frames[0].verticesCoords
 311        .allSatisfy { $0.z == 0 })
 312}
 313
 314@Test func frameNIsTheResultOfStepN() throws {
 315    let f = try FoldFile(contentsOf: fixture("half.fold"))
 316    #expect(f.stepCount == 3)
 317    #expect(f.frames[0].step == nil)
 318    #expect(f.frames[1].step?.kind == .fold)
 319    #expect(f.frames[2].step?.kind == .turnOver)
 320    #expect(f.frames[3].step?.rotateDegrees == 90)
 321}
 322
 323@Test func decodesTheStepRecordIncludingItsInstructionAndViewpoint() throws {
 324    let step = try FoldFile(contentsOf: fixture("half.fold")).frames[1].step
 325    #expect(step?.axes.count == 1)
 326    #expect(step?.technique == .plain)
 327    #expect(step?.instruction?.isEmpty == false)
 328    #expect(step?.viewpoint == Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
 329}
 330
 331@Test func decodesAnAxisTreeWithWindowsAndACurve() throws {
 332    let json = #"{"edge": 3, "movingFaces": [2], "startAngle": 0, "endAngle": 180, "parent": 0,"# +
 333               #" "window": [0.25, 1], "angles": [0, 90, 180]}"#
 334    let axis = try JSONDecoder().decode(AxisRecord.self, from: Data(json.utf8))
 335    #expect(axis.parent == 0)
 336    #expect(axis.window == [0.25, 1])
 337    #expect(axis.angles == [0, 90, 180])
 338}
 339
 340@Test func decodesAPopRecord() throws {
 341    let json = #"{"spine": [0, 1], "openAngle": 30, "phases": [0.3333333333333333, 0.6666666666666666],"# +
 342               #" "openAxes": [], "popped": [[0, 0, 0], [1, 0, 0]], "closeAxes": []}"#
 343    let pop = try JSONDecoder().decode(PopRecord.self, from: Data(json.utf8))
 344    #expect(pop.openAngle == 30)
 345    #expect(pop.popped.count == 2)
 346}
 347
 348@Test func windowsDecodeOnAStaggeredStep() throws {
 349    let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step
 350    #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]])
 351    #expect(step?.nonRigid == false)
 352}
 353
 354@Test func decodesFirstCreasedAtStepWithNullForBoundaries() throws {
 355    let f = try FoldFile(contentsOf: fixture("half.fold"))
 356    #expect(f.edgesFirstCreasedAtStep == [nil, nil, nil, nil, nil, nil, 1])
 357}
 358
 359@Test func roundTripsThroughEncodingUnchanged() throws {
 360    let f = try FoldFile(contentsOf: fixture("half.fold"))
 361    let again = try JSONDecoder().decode(FoldFile.self, from: JSONEncoder().encode(f))
 362    #expect(again.edgesVertices == f.edgesVertices)
 363    #expect(again.frames.map(\.verticesCoords) == f.frames.map(\.verticesCoords))
 364    #expect(again.frames.map(\.step) == f.frames.map(\.step))
 365}
 366
 367@Test func encodedFramesInheritFromTheKeyFrame() throws {
 368    let f = try FoldFile(contentsOf: fixture("half.fold"))
 369    let json = try JSONSerialization.jsonObject(with: JSONEncoder().encode(f)) as! [String: Any]
 370    let frames = json["file_frames"] as! [[String: Any]]
 371    #expect(frames.allSatisfy { $0["frame_parent"] as? Int == 0 && $0["frame_inherit"] as? Bool == true })
 372    #expect(frames.allSatisfy { $0["edges_vertices"] == nil })
 373}
 374
 375@Test(arguments: ["C", "J"])
 376func rejectsCutAndJoinAssignments(_ code: String) {
 377    #expect(throws: FoldError.unsupportedAssignment(code)) {
 378        try JSONDecoder().decode(EdgeAssignment.self, from: Data("\"\(code)\"".utf8))
 379    }
 380}
 381```
 382
 383- [ ] **Step 2: Run tests to verify they fail**
 384
 385Run: `swift test --package-path Packages/FoldKit --filter DecodingTests`
 386Expected: FAIL — no such module `FoldFormat`.
 387
 388- [ ] **Step 3: Write the fixtures, implement the types and `FoldFile`'s coding**
 389
 390`CodingKeys` map the format's spelling exactly: snake_case for standard keys, `faceOrders` camelCase, `edges_krz:firstCreasedAtStep`, `krz:step`, `krz:faceOrders_midFold`. `EdgeAssignment` needs its own `init(from:)` to throw `FoldError` rather than `DecodingError`. Write the fixtures from the tables in *Synthetic fixtures*; their coordinates are exact.
 391
 392- [ ] **Step 4: Run tests to verify they pass**
 393
 394Run: `swift test --package-path Packages/FoldKit --filter DecodingTests`
 395Expected: PASS.
 396
 397- [ ] **Step 5: Commit**
 398
 399```bash
 400git add Packages/FoldKit
 401git commit -m "FOLD decoding with krz extension keys and synthetic fixtures"
 402```
 403
 404---
 405
 406### Task 2: The validator
 407
 408**Files:**
 409- Create: `Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift`
 410- Test: `Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift`
 411
 412**Interfaces:**
 413- Consumes: Task 1 types.
 414- Produces:
 415  - `enum FoldDefect: Equatable, Sendable { case vertexIndexOutOfRange(edge: Int); case faceVertexOutOfRange(face: Int); case vertexCountChanged(frame: Int); case foldAngleOutOfRange(frame: Int, edge: Int, degrees: Double); case foldAngleSignDisagreesWithAssignment(frame: Int, edge: Int); case boundaryEdgeFolded(frame: Int, edge: Int); case faceOrderNotAntisymmetric(frame: Int, f: Int, g: Int); case cyclicFaceOrder(frame: Int, cycle: [Int]); case nonIsometricTransition(step: Int, edge: Int, from: Double, to: Double); case overlappingMovingSetsWithoutMidFoldOrder(step: Int); case startAndEndOrderDisagreeOnStillFaces(step: Int, f: Int, g: Int); case foldAndUnfoldWithoutPeakOrder(step: Int); case orderDisagreesWithCrease(frame: Int, edge: Int); case interleavedFolds(frame: Int, edges: [Int]); case faceInsideFold(frame: Int, face: Int, edge: Int); case nonConvexFace(face: Int); case missingInstruction(step: Int); case authorNotTraditional(String?); case missingFirstCreasedAtStep(edge: Int) }`
 416  - `func validate(_ file: FoldFile) -> [FoldDefect]`
 417  - `func movingSetsOverlapInProjection(step: Int, _ file: FoldFile) -> Bool`
 418  - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>]`
 419  - `func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)]` — each triple as "above" along a canonical normal of the two faces' common plane (the one whose first nonzero component is positive)
 420
 421This task owns Review Focus item 2. Isometry tolerance is 1e-6 × the sheet's longer side on edge length between consecutive frames. The validator checks shipped models; it is not run on crease patterns.
 422
 423The interpenetration checker (Task 6) finds faces that collide in motion. It cannot find an ordering that is impossible but collision-free — a flap drawn on the wrong side of a stack moves through exactly the same coordinates. The three **layer-order consistency** rules here find those, in every stack of coincident faces of every frame, and they are what catches a wrong guess from `foldc`:
 424
 425- **crease:** two faces joined at a crease folded to ±180 are ordered as its `edges_assignment` requires — for a valley each face's normal points toward the other, for a mountain away;
 426- **nesting:** where two folded creases coincide, their face pairs nest or are disjoint in the stack, never interleave (FOLD's "taco-taco");
 427- **inside:** a face whose interior crosses a folded crease's line does not lie between that crease's two faces ("taco-tortilla").
 428
 429- [ ] **Step 1: Write the failing tests**
 430
 431```swift
 432@Test(arguments: ["square.fold", "half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold",
 433                  "letter-staggered.fold", "quarters.fold", "occlusion.fold"])
 434func acceptsAValidModel(_ name: String) throws {
 435    #expect(validate(try FoldFile(contentsOf: fixture(name))).isEmpty)
 436}
 437
 438@Test func oppositeNormalsMakeAMutualAboveValid() {
 439    // [f, g, +1] and [g, f, +1] agree when the faces face opposite ways
 440    let pairs = normalisedFaceOrders([[0, 1, 1], [1, 0, 1]],
 441                                     normals: [SIMD3(0, 0, 1), SIMD3(0, 0, -1)])
 442    #expect(Set(pairs.map { [$0.below, $0.above] }) == [[0, 1]])
 443}
 444
 445@Test func rejectsAnOrderTheCreaseMakesImpossible() throws {
 446    #expect(validate(try FoldFile(contentsOf: fixture("order-against-crease.fold")))
 447        .contains(.orderDisagreesWithCrease(frame: 1, edge: 6)))
 448}
 449
 450@Test func rejectsInterleavedFolds() throws {
 451    let defects = validate(try FoldFile(contentsOf: fixture("interleaved-folds.fold")))
 452    #expect(defects.contains { if case .interleavedFolds(frame: 3, _) = $0 { return true }; return false })
 453}
 454
 455@Test func rejectsAFaceInsideAFoldItCrosses() throws {
 456    let defects = validate(try FoldFile(contentsOf: fixture("face-inside-fold.fold")))
 457    #expect(defects.contains(.faceInsideFold(frame: 2, face: 2, edge: 8)))
 458}
 459
 460@Test func rejectsAFoldAndUnfoldWithoutItsPeakOrder() throws {
 461    var file = try FoldFile(contentsOf: fixture("quarters.fold"))
 462    file.frames[1].faceOrdersMidFold = nil
 463    #expect(validate(file).contains(.foldAndUnfoldWithoutPeakOrder(step: 1)))
 464}
 465
 466@Test func rejectsANonConvexFace() throws {
 467    #expect(validate(try FoldFile(contentsOf: fixture("nonconvex.fold"))) == [.nonConvexFace(face: 0)])
 468}
 469
 470@Test func rejectsAFrameThatChangesTheVertexCount() throws {
 471    let defects = validate(try FoldFile(contentsOf: fixture("retopologised.fold")))
 472    #expect(defects.contains(.vertexCountChanged(frame: 2)))
 473}
 474
 475@Test func rejectsOverlappingMovingSetsWithNoMidFoldOrder() throws {
 476    let defects = validate(try FoldFile(contentsOf: fixture("letter-no-midfold.fold")))
 477    #expect(defects == [.overlappingMovingSetsWithoutMidFoldOrder(step: 1)])
 478}
 479
 480@Test func rejectsStartAndEndOrderDisagreementOnStillFaces() throws {
 481    let defects = validate(try FoldFile(contentsOf: fixture("still-face-reorder.fold")))
 482    #expect(defects.contains {
 483        if case .startAndEndOrderDisagreeOnStillFaces(step: 2, _, _) = $0 { return true }; return false })
 484}
 485
 486@Test func rejectsCyclicFaceOrder() throws {
 487    let defects = validate(try FoldFile(contentsOf: fixture("cyclic-order.fold")))
 488    #expect(defects.contains { if case .cyclicFaceOrder(frame: 2, _) = $0 { return true }; return false })
 489}
 490
 491@Test func rejectsNonIsometricTransition() throws {
 492    let defects = validate(try FoldFile(contentsOf: fixture("stretched-step.fold")))
 493    #expect(defects.contains { if case .nonIsometricTransition(step: 1, _, _, _) = $0 { return true }; return false })
 494}
 495
 496@Test func rejectsFoldAngleOutsideRange() throws {
 497    #expect(validate(try FoldFile(contentsOf: fixture("angle-200.fold")))
 498        == [.foldAngleOutOfRange(frame: 1, edge: 6, degrees: 200)])
 499}
 500
 501@Test func rejectsAFoldAngleWhoseSignDisagreesWithItsAssignment() throws {
 502    #expect(validate(try FoldFile(contentsOf: fixture("angle-sign.fold")))
 503        == [.foldAngleSignDisagreesWithAssignment(frame: 1, edge: 6)])
 504}
 505
 506@Test func rejectsAFoldedBoundaryEdge() throws {
 507    let defects = validate(try FoldFile(contentsOf: fixture("folded-boundary.fold")))
 508    #expect(defects.contains(.boundaryEdgeFolded(frame: 1, edge: 0)))
 509}
 510
 511@Test func rejectsAStepWithoutAnInstruction() throws {
 512    #expect(validate(try FoldFile(contentsOf: fixture("no-instruction.fold")))
 513        == [.missingInstruction(step: 1)])
 514}
 515
 516@Test func rejectsANonTraditionalAuthor() throws {
 517    #expect(validate(try FoldFile(contentsOf: fixture("designed-model.fold")))
 518        == [.authorNotTraditional("A. Designer")])
 519}
 520
 521@Test func rejectsEdgeReferencingMissingVertex() throws {
 522    #expect(validate(try FoldFile(contentsOf: fixture("bad-index.fold")))
 523        == [.vertexIndexOutOfRange(edge: 0)])
 524}
 525```
 526
 527- [ ] **Step 2: Run tests to verify they fail**
 528
 529Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests`
 530Expected: FAIL.
 531
 532- [ ] **Step 3: Implement `validate` and `movingSetsOverlapInProjection`**
 533
 534Normals come from the frame's coordinates and the counterclockwise `faces_vertices` order. For cycle detection and the three consistency rules, normalise every triple with `normalisedFaceOrders` first; cycle detection is depth-first search over the resulting below → above graph. The still-face rule must not use normalised pairs, because a turn-over flips every normal and would invert every pair: it compares each pair's relation in a form a rigid motion leaves unchanged — the triple rewritten with the lower face index first, `s` negated when swapping faces whose normals agree (the spec's reverse-triple rule). A raw `s = +1` graph is wrong both ways: `[f, g, +1]` with `[g, f, +1]` is valid for opposite normals, and a raw cycle can be acyclic once normalised. Antisymmetry follows the spec: a present reverse triple `[g, f, t]` has `t = -s` when the two faces' normals agree in the folded state and `t = s` when they oppose. Sign: `V` requires a positive angle, `M` negative, `F`, `U` and `B` zero. Every `foldAndUnfold` needs `krz:faceOrders_midFold`, the order at its peak, since neither end frame orders the moving faces against what they lie on there; the validator checks it is present, and Task 5's `LayerOrder.active`, which can compute the peak positions, checks it for cycles. Every non-boundary edge needs a `edges_krz:firstCreasedAtStep` except a subdivision edge (`F` and flat in every frame). Overlap in projection is tested by polygon intersection of the moving sets' projected outlines at the step's viewpoint, in frame n (where both sets have arrived).
 535
 536- [ ] **Step 4: Run tests to verify they pass**
 537
 538Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests`
 539Expected: PASS.
 540
 541- [ ] **Step 5: Commit**
 542
 543```bash
 544git add Packages/FoldKit
 545git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold ordering"
 546```
 547
 548---
 549
 550### Task 3: Reading authored steps
 551
 552**Files:**
 553- Create: `Packages/FoldKit/Sources/Folding/FoldStep.swift`
 554- Create: `Packages/FoldKit/Sources/Folding/StepReader.swift`
 555- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift`
 556- Test: `Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift`
 557
 558**Interfaces:**
 559- Consumes: Task 1 types.
 560- Produces:
 561  - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3<Double>; let direction: SIMD3<Double>; let movingFaces: Set<Int>; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange<Double>; let curve: [Double]? }`
 562  - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double`
 563  - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: Pop?; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children
 564  - `struct Pop: Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: ClosedRange<Double>; let openAxes: [FoldAxis]; let popped: [SIMD3<Double>]; let closeAxes: [FoldAxis] }` — `closeAxes`' origins and directions come from `popped`, not from frame `index − 1`
 565  - `var (FoldStep).movingFaceUnion: Set<Int> { get }`
 566  - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1`
 567  - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int); case nonRigidWithoutPop(step: Int); case popPhasesOutOfOrder(step: Int) }`
 568
 569`readSteps` **reads** the authored `krz:step`; it does not infer axes or moving sets from a frame diff. Deriving a multi-axis decomposition has genuine ambiguities — which side moved, whether a reorientation is a fold, how to partition simultaneous axes — and the author already knows the answer. This task and Task 4 own Review Focus item 1, in the form Task 0 settles.
 570
 571`FoldAxis.origin` and `direction` come from the axis edge's endpoints in frame `index − 1`. The direction is the way the moving face adjacent to the edge traverses it in `faces_vertices` order, and the origin is the vertex that traversal starts from, so that a positive rotation about it (right-hand rule) turns the moving face toward its normal — a valley — and the rotation for any step is `angle(t) − startAngle` with FOLD's own sign. `angle(at:)` first maps `t` onto the axis's window, `u = clamp((t − t0) / (t1 − t0), 0, 1)`, so an axis waits before its window and holds after it. Then it is `startAngle + u·(endAngle − startAngle)` for `fold`, `startAngle + (peakAngle − startAngle)·(1 − |2u − 1|)` for `foldAndUnfold`, or, when the axis has a curve, the curve at `u` by cubic Hermite interpolation with central-difference tangents (one-sided at the ends). Decision 0001 measured that 257 samples rebuilt this way keep a coupled vertex's tear under 1e-6.
 572
 573For an axis with a parent, `origin` and `direction` are still in frame `index − 1`'s coordinates: Task 4 applies the axis's own rotation first and its ancestors' after, so the parent's motion carries it.
 574
 575`degreeFourVertex(linear:)` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly for any of the four creases. With `linear: true` the curves are replaced by straight lines, for Task 4's control test.
 576
 577- [ ] **Step 1: Write the failing tests**
 578
 579```swift
 580@Test func stepIndicesCountFromOne() throws {
 581    let steps = try readSteps(FoldFile(contentsOf: fixture("half.fold")))
 582    #expect(steps.map(\.index) == [1, 2, 3])
 583}
 584
 585@Test func simpleValleyFoldReadsOneAxis() throws {
 586    let step = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0]
 587    #expect(step.axes.count == 1)
 588    #expect(step.axes[0].endAngle == 180)
 589}
 590
 591@Test func letterFoldReadsTwoSimultaneousAxes() throws {
 592    let step = try readSteps(FoldFile(contentsOf: fixture("letter.fold")))[0]
 593    #expect(step.axes.count == 2)
 594}
 595
 596@Test(arguments: ["half.fold", "letter.fold", "letter-sequential.fold", "quarters.fold", "occlusion.fold"])
 597func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws {
 598    for step in try readSteps(FoldFile(contentsOf: fixture(name))) {
 599        let union = step.axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
 600        #expect(union.count == step.axes.reduce(0) { $0 + $1.movingFaces.count })
 601    }
 602}
 603
 604@Test func turnOverStepHasNoAxesAndAnAxisToTurnAbout() throws {
 605    let turn = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[1]
 606    #expect(turn.kind == .turnOver)
 607    #expect(turn.axes.isEmpty)
 608    #expect(turn.turnOverAxis == .vertical)
 609}
 610
 611@Test func rotateStepCarriesItsDegrees() throws {
 612    #expect(try readSteps(FoldFile(contentsOf: fixture("half.fold")))[2].rotateDegrees == 90)
 613}
 614
 615@Test func foldAndUnfoldPeaksMidwayAndReturns() throws {
 616    let s = try readSteps(FoldFile(contentsOf: fixture("quarters.fold")))[0]
 617    #expect(s.kind == .foldAndUnfold)
 618    #expect(s.axes[0].angle(at: 0.5, kind: s.kind) == 180)
 619    #expect(s.axes[0].angle(at: 1, kind: s.kind) == 0)
 620}
 621
 622@Test func axisIsDirectedAsTheMovingFaceTraversesIt() throws {
 623    // f1 = [v1, v2, v3, v4] traverses e6 = [v1, v4] from v4 to v1
 624    let axis = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0].axes[0]
 625    #expect(axis.origin == SIMD3(1, 2, 0))
 626    #expect(axis.direction == SIMD3(0, -1, 0))
 627}
 628
 629@Test func instructionIsReadVerbatim() throws {
 630    let f = try FoldFile(contentsOf: fixture("half.fold"))
 631    #expect(try readSteps(f)[0].instruction == f.frames[1].step?.instruction)
 632}
 633
 634@Test func aWindowedAxisWaitsAndThenHolds() throws {
 635    let s = try readSteps(FoldFile(contentsOf: fixture("letter-staggered.fold")))[0]
 636    #expect(s.axes[0].angle(at: 0.25, kind: s.kind) == 90)
 637    #expect(s.axes[1].angle(at: 0.25, kind: s.kind) == 0)
 638    #expect(s.axes[0].angle(at: 0.75, kind: s.kind) == 180)
 639    #expect(s.axes[1].angle(at: 0.75, kind: s.kind) == 90)
 640}
 641
 642@Test func aCurveIsInterpolatedBetweenItsSamples() throws {
 643    let axis = try readSteps(degreeFourVertex()).first!.axes.first { $0.curve != nil }!
 644    let t = 0.5 + 0.5 / 256                        // halfway between two samples
 645    #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6)
 646}
 647
 648@Test func aNonRigidStepNeedsItsPop() {
 649    #expect(throws: StepError.nonRigidWithoutPop(step: 1)) {
 650        try readSteps(FoldFile(contentsOf: fixture("nonrigid-no-pop.fold")))
 651    }
 652}
 653
 654@Test func rotateWithoutDegreesThrows() {
 655    #expect(throws: StepError.rotateWithoutDegrees(step: 3)) {
 656        try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold")))
 657    }
 658}
 659
 660@Test func movingFaceOutOfRangeThrows() {
 661    #expect(throws: StepError.movingFacesOutOfRange(step: 1)) {
 662        try readSteps(FoldFile(contentsOf: fixture("bad-moving-face.fold")))
 663    }
 664}
 665```
 666
 667- [ ] **Step 2: Run tests to verify they fail**
 668
 669Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests`
 670Expected: FAIL.
 671
 672- [ ] **Step 3: Implement `FoldAxis`, `FoldStep` and `readSteps`**
 673
 674- [ ] **Step 4: Run tests to verify they pass**
 675
 676Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests`
 677Expected: PASS.
 678
 679- [ ] **Step 5: Commit**
 680
 681```bash
 682git add Packages/FoldKit
 683git commit -m "Read authored fold steps, including multi-axis and reorientation kinds"
 684```
 685
 686---
 687
 688### Task 4: Rigid interpolation
 689
 690**Files:**
 691- Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift`
 692- Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift`
 693
 694**Interfaces** (decision 0001; rigid steps only — Task 7b adds the path for `nonRigid` steps, whose data only `foldc` can produce):
 695- Consumes: Task 1 and Task 3 types.
 696- Produces:
 697  - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index`
 698  - `func (FoldInterpolator).positions(at t: Double) -> [SIMD3<Double>]` — `t` in 0...1
 699
 700There is no separate orientation output: a `turnOver` or `rotate` step's end frame already has rotated coordinates, so `positions(at:)` rotates the start frame about its bounding-box centre by `t` times the step's angle — 180° about the viewpoint's up vector or its right vector (`up × eye`) for `turnOver`, `rotateDegrees` about `eye` for `rotate` (right-hand rule, so positive is counterclockwise as seen).
 701
 702- [ ] **Step 1: Write the failing tests**
 703
 704```swift
 705let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold",
 706                     "letter-staggered.fold", "quarters.fold", "occlusion.fold"]
 707
 708@Test func tZeroReproducesTheStartFrame() throws {
 709    let (file, i) = try interpolator("half.fold", step: 1)
 710    #expect(zip(i.positions(at: 0), file.frames[0].verticesCoords)
 711        .allSatisfy { simd_distance($0, $1) < 1e-12 })
 712}
 713
 714@Test(arguments: modelFixtures)
 715func tOneReproducesTheEndFrameForEveryStep(_ name: String) throws {
 716    let file = try FoldFile(contentsOf: fixture(name))
 717    for step in try readSteps(file) {
 718        let i = FoldInterpolator(file: file, step: step)
 719        #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords)
 720            .allSatisfy { simd_distance($0, $1) < 1e-9 }, "\(name) step \(step.index)")
 721    }
 722}
 723
 724@Test(arguments: modelFixtures)
 725func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws {
 726    let file = try FoldFile(contentsOf: fixture(name))
 727    for step in try readSteps(file) {
 728        let i = FoldInterpolator(file: file, step: step)
 729        for t in stride(from: 0.0, through: 1.0, by: 0.05) {
 730            #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9,
 731                    "\(name) step \(step.index) t \(t)")
 732        }
 733    }
 734}
 735
 736@Test func verticesOnTheAxisDoNotMove() throws {
 737    let (file, i) = try interpolator("half.fold", step: 1)
 738    for v in [1, 4] {
 739        #expect(simd_distance(i.positions(at: 0.37)[v], file.frames[0].verticesCoords[v]) < 1e-12)
 740    }
 741}
 742
 743@Test func aValleyFoldRisesTowardTheViewerAndAMountainFoldFallsAway() throws {
 744    let (_, valley) = try interpolator("half.fold", step: 1)
 745    let (_, mountain) = try interpolator("mountain.fold", step: 1)
 746    #expect(valley.positions(at: 0.5)[2].z > 0)
 747    #expect(mountain.positions(at: 0.5)[2].z < 0)
 748}
 749
 750@Test func multiAxisStepMovesEverySetOnTheSharedParameter() throws {
 751    let (file, i) = try interpolator("letter.fold", step: 1)
 752    let start = file.frames[0].verticesCoords, mid = i.positions(at: 0.5)
 753    #expect(simd_distance(mid[0], start[0]) > 0.1)   // left flap
 754    #expect(simd_distance(mid[3], start[3]) > 0.1)   // right flap
 755}
 756
 757@Test func foldAndUnfoldPassesThroughThePeakAndReturns() throws {
 758    let (file, i) = try interpolator("quarters.fold", step: 1)
 759    #expect(simd_distance(i.positions(at: 0.5)[2], SIMD3(0, 0, 0)) < 1e-9)
 760    #expect(zip(i.positions(at: 1), file.frames[0].verticesCoords)
 761        .allSatisfy { simd_distance($0, $1) < 1e-9 })
 762}
 763
 764@Test func aCoupledVertexStaysWholeThroughout() throws {
 765    // decision 0001, case 3: curves from the closed form, sampled at 257 points
 766    let file = degreeFourVertex()
 767    let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
 768    for n in 0...1024 {
 769        #expect(maxEdgeLengthDrift(i.positions(at: Double(n) / 1024), file) < 1e-6)
 770    }
 771    #expect(zip(i.positions(at: 1), file.frames[1].verticesCoords)
 772        .allSatisfy { simd_distance($0, $1) < 1e-9 })
 773}
 774
 775@Test func theSameVertexWithLinearAnglesTears() throws {
 776    // the control: drop the curve and the paper does not hold together
 777    let file = degreeFourVertex(linear: true)
 778    let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
 779    #expect(maxEdgeLengthDrift(i.positions(at: 0.5), file) > 0.1)
 780}
 781
 782@Test func aStaggeredAxisMovesOnlyInItsWindow() throws {
 783    let (file, i) = try interpolator("letter-staggered.fold", step: 1)
 784    let start = file.frames[0].verticesCoords
 785    #expect(simd_distance(i.positions(at: 0.25)[3], start[3]) < 1e-12)   // right flap waits
 786    #expect(simd_distance(i.positions(at: 0.5)[0], SIMD3(2, 0, 0)) < 1e-9) // left flap down
 787}
 788
 789@Test func turnOverRotatesTheModelRigidly() throws {
 790    let (_, i) = try interpolator("half.fold", step: 2)
 791    #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0)))
 792    #expect(i.positions(at: 0.5).contains { $0.z != 0 })
 793}
 794
 795@Test func interpolationFitsInAFrameBudget() throws {
 796    let file = gridSheet(cells: 12)   // built in code: a 12×12 grid, one fold down the middle
 797    let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
 798    let elapsed = ContinuousClock().measure {
 799        for n in 0..<1000 { _ = i.positions(at: Double(n) / 1000) }
 800    }
 801    #expect(elapsed / 1000 < .milliseconds(1))
 802}
 803```
 804
 805- [ ] **Step 2: Run tests to verify they fail**
 806
 807Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests`
 808Expected: FAIL.
 809
 810- [ ] **Step 3: Implement `positions(at:)`**
 811
 812Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above.
 813
 814- [ ] **Step 4: Run tests to verify they pass**
 815
 816Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests`
 817Expected: PASS.
 818
 819- [ ] **Step 5: Commit**
 820
 821```bash
 822git add Packages/FoldKit
 823git commit -m "Rigid interpolation on an axis tree with windows and solved curves"
 824```
 825
 826---
 827
 828### Task 5: Layer order resolution
 829
 830**Files:**
 831- Create: `Packages/FoldKit/Sources/Folding/LayerOrder.swift`
 832- Test: `Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift`
 833
 834**Interfaces:**
 835- Consumes: Task 1–4 types; `faceNormals` and `normalisedFaceOrders` from Task 2.
 836- Produces:
 837  - `struct LayerOrder: Sendable { init(sources: [(faceOrders: [[Int]], normals: [SIMD3<Double>])]) throws }` — each source is a set of triples with the face normals of the state it describes; earlier sources win for a pair present in several. Triples are stored raw; normals are used only to check each source for cycles
 838  - `init (LayerOrder).init(faceOrders: [[Int]], normals: [SIMD3<Double>]) throws` — one source
 839  - `static func (LayerOrder).active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder` — first source frame n's `krz:faceOrders_midFold` (with the normals at the peak, from Task 4's interpolator at `t = 0.5`, for a `foldAndUnfold`, else frame n's) or, without one, frame n's `faceOrders` with frame n's normals; second source frame n − 1's `faceOrders` with frame n − 1's normals, for pairs the first lacks
 840  - `struct CoplanarCluster: Equatable, Sendable { let faces: [Int] }` — faces already sorted back-to-front for the given view
 841  - `func (LayerOrder).clusters(positions: [SIMD3<Double>], faces: [[Int]], viewDirection: SIMD3<Double>) -> [CoplanarCluster]`
 842  - `func (LayerOrder).agreesWith(_ other: LayerOrder, ignoring movingFaces: Set<Int>) -> Bool`
 843  - `func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int` — the most faces whose open interiors cover one point, over coincident faces; a flat sheet is 1
 844  - `enum LayerError: Error, Equatable, Sendable { case cyclic(cycle: [Int]) }`
 845
 846The output is **clusters**, not one global draw order, because the renderer is hybrid: the depth buffer separates clusters and the active ordering orders within them. Two faces are linked when they overlap in projection, their normals are within 2° of each other's line, and each one's vertices lie within sin 2° × the model's bounding-box diagonal of the other's plane — the distance tolerance follows the angular one, since a flap hinged at the edge of a stack and 2° off it rises that far. A cluster is a connected group of linked faces. The tolerance is wide on purpose: a facet just leaving or just arriving on a stack is nearly coplanar with it, and the depth buffer alone would z-fight there.
 847
 848Each triple's `s` is resolved against `viewDirection` using `g`'s normal **at the given positions**, since "above" in FOLD means "on the side `g`'s normal points toward", that reverses when the view crosses `g`'s plane, and a moving stack's normals turn with it. In `active`, a triple whose `g` moves in the step and whose `f` does not is rewritten into its reverse with that source's normals, so a moving/still pair is always read against the still face, whose normal does not turn. The fallback to frame n − 1 covers a flap leaving a stack, whose pairs exist only in the start frame; `foldAndUnfold` carries its peak order in `krz:faceOrders_midFold` (Task 2 requires it).
 849
 850- [ ] **Step 1: Write the failing tests**
 851
 852```swift
 853let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)]
 854let up3 = up2 + [SIMD3(0, 0, 1)]
 855
 856@Test func twoStackedCoplanarFacesFormOneClusterOrderedFarthestFirst() throws {
 857    let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2)   // 0 above 1
 858    let c = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
 859                           viewDirection: SIMD3(0, 0, -1))
 860    #expect(c.count == 1)
 861    #expect(c[0].faces == [1, 0])
 862}
 863
 864@Test func orbitingUnderneathReversesTheClusterOrder() throws {
 865    let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2)
 866    let above = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
 867                               viewDirection: SIMD3(0, 0, -1))
 868    let below = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
 869                               viewDirection: SIMD3(0, 0, 1))
 870    #expect(above[0].faces == below[0].faces.reversed())
 871}
 872
 873@Test func facesSeparatedInSpaceFormSeparateClusters() throws {
 874    let order = try LayerOrder(faceOrders: [], normals: up2)
 875    #expect(order.clusters(positions: separatedSquarePositions(), faces: twoSquares(),
 876                           viewDirection: SIMD3(0, 0, -1)).count == 2)
 877}
 878
 879@Test func unorderedCoplanarFacesKeepIndexOrder() throws {
 880    let order = try LayerOrder(faceOrders: [], normals: up3)
 881    #expect(order.clusters(positions: threeStackedPositions(), faces: threeSquares(),
 882                           viewDirection: SIMD3(0, 0, -1))[0].faces == [0, 1, 2])
 883}
 884
 885@Test func anArrivingFlapJoinsTheStackItLandsOn() throws {
 886    // letter-sequential step 2 at 179.5°: f2 is half a degree above f0 and f1
 887    let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2)
 888    let c = try LayerOrder.active(for: step, in: file)
 889        .clusters(positions: i.positions(at: 179.5 / 180), faces: file.facesVertices,
 890                  viewDirection: SIMD3(0, 0, -1))
 891    #expect(c.contains { Set($0.faces) == [0, 1, 2] && $0.faces.last == 2 })
 892}
 893
 894@Test func aFlapAtThirtyDegreesIsItsOwnCluster() throws {
 895    let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2)
 896    let c = try LayerOrder.active(for: step, in: file)
 897        .clusters(positions: i.positions(at: 150.0 / 180), faces: file.facesVertices,
 898                  viewDirection: SIMD3(0, 0, -1))
 899    #expect(c.contains { $0.faces == [2] })
 900}
 901
 902@Test func aFoldAndUnfoldPeakIsOrderedByItsMidFoldOrder() throws {
 903    // quarters step 1 at the peak: f2 lies on f3 and f1 on f0, the moving faces on top
 904    let (file, step, i) = try interpolatorWithStep("quarters.fold", step: 1)
 905    let c = try LayerOrder.active(for: step, in: file)
 906        .clusters(positions: i.positions(at: 0.5), faces: file.facesVertices,
 907                  viewDirection: SIMD3(0, 0, -1))
 908    let left = try #require(c.first { $0.faces.contains(3) })
 909    #expect(left.faces.firstIndex(of: 2)! > left.faces.firstIndex(of: 3)!)
 910}
 911
 912@Test func cyclicOrderThrows() {
 913    #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) {
 914        try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3)
 915    }
 916}
 917
 918@Test func aRawCycleThatNormalisesAwayIsAccepted() {
 919    // f0 and f2 face down: these triples say f1 < f0, f1 < f2, f2 < f0
 920    #expect(throws: Never.self) {
 921        try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]],
 922                       normals: [SIMD3(0, 0, -1), SIMD3(0, 0, 1), SIMD3(0, 0, -1)])
 923    }
 924}
 925
 926@Test func consecutiveOrderingsAgreeAwayFromTheMovingFaces() throws {
 927    let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
 928    for step in try readSteps(file) {
 929        let start = try LayerOrder(faceOrders: file.frames[step.index - 1].faceOrders,
 930                                   normals: faceNormals(file.frames[step.index - 1], file))
 931        let end = try LayerOrder(faceOrders: file.frames[step.index].faceOrders,
 932                                 normals: faceNormals(file.frames[step.index], file))
 933        #expect(start.agreesWith(end, ignoring: step.movingFaceUnion), "step \(step.index)")
 934    }
 935}
 936
 937@Test func stackDepthCountsTheLayersOverOnePoint() throws {
 938    let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
 939    #expect(stackDepth(positions: file.frames[2].verticesCoords, faces: file.facesVertices) == 3)
 940}
 941```
 942
 943- [ ] **Step 2: Run tests to verify they fail**
 944
 945Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests`
 946Expected: FAIL.
 947
 948- [ ] **Step 3: Implement `LayerOrder`, `CoplanarCluster` and `clusters`**
 949
 950`init` normalises each source's triples with that source's normals (`faceNormals(positions:faces:)` from FoldFormat) and throws on a cycle within it, the cycle listed so that each face lies above the next, as the validator reports it, then keeps the raw triples. `agreesWith` compares pairs in the rigid-motion-invariant form Task 2's still-face rule uses. `clusters` links faces by the rule above, then topologically sorts each cluster against `viewDirection`, resolving each triple with `g`'s normal at `positions`, stably on unordered pairs. `stackDepth` overlays the projected outlines of each group of coincident faces, takes one interior point of each cell of that arrangement (its centroid), counts the faces whose open interior contains it, and returns the maximum. Counting at the arrangement's vertices instead would count every face meeting at a crease vertex, so a flat sheet would score its vertex degree.
 951
 952- [ ] **Step 4: Run tests to verify they pass**
 953
 954Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests`
 955Expected: PASS.
 956
 957- [ ] **Step 5: Commit**
 958
 959```bash
 960git add Packages/FoldKit
 961git commit -m "Near-coplanar clustering and view-relative layer order"
 962```
 963
 964---
 965
 966### Task 6: The interpenetration checker
 967
 968**Files:**
 969- Create: `Packages/FoldKit/Sources/Folding/Interpenetration.swift`
 970- Test: `Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift`
 971
 972**Interfaces:**
 973- Consumes: Task 1–5 types.
 974- Produces:
 975  - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }`
 976  - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect. Task 7b adds an overload on the render mesh for non-rigid steps, whose faces bend
 977
 978"No facets pass through each other" is a headline anti-goal, so it gets a mechanical check rather than an eye. Coplanar faces are excluded — overlap there is the layer order's business. Coplanar means normals within 1e-6 rad and planes within 1e-6 × the sheet's size, so that faces landing on a stack to within the solver's tolerance count as landed. Otherwise a pair interpenetrates when their intersection reaches the relative interior of both faces; contact along edges or at vertices, shared or merely coincident, does not count. Pairs that share a vertex or an edge are **not** skipped: a flap that swings through a layer it shares a corner with is the error this exists to catch, and skipping every pair that shares a vertex would miss it. This is the function Task 7 runs per rigid step and Task 8's catalogue gate runs over every rigid step; non-rigid steps use Task 7b's mesh version.
 979
 980- [ ] **Step 1: Write the failing tests**
 981
 982```swift
 983@Test func aCleanFoldHasNoIntersections() throws {
 984    let (file, i) = try interpolator("half.fold", step: 1)
 985    #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
 986}
 987
 988@Test func twoFlapsFoldingIntoEachOtherAreDetected() throws {
 989    // both thirds of the letter sheet valley-folded at once: they meet at the midline from ~120°
 990    let (file, i) = try interpolatorForBothThirdsInFront()
 991    #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
 992}
 993
 994@Test func staggeredFlapsDoNotCollide() throws {
 995    // the same two flaps on separate windows of t
 996    let (file, i) = try interpolator("letter-staggered.fold", step: 1)
 997    #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
 998}
 999
1000@Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws {
1001    // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle
1002    // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z
1003    let (file, i) = try interpolatorForSharedVertexSweep()
1004    #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
1005}
1006
1007@Test func coplanarFacesAreNotReportedAsIntersecting() throws {
1008    let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
1009    let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
1010    #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
1011}
1012
1013@Test func edgeAdjacentFacesAreNotReportedAsIntersecting() throws {
1014    let (file, i) = try interpolator("quarters.fold", step: 3)
1015    #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
1016}
1017
1018@Test func theReportedParameterIsWhereTheIntersectionBegins() throws {
1019    let (file, i) = try interpolatorForBothThirdsInFront()
1020    let found = interpenetrations(i, faces: file.facesVertices, samples: 64)
1021    #expect(!found.isEmpty)
1022    #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 })   // the flaps meet at 120°
1023}
1024```
1025
1026- [ ] **Step 2: Run tests to verify they fail**
1027
1028Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests`
1029Expected: FAIL.
1030
1031- [ ] **Step 3: Implement `interpenetrations`**
1032
1033At each sample of `t`, triangulate the facets and test triangle-triangle intersection pairwise, skipping coplanar pairs. Discard an intersection that lies within 1e-9 of either face's boundary (the face's, not a triangle's, so the fan's internal edges do not count as boundary). An AABB pre-pass keeps the pairwise cost down; the models are small enough that nothing cleverer is needed.
1034
1035- [ ] **Step 4: Run tests to verify they pass**
1036
1037Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests`
1038Expected: PASS.
1039
1040- [ ] **Step 5: Commit**
1041
1042```bash
1043git add Packages/FoldKit
1044git commit -m "Facet interpenetration checker"
1045```
1046
1047---
1048
1049### Task 7: `foldc`, the fold-script compiler
1050
1051**Files:**
1052- Create: `Packages/FoldKit/Sources/foldc/main.swift`
1053- Create: `Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift`
1054- Create: `Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift`
1055- Create: `Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift`
1056- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,quarters,occlusion}-cp.fold` — each model fixture's sheet and creases as an editor would export them: no frames, every crease carrying its **final** `M`/`V` assignment from the fixture's last frame (`F` for a crease that ends flat). `compile` resets frame 0 to `F` and 0
1057- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,quarters,occlusion}.foldscript`
1058- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{unresolved-crease,angle-out-of-range}.foldscript`
1059- Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift` — `degreeFourPattern()` and `degreeFourScript()`, the same vertex as a crease pattern and a one-step script driven by the 140° crease
1060- Test: `Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift`
1061
1062**Interfaces:**
1063- Consumes: Task 1–6 types.
1064- Produces:
1065  - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script
1066  - `init (FoldScript).init(contentsOf url: URL) throws`
1067  - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]?; let spine: CreaseRef?; let openAngle: Double? }` — `windows` pairs with `creases`; `spine` and `openAngle` are for a reverse fold or sink (Task 7b)
1068  - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }`
1069  - `struct OrderOverride: Codable, Sendable { let above: SIMD2<Double>; let below: SIMD2<Double> }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint
1070  - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile`
1071  - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]`
1072  - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]`
1073  - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int, crease: CreaseRef); case noCreases(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2<Double>); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int); case noRigidMotion(step: Int); case curveTooCoarse(step: Int); case clockwiseFace(face: Int); case missingAngle(step: Int, crease: CreaseRef); case creaseListMismatch(step: Int); case solvedAxisWindowConflict(step: Int, edge: Int); case coincidentAxisAngle(step: Int, edge: Int) }` — Task 7b adds `popTooStrained`, `missingSpine` and `invalidSpine`
1074  - `foldc <script.foldscript> -o <model.fold>` — exits 0 on success, 1 naming the first failing step and its defects
1075
1076**This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step (Task 7b's mesh checker for a non-rigid step).
1077
1078Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`; `driver` is the first crease; `windows` are all `[0, 1]`.
1079
1080**Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the tree axes on some loop's cycle (the tree path between the two regions a loop crease joins), excluding the driver, as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. Every other axis stays linear on its scripted window. A solved axis whose scripted window differs from the driver's is rejected rather than ignored. It writes each solved axis's curve at 257 points. A solved angle that is linear to within 1e-9° is written without a curve. Each curve is checked at four times its sample density; if the gap exceeds 1e-6 × the sheet's size between samples, the step fails with `curveTooCoarse` (257 samples is fixed, and decision 0001 measured it sufficient). Regions are grown in the order the script lists the step's creases, driver first, so which crease closes a loop is determined by the script. A loop that does not close (the solver's gap stays above the tolerance) fails the step with `noRigidMotion`. The step then needs a decision (decision 0002); a solver that does not converge is not proof that no rigid motion exists, so check the script first. Reverse folds and sinks never reach this: they name a `spine` and are compiled by Task 7b. The last sample of every step is set to the end frame exactly.
1081
1082Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it.
1083
1084macOS only. Never linked into the app.
1085
1086- [ ] **Step 1: Write the failing tests**
1087
1088```swift
1089@Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"])
1090func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws {
1091    let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
1092                          pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
1093    #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12))
1094    #expect(validate(out).isEmpty)
1095}
1096
1097@Test func aCreaseThroughTwoLayersChangesBothEdges() throws {
1098    let out = try compiled("quarters")
1099    #expect(out.frames[3].edgesFoldAngle[8] == 180)
1100    #expect(out.frames[3].edgesFoldAngle[9] == -180)
1101    #expect(out.frames[3].edgesAssignment[9] == .mountain)
1102}
1103
1104@Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws {
1105    // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3
1106    #expect(try compiled("quarters").edgesFirstCreasedAtStep
1107        == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2])
1108}
1109
1110@Test func movingSideIsResolvedFromAContainedPoint() throws {
1111    #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1])
1112}
1113
1114@Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws {
1115    #expect(try compiled("half").frames[1].step?.axes[0].edge == 6)
1116}
1117
1118@Test func anOverrideReplacesTheGuessForThatPair() throws {
1119    let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
1120    let frame = file.frames[2]
1121    // the guess puts f2 (folded last) above f0; the override puts f0 above f2
1122    let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))],
1123                                          to: frame.faceOrders, frame: frame,
1124                                          viewpoint: frame.step!.viewpoint, file: file)
1125    #expect(swapped != frame.faceOrders)
1126    #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) }
1127}
1128
1129@Test func aCoupledStepIsSolvedIntoCurves() throws {
1130    // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease
1131    // gets a curve, the 0° crease rides on it, the 60° crease closes the loop
1132    let out = try compile(degreeFourScript(), pattern: degreeFourPattern())
1133    let axes = try #require(out.frames[1].step?.axes)
1134    #expect(axes.contains { $0.angles != nil })
1135    #expect(axes.contains { $0.parent != nil })
1136    for axis in axes where axis.angles != nil {
1137        #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6)
1138    }
1139}
1140
1141@Test func anUnresolvedCreaseNamesItsStep() {
1142    #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
1143        try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
1144                    pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
1145    }
1146}
1147
1148@Test func aStepThatFailsValidationNamesItsStep() {
1149    #expect {
1150        try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")),
1151                    pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
1152    } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } }
1153}
1154
1155@Test func guessedFaceOrdersAreAcyclic() throws {
1156    let out = try compiled("occlusion")
1157    for frame in out.frames { #expect(throws: Never.self) {
1158        try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } }
1159}
1160```
1161
1162- [ ] **Step 2: Run tests to verify they fail**
1163
1164Run: `swift test --package-path Packages/FoldKit --filter CompilerTests`
1165Expected: FAIL.
1166
1167- [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point**
1168
1169Every face of the crease pattern must be counterclockwise with the sheet's top side up; reject a pattern with a clockwise face (`clockwiseFace`) rather than rewinding it, since rewinding a y-down export also swaps which side is up and so swaps valley and mountain. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Produce each step's end frame by building the step and calling `FoldInterpolator.positions(at: 1)` on it, so vertex ownership, carried axes and reorientation have one implementation; Folding's `readStep(_ n: Int, in file: FoldFile) throws -> FoldStep` reads one step from frames 0…n and `readSteps` calls it for each n. The departure/arrival rule (a moving face may not have an overlapping still face on the side it departs toward in frame n − 1, or on the side it arrives from in frame n) needs the interpolator, so it is Folding's `layerMotionDefects`, built in Task 8; `foldc` runs it per step from then on. A crease found on a named crease's line through another layer takes its angle from the pattern's assignment, so `foldc` rejects such an edge (`coincidentAxisAngle`) when it becomes an axis while the named crease's scripted angle is not ±180; deriving its angle is left until a model needs it. Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. Write `faceOrders` and the mid-fold order as every overlapping pair once, `[f, g, s]` with `f < g`, as the fixtures do. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly.
1170
1171- [ ] **Step 4: Run tests to verify they pass**
1172
1173Run: `swift test --package-path Packages/FoldKit --filter CompilerTests`
1174Expected: PASS.
1175
1176- [ ] **Step 5: Commit**
1177
1178```bash
1179git add Packages/FoldKit
1180git commit -m "foldc: compile a fold script and crease pattern into a FOLD sequence"
1181```
1182
1183---
1184
1185### Task 7b: Non-rigid steps — open, pop, close
1186
1187**Files:**
1188- Create: `Packages/FoldKit/Sources/Folding/RenderMesh.swift`
1189- Create: `Packages/FoldKit/Sources/Folding/Bending.swift`
1190- Modify: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift`
1191- Modify: `Packages/FoldKit/Sources/Folding/Interpenetration.swift`
1192- Create: `Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift`
1193- Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-cp.fold`, `reverse.foldscript` — decision 0001's case 4 flap: a 4×2 sheet, spine y = 1, reverse-fold creases from (2, 1) to (3, 0) and (3, 2); step 1 folds the flap in half on the spine, step 2 is an inside reverse fold naming the spine y = 1
1194- Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift` — `tipIsBetweenBodyLayers(_:_:)` and `FoldScript.withOpenAngle(_:step:)` (see *Test helpers*)
1195- Test: `Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift`
1196
1197**Interfaces:**
1198- Consumes: Tasks 1–7.
1199- Produces:
1200  - `struct RenderMesh: Sendable { init(file: FoldFile, spacing: Double); let vertices: [SIMD2<Double>]; let triangles: [(Int, Int, Int)]; let faceOf: [Int]; let meshVertexOf: [Int] }` — built as the spike builds it: the planar arrangement of frame 0's edges plus lines every `spacing` in x and in y, each resulting convex cell fanned into triangles. `faceOf` maps a triangle to its FOLD face, `meshVertexOf` a FOLD vertex to its mesh vertex. The FOLD topology is unchanged; the mesh is the renderer's
1201  - `static func (RenderMesh).spacing(for file: FoldFile) -> Double` — frame 0's bounding box's longer side / 32
1202  - `let (FoldInterpolator).mesh: RenderMesh` — built at `init` with `RenderMesh.spacing(for:)`; for a non-rigid step the pop's least-squares matrix is factored once, at `init`
1203  - `func (FoldInterpolator).meshPositions(at t: Double) -> [SIMD3<Double>]` — for a rigid step, each face's transform applied to its mesh vertices; for a non-rigid step, the three phases below. On a non-rigid step `positions(at:)` returns the mesh positions of the FOLD vertices
1204  - `func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double` — the largest relative change in a mesh edge's length
1205  - `func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection]` — Task 6's test on mesh triangles, reporting FOLD faces; used for non-rigid steps, whose faces bend
1206  - `func compilePop(step: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord`
1207  - `CompileError` gains `popTooStrained(step: Int, strain: Double)`, `missingSpine(step: Int)` and `invalidSpine(step: Int)` (a spine on a step that is not a fold, or not folded flat)
1208
1209Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*:
1210
12111. **Open**, `[0, phases[0]]`: the flap opens rigidly on its spine from 180° to `openAngle` (default 30°, measured from flat; 20° since decision 0003), carrying everything on that side of the spine. The layer nearer the step's viewpoint opens; the other holds. A script field to choose the other layer is added when a model needs it.
12122. **Pop**, `[phases[0], phases[1]]`: as-rigid-as-possible interpolation on the render mesh, from the open pose to `popped`. Each triangle's rotation is slerped from one pose to the other, the mesh positions are solved by least squares, and the faces that do not move in the step are held.
12133. **Close**, `[phases[1], 1]`: rigid, on the reverse-fold branch, from `popped` to frame n. `closeAxes` are an ordinary axis tree with solved curves, relative to `popped`.
1214
1215**What makes a step non-rigid is its script, not the solver.** A step with technique `insideReverse`, `outsideReverse` or `sink` must name a `spine`, and `foldc` fails it with `missingSpine` otherwise. Closure cannot decide this: with the flap closed, the solver finds a rigid motion to the reverse fold's coordinates with the tip swung outside (decision 0001, case 4(a)), which is the wrong fold. For a step with a spine, `foldc`:
1216
1217- builds `openAxes` (the spine as one linear axis);
1218- builds `popped` (the reverse-fold branch with the spine held at `openAngle`, solved as in Task 7, starting each other crease at `openAngle`/180 of its travel, as the spike does). Closing the loops does not show which branch was found; a wrong branch is caught by the close reaching frame n's coordinates, the final assignment check and the validator's layer rules;
1219- builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved);
1220- checks `popped` has one position per vertex;
1221- writes `openAngle` and `phases` into the file explicitly: 30° (20° since decision 0003) and [⅓, ⅔] are the script's defaults, and the decoder requires both. The validator rejects a pop record with the wrong number of positions, phases outside 0 < p₀ < p₁ < 1, or a non-rigid step without one (`popMalformed`);
1222- measures the pop's strain on the step's render mesh, and fails the step above **10%**.
1223
1224Decision 0002 measured 7.9% at 30° and 29% at 60° on this flap, at a mesh spacing of 1/32 of its longer side. Only the inside reverse fold was measured. Outside reverse folds and sinks use the same model until a model of theirs fails the bound; if one does, stop for a decision.
1225
1226- [ ] **Step 1: Write the failing tests**
1227
1228```swift
1229@Test func aReverseFoldCompilesToANonRigidStep() throws {
1230    let out = try compiled("reverse")
1231    let step = try #require(out.frames[2].step)
1232    #expect(step.nonRigid)
1233    #expect(step.pop?.openAngle == 30)
1234    #expect(step.technique == .insideReverse)
1235}
1236
1237@Test func aReverseFoldWithoutASpineIsRejected() {
1238    #expect(throws: CompileError.missingSpine(step: 2)) {
1239        try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2),
1240                    pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
1241    }
1242}
1243
1244@Test func theOpenAndCloseLegsAreRigid() throws {
1245    // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy
1246    let file = try compiled("reverse")
1247    let step = try readSteps(file)[1]
1248    let i = FoldInterpolator(file: file, step: step)
1249    for n in 0...256 {
1250        let t = Double(n) / 256
1251        guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue }
1252        #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)")
1253    }
1254}
1255
1256@Test func thePopStaysWithinTheBound() throws {
1257    let file = try compiled("reverse")
1258    let step = try readSteps(file)[1]
1259    let i = FoldInterpolator(file: file, step: step)
1260    let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1261    let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
1262    #expect(worst <= 0.10)
1263}
1264
1265@Test func theStepEndsOnItsEndFrame() throws {
1266    let file = try compiled("reverse")
1267    let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
1268    #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 })
1269}
1270
1271@Test func nothingPassesThroughAnything() throws {
1272    let file = try compiled("reverse")
1273    let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
1274    #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
1275}
1276
1277@Test func theTipLandsBetweenTheFlapsLayers() throws {
1278    // 97% of the way through the closing phase, a point of the tip lies between the body's two layers
1279    let file = try compiled("reverse")
1280    let step = try readSteps(file)[1]
1281    let i = FoldInterpolator(file: file, step: step)
1282    let upper = step.pop!.phases.upperBound
1283    #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file))
1284}
1285
1286@Test func aFlapOpenedOnlyTo60DegreesIsRejected() {
1287    #expect {
1288        try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2),
1289                    pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
1290    } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } }
1291}
1292
1293@Test func thePopFitsInAFrameBudget() throws {
1294    let file = try compiled("reverse")
1295    let step = try readSteps(file)[1]
1296    let i = FoldInterpolator(file: file, step: step)
1297    let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1298    let elapsed = ContinuousClock().measure {
1299        for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) }
1300    }
1301    #expect(elapsed / 100 < .milliseconds(4))
1302}
1303```
1304
1305- [ ] **Step 2: Run tests to verify they fail**
1306
1307Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests`
1308Expected: FAIL.
1309
1310- [ ] **Step 3: Implement `RenderMesh`, the pop in `FoldInterpolator`, `meshInterpenetrations`, and `compilePop`**
1311
1312`spikes/interpolation/Sources/Spike/Bending.swift` is the reference for the mesh and the pop; `main.swift`'s case 6 is the reference for building the popped pose and the closing branch. A dense Cholesky factor is fine at the spike's size (561 vertices); at a full model's 1/32 mesh use a sparse one, since the frame budget test runs per frame.
1313
1314- [ ] **Step 4: Run tests to verify they pass**
1315
1316Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests`
1317Expected: PASS.
1318
1319- [ ] **Step 5: Commit**
1320
1321```bash
1322git add Packages/FoldKit
1323git commit -m "Non-rigid steps: open, pop, close"
1324```
1325
1326---
1327
1328### Task 8: `foldlint` and the model catalogue gate
1329
1330**Files:**
1331- Create: `Packages/FoldKit/Sources/foldlint/main.swift`
1332- Create: `Packages/FoldKit/Sources/Models/ModelLibrary.swift`
1333- Create: `Packages/FoldKit/Sources/Models/Resources/cup.fold`
1334- Create: `Models/cup.foldscript`
1335- Create: `Models/cup-cp.fold`
1336- Create: `docs/authoring/cup.md`
1337- Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift`
1338
1339**Interfaces:**
1340- Consumes: Tasks 1–7b.
1341- Produces:
1342  - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }`
1343  - `foldlint <path>...` — runs `validate` and then `readSteps`, which rejects step records the validator does not check; exits 0 when clean, 1 with one defect per line
1344  - `func layerMotionDefects(_ file: FoldFile) -> [FoldDefect]` in Folding, and `FoldDefect.movesThroughStillFace(step:moving:still:)` — the departure/arrival rule. Departure is read just after a face starts moving, against frame n − 1's order; arrival just before it stops, against frame n's. A non-rigid step uses its open axes for departure and its close axes for arrival, and the faces that open on the spine count as moving. `layerMotionDefects(step:in:)` checks one step on frames 0…n; `foldlint`, the catalogue gate and `foldc` (per step, as a `stepFailed`) run it. The arrival read time is the one the layer guess uses, so for a step without overrides the arrival check cannot disagree with the guess; it checks overrides and departures
1345
1346**The cup is the model authored here, not the crane.** Six steps — five folds of one axis each and a turn-over — no reverse folds, six layers where the corner flaps cross and eight in the centre once both top flaps are down. It exercises script, compile, validate, interpolate and the catalogue gate end to end without exercising coupled steps or deep stacks at the same time. The version authored folds the top flaps down — the front one, then after the turn-over the back one — rather than tucking them into the pocket, and it ends flat. Step 1's instruction starts "Valley fold"; Task 14's accessibility test reads it.
1347
1348Its crease pattern and `.foldscript` are committed next to the generated `.fold`, so the model regenerates rather than only being editable. `docs/authoring/cup.md` records the crease pattern's provenance and every layer-order override and why.
1349
1350- [ ] **Step 1: Write the failing tests**
1351
1352```swift
1353@Test func everyShippedStepEndsOnItsEndFrame() throws {
1354    // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n
1355    for file in try ModelLibrary.all() {
1356        for step in try readSteps(file) {
1357            let i = FoldInterpolator(file: file, step: step)
1358            #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords)
1359                .allSatisfy { simd_distance($0, $1) < 1e-6 * sheetSize(file) }, "\(file.fileTitle ?? "?") step \(step.index)")
1360        }
1361    }
1362}
1363
1364@Test func everyShippedModelValidates() throws {
1365    for file in try ModelLibrary.all() { #expect(validate(file).isEmpty, "\(file.fileTitle ?? "?")") }
1366}
1367
1368@Test func everyShippedModelReadsItsSteps() throws {
1369    for file in try ModelLibrary.all() {
1370        #expect(try readSteps(file).count == file.stepCount)
1371    }
1372}
1373
1374@Test func noShippedModelStretchesAtAnyStep() throws {
1375    // flagged non-rigid steps are held to Task 0b's bound instead
1376    for file in try ModelLibrary.all() {
1377        for step in try readSteps(file) where !step.nonRigid {
1378            let i = FoldInterpolator(file: file, step: step)
1379            for t in stride(from: 0.0, through: 1.0, by: 1.0 / 256) {
1380                #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6,
1381                        "\(file.fileTitle ?? "?") step \(step.index) t \(t)")
1382            }
1383        }
1384    }
1385}
1386
1387@Test func noShippedModelInterpenetratesAtAnyStep() throws {
1388    // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh
1389    for file in try ModelLibrary.all() {
1390        for step in try readSteps(file) where !step.nonRigid {
1391            let i = FoldInterpolator(file: file, step: step)
1392            #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty,
1393                    "\(file.fileTitle ?? "?") step \(step.index)")
1394        }
1395    }
1396}
1397
1398@Test func everyModelIsAttributedAsTraditional() throws {
1399    for file in try ModelLibrary.all() { #expect(file.fileAuthor == "Traditional") }
1400}
1401
1402@Test func everyShippedModelRegeneratesFromItsScript() throws {
1403    for name in try ModelLibrary.names() {
1404        let recompiled = try compile(FoldScript(contentsOf: script(name)),
1405                                     pattern: FoldFile(contentsOf: pattern(name)))
1406        #expect(structurallyEqual(recompiled, try ModelLibrary.model(named: name), tolerance: 1e-12), "\(name)")
1407    }
1408}
1409
1410@Test func everyFlaggedStepStaysWithinTheBound() throws {
1411    // decision 0002: 10% largest edge strain on the render mesh, and nothing passes through anything
1412    for file in try ModelLibrary.all() {
1413        for step in try readSteps(file) where step.nonRigid {
1414            let i = FoldInterpolator(file: file, step: step)
1415            let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
1416            let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()!
1417            #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)")
1418            #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
1419        }
1420    }
1421}
1422
1423@Test func theCatalogueContainsTheCup() throws {
1424    #expect(try ModelLibrary.names() == ["cup"])
1425}
1426
1427@Test func theCupContainsATurnOverStep() throws {
1428    #expect(try readSteps(ModelLibrary.model(named: "cup")).contains { $0.kind == .turnOver })
1429}
1430
1431@Test func foldlintExitsNonZeroOnADefectiveFile() throws {
1432    #expect(try runFoldlint(on: fixture("bad-index.fold")).exitCode == 1)
1433}
1434```
1435
1436- [ ] **Step 2: Run tests to verify they fail**
1437
1438Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests`
1439Expected: FAIL.
1440
1441- [ ] **Step 3: Implement `ModelLibrary`, `foldlint`, and author the cup's crease pattern and script**
1442
1443Iterate the cup against `foldc` and `foldlint` until clean, adding `faceOrders` overrides to the script where the interpenetration checker or the validator's layer-order rules object. The cup's turn-over step is what Task 13's gesture will be built against, so it must be present and correct here.
1444
1445- [ ] **Step 4: Run tests to verify they pass**
1446
1447Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests`
1448Expected: PASS.
1449
1450- [ ] **Step 5: Commit**
1451
1452```bash
1453git add Packages/FoldKit Models docs/authoring
1454git commit -m "Model library, foldlint and the cup"
1455```
1456
1457---
1458
1459### Task 9: Diagram generation with layer-aware occlusion
1460
1461**Files:**
1462- Create: `Packages/FoldKit/Sources/Notation/DiagramStyle.swift`
1463- Create: `Packages/FoldKit/Sources/Notation/DiagramBuilder.swift`
1464- Create: `Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift`
1465- Test: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift`
1466- Test: `Packages/FoldKit/Tests/NotationTests/Snapshots/` (golden images, and `NOTATION.md` recording each symbol choice and its source)
1467
1468**Interfaces:**
1469- Consumes: Task 1–5 and Task 8 (the cup).
1470- Produces:
1471  - `enum DiagramLine: Equatable, Sendable { case solid, light, dashed, dashDot }`
1472  - `enum DiagramArrow: Equatable, Sendable { case valleyFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>); case mountainFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>); case foldAndUnfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>, mountain: Bool); case technique(StepTechnique, at: SIMD2<Double>, toward: SIMD2<Double>); case turnOver(TurnOverAxis); case rotate(degrees: Double); case repeatMark(of: Int) }`
1473  - `struct DiagramEdge: Equatable, Sendable { let edge: Int; let from: SIMD2<Double>; let to: SIMD2<Double>; let style: DiagramLine }`
1474  - `struct Diagram: Equatable, Sendable { let edges: [DiagramEdge]; let arrows: [DiagramArrow] }`
1475  - `func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram` — draws frame `step.index − 1` with step `step.index`'s creases and arrows
1476  - `func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) -> [(SIMD2<Double>, SIMD2<Double>)]`
1477  - `struct DiagramStyle: Sendable`
1478
1479The view is orthographic from the step's authored `viewpoint` and does **not** rotate when the model is orbited. This task owns Review Focus item 5.
1480
1481Edge classes, for the diagram of step n drawing frame n − 1: `B` edges and creases folded in frame n − 1 are solid; creases made earlier and flat again are light; step n's creases (every edge coincident with an axis) are dashed for a valley and dash-dot for a mountain **as seen from the viewpoint**: the axis's turn `Δ` (`endAngle − startAngle`, or `peakAngle − startAngle` for `foldAndUnfold`) moves the moving face toward its own normal, so the fold is a valley as seen when `sign(Δ) · sign(n · eye) > 0`, with `n` the moving face's normal in frame n − 1. FOLD's assignment is relative to each face's own normal and cannot be used: on a flipped layer, or after a turn-over, it names the opposite fold, and coincident edges on different layers disagree; creases whose `edges_krz:firstCreasedAtStep` is later than n are not drawn. Arrows: a `plain` step gets one valley-fold or mountain-fold arrow per axis, by the same as-seen rule; a named technique gets that technique's arrows from the reference and no per-axis arrows; reorientation and repeat steps get their symbols.
1482
1483Reference, per the spec: Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by OrigamiUSA; where they differ OrigamiUSA's is used, and the choice is recorded in `Snapshots/NOTATION.md`.
1484
1485- [ ] **Step 1: Write the failing tests**
1486
1487```swift
1488@Test func valleyCreaseOfThisStepIsDashed() throws {
1489    #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .dashed }.map(\.edge) == [6])
1490}
1491
1492@Test func mountainCreaseOfThisStepIsDashDot() throws {
1493    #expect(try diagram("mountain.fold", step: 1).edges.filter { $0.style == .dashDot }.map(\.edge) == [6])
1494}
1495
1496@Test func valleyAndMountainAreAsSeenNotAsAssigned() throws {
1497    // quarters step 3 folds both layers; the top layer is flipped, so its edge e9 is
1498    // assigned M, but the fold is a valley as seen and nothing is dash-dot
1499    let d = try diagram("quarters.fold", step: 3)
1500    #expect(d.edges.contains { $0.style == .dashed })
1501    #expect(!d.edges.contains { $0.style == .dashDot })
1502    #expect(d.arrows.contains { if case .valleyFold = $0 { true } else { false } })
1503}
1504
1505@Test func anEdgeUnderASeamIsHidden() throws {
1506    // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2
1507    #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 })
1508}
1509
1510@Test func boundaryEdgesAreSolid() throws {
1511    #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .solid }.count == 6)
1512}
1513
1514@Test func aCreaseMadeEarlierAndFlatAgainIsLight() throws {
1515    // quarters step 2 draws frame 1, after the fold-and-unfold on x = 1
1516    #expect(Set(try diagram("quarters.fold", step: 2).edges.filter { $0.style == .light }.map(\.edge)) == [8, 9])
1517}
1518
1519@Test func creasesNotYetMetAreNotDrawnAtAll() throws {
1520    // frame 0 carries the y = 1 creases too; step 1's diagram must not show them
1521    #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) })
1522}
1523
1524@Test func edgesOccludedByLayersAboveThemAreOmitted() throws {
1525    // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip
1526    #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 })
1527}
1528
1529@Test func anEdgePartlyOccludedIsClippedNotDropped() throws {
1530    // f0's raw edge from (0,2) to (2,2) is covered for x in [1, 2]
1531    let segments = try visibleSegmentsOf("occlusion.fold", edge: 7, inFrame: 2)
1532    #expect(segments.count == 1)
1533    #expect(abs(segmentLength(segments[0]) - 1) < 1e-9)
1534}
1535
1536@Test func aPlainMultiAxisStepGetsOneArrowPerAxis() throws {
1537    let arrows = try diagram("letter.fold", step: 1).arrows
1538    #expect(arrows.filter { if case .valleyFold = $0 { true } else { false } }.count == 1)
1539    #expect(arrows.filter { if case .mountainFold = $0 { true } else { false } }.count == 1)
1540}
1541
1542@Test func aTechniqueStepGetsItsOwnArrowsNotOnePerAxis() throws {
1543    let arrows = try diagram("letter-technique.fold", step: 1).arrows
1544    #expect(arrows.filter { if case .technique(.insideReverse, _, _) = $0 { true } else { false } }.count == 1)
1545    #expect(!arrows.contains { if case .valleyFold = $0 { true } else if case .mountainFold = $0 { true } else { false } })
1546}
1547
1548@Test func foldAndUnfoldStepGetsTheReturnHead() throws {
1549    #expect(try diagram("quarters.fold", step: 1).arrows
1550        .contains { if case .foldAndUnfold = $0 { true } else { false } })
1551}
1552
1553@Test func turnOverStepCarriesTheTurnOverSymbol() throws {
1554    #expect(try diagram("half.fold", step: 2).arrows.contains(.turnOver(.vertical)))
1555}
1556
1557@Test func rotateStepCarriesItsDegrees() throws {
1558    #expect(try diagram("half.fold", step: 3).arrows.contains(.rotate(degrees: 90)))
1559}
1560
1561@Test func aRepeatedStepCarriesTheRepeatMark() throws {
1562    #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1)))
1563}
1564
1565@Test func everyStepMatchesItsGoldenImage() throws {
1566    for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"] {
1567        let file = try FoldFile(contentsOf: fixture("\(name).fold"))
1568        for step in try readSteps(file) {
1569            try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)")
1570        }
1571    }
1572    let cup = try ModelLibrary.model(named: "cup")
1573    for step in try readSteps(cup) {
1574        try expectSnapshot(render(buildDiagram(file: cup, step: step)), named: "cup-\(step.index)")
1575    }
1576}
1577```
1578
1579- [ ] **Step 2: Run tests to verify they fail**
1580
1581Run: `swift test --package-path Packages/FoldKit --filter DiagramTests`
1582Expected: FAIL.
1583
1584- [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`**
1585
1586Project through the viewpoint's orthographic matrix. Classify each edge as above. Clip each edge against the **union** of the projected faces `order` places above either of the edge's incident faces, and emit the surviving segments, drawing coincident segments once. Clipping against each face separately would keep an edge lying under the seam between two adjacent upper faces — e8 in quarters frame 2 lies on the boundary of f3 and of f2 but inside their union. An edge on the outer boundary of that union is not hidden. Subdivision edges are never drawn. A face hides an edge when it follows either of the edge's faces in their shared cluster, from `LayerOrder.clusters` looking along −`eye`; faces in other clusters do not occlude, which holds while every diagram frame is flat. Golden images are recorded when missing or with `FOLD_RECORD_SNAPSHOTS=1` (the test fails when it records), compared at 24/255 per channel, inspected by eye against the reference, then committed. The drawing itself is Notation's, so the app's diagram and the goldens are one drawing.
1587
1588- [ ] **Step 4: Run tests to verify they pass**
1589
1590Run: `swift test --package-path Packages/FoldKit --filter DiagramTests`
1591Expected: PASS.
1592
1593- [ ] **Step 5: Commit**
1594
1595```bash
1596git add Packages/FoldKit
1597git commit -m "Diagram generation with layer-aware edge occlusion"
1598```
1599
1600---
1601
1602### Task 10: The Metal paper renderer
1603
1604**Files:**
1605- Create: `Packages/FoldKit/Sources/Folding/Camera.swift`
1606- Create: `Packages/FoldKit/Sources/Renderer/PaperRenderer.swift`
1607- Create: `Packages/FoldKit/Sources/Renderer/Shaders.metal`
1608- Test: `Packages/FoldKit/Tests/FoldingTests/CameraTests.swift`
1609- Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift`
1610
1611**Interfaces:**
1612- Consumes: Tasks 1–5 and 7b (`RenderMesh`).
1613- Produces:
1614  - `struct Camera: Sendable { var eye: SIMD3<Double>; var target: SIMD3<Double>; var up: SIMD3<Double>; var fieldOfView: Double }` — in `Folding`, not `Renderer`: it is plain `simd`, and Task 12's mapping in `Folding` needs it, while `Renderer` already depends on `Folding`
1615  - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space
1616  - `var (Camera).viewDirection: SIMD3<Double> { get }` — unit vector from `eye` toward `target`
1617  - `final class PaperRenderer { init(device: MTLDevice) throws }`
1618  - `func (PaperRenderer).render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4<Float>]? = nil, into: MTLTexture) throws` — draws the render mesh (Task 7b), so a bending face in a non-rigid step draws as it bends; `positions` are mesh positions, clusters are of FOLD faces and each triangle draws with its face. `faceColours`, when given, draws FOLD face *i* in one flat unlit colour on both sides; it exists so tests can tell faces apart
1619
1620Depth handling is **hybrid**. `faceOrders` is defined only for faces that overlap geometrically, so it says nothing about the facets separated in space that make up most of a folded model, and depth testing off everywhere would be wrong for them:
1621
1622- clusters come from Task 5, already resolved against `camera.viewDirection`, over FOLD faces, never render-mesh triangles; compute membership once per *t* and re-sort only when the camera moves;
1623- each cluster is drawn back-to-front in its order with depth test on (less-or-equal) and depth **writes off**, so stacked faces resolve by order rather than by z;
1624- then the same cluster is drawn again **depth-only** (colour writes off), so that clusters drawn after it are hidden behind it. Without this pass a cluster writes no depth and anything drawn later draws over it.
1625
1626Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3.
1627
1628During a non-rigid step the faces that open on the spine move, but `FoldStep.movingFaceUnion` holds only the main axes' faces (the pop's held faces depend on that). `LayerOrder.active`'s rewrite of mixed moving/still pairs must use the set `layerMotionDefects` uses — the main, open and close axes' faces — made a named `FoldStep` property here (`allMovingFaces`) rather than a second copy. The pop's `SparseCholesky` factor is `@unchecked Sendable`; confirm concurrent solves on one factor are safe, or serialise them, before the renderer calls the interpolator from more than one thread.
1629
1630`Shaders.metal` is a copied resource compiled at `PaperRenderer.init` with `makeLibrary(source:options:)`: SwiftPM can compile it with the Metal toolchain (*Setup* step 4), but then warns on every build.
1631
1632- [ ] **Step 1: Write the failing tests**
1633
1634The geometry helpers return positions, faces, normals and a `RenderMesh` over those faces; `red`, `green` and `blue` are the debug colours of faces 0, 1 and 2. `stackedCoplanarSquares()` is two coincident unit squares facing +z with face 0 above face 1 (`[[0, 1, 1]]`).
1635
1636```swift
1637@Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() {
1638    let c = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
1639    let p = c.viewProjection(aspect: 1.5) * SIMD4(0, 0, 0, 1)
1640    #expect(abs(p.x / p.w) < 1e-12 && abs(p.y / p.w) < 1e-12)
1641    #expect(c.viewDirection == SIMD3(0, 0, -1))
1642}
1643
1644@Test func coplanarStackedFacesDoNotZFight() throws {
1645    let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [1, 0])],
1646                                    camera: cameraAbove(), faceColours: [red, green])
1647    #expect(uniqueColours(pixels) == [red])
1648}
1649
1650@Test func clusterOrderDeterminesWhichCoplanarFaceIsVisible() throws {
1651    let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [0, 1])],
1652                                    camera: cameraAbove(), faceColours: [red, green])
1653    #expect(uniqueColours(pixels) == [green])
1654}
1655
1656@Test func nearlyCoplanarFacesDoNotZFight() throws {
1657    // face 0 tilted 1° about its left edge, resting on face 1, in one cluster
1658    let pixels = try renderToPixels(squareOverATiltedSquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])],
1659                                    camera: cameraAbove(), faceColours: [red, green])
1660    #expect(uniqueColours(pixels) == [red])
1661}
1662
1663@Test func facesSeparatedInSpaceAreResolvedByDepthNotByOrder() throws {
1664    // face 0 is nearer the camera but drawn first
1665    let pixels = try renderToPixels(separatedSquares(),
1666                                    clusters: [CoplanarCluster(faces: [0]), CoplanarCluster(faces: [1])],
1667                                    camera: cameraAbove(), faceColours: [red, green])
1668    #expect(dominantColour(pixels) == red)
1669}
1670
1671@Test func aStackDrawnFirstStillHidesAFaceBehindItDrawnLater() throws {
1672    // faces 0 and 1 stacked near the camera, face 2 farther away and drawn last
1673    let pixels = try renderToPixels(nearStackAndFarSquare(),
1674                                    clusters: [CoplanarCluster(faces: [1, 0]), CoplanarCluster(faces: [2])],
1675                                    camera: cameraAbove(), faceColours: [red, green, blue])
1676    #expect(dominantColour(pixels) == red)
1677}
1678
1679@Test func orbitingUnderneathShowsTheBottomOfTheStack() throws {
1680    // clusters computed by Task 5 for each camera, as the app does
1681    let above = try renderStackWithComputedClusters(camera: cameraAbove(), faceColours: [red, green])
1682    let below = try renderStackWithComputedClusters(camera: cameraBelow(), faceColours: [red, green])
1683    #expect(uniqueColours(above) == [red])
1684    #expect(uniqueColours(below) == [green])
1685}
1686
1687@Test func backOfPaperRendersInTheBackColour() throws {
1688    let pixels = try renderToPixels(singleSquareFacingAway(), clusters: [CoplanarCluster(faces: [0])],
1689                                    camera: cameraAbove())
1690    #expect(uniqueColours(pixels) == [backColour])
1691}
1692```
1693
1694These require a Metal device; the target skips when `MTLCreateSystemDefaultDevice()` is nil. `uniqueColours` ignores the background.
1695
1696- [ ] **Step 2: Run tests to verify they fail**
1697
1698Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"`
1699Expected: FAIL.
1700
1701- [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders**
1702
1703One vertex and one fragment function. Draw the render mesh's triangles, grouped by FOLD face for clusters. Flat shading with one directional term, or the debug colour unlit. Two depth-stencil states — test on with writes off for a cluster's colour pass, test and write on for its depth pass — and a pipeline variant with colour writes masked off for the depth pass.
1704
1705- [ ] **Step 4: Run tests to verify they pass**
1706
1707Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"`
1708Expected: PASS.
1709
1710- [ ] **Step 5: Commit**
1711
1712```bash
1713git add Packages/FoldKit
1714git commit -m "Metal paper renderer with hybrid depth and cluster ordering"
1715```
1716
1717---
1718
1719### Task 11: App shell, model list and the step layout
1720
1721**Files:**
1722- Create: `App/project.yml`
1723- Create: `App/Sources/FoldApp.swift`
1724- Create: `App/Sources/ModelListView.swift`
1725- Create: `App/Sources/StepView.swift`
1726- Create: `App/Sources/DiagramCanvas.swift`
1727- Create: `App/Sources/PaperView.swift`
1728- Create: `App/Sources/Info.plist`
1729- Test: `App/UITests/StepNavigationTests.swift`
1730
1731**Interfaces:**
1732- Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator` (with `mesh` and `meshPositions(at:)`), `RenderMesh`, `LayerOrder`, `buildDiagram`, `PaperRenderer`, `Camera`.
1733- Produces:
1734  - `struct ModelListView: View`
1735  - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1
1736  - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)`
1737  - `struct PaperView: View` — `init(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI; positions come from `FoldInterpolator.meshPositions(at:)` and the mesh from `FoldInterpolator.mesh`
1738
1739`project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`.
1740
1741`DiagramCanvas` draws through Notation's public CoreGraphics drawing function (via `GraphicsContext.withCGContext`), the same one Task 9's golden images are rendered with, so the snapshots hold the diagram the user sees; it adds no glyph geometry of its own. `PaperView` computes cluster membership once per *t* and re-sorts only when the camera moves; `LayerOrder.clusters` computes both together, so add the split there if profiling on device shows the per-frame cost matters. Reuse the vertex buffer between frames, and give the depth texture `.memoryless` storage on iOS.
1742
1743- [ ] **Step 1: Write the failing UI tests**
1744
1745```swift
1746func testCupOpensAtStepOne() {
1747    let app = XCUIApplication(); app.launch()
1748    app.buttons["Cup"].tap()
1749    XCTAssertEqual(app.staticTexts["step.index"].label, "1")
1750}
1751
1752func testStepNeverAdvancesWithoutTheUserCompletingTheFold() {
1753    let app = XCUIApplication(); app.launch()
1754    app.buttons["Cup"].tap()
1755    sleep(3)
1756    XCTAssertEqual(app.staticTexts["step.index"].label, "1")
1757}
1758
1759func testTheDiagramIsCaptionedWithTheStepsInstruction() {
1760    let app = XCUIApplication(); app.launch()
1761    app.buttons["Cup"].tap()
1762    XCTAssertTrue(app.staticTexts["diagram.caption"].label.hasPrefix("Valley fold"))
1763}
1764```
1765
1766Completing a step needs Task 12's gesture and orbiting needs Task 14's; their tests are written there.
1767
1768- [ ] **Step 2: Run tests to verify they fail**
1769
1770Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`
1771Expected: FAIL — no such project.
1772
1773- [ ] **Step 3: Generate the project and implement the shell, list, step layout and both canvases**
1774
1775- [ ] **Step 4: Run tests to verify they pass**
1776
1777Run: `xcodegen generate --spec App/project.yml`, then as above.
1778Expected: PASS.
1779
1780- [ ] **Step 5: Commit**
1781
1782```bash
1783git add App
1784git commit -m "App shell, model list and step layout"
1785```
1786
1787---
1788
1789### Task 12: The fold gesture
1790
1791**Files:**
1792- Create: `App/Sources/FoldGesture.swift`
1793- Create: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift`
1794- Test: `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift`
1795- Test: `App/UITests/FoldGestureTests.swift`
1796
1797**Interfaces:**
1798- Consumes: Task 3, 4 and 7b types; `Camera` (in `Folding`) from Task 10.
1799- Produces:
1800  - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) }`
1801  - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double` — clamped to 0...1
1802  - `var (FoldParameterMapping).path: [SIMD2<Double>] { get }` — the first moving set's centroid in screen points at 129 samples of `t`
1803  - `var (FoldParameterMapping).isDegenerate: Bool { get }` — path under 8 points long
1804
1805This task owns Review Focus item 4.
1806
1807The finger drives the facet, not an abstract slider: the parameter is the point on the centroid's screen path nearest the centroid's position when grabbed plus the drag's translation, searched outward from `current` so the parameter cannot jump to a distant part of the path. A linear mapping onto the chord would leave the facet trailing the finger by up to a fifth of the throw on a 180° fold, because the centroid's screen speed is not constant. When the path is degenerate, fall back to vertical drag over a fixed 160-point throw so sensitivity stays bounded. For `foldAndUnfold`, search the outbound half (`t` 0...0.5) until the parameter reaches 0.5, then the return half (0.5...1). A non-rigid step's path doubles back the same way. It follows the centroid of the faces beyond the reverse creases through open, pop and close, and is searched one phase at a time, in order: the parameter enters a phase only once it has reached the end of the one before.
1808
1809- [ ] **Step 1: Write the failing tests**
1810
1811```swift
1812@Test func theFacetTracksTheFinger() throws {
1813    let m = try mapping("half.fold", step: 1)        // viewed from above
1814    let target = m.path[32]                          // t = 0.25
1815    let t = m.parameter(grabbedAt: m.path[0], translation: target - m.path[0], current: 0)
1816    #expect(abs(t - 0.25) < 0.01)
1817}
1818
1819@Test func dragPerpendicularToThePathDoesNotAdvanceTheFold() throws {
1820    let m = try mapping("half.fold", step: 1)
1821    let along = simd_normalize(m.path[1] - m.path[0])
1822    let perp = SIMD2(-along.y, along.x)
1823    #expect(m.parameter(grabbedAt: m.path[0], translation: perp * 50, current: 0) < 0.01)
1824}
1825
1826@Test func parameterIsClampedToUnitRange() throws {
1827    let m = try mapping("half.fold", step: 1)
1828    let along = simd_normalize(m.path[128] - m.path[0])
1829    #expect(m.parameter(grabbedAt: m.path[0], translation: along * 100_000, current: 0) == 1)
1830    #expect(m.parameter(grabbedAt: m.path[0], translation: along * -100_000, current: 0) == 0)
1831}
1832
1833@Test func headOnFoldIsReportedDegenerate() throws {
1834    #expect(try mappingForFoldTowardTheCamera().isDegenerate)
1835}
1836
1837@Test func degenerateMappingFallsBackToVerticalDrag() throws {
1838    let m = try mappingForFoldTowardTheCamera()
1839    #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 50), current: 0) > 0.1)
1840}
1841
1842@Test func theMappingIsNeverInfinitelySensitive() throws {
1843    let m = try mappingForFoldTowardTheCamera()
1844    #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2)
1845}
1846
1847@Test func aNonRigidStepIsDraggedPhaseByPhase() throws {
1848    // following the path's own samples in order reaches t = 1 without ever going back
1849    let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1],
1850                                     camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
1851                                     viewportSize: SIMD2(800, 600))
1852    var t = 0.0
1853    for p in m.path.dropFirst() {
1854        let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
1855        #expect(next >= t - 1e-9)
1856        t = next
1857    }
1858    #expect(t > 0.99)
1859}
1860
1861@Test func foldAndUnfoldGoesOutThenBack() throws {
1862    let m = try mapping("quarters.fold", step: 1)
1863    let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0)
1864    #expect(abs(atPeak - 0.5) < 0.01)
1865    let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak)
1866    #expect(back > 0.99)
1867}
1868```
1869
1870`App/UITests/FoldGestureTests.swift`:
1871
1872```swift
1873func testCompletingAStepAdvancesToTheNext() {
1874    let app = XCUIApplication(); app.launch()
1875    app.buttons["Cup"].tap()
1876    completeCurrentFold(app)   // drag along the moving facet's path to t = 1, then lift
1877    XCTAssertEqual(app.staticTexts["step.index"].label, "2")
1878}
1879
1880func testReleasingPartwayLeavesTheStepWhereItIs() {
1881    let app = XCUIApplication(); app.launch()
1882    app.buttons["Cup"].tap()
1883    dragCurrentFold(app, to: 0.5)
1884    let released = app.otherElements["fold.paper"].value as? String
1885    sleep(2)
1886    XCTAssertEqual(app.staticTexts["step.index"].label, "1")
1887    XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released)
1888    XCTAssertNotEqual(released, "0%")
1889}
1890```
1891
1892The paper view's accessibility value is the fold parameter as a percentage.
1893
1894- [ ] **Step 2: Run tests to verify they fail**
1895
1896Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`
1897Expected: FAIL.
1898
1899- [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`**
1900
1901The step completes when the parameter is 1 and the finger lifts; the release position counts as the finger's last position. Releasing below 1 leaves the paper where it is. Screen points are UIKit's (origin top-left, y down); the degenerate fallback advances with a downward drag. The path is projected at the camera target's depth rather than with per-point perspective, because under perspective a flap landing flat overshoots its end on screen; a 0.5-point end tolerance applies along the path, never across it. Segment boundaries are every axis window's ends, each fold-and-unfold's peak and each non-rigid phase's end; each segment follows an axis that moves throughout it, falls back to the vertical drag when its own path is under 8 points, and is one way. Under the launch argument `-UITesting` the app exposes the path as a hidden element `fold.path` for the UI tests' drag helpers; nothing of that is active otherwise.
1902
1903- [ ] **Step 4: Run tests to verify they pass**
1904
1905Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/FoldGestureTests`
1906Expected: PASS.
1907
1908- [ ] **Step 5: Commit**
1909
1910```bash
1911git add App Packages
1912git commit -m "Fold gesture tracking the moving facet's screen path"
1913```
1914
1915---
1916
1917### Task 13: The drag for turn-over and rotate steps
1918
1919**Files:**
1920- Create: `App/Sources/ReorientGesture.swift`
1921- Test: `App/UITests/ReorientGestureTests.swift`
1922
1923**Interfaces:**
1924- Consumes: `FoldStep.kind`, `FoldInterpolator.positions(at:)`.
1925- Produces:
1926  - `struct ReorientGesture` — a one-finger horizontal drag across the model drives `t` of a `turnOver` or `rotate` step as the drag's horizontal distance over the model's on-screen width, clamped to 0...1
1927
1928A `turnOver` has no crease and no fold angle, so the fold drag has nothing to drive — and every one of the v1 models needs turn-overs, the crane most of all. The model reorients, not the camera: the diagram's viewpoint is fixed and the reader's mental model is of turning the paper over in their hands. The parameter follows the finger like a fold does; a flick does not complete the step, because the app never advances `t` on its own.
1929
1930- [ ] **Step 1: Write the failing tests**
1931
1932```swift
1933func testDraggingAcrossTheModelCompletesATurnOverStep() {
1934    let app = XCUIApplication(); app.launch()
1935    app.buttons["Cup"].tap()
1936    advanceToFirstTurnOverStep(app)
1937    let before = app.staticTexts["step.index"].label
1938    dragAcross(app.otherElements["fold.paper"])
1939    XCTAssertNotEqual(before, app.staticTexts["step.index"].label)
1940}
1941
1942func testFoldDragDoesNothingOnATurnOverStep() {
1943    // a fold drag on a turnOver step must leave step.index unchanged
1944}
1945
1946func testReorientDragDoesNothingOnAFoldStep() {
1947    // a horizontal drag that does not follow the fold path must leave step.index unchanged
1948}
1949
1950func testTurnOverReorientsTheModelNotTheCamera() {
1951    // midway through the turn-over drag the diagram is unchanged; after it, the paper
1952    // shows its back colour
1953}
1954```
1955
1956- [ ] **Step 2: Run tests to verify they fail**
1957
1958Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/ReorientGestureTests`
1959Expected: FAIL.
1960
1961- [ ] **Step 3: Implement `ReorientGesture`**
1962
1963Gate the gesture on the current step's `kind`, so a fold drag and a reorient drag are never both live. A rightward drag advances and a leftward drag turns back; the width is frame n − 1's projected extent at the grab. The UI test checks the diagram and the camera (exposed under `-UITesting` as `paper.camera`) after a partial lift, since XCUITest's drag returns only on lift.
1964
1965- [ ] **Step 4: Run tests to verify they pass**
1966
1967Run: as above.
1968Expected: PASS.
1969
1970- [ ] **Step 5: Commit**
1971
1972```bash
1973git add App
1974git commit -m "Drag gesture for turn-over and rotate steps"
1975```
1976
1977---
1978
1979### Task 14: Orbit, zoom, accessibility and release assets
1980
1981**Files:**
1982- Create: `App/Sources/OrbitGesture.swift`
1983- Create: `App/Resources/PrivacyInfo.xcprivacy`
1984- Create: `App/UITests/AccessibilityAuditTests.swift`
1985- Create: `AppStore/rights-basis.md`
1986- Create: `scripts/take-screenshots.sh`
1987
1988**Interfaces:**
1989- Consumes: `Camera`, `PaperView`, `FoldStep.instruction`.
1990- Produces:
1991  - `struct OrbitGesture` — two-finger drag to `Camera` orbit, pinch to field of view
1992
1993`Camera.viewProjection` builds its basis from `cross(viewDirection, up)`, which is undefined when `up` is parallel to the view direction; `OrbitGesture` keeps `up` perpendicular to the view direction as it orbits, including past the poles.
1994
1995A folding model cannot be described by a static label, so the paper view's accessibility label is the step's authored `instruction`. `AppStore/rights-basis.md` records that every shipped model is traditional and why that matters.
1996
1997- [ ] **Step 1: Write the failing tests**
1998
1999```swift
2000func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws {
2001    let app = XCUIApplication(); app.launch()
2002    try app.performAccessibilityAudit()
2003    app.buttons["Cup"].tap()
2004    try app.performAccessibilityAudit()
2005}
2006
2007func testEveryScreenPassesTheAuditAtTheLargestTextSize() throws {
2008    let app = XCUIApplication()
2009    app.launchArguments += ["-UIPreferredContentSizeCategoryName",
2010                            "UICTContentSizeCategoryAccessibilityXXXL"]
2011    app.launch()
2012    try app.performAccessibilityAudit()
2013    app.buttons["Cup"].tap()
2014    try app.performAccessibilityAudit()
2015}
2016
2017func testPaperViewDescribesTheCurrentStepInWords() {
2018    let app = XCUIApplication(); app.launch()
2019    app.buttons["Cup"].tap()
2020    XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold"))
2021}
2022
2023func testTwoFingerDragOrbitsWithoutAdvancingTheFold() {
2024    let app = XCUIApplication(); app.launch()
2025    app.buttons["Cup"].tap()
2026    let paper = app.otherElements["fold.paper"]
2027    let before = paper.value as? String
2028    twoFingerDrag(paper)
2029    XCTAssertEqual(app.staticTexts["step.index"].label, "1")
2030    XCTAssertEqual(paper.value as? String, before)
2031}
2032
2033func testDiagramDoesNotRotateWhenTheModelIsOrbited() {
2034    let app = XCUIApplication(); app.launch()
2035    app.buttons["Cup"].tap()
2036    let diagram = app.otherElements["diagram"].screenshot().pngRepresentation
2037    twoFingerDrag(app.otherElements["fold.paper"])
2038    XCTAssertEqual(app.otherElements["diagram"].screenshot().pngRepresentation, diagram)
2039}
2040```
2041
2042- [ ] **Step 2: Run tests to verify they fail**
2043
2044Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test -only-testing:FoldUITests/AccessibilityAuditTests`
2045Expected: FAIL.
2046
2047- [ ] **Step 3: Implement `OrbitGesture`, the accessibility labels, the privacy manifest, the rights note and the screenshot script**
2048
2049`take-screenshots.sh` follows `krz/daybyday/scripts/take-screenshots.sh`. `PrivacyInfo.xcprivacy` declares no tracking and no collected data. XCUITest cannot make a two-finger pan, so the orbit and zoom maths are `Camera.orbited(by:)` and `Camera.zoomed(by:within:)` in Folding, unit-tested through the poles, and the UI tests use pinch and rotate. A pan or pinch that begins during a one-finger drag suspends the drag and restores its starting *t*. The paper view has a VoiceOver adjustable action that moves *t* by tenths; reaching 100% completes the step as a lift does.
2050
2051- [ ] **Step 4: Run tests to verify they pass**
2052
2053Run: as above.
2054Expected: PASS.
2055
2056- [ ] **Step 5: Commit**
2057
2058```bash
2059git add App scripts AppStore
2060git commit -m "Orbit and zoom, accessibility pass and release assets"
2061```
2062
2063---
2064
2065### Task 14b: The step list and dragging back
2066
2067**Files:**
2068- Create: `App/Sources/StepListView.swift`
2069- Modify: `App/Sources/StepView.swift`, `App/Sources/FoldSession.swift`
2070- Modify: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift`
2071- Test: `App/UITests/StepListTests.swift`, `App/Tests/FoldSessionTests.swift`, `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift`, `App/UITests/AccessibilityAuditTests.swift`
2072
2073**Interfaces:**
2074- Consumes: Tasks 11–14.
2075- Produces:
2076  - `struct StepListView: View` — every step's number and `instruction`, the current one marked
2077  - `func (FoldSession).open(step: Int)` — step counted from 1; loads that step at *t* = 0 with the camera at its viewpoint, as completing the step before it does
2078
2079**The step list.** A toolbar button (`steps.button`, label "Steps") opens the list on demand: a popover on iPad, a sheet on iPhone. The navigation title reads "Step n of N"; `step.index` stays the bare number. Choosing a step opens it at its start, frame n − 1, whatever was folded before; choosing the current step closes the list and leaves *t* alone. Nothing about the list advances *t*.
2080
2081**Dragging back.** A step's segments — axis windows and non-rigid phases — are crossed in both directions: the search runs outward from `current` across segment boundaries, so dragging the flap back takes *t* back through earlier windows and phases to 0. Where the path doubles back on screen at a boundary (a non-rigid step's open and pop), the segment *t* is in is kept until the finger leaves the overlap, so a finger moving along the retraced stretch neither jumps ahead nor falls back. The 0.5-point end tolerance applies at *t* = 1 only. A `foldAndUnfold` stays one way at its peak: its return half passes through the same poses as its outbound half, so dragging back after the peak is the unfold.
2082
2083- [ ] **Step 1: Write the failing tests**
2084
2085```swift
2086// FoldParameterTests
2087@Test func aStaggeredStepCanBeDraggedBackPastItsWindowBoundary() throws {
2088    // follow letter-staggered's samples to t = 0.75, then back to 0: t tracks k/128 both ways
2089}
2090
2091@Test func aNonRigidStepCanBeDraggedBackThroughItsPhases() throws {
2092    // follow the reverse fixture's samples to t = 1, then back: t never increases, and ends below 0.01
2093}
2094
2095@Test func aFoldAndUnfoldStillUnfoldsAfterItsPeak() throws {
2096    // quarters step 1: past 0.5, dragging back toward the start goes to 1
2097}
2098```
2099
2100```swift
2101// StepListTests
2102func testTheStepListOpensAChosenStepAtItsStart() {
2103    let app = XCUIApplication(); app.launch()
2104    app.buttons["Cup"].tap()
2105    app.buttons["steps.button"].tap()
2106    app.buttons["step.5"].tap()
2107    XCTAssertEqual(app.staticTexts["step.index"].label, "5")
2108    XCTAssertEqual(app.otherElements["fold.paper"].value as? String, "0%")
2109}
2110
2111func testTheStepListNamesEveryStep() {
2112    // six rows for the cup, each labelled with its number and instruction
2113}
2114```
2115
2116`FoldSessionTests` covers `open(step:)` (the camera resets, *t* is 0, the diagram is step n's) and choosing the current step. The accessibility audit opens the list at both text sizes.
2117
2118- [ ] **Step 2: Run tests to verify they fail**
2119
2120Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`
2121Expected: FAIL.
2122
2123- [ ] **Step 3: Implement the step list, `open(step:)` and two-way segments**
2124
2125- [ ] **Step 4: Run tests to verify they pass**
2126
2127Run: as above, then `-only-testing:FoldUITests/FoldGestureTests -test-iterations 100`.
2128Expected: PASS.
2129
2130- [ ] **Step 5: Commit**
2131
2132```bash
2133git add App Packages
2134git commit -m "Step list and dragging back across segments"
2135```
2136
2137---
2138
2139### Task 15: The crane, the sampan and the box
2140
2141**Files:**
2142- Create: `Models/crane.foldscript`, `Models/crane-cp.fold`
2143- Create: `Models/sampan.foldscript`, `Models/sampan-cp.fold`
2144- Create: `Models/box.foldscript`, `Models/box-cp.fold`
2145- Create: `Packages/FoldKit/Sources/Models/Resources/{crane,sampan,box}.fold`
2146- Create: `docs/authoring/{crane,sampan,box}.md`
2147- Modify: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` — delete `theCatalogueContainsTheCup`; `theCatalogueContainsFourModels` below replaces it
2148- Modify: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` — golden images for every step of the three new models
2149- Test: `Packages/FoldKit/Tests/ModelsTests/FourModelTests.swift`
2150
2151**Interfaces:**
2152- Consumes: everything from Tasks 0–14. No new API.
2153
2154Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source.
2155
2156Carried from batch D, to settle before or while authoring these models: a crease on a named crease's line through another layer with a scripted angle other than ±180 is rejected (the masu's 90° walls need its angle derived instead); `curveTooCoarse` is reported where an unreachable scripted angle is the real cause; the cycle computation has no test for several loops sharing axes (the petal fold); `compilePop` does not assert that held faces sit identically in the open pose and `popped`; a flap whose two layers also join through the body (the crane's neck and tail) fails with `noRigidMotion`, because the opening faces are found by cutting only the spine — rule on "that side of the spine" then; `structurallyEqual` must tolerate solver noise in `pop`. From batch E: Notation styles an edge between faces of two sibling axes, or between a carried axis's face and a fixed face, by one axis's turn — check the petal fold's golden for segments of one crease drawn in different styles; a step that unfolds a crease folded in frame n − 1 is drawn as a fold, with no unfold notation — decide it when the crane's petal fold and the sampan need it; occlusion's `cover` assumes faces are not edge-on in the view, which the masu's raised walls may break (R35's revisit).
2157
2158Task 15 ships in two merge requests. The box ships first (batch G). The crane's inside reverse folds have no rigid opening on the real crane — the opening side spans the spine — and the traditional long-form sampan's turn inside out has no rigid motion and no spine; decision 0003 measured bending the opening and found it does not work with the body held; both models ship together after it (batch G2). Decision 0003: a reverse fold opens rigidly — the whole near side turns about the spine's line, with bend lines (edges on that line through the faces crossing it, `F` in every frame, never creased) — the head opens nested on the body's spine (`openOn`), the pop is the banded slerp at a default of 20° from flat, and the render mesh is a Delaunay triangulation. During a pop, faces inside one near-coplanar cluster are left to the layer order (the author's choice), and the two halves' coincident vertices on the spine line are solved as one. The sampan ships in its short form, an open tray with flat ends; the long form with covered ends has no rigid end state as scripted and is a known gap. Shipped `.fold` files come from debug `swift run foldc`; a release build can differ by up to 9e-7° on steps solved by the loop solver's null-space step. The crane's preliminary-base collapse needs `foldc`'s loop solver to steer the free directions of a degree-6 vertex toward the linear angles, and its narrowed legs need the spine gathered only where it separates the two sides.
2159
2160The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault.
2161
2162Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps are coupled (solved curves, decision 0001) and which are flagged non-rigid with their `openAngle` and measured pop strain (decision 0002), and that the model regenerates from its script.
2163
2164- [ ] **Step 1: Write the failing tests**
2165
2166```swift
2167@Test func theCatalogueContainsFourModels() throws {
2168    #expect(try Set(ModelLibrary.names()) == ["cup", "crane", "sampan", "box"])
2169}
2170
2171@Test func theCraneContainsAMultiAxisStep() throws {
2172    #expect(try readSteps(ModelLibrary.model(named: "crane")).contains { $0.axes.count > 1 })
2173}
2174
2175@Test func theCraneStacksAtLeastEightLayersSomewhere() throws {
2176    let crane = try ModelLibrary.model(named: "crane")
2177    let deepest = (0...crane.stepCount).map {
2178        stackDepth(positions: crane.frames[$0].verticesCoords, faces: crane.facesVertices)
2179    }.max() ?? 0
2180    #expect(deepest >= 8)
2181}
2182
2183@Test func everyModelWithOverlappingMovingSetsCarriesAMidFoldOrder() throws {
2184    for file in try ModelLibrary.all() {
2185        for n in 1...file.stepCount where movingSetsOverlapInProjection(step: n, file) {
2186            #expect(file.frames[n].faceOrdersMidFold != nil, "\(file.fileTitle ?? "?") step \(n)")
2187        }
2188    }
2189}
2190
2191@Test func onlyTheCranesReverseFoldsAreFlagged() throws {
2192    // decision 0002: the neck, tail and head reverse folds; nothing else, unless the
2193    // sampan's or the masu's last step was flagged by a later decision
2194    let crane = try readSteps(ModelLibrary.model(named: "crane"))
2195    #expect(crane.filter(\.nonRigid).count == 3)
2196    #expect(crane.filter(\.nonRigid).allSatisfy { $0.technique == .insideReverse })
2197    for name in ["cup", "box", "sampan"] {
2198        #expect(try readSteps(ModelLibrary.model(named: name)).allSatisfy { !$0.nonRigid }, "\(name)")
2199    }
2200}
2201
2202@Test func everyModelHasAnAuthoringRecord() throws {
2203    for name in try ModelLibrary.names() {
2204        #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path))
2205    }
2206}
2207```
2208
2209The catalogue tests from Task 8 — validation, step reading, isometry, interpenetration, traditional attribution, regeneration from script — now run over four models instead of one and must stay green.
2210
2211- [ ] **Step 2: Run tests to verify they fail**
2212
2213Run: `swift test --package-path Packages/FoldKit --filter ModelsTests`
2214Expected: FAIL — only the cup is in the catalogue.
2215
2216- [ ] **Step 3: Author the three models**
2217
2218Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified when authored (decision 0002). The classification uses `foldc`'s closure test, the interpenetration check, the validator's layer rules and a look in the app; closure alone can succeed on a branch with the wrong layering. Classify the crane's preliminary base the same way: fold and unfold its diagonals and midlines, then collapse it as one step from the pre-creased square, rather than through squash folds, which have the reverse fold's structure. A step that closes is rigid. One that does not, and is not a reverse fold or sink, stops compilation with `noRigidMotion`. Then stop and ask the author: open, pop, close needs a spine to open on, and an inversion has none. The crane's petal folds are rigid with solved curves (decision 0002, case 7). Its inside reverse folds (neck, tail, head) name their `spine` and use open, pop, close at the default 20° (decision 0003); if one exceeds the 10% bound, its `openAngle` is lowered in the script and the record says why. The bound was measured on a two-layer flap only; the crane's flaps are narrower and several layers deep, so record each flagged step's measured strain, and if opening a flap to its `openAngle` disturbs earlier layers or no `openAngle` meets the bound, stop for a decision. The bird base's crease pattern is the one decision 0002 read from Origami Simulator's flat crane; record that provenance in `docs/authoring/crane.md`. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly.
2219
2220- [ ] **Step 4: Run tests to verify they pass**
2221
2222Run: `swift test --package-path Packages/FoldKit --filter ModelsTests`
2223Expected: PASS.
2224
2225- [ ] **Step 5: Commit**
2226
2227```bash
2228git add Models Packages/FoldKit docs/authoring
2229git commit -m "The crane, the sampan and the box"
2230```
2231
2232---
2233
2234## Open before Task 15
2235
2236- **Multi-axis steps in the app.** The fold drag's path joins each segment's followed centroid end to end, so on a multi-axis step it can leave the paper view; a short window nested inside a long one falls back to a vertical drag while the paper moves; non-rigid steps follow the axis with the most travel per phase, untested until one ships. Check all three on the crane. The catalogue gate exercises `FoldParameterMapping` on every step but not `ReorientMapping`.
2237- On device: the fold drag's 0.5-point end tolerance is about 14° on the cup's shortest iPhone paths; check it against "the last 10° completes itself". Check that a late second finger orbits rather than folds. Measure the session and mapping build times on the crane.
2238
2239## After the plan
2240
2241The plan delivers v1 complete: the engine, the compiler, the notation, the renderer, the app and four traditional models. Growing the catalogue needs no further engineering — the frog base, fish base, flapping bird and preliminary base are each a crease pattern, a script and a correction pass, gated by machinery that already exists.
2242
2243What would need new engineering: designed models, which is a permissions project before it is a code one; curved creases and wet folding, which break the rigid-flat-facet premise the whole engine rests on; and deriving layer order rather than authoring it, which is the one place this design knowingly trades authoring effort for runtime correctness and should stay that way.