@floless/app 0.135.1 → 0.137.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -563,14 +563,14 @@ var require_time_tree = __commonJS({
563
563
  * @param {number} start
564
564
  * @returns {TimeTreeNode["id"]}
565
565
  */
566
- [kAddNode](parent, label2, start2) {
566
+ [kAddNode](parent, label, start2) {
567
567
  const parentNode = this[kGetParent](parent);
568
568
  const isRoot = parentNode === null;
569
569
  if (isRoot) {
570
570
  this.root = {
571
571
  parent: null,
572
572
  id: "root",
573
- label: label2,
573
+ label,
574
574
  nodes: [],
575
575
  start: start2,
576
576
  stop: null,
@@ -579,11 +579,11 @@ var require_time_tree = __commonJS({
579
579
  this[kTrackNode](this.root);
580
580
  return this.root.id;
581
581
  }
582
- const nodeId = `${label2}-${Math.random()}`;
582
+ const nodeId = `${label}-${Math.random()}`;
583
583
  const childNode = {
584
584
  parent,
585
585
  id: nodeId,
586
- label: label2,
586
+ label,
587
587
  nodes: [],
588
588
  start: start2,
589
589
  stop: null,
@@ -599,8 +599,8 @@ var require_time_tree = __commonJS({
599
599
  * @param {number|undefined} start
600
600
  * @returns {TimeTreeNode["id"]}
601
601
  */
602
- start(parent, label2, start2 = Date.now()) {
603
- return this[kAddNode](parent, label2, start2);
602
+ start(parent, label, start2 = Date.now()) {
603
+ return this[kAddNode](parent, label, start2);
604
604
  }
605
605
  /**
606
606
  * @param {string} nodeId
@@ -6622,9 +6622,9 @@ var require_levels = __commonJS({
6622
6622
  const formatter = instance[formattersSym].level;
6623
6623
  const { labels } = instance.levels;
6624
6624
  const cache2 = {};
6625
- for (const label2 in labels) {
6626
- const level = formatter(labels[label2], Number(label2));
6627
- cache2[label2] = JSON.stringify(level).slice(0, -1);
6625
+ for (const label in labels) {
6626
+ const level = formatter(labels[label], Number(label));
6627
+ cache2[label] = JSON.stringify(level).slice(0, -1);
6628
6628
  }
6629
6629
  instance[lsCacheSym] = cache2;
6630
6630
  return instance;
@@ -7839,7 +7839,7 @@ var require_pino = __commonJS({
7839
7839
  bindings(bindings) {
7840
7840
  return bindings;
7841
7841
  },
7842
- level(label2, number) {
7842
+ level(label, number) {
7843
7843
  return { level: number };
7844
7844
  }
7845
7845
  }),
@@ -12777,9 +12777,9 @@ var require_codegen = __commonJS({
12777
12777
  }
12778
12778
  };
12779
12779
  var Label = class extends Node {
12780
- constructor(label2) {
12780
+ constructor(label) {
12781
12781
  super();
12782
- this.label = label2;
12782
+ this.label = label;
12783
12783
  this.names = {};
12784
12784
  }
12785
12785
  render({ _n }) {
@@ -12787,14 +12787,14 @@ var require_codegen = __commonJS({
12787
12787
  }
12788
12788
  };
12789
12789
  var Break = class extends Node {
12790
- constructor(label2) {
12790
+ constructor(label) {
12791
12791
  super();
12792
- this.label = label2;
12792
+ this.label = label;
12793
12793
  this.names = {};
12794
12794
  }
12795
12795
  render({ _n }) {
12796
- const label2 = this.label ? ` ${this.label}` : "";
12797
- return `break${label2};` + _n;
12796
+ const label = this.label ? ` ${this.label}` : "";
12797
+ return `break${label};` + _n;
12798
12798
  }
12799
12799
  };
12800
12800
  var Throw = class extends Node {
@@ -13206,12 +13206,12 @@ var require_codegen = __commonJS({
13206
13206
  return this._endBlockNode(For);
13207
13207
  }
13208
13208
  // `label` statement
13209
- label(label2) {
13210
- return this._leafNode(new Label(label2));
13209
+ label(label) {
13210
+ return this._leafNode(new Label(label));
13211
13211
  }
13212
13212
  // `break` statement
13213
- break(label2) {
13214
- return this._leafNode(new Break(label2));
13213
+ break(label) {
13214
+ return this._leafNode(new Break(label));
13215
13215
  }
13216
13216
  // `return` statement
13217
13217
  return(value) {
@@ -28554,9 +28554,9 @@ var require_node = __commonJS({
28554
28554
  }
28555
28555
  return staticChild.createStaticChild(path.slice(i));
28556
28556
  }
28557
- const label2 = path.charAt(0);
28558
- this.staticChildren[label2] = new StaticNode(path);
28559
- return this.staticChildren[label2];
28557
+ const label = path.charAt(0);
28558
+ this.staticChildren[label] = new StaticNode(path);
28559
+ return this.staticChildren[label];
28560
28560
  }
28561
28561
  };
28562
28562
  var StaticNode = class _StaticNode extends ParentNode {
@@ -51122,9 +51122,9 @@ var import_node_perf_hooks = require("node:perf_hooks");
51122
51122
  var MAX_EXPECTED_MS = 2 * 60 * 6e4;
51123
51123
  var MAX_LABEL_LENGTH = 60;
51124
51124
  function busyMeta(owner2) {
51125
- const label2 = typeof owner2.label === "string" && owner2.label.trim() && owner2.label.length <= MAX_LABEL_LENGTH ? owner2.label.trim() : null;
51125
+ const label = typeof owner2.label === "string" && owner2.label.trim() && owner2.label.length <= MAX_LABEL_LENGTH ? owner2.label.trim() : null;
51126
51126
  const expectedMs = typeof owner2.expectedMs === "number" && Number.isFinite(owner2.expectedMs) && owner2.expectedMs > 0 && owner2.expectedMs <= MAX_EXPECTED_MS ? owner2.expectedMs : null;
51127
- return { label: label2, expectedMs };
51127
+ return { label, expectedMs };
51128
51128
  }
51129
51129
  var LifecycleLockBusyError = class extends Error {
51130
51130
  constructor(message, busy) {
@@ -51146,7 +51146,7 @@ function remainingPhrase(remainingMs) {
51146
51146
  return `about ${minutes} minute${minutes === 1 ? "" : "s"} left`;
51147
51147
  }
51148
51148
  function busyDetail(kind, key2, owner2) {
51149
- const { label: label2, expectedMs } = busyMeta(owner2);
51149
+ const { label, expectedMs } = busyMeta(owner2);
51150
51150
  const startedMs = Date.parse(owner2.acquiredAt);
51151
51151
  const elapsedMs = Number.isFinite(startedMs) ? Math.max(0, Date.now() - startedMs) : 0;
51152
51152
  const usableEta = expectedMs != null && Number.isFinite(startedMs) ? expectedMs : null;
@@ -51154,7 +51154,7 @@ function busyDetail(kind, key2, owner2) {
51154
51154
  return {
51155
51155
  kind,
51156
51156
  key: key2,
51157
- label: label2,
51157
+ label,
51158
51158
  startedAt: owner2.acquiredAt,
51159
51159
  expectedMs: usableEta,
51160
51160
  elapsedMs,
@@ -51195,8 +51195,8 @@ var held = new import_node_async_hooks.AsyncLocalStorage();
51195
51195
  var localTails = /* @__PURE__ */ new Map();
51196
51196
  var localIntents = /* @__PURE__ */ new Map();
51197
51197
  function registerIntent(token2, options) {
51198
- const { label: label2, expectedMs } = busyMeta(options);
51199
- const intent = { label: label2, expectedMs, acquiredAt: null };
51198
+ const { label, expectedMs } = busyMeta(options);
51199
+ const intent = { label, expectedMs, acquiredAt: null };
51200
51200
  const set2 = localIntents.get(token2) ?? /* @__PURE__ */ new Set();
51201
51201
  set2.add(intent);
51202
51202
  localIntents.set(token2, set2);
@@ -55058,7 +55058,7 @@ function appVersion() {
55058
55058
  return resolveVersion({
55059
55059
  isSea: isSea2(),
55060
55060
  sqVersionXml: readSqVersionXml(),
55061
- define: true ? "0.135.1" : void 0,
55061
+ define: true ? "0.137.0" : void 0,
55062
55062
  pkgVersion: readPkgVersion()
55063
55063
  });
55064
55064
  }
@@ -55074,7 +55074,7 @@ function resolveChannel(s) {
55074
55074
  function appChannel() {
55075
55075
  return resolveChannel({
55076
55076
  isSea: isSea2(),
55077
- define: true ? "0.135.1" : void 0,
55077
+ define: true ? "0.137.0" : void 0,
55078
55078
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55079
55079
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55080
55080
  modulePath: process.argv[1]
@@ -55293,6 +55293,45 @@ function bakeFloSource(source, inputs) {
55293
55293
  // app-import.ts
55294
55294
  var import_yaml4 = __toESM(require_dist6(), 1);
55295
55295
 
55296
+ // ../web/steel-plan-view-id.js
55297
+ function planViewId(plan) {
55298
+ const id = plan && typeof plan === "object" ? plan.id : void 0;
55299
+ if (typeof id === "string" && id.trim() !== "") return id;
55300
+ const sheet = plan && typeof plan === "object" ? plan.sheet : void 0;
55301
+ return typeof sheet === "string" ? sheet : "";
55302
+ }
55303
+ function rawPlanViewId(plan) {
55304
+ if (!plan || typeof plan !== "object" || Array.isArray(plan)) return null;
55305
+ const row = (
55306
+ /** @type {{id?: unknown, sheet?: unknown}} */
55307
+ plan
55308
+ );
55309
+ if (row.id !== void 0) {
55310
+ return typeof row.id === "string" && row.id.trim() !== "" ? row.id : null;
55311
+ }
55312
+ if (typeof row.sheet === "string" && row.sheet.trim() !== "") return row.sheet;
55313
+ return null;
55314
+ }
55315
+ function planViewLabels(plans) {
55316
+ const rows2 = Array.isArray(plans) ? plans : [];
55317
+ const perSheet = /* @__PURE__ */ new Map();
55318
+ for (const plan of rows2) {
55319
+ const sheet = plan && typeof plan === "object" && typeof plan.sheet === "string" ? plan.sheet : "";
55320
+ perSheet.set(sheet, (perSheet.get(sheet) ?? 0) + 1);
55321
+ }
55322
+ const labels = /* @__PURE__ */ new Map();
55323
+ rows2.forEach((plan, index) => {
55324
+ const viewId = planViewId(plan);
55325
+ const sheet = plan && typeof plan === "object" && typeof plan.sheet === "string" ? plan.sheet : "";
55326
+ if (!sheet) {
55327
+ labels.set(viewId || `\0view${index}`, viewId || `view ${index + 1}`);
55328
+ return;
55329
+ }
55330
+ labels.set(viewId, (perSheet.get(sheet) ?? 0) > 1 ? `${sheet} \xB7 ${viewId}` : sheet);
55331
+ });
55332
+ return labels;
55333
+ }
55334
+
55296
55335
  // contract-schema.ts
55297
55336
  var import_node_fs16 = require("node:fs");
55298
55337
  var import_node_path14 = require("node:path");
@@ -55877,9 +55916,9 @@ function partFrame(from, to, up = [0, 0, 1], upX = [1, 0, 0]) {
55877
55916
  const len = Math.sqrt(dSq);
55878
55917
  if (!(len > 0) || !isFinite(len)) return null;
55879
55918
  const x = [d[0] / len, d[1] / len, d[2] / len];
55880
- const unit2 = (v, label2, min = 0) => {
55919
+ const unit2 = (v, label, min = 0) => {
55881
55920
  const l = Math.hypot(v[0], v[1], v[2]);
55882
- if (!(l > min) || !isFinite(l)) throw new Error(`partFrame ${label2} must be finite and non-degenerate`);
55921
+ if (!(l > min) || !isFinite(l)) throw new Error(`partFrame ${label} must be finite and non-degenerate`);
55883
55922
  return [v[0] / l, v[1] / l, v[2] / l];
55884
55923
  };
55885
55924
  const u = unit2(up, "up");
@@ -55939,6 +55978,25 @@ var SUPPORT_CENTERLINE_V1 = Object.freeze({
55939
55978
  minCrossingAngleDeg: 15,
55940
55979
  absoluteReachCapMm: 914.4,
55941
55980
  geometryReviewToleranceMm: 6.35,
55981
+ /**
55982
+ * How far a reader's submitted endpoint may sit from the server-derived drawing observation before
55983
+ * the read is refused (world mm — one micron).
55984
+ *
55985
+ * The comparison used to be exact JSON equality, which asked an independent reader to reproduce a
55986
+ * trig-laden similarity transform and land on the same side of `clean()`'s 1e-9 rounding boundary for
55987
+ * every endpoint. Nothing can hold that: a 250-member read was refused because three endpoints out of
55988
+ * 430 landed one 1e-9 quantum away, while the worst geometric disagreement across all 430 was
55989
+ * 6.77e-10 mm (#934). Quantising both sides does not help — it only relocates the same cliff — so the
55990
+ * comparison has to be a DISTANCE.
55991
+ *
55992
+ * 1e-3 mm is ~6 orders above the observed float noise and ~4 orders below the smallest thing the
55993
+ * check must still catch. A pre-extended endpoint hides the outward intersection by a drawing
55994
+ * setback, and this policy's own floor for a meaningful endpoint distance is
55995
+ * `geometryReviewToleranceMm` (6.35 mm) — 3.8 orders above this tolerance — so nothing the check
55996
+ * exists to catch fits inside it. Anything in 1e-5..1e-2 works; the point of the number is that it
55997
+ * sits in the middle of a very wide safe band, not that it is tuned.
55998
+ */
55999
+ literalEvidenceToleranceMm: 1e-3,
55942
56000
  maxSubjectEnds: 2e4,
55943
56001
  maxObservationsPerEnd: 16,
55944
56002
  maxMemberIdsPerTarget: 16,
@@ -55950,8 +56008,18 @@ function thresholdsForDrawingScale(ptPerFt) {
55950
56008
  if (!Number.isFinite(ptPerFt) || ptPerFt <= 0) return null;
55951
56009
  const raw = 0.5 * 304.8 / ptPerFt;
55952
56010
  const faceToleranceMm = raw <= 6.35 + 1e-12 ? 6.35 : raw >= 50.8 - 1e-12 ? 50.8 : raw;
56011
+ return thresholdsFromFaceTolerance(faceToleranceMm);
56012
+ }
56013
+ function thresholdsFromFaceTolerance(faceToleranceMm) {
55953
56014
  return Object.freeze({
55954
56015
  faceToleranceMm,
56016
+ // EVERY field named, none inheriting. They were all one expression, so retuning the gap allowance
56017
+ // — the point of #936 — would have moved the cluster spacing, the ambiguity margin, the span check
56018
+ // and the cross-view agreement with it, four unrelated decisions changed by editing one number.
56019
+ // Stating each is a prerequisite for that change, and is deliberately NOT itself a fix: every value
56020
+ // below is exactly what it was.
56021
+ faceGapToleranceMm: faceToleranceMm,
56022
+ faceOverlapToleranceMm: faceToleranceMm,
55955
56023
  targetSpanToleranceMm: faceToleranceMm,
55956
56024
  clusterToleranceMm: Math.min(faceToleranceMm, 25.4),
55957
56025
  ambiguityMarginMm: 2 * faceToleranceMm,
@@ -56113,13 +56181,15 @@ function geometryReviewModelHash(model, subjectId, end, reviewedPoint, scopeValu
56113
56181
  function geometryReviewPlanContext(model, scopeValue) {
56114
56182
  const scope = normalizedScope(scopeValue);
56115
56183
  const ids = scope.kind === "conversion" ? new Set(scope.viewIds) : scope.kind === "active-view" ? /* @__PURE__ */ new Set([scope.viewId]) : null;
56116
- return (model.plans ?? []).filter((plan) => !ids || ids.has(plan.sheet)).map((plan) => ({
56184
+ return (model.plans ?? []).filter((plan) => !ids || ids.has(planViewId(plan))).map((plan) => ({
56117
56185
  sheet: plan.sheet,
56118
56186
  viewKind: plan.viewKind,
56119
56187
  pt_per_ft: plan.pt_per_ft,
56120
- sourceRegistration: plan.sourceRegistration
56121
- })).sort((a, b) => utf8Compare(a.sheet, b.sheet));
56188
+ sourceRegistration: plan.sourceRegistration,
56189
+ ...planViewId(plan) !== plan.sheet ? { viewId: planViewId(plan) } : {}
56190
+ })).sort((a, b) => utf8Compare(a.sheet, b.sheet) || utf8Compare(planViewIdOf(a), planViewIdOf(b)));
56122
56191
  }
56192
+ var planViewIdOf = (row) => row.viewId ?? row.sheet;
56123
56193
 
56124
56194
  // steel-model-v2.ts
56125
56195
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -56183,8 +56253,21 @@ function checkModelReferences(doc) {
56183
56253
  add(`$.members[${i}]`, "column-endpoint-order", `column "${str(m.id) ?? i}" is stored top\u2192base (from.z ${za} > to.z ${zb}); columns are base\u2192top`);
56184
56254
  }
56185
56255
  });
56186
- const sheetCounts = idIndex(plans.map((p) => isObj(p) ? str(p.sheet) : null));
56187
- for (const [sheet, n] of sheetCounts) if (n > 1) add("$.plans", "plan-sheet-duplicate", `sheet "${sheet}" occurs on ${n} plans`);
56256
+ const viewIds = plans.map((p) => isObj(p) ? rawPlanViewId(p) : null);
56257
+ const viewIdCounts = idIndex(viewIds);
56258
+ const viewLabels = planViewLabels(plans);
56259
+ const nameOf = (pi) => {
56260
+ const id = viewIds[pi];
56261
+ return (id !== null && id !== void 0 ? viewLabels.get(id) : void 0) ?? id ?? String(pi);
56262
+ };
56263
+ viewIds.forEach((viewId, pi) => {
56264
+ if (viewId === null || (viewIdCounts.get(viewId) ?? 0) < 2) return;
56265
+ add(
56266
+ `$.plans[${pi}]`,
56267
+ "plan-view-id-duplicate",
56268
+ `view id "${viewId}" names ${viewIdCounts.get(viewId)} plans; a view id names one drawing view. Two views may share a physical sheet, but each needs its own $.id`
56269
+ );
56270
+ });
56188
56271
  const observations2 = [];
56189
56272
  plans.forEach((p, pi) => {
56190
56273
  if (!isObj(p)) return;
@@ -56194,14 +56277,25 @@ function checkModelReferences(doc) {
56194
56277
  });
56195
56278
  arr(p.memberRefs).forEach((id, ri) => memberRef(str(id), `$.plans[${pi}].memberRefs[${ri}]`, "member-ref-unresolved"));
56196
56279
  const has = (k) => p[k] !== void 0 && p[k] !== null;
56197
- if (has("control2_at") && !has("control2_ref")) {
56198
- add(`$.plans[${pi}]`, "control-pair-incomplete", `sheet "${sheet ?? pi}" has control2_at with no control2_ref; a second control is never the model origin, so the intersection it names must be stated`);
56199
- }
56200
- for (const side2 of ["datum", "control2"]) {
56201
- if (has(`${side2}_ref`) && !has(`${side2}_at`)) {
56202
- add(`$.plans[${pi}]`, "control-pair-incomplete", `sheet "${sheet ?? pi}" has ${side2}_ref with no ${side2}_at; naming an intersection without its point on the sheet registers nothing`);
56280
+ if (p.viewKind === "plan") {
56281
+ if (has("control2_at") && !has("control2_ref")) {
56282
+ add(`$.plans[${pi}]`, "control-pair-incomplete", `sheet "${nameOf(pi)}" has control2_at with no control2_ref; a second control is never the model origin, so the intersection it names must be stated`);
56283
+ }
56284
+ for (const side2 of ["datum", "control2"]) {
56285
+ if (has(`${side2}_ref`) && !has(`${side2}_at`)) {
56286
+ add(`$.plans[${pi}]`, "control-pair-incomplete", `sheet "${nameOf(pi)}" has ${side2}_ref with no ${side2}_at; naming an intersection without its point on the sheet registers nothing`);
56287
+ }
56203
56288
  }
56204
56289
  }
56290
+ const planStyleControls = ["datum_at", "datum_ref", "control2_at", "control2_ref"].filter((k) => has(k));
56291
+ if (p.viewKind !== "plan" && !isObj(p.sourceRegistration) && planStyleControls.length) {
56292
+ const kind = str(p.viewKind) ?? "";
56293
+ add(
56294
+ `$.plans[${pi}]`,
56295
+ "plan-controls-on-non-plan-view",
56296
+ `sheet "${nameOf(pi)}" is ${kind === "elevation" ? "an elevation" : kind ? `a ${kind}` : "an unclassified"} view carrying ${planStyleControls.map((k) => `$.${k}`).join(", ")} and nothing else; those register a PLAN and are ignored here \u2014 an elevation or section registers through $.sourceRegistration`
56297
+ );
56298
+ }
56205
56299
  const registration = isObj(p.sourceRegistration) ? p.sourceRegistration : null;
56206
56300
  if (registration) {
56207
56301
  const rp = `$.plans[${pi}].sourceRegistration`;
@@ -56503,6 +56597,29 @@ function checkModelReferences(doc) {
56503
56597
  else compare("z", parsed.levels.length);
56504
56598
  }
56505
56599
  const axisIds = new Set(axes.map((a) => isObj(a) ? str(a.id) : null).filter((v) => !!v));
56600
+ const axisDir = /* @__PURE__ */ new Map();
56601
+ for (const a of axes) {
56602
+ if (isObj(a)) {
56603
+ const id = str(a.id), dir = str(a.dir);
56604
+ if (id && dir) axisDir.set(id, dir);
56605
+ }
56606
+ }
56607
+ plans.forEach((p, pi) => {
56608
+ if (!isObj(p)) return;
56609
+ for (const key2 of ["datum_ref", "control2_ref"]) {
56610
+ const ref = isObj(p[key2]) ? p[key2] : null;
56611
+ if (!ref) continue;
56612
+ for (const [field, want] of [["xAxisId", "x"], ["yAxisId", "y"]]) {
56613
+ const id = str(ref[field]);
56614
+ const path = `$.plans[${pi}].${key2}.${field}`;
56615
+ if (!id || !axisIds.has(id)) {
56616
+ add(path, "control-ref-unresolved", `${field} "${id ?? ""}" does not name a $.grid.axes[].id \u2014 registration controls resolve against stable axis IDS, never the editable display label`);
56617
+ } else if (axisDir.get(id) !== want) {
56618
+ add(path, "control-ref-direction", `${field} names axis "${id}", which runs in ${axisDir.get(id) ?? "no"} \u2014 ${field} must name a ${want}-direction axis`);
56619
+ }
56620
+ }
56621
+ }
56622
+ });
56506
56623
  if (isObj(grid.ends)) {
56507
56624
  for (const [key2, span] of Object.entries(grid.ends)) {
56508
56625
  if (!axisIds.has(key2)) {
@@ -56583,12 +56700,12 @@ function checkModelReferences(doc) {
56583
56700
  if (gen) {
56584
56701
  const sheet = str(gen.sheet);
56585
56702
  if (sheet && !planSheets.has(sheet)) add(`$.views[${vi}].generated.sheet`, "view-generated-unresolved", `"${sheet}" does not name a plan`);
56586
- const axisId = str(gen.axisId);
56703
+ const axisId2 = str(gen.axisId);
56587
56704
  const wantDir = gen.kind === "level" ? "z" : gen.kind === "grid-x" ? "x" : gen.kind === "grid-y" ? "y" : null;
56588
56705
  if (wantDir === null) add(`$.views[${vi}].generated.kind`, "view-generated-unresolved", `unknown generated kind "${str(gen.kind)}"`);
56589
- const axis = arr(grid?.axes).find((a) => isObj(a) && str(a.id) === axisId);
56590
- if (axisId && (!axis || axis.dir !== wantDir)) {
56591
- add(`$.views[${vi}].generated.axisId`, "view-generated-unresolved", `"${axisId}" does not name a grid axis with dir "${wantDir}"`);
56706
+ const axis = arr(grid?.axes).find((a) => isObj(a) && str(a.id) === axisId2);
56707
+ if (axisId2 && (!axis || axis.dir !== wantDir)) {
56708
+ add(`$.views[${vi}].generated.axisId`, "view-generated-unresolved", `"${axisId2}" does not name a grid axis with dir "${wantDir}"`);
56592
56709
  }
56593
56710
  }
56594
56711
  });
@@ -56635,7 +56752,9 @@ var OWNED = {
56635
56752
  "steel-model": [STEEL_V2],
56636
56753
  vectorize: [VECTOR_V1]
56637
56754
  };
56638
- var MUTATING = ["put", "import", "duplicate", "bake"];
56755
+ var MUTATING = ["put", "import", "duplicate", "bake", "restore"];
56756
+ var isMutatingOperation = (operation) => MUTATING.includes(operation);
56757
+ var AUTHORING = ["put", "import"];
56639
56758
  var ContractPolicyError = class extends Error {
56640
56759
  code;
56641
56760
  constructor(message, code = "contract-not-acceptable") {
@@ -56703,8 +56822,35 @@ function assertAcceptableContract(doc, ctx) {
56703
56822
  const first = issues.slice(0, 5).map((i) => `${i.path}: ${i.message}`).join("; ");
56704
56823
  throw new ContractPolicyError(`contract failed referential integrity \u2014 ${first}`, "contract-invalid");
56705
56824
  }
56825
+ if (AUTHORING.includes(ctx.operation)) {
56826
+ const unregistered = lineagedUnregisteredViews(doc);
56827
+ if (unregistered.length) {
56828
+ throw new ContractPolicyError(
56829
+ `an elevation or section view whose observations carry endpoint lineage must state $.sourceRegistration before it can be written \u2014 ${unregistered.slice(0, 3).join(", ")}${unregistered.length > 3 ? ` and ${unregistered.length - 3} more` : ""}`,
56830
+ "contract-invalid"
56831
+ );
56832
+ }
56833
+ }
56706
56834
  }
56707
56835
  }
56836
+ function lineagedUnregisteredViews(doc) {
56837
+ const model = doc;
56838
+ if (!model || typeof model !== "object" || !Array.isArray(model.plans)) return [];
56839
+ const out = [];
56840
+ const labels = planViewLabels(model.plans);
56841
+ for (const raw of model.plans) {
56842
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
56843
+ const plan = raw;
56844
+ if (plan.viewKind !== "elevation" && plan.viewKind !== "section") continue;
56845
+ if (plan.sourceRegistration && typeof plan.sourceRegistration === "object") continue;
56846
+ const lineaged = Array.isArray(plan.memberObservations) && plan.memberObservations.some((o) => {
56847
+ const obs = o;
56848
+ return !!obs && typeof obs === "object" && obs.binding?.status === "active" && Array.isArray(obs.binding.endpointLineage) && obs.binding.endpointLineage.length > 0;
56849
+ });
56850
+ if (lineaged) out.push(`"${labels.get(rawPlanViewId(raw) ?? "") ?? rawPlanViewId(raw) ?? "(unnamed view)"}"`);
56851
+ }
56852
+ return out;
56853
+ }
56708
56854
  var isBakedContract = (value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
56709
56855
 
56710
56856
  // app-import.ts
@@ -58376,7 +58522,8 @@ function registrationOf(plan) {
58376
58522
  control2_at: plan.control2_at,
58377
58523
  control2_ref: plan.control2_ref,
58378
58524
  frame: plan.frame,
58379
- sourceRegistration: plan.sourceRegistration
58525
+ sourceRegistration: plan.sourceRegistration,
58526
+ ...planViewId(plan) !== plan.sheet ? { viewId: planViewId(plan) } : {}
58380
58527
  };
58381
58528
  }
58382
58529
  function drawingDependencyReasons(decision, beforeObservations, afterObservations) {
@@ -58742,10 +58889,31 @@ function dropSignOffsFor(projectId) {
58742
58889
  writeReviewFile(projectId, { version: 1, reviewRevision: current.reviewRevision + 1, joints });
58743
58890
  }
58744
58891
 
58892
+ // steel-plan-view-id-normalise.ts
58893
+ var needsId = (plan) => {
58894
+ if (!plan || typeof plan !== "object" || Array.isArray(plan)) return false;
58895
+ const row = plan;
58896
+ if (row.id !== void 0) return false;
58897
+ return typeof row.sheet === "string" && row.sheet.trim() !== "";
58898
+ };
58899
+ function normalisePlanViewIds(doc) {
58900
+ const model = doc;
58901
+ if (!model || typeof model !== "object" || !Array.isArray(model.plans)) return doc;
58902
+ if (typeof model.type === "string" && !model.type.startsWith("steel.model/")) return doc;
58903
+ if (!model.plans.some(needsId)) return doc;
58904
+ return {
58905
+ ...model,
58906
+ plans: model.plans.map((raw) => needsId(raw) ? { ...raw, id: raw.sheet } : raw)
58907
+ };
58908
+ }
58909
+
58745
58910
  // project-contract-hash.ts
58746
58911
  function contractHash(contract) {
58747
58912
  return hashOf(contract);
58748
58913
  }
58914
+ function comparableContractHash(contract) {
58915
+ return hashOf(normalisePlanViewIds(contract));
58916
+ }
58749
58917
 
58750
58918
  // connection-review-transition.ts
58751
58919
  var ConnectionReviewTransitionError = class extends Error {
@@ -60221,12 +60389,12 @@ function writePhase(txnDir, journal) {
60221
60389
  }
60222
60390
  }
60223
60391
  }
60224
- function validateProof(value, label2) {
60392
+ function validateProof(value, label) {
60225
60393
  if (!value || typeof value !== "object" || Array.isArray(value)) {
60226
- throw new IfcPublicationError(`${label2} proof is invalid.`);
60394
+ throw new IfcPublicationError(`${label} proof is invalid.`);
60227
60395
  }
60228
60396
  const p = value;
60229
- if (typeof p.exists !== "boolean" || typeof p.bytes !== "number" || !Number.isSafeInteger(p.bytes) || p.bytes < 0 || !(p.exists && typeof p.sha256 === "string" && /^[a-f0-9]{64}$/i.test(p.sha256) && p.bytes > 0 || !p.exists && p.sha256 === null && p.bytes === 0)) throw new IfcPublicationError(`${label2} proof is invalid.`);
60397
+ if (typeof p.exists !== "boolean" || typeof p.bytes !== "number" || !Number.isSafeInteger(p.bytes) || p.bytes < 0 || !(p.exists && typeof p.sha256 === "string" && /^[a-f0-9]{64}$/i.test(p.sha256) && p.bytes > 0 || !p.exists && p.sha256 === null && p.bytes === 0)) throw new IfcPublicationError(`${label} proof is invalid.`);
60230
60398
  return p;
60231
60399
  }
60232
60400
  function validateJournal(raw, txnDir, expectedTxnId) {
@@ -60952,9 +61120,9 @@ var navLeaf = (family) => ({
60952
61120
  families: [family],
60953
61121
  count: PROFILE_FAMILY_COUNTS[family]
60954
61122
  });
60955
- var navParent = (id, label2, families) => ({
61123
+ var navParent = (id, label, families) => ({
60956
61124
  id,
60957
- label: label2,
61125
+ label,
60958
61126
  families,
60959
61127
  count: families.reduce((sum, family) => sum + PROFILE_FAMILY_COUNTS[family], 0),
60960
61128
  children: families.map(navLeaf)
@@ -62493,14 +62661,14 @@ function durableReplace2(path, text5) {
62493
62661
  function safeLease(value) {
62494
62662
  if (!SAFE_LEASE.test(value)) throw new Error("invalid Codex lease id");
62495
62663
  }
62496
- function rejectLink(path, label2) {
62664
+ function rejectLink(path, label) {
62497
62665
  let st;
62498
62666
  try {
62499
62667
  st = (0, import_node_fs30.lstatSync)(path);
62500
62668
  } catch {
62501
- throw new Error(`${label2} not found`);
62669
+ throw new Error(`${label} not found`);
62502
62670
  }
62503
- if (st.isSymbolicLink()) throw new Error(`${label2} is a filesystem link/reparse point`);
62671
+ if (st.isSymbolicLink()) throw new Error(`${label} is a filesystem link/reparse point`);
62504
62672
  }
62505
62673
  var ps = (value) => value.replace(/'/g, "''");
62506
62674
  var sh = (value) => value.replace(/'/g, `'"'"'`);
@@ -64160,7 +64328,7 @@ My note: ${req.instruction}` : "";
64160
64328
  return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing set was attached. Re-read it into the SAME steel.model/v2 project. ${manifestPhase} The server writes the exact Filter into the existing model. Then STOP and tell me exactly: ${REVISION_READ_FILTER_QUESTION} Do not read members, build the model, open 3D, or POST /revision-read until I explicitly return after saving the Drawing Filter. Only after Save, read selected elements into model-global members in world millimetres, preserve unchanged member ids, attach active observations using { sourceHash, sheet, elementId }, and preserve grid and plan registration unless the drawings explicitly prove a reviewed change. ${post}${snaps}${note}`;
64161
64329
  }
64162
64330
  if (isInitialRead) {
64163
- return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing set was attached. Create its first steel model version without creating another project. ${manifestPhase} Use the exact returned Filter and bound pages to compose a schema-valid native steel.model/v2 checkpoint shell with zero members/model records, one canonical model grid, and registered plans matching the manifest model sheets. PUT that shell to /api/contract/${req.appId}?project=${req.project} with If-None-Match: * and X-FloLess-Prepass-Request: "${req.id}". Then STOP and tell me exactly: ${REVISION_READ_FILTER_QUESTION} Do not read members or post /revision-read before Save. AFTER Save, add model-global members in world millimetres and active observations using { sourceHash, sheet, elementId }, preserving the checkpoint Filter, grid, and plan registration exactly. ${post}${snaps}${note}`;
64331
+ return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing set was attached. Create its first steel model version without creating another project. ${manifestPhase} Use the exact returned Filter and bound pages to compose a schema-valid native steel.model/v2 checkpoint shell with zero members/model records, one canonical model grid, and one registered plans[] row per DRAWING VIEW covering the manifest model sheets \u2014 a page carrying several elevations gets one row each, sharing that page's sheet and stating its own model-global id. PUT that shell to /api/contract/${req.appId}?project=${req.project} with If-None-Match: * and X-FloLess-Prepass-Request: "${req.id}". Then STOP and tell me exactly: ${REVISION_READ_FILTER_QUESTION} Do not read members or post /revision-read before Save. AFTER Save, add model-global members in world millimetres and active observations using { sourceHash, sheet, elementId }, preserving the checkpoint Filter, grid, and plan registration exactly. ${post}${snaps}${note}`;
64164
64332
  }
64165
64333
  throw new Error("unreachable steel revision-read instruction branch");
64166
64334
  }
@@ -64459,20 +64627,20 @@ var INTERNAL_VISIBLE_WORDS = /\b(?:schema|api|manifest|ledger|registration|bindi
64459
64627
  var ITEM_STATES = /* @__PURE__ */ new Set(["pending", "done", "now", "blocked", "waiting", "provisional"]);
64460
64628
  var STATUSES = /* @__PURE__ */ new Set(["active", "waiting", "blocked", "complete", "cancelled"]);
64461
64629
  var SOURCE_SKILLS = new Set(STEEL_PROGRESS_SOURCE_SKILLS);
64462
- function exactKeys(value, allowed, label2) {
64630
+ function exactKeys(value, allowed, label) {
64463
64631
  const unexpected = Object.keys(value).filter((key2) => !allowed.includes(key2));
64464
- if (unexpected.length) throw new SteelProgressError(`${label2} contains unsupported fields`);
64632
+ if (unexpected.length) throw new SteelProgressError(`${label} contains unsupported fields`);
64465
64633
  }
64466
- function boundedText(value, label2, max2, nullable = false) {
64634
+ function boundedText(value, label, max2, nullable = false) {
64467
64635
  if (nullable && value === null) return null;
64468
64636
  if (typeof value !== "string" || !value.trim() || value.length > max2 || /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
64469
- throw new SteelProgressError(`${label2} must be plain text within ${max2} characters`);
64637
+ throw new SteelProgressError(`${label} must be plain text within ${max2} characters`);
64470
64638
  }
64471
64639
  return value.trim();
64472
64640
  }
64473
- function rejectInternalVisibleTerms(value, label2) {
64641
+ function rejectInternalVisibleTerms(value, label) {
64474
64642
  if (value && INTERNAL_VISIBLE_WORDS.test(value)) {
64475
- throw new SteelProgressError(`${label2} must use plain English without internal terms`);
64643
+ throw new SteelProgressError(`${label} must use plain English without internal terms`);
64476
64644
  }
64477
64645
  }
64478
64646
  function validateSteelProgressInput(value, requestId) {
@@ -65214,7 +65382,7 @@ function readContract(appId, projectId) {
65214
65382
  const p = contractPath(appId, projectId);
65215
65383
  if (!(0, import_node_fs37.existsSync)(p)) return null;
65216
65384
  try {
65217
- return normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8")));
65385
+ return normalisePlanViewIds(normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8"))));
65218
65386
  } catch (e) {
65219
65387
  console.warn(`readContract: ignoring unreadable contract at ${p}: ${e instanceof Error ? e.message : e}`);
65220
65388
  return null;
@@ -65222,6 +65390,7 @@ function readContract(appId, projectId) {
65222
65390
  }
65223
65391
  function writeContract(appId, doc, projectId, options) {
65224
65392
  doc = normaliseRollMarkers(doc);
65393
+ doc = normalisePlanViewIds(doc);
65225
65394
  const p = contractPath(appId, projectId);
65226
65395
  const currentType = options?.currentType !== void 0 ? options.currentType : (() => {
65227
65396
  const cur = readContract(appId, projectId);
@@ -66679,7 +66848,7 @@ function expandCustom(joint, review) {
66679
66848
  positions[k + 2] = g.positions[k + 2] + dz;
66680
66849
  }
66681
66850
  const role = typeof g.role === "string" ? g.role : void 0;
66682
- const label2 = role ? role.charAt(0).toUpperCase() + role.slice(1) : "Imported part";
66851
+ const label = role ? role.charAt(0).toUpperCase() + role.slice(1) : "Imported part";
66683
66852
  const lift = review && review.get(joint.id);
66684
66853
  out.push({
66685
66854
  id: `${joint.id}:${g.id || `m${i}`}`,
@@ -66687,7 +66856,7 @@ function expandCustom(joint, review) {
66687
66856
  kind: "mesh",
66688
66857
  positions,
66689
66858
  indices: g.indices.slice(),
66690
- meta: { label: label2, role, ...lift ? { connReview: lift } : {} }
66859
+ meta: { label, role, ...lift ? { connReview: lift } : {} }
66691
66860
  });
66692
66861
  });
66693
66862
  return out;
@@ -67088,7 +67257,7 @@ function readModel(doc) {
67088
67257
  return readModelOrIssues(doc).view ?? null;
67089
67258
  }
67090
67259
  function readModelOrIssues(doc) {
67091
- doc = normaliseRollMarkers(doc);
67260
+ doc = normalisePlanViewIds(normaliseRollMarkers(doc));
67092
67261
  if (!isModelV2(doc)) return { view: null, issues: ["not-model-v2"] };
67093
67262
  const schema = validateSteelModelV2(doc);
67094
67263
  if (!schema.valid) {
@@ -67125,6 +67294,7 @@ function readModelOrIssues(doc) {
67125
67294
  members,
67126
67295
  byId: new Map(members.map((m) => [m.id, m])),
67127
67296
  sheets: (v2.plans ?? []).map((p) => ({
67297
+ viewId: planViewId(p),
67128
67298
  sheet: p.sheet,
67129
67299
  viewKind: p.viewKind,
67130
67300
  title: p.title,
@@ -67445,18 +67615,18 @@ function buildManifest(scene) {
67445
67615
  if (ref.axes.length === 0) fail2(`the scene's grid "${id}" must state at least one axis.`);
67446
67616
  for (const axisRaw of ref.axes) {
67447
67617
  const axis = obj2(axisRaw);
67448
- const label2 = typeof axis.label === "string" ? axis.label : str2(axis.id);
67618
+ const label = typeof axis.label === "string" ? axis.label : str2(axis.id);
67449
67619
  const direction = axis.direction;
67450
67620
  if (direction !== "x" && direction !== "y") {
67451
- fail2(`the scene's grid axis "${label2}" direction must be exactly "x" or "y".`);
67621
+ fail2(`the scene's grid axis "${label}" direction must be exactly "x" or "y".`);
67452
67622
  }
67453
67623
  const offset = axis.offsetMm;
67454
- if (typeof offset !== "number" || !Number.isFinite(offset)) fail2(`the scene's grid axis "${label2}" states no offsetMm, so the checker cannot say where it belongs.`);
67624
+ if (typeof offset !== "number" || !Number.isFinite(offset)) fail2(`the scene's grid axis "${label}" states no offsetMm, so the checker cannot say where it belongs.`);
67455
67625
  const finiteEnd = (key2, fallback2) => {
67456
67626
  const value = axis[key2];
67457
67627
  if (value === void 0) return fallback2;
67458
67628
  if (typeof value !== "number" || !Number.isFinite(value)) {
67459
- fail2(`the scene's grid axis "${label2}" ${key2} must be a finite number when stated.`);
67629
+ fail2(`the scene's grid axis "${label}" ${key2} must be a finite number when stated.`);
67460
67630
  }
67461
67631
  return value;
67462
67632
  };
@@ -67464,7 +67634,7 @@ function buildManifest(scene) {
67464
67634
  const lo = finiteEnd("startMm", bound(isU ? "minY" : "minX"));
67465
67635
  const hi = finiteEnd("endMm", bound(isU ? "maxY" : "maxX"));
67466
67636
  const o = offset;
67467
- (isU ? u : v).push(isU ? { label: label2, p0: [o, lo], p1: [o, hi] } : { label: label2, p0: [lo, o], p1: [hi, o] });
67637
+ (isU ? u : v).push(isU ? { label, p0: [o, lo], p1: [o, hi] } : { label, p0: [lo, o], p1: [hi, o] });
67468
67638
  }
67469
67639
  gridAxes.push({ sceneId: id, gridGuid: guid, origin, u, v });
67470
67640
  for (const levelRaw of arr2(ref.levels)) {
@@ -67845,9 +68015,9 @@ function checkGridAxes(index, manifest) {
67845
68015
  }
67846
68016
  }
67847
68017
  function checkSpatialStructure(index, manifest) {
67848
- for (const [type, label2] of [["IFCPROJECT", "project"], ["IFCSITE", "site"], ["IFCBUILDING", "building"], ["IFCBUILDINGSTOREY", "storey"]]) {
68018
+ for (const [type, label] of [["IFCPROJECT", "project"], ["IFCSITE", "site"], ["IFCBUILDING", "building"], ["IFCBUILDINGSTOREY", "storey"]]) {
67849
68019
  const found = index.byType(type).length;
67850
- if (found !== 1) fail2(`the IFC has ${found} ${label2} records, expected exactly 1.`);
68020
+ if (found !== 1) fail2(`the IFC has ${found} ${label} records, expected exactly 1.`);
67851
68021
  }
67852
68022
  const aggregates = index.byType("IFCRELAGGREGATES");
67853
68023
  if (aggregates.length !== 3) fail2(`the IFC has ${aggregates.length} spatial aggregations, expected 3.`);
@@ -67984,9 +68154,9 @@ function checkIfcArtifact(sceneInput, receipt, emitted, index, bytes2) {
67984
68154
  }
67985
68155
 
67986
68156
  // export-receipt.ts
67987
- function record2(value, label2) {
68157
+ function record2(value, label) {
67988
68158
  if (!value || typeof value !== "object" || Array.isArray(value)) {
67989
- throw new ReceiptReconciliationError(`${label2} must be an object.`);
68159
+ throw new ReceiptReconciliationError(`${label} must be an object.`);
67990
68160
  }
67991
68161
  return value;
67992
68162
  }
@@ -68945,8 +69115,8 @@ function modelGridRecords(grid) {
68945
69115
  const axes = [];
68946
69116
  X.offsets.forEach((offsetMm, index) => {
68947
69117
  const axis = xAxes[index];
68948
- const label2 = labelX[index] || "";
68949
- if (!label2) throw new SceneContractError("The model grid has a blank X-axis label.");
69118
+ const label = labelX[index] || "";
69119
+ if (!label) throw new SceneContractError("The model grid has a blank X-axis label.");
68950
69120
  const span = ends[axis.id];
68951
69121
  const start2 = span ? Math.min(span[0], span[1]) - oy : bounds.minY;
68952
69122
  const end = span ? Math.max(span[0], span[1]) - oy : bounds.maxY;
@@ -68954,15 +69124,15 @@ function modelGridRecords(grid) {
68954
69124
  id: `${root6}:${axis.id}`,
68955
69125
  direction: "x",
68956
69126
  offsetMm,
68957
- label: label2,
69127
+ label,
68958
69128
  ...Math.abs(start2 - bounds.minY) > 0.5 ? { startMm: start2 } : {},
68959
69129
  ...Math.abs(end - bounds.maxY) > 0.5 ? { endMm: end } : {}
68960
69130
  });
68961
69131
  });
68962
69132
  Y.offsets.forEach((offsetMm, index) => {
68963
69133
  const axis = yAxes[index];
68964
- const label2 = labelY[index] || "";
68965
- if (!label2) throw new SceneContractError("The model grid has a blank Y-axis label.");
69134
+ const label = labelY[index] || "";
69135
+ if (!label) throw new SceneContractError("The model grid has a blank Y-axis label.");
68966
69136
  const span = ends[axis.id];
68967
69137
  const start2 = span ? Math.min(span[0], span[1]) - ox : bounds.minX;
68968
69138
  const end = span ? Math.max(span[0], span[1]) - ox : bounds.maxX;
@@ -68970,7 +69140,7 @@ function modelGridRecords(grid) {
68970
69140
  id: `${root6}:${axis.id}`,
68971
69141
  direction: "y",
68972
69142
  offsetMm,
68973
- label: label2,
69143
+ label,
68974
69144
  ...Math.abs(start2 - bounds.minX) > 0.5 ? { startMm: start2 } : {},
68975
69145
  ...Math.abs(end - bounds.maxX) > 0.5 ? { endMm: end } : {}
68976
69146
  });
@@ -68980,9 +69150,9 @@ function modelGridRecords(grid) {
68980
69150
  [...parsedLevels].sort((a, b) => a.sourceIndex - b.sourceIndex).forEach((level, index) => axisBySourceIndex.set(level.sourceIndex, zAxes[index]));
68981
69151
  const levels = parsedLevels.map((level) => {
68982
69152
  const axis = axisBySourceIndex.get(level.sourceIndex);
68983
- const label2 = (axis.label ?? "").trim() || level.label;
68984
- if (!label2) throw new SceneContractError("The model grid has a blank elevation label.");
68985
- return { id: `${root6}:${axis.id}`, elevationMm: level.mm, label: label2 };
69153
+ const label = (axis.label ?? "").trim() || level.label;
69154
+ if (!label) throw new SceneContractError("The model grid has a blank elevation label.");
69155
+ return { id: `${root6}:${axis.id}`, elevationMm: level.mm, label };
68986
69156
  });
68987
69157
  const record4 = {
68988
69158
  id: root6,
@@ -69845,6 +70015,8 @@ var clean = (n) => {
69845
70015
  return Object.is(q, -0) ? 0 : q;
69846
70016
  };
69847
70017
  var finite2 = (p) => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite);
70018
+ var round2 = (n) => Math.round(n * 100) / 100;
70019
+ var REGISTRATION_SPAN_TOLERANCE_PT = 2;
69848
70020
  var PlanTransformError = class extends Error {
69849
70021
  constructor(code, message, viewKind = null) {
69850
70022
  super(message);
@@ -69853,6 +70025,7 @@ var PlanTransformError = class extends Error {
69853
70025
  this.viewKind = viewKind;
69854
70026
  }
69855
70027
  };
70028
+ var subjectOf = (plan, subject) => subject || `sheet "${quote(plan && plan.sheet)}"`;
69856
70029
  var refuse = (code, message, plan) => {
69857
70030
  throw new PlanTransformError(code, message, plan && plan.viewKind);
69858
70031
  };
@@ -69870,65 +70043,66 @@ var clipQuoted = (value, max2 = MAX_QUOTED_CHARS) => {
69870
70043
  return `${text5.slice(0, end)}\u2026`;
69871
70044
  };
69872
70045
  var quote = (value) => clipQuoted(value);
69873
- function gridIntersection(grid, ref, plan, field) {
70046
+ function gridIntersection(grid, ref, plan, field, subject) {
69874
70047
  if (!grid || typeof grid !== "object") {
69875
- return refuse("grid-unavailable", `sheet "${quote(plan.sheet)}" has no model grid to resolve its registration controls`, plan);
70048
+ return refuse("grid-unavailable", `${subjectOf(plan, subject)} has no model grid to resolve its registration controls`, plan);
69876
70049
  }
69877
70050
  if (!finite2(grid.origin)) {
69878
70051
  return refuse(
69879
70052
  "grid-unavailable",
69880
- `sheet "${quote(plan.sheet)}" cannot resolve its registration controls: $.grid.origin is missing or unreadable \u2014 it must be two finite world-mm numbers giving where the first x and y grid axes cross`,
70053
+ `${subjectOf(plan, subject)} cannot resolve its registration controls: $.grid.origin is missing or unreadable \u2014 it must be two finite world-mm numbers giving where the first x and y grid axes cross`,
69881
70054
  plan
69882
70055
  );
69883
70056
  }
69884
- if (!ref || typeof ref !== "object" || typeof ref.axis_x !== "string" || typeof ref.axis_y !== "string") {
69885
- return refuse("control-ref-invalid", `sheet "${quote(plan.sheet)}" has an unreadable ${field}: a registration control needs string axis_x and axis_y labels`, plan);
70057
+ if (!ref || typeof ref !== "object" || typeof ref.xAxisId !== "string" || typeof ref.yAxisId !== "string") {
70058
+ return refuse("control-ref-invalid", `${subjectOf(plan, subject)} has an unreadable ${field}: a registration control needs string xAxisId and yAxisId grid axis ids`, plan);
69886
70059
  }
69887
70060
  const X = parseSpacings(grid.x), Y = parseSpacings(grid.y);
69888
70061
  if (X.err || Y.err) {
69889
70062
  const bad = X.err ? "$.grid.x" : "$.grid.y";
69890
- return refuse("grid-spacing-invalid", `sheet "${quote(plan.sheet)}" cannot use ${bad}: ${quote(X.err || Y.err)}`, plan);
70063
+ return refuse("grid-spacing-invalid", `${subjectOf(plan, subject)} cannot use ${bad}: ${quote(X.err || Y.err)}`, plan);
69891
70064
  }
69892
- const xs = axisLabelsFor(grid, "x", "num", X.offsets.length);
69893
- const ys = axisLabelsFor(grid, "y", "alpha", Y.offsets.length);
69894
- const uniqueIndex = (labels, wanted) => {
69895
- const hits = labels.map((label2, i) => label2 === wanted ? i : -1).filter((i) => i >= 0);
70065
+ const idsFor = (dir) => (Array.isArray(grid.axes) ? grid.axes.filter((a) => a && a.dir === dir) : []).map((a) => typeof a.id === "string" ? a.id : null);
70066
+ const xs = idsFor("x"), ys = idsFor("y");
70067
+ const uniqueIndex = (ids, wanted, count2) => {
70068
+ if (ids.length !== count2) return -1;
70069
+ const hits = ids.map((id, i) => id === wanted ? i : -1).filter((i) => i >= 0);
69896
70070
  return hits.length === 1 ? hits[0] : -1;
69897
70071
  };
69898
- const xi = uniqueIndex(xs, ref.axis_x), yi = uniqueIndex(ys, ref.axis_y);
70072
+ const xi = uniqueIndex(xs, ref.xAxisId, X.offsets.length), yi = uniqueIndex(ys, ref.yAxisId, Y.offsets.length);
69899
70073
  if (xi < 0 || yi < 0) {
69900
70074
  return refuse(
69901
70075
  "control-ref-unresolved",
69902
- `sheet "${quote(plan.sheet)}" ${field} names ${quote(ref.axis_x)}/${quote(ref.axis_y)}, which is not exactly one x and one y label on the model grid`,
70076
+ `${subjectOf(plan, subject)} ${field} names ${quote(ref.xAxisId)}/${quote(ref.yAxisId)}, which is not exactly one x and one y axis id on the model grid`,
69903
70077
  plan
69904
70078
  );
69905
70079
  }
69906
70080
  return [grid.origin[0] + X.offsets[xi], grid.origin[1] + Y.offsets[yi]];
69907
70081
  }
69908
- function planTransform(plan) {
70082
+ function planTransform(plan, subject) {
69909
70083
  const kind = plan && plan.viewKind;
69910
70084
  if (kind !== "plan") {
69911
70085
  const named = typeof kind === "string" && kind ? quote(kind) : "unknown";
69912
70086
  return refuse(
69913
70087
  "view-kind-unsupported",
69914
- `sheet "${quote(plan && plan.sheet)}" is a ${named} view; ${named} views are not supported by the plan transform`,
70088
+ `${subjectOf(plan, subject)} is a ${named} view; ${named} views are not supported by the plan transform`,
69915
70089
  plan
69916
70090
  );
69917
70091
  }
69918
70092
  if (!finite2(plan.datum_at) || !finite2(plan.control2_at) || !plan.control2_ref) {
69919
70093
  return refuse(
69920
70094
  "registration-incomplete",
69921
- `sheet "${quote(plan.sheet)}" needs $.datum_at, $.control2_at and $.control2_ref before it can be edited`,
70095
+ `${subjectOf(plan, subject)} needs $.datum_at, $.control2_at and $.control2_ref before it can be edited`,
69922
70096
  plan
69923
70097
  );
69924
70098
  }
69925
70099
  const ptPerFt = Number(plan.pt_per_ft);
69926
70100
  if (!(ptPerFt > 0) || !Number.isFinite(ptPerFt)) {
69927
- return refuse("scale-invalid", `sheet "${quote(plan.sheet)}" has no positive $.pt_per_ft, so it has no drawing scale`, plan);
70101
+ return refuse("scale-invalid", `${subjectOf(plan, subject)} has no positive $.pt_per_ft, so it has no drawing scale`, plan);
69928
70102
  }
69929
70103
  const registrationGrid = plan.modelGrid || plan.grid;
69930
- const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan, "$.datum_ref") : [0, 0];
69931
- const world1 = gridIntersection(registrationGrid, plan.control2_ref, plan, "$.control2_ref");
70104
+ const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan, "$.datum_ref", subject) : [0, 0];
70105
+ const world1 = gridIntersection(registrationGrid, plan.control2_ref, plan, "$.control2_ref", subject);
69932
70106
  const scale = mmPerPx(ptPerFt);
69933
70107
  const local1 = [
69934
70108
  (plan.control2_at[0] - plan.datum_at[0]) * scale,
@@ -69938,24 +70112,33 @@ function planTransform(plan) {
69938
70112
  const localLen = Math.hypot(local1[0], local1[1]);
69939
70113
  const worldLen = Math.hypot(worldDelta[0], worldDelta[1]);
69940
70114
  if (!(localLen > 1e-9)) {
69941
- return refuse("registration-degenerate", `sheet "${quote(plan.sheet)}" has coincident registration controls: $.datum_at and $.control2_at are the same point on the sheet`, plan);
70115
+ return refuse("registration-degenerate", `${subjectOf(plan, subject)} has coincident registration controls: $.datum_at and $.control2_at are the same point on the sheet`, plan);
69942
70116
  }
69943
70117
  if (!(worldLen > 1e-9)) {
69944
70118
  const datum = plan.datum_ref ? "$.datum_ref and $.control2_ref resolve to the same grid intersection" : "$.control2_ref resolves to the model origin, which is where an absent $.datum_ref already puts the datum";
69945
- return refuse("registration-degenerate", `sheet "${quote(plan.sheet)}" has coincident registration controls: ${datum}`, plan);
70119
+ return refuse("registration-degenerate", `${subjectOf(plan, subject)} has coincident registration controls: ${datum}`, plan);
70120
+ }
70121
+ const actualSpanPt = localLen / scale;
70122
+ const expectedSpanPt = worldLen / scale;
70123
+ if (Math.abs(actualSpanPt - expectedSpanPt) > REGISTRATION_SPAN_TOLERANCE_PT) {
70124
+ return refuse(
70125
+ "registration-span-mismatch",
70126
+ `${subjectOf(plan, subject)} registration controls span ${round2(actualSpanPt)} pt on the sheet, but ${plan.datum_ref ? "$.datum_ref" : "the model origin"} and $.control2_ref are ${round2(worldLen)} mm apart, which at ${plan.pt_per_ft} pt/ft is ${round2(expectedSpanPt)} pt \u2014 a difference of ${round2(Math.abs(actualSpanPt - expectedSpanPt))} pt, past the ${REGISTRATION_SPAN_TOLERANCE_PT} pt allowed. Either a control names the wrong grid axis or $.pt_per_ft is wrong`,
70127
+ plan
70128
+ );
69946
70129
  }
69947
70130
  const fitScale = worldLen / localLen;
69948
70131
  const rotation = Math.atan2(worldDelta[1], worldDelta[0]) - Math.atan2(local1[1], local1[0]);
69949
70132
  const c = Math.cos(rotation) * fitScale;
69950
70133
  const s = Math.sin(rotation) * fitScale;
69951
70134
  if (![c, s, fitScale, world0[0], world0[1]].every(Number.isFinite)) {
69952
- return refuse("registration-invalid", `sheet "${quote(plan.sheet)}" has a non-finite registration transform`, plan);
70135
+ return refuse("registration-invalid", `${subjectOf(plan, subject)} has a non-finite registration transform`, plan);
69953
70136
  }
69954
70137
  return { datumPx: plan.datum_at, world0, mmPerPx: scale, fitScale, rotation, c, s };
69955
70138
  }
69956
- function sheetPxToWorld(point3, plan, keepZ) {
70139
+ function sheetPxToWorld(point3, plan, keepZ, subject) {
69957
70140
  if (!finite2(point3)) return refuse("sheet-point-invalid", "a sheet point needs two finite pixel coordinates", plan);
69958
- const t = planTransform(plan);
70141
+ const t = planTransform(plan, subject);
69959
70142
  const localX = (point3[0] - t.datumPx[0]) * t.mmPerPx;
69960
70143
  const localY = (t.datumPx[1] - point3[1]) * t.mmPerPx;
69961
70144
  return {
@@ -70090,7 +70273,7 @@ function footprintBoundaryParameters(footprint, qy, qz, dy, dz) {
70090
70273
  }
70091
70274
  return values2;
70092
70275
  }
70093
- function faceContact(origin, direction, hit, target, toleranceMm) {
70276
+ function faceContact(origin, direction, hit, target, gapToleranceMm, overlapToleranceMm) {
70094
70277
  const footprint = resolveFootprint(target);
70095
70278
  if (typeof footprint === "string") return footprint;
70096
70279
  const o = xyz(origin), targetPoint = xyz(hit.point), d = xyz(direction);
@@ -70100,9 +70283,12 @@ function faceContact(origin, direction, hit, target, toleranceMm) {
70100
70283
  const boundaries = footprintBoundaryParameters(footprint, qy, qz, dy, dz).filter((value) => Number.isFinite(value) && value <= hit.distanceMm + EPS).sort((a, b) => b - a);
70101
70284
  const nearBoundary = boundaries[0];
70102
70285
  if (nearBoundary === void 0 || hit.distanceMm - nearBoundary < -EPS) return "face-contact-missed";
70286
+ const faceGapMm = nearBoundary;
70103
70287
  const faceResidualMm = Math.abs(nearBoundary);
70104
- if (faceResidualMm > toleranceMm + EPS) return "face-contact-missed";
70105
- return { faceResidualMm, faceToCenterlineMm: hit.distanceMm - nearBoundary };
70288
+ if (faceGapMm > 0 ? faceGapMm > gapToleranceMm + EPS : -faceGapMm > overlapToleranceMm + EPS) {
70289
+ return "face-contact-missed";
70290
+ }
70291
+ return { faceResidualMm, faceGapMm, faceToCenterlineMm: hit.distanceMm - nearBoundary };
70106
70292
  }
70107
70293
  var pointOrder = (a, b) => a.x - b.x || a.y - b.y || a.z - b.z;
70108
70294
  function completeLinkGroups(clusters, toleranceMm) {
@@ -70123,7 +70309,14 @@ function candidateFromCluster(cluster) {
70123
70309
  distanceMm: Math.min(...cluster.hits.map((entry2) => entry2.hit.distanceMm)),
70124
70310
  ...contacts.length ? {
70125
70311
  faceToCenterlineMm: Math.min(...contacts.map((entry2) => entry2.faceToCenterlineMm)),
70126
- faceResidualMm: Math.max(...contacts.map((entry2) => entry2.faceResidualMm))
70312
+ faceResidualMm: Math.max(...contacts.map((entry2) => entry2.faceResidualMm)),
70313
+ /*
70314
+ * The gap of the contact whose MAGNITUDE `faceResidualMm` reports, so the two describe the same
70315
+ * contact. `Math.max` over signed values would not: with a +5 mm gap and a -9 mm overlap in one
70316
+ * cluster it reports the 9 mm as the residual and the +5 mm as the gap, which reads as a 5 mm
70317
+ * setback when the real fault is a 9 mm interpenetration.
70318
+ */
70319
+ faceGapMm: contacts.reduce((worst, entry2) => Math.abs(entry2.faceGapMm) > Math.abs(worst.faceGapMm) ? entry2 : worst).faceGapMm
70127
70320
  } : {},
70128
70321
  crossingAngleDeg: Math.min(...cluster.hits.map((entry2) => entry2.hit.angleDeg)),
70129
70322
  reasons: Object.freeze(reasons)
@@ -70156,7 +70349,15 @@ function analyzeMemberEnd(input) {
70156
70349
  const ray = outwardRay(input.subject, input.end);
70157
70350
  if (!ray) return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70158
70351
  const t = input.thresholds;
70159
- if (![t.faceToleranceMm, t.targetSpanToleranceMm, t.clusterToleranceMm, t.ambiguityMarginMm, t.viewAgreementToleranceMm].every((value) => Number.isFinite(value) && value >= 0)) {
70352
+ if (![
70353
+ t.faceToleranceMm,
70354
+ t.faceGapToleranceMm,
70355
+ t.faceOverlapToleranceMm,
70356
+ t.targetSpanToleranceMm,
70357
+ t.clusterToleranceMm,
70358
+ t.ambiguityMarginMm,
70359
+ t.viewAgreementToleranceMm
70360
+ ].every((value) => Number.isFinite(value) && value >= 0)) {
70160
70361
  return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70161
70362
  }
70162
70363
  const eligibleRecords = function* () {
@@ -70188,7 +70389,7 @@ function analyzeMemberEnd(input) {
70188
70389
  const reasons = [];
70189
70390
  if (result.angleDeg + EPS < SUPPORT_CENTERLINE_V1.minCrossingAngleDeg) reasons.push("crossing-angle-too-small");
70190
70391
  if (result.distanceMm > SUPPORT_CENTERLINE_V1.absoluteReachCapMm + EPS) reasons.push("reach-cap-exceeded");
70191
- const contact = faceContact(ray.origin, ray.direction, result, target, t.faceToleranceMm);
70392
+ const contact = faceContact(ray.origin, ray.direction, result, target, t.faceGapToleranceMm, t.faceOverlapToleranceMm);
70192
70393
  const contactValue = typeof contact === "string" ? void 0 : contact;
70193
70394
  if (typeof contact === "string") reasons.push(contact);
70194
70395
  const key2 = jcs(result.point);
@@ -70394,7 +70595,7 @@ function targetMember(member) {
70394
70595
  function selectedPlans(model, scope) {
70395
70596
  if (scope.kind === "model-3d") return model.plans;
70396
70597
  const ids = scope.kind === "conversion" ? new Set(scope.viewIds) : /* @__PURE__ */ new Set([scope.viewId]);
70397
- return model.plans.filter((plan) => ids.has(plan.sheet)).sort((a, b) => Buffer.compare(Buffer.from(a.sheet), Buffer.from(b.sheet)));
70598
+ return model.plans.filter((plan) => ids.has(planViewId(plan))).sort((a, b) => Buffer.compare(Buffer.from(planViewId(a)), Buffer.from(planViewId(b))));
70398
70599
  }
70399
70600
  function analysisScope(scope, plans) {
70400
70601
  if (scope.kind === "model-3d") return { kind: "3d" };
@@ -70402,11 +70603,11 @@ function analysisScope(scope, plans) {
70402
70603
  if (plan?.viewKind === "elevation" || plan?.viewKind === "section") {
70403
70604
  return {
70404
70605
  kind: "elevation",
70405
- viewId: plan.sheet,
70606
+ viewId: planViewId(plan),
70406
70607
  registered: plans.every((item) => (item.viewKind === "elevation" || item.viewKind === "section") && !!item.sourceRegistration)
70407
70608
  };
70408
70609
  }
70409
- return { kind: "plan", viewId: plan?.sheet ?? (scope.kind === "active-view" ? scope.viewId : scope.viewIds[0] ?? "") };
70610
+ return { kind: "plan", viewId: plan ? planViewId(plan) : scope.kind === "active-view" ? scope.viewId : scope.viewIds[0] ?? "" };
70410
70611
  }
70411
70612
  function observationZ(observation, observationEnd) {
70412
70613
  const z = observationEnd === 0 ? observation.evidence.observed?.fromZ?.value : observation.evidence.observed?.toZ?.value;
@@ -70427,6 +70628,17 @@ var EvidenceNotes = class _EvidenceNotes {
70427
70628
  static key(memberId, end, reason) {
70428
70629
  return `${memberId}\0${end}\0${reason}`;
70429
70630
  }
70631
+ /**
70632
+ * What `publish` collapses duplicates ON — the note text unless a caller supplies something coarser.
70633
+ *
70634
+ * #925's whole property is that ONE shared defect states itself once however many endpoints it
70635
+ * blocks, and that worked because a shared defect produced a byte-identical sentence. A note carrying
70636
+ * a per-endpoint MEASUREMENT breaks it: 500 endpoints on one wrong-scale sheet became 500 distinct
70637
+ * notes and an audit line reading "2 diagnoses; and 498 further distinct diagnoses" for one fault.
70638
+ * So a note whose text varies per endpoint names the part that does NOT — the reason and the
70639
+ * allowance — and one exemplar is published carrying its own numbers.
70640
+ */
70641
+ dedupeKeys = /* @__PURE__ */ new Map();
70430
70642
  /**
70431
70643
  * First note wins for an endpoint+reason — it is the first failure the reader has to fix anyway —
70432
70644
  * EXCEPT when `comprehensive` says this one accounts for every offender at once. A scope-level
@@ -70434,9 +70646,10 @@ var EvidenceNotes = class _EvidenceNotes {
70434
70646
  * sheet that observation came from; publishing the narrower of the two is true but sends the author
70435
70647
  * round the repair-and-re-audit loop once per sheet, which is what #925 is about.
70436
70648
  */
70437
- record(memberId, end, reason, note, comprehensive = false) {
70649
+ record(memberId, end, reason, note, comprehensive = false, dedupeKey) {
70438
70650
  const key2 = _EvidenceNotes.key(memberId, end, reason);
70439
70651
  if (this.byEndpoint.has(key2) && !comprehensive) return;
70652
+ this.dedupeKeys.set(key2, dedupeKey ?? note);
70440
70653
  let text5 = note;
70441
70654
  while (text5.length > 0 && Buffer.byteLength(JSON.stringify(text5), "utf8") > MAX_EVIDENCE_NOTE_JSON_BYTES) {
70442
70655
  text5 = clipQuoted(text5, text5.length - 1);
@@ -70454,27 +70667,33 @@ var EvidenceNotes = class _EvidenceNotes {
70454
70667
  publish(findings, retainedMemberIds) {
70455
70668
  const byReason = /* @__PURE__ */ new Map();
70456
70669
  const seen = /* @__PURE__ */ new Map();
70670
+ const kept = /* @__PURE__ */ new Set();
70457
70671
  for (const finding of findings) {
70458
70672
  if (retainedMemberIds.has(finding.memberId)) continue;
70459
70673
  for (const reason of finding.reasonCodes) {
70460
70674
  if (!ENDPOINT_EVIDENCE_BLOCKING_REASONS.has(reason)) continue;
70461
- const note = this.byEndpoint.get(_EvidenceNotes.key(finding.memberId, finding.end, reason));
70675
+ const endpointKey = _EvidenceNotes.key(finding.memberId, finding.end, reason);
70676
+ const note = this.byEndpoint.get(endpointKey);
70462
70677
  if (note === void 0) continue;
70678
+ const dedupeKey = this.dedupeKeys.get(endpointKey) ?? note;
70463
70679
  let all = seen.get(reason);
70464
70680
  if (!all) {
70465
70681
  all = /* @__PURE__ */ new Set();
70466
70682
  seen.set(reason, all);
70467
70683
  }
70468
- all.add(note);
70684
+ all.add(dedupeKey);
70469
70685
  let notes2 = byReason.get(reason);
70470
70686
  if (!notes2) {
70471
70687
  notes2 = /* @__PURE__ */ new Set();
70472
70688
  byReason.set(reason, notes2);
70473
70689
  }
70474
- if (notes2.size < MAX_NOTES_PER_REASON) notes2.add(note);
70690
+ if (!kept.has(dedupeKey) && notes2.size < MAX_NOTES_PER_REASON) {
70691
+ kept.add(dedupeKey);
70692
+ notes2.add(note);
70693
+ }
70475
70694
  }
70476
70695
  }
70477
- const notes = [...byReason].flatMap(([reason, kept]) => [...kept].sort().map((note) => ({ reason, note }))).sort((a, b) => a.reason.localeCompare(b.reason) || a.note.localeCompare(b.note));
70696
+ const notes = [...byReason].flatMap(([reason, kept2]) => [...kept2].sort().map((note) => ({ reason, note }))).sort((a, b) => a.reason.localeCompare(b.reason) || a.note.localeCompare(b.note));
70478
70697
  const distinct = [...seen.values()].reduce((total, all) => total + all.size, 0);
70479
70698
  return { notes, omitted: distinct - notes.length };
70480
70699
  }
@@ -70483,7 +70702,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70483
70702
  const local = observation.evidence.local.wp[observationEnd];
70484
70703
  const fail3 = (reason, note) => {
70485
70704
  diagnoses.record(memberId, memberEnd, reason, note({
70486
- sheet: `sheet "${quote2(plan.sheet)}"`,
70705
+ sheet: viewLabel(model.plans, plan),
70487
70706
  obs: `observation "${quote2(observation.id)}"`
70488
70707
  }));
70489
70708
  return { kind: "failure", reason };
@@ -70498,7 +70717,12 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70498
70717
  if (plan.viewKind === "plan") {
70499
70718
  const z = observationZ(observation, observationEnd);
70500
70719
  if (!z) return fail3("endpoint-elevation-missing", ({ sheet, obs }) => `${sheet} is a plan view, so this endpoint's elevation must come from ${obs} observed.${observationEnd === 0 ? "fromZ" : "toZ"}, which is absent or unknown`);
70501
- const transformed = sheetPxToWorld(local, { ...plan, modelGrid: model.grid }, z);
70720
+ const transformed = sheetPxToWorld(
70721
+ local,
70722
+ { ...plan, modelGrid: model.grid },
70723
+ z,
70724
+ viewLabel(model.plans ?? [], plan)
70725
+ );
70502
70726
  const point3 = known(transformed);
70503
70727
  return point3 ? { kind: "point", point: point3 } : fail3("view-unregistered", ({ sheet, obs }) => `${sheet} registration maps ${obs} to a non-finite world point`);
70504
70728
  }
@@ -70517,7 +70741,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70517
70741
  }
70518
70742
  } catch (error) {
70519
70743
  if (error instanceof PlanTransformError) return fail3("view-unregistered", () => error.message);
70520
- const identity = `${plan.sheet}/${observation.id}/end-${observationEnd + 1}`;
70744
+ const identity = `${planViewId(plan)}/${observation.id}/end-${observationEnd + 1}`;
70521
70745
  throw new Error(`member-end evidence transform failed unexpectedly for ${identity}`, { cause: error });
70522
70746
  }
70523
70747
  return fail3("view-unregistered", ({ sheet }) => plan.viewKind === "elevation" || plan.viewKind === "section" ? `${sheet} is ${plan.viewKind === "section" ? "a section" : "an elevation"} view with no sourceRegistration, so a drawing observation on it cannot be placed in the model` : `${sheet} has viewKind "${plan.viewKind}"; only a registered plan, elevation or section view can place a drawing observation`);
@@ -70531,25 +70755,36 @@ function finalizedEvidence(accumulator) {
70531
70755
  if (unique.length > SUPPORT_CENTERLINE_V1.maxObservationsPerEnd) {
70532
70756
  throw new MemberEndAnalysisWorkLimitError("Member-end analysis exceeded the per-end drawing-observation budget.");
70533
70757
  }
70534
- const points = new Set(unique.map((origin) => JSON.stringify(origin.observedPoint)));
70535
70758
  const strictest = tolerances.length ? Math.min(...tolerances.map((item) => item.faceToleranceMm)) : void 0;
70759
+ const thresholds = strictest === void 0 ? void 0 : thresholdsFromFaceTolerance(strictest);
70536
70760
  const elevation2 = scopes.find((item) => item.kind === "elevation");
70537
70761
  const selectedScope = elevation2 ?? scopes.find((item) => item.kind === "plan");
70762
+ const spread2 = observedSpreadMm(unique);
70538
70763
  return {
70539
70764
  ...unique.length ? { basis: { kind: "drawing", origins: unique, originSetHash: drawingOriginSetHash(unique) } } : {},
70540
- ...strictest !== void 0 ? { thresholds: {
70541
- faceToleranceMm: strictest,
70542
- targetSpanToleranceMm: strictest,
70543
- clusterToleranceMm: Math.min(strictest, 25.4),
70544
- ambiguityMarginMm: 2 * strictest,
70545
- viewAgreementToleranceMm: strictest
70546
- } } : {},
70765
+ ...thresholds ? { thresholds } : {},
70547
70766
  ...selectedScope ? { analysisScope: selectedScope } : {},
70548
70767
  hasLineage,
70549
70768
  failures: sortedReasons(failures),
70550
- conflict: points.size > 1
70769
+ conflict: spread2 > viewAgreementToleranceOf(thresholds) + AGREEMENT_EPS_MM,
70770
+ spreadMm: spread2
70551
70771
  };
70552
70772
  }
70773
+ function observedSpreadMm(origins) {
70774
+ let worst = 0;
70775
+ for (let i = 0; i < origins.length; i += 1) {
70776
+ for (let j = i + 1; j < origins.length; j += 1) {
70777
+ const a = origins[i].observedPoint, b = origins[j].observedPoint;
70778
+ const gap = Math.hypot(a.x - b.x, a.y - b.y, a.z.known - b.z.known);
70779
+ if (gap > worst) worst = gap;
70780
+ }
70781
+ }
70782
+ return worst;
70783
+ }
70784
+ function viewAgreementToleranceOf(thresholds) {
70785
+ return thresholds ? thresholds.viewAgreementToleranceMm : 0;
70786
+ }
70787
+ var AGREEMENT_EPS_MM = 1e-7;
70553
70788
  function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70554
70789
  const accumulators = /* @__PURE__ */ new Map();
70555
70790
  for (const plan of plans) for (const observation of plan.memberObservations ?? []) {
@@ -70587,7 +70822,7 @@ function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70587
70822
  if (!tolerance) throw new TypeError("schema-valid observation scale did not produce policy thresholds");
70588
70823
  accumulator.origins.push({ observationId: observation.id, lineageId: row.lineageId, observedPoint: observed.point });
70589
70824
  accumulator.tolerances.push(tolerance);
70590
- accumulator.scopes.push(plan.viewKind === "elevation" || plan.viewKind === "section" ? { kind: "elevation", viewId: plan.sheet, registered: !!plan.sourceRegistration } : { kind: "plan", viewId: plan.sheet });
70825
+ accumulator.scopes.push(plan.viewKind === "elevation" || plan.viewKind === "section" ? { kind: "elevation", viewId: planViewId(plan), registered: !!plan.sourceRegistration } : { kind: "plan", viewId: planViewId(plan) });
70591
70826
  }
70592
70827
  }
70593
70828
  return new Map([...accumulators].map(([key2, accumulator]) => [key2, finalizedEvidence(accumulator)]));
@@ -70659,28 +70894,37 @@ function fromDecision(member, end, role) {
70659
70894
  invalidationId: decision.invalidationId
70660
70895
  };
70661
70896
  }
70662
- function unregisteredScopeNote(plans) {
70663
- const offenders = plans.filter((plan) => !((plan.viewKind === "elevation" || plan.viewKind === "section") && !!plan.sourceRegistration));
70897
+ function viewLabel(plans, plan) {
70898
+ const label = planViewLabels(plans).get(planViewId(plan));
70899
+ return label && label !== plan.sheet ? `sheet "${quote2(plan.sheet)}" view "${quote2(planViewId(plan))}"` : `sheet "${quote2(plan.sheet)}"`;
70900
+ }
70901
+ function unregisteredScopeNote(allPlans, scoped) {
70902
+ const offenders = scoped.filter((plan) => !((plan.viewKind === "elevation" || plan.viewKind === "section") && !!plan.sourceRegistration));
70664
70903
  const remedy = offenders.every((plan) => plan.viewKind === "elevation" || plan.viewKind === "section") ? "every selected view in this elevation/section scope needs sourceRegistration before any endpoint in it can be analysed; missing on" : "only an elevation or section view carrying sourceRegistration can place geometry in this scope, and no other view kind can carry one; not usable";
70665
- const named = offenders.slice(0, 3).map((plan) => `"${quote2(plan.sheet)}"`).join(", ");
70904
+ const named = offenders.slice(0, 3).map((plan) => viewLabel(allPlans, plan)).join(", ");
70666
70905
  const more = offenders.length > 3 ? ` and ${offenders.length - 3} more` : "";
70667
70906
  return `${remedy}: ${named}${more}`;
70668
70907
  }
70669
- function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70908
+ function recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70670
70909
  if (subjectReasons.includes("view-unregistered") && analysis.kind === "elevation" && !analysis.registered) {
70671
- diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(plans), true);
70910
+ diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(allPlans, plans), true);
70672
70911
  }
70673
70912
  if (evidence.conflict) {
70674
- const points = new Set((evidence.basis?.origins ?? []).map((origin) => JSON.stringify(origin.observedPoint)));
70913
+ const spread2 = evidence.spreadMm ?? 0;
70914
+ const allowed = viewAgreementToleranceOf(evidence.thresholds);
70675
70915
  diagnoses.record(
70676
70916
  memberId,
70677
70917
  end,
70678
70918
  "cross-view-conflict",
70679
- `a member endpoint's drawing observations disagree \u2014 they place it at ${points.size} different world points, so no single drawing-backed point exists`
70919
+ `a member endpoint's drawing observations disagree \u2014 its ${(evidence.basis?.origins ?? []).length} readings span ${spread2} mm, past the ${allowed} mm two views of one point may differ by, so no single drawing-backed point exists`,
70920
+ false,
70921
+ // Collapsed on the ALLOWANCE, not on the sentence: the spread is this endpoint's own measurement
70922
+ // and would otherwise split one systemic defect into one note per endpoint.
70923
+ `cross-view-conflict\0${allowed}`
70680
70924
  );
70681
70925
  }
70682
70926
  }
70683
- function freshFinding(member, end, role, scope, plans, analysis, evidence, result, diagnoses) {
70927
+ function freshFinding(member, end, role, scope, allPlans, plans, analysis, evidence, result, diagnoses) {
70684
70928
  const currentPoint = end === 0 ? member.from : member.to;
70685
70929
  const geometryOnly = !evidence.basis;
70686
70930
  const completeTargets = targetsOf(result);
@@ -70707,7 +70951,7 @@ function freshFinding(member, end, role, scope, plans, analysis, evidence, resul
70707
70951
  };
70708
70952
  const subjectReasons = result.kind === "not-checkable" ? result.reasons.map((reason) => reasonMap[reason]) : [];
70709
70953
  if (evidence.conflict || subjectReasons.includes("view-unregistered")) {
70710
- recordDerivedNotes(plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70954
+ recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70711
70955
  }
70712
70956
  if (evidence.failures.length) return {
70713
70957
  ...base,
@@ -70823,7 +71067,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70823
71067
  continue;
70824
71068
  }
70825
71069
  if (!analyzed) {
70826
- const finding2 = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, {
71070
+ const finding2 = freshFinding(member, end, role.finding, normalizedScope2, model.plans ?? [], plans, evidence.analysisScope ?? aScope, evidence, {
70827
71071
  kind: "not-checkable",
70828
71072
  reasons: Object.freeze(["subject-geometry-invalid"])
70829
71073
  }, diagnoses);
@@ -70842,7 +71086,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70842
71086
  targets: targetMap,
70843
71087
  consumeExactGeometryTest
70844
71088
  });
70845
- const finding = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, result, diagnoses);
71089
+ const finding = freshFinding(member, end, role.finding, normalizedScope2, model.plans ?? [], plans, evidence.analysisScope ?? aScope, evidence, result, diagnoses);
70846
71090
  if (finding) findings.push(finding);
70847
71091
  }
70848
71092
  }
@@ -70859,6 +71103,35 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70859
71103
  ...omitted > 0 ? { evidenceNotesOmitted: omitted } : {}
70860
71104
  };
70861
71105
  }
71106
+ var coords = (point3) => `(${point3.x}, ${point3.y}, ${point3.z.known})`;
71107
+ var NAMED_MISMATCHES = 3;
71108
+ var LiteralEvidenceMismatches = class {
71109
+ count = 0;
71110
+ worst = [];
71111
+ record(row) {
71112
+ this.count += 1;
71113
+ const at = this.worst.findIndex((seen) => row.gapMm > seen.gapMm);
71114
+ if (at >= 0) this.worst.splice(at, 0, row);
71115
+ else if (this.worst.length < NAMED_MISMATCHES) this.worst.push(row);
71116
+ if (this.worst.length > NAMED_MISMATCHES) this.worst.pop();
71117
+ }
71118
+ /**
71119
+ * One refusal for ALL mismatched ends, carrying the numbers a reader needs to act.
71120
+ *
71121
+ * The old refusal named a single member end and nothing else: no expected value, no submitted
71122
+ * value, no gap and no count. A reader could not tell one bad endpoint from all 430, could not see
71123
+ * that the true cause was three layers upstream in their grid, and spent days on it (#934). Count
71124
+ * first, then the worst offenders with both points and the distance between them.
71125
+ */
71126
+ error() {
71127
+ const named = this.worst.map((row) => `member "${quote2(row.memberId)}" end ${row.end + 1} ` + (row.submitted ? `is ${row.gapMm} mm away \u2014 submitted ${coords(row.submitted)}, drawing ${coords(row.expected)}` : `has no finite point with a known elevation \u2014 drawing ${coords(row.expected)}`));
71128
+ const rest = this.count - named.length;
71129
+ return new ContractPolicyError(
71130
+ `${this.count} reader member ${this.count === 1 ? "end does not match its" : "ends do not match their"} immutable drawing observation by more than ${SUPPORT_CENTERLINE_V1.literalEvidenceToleranceMm} mm: ${named.join("; ")}${rest > 0 ? `; and ${rest} more` : ""}`,
71131
+ "member-end-literal-evidence-mismatch"
71132
+ );
71133
+ }
71134
+ };
70862
71135
  function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE__ */ new Set(), currentModel) {
70863
71136
  const sanitized = cloneModel(literal);
70864
71137
  const currentMembers = currentModel ? new Map(currentModel.members.map((member) => [member.id, member])) : null;
@@ -70897,21 +71170,38 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70897
71170
  // observation. Nothing is published from here — `analyzeSteelMemberEnds` below builds the report.
70898
71171
  new EvidenceNotes()
70899
71172
  );
71173
+ const evidenceMismatches = new LiteralEvidenceMismatches();
70900
71174
  for (const member of sanitized.members) {
70901
71175
  if (existingMemberIds.has(member.id) || !roleOf(member)) continue;
70902
71176
  for (const end of [0, 1]) {
70903
71177
  const evidence = evidenceForEnd(evidenceIndex, member.id, end);
70904
71178
  if (!evidence.basis || evidence.conflict || evidence.failures.length) continue;
70905
- const expected = evidence.basis.origins[0]?.observedPoint;
70906
71179
  const literalPoint = known(end === 0 ? member.from : member.to);
70907
- if (expected && JSON.stringify(literalPoint) !== JSON.stringify(expected)) {
70908
- throw new ContractPolicyError(
70909
- `reader member ${member.id} end ${end + 1} does not match its immutable drawing observation`,
70910
- "member-end-literal-evidence-mismatch"
70911
- );
71180
+ const gapTo = (origin) => literalPoint ? Math.hypot(
71181
+ literalPoint.x - origin.observedPoint.x,
71182
+ literalPoint.y - origin.observedPoint.y,
71183
+ literalPoint.z.known - origin.observedPoint.z.known
71184
+ ) : Number.POSITIVE_INFINITY;
71185
+ let matched = evidence.basis.origins[0];
71186
+ let gapMm = matched ? gapTo(matched) : Number.POSITIVE_INFINITY;
71187
+ for (const origin of evidence.basis.origins) {
71188
+ const candidate = gapTo(origin);
71189
+ if (candidate < gapMm) {
71190
+ matched = origin;
71191
+ gapMm = candidate;
71192
+ }
71193
+ }
71194
+ const expected = matched?.observedPoint;
71195
+ if (!expected) continue;
71196
+ if (!(gapMm <= SUPPORT_CENTERLINE_V1.literalEvidenceToleranceMm)) {
71197
+ evidenceMismatches.record({ memberId: member.id, end, expected, submitted: literalPoint, gapMm });
71198
+ continue;
70912
71199
  }
71200
+ if (end === 0) member.from = expected;
71201
+ else member.to = expected;
70913
71202
  }
70914
71203
  }
71204
+ if (evidenceMismatches.count) throw evidenceMismatches.error();
70915
71205
  const conversion = analyzeSteelMemberEnds(sanitized, conversionScope, existingMemberIds);
70916
71206
  const model = cloneModel(sanitized);
70917
71207
  for (const finding of conversion.findings) {
@@ -70976,7 +71266,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70976
71266
  return { literalContractHash, finalContractHash: asHash(model), model, report, retainedMemberIdsHash };
70977
71267
  }
70978
71268
  function canonicalLineagedViewIds(model) {
70979
- return model.plans.filter((plan) => (plan.memberObservations ?? []).some((observation) => observation.binding.status === "active" && (observation.binding.endpointLineage?.length ?? 0) > 0)).map((plan) => plan.sheet).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
71269
+ return model.plans.filter((plan) => (plan.memberObservations ?? []).some((observation) => observation.binding.status === "active" && (observation.binding.endpointLineage?.length ?? 0) > 0)).map(planViewId).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
70980
71270
  }
70981
71271
  function hashRetainedMemberIds(ids) {
70982
71272
  return asHash([...ids].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))));
@@ -71908,7 +72198,8 @@ function isExactFilterCheckpointShell(value) {
71908
72198
  const filter = doc.filter;
71909
72199
  const filterSheets = filter.sheets.map((raw) => raw && typeof raw === "object" && !Array.isArray(raw) ? raw.sheet : null);
71910
72200
  const planSheets = doc.plans.map((raw) => raw.sheet);
71911
- return contractHash([...filterSheets].sort()) === contractHash([...planSheets].sort());
72201
+ const unique = (values2) => [...new Set(values2.map((v) => JSON.stringify(v ?? null)))].sort();
72202
+ return contractHash(unique(filterSheets)) === contractHash(unique(planSheets));
71912
72203
  }
71913
72204
  function publishNative(staged, origin) {
71914
72205
  assertPublishableSource(staged);
@@ -71967,9 +72258,18 @@ async function recoverAllProjectTransactions(listIds) {
71967
72258
  }
71968
72259
  return out;
71969
72260
  }
72261
+ function preflightNativePublication(appId, projectId, contract, currentType) {
72262
+ try {
72263
+ assertAcceptableContract(contract, { appId, projectId, operation: "put", currentType });
72264
+ } catch (e) {
72265
+ if (e instanceof ContractPolicyError) throw new ContractTransactionError(e.message, e.code);
72266
+ throw e;
72267
+ }
72268
+ }
71970
72269
  async function runNativeInitialRead(opts) {
71971
72270
  return withLifecycleLock("project", opts.projectId, () => {
71972
72271
  assertNoPendingRecovery(opts.projectId);
72272
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
71973
72273
  const current = readContract(opts.appId, opts.projectId);
71974
72274
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) throw new ContractTransactionError(`the first read requires a saved ${STEEL_V2} Drawing Filter shell and candidate`, "contract-type-unsupported");
71975
72275
  if (!isExactFilterCheckpointShell(current)) throw new ContractTransactionError("the first read requires the exact zero-model Drawing Filter checkpoint shell", "filter-checkpoint-not-empty");
@@ -71981,7 +72281,7 @@ async function runNativeInitialRead(opts) {
71981
72281
  if (!checked.ok) throw new ContractTransactionError("This filter no longer matches the attached drawing set. Reload the Drawing Filter and review it again.", "filter-invalid", checked.errors);
71982
72282
  if (contractHash(shell.filter) !== contractHash(candidate.filter)) throw new ContractTransactionError("the submitted model does not contain the exact saved Drawing Filter", "filter-changed");
71983
72283
  if (contractHash(shell.grid) !== contractHash(candidate.grid)) throw new ContractTransactionError("the submitted model changed the saved grid", "shell-changed");
71984
- const fields = ["sheet", "viewKind", "elevation_in", "pt_per_ft", "datum_at", "datum_ref", "control2_at", "control2_ref", "frame", "sourceRegistration"];
72284
+ const fields = ["id", "sheet", "viewKind", "elevation_in", "pt_per_ft", "datum_at", "datum_ref", "control2_at", "control2_ref", "frame", "sourceRegistration"];
71985
72285
  const registration = (doc) => (Array.isArray(doc.plans) ? doc.plans : []).map((raw) => Object.fromEntries(fields.filter((key2) => raw && typeof raw === "object" && key2 in raw).map((key2) => [key2, raw[key2]])));
71986
72286
  if (contractHash(registration(shell)) !== contractHash(registration(candidate))) throw new ContractTransactionError("the submitted model changed saved plan registration", "shell-changed");
71987
72287
  const normalized = normalizeSteelMemberEndsForRead(opts.candidate);
@@ -72018,6 +72318,13 @@ async function runNativeInitialRead(opts) {
72018
72318
  baseHash: input.baseHash,
72019
72319
  generation: `version:${listVersions(opts.projectId).length + 1}`,
72020
72320
  normalization: {
72321
+ // "LITERAL" means before the MEMBER-END normalisation, which is the pair this records; it has
72322
+ // never meant the raw request bytes (roll markers are still un-normalised at this point and
72323
+ // are rewritten later, at the store's door). Since #938 the view-id canonicalisation also
72324
+ // happens upstream of it, for the reason at the top of this function. What matters for the
72325
+ // receipt is that it stays self-consistent, and it does: the audit hashes `normalized.model`
72326
+ // and `assertPublishableSource` compares against `staged.contract`, which IS that document —
72327
+ // on the recovery replay too, since the journal stores the same bytes.
72021
72328
  literalCandidateHash: contractHash(opts.candidate),
72022
72329
  finalCandidateHash: contractHash(normalized.model),
72023
72330
  memberEndReportHash: contractHash(normalized.report)
@@ -72025,6 +72332,7 @@ async function runNativeInitialRead(opts) {
72025
72332
  });
72026
72333
  storedReadAudit = { version: 1, receipt, report: readAuditReport, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
72027
72334
  }
72335
+ preflightNativePublication(opts.appId, opts.projectId, normalized.model, declaredTypeOf(current));
72028
72336
  const versionSource = opts.source || storedReadAudit ? {
72029
72337
  files: opts.source?.files ?? [],
72030
72338
  ...opts.source?.requestId ? { requestId: opts.source.requestId } : {},
@@ -72054,6 +72362,7 @@ async function runNativeInitialRead(opts) {
72054
72362
  async function runNativeRevisionRead(opts) {
72055
72363
  return withLifecycleLock("project", opts.projectId, () => {
72056
72364
  assertNoPendingRecovery(opts.projectId);
72365
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
72057
72366
  const current = readContract(opts.appId, opts.projectId);
72058
72367
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) {
72059
72368
  throw new ContractTransactionError(`a revision read requires an existing ${STEEL_V2} model and a ${STEEL_V2} candidate`, "contract-type-unsupported");
@@ -72064,6 +72373,7 @@ async function runNativeRevisionRead(opts) {
72064
72373
  if (opts.source?.readAudit) {
72065
72374
  assertPublishableSource({ v: 2, appId: opts.appId, projectId: opts.projectId, contract: opts.candidate, message: opts.message, source: opts.source });
72066
72375
  }
72376
+ preflightNativePublication(opts.appId, opts.projectId, opts.candidate, declaredTypeOf(current));
72067
72377
  const dir = (0, import_node_path38.join)(projectDir(opts.projectId), `${PREFIX}${Date.now().toString(36)}-${(0, import_node_crypto27.randomUUID)().slice(0, 8)}`);
72068
72378
  (0, import_node_fs40.mkdirSync)(dir, { recursive: true });
72069
72379
  write(phase(dir, "000-begin"), { v: 2, expected: contractHash(current), at: (/* @__PURE__ */ new Date()).toISOString() });
@@ -72341,12 +72651,11 @@ function ctxFor(opts, storedType) {
72341
72651
  }
72342
72652
  function acceptContract(doc, opts) {
72343
72653
  const op = opts.operation ?? "read";
72344
- const needsStored = MUTATING_OPS.has(op);
72654
+ const needsStored = isMutatingOperation(op);
72345
72655
  const storedType = opts.currentType !== void 0 ? opts.currentType : needsStored ? storedTypeOf(opts) : null;
72346
72656
  assertAcceptableContract(doc, ctxFor(opts, storedType));
72347
- return doc;
72657
+ return normalisePlanViewIds(doc);
72348
72658
  }
72349
- var MUTATING_OPS = /* @__PURE__ */ new Set(["put", "import", "duplicate", "bake"]);
72350
72659
  function storedTypeOf(opts) {
72351
72660
  const current = readContract(opts.appId, opts.projectId);
72352
72661
  return current == null ? null : declaredTypeOf(current);
@@ -72581,7 +72890,8 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72581
72890
  let publication;
72582
72891
  try {
72583
72892
  publication = writeContract(appId, finalContract, projectId, {
72584
- operation: "put",
72893
+ // `restore` for a document coming back out of history; `put` for everything that composes one.
72894
+ operation: origin.origin === "contract-generation" && origin.restoring ? "restore" : "put",
72585
72895
  currentType: storedType
72586
72896
  });
72587
72897
  } catch (e) {
@@ -72602,7 +72912,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72602
72912
  } else if (declaredTypeOf(finalContract) === STEEL_V2) {
72603
72913
  persistConnectionReviewForWrite({
72604
72914
  projectId: projectId ?? null,
72605
- finalAfter: normaliseRollMarkers(finalContract),
72915
+ finalAfter: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72606
72916
  origin: reviewOriginForGatewayWrite(origin.origin)
72607
72917
  });
72608
72918
  }
@@ -72615,7 +72925,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72615
72925
  // review's `self` baseline was recorded against the un-normalised doc and read back drifted, and
72616
72926
  // `member-end-routes` staged its undo token over a hash the store would never reproduce, so Undo
72617
72927
  // silently never offered itself. Idempotent, and free when nothing carried a marker.
72618
- contract: normaliseRollMarkers(finalContract),
72928
+ contract: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72619
72929
  invalidatedWorkPointDecisions: prepared.invalidated,
72620
72930
  ...revalidation ? { revalidation } : {}
72621
72931
  };
@@ -72636,10 +72946,11 @@ function writeConnectionPlacementChecked(appId, doc, projectId, ifMatch, placeme
72636
72946
  [CONNECTION_PLACEMENT_AUTHORITY]: true
72637
72947
  });
72638
72948
  }
72639
- function writeContractGenerationChecked(appId, doc, projectId, why) {
72949
+ function writeContractGenerationChecked(appId, doc, projectId, why, opts = {}) {
72640
72950
  return writeContractChecked(appId, doc, projectId, {
72641
72951
  origin: "contract-generation",
72642
72952
  why,
72953
+ restoring: opts.restoring,
72643
72954
  [CONTRACT_GENERATION_AUTHORITY]: true
72644
72955
  });
72645
72956
  }
@@ -73851,7 +74162,12 @@ var REGISTRY = /* @__PURE__ */ new Map([
73851
74162
  ["$.plans[]", { disposition: "propose", note: "a sheet" }],
73852
74163
  // The MATCH KEY, exactly like `$.members[].id`: plans are paired by sheet before diffing, so this can
73853
74164
  // never differ within a pair. Listed so the coverage test sees a decision.
73854
- ["$.plans[].sheet", { disposition: "issue", note: "the sheet name, which pairs the documents \u2014 a change to it is an add plus a remove, not an edit" }],
74165
+ // THE MATCH KEY is the view id (#938): plans are paired by it before diffing, so a change to it is an
74166
+ // add plus a remove rather than an edit.
74167
+ ["$.plans[].id", { disposition: "issue", note: "the view id, which pairs the documents \u2014 a change to it is an add plus a remove, not an edit" }],
74168
+ // The PAGE a view was read off is evidence about where the read was made, and evidence is written
74169
+ // once. It no longer pairs the documents, but it is no more revisable for that.
74170
+ ["$.plans[].sheet", { disposition: "issue", note: "the page this view was read from, which is evidence about the read rather than a field to revise" }],
73855
74171
  ["$.plans[].viewKind", { disposition: "propose", note: "the reader's explicit sheet classification; unsupported kinds remain stored but are refused by their transform" }],
73856
74172
  // The canonical registration a revision read may genuinely move: where the cut plane sits, which grid
73857
74173
  // intersection anchors the sheet, what it is called, and which members it presents.
@@ -74071,6 +74387,8 @@ function revisionFramePreservesPlacement(before, after, memberId) {
74071
74387
  }
74072
74388
  }
74073
74389
  function stageRevisionRead(current, incoming) {
74390
+ current = normalisePlanViewIds(current);
74391
+ incoming = normalisePlanViewIds(incoming);
74074
74392
  const accepted = [];
74075
74393
  const bindingUpdates = [];
74076
74394
  const bindingProposals = [];
@@ -74080,7 +74398,17 @@ function stageRevisionRead(current, incoming) {
74080
74398
  const curObs = observationsOf(current);
74081
74399
  const incMembers = new Map((incoming.members ?? []).map((m) => [m.id, m]));
74082
74400
  const curMembers = new Map((current.members ?? []).map((m) => [m.id, m]));
74083
- const currentSheets = new Set((current.plans ?? []).map((p) => p.sheet));
74401
+ const currentViewIds = new Set((current.plans ?? []).map(planViewId));
74402
+ const labelSiblings = (() => {
74403
+ const byId = /* @__PURE__ */ new Map();
74404
+ for (const plan of [...current.plans ?? [], ...incoming.plans ?? []]) {
74405
+ const id = planViewId(plan);
74406
+ if (id && !byId.has(id)) byId.set(id, plan);
74407
+ }
74408
+ return [...byId.values()];
74409
+ })();
74410
+ const viewLabels = planViewLabels(labelSiblings);
74411
+ const viewLabelOf = (plan) => viewLabels.get(planViewId(plan)) ?? plan.sheet;
74084
74412
  const ownIssues = /* @__PURE__ */ new Map();
74085
74413
  const order = [];
74086
74414
  const seenIncoming = /* @__PURE__ */ new Set();
@@ -74098,8 +74426,8 @@ function stageRevisionRead(current, incoming) {
74098
74426
  bad(`${path}.evidence.source.sheet`, "observation-sheet-missing", "evidence names no source sheet, so it cannot be filed against a plan");
74099
74427
  } else if (citedSheet !== plan.sheet) {
74100
74428
  bad(`${path}.evidence.source.sheet`, "observation-sheet-mismatch", `evidence cites sheet "${citedSheet}" but lives on plan "${plan.sheet}"`);
74101
- } else if (!currentSheets.has(plan.sheet)) {
74102
- bad(`${path}.evidence.source.sheet`, "observation-depends-on-proposal", `sheet "${plan.sheet}" does not exist yet; its evidence cannot be accepted until the plan is confirmed`);
74429
+ } else if (!currentViewIds.has(planViewId(plan))) {
74430
+ bad(`${path}.evidence.source.sheet`, "observation-depends-on-proposal", `view "${planViewId(plan)}" does not exist yet; its evidence cannot be accepted until the plan is confirmed`);
74103
74431
  }
74104
74432
  for (const id of obs.binding?.memberIds ?? []) {
74105
74433
  if (curMembers.has(id)) continue;
@@ -74116,7 +74444,7 @@ function stageRevisionRead(current, incoming) {
74116
74444
  const admissible = new Set([...ownIssues].filter(([, v]) => v.length === 0).map(([k]) => k));
74117
74445
  const landing = [];
74118
74446
  const pendingUpdates = [];
74119
- for (const { obs, path } of order) {
74447
+ for (const { plan, obs, path } of order) {
74120
74448
  const mine = ownIssues.get(obs.id) ?? [];
74121
74449
  issues.push(...mine);
74122
74450
  if (mine.length) continue;
@@ -74130,7 +74458,7 @@ function stageRevisionRead(current, incoming) {
74130
74458
  if (rejected) continue;
74131
74459
  const existing = curObs.get(obs.id);
74132
74460
  if (!existing) {
74133
- landing.push({ obs, path });
74461
+ landing.push({ obs, path, viewId: planViewId(plan) });
74134
74462
  continue;
74135
74463
  }
74136
74464
  if (json(existing.obs.evidence) !== json(obs.evidence)) {
@@ -74201,9 +74529,9 @@ function stageRevisionRead(current, incoming) {
74201
74529
  candidates.delete(id);
74202
74530
  }
74203
74531
  }
74204
- for (const { obs, path } of landing) {
74532
+ for (const { obs, path, viewId } of landing) {
74205
74533
  if (candidates.has(obs.id)) {
74206
- accepted.push(withoutForgedVerification(obs, bindingProposals));
74534
+ accepted.push({ viewId, observation: withoutForgedVerification(obs, bindingProposals) });
74207
74535
  continue;
74208
74536
  }
74209
74537
  const orphaned = orphanedBy.get(obs.id);
@@ -74285,38 +74613,38 @@ function stageRevisionRead(current, incoming) {
74285
74613
  }
74286
74614
  if (fields.length) proposals.push({ kind: "member-changed", memberId: id, fields });
74287
74615
  }
74288
- const incomingSheets = new Set((incoming.plans ?? []).map((p) => p.sheet));
74289
- for (const sheet of currentSheets) {
74290
- if (!incomingSheets.has(sheet)) {
74616
+ const incomingViewIds = new Set((incoming.plans ?? []).map(planViewId));
74617
+ for (const viewId of currentViewIds) {
74618
+ if (!incomingViewIds.has(viewId)) {
74291
74619
  add(
74292
- `$.plans[${sheet}]`,
74620
+ `$.plans[${viewId}]`,
74293
74621
  "path-refused",
74294
- `sheet "${sheet}" is missing from the revision read; a revision may not remove a sheet \u2014 plan-level revision is not staged yet`
74622
+ `view "${viewId}" is missing from the revision read; a revision may not remove a drawing view \u2014 plan-level revision is not staged yet`
74295
74623
  );
74296
74624
  }
74297
74625
  }
74298
74626
  for (const id of curMembers.keys()) {
74299
74627
  if (!incMembers.has(id)) proposals.push({ kind: "member-removed", memberId: id });
74300
74628
  }
74301
- const curPlans = new Map((current.plans ?? []).map((p) => [p.sheet, p]));
74302
- const sheetCounts = /* @__PURE__ */ new Map();
74303
- for (const plan of incoming.plans ?? []) sheetCounts.set(plan.sheet, (sheetCounts.get(plan.sheet) ?? 0) + 1);
74304
- for (const [sheet, n] of sheetCounts) {
74629
+ const curPlans = new Map((current.plans ?? []).map((p) => [planViewId(p), p]));
74630
+ const viewIdCounts = /* @__PURE__ */ new Map();
74631
+ for (const plan of incoming.plans ?? []) viewIdCounts.set(planViewId(plan), (viewIdCounts.get(planViewId(plan)) ?? 0) + 1);
74632
+ for (const [viewId, n] of viewIdCounts) {
74305
74633
  if (n < 2) continue;
74306
74634
  add(
74307
- `$.plans[${sheet}]`,
74308
- "plan-sheet-duplicate",
74309
- `sheet "${sheet}" appears ${n} times in the revision read; a sheet names one plan, so which of the copies is the revision has no answer \u2014 none of them is staged`
74635
+ `$.plans[${viewId}]`,
74636
+ "plan-view-id-duplicate",
74637
+ `view "${viewId}" appears ${n} times in the revision read; a view id names one drawing view, so which of the copies is the revision has no answer \u2014 none of them is staged`
74310
74638
  );
74311
74639
  }
74312
74640
  for (const plan of incoming.plans ?? []) {
74313
- if ((sheetCounts.get(plan.sheet) ?? 0) > 1) continue;
74314
- const existing = curPlans.get(plan.sheet);
74641
+ if ((viewIdCounts.get(planViewId(plan)) ?? 0) > 1) continue;
74642
+ const existing = curPlans.get(planViewId(plan));
74315
74643
  if (existing) {
74316
74644
  const planFields = [];
74317
74645
  for (const key2 of /* @__PURE__ */ new Set([...Object.keys(existing), ...Object.keys(plan)])) {
74318
74646
  if (key2 === "memberObservations") continue;
74319
- if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${plan.sheet}].${key2}`))) continue;
74647
+ if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${planViewId(plan)}].${key2}`))) continue;
74320
74648
  const b = existing[key2];
74321
74649
  const a = plan[key2];
74322
74650
  const entry2 = entryFor(`$.plans[].${key2}`);
@@ -74324,17 +74652,17 @@ function stageRevisionRead(current, incoming) {
74324
74652
  if (entry2?.disposition === "propose") planFields.push({ key: key2, before: b, after: a });
74325
74653
  else {
74326
74654
  add(
74327
- `$.plans[${plan.sheet}].${key2}`,
74655
+ `$.plans[${planViewId(plan)}].${key2}`,
74328
74656
  "path-refused",
74329
- `"${key2}" on an existing sheet may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
74657
+ `"${key2}" on an existing drawing view may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
74330
74658
  );
74331
74659
  }
74332
74660
  }
74333
- if (planFields.length) proposals.push({ kind: "plan-changed", sheet: plan.sheet, fields: planFields });
74661
+ if (planFields.length) proposals.push({ kind: "plan-changed", viewId: planViewId(plan), sheet: plan.sheet, viewLabel: viewLabelOf(plan), fields: planFields });
74334
74662
  continue;
74335
74663
  }
74336
74664
  const { memberObservations: _refused, ...sheetOnly } = plan;
74337
- proposals.push({ kind: "plan-added", sheet: plan.sheet, plan: sheetOnly });
74665
+ proposals.push({ kind: "plan-added", viewId: planViewId(plan), sheet: plan.sheet, viewLabel: viewLabelOf(plan), plan: sheetOnly });
74338
74666
  }
74339
74667
  const HANDLED_ROOT = /* @__PURE__ */ new Set(["members", "plans"]);
74340
74668
  const curRoot = current;
@@ -74447,18 +74775,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74447
74775
  break;
74448
74776
  }
74449
74777
  case "plan-added": {
74450
- if (p.plan?.sheet !== p.sheet) {
74451
- throw new RevisionApplyError(`applyStagedRevision: the staged addition names sheet "${p.sheet}" but carries a plan for "${p.plan?.sheet}" \u2014 staging builds both from one plan, so this envelope was not produced by it`);
74778
+ if (p.plan?.sheet !== p.sheet || planViewId(p.plan) !== p.viewId) {
74779
+ throw new RevisionApplyError(`applyStagedRevision: the staged addition names view "${p.viewId}" on sheet "${p.sheet}" but carries a plan for view "${planViewId(p.plan)}" on sheet "${p.plan?.sheet}" \u2014 staging builds both from one plan, so this envelope was not produced by it`);
74452
74780
  }
74453
- if (next.plans.some((pl2) => pl2.sheet === p.plan.sheet)) {
74454
- throw new RevisionApplyError(`applyStagedRevision: sheet "${p.sheet}" already exists, so the staged addition does not describe this document`);
74781
+ if (next.plans.some((pl2) => planViewId(pl2) === p.viewId)) {
74782
+ throw new RevisionApplyError(`applyStagedRevision: view "${p.viewId}" already exists, so the staged addition does not describe this document`);
74455
74783
  }
74456
74784
  next.plans.push(structuredClone(p.plan));
74457
74785
  break;
74458
74786
  }
74459
74787
  case "plan-changed": {
74460
- const pl2 = next.plans.find((x) => x.sheet === p.sheet);
74461
- if (!pl2) throw new RevisionApplyError(`applyStagedRevision: sheet "${p.sheet}" is not in this document, so the staged change does not describe it`);
74788
+ const pl2 = next.plans.find((x) => planViewId(x) === p.viewId);
74789
+ if (!pl2) throw new RevisionApplyError(`applyStagedRevision: view "${p.viewId}" is not in this document, so the staged change does not describe it`);
74462
74790
  for (const f of p.fields) {
74463
74791
  if (!writableLeaf(`$.plans[].${f.key}`)) {
74464
74792
  throw new RevisionApplyError(`applyStagedRevision: "${f.key}" is not a plan field a revision read may change \u2014 the staged proposal does not match the registry`);
@@ -74483,10 +74811,9 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74483
74811
  }
74484
74812
  }
74485
74813
  }
74486
- const bySheet = /* @__PURE__ */ new Map();
74487
- for (const obs of staged.accepted) {
74488
- const sheet = obs.evidence.source.sheet;
74489
- bySheet.set(sheet, [...bySheet.get(sheet) ?? [], obs]);
74814
+ const byView = /* @__PURE__ */ new Map();
74815
+ for (const { viewId, observation } of staged.accepted) {
74816
+ byView.set(viewId, [...byView.get(viewId) ?? [], observation]);
74490
74817
  }
74491
74818
  const updates = /* @__PURE__ */ new Map();
74492
74819
  for (const u of [...staged.bindingUpdates, ...pick(staged.bindingProposals, selection.bindingProposals, "bindingProposals")]) {
@@ -74496,18 +74823,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74496
74823
  updates.set(u.observationId, u.to);
74497
74824
  }
74498
74825
  for (const plan of next.plans) {
74499
- const arriving = bySheet.get(plan.sheet);
74826
+ const arriving = byView.get(planViewId(plan));
74500
74827
  if (arriving?.length) {
74501
74828
  plan.memberObservations = [...plan.memberObservations ?? [], ...structuredClone(arriving)];
74502
- bySheet.delete(plan.sheet);
74829
+ byView.delete(planViewId(plan));
74503
74830
  }
74504
74831
  for (const obs of plan.memberObservations ?? []) {
74505
74832
  const to = updates.get(obs.id);
74506
74833
  if (to) obs.binding = structuredClone(to);
74507
74834
  }
74508
74835
  }
74509
- if (bySheet.size > 0) {
74510
- throw new Error(`applyStagedRevision: accepted evidence for unknown sheet(s) ${[...bySheet.keys()].join(", ")} \u2014 staging should have refused these`);
74836
+ if (byView.size > 0) {
74837
+ throw new Error(`applyStagedRevision: accepted evidence for unknown view(s) ${[...byView.keys()].join(", ")} \u2014 staging should have refused these`);
74511
74838
  }
74512
74839
  return next;
74513
74840
  }
@@ -78808,7 +79135,7 @@ function registerConnectionRoutes(app) {
78808
79135
  }
78809
79136
 
78810
79137
  // steel-intersection-ref.ts
78811
- var label = (v) => {
79138
+ var axisId = (v) => {
78812
79139
  if (typeof v !== "string") return null;
78813
79140
  const t = v.trim();
78814
79141
  return t.length > 0 ? t : null;
@@ -78817,19 +79144,19 @@ var isObj7 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
78817
79144
  function intersectionRef(v) {
78818
79145
  if (v === void 0 || v === null) return { state: "absent" };
78819
79146
  if (isObj7(v)) {
78820
- const unknown = Object.keys(v).filter((k) => k !== "axis_x" && k !== "axis_y");
79147
+ const unknown = Object.keys(v).filter((k) => k !== "xAxisId" && k !== "yAxisId");
78821
79148
  if (unknown.length) {
78822
- return { state: "invalid", why: `an intersection has only \`axis_x\` and \`axis_y\` \u2014 ${unknown.map((k) => `\`${k}\``).join(", ")} ${unknown.length > 1 ? "are" : "is"} not recognised` };
79149
+ return { state: "invalid", why: `an intersection has only \`xAxisId\` and \`yAxisId\` \u2014 ${unknown.map((k) => `\`${k}\``).join(", ")} ${unknown.length > 1 ? "are" : "is"} not recognised${unknown.some((k) => k === "axis_x" || k === "axis_y") ? "; registration names grid axis IDS now, never labels" : ""}` };
78823
79150
  }
78824
- const x = label(v.axis_x), y = label(v.axis_y);
79151
+ const x = axisId(v.xAxisId), y = axisId(v.yAxisId);
78825
79152
  if (x && y) return { state: "valid", x, y };
78826
- const missing = [!x ? "axis_x" : null, !y ? "axis_y" : null].filter(Boolean).join(" and ");
78827
- return { state: "invalid", why: `${missing} must each be a non-blank label` };
79153
+ const missing = [!x ? "xAxisId" : null, !y ? "yAxisId" : null].filter(Boolean).join(" and ");
79154
+ return { state: "invalid", why: `${missing} must each be a non-blank grid axis id` };
78828
79155
  }
78829
- return { state: "invalid", why: `a ${Array.isArray(v) ? "list" : typeof v} names no grid intersection; expected { axis_x, axis_y }` };
79156
+ return { state: "invalid", why: `a ${Array.isArray(v) ? "list" : typeof v} names no grid intersection; expected { xAxisId, yAxisId }` };
78830
79157
  }
78831
79158
  function canonicalRef(r) {
78832
- return { axis_x: r.x, axis_y: r.y };
79159
+ return { xAxisId: r.x, yAxisId: r.y };
78833
79160
  }
78834
79161
 
78835
79162
  // steel-prepass-route.ts
@@ -78890,21 +79217,30 @@ function registerSteelPrepassRoute(app, deps) {
78890
79217
  }
78891
79218
  let doc = structuredClone(current);
78892
79219
  const plans = Array.isArray(doc.plans) ? doc.plans.filter(isObj8) : [];
78893
- const names2 = plans.map((plan) => String(plan.sheet ?? ""));
79220
+ const names2 = plans.map((plan) => rawPlanViewId(plan) ?? "");
78894
79221
  const missing = Object.keys(sheets).filter((sheet) => !names2.includes(sheet));
78895
- if (missing.length) return reply.status(400).send({ ok: false, code: "prepass-unknown-sheet", error: `unknown sheet: ${missing.join(", ")}` });
79222
+ if (missing.length) return reply.status(400).send({ ok: false, code: "prepass-unknown-sheet", error: `unknown drawing view: ${missing.join(", ")}` });
78896
79223
  const duplicates = Object.keys(sheets).filter((sheet) => names2.filter((name) => name === sheet).length > 1);
78897
- if (duplicates.length) return reply.status(400).send({ ok: false, code: "prepass-duplicate-sheet", error: `duplicate sheet: ${duplicates.join(", ")}` });
79224
+ if (duplicates.length) return reply.status(400).send({ ok: false, code: "prepass-duplicate-sheet", error: `duplicate drawing view: ${duplicates.join(", ")}` });
78898
79225
  let applied = false;
78899
79226
  if (body.filter !== void 0) {
78900
79227
  doc.filter = body.filter;
78901
79228
  applied = true;
78902
79229
  }
78903
79230
  const refErrors = [];
79231
+ const viewLabels = planViewLabels(plans);
78904
79232
  for (const plan of plans) {
78905
- const sheet = String(plan.sheet ?? "");
79233
+ const sheet = rawPlanViewId(plan) ?? "";
79234
+ const viewName = viewLabels.get(sheet) ?? sheet;
78906
79235
  const patch2 = sheets[sheet];
78907
79236
  if (!isObj8(patch2)) continue;
79237
+ if (plan.viewKind !== "plan" && PLAN_KEYS.some((key2) => patch2[key2] !== void 0)) {
79238
+ return reply.status(400).send({
79239
+ ok: false,
79240
+ code: "prepass-plan-controls-on-non-plan-view",
79241
+ error: `sheet "${viewName}" is a ${String(plan.viewKind ?? "unclassified")} view; ${PLAN_KEYS.filter((key2) => patch2[key2] !== void 0).join(", ")} register a plan and do nothing here \u2014 a non-plan view registers through sourceRegistration`
79242
+ });
79243
+ }
78908
79244
  for (const key2 of PLAN_KEYS) {
78909
79245
  if (patch2[key2] === void 0) continue;
78910
79246
  if (key2 === "datum_ref" || key2 === "control2_ref") {
@@ -78924,7 +79260,7 @@ function registerSteelPrepassRoute(app, deps) {
78924
79260
  return reply.status(400).send({
78925
79261
  ok: false,
78926
79262
  code: "prepass-ref-unreadable",
78927
- error: `Grid references must use { axis_x, axis_y }: ${refErrors.join(", ")}. Nothing was written.`
79263
+ error: `Grid references must use { xAxisId, yAxisId }: ${refErrors.join(", ")}. Nothing was written.`
78928
79264
  });
78929
79265
  }
78930
79266
  if (request) {
@@ -78938,7 +79274,8 @@ function registerSteelPrepassRoute(app, deps) {
78938
79274
  }
78939
79275
  }
78940
79276
  const filterSheets = filterSheetsOf(doc);
78941
- const unregistered = filterSheets.map((sheet) => typeof sheet.sheet === "string" ? sheet.sheet.trim() : "").filter((sheet) => sheet && !names2.includes(sheet));
79277
+ const registeredPages = new Set(plans.map((plan) => String(plan.sheet ?? "")));
79278
+ const unregistered = filterSheets.map((sheet) => typeof sheet.sheet === "string" ? sheet.sheet.trim() : "").filter((sheet) => sheet && !registeredPages.has(sheet));
78942
79279
  if (unregistered.length) {
78943
79280
  return reply.status(400).send({
78944
79281
  ok: false,
@@ -84863,8 +85200,8 @@ function bomTable(bom, selection = DEFAULT_BOM_COLUMNS) {
84863
85200
  cells[m.label] = priced.reduce((t, r) => t + (Number(r.cells[m.label]) || 0), 0);
84864
85201
  }
84865
85202
  if (columns.some((c) => c.id === "length")) {
84866
- const label2 = BOM_COLUMNS.find((c) => c.id === "length").label;
84867
- cells[label2] = round1(Number(cells[label2]) || 0);
85203
+ const label = BOM_COLUMNS.find((c) => c.id === "length").label;
85204
+ cells[label] = round1(Number(cells[label]) || 0);
84868
85205
  }
84869
85206
  rows2.push({ kind: "total", cells });
84870
85207
  }
@@ -84872,7 +85209,7 @@ function bomTable(bom, selection = DEFAULT_BOM_COLUMNS) {
84872
85209
  if (!rfi.length) return { columns: labels, rows: rows2 };
84873
85210
  const profileLabel = BOM_COLUMNS.find((c) => c.id === "profile").label;
84874
85211
  const qtyLabel = BOM_COLUMNS.find((c) => c.id === "qty").label;
84875
- const locators = [["profile", profileLabel], ["qty", qtyLabel]].filter(([id]) => !selection.includes(id)).map(([, label2]) => label2);
85212
+ const locators = [["profile", profileLabel], ["qty", qtyLabel]].filter(([id]) => !selection.includes(id)).map(([, label]) => label);
84876
85213
  const unionColumns = [...locators, ...RFI_COLUMNS];
84877
85214
  const blanks = Object.fromEntries(unionColumns.map((c) => [c, ""]));
84878
85215
  return {
@@ -85474,7 +85811,8 @@ function currentApprovedSnapshot(projectId, version) {
85474
85811
  const latestHash = contractHash(latestContract);
85475
85812
  assertOwned(latest, latestHash);
85476
85813
  const draft = readAcceptedForRequest(project.app, projectId, "read");
85477
- const dirtySinceApproval = draft == null || contractHash(draft) !== latestHash;
85814
+ const comparable = comparableContractHash;
85815
+ const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
85478
85816
  return {
85479
85817
  project,
85480
85818
  version: row,
@@ -85628,6 +85966,7 @@ function atomicChanged(opts, groups) {
85628
85966
  groups.push(group);
85629
85967
  return atomicNode(group.id, opts.before, opts.after);
85630
85968
  }
85969
+ var parentLabel = (opts) => opts.parentLabel ?? String(opts.parent);
85631
85970
  function keyedCollection(opts) {
85632
85971
  const beforePresent = opts.before !== void 0;
85633
85972
  const afterPresent = opts.after !== void 0;
@@ -85639,7 +85978,7 @@ function keyedCollection(opts) {
85639
85978
  entity: "collection",
85640
85979
  category: opts.category,
85641
85980
  headline: `${opts.category} collection`,
85642
- location: opts.parent ? String(opts.parent) : "Model",
85981
+ location: opts.parent ? parentLabel(opts) : "Model",
85643
85982
  before: beforePresent ? opts.before : ABSENT,
85644
85983
  after: afterPresent ? opts.after : ABSENT
85645
85984
  }, opts.groups) };
@@ -85672,7 +86011,7 @@ function keyedCollection(opts) {
85672
86011
  entity: key2,
85673
86012
  category: opts.category,
85674
86013
  headline: opts.labelOf(isObj9(bv) ? bv : av, key2),
85675
- location: opts.parent ? `${String(opts.parent)} \xB7 ${key2}` : key2,
86014
+ location: opts.parent ? `${parentLabel(opts)} \xB7 ${key2}` : key2,
85676
86015
  before: av,
85677
86016
  after: bv,
85678
86017
  references: isObj9(bv) ? opts.referencesOf?.(bv) : []
@@ -85725,6 +86064,7 @@ function nestedEntity(base, draft, opts, groups) {
85725
86064
  type: opts.type,
85726
86065
  collection: n.collection,
85727
86066
  parent: opts.identity,
86067
+ parentLabel: opts.identityLabel,
85728
86068
  category: n.category,
85729
86069
  before: base[n.key],
85730
86070
  after: draft[n.key],
@@ -85817,6 +86157,15 @@ function unionDependencies(groups) {
85817
86157
  for (const id of ids) groups.find((group) => group.id === id).dependencyGroup = digest2;
85818
86158
  }
85819
86159
  }
86160
+ function planLabeller(base, draft) {
86161
+ const byId = /* @__PURE__ */ new Map();
86162
+ for (const row of [...arr4(isObj9(draft) ? draft.plans : null), ...arr4(isObj9(base) ? base.plans : null)]) {
86163
+ const key2 = rawPlanViewId(row);
86164
+ if (key2 !== null && !byId.has(key2)) byId.set(key2, row);
86165
+ }
86166
+ const labels = planViewLabels([...byId.values()]);
86167
+ return (_row, key2) => `Sheet ${labels.get(key2) ?? key2}`;
86168
+ }
85820
86169
  function fallback(base, draft, type, reason) {
85821
86170
  const group = groupOf({
85822
86171
  type,
@@ -85852,20 +86201,21 @@ function buildKnown(base, draft, type) {
85852
86201
  groups,
85853
86202
  referencesOf: (v) => arr4(v.ends).flatMap((end) => isObj9(end) && typeof end.conn === "string" ? [token(type, "connection", null, end.conn)] : [])
85854
86203
  }));
86204
+ const planLabel = planLabeller(base, draft);
85855
86205
  add("plans", keyedCollection({
85856
86206
  type,
85857
86207
  collection: "plan",
85858
86208
  category: "Sheet",
85859
86209
  before: base.plans,
85860
86210
  after: draft.plans,
85861
- keyOf: (v) => typeof v.sheet === "string" ? v.sheet : null,
85862
- labelOf: (_v2, key2) => `Sheet ${key2}`,
86211
+ keyOf: (v) => rawPlanViewId(v),
86212
+ labelOf: planLabel,
85863
86213
  groups,
85864
86214
  buildItem: (a, b, key2) => nestedEntity(a, b, {
85865
86215
  type,
85866
86216
  collection: "plan",
85867
86217
  identity: key2,
85868
- identityLabel: `Sheet ${key2}`,
86218
+ identityLabel: planLabel(a ?? b ?? {}, key2),
85869
86219
  nested: [
85870
86220
  {
85871
86221
  key: "memberObservations",
@@ -86223,6 +86573,11 @@ function mergeContractForward(base, latest, draft, resolutions = {}) {
86223
86573
  return { merged, conflicts };
86224
86574
  }
86225
86575
 
86576
+ // approval-forward-merge.ts
86577
+ function mergeApprovalForward(base, latest, draft, resolutions = {}) {
86578
+ return mergeContractForward(base, normalisePlanViewIds(latest), draft, resolutions);
86579
+ }
86580
+
86226
86581
  // approval-review-service.ts
86227
86582
  function prepareProjectApprovalReview(projectId, deps) {
86228
86583
  const project = getProject(projectId);
@@ -86255,7 +86610,7 @@ function prepareProjectApprovalReview(projectId, deps) {
86255
86610
  if (manifest?.workingBase && snapshot.contractHash !== manifest.workingBase.hash) {
86256
86611
  throw new WorkspaceSnapshotError(409, "the working revision base proof no longer matches History; keep it as a checkpoint and start again");
86257
86612
  }
86258
- baseContract = snapshot.contract;
86613
+ baseContract = normalisePlanViewIds(snapshot.contract);
86259
86614
  base = { version: snapshot.version.n, hash: snapshot.contractHash, approvedAt: snapshot.currentApprovedAt ?? void 0 };
86260
86615
  }
86261
86616
  const draftHash = contractHash(draft);
@@ -86275,11 +86630,11 @@ function prepareProjectApprovalReview(projectId, deps) {
86275
86630
  });
86276
86631
  if (base && row && base.version !== row.n) {
86277
86632
  const latest = currentApprovedSnapshot(projectId);
86278
- const preview2 = mergeContractForward(baseContract, latest.contract, draft);
86633
+ const preview2 = mergeApprovalForward(baseContract, latest.contract, draft);
86279
86634
  const groupsByPath = /* @__PURE__ */ new Map();
86280
86635
  for (const group of prepared.partition.groups) {
86281
86636
  const single = prepared.partition.materialize([group.id]);
86282
- for (const conflict of mergeContractForward(baseContract, latest.contract, single).conflicts) {
86637
+ for (const conflict of mergeApprovalForward(baseContract, latest.contract, single).conflicts) {
86283
86638
  const ids = groupsByPath.get(conflict.path) ?? [];
86284
86639
  ids.push(group.id);
86285
86640
  groupsByPath.set(conflict.path, ids);
@@ -86756,9 +87111,9 @@ function assertSameVolume(a, b) {
86756
87111
  }
86757
87112
  if (aDev !== bDev) throw new FilePublicationError("publication paths are not on the same volume", "different-volume", [a, b]);
86758
87113
  }
86759
- function uniqueArtifact(dir, label2, livePath) {
87114
+ function uniqueArtifact(dir, label, livePath) {
86760
87115
  (0, import_node_fs56.mkdirSync)(dir, { recursive: true });
86761
- return (0, import_node_path49.join)(dir, `.floless-${label2}-${(0, import_node_crypto39.randomUUID)()}-${(0, import_node_path49.basename)(livePath)}`);
87116
+ return (0, import_node_path49.join)(dir, `.floless-${label}-${(0, import_node_crypto39.randomUUID)()}-${(0, import_node_path49.basename)(livePath)}`);
86762
87117
  }
86763
87118
  function publishFileExclusive(input) {
86764
87119
  const { livePath, stagedPath, expectedLive, artifactDir } = input;
@@ -86844,7 +87199,7 @@ function activeCodexJournal(appId) {
86844
87199
  }
86845
87200
  return null;
86846
87201
  }
86847
- function withAppSourceLock(appId, label2, fn, options = {}) {
87202
+ function withAppSourceLock(appId, label, fn, options = {}) {
86848
87203
  return withLifecycleLock("app", appId, () => {
86849
87204
  const active2 = activeApprovalTransaction(appId);
86850
87205
  if (active2 && active2 !== options.approvalTransactionId) throw new AppSourcePublicationBusyError();
@@ -86853,7 +87208,7 @@ function withAppSourceLock(appId, label2, fn, options = {}) {
86853
87208
  throw new AppSourcePublicationBusyError();
86854
87209
  }
86855
87210
  return fn();
86856
- }, { label: label2 });
87211
+ }, { label });
86857
87212
  }
86858
87213
 
86859
87214
  // app-publication-manifest.ts
@@ -88221,7 +88576,7 @@ function summarizeBaseline(to) {
88221
88576
  }
88222
88577
  const baseline = diffContracts(to, to);
88223
88578
  const memberCount = view.members.length;
88224
- const sheetCount = view.sheets.length;
88579
+ const sheetCount = new Set(view.sheets.map((s) => s.sheet)).size;
88225
88580
  const totalLb = baseline.tonnage.toLb;
88226
88581
  const totalTons = baseline.tonnage.toTons;
88227
88582
  const bullets = [`${countWord(memberCount, "member")} across ${countWord(sheetCount, "drawing sheet")}.`];
@@ -88424,7 +88779,7 @@ function bakeContractIntoApp(sourcePath2, contract) {
88424
88779
  if (!view) {
88425
88780
  throw new InvalidModelV2Error(`refusing to bake: contract declares steel.model/v2 but is not valid v2: ${issues[0] ?? "unknown"}`, issues);
88426
88781
  }
88427
- doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(contract));
88782
+ doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(view.doc));
88428
88783
  (0, import_node_fs62.writeFileSync)(sourcePath2, doc.toString());
88429
88784
  return;
88430
88785
  }
@@ -89634,7 +89989,7 @@ async function hostReadiness(host, deps = DEFAULT_DEPS3, targetPid) {
89634
89989
  return withAwareShared(() => withSidecarRead(() => hostReadinessUnlocked(host, deps, targetPid)));
89635
89990
  }
89636
89991
  async function hostReadinessUnlocked(host, deps, targetPid) {
89637
- const label2 = HOST_LABELS[host];
89992
+ const label = HOST_LABELS[host];
89638
89993
  const floor = HOST_BAKE_AWARE_FLOORS[host];
89639
89994
  const awareVersion = deps.npmVersion();
89640
89995
  const awareCurrent = !!awareVersion && compareDotted(awareVersion, floor) >= 0;
@@ -89660,8 +90015,8 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89660
90015
  ...base,
89661
90016
  ok: false,
89662
90017
  state: "bridge-missing",
89663
- message: `Couldn\u2019t send \u2014 the connection to ${label2} isn\u2019t installed yet. Install it, then try again.`,
89664
- recovery: { action: "install-bridge", label: `Install ${label2} bridge` }
90018
+ message: `Couldn\u2019t send \u2014 the connection to ${label} isn\u2019t installed yet. Install it, then try again.`,
90019
+ recovery: { action: "install-bridge", label: `Install ${label} bridge` }
89665
90020
  };
89666
90021
  }
89667
90022
  if (!bridgeCurrent) {
@@ -89669,8 +90024,8 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89669
90024
  ...base,
89670
90025
  ok: false,
89671
90026
  state: "bridge-update-required",
89672
- message: `Couldn\u2019t send \u2014 the connection to ${label2} is stale (${bridge.version || "unversioned"}, needs ${awareVersion}). Update it, then try again.`,
89673
- recovery: { action: "install-bridge", label: `Update ${label2} bridge` }
90027
+ message: `Couldn\u2019t send \u2014 the connection to ${label} is stale (${bridge.version || "unversioned"}, needs ${awareVersion}). Update it, then try again.`,
90028
+ recovery: { action: "install-bridge", label: `Update ${label} bridge` }
89674
90029
  };
89675
90030
  }
89676
90031
  let probe;
@@ -89681,7 +90036,7 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89681
90036
  ...base,
89682
90037
  ok: false,
89683
90038
  state: "error",
89684
- message: error instanceof Error ? error.message : `Couldn\u2019t check whether ${label2} is ready.`,
90039
+ message: error instanceof Error ? error.message : `Couldn\u2019t check whether ${label} is ready.`,
89685
90040
  recovery: { action: "retry", label: "Check again" }
89686
90041
  };
89687
90042
  }
@@ -89691,7 +90046,7 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89691
90046
  ...base,
89692
90047
  ok: false,
89693
90048
  state: "error",
89694
- message: `Couldn\u2019t send \u2014 the ${label2} connection isn\u2019t responding${probe.error ? ` (${probe.error.slice(0, 120)})` : ""}. Try again, and reinstall the ${label2} bridge if it keeps happening.`,
90049
+ message: `Couldn\u2019t send \u2014 the ${label} connection isn\u2019t responding${probe.error ? ` (${probe.error.slice(0, 120)})` : ""}. Try again, and reinstall the ${label} bridge if it keeps happening.`,
89695
90050
  recovery: { action: "retry", label: "Check again" }
89696
90051
  };
89697
90052
  }
@@ -89700,8 +90055,8 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89700
90055
  ...base,
89701
90056
  ok: false,
89702
90057
  state: "host-closed",
89703
- message: probe.instances.length ? `Couldn\u2019t send \u2014 that ${label2} window isn\u2019t open any more. Try the drag again.` : `Couldn\u2019t send \u2014 ${label2} isn\u2019t open. Start it and try again.`,
89704
- recovery: probe.instances.length ? { action: "retry", label: "Check again" } : { action: "open-host", label: `Open ${label2}` }
90058
+ message: probe.instances.length ? `Couldn\u2019t send \u2014 that ${label} window isn\u2019t open any more. Try the drag again.` : `Couldn\u2019t send \u2014 ${label} isn\u2019t open. Start it and try again.`,
90059
+ recovery: probe.instances.length ? { action: "retry", label: "Check again" } : { action: "open-host", label: `Open ${label}` }
89705
90060
  };
89706
90061
  }
89707
90062
  if (!probe.ok || !session) {
@@ -89715,7 +90070,7 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89715
90070
  ...base,
89716
90071
  ok: false,
89717
90072
  state: "error",
89718
- message: `Couldn\u2019t send \u2014 ${label2} is running, but FloLess can\u2019t reach it. Restart ${label2} so its FloLess connection reloads, then try again.`,
90073
+ message: `Couldn\u2019t send \u2014 ${label} is running, but FloLess can\u2019t reach it. Restart ${label} so its FloLess connection reloads, then try again.`,
89719
90074
  recovery: { action: "retry", label: "Check again" }
89720
90075
  };
89721
90076
  }
@@ -89723,8 +90078,8 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89723
90078
  ...base,
89724
90079
  ok: false,
89725
90080
  state: "host-closed",
89726
- message: `Couldn\u2019t send \u2014 ${label2} isn\u2019t open. Start it and try again.`,
89727
- recovery: { action: "open-host", label: `Open ${label2}` }
90081
+ message: `Couldn\u2019t send \u2014 ${label} isn\u2019t open. Start it and try again.`,
90082
+ recovery: { action: "open-host", label: `Open ${label}` }
89728
90083
  };
89729
90084
  }
89730
90085
  const found = { open: true, version: session.version, pid: session.pid, rhinoId: session.rhinoId ?? null };
@@ -89733,7 +90088,7 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89733
90088
  ...base,
89734
90089
  ok: false,
89735
90090
  state: "ambiguous-session",
89736
- message: `Couldn\u2019t send \u2014 ${probe.instances.length} ${label2} windows are open and there\u2019s no way to tell which model you meant. Close all but one, or drag the members onto the window you want.`,
90091
+ message: `Couldn\u2019t send \u2014 ${probe.instances.length} ${label} windows are open and there\u2019s no way to tell which model you meant. Close all but one, or drag the members onto the window you want.`,
89737
90092
  recovery: { action: "retry", label: "Check again" }
89738
90093
  };
89739
90094
  }
@@ -89793,7 +90148,7 @@ async function hostReadinessUnlocked(host, deps, targetPid) {
89793
90148
  bakeEnv: probe.env,
89794
90149
  ok: true,
89795
90150
  state: "ready",
89796
- message: `Ready to send to ${label2}${session.version ? ` ${session.version}` : ""}.`,
90151
+ message: `Ready to send to ${label}${session.version ? ` ${session.version}` : ""}.`,
89797
90152
  recovery: null
89798
90153
  };
89799
90154
  }
@@ -94838,14 +95193,14 @@ function safeLease2(value) {
94838
95193
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)) throw new RunFileRelayError("unsafe lease id");
94839
95194
  return value;
94840
95195
  }
94841
- function rejectLink2(path, label2) {
95196
+ function rejectLink2(path, label) {
94842
95197
  let st;
94843
95198
  try {
94844
95199
  st = (0, import_node_fs75.lstatSync)(path);
94845
95200
  } catch {
94846
- throw new RunFileRelayError(`${label2} does not exist`);
95201
+ throw new RunFileRelayError(`${label} does not exist`);
94847
95202
  }
94848
- if (st.isSymbolicLink()) throw new RunFileRelayError(`${label2} is a filesystem link/reparse point`);
95203
+ if (st.isSymbolicLink()) throw new RunFileRelayError(`${label} is a filesystem link/reparse point`);
94849
95204
  }
94850
95205
  function sameIdentity(a, b) {
94851
95206
  return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs;
@@ -94860,11 +95215,11 @@ function structural(value) {
94860
95215
  function hash2(value) {
94861
95216
  return (0, import_node_crypto45.createHash)("sha256").update(value).digest("hex");
94862
95217
  }
94863
- function readRegularFile(path, maxBytes, label2) {
94864
- rejectLink2(path, label2);
95218
+ function readRegularFile(path, maxBytes, label) {
95219
+ rejectLink2(path, label);
94865
95220
  const st = (0, import_node_fs75.statSync)(path);
94866
- if (!st.isFile()) throw new RunFileRelayError(`${label2} is not a regular file`);
94867
- if (st.size > maxBytes) throw new RunFileRelayError(`${label2} is too large`);
95221
+ if (!st.isFile()) throw new RunFileRelayError(`${label} is not a regular file`);
95222
+ if (st.size > maxBytes) throw new RunFileRelayError(`${label} is too large`);
94868
95223
  return (0, import_node_fs75.readFileSync)(path);
94869
95224
  }
94870
95225
  function durableWrite3(path, value) {
@@ -95130,25 +95485,25 @@ function createRunSkillReader(options) {
95130
95485
  };
95131
95486
  return { skillName: options.skillName, read: (resource) => readPacket(resource).text, readPacket };
95132
95487
  }
95133
- function checkedDirectory(path, label2) {
95134
- rejectLink3(path, label2);
95488
+ function checkedDirectory(path, label) {
95489
+ rejectLink3(path, label);
95135
95490
  let real;
95136
95491
  try {
95137
95492
  real = import_node_fs77.realpathSync.native(path);
95138
95493
  } catch {
95139
- throw new RunSkillRelayError(`${label2} not found`);
95494
+ throw new RunSkillRelayError(`${label} not found`);
95140
95495
  }
95141
- if (!(0, import_node_fs77.statSync)(real).isDirectory()) throw new RunSkillRelayError(`${label2} is not a directory`);
95496
+ if (!(0, import_node_fs77.statSync)(real).isDirectory()) throw new RunSkillRelayError(`${label} is not a directory`);
95142
95497
  return real;
95143
95498
  }
95144
- function rejectLink3(path, label2) {
95499
+ function rejectLink3(path, label) {
95145
95500
  let st;
95146
95501
  try {
95147
95502
  st = (0, import_node_fs77.lstatSync)(path);
95148
95503
  } catch {
95149
- throw new RunSkillRelayError(`${label2} not found`);
95504
+ throw new RunSkillRelayError(`${label} not found`);
95150
95505
  }
95151
- if (st.isSymbolicLink()) throw new RunSkillRelayError(`${label2} is a filesystem link/reparse point`);
95506
+ if (st.isSymbolicLink()) throw new RunSkillRelayError(`${label} is a filesystem link/reparse point`);
95152
95507
  }
95153
95508
 
95154
95509
  // terminal-run.ts
@@ -99940,7 +100295,7 @@ async function startServer() {
99940
100295
  manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
99941
100296
  }
99942
100297
  const latest = currentApprovedSnapshot(project.id);
99943
- const dirty = contractHash(current) !== latest.contractHash;
100298
+ const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
99944
100299
  const checkpoint = dirty ? captureProjectCheckpoint({
99945
100300
  project,
99946
100301
  publicationIdentity,
@@ -99950,7 +100305,7 @@ async function startServer() {
99950
100305
  }) : null;
99951
100306
  let publication = null;
99952
100307
  try {
99953
- const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`);
100308
+ const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
99954
100309
  publication = written;
99955
100310
  } catch (error) {
99956
100311
  if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
@@ -99962,7 +100317,11 @@ async function startServer() {
99962
100317
  expectedEpoch: manifest.epoch,
99963
100318
  expectedDraftHash: manifest.draftHash,
99964
100319
  publicationIdentity,
99965
- contract: target.contract,
100320
+ contract: normalisePlanViewIds(target.contract),
100321
+ // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
100322
+ // `source.hash` names the version this came from — while `contract:` above is the document the
100323
+ // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
100324
+ // stored canonically made the manifest disagree with the store the instant it was written.
99966
100325
  source: { kind: "approved", version, hash: target.contractHash },
99967
100326
  workingBase: { version, hash: target.contractHash }
99968
100327
  });
@@ -99999,10 +100358,10 @@ async function startServer() {
99999
100358
  let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
100000
100359
  if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100001
100360
  const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
100002
- if (!latest || contractHash(current) !== latest.contractHash) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
100361
+ if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
100003
100362
  let publication;
100004
100363
  try {
100005
- publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint");
100364
+ publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
100006
100365
  } catch (error) {
100007
100366
  return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
100008
100367
  }
@@ -100012,7 +100371,7 @@ async function startServer() {
100012
100371
  expectedEpoch: manifest.epoch,
100013
100372
  expectedDraftHash: manifest.draftHash,
100014
100373
  publicationIdentity,
100015
- contract: saved.contract,
100374
+ contract: normalisePlanViewIds(saved.contract),
100016
100375
  source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
100017
100376
  workingBase: saved.base
100018
100377
  });
@@ -100145,7 +100504,8 @@ async function startServer() {
100145
100504
  project.app,
100146
100505
  doc,
100147
100506
  project.id,
100148
- "rollback deliberately replaces the current contract with a historical version"
100507
+ "rollback deliberately replaces the current contract with a historical version",
100508
+ { restoring: true }
100149
100509
  );
100150
100510
  } catch (e) {
100151
100511
  if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
@@ -100553,7 +100913,7 @@ async function startServer() {
100553
100913
  }
100554
100914
  mergeResolutions[conflict.path] = choice === "use-draft" ? "draft" : "latest";
100555
100915
  }
100556
- const forward = mergeContractForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100916
+ const forward = mergeApprovalForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100557
100917
  approvalCandidate = forward.merged;
100558
100918
  }
100559
100919
  const accepts = projectApprovalCandidateAccepted(req.params.appId, project, approvalCandidate);
@@ -100607,7 +100967,7 @@ async function startServer() {
100607
100967
  const approvedVersion = outcome.version?.n;
100608
100968
  if (selected.pendingIds.length) {
100609
100969
  const pendingAuthor = prepared.partition.materialize(selected.pendingIds);
100610
- const remaining2 = mergeContractForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
100970
+ const remaining2 = mergeApprovalForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
100611
100971
  if (remaining2.conflicts.length) {
100612
100972
  await writeContractGenerationChecked(req.params.appId, originalDraft, project, "preserve pending reviewed changes after approval");
100613
100973
  } else {