@floless/app 0.136.0 → 0.137.1

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.1" : 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.1" : 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,66 @@ 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
+ var hasDerivedId = (plan) => {
58910
+ if (!plan || typeof plan !== "object" || Array.isArray(plan)) return false;
58911
+ const row = plan;
58912
+ return typeof row.sheet === "string" && row.sheet.trim() !== "" && row.id === row.sheet;
58913
+ };
58914
+ function stripDerivedPlanViewIds(doc) {
58915
+ const model = doc;
58916
+ if (!model || typeof model !== "object" || !Array.isArray(model.plans)) return doc;
58917
+ if (typeof model.type === "string" && !model.type.startsWith("steel.model/")) return doc;
58918
+ if (!model.plans.some(hasDerivedId)) return doc;
58919
+ return {
58920
+ ...model,
58921
+ plans: model.plans.map((raw) => {
58922
+ if (!hasDerivedId(raw)) return raw;
58923
+ const { id: _derived, ...rest } = raw;
58924
+ return rest;
58925
+ })
58926
+ };
58927
+ }
58928
+
58798
58929
  // project-contract-hash.ts
58799
58930
  function contractHash(contract) {
58800
58931
  return hashOf(contract);
58801
58932
  }
58933
+ function contractIdentityHash(contract) {
58934
+ return hashOf(stripDerivedPlanViewIds(contract));
58935
+ }
58936
+ function supersededContractIdentityHash(contract) {
58937
+ return hashOf(normalisePlanViewIds(contract));
58938
+ }
58939
+ function comparableContractHash(contract) {
58940
+ return contractIdentityHash(contract);
58941
+ }
58942
+ function etagsOf(doc) {
58943
+ if (doc == null) return { current: null, superseded: null };
58944
+ const current = `"${contractIdentityHash(doc)}"`;
58945
+ const superseded = `"${supersededContractIdentityHash(doc)}"`;
58946
+ return { current, superseded: superseded === current ? null : superseded };
58947
+ }
58948
+ function recordedEtagNamesContract(recorded, etags) {
58949
+ if (!recorded) return false;
58950
+ return recorded === etags.current || etags.superseded !== null && recorded === etags.superseded;
58951
+ }
58802
58952
 
58803
58953
  // connection-review-transition.ts
58804
58954
  var ConnectionReviewTransitionError = class extends Error {
@@ -64213,7 +64363,7 @@ My note: ${req.instruction}` : "";
64213
64363
  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
64364
  }
64215
64365
  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}`;
64366
+ 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
64367
  }
64218
64368
  throw new Error("unreachable steel revision-read instruction branch");
64219
64369
  }
@@ -65171,7 +65321,8 @@ var import_node_os24 = require("node:os");
65171
65321
  // contract-publication.ts
65172
65322
  var import_node_fs36 = require("node:fs");
65173
65323
  var publicationPath = (path) => `${path}.publication.json`;
65174
- var tagOf = (contract) => `"${contractHash(contract)}"`;
65324
+ var tagOf = (contract) => `"${contractIdentityHash(contract)}"`;
65325
+ var supersededTagOf = (contract) => `"${supersededContractIdentityHash(contract)}"`;
65175
65326
  function valid(value) {
65176
65327
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
65177
65328
  const row = value;
@@ -65206,6 +65357,10 @@ function publicationForSnapshot(contractFile, contract) {
65206
65357
  const etag = tagOf(contract);
65207
65358
  const previous = readStored(contractFile);
65208
65359
  if (previous?.etag === etag) return { etag, storeRevision: previous.storeRevision };
65360
+ if (previous && previous.etag === supersededTagOf(contract)) {
65361
+ persist(contractFile, { version: 1, etag, storeRevision: previous.storeRevision });
65362
+ return { etag, storeRevision: previous.storeRevision };
65363
+ }
65209
65364
  const storeRevision = previous ? previous.storeRevision + 1 : 0;
65210
65365
  if (!Number.isSafeInteger(storeRevision)) throw new Error("working-contract storeRevision is exhausted");
65211
65366
  persist(contractFile, { version: 1, etag, storeRevision });
@@ -65267,7 +65422,7 @@ function readContract(appId, projectId) {
65267
65422
  const p = contractPath(appId, projectId);
65268
65423
  if (!(0, import_node_fs37.existsSync)(p)) return null;
65269
65424
  try {
65270
- return normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8")));
65425
+ return normalisePlanViewIds(normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8"))));
65271
65426
  } catch (e) {
65272
65427
  console.warn(`readContract: ignoring unreadable contract at ${p}: ${e instanceof Error ? e.message : e}`);
65273
65428
  return null;
@@ -65275,6 +65430,7 @@ function readContract(appId, projectId) {
65275
65430
  }
65276
65431
  function writeContract(appId, doc, projectId, options) {
65277
65432
  doc = normaliseRollMarkers(doc);
65433
+ doc = normalisePlanViewIds(doc);
65278
65434
  const p = contractPath(appId, projectId);
65279
65435
  const currentType = options?.currentType !== void 0 ? options.currentType : (() => {
65280
65436
  const cur = readContract(appId, projectId);
@@ -67141,7 +67297,7 @@ function readModel(doc) {
67141
67297
  return readModelOrIssues(doc).view ?? null;
67142
67298
  }
67143
67299
  function readModelOrIssues(doc) {
67144
- doc = normaliseRollMarkers(doc);
67300
+ doc = normalisePlanViewIds(normaliseRollMarkers(doc));
67145
67301
  if (!isModelV2(doc)) return { view: null, issues: ["not-model-v2"] };
67146
67302
  const schema = validateSteelModelV2(doc);
67147
67303
  if (!schema.valid) {
@@ -67178,6 +67334,7 @@ function readModelOrIssues(doc) {
67178
67334
  members,
67179
67335
  byId: new Map(members.map((m) => [m.id, m])),
67180
67336
  sheets: (v2.plans ?? []).map((p) => ({
67337
+ viewId: planViewId(p),
67181
67338
  sheet: p.sheet,
67182
67339
  viewKind: p.viewKind,
67183
67340
  title: p.title,
@@ -69908,6 +70065,7 @@ var PlanTransformError = class extends Error {
69908
70065
  this.viewKind = viewKind;
69909
70066
  }
69910
70067
  };
70068
+ var subjectOf = (plan, subject) => subject || `sheet "${quote(plan && plan.sheet)}"`;
69911
70069
  var refuse = (code, message, plan) => {
69912
70070
  throw new PlanTransformError(code, message, plan && plan.viewKind);
69913
70071
  };
@@ -69925,24 +70083,24 @@ var clipQuoted = (value, max2 = MAX_QUOTED_CHARS) => {
69925
70083
  return `${text5.slice(0, end)}\u2026`;
69926
70084
  };
69927
70085
  var quote = (value) => clipQuoted(value);
69928
- function gridIntersection(grid, ref, plan, field) {
70086
+ function gridIntersection(grid, ref, plan, field, subject) {
69929
70087
  if (!grid || typeof grid !== "object") {
69930
- return refuse("grid-unavailable", `sheet "${quote(plan.sheet)}" has no model grid to resolve its registration controls`, plan);
70088
+ return refuse("grid-unavailable", `${subjectOf(plan, subject)} has no model grid to resolve its registration controls`, plan);
69931
70089
  }
69932
70090
  if (!finite2(grid.origin)) {
69933
70091
  return refuse(
69934
70092
  "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`,
70093
+ `${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
70094
  plan
69937
70095
  );
69938
70096
  }
69939
70097
  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);
70098
+ 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
70099
  }
69942
70100
  const X = parseSpacings(grid.x), Y = parseSpacings(grid.y);
69943
70101
  if (X.err || Y.err) {
69944
70102
  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);
70103
+ return refuse("grid-spacing-invalid", `${subjectOf(plan, subject)} cannot use ${bad}: ${quote(X.err || Y.err)}`, plan);
69946
70104
  }
69947
70105
  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
70106
  const xs = idsFor("x"), ys = idsFor("y");
@@ -69955,36 +70113,36 @@ function gridIntersection(grid, ref, plan, field) {
69955
70113
  if (xi < 0 || yi < 0) {
69956
70114
  return refuse(
69957
70115
  "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`,
70116
+ `${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
70117
  plan
69960
70118
  );
69961
70119
  }
69962
70120
  return [grid.origin[0] + X.offsets[xi], grid.origin[1] + Y.offsets[yi]];
69963
70121
  }
69964
- function planTransform(plan) {
70122
+ function planTransform(plan, subject) {
69965
70123
  const kind = plan && plan.viewKind;
69966
70124
  if (kind !== "plan") {
69967
70125
  const named = typeof kind === "string" && kind ? quote(kind) : "unknown";
69968
70126
  return refuse(
69969
70127
  "view-kind-unsupported",
69970
- `sheet "${quote(plan && plan.sheet)}" is a ${named} view; ${named} views are not supported by the plan transform`,
70128
+ `${subjectOf(plan, subject)} is a ${named} view; ${named} views are not supported by the plan transform`,
69971
70129
  plan
69972
70130
  );
69973
70131
  }
69974
70132
  if (!finite2(plan.datum_at) || !finite2(plan.control2_at) || !plan.control2_ref) {
69975
70133
  return refuse(
69976
70134
  "registration-incomplete",
69977
- `sheet "${quote(plan.sheet)}" needs $.datum_at, $.control2_at and $.control2_ref before it can be edited`,
70135
+ `${subjectOf(plan, subject)} needs $.datum_at, $.control2_at and $.control2_ref before it can be edited`,
69978
70136
  plan
69979
70137
  );
69980
70138
  }
69981
70139
  const ptPerFt = Number(plan.pt_per_ft);
69982
70140
  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);
70141
+ return refuse("scale-invalid", `${subjectOf(plan, subject)} has no positive $.pt_per_ft, so it has no drawing scale`, plan);
69984
70142
  }
69985
70143
  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");
70144
+ const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan, "$.datum_ref", subject) : [0, 0];
70145
+ const world1 = gridIntersection(registrationGrid, plan.control2_ref, plan, "$.control2_ref", subject);
69988
70146
  const scale = mmPerPx(ptPerFt);
69989
70147
  const local1 = [
69990
70148
  (plan.control2_at[0] - plan.datum_at[0]) * scale,
@@ -69994,18 +70152,18 @@ function planTransform(plan) {
69994
70152
  const localLen = Math.hypot(local1[0], local1[1]);
69995
70153
  const worldLen = Math.hypot(worldDelta[0], worldDelta[1]);
69996
70154
  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);
70155
+ 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
70156
  }
69999
70157
  if (!(worldLen > 1e-9)) {
70000
70158
  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);
70159
+ return refuse("registration-degenerate", `${subjectOf(plan, subject)} has coincident registration controls: ${datum}`, plan);
70002
70160
  }
70003
70161
  const actualSpanPt = localLen / scale;
70004
70162
  const expectedSpanPt = worldLen / scale;
70005
70163
  if (Math.abs(actualSpanPt - expectedSpanPt) > REGISTRATION_SPAN_TOLERANCE_PT) {
70006
70164
  return refuse(
70007
70165
  "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`,
70166
+ `${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
70167
  plan
70010
70168
  );
70011
70169
  }
@@ -70014,13 +70172,13 @@ function planTransform(plan) {
70014
70172
  const c = Math.cos(rotation) * fitScale;
70015
70173
  const s = Math.sin(rotation) * fitScale;
70016
70174
  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);
70175
+ return refuse("registration-invalid", `${subjectOf(plan, subject)} has a non-finite registration transform`, plan);
70018
70176
  }
70019
70177
  return { datumPx: plan.datum_at, world0, mmPerPx: scale, fitScale, rotation, c, s };
70020
70178
  }
70021
- function sheetPxToWorld(point3, plan, keepZ) {
70179
+ function sheetPxToWorld(point3, plan, keepZ, subject) {
70022
70180
  if (!finite2(point3)) return refuse("sheet-point-invalid", "a sheet point needs two finite pixel coordinates", plan);
70023
- const t = planTransform(plan);
70181
+ const t = planTransform(plan, subject);
70024
70182
  const localX = (point3[0] - t.datumPx[0]) * t.mmPerPx;
70025
70183
  const localY = (t.datumPx[1] - point3[1]) * t.mmPerPx;
70026
70184
  return {
@@ -70155,7 +70313,7 @@ function footprintBoundaryParameters(footprint, qy, qz, dy, dz) {
70155
70313
  }
70156
70314
  return values2;
70157
70315
  }
70158
- function faceContact(origin, direction, hit, target, toleranceMm) {
70316
+ function faceContact(origin, direction, hit, target, gapToleranceMm, overlapToleranceMm) {
70159
70317
  const footprint = resolveFootprint(target);
70160
70318
  if (typeof footprint === "string") return footprint;
70161
70319
  const o = xyz(origin), targetPoint = xyz(hit.point), d = xyz(direction);
@@ -70165,9 +70323,12 @@ function faceContact(origin, direction, hit, target, toleranceMm) {
70165
70323
  const boundaries = footprintBoundaryParameters(footprint, qy, qz, dy, dz).filter((value) => Number.isFinite(value) && value <= hit.distanceMm + EPS).sort((a, b) => b - a);
70166
70324
  const nearBoundary = boundaries[0];
70167
70325
  if (nearBoundary === void 0 || hit.distanceMm - nearBoundary < -EPS) return "face-contact-missed";
70326
+ const faceGapMm = nearBoundary;
70168
70327
  const faceResidualMm = Math.abs(nearBoundary);
70169
- if (faceResidualMm > toleranceMm + EPS) return "face-contact-missed";
70170
- return { faceResidualMm, faceToCenterlineMm: hit.distanceMm - nearBoundary };
70328
+ if (faceGapMm > 0 ? faceGapMm > gapToleranceMm + EPS : -faceGapMm > overlapToleranceMm + EPS) {
70329
+ return "face-contact-missed";
70330
+ }
70331
+ return { faceResidualMm, faceGapMm, faceToCenterlineMm: hit.distanceMm - nearBoundary };
70171
70332
  }
70172
70333
  var pointOrder = (a, b) => a.x - b.x || a.y - b.y || a.z - b.z;
70173
70334
  function completeLinkGroups(clusters, toleranceMm) {
@@ -70188,7 +70349,14 @@ function candidateFromCluster(cluster) {
70188
70349
  distanceMm: Math.min(...cluster.hits.map((entry2) => entry2.hit.distanceMm)),
70189
70350
  ...contacts.length ? {
70190
70351
  faceToCenterlineMm: Math.min(...contacts.map((entry2) => entry2.faceToCenterlineMm)),
70191
- faceResidualMm: Math.max(...contacts.map((entry2) => entry2.faceResidualMm))
70352
+ faceResidualMm: Math.max(...contacts.map((entry2) => entry2.faceResidualMm)),
70353
+ /*
70354
+ * The gap of the contact whose MAGNITUDE `faceResidualMm` reports, so the two describe the same
70355
+ * contact. `Math.max` over signed values would not: with a +5 mm gap and a -9 mm overlap in one
70356
+ * cluster it reports the 9 mm as the residual and the +5 mm as the gap, which reads as a 5 mm
70357
+ * setback when the real fault is a 9 mm interpenetration.
70358
+ */
70359
+ faceGapMm: contacts.reduce((worst, entry2) => Math.abs(entry2.faceGapMm) > Math.abs(worst.faceGapMm) ? entry2 : worst).faceGapMm
70192
70360
  } : {},
70193
70361
  crossingAngleDeg: Math.min(...cluster.hits.map((entry2) => entry2.hit.angleDeg)),
70194
70362
  reasons: Object.freeze(reasons)
@@ -70221,7 +70389,15 @@ function analyzeMemberEnd(input) {
70221
70389
  const ray = outwardRay(input.subject, input.end);
70222
70390
  if (!ray) return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70223
70391
  const t = input.thresholds;
70224
- if (![t.faceToleranceMm, t.targetSpanToleranceMm, t.clusterToleranceMm, t.ambiguityMarginMm, t.viewAgreementToleranceMm].every((value) => Number.isFinite(value) && value >= 0)) {
70392
+ if (![
70393
+ t.faceToleranceMm,
70394
+ t.faceGapToleranceMm,
70395
+ t.faceOverlapToleranceMm,
70396
+ t.targetSpanToleranceMm,
70397
+ t.clusterToleranceMm,
70398
+ t.ambiguityMarginMm,
70399
+ t.viewAgreementToleranceMm
70400
+ ].every((value) => Number.isFinite(value) && value >= 0)) {
70225
70401
  return { kind: "not-checkable", reasons: Object.freeze(["subject-geometry-invalid"]) };
70226
70402
  }
70227
70403
  const eligibleRecords = function* () {
@@ -70253,7 +70429,7 @@ function analyzeMemberEnd(input) {
70253
70429
  const reasons = [];
70254
70430
  if (result.angleDeg + EPS < SUPPORT_CENTERLINE_V1.minCrossingAngleDeg) reasons.push("crossing-angle-too-small");
70255
70431
  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);
70432
+ const contact = faceContact(ray.origin, ray.direction, result, target, t.faceGapToleranceMm, t.faceOverlapToleranceMm);
70257
70433
  const contactValue = typeof contact === "string" ? void 0 : contact;
70258
70434
  if (typeof contact === "string") reasons.push(contact);
70259
70435
  const key2 = jcs(result.point);
@@ -70459,7 +70635,7 @@ function targetMember(member) {
70459
70635
  function selectedPlans(model, scope) {
70460
70636
  if (scope.kind === "model-3d") return model.plans;
70461
70637
  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)));
70638
+ return model.plans.filter((plan) => ids.has(planViewId(plan))).sort((a, b) => Buffer.compare(Buffer.from(planViewId(a)), Buffer.from(planViewId(b))));
70463
70639
  }
70464
70640
  function analysisScope(scope, plans) {
70465
70641
  if (scope.kind === "model-3d") return { kind: "3d" };
@@ -70467,11 +70643,11 @@ function analysisScope(scope, plans) {
70467
70643
  if (plan?.viewKind === "elevation" || plan?.viewKind === "section") {
70468
70644
  return {
70469
70645
  kind: "elevation",
70470
- viewId: plan.sheet,
70646
+ viewId: planViewId(plan),
70471
70647
  registered: plans.every((item) => (item.viewKind === "elevation" || item.viewKind === "section") && !!item.sourceRegistration)
70472
70648
  };
70473
70649
  }
70474
- return { kind: "plan", viewId: plan?.sheet ?? (scope.kind === "active-view" ? scope.viewId : scope.viewIds[0] ?? "") };
70650
+ return { kind: "plan", viewId: plan ? planViewId(plan) : scope.kind === "active-view" ? scope.viewId : scope.viewIds[0] ?? "" };
70475
70651
  }
70476
70652
  function observationZ(observation, observationEnd) {
70477
70653
  const z = observationEnd === 0 ? observation.evidence.observed?.fromZ?.value : observation.evidence.observed?.toZ?.value;
@@ -70566,7 +70742,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70566
70742
  const local = observation.evidence.local.wp[observationEnd];
70567
70743
  const fail3 = (reason, note) => {
70568
70744
  diagnoses.record(memberId, memberEnd, reason, note({
70569
- sheet: `sheet "${quote2(plan.sheet)}"`,
70745
+ sheet: viewLabel(model.plans, plan),
70570
70746
  obs: `observation "${quote2(observation.id)}"`
70571
70747
  }));
70572
70748
  return { kind: "failure", reason };
@@ -70581,7 +70757,12 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70581
70757
  if (plan.viewKind === "plan") {
70582
70758
  const z = observationZ(observation, observationEnd);
70583
70759
  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);
70760
+ const transformed = sheetPxToWorld(
70761
+ local,
70762
+ { ...plan, modelGrid: model.grid },
70763
+ z,
70764
+ viewLabel(model.plans ?? [], plan)
70765
+ );
70585
70766
  const point3 = known(transformed);
70586
70767
  return point3 ? { kind: "point", point: point3 } : fail3("view-unregistered", ({ sheet, obs }) => `${sheet} registration maps ${obs} to a non-finite world point`);
70587
70768
  }
@@ -70600,7 +70781,7 @@ function observationPoint(model, plan, observation, observationEnd, memberId, me
70600
70781
  }
70601
70782
  } catch (error) {
70602
70783
  if (error instanceof PlanTransformError) return fail3("view-unregistered", () => error.message);
70603
- const identity = `${plan.sheet}/${observation.id}/end-${observationEnd + 1}`;
70784
+ const identity = `${planViewId(plan)}/${observation.id}/end-${observationEnd + 1}`;
70604
70785
  throw new Error(`member-end evidence transform failed unexpectedly for ${identity}`, { cause: error });
70605
70786
  }
70606
70787
  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 +70796,7 @@ function finalizedEvidence(accumulator) {
70615
70796
  throw new MemberEndAnalysisWorkLimitError("Member-end analysis exceeded the per-end drawing-observation budget.");
70616
70797
  }
70617
70798
  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
- };
70799
+ const thresholds = strictest === void 0 ? void 0 : thresholdsFromFaceTolerance(strictest);
70625
70800
  const elevation2 = scopes.find((item) => item.kind === "elevation");
70626
70801
  const selectedScope = elevation2 ?? scopes.find((item) => item.kind === "plan");
70627
70802
  const spread2 = observedSpreadMm(unique);
@@ -70687,7 +70862,7 @@ function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70687
70862
  if (!tolerance) throw new TypeError("schema-valid observation scale did not produce policy thresholds");
70688
70863
  accumulator.origins.push({ observationId: observation.id, lineageId: row.lineageId, observedPoint: observed.point });
70689
70864
  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 });
70865
+ accumulator.scopes.push(plan.viewKind === "elevation" || plan.viewKind === "section" ? { kind: "elevation", viewId: planViewId(plan), registered: !!plan.sourceRegistration } : { kind: "plan", viewId: planViewId(plan) });
70691
70866
  }
70692
70867
  }
70693
70868
  return new Map([...accumulators].map(([key2, accumulator]) => [key2, finalizedEvidence(accumulator)]));
@@ -70759,16 +70934,20 @@ function fromDecision(member, end, role) {
70759
70934
  invalidationId: decision.invalidationId
70760
70935
  };
70761
70936
  }
70762
- function unregisteredScopeNote(plans) {
70763
- const offenders = plans.filter((plan) => !((plan.viewKind === "elevation" || plan.viewKind === "section") && !!plan.sourceRegistration));
70937
+ function viewLabel(plans, plan) {
70938
+ const label = planViewLabels(plans).get(planViewId(plan));
70939
+ return label && label !== plan.sheet ? `sheet "${quote2(plan.sheet)}" view "${quote2(planViewId(plan))}"` : `sheet "${quote2(plan.sheet)}"`;
70940
+ }
70941
+ function unregisteredScopeNote(allPlans, scoped) {
70942
+ const offenders = scoped.filter((plan) => !((plan.viewKind === "elevation" || plan.viewKind === "section") && !!plan.sourceRegistration));
70764
70943
  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(", ");
70944
+ const named = offenders.slice(0, 3).map((plan) => viewLabel(allPlans, plan)).join(", ");
70766
70945
  const more = offenders.length > 3 ? ` and ${offenders.length - 3} more` : "";
70767
70946
  return `${remedy}: ${named}${more}`;
70768
70947
  }
70769
- function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70948
+ function recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70770
70949
  if (subjectReasons.includes("view-unregistered") && analysis.kind === "elevation" && !analysis.registered) {
70771
- diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(plans), true);
70950
+ diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(allPlans, plans), true);
70772
70951
  }
70773
70952
  if (evidence.conflict) {
70774
70953
  const spread2 = evidence.spreadMm ?? 0;
@@ -70785,7 +70964,7 @@ function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId,
70785
70964
  );
70786
70965
  }
70787
70966
  }
70788
- function freshFinding(member, end, role, scope, plans, analysis, evidence, result, diagnoses) {
70967
+ function freshFinding(member, end, role, scope, allPlans, plans, analysis, evidence, result, diagnoses) {
70789
70968
  const currentPoint = end === 0 ? member.from : member.to;
70790
70969
  const geometryOnly = !evidence.basis;
70791
70970
  const completeTargets = targetsOf(result);
@@ -70812,7 +70991,7 @@ function freshFinding(member, end, role, scope, plans, analysis, evidence, resul
70812
70991
  };
70813
70992
  const subjectReasons = result.kind === "not-checkable" ? result.reasons.map((reason) => reasonMap[reason]) : [];
70814
70993
  if (evidence.conflict || subjectReasons.includes("view-unregistered")) {
70815
- recordDerivedNotes(plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70994
+ recordDerivedNotes(allPlans, plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70816
70995
  }
70817
70996
  if (evidence.failures.length) return {
70818
70997
  ...base,
@@ -70928,7 +71107,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70928
71107
  continue;
70929
71108
  }
70930
71109
  if (!analyzed) {
70931
- const finding2 = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, {
71110
+ const finding2 = freshFinding(member, end, role.finding, normalizedScope2, model.plans ?? [], plans, evidence.analysisScope ?? aScope, evidence, {
70932
71111
  kind: "not-checkable",
70933
71112
  reasons: Object.freeze(["subject-geometry-invalid"])
70934
71113
  }, diagnoses);
@@ -70947,7 +71126,7 @@ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ *
70947
71126
  targets: targetMap,
70948
71127
  consumeExactGeometryTest
70949
71128
  });
70950
- const finding = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, result, diagnoses);
71129
+ const finding = freshFinding(member, end, role.finding, normalizedScope2, model.plans ?? [], plans, evidence.analysisScope ?? aScope, evidence, result, diagnoses);
70951
71130
  if (finding) findings.push(finding);
70952
71131
  }
70953
71132
  }
@@ -71127,7 +71306,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
71127
71306
  return { literalContractHash, finalContractHash: asHash(model), model, report, retainedMemberIdsHash };
71128
71307
  }
71129
71308
  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)));
71309
+ 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
71310
  }
71132
71311
  function hashRetainedMemberIds(ids) {
71133
71312
  return asHash([...ids].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))));
@@ -72059,7 +72238,8 @@ function isExactFilterCheckpointShell(value) {
72059
72238
  const filter = doc.filter;
72060
72239
  const filterSheets = filter.sheets.map((raw) => raw && typeof raw === "object" && !Array.isArray(raw) ? raw.sheet : null);
72061
72240
  const planSheets = doc.plans.map((raw) => raw.sheet);
72062
- return contractHash([...filterSheets].sort()) === contractHash([...planSheets].sort());
72241
+ const unique = (values2) => [...new Set(values2.map((v) => JSON.stringify(v ?? null)))].sort();
72242
+ return contractHash(unique(filterSheets)) === contractHash(unique(planSheets));
72063
72243
  }
72064
72244
  function publishNative(staged, origin) {
72065
72245
  assertPublishableSource(staged);
@@ -72118,21 +72298,30 @@ async function recoverAllProjectTransactions(listIds) {
72118
72298
  }
72119
72299
  return out;
72120
72300
  }
72301
+ function preflightNativePublication(appId, projectId, contract, currentType) {
72302
+ try {
72303
+ assertAcceptableContract(contract, { appId, projectId, operation: "put", currentType });
72304
+ } catch (e) {
72305
+ if (e instanceof ContractPolicyError) throw new ContractTransactionError(e.message, e.code);
72306
+ throw e;
72307
+ }
72308
+ }
72121
72309
  async function runNativeInitialRead(opts) {
72122
72310
  return withLifecycleLock("project", opts.projectId, () => {
72123
72311
  assertNoPendingRecovery(opts.projectId);
72312
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
72124
72313
  const current = readContract(opts.appId, opts.projectId);
72125
72314
  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
72315
  if (!isExactFilterCheckpointShell(current)) throw new ContractTransactionError("the first read requires the exact zero-model Drawing Filter checkpoint shell", "filter-checkpoint-not-empty");
72127
72316
  if (listVersions(opts.projectId).length) throw new ContractTransactionError("the initial read requires empty project history", "history-already-exists");
72128
- if (`"${contractHash(current)}"` !== opts.filterSavedEtag) throw new ContractTransactionError("the Drawing Filter changed after it was saved", "filter-changed");
72317
+ if (!recordedEtagNamesContract(opts.filterSavedEtag, etagsOf(current))) throw new ContractTransactionError("the Drawing Filter changed after it was saved", "filter-changed");
72129
72318
  const candidate = opts.candidate;
72130
72319
  const shell = current;
72131
72320
  const checked = validateSteelFilter(candidate, opts.source?.files.map((file) => file.sha256.toLowerCase()));
72132
72321
  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
72322
  if (contractHash(shell.filter) !== contractHash(candidate.filter)) throw new ContractTransactionError("the submitted model does not contain the exact saved Drawing Filter", "filter-changed");
72134
72323
  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"];
72324
+ const fields = ["id", "sheet", "viewKind", "elevation_in", "pt_per_ft", "datum_at", "datum_ref", "control2_at", "control2_ref", "frame", "sourceRegistration"];
72136
72325
  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
72326
  if (contractHash(registration(shell)) !== contractHash(registration(candidate))) throw new ContractTransactionError("the submitted model changed saved plan registration", "shell-changed");
72138
72327
  const normalized = normalizeSteelMemberEndsForRead(opts.candidate);
@@ -72169,6 +72358,13 @@ async function runNativeInitialRead(opts) {
72169
72358
  baseHash: input.baseHash,
72170
72359
  generation: `version:${listVersions(opts.projectId).length + 1}`,
72171
72360
  normalization: {
72361
+ // "LITERAL" means before the MEMBER-END normalisation, which is the pair this records; it has
72362
+ // never meant the raw request bytes (roll markers are still un-normalised at this point and
72363
+ // are rewritten later, at the store's door). Since #938 the view-id canonicalisation also
72364
+ // happens upstream of it, for the reason at the top of this function. What matters for the
72365
+ // receipt is that it stays self-consistent, and it does: the audit hashes `normalized.model`
72366
+ // and `assertPublishableSource` compares against `staged.contract`, which IS that document —
72367
+ // on the recovery replay too, since the journal stores the same bytes.
72172
72368
  literalCandidateHash: contractHash(opts.candidate),
72173
72369
  finalCandidateHash: contractHash(normalized.model),
72174
72370
  memberEndReportHash: contractHash(normalized.report)
@@ -72176,6 +72372,7 @@ async function runNativeInitialRead(opts) {
72176
72372
  });
72177
72373
  storedReadAudit = { version: 1, receipt, report: readAuditReport, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
72178
72374
  }
72375
+ preflightNativePublication(opts.appId, opts.projectId, normalized.model, declaredTypeOf(current));
72179
72376
  const versionSource = opts.source || storedReadAudit ? {
72180
72377
  files: opts.source?.files ?? [],
72181
72378
  ...opts.source?.requestId ? { requestId: opts.source.requestId } : {},
@@ -72205,16 +72402,18 @@ async function runNativeInitialRead(opts) {
72205
72402
  async function runNativeRevisionRead(opts) {
72206
72403
  return withLifecycleLock("project", opts.projectId, () => {
72207
72404
  assertNoPendingRecovery(opts.projectId);
72405
+ opts = { ...opts, candidate: normalisePlanViewIds(opts.candidate) };
72208
72406
  const current = readContract(opts.appId, opts.projectId);
72209
72407
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) {
72210
72408
  throw new ContractTransactionError(`a revision read requires an existing ${STEEL_V2} model and a ${STEEL_V2} candidate`, "contract-type-unsupported");
72211
72409
  }
72212
- if (`"${contractHash(current)}"` !== opts.expectedEtag) {
72410
+ if (!recordedEtagNamesContract(opts.expectedEtag, etagsOf(current))) {
72213
72411
  throw new ContractTransactionError("the model changed while this revision was being confirmed", "contract-changed");
72214
72412
  }
72215
72413
  if (opts.source?.readAudit) {
72216
72414
  assertPublishableSource({ v: 2, appId: opts.appId, projectId: opts.projectId, contract: opts.candidate, message: opts.message, source: opts.source });
72217
72415
  }
72416
+ preflightNativePublication(opts.appId, opts.projectId, opts.candidate, declaredTypeOf(current));
72218
72417
  const dir = (0, import_node_path38.join)(projectDir(opts.projectId), `${PREFIX}${Date.now().toString(36)}-${(0, import_node_crypto27.randomUUID)().slice(0, 8)}`);
72219
72418
  (0, import_node_fs40.mkdirSync)(dir, { recursive: true });
72220
72419
  write(phase(dir, "000-begin"), { v: 2, expected: contractHash(current), at: (/* @__PURE__ */ new Date()).toISOString() });
@@ -72492,12 +72691,11 @@ function ctxFor(opts, storedType) {
72492
72691
  }
72493
72692
  function acceptContract(doc, opts) {
72494
72693
  const op = opts.operation ?? "read";
72495
- const needsStored = MUTATING_OPS.has(op);
72694
+ const needsStored = isMutatingOperation(op);
72496
72695
  const storedType = opts.currentType !== void 0 ? opts.currentType : needsStored ? storedTypeOf(opts) : null;
72497
72696
  assertAcceptableContract(doc, ctxFor(opts, storedType));
72498
- return doc;
72697
+ return normalisePlanViewIds(doc);
72499
72698
  }
72500
- var MUTATING_OPS = /* @__PURE__ */ new Set(["put", "import", "duplicate", "bake"]);
72501
72699
  function storedTypeOf(opts) {
72502
72700
  const current = readContract(opts.appId, opts.projectId);
72503
72701
  return current == null ? null : declaredTypeOf(current);
@@ -72595,12 +72793,18 @@ function acceptedContractIdentity(appId, projectId) {
72595
72793
  ctxFor({ appId, projectId, operation: "read" }, cached.contractType)
72596
72794
  );
72597
72795
  }
72598
- return { contractType: cached.contractType, contractEtag: cached.contractEtag };
72796
+ return {
72797
+ contractType: cached.contractType,
72798
+ contractEtag: cached.contractEtag,
72799
+ contractEtagSuperseded: cached.contractEtagSuperseded
72800
+ };
72599
72801
  }
72600
72802
  const contract = readAcceptedForRequest(appId, projectId, "read");
72803
+ const tags = etagsOf(contract);
72601
72804
  const identity = {
72602
72805
  contractType: contract == null ? void 0 : declaredTypeOf(contract),
72603
- contractEtag: etagOf(contract)
72806
+ contractEtag: tags.current,
72807
+ contractEtagSuperseded: tags.superseded
72604
72808
  };
72605
72809
  const after = signature();
72606
72810
  if (before === after) {
@@ -72609,14 +72813,17 @@ function acceptedContractIdentity(appId, projectId) {
72609
72813
  return identity;
72610
72814
  }
72611
72815
  }
72612
- return { contractType: void 0, contractEtag: null };
72816
+ return { contractType: void 0, contractEtag: null, contractEtagSuperseded: null };
72613
72817
  }
72614
72818
  function etagOf(doc) {
72615
- return doc == null ? null : `"${contractHash(doc)}"`;
72819
+ return doc == null ? null : `"${contractIdentityHash(doc)}"`;
72616
72820
  }
72617
72821
  function storeEtag(appId, projectId) {
72618
72822
  return etagOf(readContract(appId, projectId));
72619
72823
  }
72824
+ function storeEtags(appId, projectId) {
72825
+ return etagsOf(readContract(appId, projectId));
72826
+ }
72620
72827
  function storedContractBytesExist(appId, projectId) {
72621
72828
  return (0, import_node_fs41.existsSync)(contractPath(appId, projectId));
72622
72829
  }
@@ -72674,7 +72881,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72674
72881
  return withLifecycleLock(kind, key2, () => {
72675
72882
  assertServable(projectId);
72676
72883
  const current = readContract(appId, projectId);
72677
- const currentTag = etagOf(current);
72884
+ const currentTags = etagsOf(current);
72678
72885
  if (pre.ifNoneMatch === "*" && current != null) {
72679
72886
  throw new PreconditionFailedError(
72680
72887
  "this store already holds a contract \u2014 GET it and send `If-Match: <the ETag>` as the only precondition to replace it"
@@ -72686,7 +72893,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72686
72893
  "this store holds no contract to replace \u2014 send `If-None-Match: *` as the only precondition to create one"
72687
72894
  );
72688
72895
  }
72689
- if (pre.ifMatch !== "*" && pre.ifMatch !== currentTag) {
72896
+ if (pre.ifMatch !== "*" && !recordedEtagNamesContract(pre.ifMatch, currentTags)) {
72690
72897
  throw new PreconditionFailedError(
72691
72898
  "the contract changed since you last read it \u2014 GET it again, re-apply your edit to that document, and write with the new `If-Match: <the ETag>`"
72692
72899
  );
@@ -72732,7 +72939,8 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72732
72939
  let publication;
72733
72940
  try {
72734
72941
  publication = writeContract(appId, finalContract, projectId, {
72735
- operation: "put",
72942
+ // `restore` for a document coming back out of history; `put` for everything that composes one.
72943
+ operation: origin.origin === "contract-generation" && origin.restoring ? "restore" : "put",
72736
72944
  currentType: storedType
72737
72945
  });
72738
72946
  } catch (e) {
@@ -72753,7 +72961,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72753
72961
  } else if (declaredTypeOf(finalContract) === STEEL_V2) {
72754
72962
  persistConnectionReviewForWrite({
72755
72963
  projectId: projectId ?? null,
72756
- finalAfter: normaliseRollMarkers(finalContract),
72964
+ finalAfter: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72757
72965
  origin: reviewOriginForGatewayWrite(origin.origin)
72758
72966
  });
72759
72967
  }
@@ -72766,7 +72974,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72766
72974
  // review's `self` baseline was recorded against the un-normalised doc and read back drifted, and
72767
72975
  // `member-end-routes` staged its undo token over a hash the store would never reproduce, so Undo
72768
72976
  // silently never offered itself. Idempotent, and free when nothing carried a marker.
72769
- contract: normaliseRollMarkers(finalContract),
72977
+ contract: normalisePlanViewIds(normaliseRollMarkers(finalContract)),
72770
72978
  invalidatedWorkPointDecisions: prepared.invalidated,
72771
72979
  ...revalidation ? { revalidation } : {}
72772
72980
  };
@@ -72787,10 +72995,11 @@ function writeConnectionPlacementChecked(appId, doc, projectId, ifMatch, placeme
72787
72995
  [CONNECTION_PLACEMENT_AUTHORITY]: true
72788
72996
  });
72789
72997
  }
72790
- function writeContractGenerationChecked(appId, doc, projectId, why) {
72998
+ function writeContractGenerationChecked(appId, doc, projectId, why, opts = {}) {
72791
72999
  return writeContractChecked(appId, doc, projectId, {
72792
73000
  origin: "contract-generation",
72793
73001
  why,
73002
+ restoring: opts.restoring,
72794
73003
  [CONTRACT_GENERATION_AUTHORITY]: true
72795
73004
  });
72796
73005
  }
@@ -74002,7 +74211,12 @@ var REGISTRY = /* @__PURE__ */ new Map([
74002
74211
  ["$.plans[]", { disposition: "propose", note: "a sheet" }],
74003
74212
  // The MATCH KEY, exactly like `$.members[].id`: plans are paired by sheet before diffing, so this can
74004
74213
  // 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" }],
74214
+ // THE MATCH KEY is the view id (#938): plans are paired by it before diffing, so a change to it is an
74215
+ // add plus a remove rather than an edit.
74216
+ ["$.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" }],
74217
+ // The PAGE a view was read off is evidence about where the read was made, and evidence is written
74218
+ // once. It no longer pairs the documents, but it is no more revisable for that.
74219
+ ["$.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
74220
  ["$.plans[].viewKind", { disposition: "propose", note: "the reader's explicit sheet classification; unsupported kinds remain stored but are refused by their transform" }],
74007
74221
  // The canonical registration a revision read may genuinely move: where the cut plane sits, which grid
74008
74222
  // intersection anchors the sheet, what it is called, and which members it presents.
@@ -74222,6 +74436,8 @@ function revisionFramePreservesPlacement(before, after, memberId) {
74222
74436
  }
74223
74437
  }
74224
74438
  function stageRevisionRead(current, incoming) {
74439
+ current = normalisePlanViewIds(current);
74440
+ incoming = normalisePlanViewIds(incoming);
74225
74441
  const accepted = [];
74226
74442
  const bindingUpdates = [];
74227
74443
  const bindingProposals = [];
@@ -74231,7 +74447,17 @@ function stageRevisionRead(current, incoming) {
74231
74447
  const curObs = observationsOf(current);
74232
74448
  const incMembers = new Map((incoming.members ?? []).map((m) => [m.id, m]));
74233
74449
  const curMembers = new Map((current.members ?? []).map((m) => [m.id, m]));
74234
- const currentSheets = new Set((current.plans ?? []).map((p) => p.sheet));
74450
+ const currentViewIds = new Set((current.plans ?? []).map(planViewId));
74451
+ const labelSiblings = (() => {
74452
+ const byId = /* @__PURE__ */ new Map();
74453
+ for (const plan of [...current.plans ?? [], ...incoming.plans ?? []]) {
74454
+ const id = planViewId(plan);
74455
+ if (id && !byId.has(id)) byId.set(id, plan);
74456
+ }
74457
+ return [...byId.values()];
74458
+ })();
74459
+ const viewLabels = planViewLabels(labelSiblings);
74460
+ const viewLabelOf = (plan) => viewLabels.get(planViewId(plan)) ?? plan.sheet;
74235
74461
  const ownIssues = /* @__PURE__ */ new Map();
74236
74462
  const order = [];
74237
74463
  const seenIncoming = /* @__PURE__ */ new Set();
@@ -74249,8 +74475,8 @@ function stageRevisionRead(current, incoming) {
74249
74475
  bad(`${path}.evidence.source.sheet`, "observation-sheet-missing", "evidence names no source sheet, so it cannot be filed against a plan");
74250
74476
  } else if (citedSheet !== plan.sheet) {
74251
74477
  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`);
74478
+ } else if (!currentViewIds.has(planViewId(plan))) {
74479
+ 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
74480
  }
74255
74481
  for (const id of obs.binding?.memberIds ?? []) {
74256
74482
  if (curMembers.has(id)) continue;
@@ -74267,7 +74493,7 @@ function stageRevisionRead(current, incoming) {
74267
74493
  const admissible = new Set([...ownIssues].filter(([, v]) => v.length === 0).map(([k]) => k));
74268
74494
  const landing = [];
74269
74495
  const pendingUpdates = [];
74270
- for (const { obs, path } of order) {
74496
+ for (const { plan, obs, path } of order) {
74271
74497
  const mine = ownIssues.get(obs.id) ?? [];
74272
74498
  issues.push(...mine);
74273
74499
  if (mine.length) continue;
@@ -74281,7 +74507,7 @@ function stageRevisionRead(current, incoming) {
74281
74507
  if (rejected) continue;
74282
74508
  const existing = curObs.get(obs.id);
74283
74509
  if (!existing) {
74284
- landing.push({ obs, path });
74510
+ landing.push({ obs, path, viewId: planViewId(plan) });
74285
74511
  continue;
74286
74512
  }
74287
74513
  if (json(existing.obs.evidence) !== json(obs.evidence)) {
@@ -74352,9 +74578,9 @@ function stageRevisionRead(current, incoming) {
74352
74578
  candidates.delete(id);
74353
74579
  }
74354
74580
  }
74355
- for (const { obs, path } of landing) {
74581
+ for (const { obs, path, viewId } of landing) {
74356
74582
  if (candidates.has(obs.id)) {
74357
- accepted.push(withoutForgedVerification(obs, bindingProposals));
74583
+ accepted.push({ viewId, observation: withoutForgedVerification(obs, bindingProposals) });
74358
74584
  continue;
74359
74585
  }
74360
74586
  const orphaned = orphanedBy.get(obs.id);
@@ -74436,38 +74662,38 @@ function stageRevisionRead(current, incoming) {
74436
74662
  }
74437
74663
  if (fields.length) proposals.push({ kind: "member-changed", memberId: id, fields });
74438
74664
  }
74439
- const incomingSheets = new Set((incoming.plans ?? []).map((p) => p.sheet));
74440
- for (const sheet of currentSheets) {
74441
- if (!incomingSheets.has(sheet)) {
74665
+ const incomingViewIds = new Set((incoming.plans ?? []).map(planViewId));
74666
+ for (const viewId of currentViewIds) {
74667
+ if (!incomingViewIds.has(viewId)) {
74442
74668
  add(
74443
- `$.plans[${sheet}]`,
74669
+ `$.plans[${viewId}]`,
74444
74670
  "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`
74671
+ `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
74672
  );
74447
74673
  }
74448
74674
  }
74449
74675
  for (const id of curMembers.keys()) {
74450
74676
  if (!incMembers.has(id)) proposals.push({ kind: "member-removed", memberId: id });
74451
74677
  }
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) {
74678
+ const curPlans = new Map((current.plans ?? []).map((p) => [planViewId(p), p]));
74679
+ const viewIdCounts = /* @__PURE__ */ new Map();
74680
+ for (const plan of incoming.plans ?? []) viewIdCounts.set(planViewId(plan), (viewIdCounts.get(planViewId(plan)) ?? 0) + 1);
74681
+ for (const [viewId, n] of viewIdCounts) {
74456
74682
  if (n < 2) continue;
74457
74683
  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`
74684
+ `$.plans[${viewId}]`,
74685
+ "plan-view-id-duplicate",
74686
+ `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
74687
  );
74462
74688
  }
74463
74689
  for (const plan of incoming.plans ?? []) {
74464
- if ((sheetCounts.get(plan.sheet) ?? 0) > 1) continue;
74465
- const existing = curPlans.get(plan.sheet);
74690
+ if ((viewIdCounts.get(planViewId(plan)) ?? 0) > 1) continue;
74691
+ const existing = curPlans.get(planViewId(plan));
74466
74692
  if (existing) {
74467
74693
  const planFields = [];
74468
74694
  for (const key2 of /* @__PURE__ */ new Set([...Object.keys(existing), ...Object.keys(plan)])) {
74469
74695
  if (key2 === "memberObservations") continue;
74470
- if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${plan.sheet}].${key2}`))) continue;
74696
+ if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${planViewId(plan)}].${key2}`))) continue;
74471
74697
  const b = existing[key2];
74472
74698
  const a = plan[key2];
74473
74699
  const entry2 = entryFor(`$.plans[].${key2}`);
@@ -74475,17 +74701,17 @@ function stageRevisionRead(current, incoming) {
74475
74701
  if (entry2?.disposition === "propose") planFields.push({ key: key2, before: b, after: a });
74476
74702
  else {
74477
74703
  add(
74478
- `$.plans[${plan.sheet}].${key2}`,
74704
+ `$.plans[${planViewId(plan)}].${key2}`,
74479
74705
  "path-refused",
74480
- `"${key2}" on an existing sheet may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
74706
+ `"${key2}" on an existing drawing view may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
74481
74707
  );
74482
74708
  }
74483
74709
  }
74484
- if (planFields.length) proposals.push({ kind: "plan-changed", sheet: plan.sheet, fields: planFields });
74710
+ if (planFields.length) proposals.push({ kind: "plan-changed", viewId: planViewId(plan), sheet: plan.sheet, viewLabel: viewLabelOf(plan), fields: planFields });
74485
74711
  continue;
74486
74712
  }
74487
74713
  const { memberObservations: _refused, ...sheetOnly } = plan;
74488
- proposals.push({ kind: "plan-added", sheet: plan.sheet, plan: sheetOnly });
74714
+ proposals.push({ kind: "plan-added", viewId: planViewId(plan), sheet: plan.sheet, viewLabel: viewLabelOf(plan), plan: sheetOnly });
74489
74715
  }
74490
74716
  const HANDLED_ROOT = /* @__PURE__ */ new Set(["members", "plans"]);
74491
74717
  const curRoot = current;
@@ -74598,18 +74824,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74598
74824
  break;
74599
74825
  }
74600
74826
  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`);
74827
+ if (p.plan?.sheet !== p.sheet || planViewId(p.plan) !== p.viewId) {
74828
+ 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
74829
  }
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`);
74830
+ if (next.plans.some((pl2) => planViewId(pl2) === p.viewId)) {
74831
+ throw new RevisionApplyError(`applyStagedRevision: view "${p.viewId}" already exists, so the staged addition does not describe this document`);
74606
74832
  }
74607
74833
  next.plans.push(structuredClone(p.plan));
74608
74834
  break;
74609
74835
  }
74610
74836
  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`);
74837
+ const pl2 = next.plans.find((x) => planViewId(x) === p.viewId);
74838
+ if (!pl2) throw new RevisionApplyError(`applyStagedRevision: view "${p.viewId}" is not in this document, so the staged change does not describe it`);
74613
74839
  for (const f of p.fields) {
74614
74840
  if (!writableLeaf(`$.plans[].${f.key}`)) {
74615
74841
  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 +74860,9 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74634
74860
  }
74635
74861
  }
74636
74862
  }
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]);
74863
+ const byView = /* @__PURE__ */ new Map();
74864
+ for (const { viewId, observation } of staged.accepted) {
74865
+ byView.set(viewId, [...byView.get(viewId) ?? [], observation]);
74641
74866
  }
74642
74867
  const updates = /* @__PURE__ */ new Map();
74643
74868
  for (const u of [...staged.bindingUpdates, ...pick(staged.bindingProposals, selection.bindingProposals, "bindingProposals")]) {
@@ -74647,18 +74872,18 @@ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
74647
74872
  updates.set(u.observationId, u.to);
74648
74873
  }
74649
74874
  for (const plan of next.plans) {
74650
- const arriving = bySheet.get(plan.sheet);
74875
+ const arriving = byView.get(planViewId(plan));
74651
74876
  if (arriving?.length) {
74652
74877
  plan.memberObservations = [...plan.memberObservations ?? [], ...structuredClone(arriving)];
74653
- bySheet.delete(plan.sheet);
74878
+ byView.delete(planViewId(plan));
74654
74879
  }
74655
74880
  for (const obs of plan.memberObservations ?? []) {
74656
74881
  const to = updates.get(obs.id);
74657
74882
  if (to) obs.binding = structuredClone(to);
74658
74883
  }
74659
74884
  }
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`);
74885
+ if (byView.size > 0) {
74886
+ throw new Error(`applyStagedRevision: accepted evidence for unknown view(s) ${[...byView.keys()].join(", ")} \u2014 staging should have refused these`);
74662
74887
  }
74663
74888
  return next;
74664
74889
  }
@@ -76233,21 +76458,24 @@ function steelExclusionPreflight(ledger, filter) {
76233
76458
  }
76234
76459
 
76235
76460
  // revision-request-view.ts
76236
- function filterCheckpointMatchesCurrent(request, currentEtag) {
76237
- return request.type === "revision-read" && request.settledVersion === void 0 && request.prepassReady === true && request.filterSaved === true && typeof request.filterSavedEtag === "string" && request.filterSavedEtag.length > 0 && request.filterSavedEtag === currentEtag;
76461
+ function contractEtagsOf(facts) {
76462
+ return { current: facts?.contractEtag ?? null, superseded: facts?.contractEtagSuperseded ?? null };
76238
76463
  }
76239
- function filterCheckpointIsCurrent(request, currentEtag) {
76240
- return request.status === "pending" && filterCheckpointMatchesCurrent(request, currentEtag);
76464
+ function filterCheckpointMatchesCurrent(request, current) {
76465
+ return request.type === "revision-read" && request.settledVersion === void 0 && request.prepassReady === true && request.filterSaved === true && typeof request.filterSavedEtag === "string" && request.filterSavedEtag.length > 0 && recordedEtagNamesContract(request.filterSavedEtag, current);
76466
+ }
76467
+ function filterCheckpointIsCurrent(request, current) {
76468
+ return request.status === "pending" && filterCheckpointMatchesCurrent(request, current);
76241
76469
  }
76242
76470
  function acceptedContractFacts(appId, projectId) {
76243
76471
  try {
76244
76472
  return acceptedContractIdentity(appId, projectId);
76245
76473
  } catch {
76246
- return { contractType: void 0, contractEtag: null };
76474
+ return { contractType: void 0, contractEtag: null, contractEtagSuperseded: null };
76247
76475
  }
76248
76476
  }
76249
- function acceptedContractEtag(appId, projectId) {
76250
- return acceptedContractFacts(appId, projectId).contractEtag;
76477
+ function acceptedContractEtags(appId, projectId) {
76478
+ return contractEtagsOf(acceptedContractFacts(appId, projectId));
76251
76479
  }
76252
76480
  function revisionRequestStageId(request) {
76253
76481
  if (request.type !== "revision-read" || request.status !== "staged" || !request.project) return void 0;
@@ -76260,7 +76488,10 @@ function revisionRequestStageId(request) {
76260
76488
  function revisionRequestViewFields(request, memo = {}) {
76261
76489
  const discard = request.type === "revision-read" && request.status === "staged" ? revisionDiscardPolicyFor(request) : void 0;
76262
76490
  const contractFacts = request.type === "revision-read" && request.appId && request.project ? (memo.contractFacts ?? acceptedContractFacts)(request.appId, request.project) : void 0;
76491
+ const etags = contractEtagsOf(contractFacts);
76492
+ const canonicalCheckpointEtag = request.type === "revision-read" && request.appId && request.project && filterCheckpointMatchesCurrent(request, etags) && etags.current ? etags.current : void 0;
76263
76493
  return {
76494
+ ...canonicalCheckpointEtag ? { filterSavedEtag: canonicalCheckpointEtag } : {},
76264
76495
  appTemplateId: request.appId ? (memo.templateId ?? resolveTemplateId)(request.appId) : void 0,
76265
76496
  nativeSteelReady: request.type === "revision-read" && request.appId && request.project ? (() => {
76266
76497
  const project = getProject(request.project);
@@ -76272,10 +76503,7 @@ function revisionRequestViewFields(request, memo = {}) {
76272
76503
  canDiscardRevision: discard?.canClear,
76273
76504
  discardWhy: discard?.clearWhy,
76274
76505
  discardState: discard?.clearState,
76275
- filterCheckpointCurrent: request.type === "revision-read" && request.appId && request.project ? filterCheckpointIsCurrent(
76276
- request,
76277
- contractFacts?.contractEtag ?? null
76278
- ) : void 0
76506
+ filterCheckpointCurrent: request.type === "revision-read" && request.appId && request.project ? filterCheckpointIsCurrent(request, etags) : void 0
76279
76507
  };
76280
76508
  }
76281
76509
  function enrichedRevisionRequestView(request, extra, memo = {}) {
@@ -76497,7 +76725,7 @@ function loadAuthoritativeSteelAuditState(project, requestId, attestation, allow
76497
76725
  })) throw new SteelAuditStateError("steel-source-manifest-changed", "the verified project source bytes no longer match the manifest");
76498
76726
  const parsedAttestation = parseSteelReadAttestation(attestation);
76499
76727
  const current = readAcceptedForRequest(project.app, project.id, "read");
76500
- if (!filterCheckpointMatchesCurrent(request, etagOf(current))) {
76728
+ if (!filterCheckpointMatchesCurrent(request, etagsOf(current))) {
76501
76729
  throw new SteelAuditStateError("steel-filter-save-missing", "the request has no current exact Filter Save checkpoint");
76502
76730
  }
76503
76731
  return {
@@ -76587,7 +76815,7 @@ async function stageForReview(reply, project, requestId, candidate, filterSavedE
76587
76815
  }
76588
76816
  const candidateDoc = candidate;
76589
76817
  const currentDoc = current;
76590
- if (!filterSavedEtag || etagOf(current) !== filterSavedEtag) {
76818
+ if (!recordedEtagNamesContract(filterSavedEtag, etagsOf(current))) {
76591
76819
  return reply.status(409).send({ ok: false, code: "filter-save-changed", error: "the model changed after the Drawing Filter was saved \xE2\u20AC\u201D reload and save it again" });
76592
76820
  }
76593
76821
  if (contractHash(currentDoc.filter) !== contractHash(candidateDoc.filter)) {
@@ -77488,8 +77716,8 @@ function registerRevisionRoutes(app, deps = {}) {
77488
77716
  async (req, reply) => withLifecycleLock("project", req.params.id, async () => {
77489
77717
  const project = getProject(req.params.id);
77490
77718
  const request = getRequest(req.params.reqId);
77491
- const currentEtag = project ? acceptedContractEtag(project.app, project.id) : null;
77492
- if (!project || !request || request.type !== "revision-read" || request.project !== project.id || !filterCheckpointIsCurrent(request, currentEtag)) {
77719
+ const currentEtags = project ? acceptedContractEtags(project.app, project.id) : { current: null, superseded: null };
77720
+ if (!project || !request || request.type !== "revision-read" || request.project !== project.id || !filterCheckpointIsCurrent(request, currentEtags)) {
77493
77721
  return reply.status(404).send({ ok: false, error: "unknown active drawing read" });
77494
77722
  }
77495
77723
  let progress;
@@ -77531,9 +77759,11 @@ function registerRevisionRoutes(app, deps = {}) {
77531
77759
  if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.status !== "pending" || request.settledVersion !== void 0) {
77532
77760
  return reply.status(404).send({ ok: false, error: "unknown pending revision request" });
77533
77761
  }
77534
- const etag = typeof req.body?.etag === "string" ? req.body.etag : "";
77762
+ const supplied = typeof req.body?.etag === "string" ? req.body.etag : "";
77535
77763
  const current = readAcceptedForRequest(project.app, project.id, "read");
77536
- if (!request.prepassReady || !etag || etag !== etagOf(current) || !hasSteelFilterCheckpoint(current)) return reply.status(409).send({ ok: false, error: "save the populated Steel Filter that this request pre-read before continuing" });
77764
+ const currentTags = etagsOf(current);
77765
+ if (!request.prepassReady || !recordedEtagNamesContract(supplied, currentTags) || !hasSteelFilterCheckpoint(current)) return reply.status(409).send({ ok: false, error: "save the populated Steel Filter that this request pre-read before continuing" });
77766
+ const etag = currentTags.current;
77537
77767
  if (req.body?.layerSignOff !== void 0) {
77538
77768
  return reply.status(400).send({
77539
77769
  ok: false,
@@ -77831,15 +78061,15 @@ function registerRevisionRoutes(app, deps = {}) {
77831
78061
  error: "resume this read with If-Match set to the ETag recorded by the Steel Filter Save"
77832
78062
  });
77833
78063
  }
77834
- if (!ifMatchTags.includes(request.filterSavedEtag)) {
78064
+ const liveTags = etagsOf(readAcceptedForRequest(project.app, project.id, "read"));
78065
+ if (!recordedEtagNamesContract(request.filterSavedEtag, liveTags)) {
77835
78066
  return reply.status(412).send({
77836
78067
  ok: false,
77837
78068
  code: "filter-save-changed",
77838
78069
  error: "the Steel Filter contract changed after Save \u2014 re-read it before committing this revision"
77839
78070
  });
77840
78071
  }
77841
- const liveEtag = etagOf(readAcceptedForRequest(project.app, project.id, "read"));
77842
- if (!liveEtag || !ifMatchTags.includes(liveEtag)) {
78072
+ if (!ifMatchTags.some((tag) => recordedEtagNamesContract(tag, liveTags))) {
77843
78073
  return reply.status(412).send({ ok: false, code: "filter-save-changed", error: "the contract changed after Steel Filter Save \u2014 re-read it before committing this revision" });
77844
78074
  }
77845
78075
  }
@@ -77856,7 +78086,7 @@ function registerRevisionRoutes(app, deps = {}) {
77856
78086
  }
77857
78087
  const appTemplateId = resolveTemplateId(project.app);
77858
78088
  const candidateType = declaredTypeOf(req.body.contract);
77859
- if (appTemplateId === "steel-model" && !filterCheckpointMatchesCurrent(request, etagOf(currentForEvidence))) {
78089
+ if (appTemplateId === "steel-model" && !filterCheckpointMatchesCurrent(request, etagsOf(currentForEvidence))) {
77860
78090
  return reply.status(409).send({
77861
78091
  ok: false,
77862
78092
  error: "complete this request's Steel Filter pre-read, then review and Save the Filter before committing the read"
@@ -78844,7 +79074,7 @@ async function applyReviewVerb(verb, projectId, jointId, expected, ifMatch) {
78844
79074
  if (!ifMatch) {
78845
79075
  throw new PreconditionRequiredError("marking a connection reviewed requires If-Match \u2014 the model generation you looked at");
78846
79076
  }
78847
- if (ifMatch !== snapshot.etag) {
79077
+ if (!recordedEtagNamesContract(ifMatch, etagsOf(model))) {
78848
79078
  throw new ConnectionCommandError(
78849
79079
  "the model changed while you were looking at this connection \u2014 reload and check it again before marking it reviewed",
78850
79080
  "contract-changed",
@@ -79041,26 +79271,28 @@ function registerSteelPrepassRoute(app, deps) {
79041
79271
  }
79042
79272
  let doc = structuredClone(current);
79043
79273
  const plans = Array.isArray(doc.plans) ? doc.plans.filter(isObj8) : [];
79044
- const names2 = plans.map((plan) => String(plan.sheet ?? ""));
79274
+ const names2 = plans.map((plan) => rawPlanViewId(plan) ?? "");
79045
79275
  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(", ")}` });
79276
+ if (missing.length) return reply.status(400).send({ ok: false, code: "prepass-unknown-sheet", error: `unknown drawing view: ${missing.join(", ")}` });
79047
79277
  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(", ")}` });
79278
+ if (duplicates.length) return reply.status(400).send({ ok: false, code: "prepass-duplicate-sheet", error: `duplicate drawing view: ${duplicates.join(", ")}` });
79049
79279
  let applied = false;
79050
79280
  if (body.filter !== void 0) {
79051
79281
  doc.filter = body.filter;
79052
79282
  applied = true;
79053
79283
  }
79054
79284
  const refErrors = [];
79285
+ const viewLabels = planViewLabels(plans);
79055
79286
  for (const plan of plans) {
79056
- const sheet = String(plan.sheet ?? "");
79287
+ const sheet = rawPlanViewId(plan) ?? "";
79288
+ const viewName = viewLabels.get(sheet) ?? sheet;
79057
79289
  const patch2 = sheets[sheet];
79058
79290
  if (!isObj8(patch2)) continue;
79059
79291
  if (plan.viewKind !== "plan" && PLAN_KEYS.some((key2) => patch2[key2] !== void 0)) {
79060
79292
  return reply.status(400).send({
79061
79293
  ok: false,
79062
79294
  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`
79295
+ 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
79296
  });
79065
79297
  }
79066
79298
  for (const key2 of PLAN_KEYS) {
@@ -79096,7 +79328,8 @@ function registerSteelPrepassRoute(app, deps) {
79096
79328
  }
79097
79329
  }
79098
79330
  const filterSheets = filterSheetsOf(doc);
79099
- const unregistered = filterSheets.map((sheet) => typeof sheet.sheet === "string" ? sheet.sheet.trim() : "").filter((sheet) => sheet && !names2.includes(sheet));
79331
+ const registeredPages = new Set(plans.map((plan) => String(plan.sheet ?? "")));
79332
+ const unregistered = filterSheets.map((sheet) => typeof sheet.sheet === "string" ? sheet.sheet.trim() : "").filter((sheet) => sheet && !registeredPages.has(sheet));
79100
79333
  if (unregistered.length) {
79101
79334
  return reply.status(400).send({
79102
79335
  ok: false,
@@ -85632,7 +85865,8 @@ function currentApprovedSnapshot(projectId, version) {
85632
85865
  const latestHash = contractHash(latestContract);
85633
85866
  assertOwned(latest, latestHash);
85634
85867
  const draft = readAcceptedForRequest(project.app, projectId, "read");
85635
- const dirtySinceApproval = draft == null || contractHash(draft) !== latestHash;
85868
+ const comparable = comparableContractHash;
85869
+ const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
85636
85870
  return {
85637
85871
  project,
85638
85872
  version: row,
@@ -85786,6 +86020,7 @@ function atomicChanged(opts, groups) {
85786
86020
  groups.push(group);
85787
86021
  return atomicNode(group.id, opts.before, opts.after);
85788
86022
  }
86023
+ var parentLabel = (opts) => opts.parentLabel ?? String(opts.parent);
85789
86024
  function keyedCollection(opts) {
85790
86025
  const beforePresent = opts.before !== void 0;
85791
86026
  const afterPresent = opts.after !== void 0;
@@ -85797,7 +86032,7 @@ function keyedCollection(opts) {
85797
86032
  entity: "collection",
85798
86033
  category: opts.category,
85799
86034
  headline: `${opts.category} collection`,
85800
- location: opts.parent ? String(opts.parent) : "Model",
86035
+ location: opts.parent ? parentLabel(opts) : "Model",
85801
86036
  before: beforePresent ? opts.before : ABSENT,
85802
86037
  after: afterPresent ? opts.after : ABSENT
85803
86038
  }, opts.groups) };
@@ -85830,7 +86065,7 @@ function keyedCollection(opts) {
85830
86065
  entity: key2,
85831
86066
  category: opts.category,
85832
86067
  headline: opts.labelOf(isObj9(bv) ? bv : av, key2),
85833
- location: opts.parent ? `${String(opts.parent)} \xB7 ${key2}` : key2,
86068
+ location: opts.parent ? `${parentLabel(opts)} \xB7 ${key2}` : key2,
85834
86069
  before: av,
85835
86070
  after: bv,
85836
86071
  references: isObj9(bv) ? opts.referencesOf?.(bv) : []
@@ -85883,6 +86118,7 @@ function nestedEntity(base, draft, opts, groups) {
85883
86118
  type: opts.type,
85884
86119
  collection: n.collection,
85885
86120
  parent: opts.identity,
86121
+ parentLabel: opts.identityLabel,
85886
86122
  category: n.category,
85887
86123
  before: base[n.key],
85888
86124
  after: draft[n.key],
@@ -85975,6 +86211,15 @@ function unionDependencies(groups) {
85975
86211
  for (const id of ids) groups.find((group) => group.id === id).dependencyGroup = digest2;
85976
86212
  }
85977
86213
  }
86214
+ function planLabeller(base, draft) {
86215
+ const byId = /* @__PURE__ */ new Map();
86216
+ for (const row of [...arr4(isObj9(draft) ? draft.plans : null), ...arr4(isObj9(base) ? base.plans : null)]) {
86217
+ const key2 = rawPlanViewId(row);
86218
+ if (key2 !== null && !byId.has(key2)) byId.set(key2, row);
86219
+ }
86220
+ const labels = planViewLabels([...byId.values()]);
86221
+ return (_row, key2) => `Sheet ${labels.get(key2) ?? key2}`;
86222
+ }
85978
86223
  function fallback(base, draft, type, reason) {
85979
86224
  const group = groupOf({
85980
86225
  type,
@@ -86010,20 +86255,21 @@ function buildKnown(base, draft, type) {
86010
86255
  groups,
86011
86256
  referencesOf: (v) => arr4(v.ends).flatMap((end) => isObj9(end) && typeof end.conn === "string" ? [token(type, "connection", null, end.conn)] : [])
86012
86257
  }));
86258
+ const planLabel = planLabeller(base, draft);
86013
86259
  add("plans", keyedCollection({
86014
86260
  type,
86015
86261
  collection: "plan",
86016
86262
  category: "Sheet",
86017
86263
  before: base.plans,
86018
86264
  after: draft.plans,
86019
- keyOf: (v) => typeof v.sheet === "string" ? v.sheet : null,
86020
- labelOf: (_v2, key2) => `Sheet ${key2}`,
86265
+ keyOf: (v) => rawPlanViewId(v),
86266
+ labelOf: planLabel,
86021
86267
  groups,
86022
86268
  buildItem: (a, b, key2) => nestedEntity(a, b, {
86023
86269
  type,
86024
86270
  collection: "plan",
86025
86271
  identity: key2,
86026
- identityLabel: `Sheet ${key2}`,
86272
+ identityLabel: planLabel(a ?? b ?? {}, key2),
86027
86273
  nested: [
86028
86274
  {
86029
86275
  key: "memberObservations",
@@ -86381,6 +86627,11 @@ function mergeContractForward(base, latest, draft, resolutions = {}) {
86381
86627
  return { merged, conflicts };
86382
86628
  }
86383
86629
 
86630
+ // approval-forward-merge.ts
86631
+ function mergeApprovalForward(base, latest, draft, resolutions = {}) {
86632
+ return mergeContractForward(base, normalisePlanViewIds(latest), draft, resolutions);
86633
+ }
86634
+
86384
86635
  // approval-review-service.ts
86385
86636
  function prepareProjectApprovalReview(projectId, deps) {
86386
86637
  const project = getProject(projectId);
@@ -86413,7 +86664,7 @@ function prepareProjectApprovalReview(projectId, deps) {
86413
86664
  if (manifest?.workingBase && snapshot.contractHash !== manifest.workingBase.hash) {
86414
86665
  throw new WorkspaceSnapshotError(409, "the working revision base proof no longer matches History; keep it as a checkpoint and start again");
86415
86666
  }
86416
- baseContract = snapshot.contract;
86667
+ baseContract = normalisePlanViewIds(snapshot.contract);
86417
86668
  base = { version: snapshot.version.n, hash: snapshot.contractHash, approvedAt: snapshot.currentApprovedAt ?? void 0 };
86418
86669
  }
86419
86670
  const draftHash = contractHash(draft);
@@ -86433,11 +86684,11 @@ function prepareProjectApprovalReview(projectId, deps) {
86433
86684
  });
86434
86685
  if (base && row && base.version !== row.n) {
86435
86686
  const latest = currentApprovedSnapshot(projectId);
86436
- const preview2 = mergeContractForward(baseContract, latest.contract, draft);
86687
+ const preview2 = mergeApprovalForward(baseContract, latest.contract, draft);
86437
86688
  const groupsByPath = /* @__PURE__ */ new Map();
86438
86689
  for (const group of prepared.partition.groups) {
86439
86690
  const single = prepared.partition.materialize([group.id]);
86440
- for (const conflict of mergeContractForward(baseContract, latest.contract, single).conflicts) {
86691
+ for (const conflict of mergeApprovalForward(baseContract, latest.contract, single).conflicts) {
86441
86692
  const ids = groupsByPath.get(conflict.path) ?? [];
86442
86693
  ids.push(group.id);
86443
86694
  groupsByPath.set(conflict.path, ids);
@@ -86709,8 +86960,7 @@ function captureExportSource(projectId, selector = { kind: "latest-approved" },
86709
86960
  contract = readAcceptedForRequest(project.app, projectId, "read");
86710
86961
  if (contract == null) throw new Error("working copy is unavailable");
86711
86962
  const manifest = readWorkingRevisionManifest(project);
86712
- const actualEtag = etagOf(contract);
86713
- if (selector.expectedEtag && selector.expectedEtag !== actualEtag) throw new Error("working copy changed; reload before exporting");
86963
+ if (selector.expectedEtag && !recordedEtagNamesContract(selector.expectedEtag, etagsOf(contract))) throw new Error("working copy changed; reload before exporting");
86714
86964
  if (selector.expectedEpoch !== void 0 && selector.expectedEpoch !== manifest?.epoch) throw new Error("working revision changed; reload before exporting");
86715
86965
  kind = "working";
86716
86966
  sourceRef = manifest?.revisionId ?? hashOf(contract).slice(0, 12);
@@ -88379,7 +88629,7 @@ function summarizeBaseline(to) {
88379
88629
  }
88380
88630
  const baseline = diffContracts(to, to);
88381
88631
  const memberCount = view.members.length;
88382
- const sheetCount = view.sheets.length;
88632
+ const sheetCount = new Set(view.sheets.map((s) => s.sheet)).size;
88383
88633
  const totalLb = baseline.tonnage.toLb;
88384
88634
  const totalTons = baseline.tonnage.toTons;
88385
88635
  const bullets = [`${countWord(memberCount, "member")} across ${countWord(sheetCount, "drawing sheet")}.`];
@@ -88582,7 +88832,7 @@ function bakeContractIntoApp(sourcePath2, contract) {
88582
88832
  if (!view) {
88583
88833
  throw new InvalidModelV2Error(`refusing to bake: contract declares steel.model/v2 but is not valid v2: ${issues[0] ?? "unknown"}`, issues);
88584
88834
  }
88585
- doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(contract));
88835
+ doc.setIn(["nodes", idx, "config", "takeoff"], bakedV2(view.doc));
88586
88836
  (0, import_node_fs62.writeFileSync)(sourcePath2, doc.toString());
88587
88837
  return;
88588
88838
  }
@@ -100075,12 +100325,12 @@ async function startServer() {
100075
100325
  }
100076
100326
  const current = readAcceptedForRequest(project.app, project.id, "read");
100077
100327
  if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
100078
- const actualEtag = storeEtag(project.app, project.id);
100328
+ const actualEtags = storeEtags(project.app, project.id);
100079
100329
  const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
100080
100330
  if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100081
100331
  return reply.status(428).send({ ok: false, error: "Reload History and send the working ETag and revision epoch." });
100082
100332
  }
100083
- if (req.body.expectedEtag !== actualEtag) {
100333
+ if (!recordedEtagNamesContract(req.body.expectedEtag, actualEtags)) {
100084
100334
  return reply.status(409).send({ ok: false, error: "The working copy changed. Reload History before starting." });
100085
100335
  }
100086
100336
  const observedManifest = readWorkingRevisionManifest(project);
@@ -100098,7 +100348,7 @@ async function startServer() {
100098
100348
  manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100099
100349
  }
100100
100350
  const latest = currentApprovedSnapshot(project.id);
100101
- const dirty = contractHash(current) !== latest.contractHash;
100351
+ const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
100102
100352
  const checkpoint = dirty ? captureProjectCheckpoint({
100103
100353
  project,
100104
100354
  publicationIdentity,
@@ -100108,7 +100358,7 @@ async function startServer() {
100108
100358
  }) : null;
100109
100359
  let publication = null;
100110
100360
  try {
100111
- const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`);
100361
+ const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
100112
100362
  publication = written;
100113
100363
  } catch (error) {
100114
100364
  if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
@@ -100120,7 +100370,11 @@ async function startServer() {
100120
100370
  expectedEpoch: manifest.epoch,
100121
100371
  expectedDraftHash: manifest.draftHash,
100122
100372
  publicationIdentity,
100123
- contract: target.contract,
100373
+ contract: normalisePlanViewIds(target.contract),
100374
+ // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
100375
+ // `source.hash` names the version this came from — while `contract:` above is the document the
100376
+ // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
100377
+ // stored canonically made the manifest disagree with the store the instant it was written.
100124
100378
  source: { kind: "approved", version, hash: target.contractHash },
100125
100379
  workingBase: { version, hash: target.contractHash }
100126
100380
  });
@@ -100150,17 +100404,17 @@ async function startServer() {
100150
100404
  if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100151
100405
  return reply.status(428).send({ ok: false, error: "Reload Saved work and send the working ETag and revision epoch." });
100152
100406
  }
100153
- if (req.body.expectedEtag !== storeEtag(project.app, project.id)) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
100407
+ if (!recordedEtagNamesContract(req.body.expectedEtag, storeEtags(project.app, project.id))) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
100154
100408
  const observedManifest = readWorkingRevisionManifest(project);
100155
100409
  if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) return reply.status(409).send({ ok: false, error: "The working revision changed. Reload Saved work." });
100156
100410
  const publicationIdentity = saved.publicationIdentity;
100157
100411
  let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
100158
100412
  if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100159
100413
  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 });
100414
+ if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
100161
100415
  let publication;
100162
100416
  try {
100163
- publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint");
100417
+ publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
100164
100418
  } catch (error) {
100165
100419
  return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
100166
100420
  }
@@ -100170,7 +100424,7 @@ async function startServer() {
100170
100424
  expectedEpoch: manifest.epoch,
100171
100425
  expectedDraftHash: manifest.draftHash,
100172
100426
  publicationIdentity,
100173
- contract: saved.contract,
100427
+ contract: normalisePlanViewIds(saved.contract),
100174
100428
  source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
100175
100429
  workingBase: saved.base
100176
100430
  });
@@ -100303,7 +100557,8 @@ async function startServer() {
100303
100557
  project.app,
100304
100558
  doc,
100305
100559
  project.id,
100306
- "rollback deliberately replaces the current contract with a historical version"
100560
+ "rollback deliberately replaces the current contract with a historical version",
100561
+ { restoring: true }
100307
100562
  );
100308
100563
  } catch (e) {
100309
100564
  if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
@@ -100711,7 +100966,7 @@ async function startServer() {
100711
100966
  }
100712
100967
  mergeResolutions[conflict.path] = choice === "use-draft" ? "draft" : "latest";
100713
100968
  }
100714
- const forward = mergeContractForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100969
+ const forward = mergeApprovalForward(prepared.partition.base, latest.contract, selected.candidate, mergeResolutions);
100715
100970
  approvalCandidate = forward.merged;
100716
100971
  }
100717
100972
  const accepts = projectApprovalCandidateAccepted(req.params.appId, project, approvalCandidate);
@@ -100765,7 +101020,7 @@ async function startServer() {
100765
101020
  const approvedVersion = outcome.version?.n;
100766
101021
  if (selected.pendingIds.length) {
100767
101022
  const pendingAuthor = prepared.partition.materialize(selected.pendingIds);
100768
- const remaining2 = mergeContractForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
101023
+ const remaining2 = mergeApprovalForward(prepared.partition.base, approvalCandidate, pendingAuthor, mergeResolutions);
100769
101024
  if (remaining2.conflicts.length) {
100770
101025
  await writeContractGenerationChecked(req.params.appId, originalDraft, project, "preserve pending reviewed changes after approval");
100771
101026
  } else {