# Direct Edit Solver And API ## 1. Scope / Trigger This contract covers the pure direct-edit resolver and the workbench endpoints that preview, persist, checkpoint, and rebase `native-road-edits/v2` documents. It is required because the feature crosses compiler, storage, and HTTP layers. ## 2. Signatures ```js resolveDirectEditConstraints(model, editDocument, context) // -> { roadProfiles, junctionPlans, clusterPlans, constraintStates, handles, diagnostics } GET /api/edit-state POST /api/edit-preview POST /api/edits POST /api/revisions POST /api/revisions/:id/rebase ``` ## 3. Contracts - The resolver is deterministic and must not import `fs`, `path`, `http`, or write files. It accepts a baseline model, an optional validated v2 document, and `{ revisionId, compilerGeometryVersion, previewSeq }` context. - `GET /api/edit-state` returns the active document, `documentVersion`, active revision, constraint states, diagnostics, and `road-edit-handles/v1` manifest. - `POST /api/edit-preview` accepts `document` (or replacement `constraints` and `operations`) and optional integer `previewSeq`. It returns the same manifest/state data plus compiled layers, echoes `previewSeq`, and never changes active files. Work over the 300ms budget sets `degraded: true`. - `POST /api/edits` requires integer `expectedDocumentVersion` and either a complete `document` or replacement arrays. Saves through a staging file and rename, increments `documentVersion`, and returns the active revision. - A version mismatch returns HTTP 409 with `{ ok: false, error, current }` and leaves the active document byte-identical. - `POST /api/revisions` requires a non-empty `label`; it creates an immutable checkpoint and returns its manifest plus current edit state. - `POST /api/revisions/:id/rebase` is read-only and returns status counts plus per-constraint details. `pending`, `conflicted`, and `stale` constraints do not enter geometry solving. - A resolved constraint whose saved numeric value no longer fits the current geometry range is returned as `stale` with reason `range-out-of-bounds`. A missing replay anchor uses reason `anchor-missing`; callers must not infer the stale cause from the status alone. ## 4. Validation & Error Matrix | Condition | Required behavior | | --- | --- | | Missing or invalid v2 document fields | Reject with a field-specific 400 error | | Missing `expectedDocumentVersion` | Reject with 400; do not write | | Expected version differs from active version | Return 409 and current version; do not write | | Empty checkpoint label | Reject with 400; no revision is created | | Missing active workspace for preview | Reject with 400; no files are created | | Solver replay anchor cannot resolve | Mark `stale` or `conflicted` with diagnostic; never silently apply | | Compiler geometry version differs | Mark all replayable constraints `recheck` without changing values | | Invariant violation (lane width, crossing boundaries, self-intersection, connector bounds) | Return a blocking diagnostic; do not clamp or silently repair | | Constraint value outside the current handle range | Return a blocking diagnostic; do not clamp or silently repair | ## 5. Good / Base / Bad Cases - Good: preview the same document later saved with the same active baseline; compiled layers and solver diagnostics agree, while tracked file bytes and mtimes remain unchanged. - Base: an empty v2 document yields byte-for-byte baseline geometry and an empty constraint-state list. - Bad: two tabs save version `N`; the second save with `N` receives 409 and cannot overwrite the first tab's document. ## 6. Tests Required - Unit: resolver purity, empty-document identity, five replay statuses, handle manifest fields, and blocking invariant diagnostics. - Integration: preview file bytes/mtimes unchanged, `previewSeq` echoed, preview layers matching formal compilation, and `degraded` represented as a boolean. - Persistence: atomic save, version-409 no-write path, checkpoint parent and digest integrity, and rebase counts/details. ## 7. Wrong vs Correct ### Wrong ```js fs.writeFileSync(activeEdits, JSON.stringify(draft)); ``` This permits half-written documents and allows a stale browser tab to overwrite newer edits. ### Correct ```js if (expectedDocumentVersion !== current.documentVersion) throw conflict409(); saveEditDocument(activeEdits, { ...draft, documentVersion: current.documentVersion }); ``` The service checks the version before the atomic version-bumping write, while the pure resolver remains reusable by preview and formal compilation. ## 8. Left and right `left` is `heading - 90`. Three places agree and must keep agreeing: - `offsetLine()` (`native-road.js`) offsets a positive value counter-clockwise from the direction of travel, i.e. toward geographic left. - `centerlineShift = (edgeOffsets.left - edgeOffsets.right) / 2`, so widening the left edge moves the centerline left. - Sidewalks use `heading + (side === 'left' ? -90 : 90)`. The handle manifest reports `axisAzimuth = tangent + 90` for both sides, which is therefore *right*. Handle placement must offset the left handle by `tangent - 90`. Complex carriageway edge handles use the same convention, but their position is the effective inner entry section rather than the legacy cutback point: ```text innerStation = outerStation - transitionLength + positionOffset edgeDistance = effectiveWidth / 2 + sideEdgeOffset ``` Compute the tangent at `innerStation`, then apply `directionOffsetDegrees` before placing the left and right handles. This keeps the manifest aligned with `JunctionBoundaryGraph` after transition, position, direction, width, or edge edits. Tests must measure that the two handles are geographically opposite and their separation equals `effectiveWidth + leftOffset + rightOffset` within the geometry tolerance; checking only stored scalar values does not prove placement. **Regression**: `makeRoadHandles()` once placed the left handle at `tangent + 90`, drawing it over the right kerb, so dragging the visually-left handle moved the right edge. Assert sides by geography (a north-heading road's left handle is west of its centerline), never by axis sign — a sign convention can be wrong on both sides of the wire at once and still look self-consistent. ## 9. What the geometry stage actually reads `compileGeometry()` honours only four profile fields: | Field | Read at | | --- | --- | | `edgeOffsets.left/right` | `native-road.js` centerline shift | | `widthMeters` | road width | | `sidewalkWidths.left/right` | `sidewalkRing()` | | `laneDividerOffsets` | lane separator placement | `profile.interval` and `profile.transitions` are written by the solver and read by nothing: every direct edit currently applies to the whole road. Do not add UI for interval-scoped editing until that changes — see `research/interval-not-applied.md` in the map-editor task. ## 10. Saving is not applying `POST /api/edits` writes the v2 document only. `/api/state` serves the outputs of the last compile, so a save without a recompile leaves a refresh showing pre-edit geometry — indistinguishable from a failed save. `compileInput()` is the only caller that passes `editsFile`, and `session.context.compileFresh` must be installed by **every** path that sets `session.area`, including `/api/import`. It was originally wired only when the server started with an area on the command line, so every UI-imported session answered `请先导入 OSM 文件` to `/api/compile`. An identity test cannot catch a `editsFile` regression: an ignored document and an empty one produce identical output. Assert that a **non-empty** document changes the compiled output. Wiring gaps between two handlers need an HTTP-level test, and a regression test is only trustworthy once you have watched it fail without the fix. --- ## 11. One segment, two directional roads, two junctions A segment's forward and backward roads can both reach the same junction while serving different objects. Anything that resolves "the thing at this approach" by taking the first match will therefore publish one road's answer on the other's handle. Measured: 15 of 23 segments carried two `junction-crosswalk-inset` handles, and one segment carried two crosswalk groups. The discriminator is the road whose **last source node** is this junction — `road.sourceNodeIds.at(-1)` — which is the rule `crossingJunctionInset()` already applies to find its junction plan: ```js // WRONG — whichever direction comes first in `items` wins const crossing = approach.items.map((i) => crossingByRoadId.get(i.road.id)).find(Boolean); // RIGHT — the road that actually ends here const crossing = approach.items .filter((i) => String(i.road.sourceNodeIds?.at(-1)) === String(nodeId)) .map((i) => crossingByRoadId.get(i.road.id)) .find(Boolean); ``` **Mistake made, twice in one session**: once on the client picking a handle for a selected element, once in the solver computing that handle's bound. Both produced plausible values on the wrong object, which no type check and no smoke test catches — only asserting against a segment that genuinely has two. --- ## 12. A handle's range is part of its contract `value.min` / `value.max` say "drag here and something happens". Each kind currently derives them independently, and every one measured was wrong in a different direction: | kind | declared | measured | failure | | --- | --- | --- | --- | | `road-edge-offset` | ±2.925 | rejected past ~±1 | blocking diagnostic mid-drag | | `junction-crosswalk-inset` | 0–8 | inert past 1.0–4.5 | **silent**, 44–88% dead | | `junction-stop-line-offset` | 0.5–126.28 | fully linear | no meaningful ceiling at all | The silent case is the worst: a drag that does nothing is indistinguishable from a broken control, and it is what `flag.ts` blocks whole features for. Rules: - Derive the ceiling from the geometry that consumes the value, not from a constant. `effectiveCrosswalkInsetMax()` is the worked example: read where the consuming function saturates and solve for it. - Never publish a `max` below the current value — a manifest that contradicts itself. Equal is fine and honest: it says there is no headroom. - A range wide enough to produce nonsense (a stop line 126m from its junction) is as much a defect as one that is dead. ## 13. Complex junction shape summary ### 1. Scope / Trigger Complex-junction compilation publishes a structural classification which the JunctionTools page displays. This crosses the compiler, the persisted GeoJSON layer, `/api/state`, and the typed browser state. ### 2. Signatures ```js GET /api/state?debug=1 // debug.junctionShapes?: Array<{ // clusterId: string, kind: string, label: string, // armCount: number, throughPairCount: number // }> ``` ### 3. Contracts - `complex-core` is published in `layers/road_surface.geojson`, not `intersection_surface.geojson`. - Its `shape_kind`, `shape_label`, `arm_count`, and `through_pair_count` properties are the compiler authority. The service must project them without reclassifying from node count. - `debug.junctionShapes` is present only for debug state. An absent matching entry means the client shows its ordinary cluster context, not an invented shape. ### 4. Validation & Error Matrix | Condition | Required behavior | | --- | --- | | No complex core for a configured cluster | Omit its summary; do not emit a false shape | | Shape is unsupported | Compiler emits a normal-junction fallback diagnostic and no `complex-core` | | GeoJSON properties are missing | Use `unsupported` and the readable fallback label only while projecting an existing core | ### 5. Good / Base / Bad Cases - Good: a five-node cluster with five external arms returns `5 臂非规则路口`. - Base: debug is off, so no shape summaries are returned. - Bad: reading `intersection_surface.geojson` returns no complex cores and makes the UI falsely appear to lack classification. ### 6. Tests Required - Compiler: assert `complex-core` has the expected shape kind and arm count for a real OSM cluster. - Service/UI: assert debug state reads the road-surface core and the workspace renders the received label without node-count inference. ### 7. Wrong vs Correct ```js // Wrong: complex cores are not stored in this layer. readLayer('layers/intersection_surface.geojson') // Correct: project compiler-owned properties from their published layer. readLayer('layers/road_surface.geojson') ``` ## 14. Junction structure and standards profile Stage-0 JunctionTools structure is compiler-owned and versioned independently of the direct-edit document. `buildJunctionStructure(input)` must return `junction-structure/v1` with unique stable object keys, readable labels, and explicit arm/corner/facility references; it must reject duplicate keys, unknown references, and an effective arm count that differs from the supplied arms. It must not infer missing arms from an internal `2x1`/`2x2` layout. `CN_URBAN_DEFAULT_PROFILE` is the immutable `cn-urban-default` profile. Use `cloneProfile()` before applying project-specific changes and `validateStandardsProfile()` at the boundary. Rules distinguish recommended, warning, and blocking/invariant fields; a profile is metadata and rule configuration, not a client-side save decision. Keep the compiler as the sole producer of structure and diagnostics so the client cannot reclassify a junction from node counts. ## 15. Save-time geometry validation `saveEdits()` must run the same `resolveDirectEditConstraints()` used by `editPreview()` after validating the candidate document and before writing it. Any diagnostic with `severity: 'error'` returns HTTP 400 and leaves the active document byte-identical; warnings remain saveable. This prevents a client from skipping preview and persisting a width, corner radius, crossing offset, or stop-line value that the compiler rejects. Version conflicts are checked first and continue to return HTTP 409 without invoking geometry validation writes. ## 16. Scoped complex junction identity ### Scope and signatures Stage 1 establishes the read model consumed by later cluster editing. Use `resolveComplexJunctionTopology(model, cluster, helpers)` in complex geometry, then `structureFromTopology(topology, shape, center, features)`. Projection is `projectJunctionStructure({ model, layers, trafficSignals, junctionRef })`. ### Contracts - `junctionRef` is `{ type: 'node' | 'cluster', id }`. Explicit `null` means no junction projection; unknown references return `null`, never the first core. - `GET /api/state` returns `junctionStructures`, keyed by `node:` and `cluster:`. The legacy singular field is null at this unscoped entry point. - `GET /api/edit-state?junction=` preserves the node selection contract; `?cluster=` selects a cluster. Preview uses the equivalent `selection` object. A selected editable cluster publishes its external carriageway, corner, and stop-line handles. It publishes `cluster-crossing-inset` only for an arm with a matching OSM crossing node. - A cluster carriageway anchor contains `clusterId`, stable `carriagewayKey`, `sourceNodeIds`, and `sourceRoadIds`. Replay matches all source identity; a missing or changed source is stale with `anchor-missing`. The solver stores width and cutback values separately, and `compileGeometry()` applies them only to the matching complex-junction approach before geometry is generated. - A cluster corner anchor contains its stable adjacent-arm `cornerKey` and the two representative carriageway keys. It is replayed against the same source-sorted arm grouping used by `resolveComplexJunctionTopology()`. The complex generator reads a local radius by that `cornerKey`; no other corner is rewritten. - A cluster crossing anchor contains `clusterId`, stable `crossingKey` (`crossing:`), and its source-backed carriageway keys. Crosswalk inset is in `0..8` m; stop-line offset is in `0.5..12` m. Replay resolves the same arm grouping and marks a missing arm `stale/anchor-missing`. Generated crosswalk stripes and stop lines publish that `crossing_key`; the generator applies the inset once per stripe group and positions each incoming stop line relative to its matching crossing. Never identify these facilities by `crossing_node_id`, because complex members can share a node. - A road envelope or inferred stop line is not crossing evidence. Without a matching source crossing node, compilation emits no complex crosswalk, publishes no crossing-inset handle, records facility evidence as `unknown-no-crossing-source`, and emits `complex-junction-crossing-source-missing`. A stop line may remain as an independent inferred facility; its position must not consume a nonexistent crossing inset. - Source matching uses the same inferred arm radius in handle publication and constraint solving. A published handle must remain applicable at every advertised value, including `value.max`. - Preview and save both evaluate the same candidate through the resolver and `compileGeometry()`. Save rejects every `severity: error` diagnostic before writing the edit document. - Complex road-surface features carry `junction_key`, `object_key` and relevant `arm_key`, `carriageway_key`, `corner_key`. Core (or the first remaining approach when the core fails) carries `junction_structure` for persisted reads. - A supported complex core publishes measurable region evidence: `connected_entry_count`, `required_pavement_connected`, `core_ring_area`, `core_ring_self_intersects`, and the existing shared-seam metrics. A contained exclusion hole is valid only when it preserves every required entry seam. - Stable keys derive from cluster and sorted source node/segment/road IDs, with corner keys derived from adjacent arms. Display indices and headings are not object identities. `topologyFingerprint` detects source topology changes. - Root provenance lists member nodes and external road/segment IDs. Arms point to carriageways, corners to arms, facilities to feature IDs; normalizers must preserve these fields and readonly capabilities across JSON round trips. - Signal projection joins exact member `node_id` / `control_id`, retaining the existing `signal_uid` as `geometryRef` and `provenance.featureIds`. It does not rewrite the separately persisted signal document or guess from UID substrings. ### Validation matrix | Input | Result | | --- | --- | | Multiple selection keys or repeated query keys | 400, no implicit priority | | Empty/object-valued ID | 400 | | Unknown node/cluster or missing compiled complex structure | null structure, empty diagnostics | | Missing/ambiguous object source | readonly capability with reason | | Explicit cluster selection | empty handles; never all-area or member-node handles | ### Cases and tests Good: reorder member/road arrays and retain semantic IDs; delete a source and change its identity/fingerprint. Base: legacy node editing still works. Bad: opening cluster B while rendering cluster A's first core. Test the 3/4/offset/5+ arm matrix, two-cluster isolation, internal-link exclusion, grouped crossings, scoped signals, JSON round trips, and persisted/preview projection equality. ```js // Wrong: chooses an arbitrary junction and loses the selected scope. projectJunctionStructure({ model, layers }); // Correct for a scoped editor: projectJunctionStructure({ model, layers, trafficSignals, junctionRef: { type: 'cluster', id: selectedClusterId } }); ``` ## Complex carriageway transition length `cluster-carriageway-transition-length` uses the source-checked `cluster-carriageway` anchor and `value.transitionLengthMeters`. Replay verifies source road/node membership before solving. The resolved `clusterTransitions` map is separate from `clusterCutbacks`: the outer source seam is fixed, and the inner station is `outerStation - transitionLengthMeters` along the source polyline. Radial distance differences are not lengths on curved approaches. The maximum is the available outer station; the minimum is the smaller of the configured minimum and the existing source-derived transition (short existing approaches remain representable). Impossible surface geometry still requires compiler validation. A saved transition is never silently clamped. Regression evidence: solver rejects out-of-range/source-mismatched values; API preview measures the requested length and preserves the outer seam; save/read/replay reproduces preview geometry; browser input sends the new kind. ## Complex carriageway direction and edge bounds `cluster-carriageway-direction` remains persisted as `value.offsetDegrees`, including for numeric input and existing documents. Its manifest handle declares `interaction.kind = rotation`, an EPSG:4326 `center` at the effective inner entry section, and `radiusMeters`. Pointer projection is the signed shortest azimuth change around that center; pointer metres must never be interpreted as degrees. The direction ghost follows the declared circle and uses degree units. Position and width handles use the same effective inner entry section as the BoundaryGraph. Direction edits rotate the width axis and both edge handles at that section. The manifest and solver share the carriageway edge range. For one side, with effective width `W`, opposite offset `O`, and minimum lane total `M`, the range is `max(-W/2, M-W-O)..W/2`. Both endpoints are accepted; a value outside the range is rejected with a blocking geometry diagnostic. Independent side constraints and legacy constraints containing both offsets must be evaluated with both effective offsets present. Boundary closure reports `sharedSeamErrors` per carriageway and `maxSharedSeamErrorMeters` as the maximum endpoint distance in local metres between the core ring edge and its BoundaryGraph `inner` edge. Missing or non-contiguous edges remain `Infinity`; the value is not a boolean adjacency placeholder. Explicit transition stations are clamped to the source polyline range for legacy/direct compiler inputs and marked `insufficient-source-length` when the requested length cannot fit. The solver rejects such values before they can be saved. ## Shared complex approach consumers `compileGeometry()` builds each complex approach BoundaryGraph once. External road surfaces, edges, sidewalks, center markings and published lane centerlines read its source-polyline `outer.stationMeters`; do not independently reconstruct `outerRadius - cutback` in a consumer. The complex surface generator receives the same graph instance. Transition lane endpoints interpolate the respective outer and inner section edges, preserving the fixed source width when the inner width changes. Unsupported, invalid or excluded transitions do not publish preview lanes or their derived markings. This contract does not yet replace the separate corner sidewalk overrun geometry or validate all short-road suppression paths.