@floless/app 0.136.0 → 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.
@@ -55058,7 +55058,7 @@ function appVersion() {
55058
55058
  return resolveVersion({
55059
55059
  isSea: isSea2(),
55060
55060
  sqVersionXml: readSqVersionXml(),
55061
- define: true ? "0.136.0" : 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.136.0" : 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");
@@ -55969,8 +56008,18 @@ function thresholdsForDrawingScale(ptPerFt) {
55969
56008
  if (!Number.isFinite(ptPerFt) || ptPerFt <= 0) return null;
55970
56009
  const raw = 0.5 * 304.8 / ptPerFt;
55971
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) {
55972
56014
  return Object.freeze({
55973
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,
55974
56023
  targetSpanToleranceMm: faceToleranceMm,
55975
56024
  clusterToleranceMm: Math.min(faceToleranceMm, 25.4),
55976
56025
  ambiguityMarginMm: 2 * faceToleranceMm,
@@ -56132,13 +56181,15 @@ function geometryReviewModelHash(model, subjectId, end, reviewedPoint, scopeValu
56132
56181
  function geometryReviewPlanContext(model, scopeValue) {
56133
56182
  const scope = normalizedScope(scopeValue);
56134
56183
  const ids = scope.kind === "conversion" ? new Set(scope.viewIds) : scope.kind === "active-view" ? /* @__PURE__ */ new Set([scope.viewId]) : null;
56135
- 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) => ({
56136
56185
  sheet: plan.sheet,
56137
56186
  viewKind: plan.viewKind,
56138
56187
  pt_per_ft: plan.pt_per_ft,
56139
- sourceRegistration: plan.sourceRegistration
56140
- })).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)));
56141
56191
  }
56192
+ var planViewIdOf = (row) => row.viewId ?? row.sheet;
56142
56193
 
56143
56194
  // steel-model-v2.ts
56144
56195
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -56202,8 +56253,21 @@ function checkModelReferences(doc) {
56202
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`);
56203
56254
  }
56204
56255
  });
56205
- const sheetCounts = idIndex(plans.map((p) => isObj(p) ? str(p.sheet) : null));
56206
- 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
+ });
56207
56271
  const observations2 = [];
56208
56272
  plans.forEach((p, pi) => {
56209
56273
  if (!isObj(p)) return;
@@ -56215,11 +56279,11 @@ function checkModelReferences(doc) {
56215
56279
  const has = (k) => p[k] !== void 0 && p[k] !== null;
56216
56280
  if (p.viewKind === "plan") {
56217
56281
  if (has("control2_at") && !has("control2_ref")) {
56218
- 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`);
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`);
56219
56283
  }
56220
56284
  for (const side2 of ["datum", "control2"]) {
56221
56285
  if (has(`${side2}_ref`) && !has(`${side2}_at`)) {
56222
- 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`);
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`);
56223
56287
  }
56224
56288
  }
56225
56289
  }
@@ -56229,7 +56293,7 @@ function checkModelReferences(doc) {
56229
56293
  add(
56230
56294
  `$.plans[${pi}]`,
56231
56295
  "plan-controls-on-non-plan-view",
56232
- `sheet "${sheet ?? 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`
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`
56233
56297
  );
56234
56298
  }
56235
56299
  const registration = isObj(p.sourceRegistration) ? p.sourceRegistration : null;
@@ -56688,7 +56752,9 @@ var OWNED = {
56688
56752
  "steel-model": [STEEL_V2],
56689
56753
  vectorize: [VECTOR_V1]
56690
56754
  };
56691
- 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"];
56692
56758
  var ContractPolicyError = class extends Error {
56693
56759
  code;
56694
56760
  constructor(message, code = "contract-not-acceptable") {
@@ -56756,8 +56822,35 @@ function assertAcceptableContract(doc, ctx) {
56756
56822
  const first = issues.slice(0, 5).map((i) => `${i.path}: ${i.message}`).join("; ");
56757
56823
  throw new ContractPolicyError(`contract failed referential integrity \u2014 ${first}`, "contract-invalid");
56758
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
+ }
56759
56834
  }
56760
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
+ }
56761
56854
  var isBakedContract = (value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
56762
56855
 
56763
56856
  // app-import.ts
@@ -58429,7 +58522,8 @@ function registrationOf(plan) {
58429
58522
  control2_at: plan.control2_at,
58430
58523
  control2_ref: plan.control2_ref,
58431
58524
  frame: plan.frame,
58432
- sourceRegistration: plan.sourceRegistration
58525
+ sourceRegistration: plan.sourceRegistration,
58526
+ ...planViewId(plan) !== plan.sheet ? { viewId: planViewId(plan) } : {}
58433
58527
  };
58434
58528
  }
58435
58529
  function drawingDependencyReasons(decision, beforeObservations, afterObservations) {
@@ -58795,10 +58889,31 @@ function dropSignOffsFor(projectId) {
58795
58889
  writeReviewFile(projectId, { version: 1, reviewRevision: current.reviewRevision + 1, joints });
58796
58890
  }
58797
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
+
58798
58910
  // project-contract-hash.ts
58799
58911
  function contractHash(contract) {
58800
58912
  return hashOf(contract);
58801
58913
  }
58914
+ function comparableContractHash(contract) {
58915
+ return hashOf(normalisePlanViewIds(contract));
58916
+ }
58802
58917
 
58803
58918
  // connection-review-transition.ts
58804
58919
  var ConnectionReviewTransitionError = class extends Error {
@@ -64213,7 +64328,7 @@ My note: ${req.instruction}` : "";
64213
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}`;
64214
64329
  }
64215
64330
  if (isInitialRead) {
64216
- 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}`;
64217
64332
  }
64218
64333
  throw new Error("unreachable steel revision-read instruction branch");
64219
64334
  }
@@ -65267,7 +65382,7 @@ function readContract(appId, projectId) {
65267
65382
  const p = contractPath(appId, projectId);
65268
65383
  if (!(0, import_node_fs37.existsSync)(p)) return null;
65269
65384
  try {
65270
- return normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8")));
65385
+ return normalisePlanViewIds(normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8"))));
65271
65386
  } catch (e) {
65272
65387
  console.warn(`readContract: ignoring unreadable contract at ${p}: ${e instanceof Error ? e.message : e}`);
65273
65388
  return null;
@@ -65275,6 +65390,7 @@ function readContract(appId, projectId) {
65275
65390
  }
65276
65391
  function writeContract(appId, doc, projectId, options) {
65277
65392
  doc = normaliseRollMarkers(doc);
65393
+ doc = normalisePlanViewIds(doc);
65278
65394
  const p = contractPath(appId, projectId);
65279
65395
  const currentType = options?.currentType !== void 0 ? options.currentType : (() => {
65280
65396
  const cur = readContract(appId, projectId);
@@ -67141,7 +67257,7 @@ function readModel(doc) {
67141
67257
  return readModelOrIssues(doc).view ?? null;
67142
67258
  }
67143
67259
  function readModelOrIssues(doc) {
67144
- doc = normaliseRollMarkers(doc);
67260
+ doc = normalisePlanViewIds(normaliseRollMarkers(doc));
67145
67261
  if (!isModelV2(doc)) return { view: null, issues: ["not-model-v2"] };
67146
67262
  const schema = validateSteelModelV2(doc);
67147
67263
  if (!schema.valid) {
@@ -67178,6 +67294,7 @@ function readModelOrIssues(doc) {
67178
67294
  members,
67179
67295
  byId: new Map(members.map((m) => [m.id, m])),
67180
67296
  sheets: (v2.plans ?? []).map((p) => ({
67297
+ viewId: planViewId(p),
67181
67298
  sheet: p.sheet,
67182
67299
  viewKind: p.viewKind,
67183
67300
  title: p.title,
@@ -69908,6 +70025,7 @@ var PlanTransformError = class extends Error {
69908
70025
  this.viewKind = viewKind;
69909
70026
  }
69910
70027
  };
70028
+ var subjectOf = (plan, subject) => subject || `sheet "${quote(plan && plan.sheet)}"`;
69911
70029
  var refuse = (code, message, plan) => {
69912
70030
  throw new PlanTransformError(code, message, plan && plan.viewKind);
69913
70031
  };
@@ -69925,24 +70043,24 @@ var clipQuoted = (value, max2 = MAX_QUOTED_CHARS) => {
69925
70043
  return `${text5.slice(0, end)}\u2026`;
69926
70044
  };
69927
70045
  var quote = (value) => clipQuoted(value);
69928
- function gridIntersection(grid, ref, plan, field) {
70046
+ function gridIntersection(grid, ref, plan, field, subject) {
69929
70047
  if (!grid || typeof grid !== "object") {
69930
- 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);
69931
70049
  }
69932
70050
  if (!finite2(grid.origin)) {
69933
70051
  return refuse(
69934
70052
  "grid-unavailable",
69935
- `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`,
69936
70054
  plan
69937
70055
  );
69938
70056
  }
69939
70057
  if (!ref || typeof ref !== "object" || typeof ref.xAxisId !== "string" || typeof ref.yAxisId !== "string") {
69940
- return refuse("control-ref-invalid", `sheet "${quote(plan.sheet)}" has an unreadable ${field}: a registration control needs string xAxisId and yAxisId grid axis ids`, plan);
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);
69941
70059
  }
69942
70060
  const X = parseSpacings(grid.x), Y = parseSpacings(grid.y);
69943
70061
  if (X.err || Y.err) {
69944
70062
  const bad = X.err ? "$.grid.x" : "$.grid.y";
69945
- 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);
69946
70064
  }
69947
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);
69948
70066
  const xs = idsFor("x"), ys = idsFor("y");
@@ -69955,36 +70073,36 @@ function gridIntersection(grid, ref, plan, field) {
69955
70073
  if (xi < 0 || yi < 0) {
69956
70074
  return refuse(
69957
70075
  "control-ref-unresolved",
69958
- `sheet "${quote(plan.sheet)}" ${field} names ${quote(ref.xAxisId)}/${quote(ref.yAxisId)}, which is not exactly one x and one y axis id 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`,
69959
70077
  plan
69960
70078
  );
69961
70079
  }
69962
70080
  return [grid.origin[0] + X.offsets[xi], grid.origin[1] + Y.offsets[yi]];
69963
70081
  }
69964
- function planTransform(plan) {
70082
+ function planTransform(plan, subject) {
69965
70083
  const kind = plan && plan.viewKind;
69966
70084
  if (kind !== "plan") {
69967
70085
  const named = typeof kind === "string" && kind ? quote(kind) : "unknown";
69968
70086
  return refuse(
69969
70087
  "view-kind-unsupported",
69970
- `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`,
69971
70089
  plan
69972
70090
  );
69973
70091
  }
69974
70092
  if (!finite2(plan.datum_at) || !finite2(plan.control2_at) || !plan.control2_ref) {
69975
70093
  return refuse(
69976
70094
  "registration-incomplete",
69977
- `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`,
69978
70096
  plan
69979
70097
  );
69980
70098
  }
69981
70099
  const ptPerFt = Number(plan.pt_per_ft);
69982
70100
  if (!(ptPerFt > 0) || !Number.isFinite(ptPerFt)) {
69983
- 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);
69984
70102
  }
69985
70103
  const registrationGrid = plan.modelGrid || plan.grid;
69986
- const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan, "$.datum_ref") : [0, 0];
69987
- 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);
69988
70106
  const scale = mmPerPx(ptPerFt);
69989
70107
  const local1 = [
69990
70108
  (plan.control2_at[0] - plan.datum_at[0]) * scale,
@@ -69994,18 +70112,18 @@ function planTransform(plan) {
69994
70112
  const localLen = Math.hypot(local1[0], local1[1]);
69995
70113
  const worldLen = Math.hypot(worldDelta[0], worldDelta[1]);
69996
70114
  if (!(localLen > 1e-9)) {
69997
- 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);
69998
70116
  }
69999
70117
  if (!(worldLen > 1e-9)) {
70000
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";
70001
- 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);
70002
70120
  }
70003
70121
  const actualSpanPt = localLen / scale;
70004
70122
  const expectedSpanPt = worldLen / scale;
70005
70123
  if (Math.abs(actualSpanPt - expectedSpanPt) > REGISTRATION_SPAN_TOLERANCE_PT) {
70006
70124
  return refuse(
70007
70125
  "registration-span-mismatch",
70008
- `sheet "${quote(plan.sheet)}" 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`,
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`,
70009
70127
  plan
70010
70128
  );
70011
70129
  }
@@ -70014,13 +70132,13 @@ function planTransform(plan) {
70014
70132
  const c = Math.cos(rotation) * fitScale;
70015
70133
  const s = Math.sin(rotation) * fitScale;
70016
70134
  if (![c, s, fitScale, world0[0], world0[1]].every(Number.isFinite)) {
70017
- 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);
70018
70136
  }
70019
70137
  return { datumPx: plan.datum_at, world0, mmPerPx: scale, fitScale, rotation, c, s };
70020
70138
  }
70021
- function sheetPxToWorld(point3, plan, keepZ) {
70139
+ function sheetPxToWorld(point3, plan, keepZ, subject) {
70022
70140
  if (!finite2(point3)) return refuse("sheet-point-invalid", "a sheet point needs two finite pixel coordinates", plan);
70023
- const t = planTransform(plan);
70141
+ const t = planTransform(plan, subject);
70024
70142
  const localX = (point3[0] - t.datumPx[0]) * t.mmPerPx;
70025
70143
  const localY = (t.datumPx[1] - point3[1]) * t.mmPerPx;
70026
70144
  return {
@@ -70155,7 +70273,7 @@ function footprintBoundaryParameters(footprint, qy, qz, dy, dz) {
70155
70273
  }
70156
70274
  return values2;
70157
70275
  }
70158
- function faceContact(origin, direction, hit, target, toleranceMm) {
70276
+ function faceContact(origin, direction, hit, target, gapToleranceMm, overlapToleranceMm) {
70159
70277
  const footprint = resolveFootprint(target);
70160
70278
  if (typeof footprint === "string") return footprint;
70161
70279
  const o = xyz(origin), targetPoint = xyz(hit.point), d = xyz(direction);
@@ -70165,9 +70283,12 @@ function faceContact(origin, direction, hit, target, toleranceMm) {
70165
70283
  const boundaries = footprintBoundaryParameters(footprint, qy, qz, dy, dz).filter((value) => Number.isFinite(value) && value <= hit.distanceMm + EPS).sort((a, b) => b - a);
70166
70284
  const nearBoundary = boundaries[0];
70167
70285
  if (nearBoundary === void 0 || hit.distanceMm - nearBoundary < -EPS) return "face-contact-missed";
70286
+ const faceGapMm = nearBoundary;
70168
70287
  const faceResidualMm = Math.abs(nearBoundary);
70169
- if (faceResidualMm > toleranceMm + EPS) return "face-contact-missed";
70170
- 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 };
70171
70292
  }
70172
70293
  var pointOrder = (a, b) => a.x - b.x || a.y - b.y || a.z - b.z;
70173
70294
  function completeLinkGroups(clusters, toleranceMm) {
@@ -70188,7 +70309,14 @@ function candidateFromCluster(cluster) {
70188
70309
  distanceMm: Math.min(...cluster.hits.map((entry2) => entry2.hit.distanceMm)),
70189
70310
  ...contacts.length ? {
70190
70311
  faceToCenterlineMm: Math.min(...contacts.map((entry2) => entry2.faceToCenterlineMm)),
70191
- 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
70192
70320
  } : {},
70193
70321
  crossingAngleDeg: Math.min(...cluster.hits.map((entry2) => entry2.hit.angleDeg)),
70194
70322
  reasons: Object.freeze(reasons)
@@ -70221,7 +70349,15 @@ function analyzeMemberEnd(input) {
70221
70349
  const ray = outwardRay(input.subject, input.end);
70222
70350
  if (!ray) return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70223
70351
  const t = input.thresholds;
70224
- 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)) {
70225
70361
  return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70226
70362
  }
70227
70363
  const eligibleRecords = function* () {
@@ -70253,7 +70389,7 @@ function analyzeMemberEnd(input) {
70253
70389
  const reasons = [];
70254
70390
  if (result.angleDeg + EPS < SUPPORT_CENTERLINE_V1.minCrossingAngleDeg) reasons.push("crossing-angle-too-small");
70255
70391
  if (result.distanceMm > SUPPORT_CENTERLINE_V1.absoluteReachCapMm + EPS) reasons.push("reach-cap-exceeded");
70256
- 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);
70257
70393
  const contactValue = typeof contact === "string" ? void 0 : contact;
70258
70394
  if (typeof contact === "string") reasons.push(contact);
70259
70395
  const key2 = jcs(result.point);
@@ -70459,7 +70595,7 @@ function targetMember(member) {
70459
70595
  function selectedPlans(model, scope) {
70460
70596
  if (scope.kind === "model-3d") return model.plans;
70461
70597
  const ids = scope.kind === "conversion" ? new Set(scope.viewIds) : /* @__PURE__ */ new Set([scope.viewId]);
70462
- 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))));
70463
70599
  }
70464
70600
  function analysisScope(scope, plans) {
70465
70601
  if (scope.kind === "model-3d") return { kind: "3d" };
@@ -70467,11 +70603,11 @@ function analysisScope(scope, plans) {
70467
70603
  if (plan?.viewKind === "elevation" || plan?.viewKind === "section") {
70468
70604
  return {
70469
70605
  kind: "elevation",
70470
- viewId: plan.sheet,
70606
+ viewId: planViewId(plan),
70471
70607
  registered: plans.every((item) => (item.viewKind === "elevation" || item.viewKind === "section") && !!item.sourceRegistration)
70472
70608
  };
70473
70609
  }
70474
- 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] ?? "" };
70475
70611
  }
70476
70612
  function observationZ(observation, observationEnd) {
70477
70613
  const z = observationEnd === 0 ? observation.evidence.observed?.fromZ?.value : observation.evidence.observed?.toZ?.value;
@@ -70566,7 +70702,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70566
70702
  const local = observation.evidence.local.wp[observationEnd];
70567
70703
  const fail3 = (reason, note) => {
70568
70704
  diagnoses.record(memberId, memberEnd, reason, note({
70569
- sheet: `sheet "${quote2(plan.sheet)}"`,
70705
+ sheet: viewLabel(model.plans, plan),
70570
70706
  obs: `observation "${quote2(observation.id)}"`
70571
70707
  }));
70572
70708
  return { kind: "failure", reason };
@@ -70581,7 +70717,12 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70581
70717
  if (plan.viewKind === "plan") {
70582
70718
  const z = observationZ(observation, observationEnd);
70583
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`);
70584
- 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
+ );
70585
70726
  const point3 = known(transformed);
70586
70727
  return point3 ? { kind: "point", point: point3 } : fail3("view-unregistered", ({ sheet, obs }) => `${sheet} registration maps ${obs} to a non-finite world point`);
70587
70728
  }
@@ -70600,7 +70741,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70600
70741
  }
70601
70742
  } catch (error) {
70602
70743
  if (error instanceof PlanTransformError) return fail3("view-unregistered", () => error.message);
70603
- const identity = `${plan.sheet}/${observation.id}/end-${observationEnd + 1}`;
70744
+ const identity = `${planViewId(plan)}/${observation.id}/end-${observationEnd + 1}`;
70604
70745
  throw new Error(`member-end evidence transform failed unexpectedly for ${identity}`, { cause: error });
70605
70746
  }
70606
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`);
@@ -70615,13 +70756,7 @@ function finalizedEvidence(accumulator) {
70615
70756
  throw new MemberEndAnalysisWorkLimitError("Member-end analysis exceeded the per-end drawing-observation budget.");
70616
70757
  }
70617
70758
  const strictest = tolerances.length ? Math.min(...tolerances.map((item) => item.faceToleranceMm)) : void 0;
70618
- const thresholds = strictest === void 0 ? void 0 : {
70619
- faceToleranceMm: strictest,
70620
- targetSpanToleranceMm: strictest,
70621
- clusterToleranceMm: Math.min(strictest, 25.4),
70622
- ambiguityMarginMm: 2 * strictest,
70623
- viewAgreementToleranceMm: strictest
70624
- };
70759
+ const thresholds = strictest === void 0 ? void 0 : thresholdsFromFaceTolerance(strictest);
70625
70760
  const elevation2 = scopes.find((item) => item.kind === "elevation");
70626
70761
  const selectedScope = elevation2 ?? scopes.find((item) => item.kind === "plan");
70627
70762
  const spread2 = observedSpreadMm(unique);
@@ -70687,7 +70822,7 @@ function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70687
70822
  if (!tolerance) throw new TypeError("schema-valid observation scale did not produce policy thresholds");
70688
70823
  accumulator.origins.push({ observationId: observation.id, lineageId: row.lineageId, observedPoint: observed.point });
70689
70824
  accumulator.tolerances.push(tolerance);
70690
- 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) });
70691
70826
  }
70692
70827
  }
70693
70828
  return new Map([...accumulators].map(([key2, accumulator]) => [key2, finalizedEvidence(accumulator)]));
@@ -70759,16 +70894,20 @@ function fromDecision(member, end, role) {
70759
70894
  invalidationId: decision.invalidationId
70760
70895
  };
70761
70896
  }
70762
- function unregisteredScopeNote(plans) {
70763
- 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));
70764
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";
70765
- 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(", ");
70766
70905
  const more = offenders.length > 3 ? ` and ${offenders.length - 3} more` : "";
70767
70906
  return `${remedy}: ${named}${more}`;
70768
70907
  }
70769
- function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70908
+ function recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70770
70909
  if (subjectReasons.includes("view-unregistered") && analysis.kind === "elevation" && !analysis.registered) {
70771
- diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(plans), true);
70910
+ diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(allPlans, plans), true);
70772
70911
  }
70773
70912
  if (evidence.conflict) {
70774
70913
  const spread2 = evidence.spreadMm ?? 0;
@@ -70785,7 +70924,7 @@ function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId,
70785
70924
  );
70786
70925
  }
70787
70926
  }
70788
- function freshFinding(member, end, role, scope, plans, analysis, evidence, result, diagnoses) {
70927
+ function freshFinding(member, end, role, scope, allPlans, plans, analysis, evidence, result, diagnoses) {
70789
70928
  const currentPoint = end === 0 ? member.from : member.to;
70790
70929
  const geometryOnly = !evidence.basis;
70791
70930
  const completeTargets = targetsOf(result);
@@ -70812,7 +70951,7 @@ function freshFinding(member, end, role, scope, plans, analysis, evidence, resul
70812
70951
  };
70813
70952
  const subjectReasons = result.kind === "not-checkable" ? result.reasons.map((reason) => reasonMap[reason]) : [];
70814
70953
  if (evidence.conflict || subjectReasons.includes("view-unregistered")) {
70815
- recordDerivedNotes(plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70954
+ recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70816
70955
  }
70817
70956
  if (evidence.failures.length) return {
70818
70957
  ...base,
@@ -70928,7 +71067,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70928
71067
  continue;
70929
71068
  }
70930
71069
  if (!analyzed) {
70931
- 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, {
70932
71071
  kind: "not-checkable",
70933
71072
  reasons: Object.freeze(["subject-geometry-invalid"])
70934
71073
  }, diagnoses);
@@ -70947,7 +71086,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70947
71086
  targets: targetMap,
70948
71087
  consumeExactGeometryTest
70949
71088
  });
70950
- 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);
70951
71090
  if (finding) findings.push(finding);
70952
71091
  }
70953
71092
  }
@@ -71127,7 +71266,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
71127
71266
  return { literalContractHash, finalContractHash: asHash(model), model, report, retainedMemberIdsHash };
71128
71267
  }
71129
71268
  function canonicalLineagedViewIds(model) {
71130
- 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)));
71131
71270
  }
71132
71271
  function hashRetainedMemberIds(ids) {
71133
71272
  return asHash([...ids].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))));
@@ -72059,7 +72198,8 @@ function isExactFilterCheckpointShell(value) {
72059
72198
  const filter = doc.filter;
72060
72199
  const filterSheets = filter.sheets.map((raw) => raw && typeof raw === "object" && !Array.isArray(raw) ? raw.sheet : null);
72061
72200
  const planSheets = doc.plans.map((raw) => raw.sheet);
72062
- 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));
72063
72203
  }
72064
72204
  function publishNative(staged, origin) {
72065
72205
  assertPublishableSource(staged);
@@ -72118,9 +72258,18 @@ async function recoverAllProjectTransactions(listIds) {
72118
72258
  }
72119
72259
  return out;
72120
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
+ }
72121
72269
  async function runNativeInitialRead(opts) {
72122
72270
  return withLifecycleLock("project", opts.projectId, () => {
72123
72271
  assertNoPendingRecovery(opts.projectId);
72272
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
72124
72273
  const current = readContract(opts.appId, opts.projectId);
72125
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");
72126
72275
  if (!isExactFilterCheckpointShell(current)) throw new ContractTransactionError("the first read requires the exact zero-model Drawing Filter checkpoint shell", "filter-checkpoint-not-empty");
@@ -72132,7 +72281,7 @@ async function runNativeInitialRead(opts) {
72132
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);
72133
72282
  if (contractHash(shell.filter) !== contractHash(candidate.filter)) throw new ContractTransactionError("the submitted model does not contain the exact saved Drawing Filter", "filter-changed");
72134
72283
  if (contractHash(shell.grid) !== contractHash(candidate.grid)) throw new ContractTransactionError("the submitted model changed the saved grid", "shell-changed");
72135
- 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"];
72136
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]])));
72137
72286
  if (contractHash(registration(shell)) !== contractHash(registration(candidate))) throw new ContractTransactionError("the submitted model changed saved plan registration", "shell-changed");
72138
72287
  const normalized = normalizeSteelMemberEndsForRead(opts.candidate);
@@ -72169,6 +72318,13 @@ async function runNativeInitialRead(opts) {
72169
72318
  baseHash: input.baseHash,
72170
72319
  generation: `version:${listVersions(opts.projectId).length + 1}`,
72171
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.
72172
72328
  literalCandidateHash: contractHash(opts.candidate),
72173
72329
  finalCandidateHash: contractHash(normalized.model),
72174
72330
  memberEndReportHash: contractHash(normalized.report)
@@ -72176,6 +72332,7 @@ async function runNativeInitialRead(opts) {
72176
72332
  });
72177
72333
  storedReadAudit = { version: 1, receipt, report: readAuditReport, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
72178
72334
  }
72335
+ preflightNativePublication(opts.appId, opts.projectId, normalized.model, declaredTypeOf(current));
72179
72336
  const versionSource = opts.source || storedReadAudit ? {
72180
72337
  files: opts.source?.files ?? [],
72181
72338
  ...opts.source?.requestId ? { requestId: opts.source.requestId } : {},
@@ -72205,6 +72362,7 @@ async function runNativeInitialRead(opts) {
72205
72362
  async function runNativeRevisionRead(opts) {
72206
72363
  return withLifecycleLock("project", opts.projectId, () => {
72207
72364
  assertNoPendingRecovery(opts.projectId);
72365
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
72208
72366
  const current = readContract(opts.appId, opts.projectId);
72209
72367
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) {
72210
72368
  throw new ContractTransactionError(`a revision read requires an existing ${STEEL_V2} model and a ${STEEL_V2} candidate`, "contract-type-unsupported");
@@ -72215,6 +72373,7 @@ async function runNativeRevisionRead(opts) {
72215
72373
  if (opts.source?.readAudit) {
72216
72374
  assertPublishableSource({ v: 2, appId: opts.appId, projectId: opts.projectId, contract: opts.candidate, message: opts.message, source: opts.source });
72217
72375
  }
72376
+ preflightNativePublication(opts.appId, opts.projectId, opts.candidate, declaredTypeOf(current));
72218
72377
  const dir = (0, import_node_path38.join)(projectDir(opts.projectId), `${PREFIX}${Date.now().toString(36)}-${(0, import_node_crypto27.randomUUID)().slice(0, 8)}`);
72219
72378
  (0, import_node_fs40.mkdirSync)(dir, { recursive: true });
72220
72379
  write(phase(dir, "000-begin"), { v: 2, expected: contractHash(current), at: (/* @__PURE__ */ new Date()).toISOString() });
@@ -72492,12 +72651,11 @@ function ctxFor(opts, storedType) {
72492
72651
  }
72493
72652
  function acceptContract(doc, opts) {
72494
72653
  const op = opts.operation ?? "read";
72495
- const needsStored = MUTATING_OPS.has(op);
72654
+ const needsStored = isMutatingOperation(op);
72496
72655
  const storedType = opts.currentType !== void 0 ? opts.currentType : needsStored ? storedTypeOf(opts) : null;
72497
72656
  assertAcceptableContract(doc, ctxFor(opts, storedType));
72498
- return doc;
72657
+ return normalisePlanViewIds(doc);
72499
72658
  }
72500
- var MUTATING_OPS = /* @__PURE__ */ new Set(["put", "import", "duplicate", "bake"]);
72501
72659
  function storedTypeOf(opts) {
72502
72660
  const current = readContract(opts.appId, opts.projectId);
72503
72661
  return current == null ? null : declaredTypeOf(current);
@@ -72732,7 +72890,8 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72732
72890
  let publication;
72733
72891
  try {
72734
72892
  publication = writeContract(appId, finalContract, projectId, {
72735
- 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",
72736
72895
  currentType: storedType
72737
72896
  });
72738
72897
  } catch (e) {
@@ -72753,7 +72912,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72753
72912
  } else if (declaredTypeOf(finalContract) === STEEL_V2) {
72754
72913
  persistConnectionReviewForWrite({
72755
72914
  projectId: projectId ?? null,
72756
- finalAfter: normaliseRollMarkers(finalContract),
72915
+ finalAfter: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72757
72916
  origin: reviewOriginForGatewayWrite(origin.origin)
72758
72917
  });
72759
72918
  }
@@ -72766,7 +72925,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72766
72925
  // review's `self` baseline was recorded against the un-normalised doc and read back drifted, and
72767
72926
  // `member-end-routes` staged its undo token over a hash the store would never reproduce, so Undo
72768
72927
  // silently never offered itself. Idempotent, and free when nothing carried a marker.
72769
- contract: normaliseRollMarkers(finalContract),
72928
+ contract: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72770
72929
  invalidatedWorkPointDecisions: prepared.invalidated,
72771
72930
  ...revalidation ? { revalidation } : {}
72772
72931
  };
@@ -72787,10 +72946,11 @@ function writeConnectionPlacementChecked(appId, doc, projectId, ifMatch, placeme
72787
72946
  [CONNECTION_PLACEMENT_AUTHORITY]: true
72788
72947
  });
72789
72948
  }
72790
- function writeContractGenerationChecked(appId, doc, projectId, why) {
72949
+ function writeContractGenerationChecked(appId, doc, projectId, why, opts = {}) {
72791
72950
  return writeContractChecked(appId, doc, projectId, {
72792
72951
  origin: "contract-generation",
72793
72952
  why,
72953
+ restoring: opts.restoring,
72794
72954
  [CONTRACT_GENERATION_AUTHORITY]: true
72795
72955
  });
72796
72956
  }
@@ -74002,7 +74162,12 @@ var REGISTRY = /* @__PURE__ */ new Map([
74002
74162
  ["$.plans[]", { disposition: "propose", note: "a sheet" }],
74003
74163
  // The MATCH KEY, exactly like `$.members[].id`: plans are paired by sheet before diffing, so this can
74004
74164
  // never differ within a pair. Listed so the coverage test sees a decision.
74005
- ["$.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" }],
74006
74171
  ["$.plans[].viewKind", { disposition: "propose", note: "the reader's explicit sheet classification; unsupported kinds remain stored but are refused by their transform" }],
74007
74172
  // The canonical registration a revision read may genuinely move: where the cut plane sits, which grid
74008
74173
  // intersection anchors the sheet, what it is called, and which members it presents.
@@ -74222,6 +74387,8 @@ function revisionFramePreservesPlacement(before, after, memberId) {
74222
74387
  }
74223
74388
  }
74224
74389
  function stageRevisionRead(current, incoming) {
74390
+ current = normalisePlanViewIds(current);
74391
+ incoming = normalisePlanViewIds(incoming);
74225
74392
  const accepted = [];
74226
74393
  const bindingUpdates = [];
74227
74394
  const bindingProposals = [];
@@ -74231,7 +74398,17 @@ function stageRevisionRead(current, incoming) {
74231
74398
  const curObs = observationsOf(current);
74232
74399
  const incMembers = new Map((incoming.members ?? []).map((m) => [m.id, m]));
74233
74400
  const curMembers = new Map((current.members ?? []).map((m) => [m.id, m]));
74234
- 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;
74235
74412
  const ownIssues = /* @__PURE__ */ new Map();
74236
74413
  const order = [];
74237
74414
  const seenIncoming = /* @__PURE__ */ new Set();
@@ -74249,8 +74426,8 @@ function stageRevisionRead(current, incoming) {
74249
74426
  bad(`${path}.evidence.source.sheet`, "observation-sheet-missing", "evidence names no source sheet, so it cannot be filed against a plan");
74250
74427
  } else if (citedSheet !== plan.sheet) {
74251
74428
  bad(`${path}.evidence.source.sheet`, "observation-sheet-mismatch", `evidence cites sheet "${citedSheet}" but lives on plan "${plan.sheet}"`);
74252
- } else if (!currentSheets.has(plan.sheet)) {
74253
- 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`);
74254
74431
  }
74255
74432
  for (const id of obs.binding?.memberIds ?? []) {
74256
74433
  if (curMembers.has(id)) continue;
@@ -74267,7 +74444,7 @@ function stageRevisionRead(current, incoming) {
74267
74444
  const admissible = new Set([...ownIssues].filter(([, v]) => v.length === 0).map(([k]) => k));
74268
74445
  const landing = [];
74269
74446
  const pendingUpdates = [];
74270
- for (const { obs, path } of order) {
74447
+ for (const { plan, obs, path } of order) {
74271
74448
  const mine = ownIssues.get(obs.id) ?? [];
74272
74449
  issues.push(...mine);
74273
74450
  if (mine.length) continue;
@@ -74281,7 +74458,7 @@ function stageRevisionRead(current, incoming) {
74281
74458
  if (rejected) continue;
74282
74459
  const existing = curObs.get(obs.id);
74283
74460
  if (!existing) {
74284
- landing.push({ obs, path });
74461
+ landing.push({ obs, path, viewId: planViewId(plan) });
74285
74462
  continue;
74286
74463
  }
74287
74464
  if (json(existing.obs.evidence) !== json(obs.evidence)) {
@@ -74352,9 +74529,9 @@ function stageRevisionRead(current, incoming) {
74352
74529
  candidates.delete(id);
74353
74530
  }
74354
74531
  }
74355
- for (const { obs, path } of landing) {
74532
+ for (const { obs, path, viewId } of landing) {
74356
74533
  if (candidates.has(obs.id)) {
74357
- accepted.push(withoutForgedVerification(obs, bindingProposals));
74534
+ accepted.push({ viewId, observation: withoutForgedVerification(obs, bindingProposals) });
74358
74535
  continue;
74359
74536
  }
74360
74537
  const orphaned = orphanedBy.get(obs.id);
@@ -74436,38 +74613,38 @@ function stageRevisionRead(current, incoming) {
74436
74613
  }
74437
74614
  if (fields.length) proposals.push({ kind: "member-changed", memberId: id, fields });
74438
74615
  }
74439
- const incomingSheets = new Set((incoming.plans ?? []).map((p) => p.sheet));
74440
- for (const sheet of currentSheets) {
74441
- if (!incomingSheets.has(sheet)) {
74616
+ const incomingViewIds = new Set((incoming.plans ?? []).map(planViewId));
74617
+ for (const viewId of currentViewIds) {
74618
+ if (!incomingViewIds.has(viewId)) {
74442
74619
  add(
74443
- `$.plans[${sheet}]`,
74620
+ `$.plans[${viewId}]`,
74444
74621
  "path-refused",
74445
- `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`
74446
74623
  );
74447
74624
  }
74448
74625
  }
74449
74626
  for (const id of curMembers.keys()) {
74450
74627
  if (!incMembers.has(id)) proposals.push({ kind: "member-removed", memberId: id });
74451
74628
  }
74452
- const curPlans = new Map((current.plans ?? []).map((p) => [p.sheet, p]));
74453
- const sheetCounts = /* @__PURE__ */ new Map();
74454
- for (const plan of incoming.plans ?? []) sheetCounts.set(plan.sheet, (sheetCounts.get(plan.sheet) ?? 0) + 1);
74455
- 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) {
74456
74633
  if (n < 2) continue;
74457
74634
  add(
74458
- `$.plans[${sheet}]`,
74459
- "plan-sheet-duplicate",
74460
- `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`
74461
74638
  );
74462
74639
  }
74463
74640
  for (const plan of incoming.plans ?? []) {
74464
- if ((sheetCounts.get(plan.sheet) ?? 0) > 1) continue;
74465
- const existing = curPlans.get(plan.sheet);
74641
+ if ((viewIdCounts.get(planViewId(plan)) ?? 0) > 1) continue;
74642
+ const existing = curPlans.get(planViewId(plan));
74466
74643
  if (existing) {
74467
74644
  const planFields = [];
74468
74645
  for (const key2 of /* @__PURE__ */ new Set([...Object.keys(existing), ...Object.keys(plan)])) {
74469
74646
  if (key2 === "memberObservations") continue;
74470
- if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${plan.sheet}].${key2}`))) continue;
74647
+ if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${planViewId(plan)}].${key2}`))) continue;
74471
74648
  const b = existing[key2];
74472
74649
  const a = plan[key2];
74473
74650
  const entry2 = entryFor(`$.plans[].${key2}`);
@@ -74475,17 +74652,17 @@ function stageRevisionRead(current, incoming) {
74475
74652
  if (entry2?.disposition === "propose") planFields.push({ key: key2, before: b, after: a });
74476
74653
  else {
74477
74654
  add(
74478
- `$.plans[${plan.sheet}].${key2}`,
74655
+ `$.plans[${planViewId(plan)}].${key2}`,
74479
74656
  "path-refused",
74480
- `"${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}` : ""}`
74481
74658
  );
74482
74659
  }
74483
74660
  }
74484
- 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 });
74485
74662
  continue;
74486
74663
  }
74487
74664
  const { memberObservations: _refused, ...sheetOnly } = plan;
74488
- 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 });
74489
74666
  }
74490
74667
  const HANDLED_ROOT = /* @__PURE__ */ new Set(["members", "plans"]);
74491
74668
  const curRoot = current;
@@ -74598,18 +74775,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74598
74775
  break;
74599
74776
  }
74600
74777
  case "plan-added": {
74601
- if (p.plan?.sheet !== p.sheet) {
74602
- 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`);
74603
74780
  }
74604
- if (next.plans.some((pl2) => pl2.sheet === p.plan.sheet)) {
74605
- 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`);
74606
74783
  }
74607
74784
  next.plans.push(structuredClone(p.plan));
74608
74785
  break;
74609
74786
  }
74610
74787
  case "plan-changed": {
74611
- const pl2 = next.plans.find((x) => x.sheet === p.sheet);
74612
- 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`);
74613
74790
  for (const f of p.fields) {
74614
74791
  if (!writableLeaf(`$.plans[].${f.key}`)) {
74615
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`);
@@ -74634,10 +74811,9 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74634
74811
  }
74635
74812
  }
74636
74813
  }
74637
- const bySheet = /* @__PURE__ */ new Map();
74638
- for (const obs of staged.accepted) {
74639
- const sheet = obs.evidence.source.sheet;
74640
- 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]);
74641
74817
  }
74642
74818
  const updates = /* @__PURE__ */ new Map();
74643
74819
  for (const u of [...staged.bindingUpdates, ...pick(staged.bindingProposals, selection.bindingProposals, "bindingProposals")]) {
@@ -74647,18 +74823,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74647
74823
  updates.set(u.observationId, u.to);
74648
74824
  }
74649
74825
  for (const plan of next.plans) {
74650
- const arriving = bySheet.get(plan.sheet);
74826
+ const arriving = byView.get(planViewId(plan));
74651
74827
  if (arriving?.length) {
74652
74828
  plan.memberObservations = [...plan.memberObservations ?? [], ...structuredClone(arriving)];
74653
- bySheet.delete(plan.sheet);
74829
+ byView.delete(planViewId(plan));
74654
74830
  }
74655
74831
  for (const obs of plan.memberObservations ?? []) {
74656
74832
  const to = updates.get(obs.id);
74657
74833
  if (to) obs.binding = structuredClone(to);
74658
74834
  }
74659
74835
  }
74660
- if (bySheet.size > 0) {
74661
- 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`);
74662
74838
  }
74663
74839
  return next;
74664
74840
  }
@@ -79041,26 +79217,28 @@ function registerSteelPrepassRoute(app, deps) {
79041
79217
  }
79042
79218
  let doc = structuredClone(current);
79043
79219
  const plans = Array.isArray(doc.plans) ? doc.plans.filter(isObj8) : [];
79044
- const names2 = plans.map((plan) => String(plan.sheet ?? ""));
79220
+ const names2 = plans.map((plan) => rawPlanViewId(plan) ?? "");
79045
79221
  const missing = Object.keys(sheets).filter((sheet) => !names2.includes(sheet));
79046
- 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(", ")}` });
79047
79223
  const duplicates = Object.keys(sheets).filter((sheet) => names2.filter((name) => name === sheet).length > 1);
79048
- 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(", ")}` });
79049
79225
  let applied = false;
79050
79226
  if (body.filter !== void 0) {
79051
79227
  doc.filter = body.filter;
79052
79228
  applied = true;
79053
79229
  }
79054
79230
  const refErrors = [];
79231
+ const viewLabels = planViewLabels(plans);
79055
79232
  for (const plan of plans) {
79056
- const sheet = String(plan.sheet ?? "");
79233
+ const sheet = rawPlanViewId(plan) ?? "";
79234
+ const viewName = viewLabels.get(sheet) ?? sheet;
79057
79235
  const patch2 = sheets[sheet];
79058
79236
  if (!isObj8(patch2)) continue;
79059
79237
  if (plan.viewKind !== "plan" && PLAN_KEYS.some((key2) => patch2[key2] !== void 0)) {
79060
79238
  return reply.status(400).send({
79061
79239
  ok: false,
79062
79240
  code: "prepass-plan-controls-on-non-plan-view",
79063
- error: `sheet "${sheet}" 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`
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`
79064
79242
  });
79065
79243
  }
79066
79244
  for (const key2 of PLAN_KEYS) {
@@ -79096,7 +79274,8 @@ function registerSteelPrepassRoute(app, deps) {
79096
79274
  }
79097
79275
  }
79098
79276
  const filterSheets = filterSheetsOf(doc);
79099
- 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));
79100
79279
  if (unregistered.length) {
79101
79280
  return reply.status(400).send({
79102
79281
  ok: false,
@@ -85632,7 +85811,8 @@ function currentApprovedSnapshot(projectId, version) {
85632
85811
  const latestHash = contractHash(latestContract);
85633
85812
  assertOwned(latest, latestHash);
85634
85813
  const draft = readAcceptedForRequest(project.app, projectId, "read");
85635
- const dirtySinceApproval = draft == null || contractHash(draft) !== latestHash;
85814
+ const comparable = comparableContractHash;
85815
+ const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
85636
85816
  return {
85637
85817
  project,
85638
85818
  version: row,
@@ -85786,6 +85966,7 @@ function atomicChanged(opts, groups) {
85786
85966
  groups.push(group);
85787
85967
  return atomicNode(group.id, opts.before, opts.after);
85788
85968
  }
85969
+ var parentLabel = (opts) => opts.parentLabel ?? String(opts.parent);
85789
85970
  function keyedCollection(opts) {
85790
85971
  const beforePresent = opts.before !== void 0;
85791
85972
  const afterPresent = opts.after !== void 0;
@@ -85797,7 +85978,7 @@ function keyedCollection(opts) {
85797
85978
  entity: "collection",
85798
85979
  category: opts.category,
85799
85980
  headline: `${opts.category} collection`,
85800
- location: opts.parent ? String(opts.parent) : "Model",
85981
+ location: opts.parent ? parentLabel(opts) : "Model",
85801
85982
  before: beforePresent ? opts.before : ABSENT,
85802
85983
  after: afterPresent ? opts.after : ABSENT
85803
85984
  }, opts.groups) };
@@ -85830,7 +86011,7 @@ function keyedCollection(opts) {
85830
86011
  entity: key2,
85831
86012
  category: opts.category,
85832
86013
  headline: opts.labelOf(isObj9(bv) ? bv : av, key2),
85833
- location: opts.parent ? `${String(opts.parent)} \xB7 ${key2}` : key2,
86014
+ location: opts.parent ? `${parentLabel(opts)} \xB7 ${key2}` : key2,
85834
86015
  before: av,
85835
86016
  after: bv,
85836
86017
  references: isObj9(bv) ? opts.referencesOf?.(bv) : []
@@ -85883,6 +86064,7 @@ function nestedEntity(base, draft, opts, groups) {
85883
86064
  type: opts.type,
85884
86065
  collection: n.collection,
85885
86066
  parent: opts.identity,
86067
+ parentLabel: opts.identityLabel,
85886
86068
  category: n.category,
85887
86069
  before: base[n.key],
85888
86070
  after: draft[n.key],
@@ -85975,6 +86157,15 @@ function unionDependencies(groups) {
85975
86157
  for (const id of ids) groups.find((group) => group.id === id).dependencyGroup = digest2;
85976
86158
  }
85977
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
+ }
85978
86169
  function fallback(base, draft, type, reason) {
85979
86170
  const group = groupOf({
85980
86171
  type,
@@ -86010,20 +86201,21 @@ function buildKnown(base, draft, type) {
86010
86201
  groups,
86011
86202
  referencesOf: (v) => arr4(v.ends).flatMap((end) => isObj9(end) && typeof end.conn === "string" ? [token(type, "connection", null, end.conn)] : [])
86012
86203
  }));
86204
+ const planLabel = planLabeller(base, draft);
86013
86205
  add("plans", keyedCollection({
86014
86206
  type,
86015
86207
  collection: "plan",
86016
86208
  category: "Sheet",
86017
86209
  before: base.plans,
86018
86210
  after: draft.plans,
86019
- keyOf: (v) => typeof v.sheet === "string" ? v.sheet : null,
86020
- labelOf: (_v2, key2) => `Sheet ${key2}`,
86211
+ keyOf: (v) => rawPlanViewId(v),
86212
+ labelOf: planLabel,
86021
86213
  groups,
86022
86214
  buildItem: (a, b, key2) => nestedEntity(a, b, {
86023
86215
  type,
86024
86216
  collection: "plan",
86025
86217
  identity: key2,
86026
- identityLabel: `Sheet ${key2}`,
86218
+ identityLabel: planLabel(a ?? b ?? {}, key2),
86027
86219
  nested: [
86028
86220
  {
86029
86221
  key: "memberObservations",
@@ -86381,6 +86573,11 @@ function mergeContractForward(base, latest, draft, resolutions = {}) {
86381
86573
  return { merged, conflicts };
86382
86574
  }
86383
86575
 
86576
+ // approval-forward-merge.ts
86577
+ function mergeApprovalForward(base, latest, draft, resolutions = {}) {
86578
+ return mergeContractForward(base, normalisePlanViewIds(latest), draft, resolutions);
86579
+ }
86580
+
86384
86581
  // approval-review-service.ts
86385
86582
  function prepareProjectApprovalReview(projectId, deps) {
86386
86583
  const project = getProject(projectId);
@@ -86413,7 +86610,7 @@ function prepareProjectApprovalReview(projectId, deps) {
86413
86610
  if (manifest?.workingBase && snapshot.contractHash !== manifest.workingBase.hash) {
86414
86611
  throw new WorkspaceSnapshotError(409, "the working revision base proof no longer matches History; keep it as a checkpoint and start again");
86415
86612
  }
86416
- baseContract = snapshot.contract;
86613
+ baseContract = normalisePlanViewIds(snapshot.contract);
86417
86614
  base = { version: snapshot.version.n, hash: snapshot.contractHash, approvedAt: snapshot.currentApprovedAt ?? void 0 };
86418
86615
  }
86419
86616
  const draftHash = contractHash(draft);
@@ -86433,11 +86630,11 @@ function prepareProjectApprovalReview(projectId, deps) {
86433
86630
  });
86434
86631
  if (base && row && base.version !== row.n) {
86435
86632
  const latest = currentApprovedSnapshot(projectId);
86436
- const preview2 = mergeContractForward(baseContract, latest.contract, draft);
86633
+ const preview2 = mergeApprovalForward(baseContract, latest.contract, draft);
86437
86634
  const groupsByPath = /* @__PURE__ */ new Map();
86438
86635
  for (const group of prepared.partition.groups) {
86439
86636
  const single = prepared.partition.materialize([group.id]);
86440
- for (const conflict of mergeContractForward(baseContract, latest.contract, single).conflicts) {
86637
+ for (const conflict of mergeApprovalForward(baseContract, latest.contract, single).conflicts) {
86441
86638
  const ids = groupsByPath.get(conflict.path) ?? [];
86442
86639
  ids.push(group.id);
86443
86640
  groupsByPath.set(conflict.path, ids);
@@ -88379,7 +88576,7 @@ function summarizeBaseline(to) {
88379
88576
  }
88380
88577
  const baseline = diffContracts(to, to);
88381
88578
  const memberCount = view.members.length;
88382
- const sheetCount = view.sheets.length;
88579
+ const sheetCount = new Set(view.sheets.map((s) => s.sheet)).size;
88383
88580
  const totalLb = baseline.tonnage.toLb;
88384
88581
  const totalTons = baseline.tonnage.toTons;
88385
88582
  const bullets = [`${countWord(memberCount, "member")} across ${countWord(sheetCount, "drawing sheet")}.`];
@@ -88582,7 +88779,7 @@ function bakeContractIntoApp(sourcePath2, contract) {
88582
88779
  if (!view) {
88583
88780
  throw new InvalidModelV2Error(`refusing to bake: contract declares steel.model/v2 but is not valid v2: ${issues[0] ?? "unknown"}`, issues);
88584
88781
  }
88585
- doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(contract));
88782
+ doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(view.doc));
88586
88783
  (0, import_node_fs62.writeFileSync)(sourcePath2, doc.toString());
88587
88784
  return;
88588
88785
  }
@@ -100098,7 +100295,7 @@ async function startServer() {
100098
100295
  manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100099
100296
  }
100100
100297
  const latest = currentApprovedSnapshot(project.id);
100101
- const dirty = contractHash(current) !== latest.contractHash;
100298
+ const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
100102
100299
  const checkpoint = dirty ? captureProjectCheckpoint({
100103
100300
  project,
100104
100301
  publicationIdentity,
@@ -100108,7 +100305,7 @@ async function startServer() {
100108
100305
  }) : null;
100109
100306
  let publication = null;
100110
100307
  try {
100111
- 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 });
100112
100309
  publication = written;
100113
100310
  } catch (error) {
100114
100311
  if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
@@ -100120,7 +100317,11 @@ async function startServer() {
100120
100317
  expectedEpoch: manifest.epoch,
100121
100318
  expectedDraftHash: manifest.draftHash,
100122
100319
  publicationIdentity,
100123
- 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.
100124
100325
  source: { kind: "approved", version, hash: target.contractHash },
100125
100326
  workingBase: { version, hash: target.contractHash }
100126
100327
  });
@@ -100157,10 +100358,10 @@ async function startServer() {
100157
100358
  let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
100158
100359
  if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100159
100360
  const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
100160
- 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 });
100161
100362
  let publication;
100162
100363
  try {
100163
- 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 });
100164
100365
  } catch (error) {
100165
100366
  return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
100166
100367
  }
@@ -100170,7 +100371,7 @@ async function startServer() {
100170
100371
  expectedEpoch: manifest.epoch,
100171
100372
  expectedDraftHash: manifest.draftHash,
100172
100373
  publicationIdentity,
100173
- contract: saved.contract,
100374
+ contract: normalisePlanViewIds(saved.contract),
100174
100375
  source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
100175
100376
  workingBase: saved.base
100176
100377
  });
@@ -100303,7 +100504,8 @@ async function startServer() {
100303
100504
  project.app,
100304
100505
  doc,
100305
100506
  project.id,
100306
- "rollback deliberately replaces the current contract with a historical version"
100507
+ "rollback deliberately replaces the current contract with a historical version",
100508
+ { restoring: true }
100307
100509
  );
100308
100510
  } catch (e) {
100309
100511
  if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
@@ -100711,7 +100913,7 @@ async function startServer() {
100711
100913
  }
100712
100914
  mergeResolutions[conflict.path] = choice === "use-draft" ? "draft" : "latest";
100713
100915
  }
100714
- const forward = mergeContractForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100916
+ const forward = mergeApprovalForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100715
100917
  approvalCandidate = forward.merged;
100716
100918
  }
100717
100919
  const accepts = projectApprovalCandidateAccepted(req.params.appId, project, approvalCandidate);
@@ -100765,7 +100967,7 @@ async function startServer() {
100765
100967
  const approvedVersion = outcome.version?.n;
100766
100968
  if (selected.pendingIds.length) {
100767
100969
  const pendingAuthor = prepared.partition.materialize(selected.pendingIds);
100768
- const remaining2 = mergeContractForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
100970
+ const remaining2 = mergeApprovalForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
100769
100971
  if (remaining2.conflicts.length) {
100770
100972
  await writeContractGenerationChecked(req.params.appId, originalDraft, project, "preserve pending reviewed changes after approval");
100771
100973
  } else {