@floless/app 0.134.1 → 0.134.2

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.
@@ -3124,14 +3124,14 @@ var require_validation = __commonJS({
3124
3124
  return acc;
3125
3125
  }, {});
3126
3126
  }
3127
- function compileSchemasForValidation(context, compile, isCustom2) {
3127
+ function compileSchemasForValidation(context, compile, isCustom3) {
3128
3128
  const { schema } = context;
3129
3129
  if (!schema) {
3130
3130
  return;
3131
3131
  }
3132
3132
  const { method, url } = context.config || {};
3133
3133
  const headers = schema.headers;
3134
- if (headers && (isCustom2 || Object.getPrototypeOf(headers) !== Object.prototype)) {
3134
+ if (headers && (isCustom3 || Object.getPrototypeOf(headers) !== Object.prototype)) {
3135
3135
  context[headersSchema] = compile({ schema: headers, method, url, httpPart: "headers" });
3136
3136
  } else if (headers) {
3137
3137
  const headersSchemaLowerCase = {};
@@ -30098,11 +30098,11 @@ var require_route = __commonJS({
30098
30098
  schemaController.setupValidator(this[kOptions]);
30099
30099
  }
30100
30100
  try {
30101
- const isCustom2 = typeof opts?.validatorCompiler === "function" || schemaController.isCustomValidatorCompiler;
30101
+ const isCustom3 = typeof opts?.validatorCompiler === "function" || schemaController.isCustomValidatorCompiler;
30102
30102
  compileSchemasForValidation(
30103
30103
  context,
30104
30104
  opts.validatorCompiler || schemaController.validatorCompiler,
30105
- isCustom2
30105
+ isCustom3
30106
30106
  );
30107
30107
  } catch (error) {
30108
30108
  throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url, error.message);
@@ -55037,7 +55037,7 @@ function appVersion() {
55037
55037
  return resolveVersion({
55038
55038
  isSea: isSea2(),
55039
55039
  sqVersionXml: readSqVersionXml(),
55040
- define: true ? "0.134.1" : void 0,
55040
+ define: true ? "0.134.2" : void 0,
55041
55041
  pkgVersion: readPkgVersion()
55042
55042
  });
55043
55043
  }
@@ -55053,7 +55053,7 @@ function resolveChannel(s) {
55053
55053
  function appChannel() {
55054
55054
  return resolveChannel({
55055
55055
  isSea: isSea2(),
55056
- define: true ? "0.134.1" : void 0,
55056
+ define: true ? "0.134.2" : void 0,
55057
55057
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55058
55058
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55059
55059
  modulePath: process.argv[1]
@@ -58600,7 +58600,8 @@ var UNTRACKED_REASONS = /* @__PURE__ */ new Set([
58600
58600
  "no-members-chosen",
58601
58601
  "app-scoped"
58602
58602
  ]);
58603
- var EMPTY_REVIEW_FILE = () => ({ version: 1, reviewRevision: 0, joints: {} });
58603
+ var emptyJoints = () => /* @__PURE__ */ Object.create(null);
58604
+ var EMPTY_REVIEW_FILE = () => ({ version: 1, reviewRevision: 0, joints: emptyJoints() });
58604
58605
  function projectReviewDir(projectId) {
58605
58606
  return (0, import_node_path16.join)(ROOT2, "projects", safeProjectSeg(projectId));
58606
58607
  }
@@ -58645,7 +58646,7 @@ function parseReviewFile(raw) {
58645
58646
  if (raw.version !== 1) return null;
58646
58647
  if (typeof raw.reviewRevision !== "number" || !Number.isInteger(raw.reviewRevision) || raw.reviewRevision < 0) return null;
58647
58648
  if (!isObj2(raw.joints)) return null;
58648
- const joints = {};
58649
+ const joints = emptyJoints();
58649
58650
  for (const [jointId, row] of Object.entries(raw.joints)) {
58650
58651
  if (!jointId) return null;
58651
58652
  const parsed = parseRow(row);
@@ -58708,7 +58709,7 @@ function writeReviewFile(projectId, next) {
58708
58709
  }
58709
58710
  function dropSignOffsFor(projectId) {
58710
58711
  const current = readReviewFile(projectId);
58711
- const joints = {};
58712
+ const joints = emptyJoints();
58712
58713
  let changed = false;
58713
58714
  for (const [id, row] of Object.entries(current.joints)) {
58714
58715
  if ("baseline" in row && row.signedOff !== void 0) {
@@ -58751,7 +58752,7 @@ function applyConnectionReviewTransition(args) {
58751
58752
  const { projectId, finalAfter, origin, placement } = args;
58752
58753
  const customJoints = (finalAfter.joints ?? []).filter(isCustom);
58753
58754
  if (projectId === null) {
58754
- const joints = {};
58755
+ const joints = emptyJoints();
58755
58756
  for (const j of customJoints) joints[j.id] = { untracked: "app-scoped" };
58756
58757
  return { version: 1, reviewRevision: 0, joints };
58757
58758
  }
@@ -58765,7 +58766,7 @@ function applyConnectionReviewTransition(args) {
58765
58766
  const byId = new Map((finalAfter.members ?? []).map((m) => [m.id, m]));
58766
58767
  let hash3 = null;
58767
58768
  const contractHashLazy = () => hash3 ??= contractHash(finalAfter);
58768
- const next = {};
58769
+ const next = emptyJoints();
58769
58770
  for (const joint of customJoints) {
58770
58771
  const existing = current.joints[joint.id];
58771
58772
  if (origin === "placement" && placement && placement.jointId === joint.id) {
@@ -58873,7 +58874,7 @@ function sanitizeImportedConnectionReview(raw, contract) {
58873
58874
  const doc = contract ?? {};
58874
58875
  const joints = new Map((doc.joints ?? []).filter(isCustom).map((j) => [j.id, j]));
58875
58876
  const byId = new Map((doc.members ?? []).map((m) => [m.id, m]));
58876
- const joints2 = {};
58877
+ const joints2 = emptyJoints();
58877
58878
  for (const [jointId, row] of Object.entries(parsed.joints)) {
58878
58879
  const joint = joints.get(jointId);
58879
58880
  if (!joint) continue;
@@ -63914,7 +63915,7 @@ ${isInitialRead ? "Initial" : "Revised"} drawing${req.snapshots.length > 1 ? "s"
63914
63915
  My note: ${req.instruction}` : "";
63915
63916
  const messageHint = isInitialRead ? "<plain-English what was read>" : "<plain-English what changed>";
63916
63917
  const vectorPost = `GET the current contract again and keep its ETag, then POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that current ETag>. The server derives the base version and source provenance from this queued request. The first completed vector drawing publishes History version 1; later reads stage a review and publish only after confirmation. Do NOT DELETE the request yourself. If you can't read the drawing, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
63917
- const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v2 attestation. The manifest response carries two derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole", candidateShardHash, note } pageReview, and never a second one) and layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger). Keep every disposition reason concise (a short phrase, not a paragraph): the whole attestation has an 8 MB limit, so on a very large set verbose reasons can push it over \u2014 prefer a modeling observation over a written disposition wherever a line is genuinely a member, and note that lines on a layer the human switched OFF and approved as not-steel need NO per-line disposition when you attest that layer annotation, existing or other. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, attestation }; a blocked report is a mandatory checklist, so fix every blocker and repeat until status is read-complete. Then POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
63918
+ const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v4 attestation. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), and facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it). The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour). If even one failing dimension does not, that line needs its own row whatever the others say. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, attestation }; a blocked report is a mandatory checklist, so fix every blocker and repeat until status is read-complete. Then POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
63918
63919
  const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}. This is the only allowed path to inventory source pages and mint Filter element ids. If it returns sheet-identification-required, inspect only the listed pages, establish each sheet identity, and retry with explicit { bindings: [{ pageId, sheet, title?, evidenceKind }] }. If it returns steel-manifest-over-budget, do NOT retry \u2014 stop and tell me, relaying the response's own recovery text: when scope is "page" ONE sheet is too dense and the response's overBudget lists only the offending sheet(s), so that sheet has to come out or be split; when scope is "total" the whole set carries too many elements and must be re-submitted as smaller revisions; when scope is "bytes" the set produces more drawing data than one read can hold, and the lever is WEIGHT not element count \u2014 overBudget lists every sheet with its byte share, heaviest first, and the response's own recovery says whether the fix is moving those sheets out or splitting one sheet that is over on its own. If scope is null the extraction overflowed before anything could be measured, so there is no breakdown at all and the set must be re-submitted as materially smaller revisions. If it returns steel-manifest-extraction-failed, the extraction itself is inconsistent \u2014 do NOT retry (it will fail identically); stop and report it to me with the response's diagnostic. Never build or rename Filter geometry yourself.`;
63919
63920
  if ((req.appTemplateId || req.appId) === "vectorize") {
63920
63921
  if (isInitialRead) {
@@ -64629,6 +64630,35 @@ async function extractConnection(companionId, ifcPath, id, opts = {}) {
64629
64630
  return toCustomConnection(out, id);
64630
64631
  }
64631
64632
 
64633
+ // steel-roll-marker.ts
64634
+ var ROLL_SUFFIX = /[\s-]+FLAT\.?\s*$/i;
64635
+ var FLAT_STOCK = /^\s*(?:PL|PLATE|BAR|FB|FLAT)(?![A-Z])/i;
64636
+ var hasRollMarker = (profile) => {
64637
+ const raw = (profile ?? "").trim();
64638
+ return !FLAT_STOCK.test(raw) && ROLL_SUFFIX.test(raw);
64639
+ };
64640
+ var rollDegreesFor = (profile) => hasRollMarker(profile) ? 90 : 0;
64641
+ var withoutRollMarker = (profile) => FLAT_STOCK.test(profile) ? profile : profile.replace(ROLL_SUFFIX, "");
64642
+ function normaliseRollMarkers(doc) {
64643
+ const model = doc;
64644
+ if (!model || typeof model !== "object" || !Array.isArray(model.members)) return doc;
64645
+ if (typeof model.type === "string" && !model.type.startsWith("steel.model/")) return doc;
64646
+ if (!model.members.some((m) => typeof m === "object" && m !== null && typeof m.profile === "string" && hasRollMarker(m.profile))) {
64647
+ return doc;
64648
+ }
64649
+ return {
64650
+ ...model,
64651
+ members: model.members.map((raw) => {
64652
+ const m = raw;
64653
+ if (typeof m?.profile !== "string" || !hasRollMarker(m.profile)) return raw;
64654
+ if (m.rot !== void 0 && typeof m.rot !== "number") return raw;
64655
+ const rolled = { ...raw, profile: withoutRollMarker(m.profile).trim() };
64656
+ rolled.rot = 90;
64657
+ return rolled;
64658
+ })
64659
+ };
64660
+ }
64661
+
64632
64662
  // contract-store.ts
64633
64663
  var import_node_fs37 = require("node:fs");
64634
64664
  var import_node_path35 = require("node:path");
@@ -64733,13 +64763,14 @@ function readContract(appId, projectId) {
64733
64763
  const p = contractPath(appId, projectId);
64734
64764
  if (!(0, import_node_fs37.existsSync)(p)) return null;
64735
64765
  try {
64736
- return JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8"));
64766
+ return normaliseRollMarkers(JSON.parse((0, import_node_fs37.readFileSync)(p, "utf8")));
64737
64767
  } catch (e) {
64738
64768
  console.warn(`readContract: ignoring unreadable contract at ${p}: ${e instanceof Error ? e.message : e}`);
64739
64769
  return null;
64740
64770
  }
64741
64771
  }
64742
64772
  function writeContract(appId, doc, projectId, options) {
64773
+ doc = normaliseRollMarkers(doc);
64743
64774
  const p = contractPath(appId, projectId);
64744
64775
  const currentType = options?.currentType !== void 0 ? options.currentType : (() => {
64745
64776
  const cur = readContract(appId, projectId);
@@ -65119,6 +65150,11 @@ function facetKey(dim, value) {
65119
65150
  if (dim === "color") return typeof value === "string" ? value.toLowerCase() : void 0;
65120
65151
  throw new Error(`facetKey: unknown dimension ${JSON.stringify(dim)}`);
65121
65152
  }
65153
+ function isDismissibleFacetValue(dim, key2) {
65154
+ if (dim === "thickness") return typeof key2 === "number" && Number.isFinite(key2);
65155
+ if (dim === "layer" || dim === "color") return typeof key2 === "string" && key2 !== "";
65156
+ throw new Error(`isDismissibleFacetValue: unknown dimension ${JSON.stringify(dim)}`);
65157
+ }
65122
65158
  function selectionMode(mode) {
65123
65159
  return typeof mode === "string" ? mode : "layer";
65124
65160
  }
@@ -65167,17 +65203,26 @@ function normalizeFilter(filter) {
65167
65203
  const active2 = n === 0 || a < 0 || a >= n ? 0 : a;
65168
65204
  return { sheets, active: active2 };
65169
65205
  }
65170
- function dismissibleLayerNames(filter) {
65171
- const rows2 = filter && typeof filter === "object" && Array.isArray(filter.layers) ? filter.layers : [];
65172
- const allOff = /* @__PURE__ */ new Map();
65173
- const order = [];
65174
- for (const row of rows2) {
65175
- if (!row || typeof row !== "object" || Array.isArray(row)) continue;
65176
- if (typeof row.name !== "string" || row.name === "") continue;
65177
- if (!allOff.has(row.name)) order.push(row.name);
65178
- allOff.set(row.name, (allOff.get(row.name) ?? true) && row.on === false);
65206
+ function dismissibleFacetValues(filter) {
65207
+ const source = filter && typeof filter === "object" && !Array.isArray(filter) ? filter : {};
65208
+ const active2 = new Set(selectionDims(source.mode));
65209
+ const out = [];
65210
+ for (const dim of MODE_ORDER) {
65211
+ if (!active2.has(dim)) continue;
65212
+ const d = FACET_DIMS[dim];
65213
+ const rows2 = Array.isArray(source[d.control]) ? source[d.control] : [];
65214
+ const allOff = /* @__PURE__ */ new Map();
65215
+ const order = [];
65216
+ for (const row of rows2) {
65217
+ if (!row || typeof row !== "object" || Array.isArray(row)) continue;
65218
+ const key2 = facetKey(dim, row[d.rowKey]);
65219
+ if (key2 === void 0 || !isDismissibleFacetValue(dim, key2)) continue;
65220
+ if (!allOff.has(key2)) order.push(key2);
65221
+ allOff.set(key2, (allOff.get(key2) ?? true) && row.on === false);
65222
+ }
65223
+ for (const value of order) if (allOff.get(value) === true) out.push({ dim, value });
65179
65224
  }
65180
- return order.filter((name) => allOff.get(name) === true);
65225
+ return out;
65181
65226
  }
65182
65227
 
65183
65228
  // steel-filter-contract.ts
@@ -66169,7 +66214,7 @@ function expandBraceGusset(joint, brace, support, nativeSupport) {
66169
66214
  else if (support) weldRecords(viewOperations, support.id);
66170
66215
  return { parts, operations, viewOperations, trims: [{ id: brace.id, end: at, mm: trimMm }], diagnostics };
66171
66216
  }
66172
- function expandCustom(joint) {
66217
+ function expandCustom(joint, review) {
66173
66218
  const place = finite3(joint.place) ? joint.place : [0, 0, 0];
66174
66219
  const [dx, dy, dz] = place;
66175
66220
  const out = [];
@@ -66184,7 +66229,15 @@ function expandCustom(joint) {
66184
66229
  }
66185
66230
  const role = typeof g.role === "string" ? g.role : void 0;
66186
66231
  const label2 = role ? role.charAt(0).toUpperCase() + role.slice(1) : "Imported part";
66187
- out.push({ id: `${joint.id}:${g.id || `m${i}`}`, group: "custom", kind: "mesh", positions, indices: g.indices.slice(), meta: { label: label2, role } });
66232
+ const lift = review && review.get(joint.id);
66233
+ out.push({
66234
+ id: `${joint.id}:${g.id || `m${i}`}`,
66235
+ group: "custom",
66236
+ kind: "mesh",
66237
+ positions,
66238
+ indices: g.indices.slice(),
66239
+ meta: { label: label2, role, ...lift ? { connReview: lift } : {} }
66240
+ });
66188
66241
  });
66189
66242
  return out;
66190
66243
  }
@@ -66321,7 +66374,7 @@ function measureJointFit(joint, main2, expansion, support) {
66321
66374
  }
66322
66375
  return { jointId: joint.id, kind: joint.kind, facts, unresolved };
66323
66376
  }
66324
- function expandJoints(joints, memberGeo) {
66377
+ function expandJoints(joints, memberGeo, review) {
66325
66378
  const elements = [];
66326
66379
  const operations = [];
66327
66380
  const viewOperations = [];
@@ -66336,7 +66389,7 @@ function expandJoints(joints, memberGeo) {
66336
66389
  return;
66337
66390
  }
66338
66391
  if (j.kind === "custom") {
66339
- const parts = expandCustom(j);
66392
+ const parts = expandCustom(j, review);
66340
66393
  if (!parts.length) {
66341
66394
  skipped.push(j.id);
66342
66395
  return;
@@ -66584,6 +66637,7 @@ function readModel(doc) {
66584
66637
  return readModelOrIssues(doc).view ?? null;
66585
66638
  }
66586
66639
  function readModelOrIssues(doc) {
66640
+ doc = normaliseRollMarkers(doc);
66587
66641
  if (!isModelV2(doc)) return { view: null, issues: ["not-model-v2"] };
66588
66642
  const schema = validateSteelModelV2(doc);
66589
66643
  if (!schema.valid) {
@@ -67806,12 +67860,13 @@ var FT_TO_MM = 304.8;
67806
67860
  var IN_TO_MM2 = 25.4;
67807
67861
  var memberIsBrace = (m) => typeof m.memberType === "string" && m.memberType.trim().toLowerCase() === "brace";
67808
67862
  function foldedWeight(weights, profile) {
67809
- const target = canonProfile(profile);
67810
- const hit = Object.entries(weights).find(([k]) => canonProfile(k) === target);
67811
- return hit ? hit[1] ?? null : aiscWeightPlf(profile);
67863
+ const target = canonProfile(withoutRollMarker(profile));
67864
+ const hit = Object.entries(weights).find(([k]) => canonProfile(withoutRollMarker(k)) === target);
67865
+ return hit ? hit[1] ?? null : aiscWeightPlf(withoutRollMarker(profile));
67812
67866
  }
67813
67867
  function profileDimsIn(profile) {
67814
67868
  if (!profile) return null;
67869
+ profile = withoutRollMarker(profile);
67815
67870
  const p = profile.trim().toUpperCase().replace(/[×✕✖]/g, "X").replace(/ /g, " ");
67816
67871
  if (p === "" || /(^|[^A-Z])MF($|[^A-Z])/.test(p)) return null;
67817
67872
  const display = displaySectionFor(profile);
@@ -67967,11 +68022,11 @@ function applyMemberTrims(elements, trims) {
67967
68022
  }
67968
68023
  return unapplied;
67969
68024
  }
67970
- function contractToScene(contractInput) {
68025
+ function contractToScene(contractInput, review) {
67971
68026
  if (isModelV2(contractInput)) {
67972
68027
  const { view, issues } = readModelOrIssues(contractInput);
67973
68028
  if (!view) throw new InvalidModelV2Error(`contract declares steel.model/v2 but is not valid v2: ${issues[0] ?? "unknown"}`, issues);
67974
- return sceneFromModel(view);
68029
+ return sceneFromModel(view, review);
67975
68030
  }
67976
68031
  throw new InvalidModelV2Error("scene export requires a valid steel.model/v2 contract", ["$.type: expected steel.model/v2"]);
67977
68032
  }
@@ -68195,7 +68250,7 @@ function placeMember(m) {
68195
68250
  const mIsBrace = memberIsBrace(m);
68196
68251
  const braceType = m.brace?.type;
68197
68252
  const profile = canonProfile(m.profile) || (explicit ? "CUSTOM" : "");
68198
- const xs = xsectionFor(profile, { w: dims.w, d: dims.d });
68253
+ const xs = xsectionFor(withoutRollMarker(profile), { w: dims.w, d: dims.d });
68199
68254
  const ax = m.from.x, ay = m.from.y, bx = m.to.x, by = m.to.y;
68200
68255
  const refFrom = [ax, ay, z0];
68201
68256
  const refTo = [bx, by, z1];
@@ -68211,7 +68266,9 @@ function placeMember(m) {
68211
68266
  mIsBrace && braceType === "vertical"
68212
68267
  );
68213
68268
  const widthFace = effectiveWidthPosition(m.positionH);
68214
- const rawRot = typeof m.rot === "number" ? m.rot : 0;
68269
+ const roll = rollDegreesFor(m.profile);
68270
+ const authoredRot = roll ? roll : typeof m.rot === "number" ? m.rot : void 0;
68271
+ const rawRot = authoredRot ?? 0;
68215
68272
  const th = rawRot * Math.PI / 180;
68216
68273
  const c = Math.cos(th), s = Math.sin(th);
68217
68274
  const widthAxis = frame ? [
@@ -68227,12 +68284,12 @@ function placeMember(m) {
68227
68284
  const effectiveRot = storedBasis && widthAxis && globalFrame ? Math.atan2(
68228
68285
  widthAxis[0] * globalFrame.z[0] + widthAxis[1] * globalFrame.z[1] + widthAxis[2] * globalFrame.z[2],
68229
68286
  widthAxis[0] * globalFrame.y[0] + widthAxis[1] * globalFrame.y[1] + widthAxis[2] * globalFrame.y[2]
68230
- ) * 180 / Math.PI : m.rot;
68287
+ ) * 180 / Math.PI : authoredRot;
68231
68288
  const ex = sectionExtents(outlineFor(profile, dims.w, dims.d, xs, dims.round === true));
68232
- const o = frame ? positionOffsetVector(frame, ex, depthFace, widthFace, m.rot, m.positionHOffset, m.positionOffset) : [0, 0, 0];
68289
+ const o = frame ? positionOffsetVector(frame, ex, depthFace, widthFace, authoredRot, m.positionHOffset, m.positionOffset) : [0, 0, 0];
68233
68290
  const from = [refFrom[0] + o[0], refFrom[1] + o[1], refFrom[2] + o[2]];
68234
68291
  const to = [refTo[0] + o[0], refTo[1] + o[1], refTo[2] + o[2]];
68235
- const named = frame ? positionOffsetVector(frame, ex, depthFace, widthFace, m.rot) : [0, 0, 0];
68292
+ const named = frame ? positionOffsetVector(frame, ex, depthFace, widthFace, authoredRot) : [0, 0, 0];
68236
68293
  const latMag = Math.hypot(named[0], named[1]);
68237
68294
  const numeric = [o[0] - named[0], o[1] - named[1], o[2] - named[2]];
68238
68295
  const hasNumeric = numeric.some((v) => v !== 0);
@@ -68281,7 +68338,7 @@ function memberGeoEntry(p) {
68281
68338
  ...typeof p.rot === "number" ? { rot: p.rot } : {}
68282
68339
  };
68283
68340
  }
68284
- function sceneFromModel(view) {
68341
+ function sceneFromModel(view, review) {
68285
68342
  const blocked = membersBlockingExport(view.doc);
68286
68343
  if (blocked.length) {
68287
68344
  throw new SceneContractError(
@@ -68343,7 +68400,7 @@ function sceneFromModel(view) {
68343
68400
  label: profile,
68344
68401
  color: pickColor(profile, paletteRank.indexOf(profile), view.doc)
68345
68402
  }));
68346
- const joints = expandJoints(view.doc.joints, memberGeo);
68403
+ const joints = expandJoints(view.doc.joints, memberGeo, review);
68347
68404
  const coverage = partCoverage(view.doc.joints, { elements: joints.elements, skippedJointIds: joints.skipped });
68348
68405
  if (!coverageOk(coverage)) console.warn(`[steel] ${describeCoverage(coverage)}`);
68349
68406
  applyBeamClearance(elements, beamClears, refusedJointIds(view.doc.joints, joints.skipped));
@@ -68504,6 +68561,38 @@ var import_node_fs39 = require("node:fs");
68504
68561
  var import_node_os25 = require("node:os");
68505
68562
  var import_node_path37 = require("node:path");
68506
68563
 
68564
+ // steel-exclusion-eligibility.ts
68565
+ function facetFailures(input) {
68566
+ const { facets, activeDims, onSets, dismissible } = input;
68567
+ const out = [];
68568
+ for (const dim of activeDims) {
68569
+ const descriptor = FACET_DIMS[dim];
68570
+ const key2 = facetKey(dim, facets[descriptor.elementKey]);
68571
+ if (key2 !== void 0 && onSets[dim].has(key2)) continue;
68572
+ if (key2 === void 0) {
68573
+ out.push({ dim, kind: "malformed" });
68574
+ continue;
68575
+ }
68576
+ out.push(dismissible.get(dim)?.has(key2) ? { dim, kind: "excluded", value: key2 } : { dim, kind: "not-approved", value: key2 });
68577
+ }
68578
+ return out;
68579
+ }
68580
+ var everyFailureExcluded = (failures) => failures.every((failure) => failure.kind === "excluded");
68581
+ function dismissibleByDimension(rows2) {
68582
+ const out = /* @__PURE__ */ new Map();
68583
+ for (const row of rows2) {
68584
+ let set2 = out.get(row.dim);
68585
+ if (!set2) {
68586
+ set2 = /* @__PURE__ */ new Set();
68587
+ out.set(row.dim, set2);
68588
+ }
68589
+ set2.add(row.value);
68590
+ }
68591
+ return out;
68592
+ }
68593
+ var FACET_KEY_SEP = String.fromCharCode(0);
68594
+ var facetMapKey = (dim, value) => `${dim}${FACET_KEY_SEP}${String(value)}`;
68595
+
68507
68596
  // steel-source-inventory.ts
68508
68597
  var STEEL_SOURCE_CANDIDATE_KINDS = /* @__PURE__ */ new Set([
68509
68598
  "potential-member-line",
@@ -68792,6 +68881,22 @@ function sourceLineInventory(input) {
68792
68881
  }
68793
68882
  return { lines, unboundSheets, unownedCandidates, index };
68794
68883
  }
68884
+ var SteelFacetCensusUnreconciledError = class extends Error {
68885
+ constructor(dim, role, censused, uncensused, population) {
68886
+ super(`the ${dim} facet census does not reconcile for ${role}: ${censused} censused + ${uncensused} uncensused != ${population} lines`);
68887
+ this.dim = dim;
68888
+ this.role = role;
68889
+ this.censused = censused;
68890
+ this.uncensused = uncensused;
68891
+ this.population = population;
68892
+ this.name = "SteelFacetCensusUnreconciledError";
68893
+ }
68894
+ dim;
68895
+ role;
68896
+ censused;
68897
+ uncensused;
68898
+ population;
68899
+ };
68795
68900
  var SteelLedgerUnboundError = class extends Error {
68796
68901
  constructor(samples) {
68797
68902
  super("the source ledger holds lines this manifest cannot account for, so layer line counts cannot be derived");
@@ -68815,19 +68920,72 @@ function steelReadLayerLineCounts(ledger) {
68815
68920
  }
68816
68921
  return [...byLayer.values()];
68817
68922
  }
68923
+ var FACET_CENSUS_DIMS = ["thickness", "color"];
68924
+ function steelReadFacetLineCounts(ledger) {
68925
+ const unaccounted = [...ledger.unboundSheets, ...ledger.unownedCandidates];
68926
+ if (unaccounted.length) throw new SteelLedgerUnboundError(unaccounted);
68927
+ const byValue = /* @__PURE__ */ new Map();
68928
+ const uncensused = FACET_CENSUS_DIMS.map((dim) => ({ dim, model: 0, evidence: 0 }));
68929
+ const population = { model: 0, evidence: 0 };
68930
+ for (const row of ledger.lines) {
68931
+ if (row.sourceRole !== "model" && row.sourceRole !== "evidence") continue;
68932
+ population[row.sourceRole] += 1;
68933
+ for (const [index, dim] of FACET_CENSUS_DIMS.entries()) {
68934
+ const descriptor = FACET_DIMS[dim];
68935
+ const key2 = canonicalKey(dim, row.facets[descriptor.elementKey]);
68936
+ if (key2 === void 0 || !isDismissibleFacetValue(dim, key2)) {
68937
+ uncensused[index][row.sourceRole] += 1;
68938
+ continue;
68939
+ }
68940
+ const mapKey = facetMapKey(dim, key2);
68941
+ let entry2 = byValue.get(mapKey);
68942
+ if (!entry2) {
68943
+ entry2 = { dim, value: key2, model: 0, evidence: 0 };
68944
+ byValue.set(mapKey, entry2);
68945
+ }
68946
+ entry2[row.sourceRole] += 1;
68947
+ }
68948
+ }
68949
+ const rows2 = [...byValue.values()];
68950
+ for (const [index, dim] of FACET_CENSUS_DIMS.entries()) {
68951
+ for (const role of ["model", "evidence"]) {
68952
+ const censused = rows2.reduce((sum, entry2) => entry2.dim === dim ? sum + entry2[role] : sum, 0);
68953
+ if (censused + uncensused[index][role] !== population[role]) {
68954
+ throw new SteelFacetCensusUnreconciledError(dim, role, censused, uncensused[index][role], population[role]);
68955
+ }
68956
+ }
68957
+ }
68958
+ return { rows: rows2, uncensused, population };
68959
+ }
68818
68960
 
68819
68961
  // steel-read-manifest.ts
68820
- var STEEL_FILTER_EXTRACTOR_VERSION = "pymupdf-steel-filter/v2";
68962
+ var STEEL_FILTER_EXTRACTOR_VERSION = "pymupdf-steel-filter/v3";
68821
68963
  var STEEL_READ_MAX_SOURCES = 400;
68822
68964
  var STEEL_READ_MAX_PAGES = 2e3;
68823
68965
  var STEEL_READ_MAX_PAGE_ELEMENTS = 4e4;
68824
68966
  var STEEL_READ_MAX_TOTAL_ELEMENTS = 2e5;
68825
- var STEEL_LAYER_SIGNOFF_DOMAIN = "floless:steel-layer-signoff:v1";
68826
- function steelLayerSignOffDigest(filter) {
68827
- return steelLayerSignOffDigestOfNames(dismissibleLayerNames(filter));
68828
- }
68829
- function steelLayerSignOffDigestOfNames(layers) {
68830
- return hashOf({ domain: STEEL_LAYER_SIGNOFF_DOMAIN, layers });
68967
+ var STEEL_EXCLUSION_SIGNOFF_DOMAIN = "floless:steel-exclusion-signoff:v2";
68968
+ function steelExclusionSignOffDigest(filter) {
68969
+ const source = filter && typeof filter === "object" && !Array.isArray(filter) ? filter : {};
68970
+ return steelExclusionSignOffDigestOfValues(source.mode, dismissibleFacetValues(filter));
68971
+ }
68972
+ function steelExclusionSignOffDigestOfValues(mode, exclusions) {
68973
+ return hashOf({ domain: STEEL_EXCLUSION_SIGNOFF_DOMAIN, mode, exclusions });
68974
+ }
68975
+ var STEEL_FILTER_CONTROLS_DOMAIN = "floless:steel-filter-controls:v1";
68976
+ function steelFilterControlsHash(filterLike) {
68977
+ const source = filterLike && typeof filterLike === "object" && !Array.isArray(filterLike) ? filterLike : {};
68978
+ const controls = {};
68979
+ for (const dim of MODE_ORDER) {
68980
+ const descriptor = FACET_DIMS[dim];
68981
+ const rows2 = Array.isArray(source[descriptor.control]) ? source[descriptor.control] : [];
68982
+ controls[descriptor.control] = rows2.map((row) => {
68983
+ const raw = row && typeof row === "object" && !Array.isArray(row) ? row : {};
68984
+ const key2 = facetKey(dim, raw[descriptor.rowKey]);
68985
+ return { [descriptor.rowKey]: key2 === void 0 ? { unkeyable: raw[descriptor.rowKey] } : key2, on: raw.on };
68986
+ });
68987
+ }
68988
+ return hashOf({ domain: STEEL_FILTER_CONTROLS_DOMAIN, mode: source.mode, ...controls });
68831
68989
  }
68832
68990
  function steelFilterGeometryHash(filter) {
68833
68991
  const clone2 = filter == null ? filter : JSON.parse(JSON.stringify(filter));
@@ -68866,6 +69024,7 @@ function validCompactCandidate(candidate, isModelPage2) {
68866
69024
  }
68867
69025
  function validManifest(manifest) {
68868
69026
  if (manifest.version !== 1 || manifest.extractorVersion !== STEEL_FILTER_EXTRACTOR_VERSION) return false;
69027
+ if (!manifest.filter || typeof manifest.filter !== "object" || Array.isArray(manifest.filter) || manifest.filter.extractorVersion !== manifest.extractorVersion) return false;
68869
69028
  if (manifest.candidatesRepr !== void 0 && manifest.candidatesRepr !== "v2-compact") return false;
68870
69029
  if (manifest.censusScope !== void 0 && manifest.censusScope !== "whole-set") return false;
68871
69030
  if (!isPersistedRequestId(manifest.requestId) || typeof manifest.projectId !== "string" || typeof manifest.appId !== "string") return false;
@@ -68928,6 +69087,16 @@ function isRecord(value) {
68928
69087
  if (!Number.isInteger(signOff.layerCount) || signOff.layerCount < 0) return false;
68929
69088
  if (typeof signOff.at !== "string") return false;
68930
69089
  }
69090
+ if (row.exclusionSignOff !== void 0) {
69091
+ const signOff = row.exclusionSignOff;
69092
+ if (!signOff || typeof signOff !== "object" || Array.isArray(signOff)) return false;
69093
+ if (signOff.version !== 2 || signOff.basis !== "facets/v2") return false;
69094
+ if (typeof signOff.digest !== "string" || !SHA256.test(signOff.digest)) return false;
69095
+ if (typeof signOff.manifestHash !== "string" || !SHA256.test(signOff.manifestHash)) return false;
69096
+ if (typeof signOff.controlsHash !== "string" || !SHA256.test(signOff.controlsHash)) return false;
69097
+ if (!Number.isInteger(signOff.valueCount) || signOff.valueCount < 0) return false;
69098
+ if (typeof signOff.at !== "string") return false;
69099
+ }
68931
69100
  return hashOf(manifest) === row.manifestHash;
68932
69101
  }
68933
69102
  function atomicWrite(path, bytes2) {
@@ -68967,7 +69136,9 @@ var SteelReadPageBudgetError = class extends Error {
68967
69136
  limit = STEEL_READ_MAX_PAGE_ELEMENTS;
68968
69137
  };
68969
69138
  function writeSteelReadManifest(manifest, now = (/* @__PURE__ */ new Date()).toISOString()) {
68970
- if (!validManifest(manifest)) throw new SteelReadManifestInvalidError("steel read manifest exceeds its limits or has invalid server-owned identities");
69139
+ if (!validManifest(manifest)) {
69140
+ throw new SteelReadManifestInvalidError("steel read manifest exceeds its limits or has invalid server-owned identities");
69141
+ }
68971
69142
  assertAdmissiblePageElementCounts(manifest);
68972
69143
  const stored2 = { manifest, manifestHash: hashOf(manifest), createdAt: now };
68973
69144
  atomicWrite(recordPath(manifest.requestId), `${canonicalJson(stored2)}
@@ -68984,9 +69155,24 @@ function readSteelReadManifest(requestId) {
68984
69155
  return null;
68985
69156
  }
68986
69157
  }
68987
- function recordSteelFilterSave(requestId, filter, etag, now = (/* @__PURE__ */ new Date()).toISOString(), layerSignOff) {
69158
+ var SteelManifestMovedError = class extends Error {
69159
+ constructor(expected, actual) {
69160
+ super("the steel manifest was replaced while this Filter Save was in flight");
69161
+ this.expected = expected;
69162
+ this.actual = actual;
69163
+ this.name = "SteelManifestMovedError";
69164
+ }
69165
+ expected;
69166
+ actual;
69167
+ };
69168
+ function recordSteelFilterSave(input) {
69169
+ const { requestId, filter, etag, expectedManifestHash, exclusionSignOff } = input;
69170
+ const now = input.now ?? (/* @__PURE__ */ new Date()).toISOString();
68988
69171
  const current = readSteelReadManifest(requestId);
68989
69172
  if (!current) throw new SteelFilterCheckpointRejectedError("steel read manifest is missing or corrupt");
69173
+ if (current.manifestHash !== expectedManifestHash) {
69174
+ throw new SteelManifestMovedError(expectedManifestHash, current.manifestHash);
69175
+ }
68990
69176
  if (steelFilterGeometryHash(filter) !== steelFilterGeometryHash(current.manifest.filter)) {
68991
69177
  throw new SteelFilterCheckpointRejectedError("saved Steel Filter geometry does not match the server manifest");
68992
69178
  }
@@ -68997,7 +69183,8 @@ function recordSteelFilterSave(requestId, filter, etag, now = (/* @__PURE__ */ n
68997
69183
  filterSavedAt: now
68998
69184
  };
68999
69185
  delete next.layerSignOff;
69000
- if (layerSignOff) next.layerSignOff = layerSignOff;
69186
+ delete next.exclusionSignOff;
69187
+ if (exclusionSignOff) next.exclusionSignOff = exclusionSignOff;
69001
69188
  atomicWrite(recordPath(requestId), `${canonicalJson(next)}
69002
69189
  `);
69003
69190
  return next;
@@ -69108,6 +69295,21 @@ function hasTotalBooleanOn(filter) {
69108
69295
  return rows2.every((row) => isObj5(row) && typeof row.on === "boolean");
69109
69296
  });
69110
69297
  }
69298
+ function hasCanonicalMode(filter) {
69299
+ if (!isObj5(filter)) return false;
69300
+ const mode = filter.mode;
69301
+ return typeof mode === "string" && mode !== "" && mode === canonicalMode(modeDims(mode));
69302
+ }
69303
+ function hasWellFormedControlValues(filter) {
69304
+ if (!isObj5(filter)) return false;
69305
+ return FACETS.every(({ facet, key: key2 }) => {
69306
+ const rows2 = filter[facet];
69307
+ if (rows2 === void 0) return true;
69308
+ if (!Array.isArray(rows2)) return false;
69309
+ const dim = DIM_OF_ROW_KEY[key2];
69310
+ return rows2.every((row) => isObj5(row) && facetKey(dim, row[key2]) !== void 0);
69311
+ });
69312
+ }
69111
69313
 
69112
69314
  // steel-read-audit.ts
69113
69315
  var STEEL_READ_AUDIT_POLICY = "steel-read-completion/v1";
@@ -69115,6 +69317,9 @@ var MAX_ATTESTATION_BYTES = 8 * 1024 * 1024;
69115
69317
  var MAX_LINES = STEEL_READ_MAX_TOTAL_ELEMENTS;
69116
69318
  var MAX_PAGES = 2e3;
69117
69319
  var MAX_LAYERS = 2e4;
69320
+ var MAX_FACET_EXCLUSIONS = 5e3;
69321
+ var MAX_FACET_VALUE_CHARS = 200;
69322
+ var MAX_DISPOSITION_GROUPS = 5e3;
69118
69323
  var MAX_JOINTS = 1e4;
69119
69324
  var MAX_MEMBERS = 1e4;
69120
69325
  var MAX_TEXT = 1e3;
@@ -69129,8 +69334,18 @@ var SteelReadAttestationError = class extends Error {
69129
69334
  this.name = "SteelReadAttestationError";
69130
69335
  }
69131
69336
  };
69132
- var ATTESTATION_V1_RETIRED_ERROR = "this read carries a retired steel-read/v1 attestation; steel-read/v1 is no longer accepted \u2014 re-run the read so the reader emits a steel-read/v2 proof (one whole-page review carrying candidateShardHash per manifest page, and a layer census instead of per-element enumeration)";
69133
- var ATTESTATION_SHAPE_ERROR = "attestation must be the closed steel-read/v2 shape";
69337
+ var SteelReadAttestationRetiredError = class extends SteelReadAttestationError {
69338
+ constructor(retiredVersion, message) {
69339
+ super(message);
69340
+ this.retiredVersion = retiredVersion;
69341
+ this.name = "SteelReadAttestationRetiredError";
69342
+ }
69343
+ retiredVersion;
69344
+ };
69345
+ var ATTESTATION_V1_RETIRED_ERROR = "this read carries a retired steel-read/v1 attestation; steel-read/v1 is no longer accepted \u2014 re-run the read so the reader emits a steel-read/v4 proof (one whole-page review carrying candidateShardHash per manifest page, a layer census instead of per-element enumeration, facetExclusions[] for the human-excluded line weights and colours, and lineDispositionGroups[] where one reason covers many named ids)";
69346
+ var ATTESTATION_V2_RETIRED_ERROR = "this read carries a retired steel-read/v2 attestation; steel-read/v2 is no longer accepted \u2014 re-run the read so the reader emits a steel-read/v4 proof (which adds facetExclusions[]: one row per human-excluded line weight or colour, each with a server-verified role-split lineCounts; and lineDispositionGroups[], where one reason covers many named ids)";
69347
+ var ATTESTATION_V3_RETIRED_ERROR = "this read carries a retired steel-read/v3 attestation; steel-read/v3 is no longer accepted \u2014 re-run the read so the reader emits a steel-read/v4 proof (which adds lineDispositionGroups[]: one disposition and reason covering many individually-named elementIds, so a large honest dismissal no longer repeats the same sentence once per line)";
69348
+ var ATTESTATION_SHAPE_ERROR = "attestation must be the closed steel-read/v4 shape";
69134
69349
  function parseSteelReadAttestation(input) {
69135
69350
  let json2;
69136
69351
  try {
@@ -69139,9 +69354,11 @@ function parseSteelReadAttestation(input) {
69139
69354
  throw new SteelReadAttestationError("attestation must be acyclic JSON");
69140
69355
  }
69141
69356
  if (typeof json2 !== "string" || !isObj6(input)) throw new SteelReadAttestationError(ATTESTATION_SHAPE_ERROR);
69142
- if (input.version === 1) throw new SteelReadAttestationError(ATTESTATION_V1_RETIRED_ERROR);
69357
+ if (input.version === 1) throw new SteelReadAttestationRetiredError(1, ATTESTATION_V1_RETIRED_ERROR);
69358
+ if (input.version === 2) throw new SteelReadAttestationRetiredError(2, ATTESTATION_V2_RETIRED_ERROR);
69359
+ if (input.version === 3) throw new SteelReadAttestationRetiredError(3, ATTESTATION_V3_RETIRED_ERROR);
69143
69360
  if (Buffer.byteLength(json2) > MAX_ATTESTATION_BYTES) throw new SteelReadAttestationError("attestation exceeds the 8 MB limit");
69144
- if (input.version !== 2 || !exactKeys(input, ["version", "massing", "layers", "lineDispositions", "pageReviews", "references", "candidateDispositions", "jointReviews"])) {
69361
+ if (input.version !== 4 || !exactKeys(input, ["version", "massing", "layers", "facetExclusions", "lineDispositions", "lineDispositionGroups", "pageReviews", "references", "candidateDispositions", "jointReviews"])) {
69145
69362
  throw new SteelReadAttestationError(ATTESTATION_SHAPE_ERROR);
69146
69363
  }
69147
69364
  if (!isObj6(input.massing) || !exactKeys(input.massing, ["buildingCount", "summary"]) || !Number.isInteger(input.massing.buildingCount) || input.massing.buildingCount < 1 || !text3(input.massing.summary)) {
@@ -69166,6 +69383,32 @@ function parseSteelReadAttestation(input) {
69166
69383
  lineCounts: { model: counts2.model, evidence: counts2.evidence }
69167
69384
  };
69168
69385
  });
69386
+ if (!Array.isArray(input.facetExclusions) || input.facetExclusions.length > MAX_FACET_EXCLUSIONS) throw new SteelReadAttestationError("facetExclusions must be a bounded array");
69387
+ const facetSeen = /* @__PURE__ */ new Set();
69388
+ const facetKinds = /* @__PURE__ */ new Set(["member", "annotation", "existing", "mixed", "other"]);
69389
+ const facetExclusions = input.facetExclusions.map((raw, index) => {
69390
+ if (!isObj6(raw) || !exactKeys(raw, ["dim", "value", "disposition", "note", "lineCounts"])) throw new SteelReadAttestationError(`facetExclusions[${index}] has unknown or missing keys`);
69391
+ const dim = raw.dim === "thickness" ? "thickness" : raw.dim === "color" ? "color" : void 0;
69392
+ if (dim === void 0) throw new SteelReadAttestationError(`facetExclusions[${index}] must name the thickness or color dimension`);
69393
+ const key2 = facetKey(dim, dim === "thickness" ? raw.value : typeof raw.value === "string" && raw.value.length <= MAX_FACET_VALUE_CHARS ? raw.value : void 0);
69394
+ if (key2 === void 0 || (typeof key2 === "number" ? !Number.isFinite(key2) : key2 === "")) throw new SteelReadAttestationError(`facetExclusions[${index}] has no well-formed value for its dimension`);
69395
+ const note = text3(raw.note);
69396
+ if (typeof raw.disposition !== "string" || !facetKinds.has(raw.disposition) || !note) throw new SteelReadAttestationError(`facetExclusions[${index}] is malformed`);
69397
+ const seenKey = facetMapKey(dim, key2);
69398
+ if (facetSeen.has(seenKey)) throw new SteelReadAttestationError(`facetExclusions[${index}] duplicates an earlier (dim, value)`);
69399
+ facetSeen.add(seenKey);
69400
+ const counts2 = raw.lineCounts;
69401
+ if (!isObj6(counts2) || !exactKeys(counts2, ["model", "evidence"]) || !Number.isInteger(counts2.model) || counts2.model < 0 || !Number.isInteger(counts2.evidence) || counts2.evidence < 0) {
69402
+ throw new SteelReadAttestationError(`facetExclusions[${index}] must state non-negative integer model/evidence lineCounts`);
69403
+ }
69404
+ return {
69405
+ dim,
69406
+ value: key2,
69407
+ disposition: raw.disposition,
69408
+ note,
69409
+ lineCounts: { model: counts2.model, evidence: counts2.evidence }
69410
+ };
69411
+ });
69169
69412
  if (!Array.isArray(input.lineDispositions) || input.lineDispositions.length > MAX_LINES) throw new SteelReadAttestationError("lineDispositions must be a bounded array");
69170
69413
  const lineIds = /* @__PURE__ */ new Set();
69171
69414
  const dispositions = /* @__PURE__ */ new Set(["annotation", "existing", "duplicate", "not-steel", "unresolved"]);
@@ -69178,6 +69421,26 @@ function parseSteelReadAttestation(input) {
69178
69421
  lineIds.add(elementId);
69179
69422
  return { elementId, disposition: raw.disposition, reason, ...duplicateOf ? { duplicateOf } : {} };
69180
69423
  });
69424
+ if (!Array.isArray(input.lineDispositionGroups) || input.lineDispositionGroups.length > MAX_DISPOSITION_GROUPS) throw new SteelReadAttestationError("lineDispositionGroups must be a bounded array");
69425
+ const lineDispositionGroups = input.lineDispositionGroups.map((raw, index) => {
69426
+ if (!isObj6(raw) || !exactKeys(raw, ["disposition", "reason", "duplicateOf", "elementIds"])) throw new SteelReadAttestationError(`lineDispositionGroups[${index}] has unknown or missing keys`);
69427
+ const reason = text3(raw.reason);
69428
+ if (typeof raw.disposition !== "string" || !dispositions.has(raw.disposition) || !reason) throw new SteelReadAttestationError(`lineDispositionGroups[${index}] is malformed`);
69429
+ const duplicateOf = raw.duplicateOf === void 0 ? void 0 : text3(raw.duplicateOf, 200);
69430
+ if (raw.disposition === "duplicate" ? !duplicateOf : duplicateOf !== void 0) throw new SteelReadAttestationError(`lineDispositionGroups[${index}] has an invalid duplicate target`);
69431
+ if (!Array.isArray(raw.elementIds) || raw.elementIds.length === 0) throw new SteelReadAttestationError(`lineDispositionGroups[${index}] must name at least one elementId`);
69432
+ if (duplicateOf && raw.elementIds.some((id) => typeof id === "string" && id.trim() === duplicateOf)) {
69433
+ throw new SteelReadAttestationError(`lineDispositionGroups[${index}] names its own duplicateOf target`);
69434
+ }
69435
+ const elementIds = raw.elementIds.map((rawId, idIndex2) => {
69436
+ const elementId = text3(rawId, 200);
69437
+ if (!elementId || lineIds.has(elementId)) throw new SteelReadAttestationError(`lineDispositionGroups[${index}].elementIds[${idIndex2}] is malformed or duplicated`);
69438
+ lineIds.add(elementId);
69439
+ if (lineIds.size > MAX_LINES) throw new SteelReadAttestationError("lineDispositions and lineDispositionGroups name more lines than the element cap admits");
69440
+ return elementId;
69441
+ });
69442
+ return { disposition: raw.disposition, reason, ...duplicateOf ? { duplicateOf } : {}, elementIds };
69443
+ });
69181
69444
  if (!Array.isArray(input.pageReviews) || input.pageReviews.length > MAX_PAGES) throw new SteelReadAttestationError("pageReviews must be bounded");
69182
69445
  const reviewedPageIds = /* @__PURE__ */ new Set();
69183
69446
  const pageReviews = input.pageReviews.map((raw, index) => {
@@ -69222,7 +69485,7 @@ function parseSteelReadAttestation(input) {
69222
69485
  jointIds.add(jointId);
69223
69486
  return { jointId, dependencyHash: raw.dependencyHash, note };
69224
69487
  });
69225
- return { version: 2, massing: { buildingCount: input.massing.buildingCount, summary: text3(input.massing.summary) }, layers, lineDispositions, pageReviews, references, candidateDispositions, jointReviews };
69488
+ return { version: 4, massing: { buildingCount: input.massing.buildingCount, summary: text3(input.massing.summary) }, layers, facetExclusions, lineDispositions, lineDispositionGroups, pageReviews, references, candidateDispositions, jointReviews };
69226
69489
  }
69227
69490
  function referenceInventory(filter, manifest, inventory) {
69228
69491
  if (!isObj6(filter)) return [];
@@ -69332,18 +69595,39 @@ function jointDependencyHash(candidate, jointId) {
69332
69595
  const connection = typeof joint.conn === "string" && Array.isArray(candidate.connections) ? candidate.connections.filter(isObj6).find((row) => row.id === joint.conn) ?? null : null;
69333
69596
  return hashOf({ policy: "steel-joint-dependency/v1", joint, members, connection, expansion: "steel-joints/v2-measured-fit" });
69334
69597
  }
69335
- function steelLayerSignOffValid(input) {
69336
- const { storedManifest, filter, lineLayers } = input;
69337
- const signOff = storedManifest.layerSignOff;
69338
- if (!signOff) return false;
69339
- if (storedManifest.manifest.censusScope !== "whole-set") return false;
69340
- if (signOff.digest !== steelLayerSignOffDigest(filter)) return false;
69341
- if (!hasTotalBooleanOn(filter)) return false;
69342
- const controlNames = /* @__PURE__ */ new Set();
69343
- const rows2 = isObj6(filter) && Array.isArray(filter.layers) ? filter.layers : [];
69344
- for (const row of rows2) if (isObj6(row) && typeof row.name === "string") controlNames.add(row.name);
69345
- for (const layer of lineLayers) if (layer && !controlNames.has(layer)) return false;
69346
- return true;
69598
+ function steelExclusionSignOffValid(input) {
69599
+ const { storedManifest, filter, lineFacets } = input;
69600
+ const signOff = storedManifest.exclusionSignOff;
69601
+ if (!signOff || signOff.version !== 2 || signOff.basis !== "facets/v2") return { ok: false, why: "absent" };
69602
+ if (storedManifest.manifest.censusScope !== "whole-set") return { ok: false, why: "scope" };
69603
+ if (signOff.digest !== steelExclusionSignOffDigest(filter)) return { ok: false, why: "digest" };
69604
+ if (!hasTotalBooleanOn(filter)) return { ok: false, why: "controls-not-total" };
69605
+ if (!hasCanonicalMode(filter)) return { ok: false, why: "mode-noncanonical" };
69606
+ if (signOff.manifestHash !== storedManifest.manifestHash) return { ok: false, why: "manifest-moved" };
69607
+ if (signOff.controlsHash !== steelFilterControlsHash(filter)) return { ok: false, why: "controls-moved" };
69608
+ const source = isObj6(filter) ? filter : {};
69609
+ const active2 = selectionDims(source.mode);
69610
+ const censusByDim = /* @__PURE__ */ new Map();
69611
+ for (const dim of active2) {
69612
+ const descriptor = FACET_DIMS[dim];
69613
+ const rows2 = Array.isArray(source[descriptor.control]) ? source[descriptor.control] : [];
69614
+ const keys = /* @__PURE__ */ new Set();
69615
+ for (const row of rows2) {
69616
+ if (!isObj6(row)) continue;
69617
+ const key2 = facetKey(dim, row[descriptor.rowKey]);
69618
+ if (key2 !== void 0) keys.add(key2);
69619
+ }
69620
+ censusByDim.set(dim, keys);
69621
+ }
69622
+ for (const facets of lineFacets) {
69623
+ for (const dim of active2) {
69624
+ const descriptor = FACET_DIMS[dim];
69625
+ const key2 = facetKey(dim, facets[descriptor.elementKey]);
69626
+ if (key2 === void 0 || !isDismissibleFacetValue(dim, key2)) continue;
69627
+ if (!censusByDim.get(dim).has(key2)) return { ok: false, why: "census-coverage", detail: `${dim}:${String(key2)}` };
69628
+ }
69629
+ }
69630
+ return { ok: true };
69347
69631
  }
69348
69632
  function evaluateSteelRead(context) {
69349
69633
  const proof3 = parseSteelReadAttestation(context.attestation);
@@ -69357,11 +69641,15 @@ function evaluateSteelRead(context) {
69357
69641
  const checkpointBytesMatch = checkpointRecorded && hashOf(filter) === storedManifest.savedFilterHash;
69358
69642
  const checkpointGeometryMatch = checkpointBytesMatch && steelFilterGeometryHash(filter) === steelFilterGeometryHash(storedManifest.manifest.filter);
69359
69643
  const checkpointControlsTotal = hasTotalBooleanOn(filter);
69360
- const filterCheckpointPassed = checkpointRecorded && checkpointBytesMatch && checkpointGeometryMatch && checkpointControlsTotal;
69644
+ const checkpointModeCanonical = hasCanonicalMode(filter);
69645
+ const checkpointControlValuesOk = hasWellFormedControlValues(filter);
69646
+ const filterCheckpointPassed = checkpointRecorded && checkpointBytesMatch && checkpointGeometryMatch && checkpointControlsTotal && checkpointModeCanonical && checkpointControlValuesOk;
69361
69647
  if (!checkpointRecorded) add("filter-checkpoint", "block", "the exact server-manifest Filter has not been saved");
69362
69648
  else if (!checkpointBytesMatch) add("filter-checkpoint", "block", "candidate.filter is not byte-equivalent to the saved Filter checkpoint");
69363
69649
  else if (!checkpointGeometryMatch) add("filter-checkpoint", "block", "candidate Filter geometry/ids differ from the server manifest");
69364
69650
  else if (!checkpointControlsTotal) add("filter-checkpoint", "block", "the saved Filter has a control with no explicit true/false selection");
69651
+ else if (!checkpointModeCanonical) add("filter-checkpoint", "block", "the saved Filter's match-on mode is empty or not canonical; reopen the Drawing Filter and save it again");
69652
+ else if (!checkpointControlValuesOk) add("filter-checkpoint", "block", "the saved Filter has a layer, thickness or colour control whose value is not a value for that control");
69365
69653
  else add("filter-checkpoint", "pass", "candidate uses the exact saved server-owned Filter");
69366
69654
  const validation = validateSteelModelV2(candidate);
69367
69655
  if (!validation.valid) add("contract-validity", "block", `${validation.errors.length} v2 schema/semantic error(s)`, validation.errors.map((error) => `${error.path}: ${error.message}`));
@@ -69401,7 +69689,7 @@ function evaluateSteelRead(context) {
69401
69689
  sourceManifestOk ? `${manifestSources.size} source(s) and ${storedManifest.manifest.pages.length} page(s) are identity-bound` : ledger.unboundSheets.length ? "a saved Filter sheet does not bind to a model page of this manifest" : unownedSources.length ? "a model-page candidate does not resolve in the saved Filter" : "a manifest page cites a foreign source",
69402
69690
  unownedSources
69403
69691
  );
69404
- const filterLayers = new Set(lines.map((line) => line.layer));
69692
+ const filterLayers = new Set(lines.map((line) => line.layer).filter((layer) => isDismissibleFacetValue("layer", layer)));
69405
69693
  const attestedLayers = new Set(proof3.layers.map((row) => row.layer));
69406
69694
  const missingLayers = [...filterLayers].filter((layer) => !attestedLayers.has(layer));
69407
69695
  const foreignLayers = [...attestedLayers].filter((layer) => !filterLayers.has(layer));
@@ -69428,23 +69716,72 @@ function evaluateSteelRead(context) {
69428
69716
  ledgerUnbound ? "layer line counts cannot be verified while the source ledger holds unaccounted lines" : censusCoverageBad ? "layer census does not exactly cover Filter layers" : countMismatches.length ? "attested layer line counts do not match the server-recomputed ledger" : `${filterLayers.size} Filter layer(s) classified`,
69429
69717
  ledgerUnbound ? ledgerUnbound.samples : [...missingLayers, ...foreignLayers, ...countMismatches]
69430
69718
  );
69431
- const dismissible = new Set(dismissibleLayerNames(filter));
69719
+ const dismissibleFacets = dismissibleFacetValues(filter);
69720
+ const requiredFacetKeys = /* @__PURE__ */ new Set();
69721
+ for (const row of dismissibleFacets) if (FACET_CENSUS_DIMS.includes(row.dim)) requiredFacetKeys.add(facetMapKey(row.dim, row.value));
69722
+ const attestedFacetKeys = new Set(proof3.facetExclusions.map((row) => facetMapKey(row.dim, row.value)));
69723
+ const missingFacets = [...requiredFacetKeys].filter((key2) => !attestedFacetKeys.has(key2));
69724
+ const foreignFacets = [...attestedFacetKeys].filter((key2) => !requiredFacetKeys.has(key2));
69725
+ let countsByFacet = null;
69726
+ let facetLedgerUnbound = null;
69727
+ try {
69728
+ countsByFacet = new Map(steelReadFacetLineCounts(ledger).rows.map((row) => [facetMapKey(row.dim, row.value), { model: row.model, evidence: row.evidence }]));
69729
+ } catch (error) {
69730
+ if (!(error instanceof SteelLedgerUnboundError)) throw error;
69731
+ facetLedgerUnbound = error;
69732
+ }
69733
+ const facetCountMismatches = [];
69734
+ for (const row of proof3.facetExclusions) {
69735
+ const key2 = facetMapKey(row.dim, row.value);
69736
+ if (!requiredFacetKeys.has(key2) || !countsByFacet) continue;
69737
+ const actual = countsByFacet.get(key2) ?? { model: 0, evidence: 0 };
69738
+ if (row.lineCounts.model !== actual.model || row.lineCounts.evidence !== actual.evidence) {
69739
+ facetCountMismatches.push(`${row.dim}:${String(row.value)}:attested=model=${row.lineCounts.model}:evidence=${row.lineCounts.evidence}:actual=model=${actual.model}:evidence=${actual.evidence}`);
69740
+ }
69741
+ }
69742
+ const facetCoverageBad = missingFacets.length > 0 || foreignFacets.length > 0;
69743
+ add(
69744
+ "facet-census",
69745
+ facetLedgerUnbound || facetCoverageBad || facetCountMismatches.length ? "block" : "pass",
69746
+ facetLedgerUnbound ? "facet line counts cannot be verified while the source ledger holds unaccounted lines" : facetCoverageBad ? "facet census does not exactly cover the dismissible thickness/colour values" : facetCountMismatches.length ? "attested facet line counts do not match the server-recomputed ledger" : `${requiredFacetKeys.size} human-excluded thickness/colour value(s) classified`,
69747
+ facetLedgerUnbound ? facetLedgerUnbound.samples : [...missingFacets.map((key2) => key2.replace(FACET_KEY_SEP, ":")), ...foreignFacets.map((key2) => key2.replace(FACET_KEY_SEP, ":")), ...facetCountMismatches]
69748
+ );
69749
+ const dismissibleByDim = dismissibleByDimension(dismissibleFacets);
69432
69750
  const attestedByLayer = new Map(proof3.layers.map((row) => [row.layer, row.disposition]));
69433
- const signOffValid = steelLayerSignOffValid({ storedManifest, filter, lineLayers: lines.map((line) => line.layer) });
69434
- const shorthandLayerQualifies = (layer) => {
69435
- if (!ledger.index.byLayer) return false;
69436
- if (!dismissible.has(layer)) return false;
69437
- const attested = attestedByLayer.get(layer);
69438
- return attested !== void 0 && SHORTHAND_DISPOSITIONS.has(attested);
69751
+ const attestedByFacet = new Map(proof3.facetExclusions.map((row) => [facetMapKey(row.dim, row.value), row.disposition]));
69752
+ const signOffVerdict = steelExclusionSignOffValid({ storedManifest, filter, lineFacets: lines.map((line) => line.facets) });
69753
+ const signOffValid = signOffVerdict.ok;
69754
+ const onSetByDim = {
69755
+ thickness: ledger.index.widths,
69756
+ layer: ledger.index.layers,
69757
+ color: ledger.index.colors
69758
+ };
69759
+ const activeDims = selectionDims(ledger.index.mode);
69760
+ const shorthandQualifies = (line) => {
69761
+ const failures = facetFailures({ facets: line.facets, activeDims, onSets: onSetByDim, dismissible: dismissibleByDim });
69762
+ let owner2 = null;
69763
+ for (const failure of failures) {
69764
+ if (failure.kind === "malformed") return { ok: false, blockedBy: failure.dim, why: "malformed" };
69765
+ if (failure.kind === "not-approved") return { ok: false, blockedBy: failure.dim, why: "not-approved" };
69766
+ const attested = failure.dim === "layer" ? attestedByLayer.get(failure.value) : attestedByFacet.get(facetMapKey(failure.dim, failure.value));
69767
+ if (attested === void 0 || !SHORTHAND_DISPOSITIONS.has(attested)) return { ok: false, blockedBy: failure.dim, why: attested ?? "unattested" };
69768
+ if (!owner2) owner2 = { dim: failure.dim, value: failure.value };
69769
+ }
69770
+ return owner2 ? { ok: true, ...owner2 } : { ok: false, why: "selected" };
69439
69771
  };
69440
69772
  const shorthandGatesOpen = filterCheckpointPassed && signOffValid;
69441
69773
  const observations2 = activeObservationElements(candidate);
69442
- const dispositionById = new Map(proof3.lineDispositions.map((row) => [row.elementId, row]));
69774
+ const dispositionById = new Map(
69775
+ proof3.lineDispositions.map((row) => [row.elementId, row])
69776
+ );
69777
+ for (const group of proof3.lineDispositionGroups) for (const id of group.elementIds) dispositionById.set(id, group);
69778
+ const explicitDispositionCount = dispositionById.size;
69443
69779
  const linesById = new Map(lines.map((line) => [line.id, line]));
69444
69780
  const lineIds = new Set(linesById.keys());
69445
69781
  const missingLines = [], foreignLines = [], invalidObservations = [], excludedModeled = [];
69446
69782
  let observedLines = 0, shorthandAccounted = 0, withheldByShorthand = 0;
69447
- const shorthandLayers = /* @__PURE__ */ new Set();
69783
+ const dismissedByValue = /* @__PURE__ */ new Map();
69784
+ const blockReasons = /* @__PURE__ */ new Map();
69448
69785
  for (const line of lines) {
69449
69786
  const observation = observations2.get(line.id);
69450
69787
  const disposition = dispositionById.get(line.id);
@@ -69454,15 +69791,29 @@ function evaluateSteelRead(context) {
69454
69791
  if (line.selected && line.modelable) {
69455
69792
  if (!observation && !disposition) missingLines.push(line.id);
69456
69793
  } else if (!disposition) {
69457
- if (!line.selected && shorthandLayerQualifies(line.layer)) {
69794
+ const verdict = line.selected ? { ok: false, why: "selected" } : shorthandQualifies(line);
69795
+ if (verdict.ok) {
69458
69796
  if (shorthandGatesOpen) {
69459
69797
  shorthandAccounted++;
69460
- shorthandLayers.add(line.layer);
69798
+ const key2 = facetMapKey(verdict.dim, verdict.value);
69799
+ let entry2 = dismissedByValue.get(key2);
69800
+ if (!entry2) {
69801
+ entry2 = { dim: verdict.dim, value: verdict.value, model: 0, evidence: 0 };
69802
+ dismissedByValue.set(key2, entry2);
69803
+ }
69804
+ if (line.sourceRole === "model") entry2.model += 1;
69805
+ else if (line.sourceRole === "evidence") entry2.evidence += 1;
69461
69806
  } else {
69462
69807
  withheldByShorthand++;
69463
69808
  missingLines.push(line.id);
69464
69809
  }
69465
- } else missingLines.push(line.id);
69810
+ } else {
69811
+ if (verdict.blockedBy) {
69812
+ const reason = `${verdict.blockedBy}:${verdict.why}`;
69813
+ blockReasons.set(reason, (blockReasons.get(reason) ?? 0) + 1);
69814
+ }
69815
+ missingLines.push(line.id);
69816
+ }
69466
69817
  }
69467
69818
  if (disposition?.disposition === "duplicate") {
69468
69819
  const target = disposition.duplicateOf === void 0 ? void 0 : linesById.get(disposition.duplicateOf);
@@ -69470,19 +69821,25 @@ function evaluateSteelRead(context) {
69470
69821
  }
69471
69822
  }
69472
69823
  for (const id of dispositionById.keys()) if (!lineIds.has(id)) foreignLines.push(id);
69473
- const shorthandSamples = [...shorthandLayers].sort().map((layer) => {
69474
- const counts2 = countsByLayer?.get(layer);
69475
- return `${layer}:model=${counts2?.model ?? 0}:evidence=${counts2?.evidence ?? 0}`;
69476
- });
69824
+ const shorthandSamples = [...dismissedByValue.values()].map((row) => `${row.dim}:${String(row.value)}:dismissed=model=${row.model}:evidence=${row.evidence}`).sort();
69825
+ const shorthandDims = [...new Set([...dismissedByValue.values()].map((row) => row.dim))].sort((a, b) => MODE_ORDER.indexOf(a) - MODE_ORDER.indexOf(b));
69826
+ const groupedByDisposition = /* @__PURE__ */ new Map();
69827
+ for (const group of proof3.lineDispositionGroups) {
69828
+ groupedByDisposition.set(group.disposition, (groupedByDisposition.get(group.disposition) ?? 0) + group.elementIds.length);
69829
+ }
69830
+ const groupedSamples = [...groupedByDisposition.entries()].map(([disposition, count2]) => `grouped:${disposition}=${count2}`).sort();
69831
+ const ledgerSamples = shorthandSamples;
69832
+ const groupedDetail = groupedSamples.length ? ` (${groupedSamples.length} disposition(s) grouped: ${groupedSamples.join(", ")})` : "";
69477
69833
  if (missingLines.length || foreignLines.length || invalidObservations.length || excludedModeled.length) {
69478
- const withheldCause = withheldByShorthand === 0 ? "" : !filterCheckpointPassed ? " \u2014 layer shorthand is withheld until the saved Filter checkpoint passes" : !storedManifest.layerSignOff ? " \u2014 layer shorthand is withheld until the saved layer list is approved" : storedManifest.manifest.censusScope !== "whole-set" ? " \u2014 this manifest's layer census covers only the model sheets; regenerate it, then approve the layer list" : " \u2014 the approved layer list no longer matches this Filter";
69479
- add("source-ledger", "block", `${missingLines.length} unaccounted, ${foreignLines.length} foreign, ${invalidObservations.length} invalid, ${excludedModeled.length} excluded-but-modeled line(s)${withheldCause}`, [...missingLines, ...foreignLines, ...invalidObservations, ...excludedModeled]);
69834
+ const withheldCause = withheldByShorthand === 0 ? "" : !filterCheckpointPassed ? " \u2014 exclusion shorthand is withheld until the saved Filter checkpoint passes" : !storedManifest.exclusionSignOff && storedManifest.layerSignOff ? " \u2014 this read's approval was recorded before exclusions covered thickness and colour; reopen the Drawing Filter and approve the exclusions again" : signOffVerdict.ok ? "" : signOffVerdict.why === "absent" ? " \u2014 exclusion shorthand is withheld until the saved exclusions are approved" : signOffVerdict.why === "scope" ? " \u2014 this manifest's census covers only the model sheets; regenerate it, then approve the exclusions" : signOffVerdict.why === "manifest-moved" ? " \u2014 this drawing set was re-scanned after the exclusions were approved; reload the Drawing Filter and approve them against the current scan" : signOffVerdict.why === "controls-moved" ? " \u2014 the Drawing Filter controls changed after the exclusions were approved; reload the Drawing Filter and approve them again" : signOffVerdict.why === "census-coverage" ? ` \u2014 this manifest's census does not cover ${signOffVerdict.detail ?? "a value the drawing set carries"}, so the approved list could not have covered the set; regenerate this request's steel manifest` : " \u2014 the approved exclusion list no longer matches this Filter";
69835
+ const reasonDetail = blockReasons.size ? ` \u2014 ${[...blockReasons.entries()].sort().map(([reason, count2]) => `${count2} on ${reason}`).join(", ")}` : "";
69836
+ add("source-ledger", "block", `${missingLines.length} unaccounted, ${foreignLines.length} foreign, ${invalidObservations.length} invalid, ${excludedModeled.length} excluded-but-modeled line(s)${withheldCause}${reasonDetail}`, [...missingLines, ...foreignLines, ...invalidObservations, ...excludedModeled]);
69480
69837
  } else {
69481
69838
  add(
69482
69839
  "source-ledger",
69483
- proof3.lineDispositions.length || shorthandAccounted ? "warning" : "pass",
69484
- `${lines.length}/${lines.length} manifest line(s) accounted; ${observedLines} by active observations, ${proof3.lineDispositions.length} by explicit dispositions, and ${shorthandAccounted} by whole-set layer shorthand on ${shorthandLayers.size} human-disabled layer(s)`,
69485
- shorthandSamples
69840
+ explicitDispositionCount || shorthandAccounted ? "warning" : "pass",
69841
+ `${lines.length}/${lines.length} manifest line(s) accounted; ${observedLines} by active observations, ${explicitDispositionCount} by explicit dispositions${groupedDetail}, and ${shorthandAccounted} by whole-set exclusion shorthand on ${dismissedByValue.size} human-excluded value(s)${shorthandDims.length ? ` across ${shorthandDims.join(", ")}` : ""}`,
69842
+ ledgerSamples
69486
69843
  );
69487
69844
  }
69488
69845
  const pagesById = new Map(storedManifest.manifest.pages.map((page) => [page.id, page]));
@@ -69625,7 +69982,10 @@ function evaluateSteelRead(context) {
69625
69982
  lines: lines.length,
69626
69983
  selectedLines: lines.filter((line) => line.selected).length,
69627
69984
  observedLines,
69628
- dispositions: proof3.lineDispositions.length,
69985
+ // NAMED IDS across both arrays, not rows — see `explicitDispositionCount`. `counts` stays a
69986
+ // CLOSED shape: this field keeps its name and its meaning ("how many lines carry a written
69987
+ // disposition") and merely stops being computed wrongly.
69988
+ dispositions: explicitDispositionCount,
69629
69989
  members: members.length,
69630
69990
  joints: joints.length,
69631
69991
  warnings,
@@ -70887,6 +71247,77 @@ async function runNativeRevisionRead(opts) {
70887
71247
  });
70888
71248
  }
70889
71249
 
71250
+ // connection-review-derive.ts
71251
+ var isCustom2 = (j) => !!j && typeof j.id === "string" && !!j.id && j.kind === "custom";
71252
+ var rowFor = (review, jointId) => Object.prototype.hasOwnProperty.call(review.joints, jointId) ? review.joints[jointId] : void 0;
71253
+ function reviewAggregate(input) {
71254
+ return hashOf({
71255
+ domain: "floless:connection-review-aggregate:v1",
71256
+ self: input.self,
71257
+ members: input.members.map((m) => "missing" in m ? { id: m.id, missing: true } : { id: m.id, fp: m.fp })
71258
+ });
71259
+ }
71260
+ function baselineAggregate(baseline) {
71261
+ return reviewAggregate({ self: baseline.self, members: baseline.members });
71262
+ }
71263
+ function liveAggregate(baseline, joint, membersById) {
71264
+ return reviewAggregate({
71265
+ self: connectionSelfDigest(joint),
71266
+ members: baseline.members.map((m) => {
71267
+ const member = membersById.get(m.id);
71268
+ return member === void 0 ? { id: m.id, missing: true } : { id: m.id, fp: memberPhysicalInputDigest(member) };
71269
+ })
71270
+ });
71271
+ }
71272
+ function deriveConnectionReviewState(row, joint, membersById) {
71273
+ if (!row) return { state: "untracked", reason: "placed-outside-a-placement-command" };
71274
+ if ("untracked" in row) return { state: "untracked", reason: row.untracked };
71275
+ if (row.baseline.members.length === 0) return { state: "untracked", reason: "no-members-chosen" };
71276
+ const live = liveAggregate(row.baseline, joint, membersById);
71277
+ if (live === baselineAggregate(row.baseline)) return { state: "clean" };
71278
+ if (row.signedOff !== void 0 && live === row.signedOff) return { state: "clean" };
71279
+ return { state: "needs-review", memberIds: row.baseline.members.map((m) => m.id) };
71280
+ }
71281
+ function connectionReviewSummary(review, contract) {
71282
+ const membersById = new Map((contract.members ?? []).map((m) => [m.id, m]));
71283
+ const needsReview = [];
71284
+ const untracked = [];
71285
+ const signedOff = [];
71286
+ for (const joint of (contract.joints ?? []).filter(isCustom2)) {
71287
+ const row = rowFor(review, joint.id);
71288
+ const derived = deriveConnectionReviewState(row, joint, membersById);
71289
+ if (derived.state === "needs-review") needsReview.push({ jointId: joint.id, memberIds: derived.memberIds });
71290
+ else if (derived.state === "untracked") untracked.push({ jointId: joint.id, reason: derived.reason });
71291
+ else if (row && "baseline" in row && row.signedOff !== void 0 && row.signedOff === liveAggregate(row.baseline, joint, membersById)) {
71292
+ signedOff.push(joint.id);
71293
+ }
71294
+ }
71295
+ needsReview.sort((a, b) => a.jointId < b.jointId ? -1 : a.jointId > b.jointId ? 1 : 0);
71296
+ untracked.sort((a, b) => a.jointId < b.jointId ? -1 : a.jointId > b.jointId ? 1 : 0);
71297
+ signedOff.sort();
71298
+ return { reviewRevision: review.reviewRevision, needsReview, untracked, signedOff };
71299
+ }
71300
+ function connectionReviewSceneMap(review, contract) {
71301
+ const out = /* @__PURE__ */ new Map();
71302
+ const s = connectionReviewSummary(review, contract);
71303
+ for (const e of s.needsReview) out.set(e.jointId, "needs-review");
71304
+ for (const e of s.untracked) out.set(e.jointId, "untracked");
71305
+ return out;
71306
+ }
71307
+ function connectionReviewUnavailable(contract) {
71308
+ const untracked = (contract?.joints ?? []).filter(isCustom2).map((j) => ({ jointId: j.id, reason: "placed-outside-a-placement-command" })).sort((a, b) => a.jointId < b.jointId ? -1 : a.jointId > b.jointId ? 1 : 0);
71309
+ return { reviewRevision: -1, needsReview: [], untracked, signedOff: [] };
71310
+ }
71311
+ function connectionReviewUnavailableSceneMap(contract) {
71312
+ const out = /* @__PURE__ */ new Map();
71313
+ for (const e of connectionReviewUnavailable(contract).untracked) out.set(e.jointId, "untracked");
71314
+ return out;
71315
+ }
71316
+ function signOffAggregateFor(row, joint, membersById) {
71317
+ if (!row || !("baseline" in row)) return null;
71318
+ return liveAggregate(row.baseline, joint, membersById);
71319
+ }
71320
+
70890
71321
  // steel-member-geo.ts
70891
71322
  function buildMemberGeo(model) {
70892
71323
  const { view, issues } = readModelOrIssues(model);
@@ -71107,9 +71538,21 @@ async function readContractSnapshot(opts) {
71107
71538
  const contract = readAcceptedContract(opts);
71108
71539
  if (contract == null) return null;
71109
71540
  const publication = publicationForSnapshot(contractPath(opts.appId, opts.projectId), contract);
71110
- return { contract, ...publication };
71541
+ const review = opts.projectId ? reviewForSnapshot(opts.projectId, contract) : null;
71542
+ return { contract, ...publication, ...review ?? {} };
71111
71543
  });
71112
71544
  }
71545
+ function reviewForSnapshot(projectId, contract) {
71546
+ if (!isModelV2(contract)) return null;
71547
+ try {
71548
+ const file = readReviewFile(projectId);
71549
+ return { reviewRevision: file.reviewRevision, review: connectionReviewSummary(file, contract) };
71550
+ } catch (e) {
71551
+ console.error("[connection-review] could not derive the review summary for this snapshot", e, { projectId });
71552
+ const review = connectionReviewUnavailable(contract);
71553
+ return { reviewRevision: review.reviewRevision, review };
71554
+ }
71555
+ }
71113
71556
  var NO_CONTRACT = Object.freeze({ kind: "none" });
71114
71557
  function resolveAppContract(appId, operation, readAppFn) {
71115
71558
  const resolved = readAppFn ? readContractForAppWithSource(appId, readAppFn) : readContractForAppWithSource(appId);
@@ -71173,6 +71616,7 @@ var PreconditionRequiredError = class extends Error {
71173
71616
  };
71174
71617
  var MEMBER_END_DECISION_AUTHORITY = /* @__PURE__ */ Symbol("member-end-decision-authority");
71175
71618
  var CONTRACT_GENERATION_AUTHORITY = /* @__PURE__ */ Symbol("contract-generation-authority");
71619
+ var CONNECTION_PLACEMENT_AUTHORITY = /* @__PURE__ */ Symbol("connection-placement-authority");
71176
71620
  async function writeContractChecked(appId, doc, projectId, origin) {
71177
71621
  const kind = projectId ? "project" : "app";
71178
71622
  const key2 = projectId ?? appId;
@@ -71279,14 +71723,20 @@ async function writeContractChecked(appId, doc, projectId, origin) {
71279
71723
  } else if (declaredTypeOf(finalContract) === STEEL_V2) {
71280
71724
  persistConnectionReviewForWrite({
71281
71725
  projectId: projectId ?? null,
71282
- finalAfter: finalContract,
71726
+ finalAfter: normaliseRollMarkers(finalContract),
71283
71727
  origin: reviewOriginForGatewayWrite(origin.origin)
71284
71728
  });
71285
71729
  }
71286
71730
  return {
71287
71731
  ...publication,
71288
71732
  conditional: !!(pre.ifMatch || pre.ifNoneMatch),
71289
- contract: finalContract,
71733
+ // The STORED document, not the caller's pre-normalisation one (#860). `writeContract` normalises
71734
+ // roll markers, so returning `finalContract` hands the caller a document whose ETag — computed
71735
+ // over the normalised bytes — does not describe it. Two things broke on that: the connection
71736
+ // review's `self` baseline was recorded against the un-normalised doc and read back drifted, and
71737
+ // `member-end-routes` staged its undo token over a hash the store would never reproduce, so Undo
71738
+ // silently never offered itself. Idempotent, and free when nothing carried a marker.
71739
+ contract: normaliseRollMarkers(finalContract),
71290
71740
  invalidatedWorkPointDecisions: prepared.invalidated,
71291
71741
  ...revalidation ? { revalidation } : {}
71292
71742
  };
@@ -71299,6 +71749,14 @@ function writeMemberEndContractChecked(appId, doc, projectId, ifMatch) {
71299
71749
  [MEMBER_END_DECISION_AUTHORITY]: true
71300
71750
  });
71301
71751
  }
71752
+ function writeConnectionPlacementChecked(appId, doc, projectId, ifMatch, placement) {
71753
+ return writeContractChecked(appId, doc, projectId, {
71754
+ origin: "connection-placement",
71755
+ ifMatch,
71756
+ placement,
71757
+ [CONNECTION_PLACEMENT_AUTHORITY]: true
71758
+ });
71759
+ }
71302
71760
  function writeContractGenerationChecked(appId, doc, projectId, why) {
71303
71761
  return writeContractChecked(appId, doc, projectId, {
71304
71762
  origin: "contract-generation",
@@ -72432,6 +72890,9 @@ function sanitizeMutationId(raw) {
72432
72890
  if (typeof raw !== "string") return void 0;
72433
72891
  return MUTATION_ID_RE.test(raw) ? raw : void 0;
72434
72892
  }
72893
+ function reviewChangedEvent(appId, project, reviewRevision) {
72894
+ return { type: "review-changed", appId, project, reviewRevision };
72895
+ }
72435
72896
  function contractChangedEvent(appId, project, etag, storeRevision, rawMutationId) {
72436
72897
  const mutationId = sanitizeMutationId(rawMutationId);
72437
72898
  return { type: "contract-changed", appId, project, etag, storeRevision, ...mutationId ? { mutationId } : {} };
@@ -73400,7 +73861,7 @@ function revisionReadContractError(appId, contract, current, lifecycle = { initi
73400
73861
  // steel-filter-prepass.ts
73401
73862
  var import_node_child_process7 = require("node:child_process");
73402
73863
  var PYTHON = String.raw`
73403
- import base64, hashlib, json, math, re, sys
73864
+ import base64, decimal, hashlib, json, math, re, sys
73404
73865
  import fitz
73405
73866
 
73406
73867
  manifest = json.load(sys.stdin)
@@ -73444,11 +73905,68 @@ def colour(v):
73444
73905
  return "#%06x" % (v & 0xffffff)
73445
73906
  return "#000000"
73446
73907
 
73908
+ # THE canonical facet key, in Python - the FOURTH canonicaliser, and the last one (issue #805 Phase D).
73909
+ #
73910
+ # facetKey in web/steel-filter-core.js already covers the browser panel, the ledger predicate and the
73911
+ # whole-set census merge. This one covers the EXTRACTOR, and it was the hole: old_on matched a stored
73912
+ # row by RAW equality, so a human exclusion recorded against "#ABC123" was never found for the "#abc123"
73913
+ # this pass emits, and a stored 0.4001 was never found for a re-extracted 0.4. The human's decision
73914
+ # silently reverted to the default - ON for thickness and colour - on the very next extraction.
73915
+ #
73916
+ # The rules are facetKey's, exactly: widths to 2 dp, colours lower-cased, layer names compared exactly.
73917
+ # The rounding deliberately mirrors JavaScript's Number(w.toFixed(2)) rather than Python's round(),
73918
+ # which is banker's: round(0.125, 2) is 0.12 while JS gives 0.13, and one key rule that answers
73919
+ # differently in two languages is the defect this whole phase exists to remove. Decimal over the FLOAT
73920
+ # (never over repr()) reproduces toFixed's own basis - the exact binary value - so 1.005, whose float is
73921
+ # really 1.00499..., rounds DOWN in both.
73922
+ #
73923
+ # NaN and Infinity cannot reach here: "old" is json.loads output and JSON carries neither literal. They
73924
+ # are guarded anyway, and a non-finite width simply finds no prior decision, which falls back to the
73925
+ # default - and a defaulted-ON value is never dismissible, so the fallback is the safe direction.
73926
+ def facet_key(kind, value):
73927
+ if kind == "thicknesses":
73928
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
73929
+ return None
73930
+ if not math.isfinite(value):
73931
+ return None
73932
+ # The context is WIDENED, and that is not tuning. Decimal's default 28-digit precision cannot
73933
+ # hold the quantized result of a large double - Decimal(1e100) carries ~101 integer digits, so
73934
+ # quantizing it to two places needs ~103 and raises InvalidOperation instead of rounding. That
73935
+ # exception escapes the extraction, so ONE unrelated stale row in a prior filter killed the
73936
+ # whole pass. 400 digits covers every finite double (the largest carries ~309 integer digits),
73937
+ # so the branch cannot raise for any value JSON can express. Parity is preserved across the
73938
+ # whole range, including where JS's toFixed switches to exponential: the expansion round-trips
73939
+ # back to the same double. (Codex review, finding 2.)
73940
+ with decimal.localcontext() as ctx:
73941
+ ctx.prec = 400
73942
+ return float(decimal.Decimal(float(value)).quantize(decimal.Decimal("0.01"), rounding=decimal.ROUND_HALF_UP))
73943
+ if kind == "layers":
73944
+ return value if isinstance(value, str) else None
73945
+ if kind == "colors":
73946
+ return value.lower() if isinstance(value, str) else None
73947
+ # Loud, and unreachable from correct code is exactly why: a quiet None here would silently discard
73948
+ # EVERY prior tick for that facet and re-default the whole list.
73949
+ raise RuntimeError("facet_key: unknown facet %r" % (kind,))
73950
+
73951
+ # A prior human tick for one canonical value: the UNION of "on" across every stored row that folds to
73952
+ # it, or None for "no prior decision" - which is NOT the same as a prior False.
73953
+ #
73954
+ # Union rather than first-wins, and that is load-bearing rather than tidy. Once "#ABC123: false" and
73955
+ # "#abc123: true" are ONE value, first-wins makes the answer depend on which order two colliding rows
73956
+ # happen to sit in, and OFF is the DANGEROUS direction: an OFF value is what the completion proof may
73957
+ # dismiss without a line-by-line reason, so an accident of ordering would turn a human's CONFLICTING
73958
+ # controls into an authoritative "the human excluded this". Union-of-ON is also exactly what
73959
+ # mergeWholeSetLayerCensus does for the same collision, and what selFromFilter renders.
73447
73960
  def old_on(kind, key, field):
73961
+ canonical = facet_key(kind, key)
73962
+ found = None
73448
73963
  for item in old.get(kind, []):
73449
- if item.get(field) == key and "on" in item:
73450
- return bool(item["on"])
73451
- return None
73964
+ if not isinstance(item, dict) or "on" not in item:
73965
+ continue
73966
+ if facet_key(kind, item.get(field)) != canonical:
73967
+ continue
73968
+ found = bool(item["on"]) if found is None else (found or bool(item["on"]))
73969
+ return found
73452
73970
 
73453
73971
  # Which layer names read as structural steel. This decides a layer's "steel" flag AND its default
73454
73972
  # "on" tick, and the error cost is ASYMMETRIC: a layer this misses defaults OFF, and an OFF layer is
@@ -73501,6 +74019,39 @@ def path_svg(items, matrix):
73501
74019
  out.append("M%s %sL%s %sL%s %sL%s %sZ" % tuple(v for p in points for v in p))
73502
74020
  return "".join(out)
73503
74021
 
74022
+ def line_dash_pattern(path_type, value):
74023
+ # The dashed flag is structural: a valid stroked dash cycle has a positive OFF interval. Fill, clip and
74024
+ # group records do not paint a line, so PyMuPDF's dash metadata is irrelevant for them. Unknown
74025
+ # painted record types fail loudly rather than quietly changing drawing semantics after an
74026
+ # extractor upgrade.
74027
+ import math, re
74028
+ if path_type in ("f", "clip", "group"):
74029
+ return False
74030
+ if path_type not in ("s", "fs"):
74031
+ raise RuntimeError("unsupported PyMuPDF painted drawing type: %r" % (path_type,))
74032
+ if value is None or value == "":
74033
+ return False
74034
+ if not isinstance(value, str):
74035
+ raise RuntimeError("PyMuPDF returned a non-string dash pattern")
74036
+ match = re.fullmatch(r"\s*\[([^\]]*)\]\s+([^\s]+)\s*", value)
74037
+ if match is None:
74038
+ raise RuntimeError("PyMuPDF returned a malformed dash pattern: %r" % (value,))
74039
+ try:
74040
+ cycle = [float(token) for token in match.group(1).split()]
74041
+ phase = float(match.group(2))
74042
+ except ValueError:
74043
+ raise RuntimeError("PyMuPDF returned a malformed dash pattern: %r" % (value,))
74044
+ if not math.isfinite(phase) or any(not math.isfinite(length) or length < 0 for length in cycle):
74045
+ raise RuntimeError("PyMuPDF returned a non-finite or negative dash pattern: %r" % (value,))
74046
+ if not cycle:
74047
+ return False
74048
+ # PyMuPDF accepts and emits all-zero dash arrays. Issue #847 explicitly defines those as
74049
+ # continuous, so do not turn a real producer value into a whole-drawing extraction failure.
74050
+ if not any(length > 0 for length in cycle):
74051
+ return False
74052
+ normalized = cycle * 2 if len(cycle) % 2 else cycle
74053
+ return any(length > 0 for length in normalized[1::2])
74054
+
73504
74055
  sheet_rows = []
73505
74056
  sheet_names = []
73506
74057
  measured = []
@@ -73554,7 +74105,7 @@ for source in manifest["sources"]:
73554
74105
  if rounded:
73555
74106
  element = {"kind":"circle", "layer":layer, "cx":n((bbox.x0+bbox.x1)/2), "cy":n((bbox.y0+bbox.y1)/2), "r":n((bbox.width+bbox.height)/4), "w":width, "color":color}
73556
74107
  else:
73557
- element = {"kind":"line", "layer":layer, "w":width, "color":color, "d":svg, "dashed":bool(drawing.get("dashes"))}
74108
+ element = {"kind":"line", "layer":layer, "w":width, "color":color, "d":svg, "dashed":line_dash_pattern(drawing.get("type"), drawing.get("dashes"))}
73558
74109
  page_elements += 1
73559
74110
  if page_elements <= max_page_elements:
73560
74111
  elements.append(element)
@@ -73661,7 +74212,7 @@ for key in sorted(colour_counts):
73661
74212
  # The envelope is accounted for too, so EVERY byte this process writes has been counted against the
73662
74213
  # budget before any of it is written. Without this the layer/width/colour census would be a blind
73663
74214
  # spot — small on a real set, unbounded in principle on a set with thousands of distinct layers.
73664
- head = '{"extractorVersion":"pymupdf-steel-filter/v2","mode":"layer","active":0,"sheets":['
74215
+ head = '{"extractorVersion":"${STEEL_FILTER_EXTRACTOR_VERSION}","mode":"layer","active":0,"sheets":['
73665
74216
  tail = '],"layers":%s,"thicknesses":%s,"colors":%s}' % (
73666
74217
  json.dumps(layers, separators=(",", ":"), ensure_ascii=True),
73667
74218
  json.dumps(widths, separators=(",", ":"), ensure_ascii=True),
@@ -73738,6 +74289,12 @@ for source in manifest["sources"]:
73738
74289
 
73739
74290
  json.dump({"pages":pages}, sys.stdout, separators=(",", ":"))
73740
74291
  `;
74292
+ function currentSteelFilterResult(value) {
74293
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.extractorVersion !== STEEL_FILTER_EXTRACTOR_VERSION || !Array.isArray(value.sheets)) {
74294
+ throw new Error(`Steel Filter extraction must return ${STEEL_FILTER_EXTRACTOR_VERSION}`);
74295
+ }
74296
+ return value;
74297
+ }
73741
74298
  var SteelFilterBudgetError = class extends Error {
73742
74299
  total;
73743
74300
  bytes;
@@ -73880,10 +74437,11 @@ async function extractSteelFilter(manifest, options = {}) {
73880
74437
  }
73881
74438
  throw budgetRefusalFrom(refusal, limits);
73882
74439
  }
73883
- if (!filter || typeof filter !== "object" || !Array.isArray(filter.sheets) || filter.sheets.length === 0 || filter.sheets.length > STEEL_READ_MAX_PAGES) {
74440
+ const result = currentSteelFilterResult(filter);
74441
+ if (result.sheets.length === 0 || result.sheets.length > STEEL_READ_MAX_PAGES) {
73884
74442
  throw new Error("Steel Filter extraction returned no populated sheets");
73885
74443
  }
73886
- const sheets = filter.sheets;
74444
+ const sheets = result.sheets;
73887
74445
  const counts2 = [];
73888
74446
  for (const sheet of sheets) {
73889
74447
  if (!sheet || typeof sheet !== "object" || Array.isArray(sheet) || !Array.isArray(sheet.elements)) {
@@ -73931,7 +74489,7 @@ async function extractSteelFilter(manifest, options = {}) {
73931
74489
  });
73932
74490
  }
73933
74491
  }
73934
- return filter;
74492
+ return result;
73935
74493
  }
73936
74494
  async function inspectSteelSourcePages(sources, options = {}) {
73937
74495
  if (!sources.length || sources.length > STEEL_READ_MAX_SOURCES) throw new Error("the revision needs a bounded PDF source inventory");
@@ -73970,12 +74528,133 @@ async function inspectSteelSourcePages(sources, options = {}) {
73970
74528
  });
73971
74529
  }
73972
74530
 
74531
+ // steel-exclusion-preflight.ts
74532
+ var MIN_DISPOSITION_ROW_BYTES_WITHOUT_ID = 14 + 17 + 8 + 12 + 1 + 2 + 1;
74533
+ var minimumRowBytes = (id) => MIN_DISPOSITION_ROW_BYTES_WITHOUT_ID + Buffer.byteLength(JSON.stringify(id)) - 2;
74534
+ var minimumRowBytesNoSeparator = (id) => minimumRowBytes(id) - 1;
74535
+ var minimalProofBytes = (pageIds, carrier) => Buffer.byteLength(JSON.stringify({
74536
+ version: 4,
74537
+ massing: { buildingCount: 1, summary: "x" },
74538
+ layers: [],
74539
+ facetExclusions: [],
74540
+ // The ROW carrier states its id inline (the caller adds the id's bytes minus the two quotes counted
74541
+ // here); the GROUP carrier leaves `elementIds` empty for the caller to fill.
74542
+ lineDispositions: carrier === "row" ? [{ elementId: "", disposition: "existing", reason: "x" }] : [],
74543
+ lineDispositionGroups: carrier === "group" ? [{ disposition: "existing", reason: "x", elementIds: [] }] : [],
74544
+ pageReviews: pageIds.map((pageId) => ({ pageId, kind: "whole", candidateShardHash: "0".repeat(64), note: "x" })),
74545
+ references: [],
74546
+ candidateDispositions: [],
74547
+ jointReviews: []
74548
+ }));
74549
+ var groupedIdBytes = (id) => Buffer.byteLength(JSON.stringify(id));
74550
+ var emptySplit = () => ({ model: 0, evidence: 0 });
74551
+ var addRole = (split, line) => {
74552
+ if (line.sourceRole === "model") split.model += 1;
74553
+ else if (line.sourceRole === "evidence") split.evidence += 1;
74554
+ };
74555
+ function steelExclusionPreflight(ledger, filter) {
74556
+ const census = steelReadFacetLineCounts(ledger);
74557
+ const dismissed = dismissibleFacetValues(filter);
74558
+ const dismissibleByDim = dismissibleByDimension(dismissed);
74559
+ const activeDims = selectionDims(ledger.index.mode);
74560
+ const onSetByDim = {
74561
+ thickness: ledger.index.widths,
74562
+ layer: ledger.index.layers,
74563
+ color: ledger.index.colors
74564
+ };
74565
+ const potentialLines = emptySplit();
74566
+ const selectedOnEvidence = emptySplit();
74567
+ const unauthorisedExclusion = emptySplit();
74568
+ let selectedModelable = 0;
74569
+ let lowerBoundRows = 0;
74570
+ let forcedIdBytes = 0;
74571
+ const pageIds = /* @__PURE__ */ new Set();
74572
+ let worstCaseRows = 0;
74573
+ let worstCaseRowBytes = 0;
74574
+ for (const line of ledger.lines) {
74575
+ pageIds.add(line.pageId);
74576
+ if (line.selected) {
74577
+ if (line.modelable) {
74578
+ selectedModelable += 1;
74579
+ worstCaseRows += 1;
74580
+ worstCaseRowBytes += minimumRowBytesNoSeparator(line.id);
74581
+ continue;
74582
+ }
74583
+ addRole(selectedOnEvidence, line);
74584
+ lowerBoundRows += 1;
74585
+ forcedIdBytes += groupedIdBytes(line.id);
74586
+ worstCaseRows += 1;
74587
+ worstCaseRowBytes += minimumRowBytesNoSeparator(line.id);
74588
+ continue;
74589
+ }
74590
+ if (everyFailureExcluded(facetFailures({ facets: line.facets, activeDims, onSets: onSetByDim, dismissible: dismissibleByDim }))) {
74591
+ addRole(potentialLines, line);
74592
+ continue;
74593
+ }
74594
+ addRole(unauthorisedExclusion, line);
74595
+ lowerBoundRows += 1;
74596
+ forcedIdBytes += groupedIdBytes(line.id);
74597
+ worstCaseRows += 1;
74598
+ worstCaseRowBytes += minimumRowBytesNoSeparator(line.id);
74599
+ }
74600
+ const pages = [...pageIds].sort();
74601
+ const worstCaseBytes = worstCaseRows === 0 ? minimalProofBytes(pages, "none") : minimalProofBytes(pages, "none") + worstCaseRowBytes + (worstCaseRows - 1);
74602
+ const lowerBoundBytes = lowerBoundRows === 0 ? minimalProofBytes(pages, "none") : Math.min(
74603
+ minimalProofBytes(pages, "row") + forcedIdBytes - 2 + (lowerBoundRows - 1) * (MIN_DISPOSITION_ROW_BYTES_WITHOUT_ID - 2),
74604
+ minimalProofBytes(pages, "group") + forcedIdBytes + (lowerBoundRows - 1)
74605
+ );
74606
+ return {
74607
+ dismissed,
74608
+ facetLineCounts: census.rows.map((row) => ({ dim: row.dim, value: row.value, model: row.model, evidence: row.evidence })),
74609
+ facetUncensused: census.uncensused.map((row) => ({ dim: row.dim, model: row.model, evidence: row.evidence })),
74610
+ potentialLines,
74611
+ forcedRows: {
74612
+ selectedOnEvidence,
74613
+ unauthorisedExclusion,
74614
+ total: lowerBoundRows
74615
+ },
74616
+ selectedModelable,
74617
+ budget: {
74618
+ capBytes: MAX_ATTESTATION_BYTES,
74619
+ lowerBoundRows,
74620
+ lowerBoundBytes,
74621
+ worstCaseRows,
74622
+ worstCaseBytes,
74623
+ impossible: lowerBoundBytes > MAX_ATTESTATION_BYTES,
74624
+ strained: worstCaseBytes > MAX_ATTESTATION_BYTES
74625
+ }
74626
+ };
74627
+ }
74628
+
73973
74629
  // revision-routes.ts
73974
74630
  var EVIDENCE_KINDS = /* @__PURE__ */ new Set(["plan", "elevation", "section", "detail", "schedule", "notes", "foundation", "other"]);
73975
74631
  var MODEL_KINDS = /* @__PURE__ */ new Set(["plan", "elevation", "section"]);
73976
74632
  var SHEET_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/;
73977
- var MAX_SIGNOFF_LAYERS = 5e3;
73978
- var MAX_SIGNOFF_LAYER_NAME = 200;
74633
+ var MAX_SIGNOFF_VALUES = MAX_FACET_EXCLUSIONS;
74634
+ var MAX_SIGNOFF_STRING_VALUE = MAX_FACET_VALUE_CHARS;
74635
+ var MAX_PREVIEW_BODY_BYTES = STEEL_FILTER_MAX_OUTPUT_BYTES;
74636
+ var PREVIEW_CACHE_MAX = 32;
74637
+ var previewCache = /* @__PURE__ */ new Map();
74638
+ var previewCacheKey = (requestId, manifestHash, controlsHash) => `${requestId}|${manifestHash}|${controlsHash}`;
74639
+ function previewCacheGet(key2) {
74640
+ if (!previewCache.has(key2)) return void 0;
74641
+ const value = previewCache.get(key2);
74642
+ previewCache.delete(key2);
74643
+ previewCache.set(key2, value);
74644
+ return value;
74645
+ }
74646
+ function previewCacheSet(key2, value) {
74647
+ previewCache.delete(key2);
74648
+ previewCache.set(key2, value);
74649
+ while (previewCache.size > PREVIEW_CACHE_MAX) {
74650
+ const oldest = previewCache.keys().next();
74651
+ if (oldest.done) break;
74652
+ previewCache.delete(oldest.value);
74653
+ }
74654
+ }
74655
+ function dropSteelExclusionPreviewCache(requestId) {
74656
+ for (const key2 of [...previewCache.keys()]) if (key2.startsWith(`${requestId}|`)) previewCache.delete(key2);
74657
+ }
73979
74658
  function retainedNormalizationReceipt(literalCandidateHash, candidate, current) {
73980
74659
  if (!literalCandidateHash) return void 0;
73981
74660
  const normalized = normalizeSteelMemberEndsForRead(candidate, new Set(current.members.map((member) => member.id)));
@@ -74038,7 +74717,7 @@ function buildCompactManifestPages(pages, evidenceSheets, filter) {
74038
74717
  }
74039
74718
  function replyStagedAttestationRetired(input) {
74040
74719
  const { reply, req, error, projectId, requestId, stagingKey, startedAt } = input;
74041
- const retired = error.message === ATTESTATION_V1_RETIRED_ERROR;
74720
+ const retired = error instanceof SteelReadAttestationRetiredError;
74042
74721
  req.log.warn({
74043
74722
  phase: "confirm",
74044
74723
  projectId,
@@ -74082,7 +74761,13 @@ function logSteelAuditEvent(log2, input) {
74082
74761
  // confirm step cannot show it either (`stagedSummary` carries no audit report). So the samples of
74083
74762
  // every warning ride the audit event, making a wholesale dismissal a durable, searchable record at
74084
74763
  // all three phases — preflight, submit and confirm (#805 Phase C slice 2).
74085
- warnings: input.report.checks.filter((check) => check.status === "warning").slice(0, 10).map((check) => ({ id: check.id, samples: (check.samples ?? []).slice(0, 20) })),
74764
+ // `detail` rides along, not just `id` and `samples`. The samples are a BOUNDED projection — 20
74765
+ // slots shared between the shorthand's per-value evidence and the grouped per-disposition
74766
+ // breakdown — so on a large read the log could record that a wholesale dismissal happened while
74767
+ // dropping what KIND it was. The detail sentence carries the full breakdown and is the only place
74768
+ // the reason a check warned survives at all; without it this record is `source-ledger:warning`
74769
+ // and nothing an investigator can act on (#805 Phase D).
74770
+ warnings: input.report.checks.filter((check) => check.status === "warning").slice(0, 10).map((check) => ({ id: check.id, detail: check.detail.slice(0, 500), samples: (check.samples ?? []).slice(0, 20) })),
74086
74771
  counts: input.report.counts,
74087
74772
  durationMs: Math.max(0, Date.now() - input.startedAt)
74088
74773
  }, "steel read audit event");
@@ -74543,6 +75228,8 @@ function registerRevisionRoutes(app, deps = {}) {
74543
75228
  pages: modelPages.map((page) => ({ sourceHash: page.sourceHash, page: page.page, sheet: page.sheet })),
74544
75229
  ...currentObj?.filter === void 0 ? {} : { filter: currentObj.filter }
74545
75230
  });
75231
+ evidenceFilter = currentSteelFilterResult(evidenceFilter);
75232
+ filter = currentSteelFilterResult(filter);
74546
75233
  } catch (error) {
74547
75234
  if (error instanceof SteelFilterBudgetError) {
74548
75235
  const labelByPage = new Map(pages.map((page) => [`${page.sourceHash} ${page.page}`, page.sheet]));
@@ -74603,13 +75290,14 @@ function registerRevisionRoutes(app, deps = {}) {
74603
75290
  return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: error instanceof Error ? error.message : "could not extract Steel Filter geometry" });
74604
75291
  }
74605
75292
  filter = mergeWholeSetLayerCensus({ modelFilter: filter, evidenceFilter, priorFilter: currentObj?.filter });
75293
+ filter = currentSteelFilterResult(filter);
74606
75294
  const evidenceSheets = evidenceFilter && typeof evidenceFilter === "object" && !Array.isArray(evidenceFilter) && Array.isArray(evidenceFilter.sheets) ? evidenceFilter.sheets : [];
74607
75295
  let stored2;
74608
75296
  try {
74609
75297
  const manifestPages = buildCompactManifestPages(pages, evidenceSheets, filter);
74610
75298
  stored2 = writeSteelReadManifest({
74611
75299
  version: 1,
74612
- extractorVersion: "pymupdf-steel-filter/v2",
75300
+ extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
74613
75301
  requestId: request.id,
74614
75302
  projectId: project.id,
74615
75303
  appId: project.app,
@@ -74708,18 +75396,21 @@ function registerRevisionRoutes(app, deps = {}) {
74708
75396
  pageId: error.pageId
74709
75397
  });
74710
75398
  }
75399
+ const acceptedForFilter = readAcceptedForRequest(project.app, project.id, "read");
75400
+ const acceptedFilter = acceptedForFilter && typeof acceptedForFilter === "object" && !Array.isArray(acceptedForFilter) ? acceptedForFilter.filter : void 0;
75401
+ const savedFilterCurrent = !!stored2.savedFilterHash && hashOf(acceptedFilter) === stored2.savedFilterHash;
75402
+ const exclusionBasis = savedFilterCurrent ? "saved-filter" : "manifest-filter";
75403
+ const effectiveFilter = savedFilterCurrent ? acceptedFilter : stored2.manifest.filter;
74711
75404
  let layerLineCounts;
75405
+ let preflight;
74712
75406
  try {
74713
- layerLineCounts = steelReadLayerLineCounts(sourceLineInventory({
75407
+ const ledger = sourceLineInventory({
74714
75408
  pages: stored2.manifest.pages,
74715
- // The GET necessarily folds over the MANIFEST's filter (there is no candidate yet) while the
74716
- // audit folds over `candidate.filter`. Those provably yield identical counts whenever
74717
- // `steelFilterGeometryHash` matches — the counts read page roles, sheet bindings, layers and
74718
- // geometry, never the `on` flags — and that hash equality is exactly what `filter-checkpoint`
74719
- // requires before any verdict rests on them.
74720
- filter: stored2.manifest.filter,
75409
+ filter: effectiveFilter,
74721
75410
  inventory: stored2.manifest.candidatesRepr === "v2-compact" ? compactManifestInventory(stored2.manifest.pages) : null
74722
- }));
75411
+ });
75412
+ layerLineCounts = steelReadLayerLineCounts(ledger);
75413
+ preflight = steelExclusionPreflight(ledger, effectiveFilter);
74723
75414
  } catch (error) {
74724
75415
  if (!(error instanceof SteelLedgerUnboundError)) throw error;
74725
75416
  return reply.status(409).send({
@@ -74729,7 +75420,21 @@ function registerRevisionRoutes(app, deps = {}) {
74729
75420
  samples: error.samples.slice(0, 20)
74730
75421
  });
74731
75422
  }
74732
- return { ok: true, ...stored2, pageShards, layerLineCounts };
75423
+ return {
75424
+ ok: true,
75425
+ ...stored2,
75426
+ pageShards,
75427
+ layerLineCounts,
75428
+ exclusionBasis,
75429
+ facetLineCounts: preflight.facetLineCounts,
75430
+ facetUncensused: preflight.facetUncensused,
75431
+ ...savedFilterCurrent ? {
75432
+ dismissibleFacetValues: preflight.dismissed,
75433
+ proofBudget: preflight.budget,
75434
+ forcedRows: preflight.forcedRows,
75435
+ potentialLines: preflight.potentialLines
75436
+ } : {}
75437
+ };
74733
75438
  }
74734
75439
  );
74735
75440
  app.post(
@@ -74744,11 +75449,121 @@ function registerRevisionRoutes(app, deps = {}) {
74744
75449
  return reply.status(410).send({ ok: false, error: "record the initial Filter pre-read on its contract create with X-FloLess-Prepass-Request" });
74745
75450
  }
74746
75451
  );
75452
+ app.post(
75453
+ "/api/projects/:id/revision-requests/:reqId/exclusion-preview",
75454
+ // The body carries EVERY control, because exact coverage of the census is the point — but it never
75455
+ // carries sheets or geometry. Sized from the extractor's own output budget so a maximal ADMITTED
75456
+ // census always arrives and is refused by NAME rather than by an opaque 413 the modal cannot
75457
+ // recover from. See MAX_PREVIEW_BODY_BYTES.
75458
+ { bodyLimit: MAX_PREVIEW_BODY_BYTES },
75459
+ async (req, reply) => {
75460
+ const project = getProject(req.params.id);
75461
+ const request = getRequest(req.params.reqId);
75462
+ if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.appId !== project.app) {
75463
+ return reply.status(404).send({ ok: false, error: "unknown steel revision request" });
75464
+ }
75465
+ if (request.status !== "pending" || !request.prepassReady) {
75466
+ return reply.status(409).send({ ok: false, code: "steel-preview-not-pending", error: "this request is not waiting for a Drawing Filter save" });
75467
+ }
75468
+ const stored2 = readSteelReadManifest(request.id);
75469
+ if (!stored2 || stored2.manifestHash !== request.steelManifestHash || stored2.manifest.projectId !== project.id || stored2.manifest.appId !== project.app) {
75470
+ return reply.status(410).send({ ok: false, code: "steel-manifest-missing", error: "this request no longer has a coherent server-owned steel manifest" });
75471
+ }
75472
+ if (stored2.manifest.censusScope !== "whole-set") {
75473
+ return reply.status(409).send({
75474
+ ok: false,
75475
+ code: "steel-census-scope-missing",
75476
+ error: "regenerate this request's steel manifest before approving the exclusions \u2014 this manifest's census covers only the model sheets"
75477
+ });
75478
+ }
75479
+ const body = req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : null;
75480
+ const bodyKeys = body ? Object.keys(body).sort().join(",") : "";
75481
+ if (!body || bodyKeys !== "colors,layers,mode,thicknesses") {
75482
+ return reply.status(400).send({ ok: false, code: "steel-preview-body-invalid", error: "the preview body must carry exactly mode, layers, thicknesses and colors" });
75483
+ }
75484
+ if (!hasCanonicalMode(body)) {
75485
+ return reply.status(400).send({ ok: false, code: "steel-filter-mode-noncanonical", error: "the preview mode must be a non-empty canonical match-on mode" });
75486
+ }
75487
+ const manifestFilter = stored2.manifest.filter && typeof stored2.manifest.filter === "object" && !Array.isArray(stored2.manifest.filter) ? stored2.manifest.filter : null;
75488
+ if (!manifestFilter) {
75489
+ return reply.status(409).send({ ok: false, code: "steel-manifest-unrepresentable", error: "this manifest records no Drawing Filter to preview against" });
75490
+ }
75491
+ const proposed = { ...manifestFilter, mode: body.mode };
75492
+ for (const dim of MODE_ORDER) {
75493
+ const descriptor = FACET_DIMS[dim];
75494
+ const published = Array.isArray(manifestFilter[descriptor.control]) ? manifestFilter[descriptor.control] : [];
75495
+ const offered = body[descriptor.control];
75496
+ if (!Array.isArray(offered) || offered.length !== published.length) {
75497
+ return reply.status(409).send({
75498
+ ok: false,
75499
+ code: "steel-preview-controls-stale",
75500
+ error: "the controls in this preview are not the ones this drawing scan published \u2014 reload the Drawing Filter and try again",
75501
+ dimension: dim
75502
+ });
75503
+ }
75504
+ const rows2 = [];
75505
+ for (let index = 0; index < offered.length; index += 1) {
75506
+ const row = offered[index];
75507
+ const source = published[index];
75508
+ if (!row || typeof row !== "object" || Array.isArray(row) || !source || typeof source !== "object" || Array.isArray(source)) {
75509
+ return reply.status(409).send({ ok: false, code: "steel-preview-controls-stale", error: "the controls in this preview are not the ones this drawing scan published \u2014 reload the Drawing Filter and try again", dimension: dim });
75510
+ }
75511
+ const entry2 = row;
75512
+ const sourceRow = source;
75513
+ const keys = Object.keys(entry2).sort().join(",");
75514
+ if (keys !== [descriptor.rowKey, "on"].sort().join(",") || typeof entry2.on !== "boolean") {
75515
+ return reply.status(400).send({ ok: false, code: "steel-preview-body-invalid", error: `each ${descriptor.control} control must carry exactly ${descriptor.rowKey} and a true/false on` });
75516
+ }
75517
+ const offeredKey = facetKey(dim, entry2[descriptor.rowKey]);
75518
+ const publishedKey = facetKey(dim, sourceRow[descriptor.rowKey]);
75519
+ if (offeredKey === void 0 || publishedKey === void 0 || offeredKey !== publishedKey) {
75520
+ return reply.status(409).send({ ok: false, code: "steel-preview-controls-stale", error: "the controls in this preview are not the ones this drawing scan published \u2014 reload the Drawing Filter and try again", dimension: dim });
75521
+ }
75522
+ rows2.push({ ...sourceRow, on: entry2.on });
75523
+ }
75524
+ proposed[descriptor.control] = rows2;
75525
+ }
75526
+ const controlsHash = steelFilterControlsHash(proposed);
75527
+ const cacheKey = previewCacheKey(request.id, stored2.manifestHash, controlsHash);
75528
+ const cached = previewCacheGet(cacheKey);
75529
+ if (cached !== void 0) return cached;
75530
+ let preflight;
75531
+ try {
75532
+ preflight = steelExclusionPreflight(sourceLineInventory({
75533
+ pages: stored2.manifest.pages,
75534
+ filter: proposed,
75535
+ inventory: stored2.manifest.candidatesRepr === "v2-compact" ? compactManifestInventory(stored2.manifest.pages) : null
75536
+ }), proposed);
75537
+ } catch (error) {
75538
+ if (!(error instanceof SteelLedgerUnboundError)) throw error;
75539
+ return reply.status(409).send({
75540
+ ok: false,
75541
+ code: "steel-manifest-ledger-unbound",
75542
+ error: "this manifest and its Drawing Filter no longer describe the same drawing set; regenerate this request's steel manifest",
75543
+ samples: error.samples.slice(0, 20)
75544
+ });
75545
+ }
75546
+ const payload = {
75547
+ ok: true,
75548
+ manifestHash: stored2.manifestHash,
75549
+ controlsHash,
75550
+ dismissed: preflight.dismissed,
75551
+ facetLineCounts: preflight.facetLineCounts,
75552
+ // A CEILING, never a promise — a later `member`, `mixed` or absent attestation reduces it. The
75553
+ // modal's copy must say "up to", and this field's name is the reminder.
75554
+ potentialLines: preflight.potentialLines,
75555
+ forcedRows: preflight.forcedRows,
75556
+ proofBudget: preflight.budget
75557
+ };
75558
+ previewCacheSet(cacheKey, payload);
75559
+ return payload;
75560
+ }
75561
+ );
74747
75562
  app.post(
74748
75563
  "/api/projects/:id/revision-requests/:reqId/filter-saved",
74749
- // The approved layer names ride with the Save, so this body is no longer a bare ETag. Sized so a
75564
+ // The approved exclusions ride with the Save, so this body is no longer a bare ETag. Sized so a
74750
75565
  // MAXIMAL LEGAL list still arrives and is refused BY NAME rather than by an opaque 413: 5,000
74751
- // names x 200 characters is ~1 MB of ASCII but up to ~4 MB once the characters are multi-byte and
75566
+ // values x 200 characters is ~1 MB of ASCII but up to ~4 MB once the characters are multi-byte and
74752
75567
  // JSON-escaped, which a 2 MB limit would have cut off at the transport layer.
74753
75568
  { bodyLimit: 8 * 1024 * 1024 },
74754
75569
  async (req, reply) => withLifecycleLock("project", req.params.id, async () => {
@@ -74760,6 +75575,13 @@ function registerRevisionRoutes(app, deps = {}) {
74760
75575
  const etag = typeof req.body?.etag === "string" ? req.body.etag : "";
74761
75576
  const current = readAcceptedForRequest(project.app, project.id, "read");
74762
75577
  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" });
75578
+ if (req.body?.layerSignOff !== void 0) {
75579
+ return reply.status(400).send({
75580
+ ok: false,
75581
+ code: "steel-layer-signoff-retired",
75582
+ error: "layer approvals are retired \u2014 this build records an exclusion approval covering thickness, layer and colour. Reload the Drawing Filter and approve the exclusions it shows."
75583
+ });
75584
+ }
74763
75585
  if (request.steelAuditPolicy === 1) {
74764
75586
  const manifest = readSteelReadManifest(request.id);
74765
75587
  if (!manifest || manifest.manifestHash !== request.steelManifestHash || manifest.manifest.projectId !== project.id || manifest.manifest.appId !== project.app) {
@@ -74773,39 +75595,103 @@ function registerRevisionRoutes(app, deps = {}) {
74773
75595
  error: "every Drawing Filter layer, thickness and colour control must carry an explicit true/false selection"
74774
75596
  });
74775
75597
  }
75598
+ if (!hasWellFormedControlValues(filter)) {
75599
+ return reply.status(409).send({
75600
+ ok: false,
75601
+ code: "steel-filter-control-values-invalid",
75602
+ error: "every Drawing Filter control must carry a value of its own kind \u2014 a layer name as text, a thickness as a number, a colour as text"
75603
+ });
75604
+ }
75605
+ if (!hasCanonicalMode(filter)) {
75606
+ return reply.status(409).send({
75607
+ ok: false,
75608
+ code: "steel-filter-mode-noncanonical",
75609
+ error: "this Drawing Filter's match-on mode is empty or not one this build can read; reopen the Drawing Filter and save it again"
75610
+ });
75611
+ }
74776
75612
  let signOff;
74777
- if (req.body?.layerSignOff !== void 0) {
74778
- const submitted = req.body.layerSignOff?.dismissedLayers;
74779
- if (!req.body.layerSignOff || typeof req.body.layerSignOff !== "object" || Array.isArray(req.body.layerSignOff) || !Array.isArray(submitted) || submitted.length > MAX_SIGNOFF_LAYERS || !submitted.every((name) => typeof name === "string" && name.length > 0 && name.length <= MAX_SIGNOFF_LAYER_NAME)) {
75613
+ if (req.body?.exclusionSignOff !== void 0) {
75614
+ const body = req.body.exclusionSignOff;
75615
+ const submitted = body?.dismissed;
75616
+ const bodyObj = body && typeof body === "object" && !Array.isArray(body) ? body : null;
75617
+ if (!bodyObj || !Array.isArray(submitted)) {
75618
+ return reply.status(400).send({
75619
+ ok: false,
75620
+ code: "steel-exclusion-signoff-invalid",
75621
+ error: "an exclusion approval must list the {dim, value} pairs it displayed, with the mode and the preview hashes it was taken against"
75622
+ });
75623
+ }
75624
+ if (submitted.length > MAX_SIGNOFF_VALUES) {
74780
75625
  return reply.status(400).send({
74781
75626
  ok: false,
74782
- code: "steel-layer-signoff-invalid",
74783
- error: "a layer approval must list the approved layer names it displayed, as a bounded list of non-empty strings"
75627
+ code: "steel-exclusion-signoff-too-many",
75628
+ error: `this approval lists ${submitted.length} excluded values, over the ${MAX_SIGNOFF_VALUES} this read can record. Leave more values switched on in the Drawing Filter \u2014 that both shrinks the list and reduces what would be dismissed without review.`,
75629
+ count: submitted.length,
75630
+ limit: MAX_SIGNOFF_VALUES
75631
+ });
75632
+ }
75633
+ const dims = new Set(MODE_ORDER);
75634
+ const wellFormed = submitted.every((row) => {
75635
+ if (!row || typeof row !== "object" || Array.isArray(row)) return false;
75636
+ const entry2 = row;
75637
+ if (Object.keys(entry2).length !== 2 || typeof entry2.dim !== "string" || !dims.has(entry2.dim)) return false;
75638
+ if (entry2.dim === "thickness") return typeof entry2.value === "number" && Number.isFinite(entry2.value);
75639
+ return typeof entry2.value === "string" && entry2.value.length > 0 && entry2.value.length <= MAX_SIGNOFF_STRING_VALUE;
75640
+ });
75641
+ if (!wellFormed || typeof bodyObj.mode !== "string" || typeof bodyObj.manifestHash !== "string" || typeof bodyObj.controlsHash !== "string") {
75642
+ return reply.status(400).send({
75643
+ ok: false,
75644
+ code: "steel-exclusion-signoff-invalid",
75645
+ error: "an exclusion approval must list the {dim, value} pairs it displayed, with the mode and the preview hashes it was taken against"
74784
75646
  });
74785
75647
  }
74786
75648
  if (manifest.manifest.censusScope !== "whole-set") {
74787
75649
  return reply.status(409).send({
74788
75650
  ok: false,
74789
75651
  code: "steel-census-scope-missing",
74790
- error: "regenerate this request's steel manifest before approving the layer list \u2014 this manifest's layer census covers only the model sheets"
75652
+ error: "regenerate this request's steel manifest before approving the exclusions \u2014 this manifest's census covers only the model sheets"
74791
75653
  });
74792
75654
  }
74793
- if (steelLayerSignOffDigestOfNames(submitted) !== steelLayerSignOffDigest(filter)) {
75655
+ const digest2 = steelExclusionSignOffDigest(filter);
75656
+ if (steelExclusionSignOffDigestOfValues(bodyObj.mode, submitted) !== digest2) {
74794
75657
  return reply.status(409).send({
74795
75658
  ok: false,
74796
- code: "steel-layer-signoff-stale",
74797
- error: "the layer list changed since you approved it \u2014 review the layers and approve the list again"
75659
+ code: "steel-exclusion-signoff-stale",
75660
+ error: "the exclusion list changed since you approved it \u2014 review what this read will dismiss and approve it again"
74798
75661
  });
74799
75662
  }
74800
- signOff = { version: 1, digest: steelLayerSignOffDigest(filter), layerCount: submitted.length, at: (/* @__PURE__ */ new Date()).toISOString() };
75663
+ const controlsHash = steelFilterControlsHash(filter);
75664
+ if (bodyObj.manifestHash !== manifest.manifestHash || bodyObj.controlsHash !== controlsHash) {
75665
+ return reply.status(409).send({
75666
+ ok: false,
75667
+ code: "steel-exclusion-preview-stale",
75668
+ error: "this drawing set was re-scanned while you were reviewing the exclusions \u2014 reload the Drawing Filter and approve them again"
75669
+ });
75670
+ }
75671
+ signOff = {
75672
+ version: 2,
75673
+ basis: "facets/v2",
75674
+ digest: digest2,
75675
+ manifestHash: manifest.manifestHash,
75676
+ controlsHash,
75677
+ valueCount: submitted.length,
75678
+ at: (/* @__PURE__ */ new Date()).toISOString()
75679
+ };
74801
75680
  }
74802
75681
  try {
74803
- const saved = recordSteelFilterSave(request.id, filter, etag, void 0, signOff);
75682
+ const saved = recordSteelFilterSave({ requestId: request.id, filter, etag, expectedManifestHash: manifest.manifestHash, exclusionSignOff: signOff });
74804
75683
  const updated2 = patchRequest(request.id, { filterSaved: true, filterSavedEtag: etag, steelSavedFilterHash: saved.savedFilterHash });
74805
75684
  if (!updated2) return reply.status(409).send({ ok: false, error: "the revision request changed while recording the Filter Save" });
74806
75685
  broadcast({ type: "request-added", request: requestView(updated2) });
74807
75686
  return { ok: true, request: requestView(updated2) };
74808
75687
  } catch (error) {
75688
+ if (error instanceof SteelManifestMovedError) {
75689
+ return reply.status(409).send({
75690
+ ok: false,
75691
+ code: "steel-exclusion-preview-stale",
75692
+ error: "this drawing set was re-scanned while you were reviewing the exclusions \u2014 reload the Drawing Filter and approve them again"
75693
+ });
75694
+ }
74809
75695
  if (!(error instanceof SteelFilterCheckpointRejectedError)) throw error;
74810
75696
  return reply.status(409).send({
74811
75697
  ok: false,
@@ -74815,6 +75701,13 @@ function registerRevisionRoutes(app, deps = {}) {
74815
75701
  });
74816
75702
  }
74817
75703
  }
75704
+ if (req.body?.exclusionSignOff !== void 0) {
75705
+ return reply.status(409).send({
75706
+ ok: false,
75707
+ code: "steel-exclusion-signoff-not-applicable",
75708
+ error: "this request is not governed by the Steel Model completion policy, so an exclusion approval cannot be recorded against it"
75709
+ });
75710
+ }
74818
75711
  const updated = patchRequest(request.id, { filterSaved: true, filterSavedEtag: etag });
74819
75712
  if (!updated) return reply.status(409).send({ ok: false, error: "the revision request changed while recording the Filter Save" });
74820
75713
  broadcast({ type: "request-added", request: requestView(updated) });
@@ -74892,7 +75785,10 @@ function registerRevisionRoutes(app, deps = {}) {
74892
75785
  const alreadyCommitted = listVersions(project.id).find((row) => row.source?.requestId === request.id);
74893
75786
  if (alreadyCommitted) {
74894
75787
  settleCommittedRevisionRequest(request, alreadyCommitted.n, req.log);
74895
- if (request.steelAuditPolicy === 1) dropSteelReadManifest(request.id);
75788
+ if (request.steelAuditPolicy === 1) {
75789
+ dropSteelReadManifest(request.id);
75790
+ dropSteelExclusionPreviewCache(request.id);
75791
+ }
74896
75792
  const snapshot = await readContractSnapshot({ appId: project.app, projectId: project.id });
74897
75793
  if (snapshot) broadcast(contractChangedWithReason(project.app, project.id, snapshot.etag, snapshot.storeRevision, "revision-read"));
74898
75794
  return { ok: true, version: alreadyCommitted, contractType: storedContractType(project.app, project.id) };
@@ -75015,7 +75911,10 @@ function registerRevisionRoutes(app, deps = {}) {
75015
75911
  const version = listVersions(project.id).find((row) => row.n === committed.versionN);
75016
75912
  broadcast(contractChangedWithReason(project.app, project.id, committed.etag, committed.storeRevision, "revision-read"));
75017
75913
  settleCommittedRevisionRequest(request, committed.versionN, req.log);
75018
- if (requiresSteelAudit) dropSteelReadManifest(request.id);
75914
+ if (requiresSteelAudit) {
75915
+ dropSteelReadManifest(request.id);
75916
+ dropSteelExclusionPreviewCache(request.id);
75917
+ }
75019
75918
  return {
75020
75919
  ok: true,
75021
75920
  version,
@@ -75284,7 +76183,10 @@ function registerRevisionRoutes(app, deps = {}) {
75284
76183
  broadcast(contractChangedWithReason(project.app, project.id, committed.etag, committed.storeRevision, "revision-read"));
75285
76184
  if (request.steelAuditPolicy === 1) dropStagingForRequest(stagingKey, request.id);
75286
76185
  else dropStagingFor(stagingKey);
75287
- if (request.steelAuditPolicy === 1) dropSteelReadManifest(request.id);
76186
+ if (request.steelAuditPolicy === 1) {
76187
+ dropSteelReadManifest(request.id);
76188
+ dropSteelExclusionPreviewCache(request.id);
76189
+ }
75288
76190
  settleCommittedRevisionRequest(request, committed.versionN, req.log);
75289
76191
  if (confirmedAudit) logSteelAuditEvent(req.log, {
75290
76192
  phase: "confirm",
@@ -75319,7 +76221,10 @@ function registerRevisionRoutes(app, deps = {}) {
75319
76221
  const key2 = getProjectStagingId(project.id);
75320
76222
  if (key2 && existing.steelAuditPolicy === 1) dropStagingForRequest(key2, existing.id);
75321
76223
  else if (key2 && readStagedRecord(key2)?.requestId === existing.id) dropLegacyStagingFor(key2);
75322
- if (existing.steelAuditPolicy === 1) dropSteelReadManifest(existing.id);
76224
+ if (existing.steelAuditPolicy === 1) {
76225
+ dropSteelReadManifest(existing.id);
76226
+ dropSteelExclusionPreviewCache(existing.id);
76227
+ }
75323
76228
  const request = patchRequest(existing.id, { status: "failed", error });
75324
76229
  broadcast({ type: "request-added", request });
75325
76230
  return { ok: true, request: requestView(request) };
@@ -75707,6 +76612,185 @@ function registerMemberEndRoutes(app) {
75707
76612
  });
75708
76613
  }
75709
76614
 
76615
+ // connection-routes.ts
76616
+ var ConnectionCommandError = class extends Error {
76617
+ constructor(message, code, status) {
76618
+ super(message);
76619
+ this.code = code;
76620
+ this.status = status;
76621
+ this.name = "ConnectionCommandError";
76622
+ }
76623
+ code;
76624
+ status;
76625
+ };
76626
+ function memberIdsOf(value) {
76627
+ if (value === void 0 || value === null) return [];
76628
+ if (!Array.isArray(value)) throw new ConnectionCommandError("memberIds must be an array of member ids", "bad-member-ids", 400);
76629
+ const ids = /* @__PURE__ */ new Set();
76630
+ for (const raw of value) {
76631
+ if (typeof raw !== "string" || !raw) throw new ConnectionCommandError("every member id must be a non-empty string", "bad-member-ids", 400);
76632
+ ids.add(raw);
76633
+ }
76634
+ return [...ids].sort();
76635
+ }
76636
+ function jointOf(value) {
76637
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ConnectionCommandError("joint must be an object", "bad-joint", 400);
76638
+ const joint = value;
76639
+ if (typeof joint.id !== "string" || !joint.id) throw new ConnectionCommandError("joint.id must be a non-empty string", "bad-joint", 400);
76640
+ if (joint.kind !== "custom") throw new ConnectionCommandError("only a custom connection is placed through this command", "not-custom", 422);
76641
+ return joint;
76642
+ }
76643
+ function ifMatchOf2(value) {
76644
+ if (typeof value !== "string" || !value) throw new PreconditionRequiredError("placing a connection requires If-Match from the current contract");
76645
+ return value;
76646
+ }
76647
+ function commandFailure2(reply, error) {
76648
+ if (error instanceof ConnectionCommandError) return reply.status(error.status).send({ ok: false, code: error.code, error: error.message });
76649
+ if (error instanceof ConnectionReviewTransitionError) return reply.status(422).send({ ok: false, code: "placement-refused", error: error.message });
76650
+ if (error instanceof PreconditionRequiredError) return reply.status(428).send({ ok: false, code: error.code, error: error.message });
76651
+ if (error instanceof PreconditionFailedError) return reply.status(412).send({ ok: false, code: error.code, error: "The model changed while this connection was being placed \u2014 it is not being watched." });
76652
+ throw error;
76653
+ }
76654
+ function expectedReviewRevisionOf(value) {
76655
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
76656
+ throw new ConnectionCommandError(
76657
+ "a review action must say which review generation it acted on (reviewRevision)",
76658
+ "review-revision-required",
76659
+ 428
76660
+ );
76661
+ }
76662
+ return value;
76663
+ }
76664
+ async function applyReviewVerb(verb, projectId, jointId, expected, ifMatch) {
76665
+ const project = getProject(projectId);
76666
+ if (!project) throw new ConnectionCommandError(`unknown project: ${projectId}`, "project-not-found", 404);
76667
+ return withLifecycleLock("project", project.id, async () => {
76668
+ const snapshot = await readContractSnapshot({ appId: project.app, projectId: project.id });
76669
+ if (!snapshot) throw new ConnectionCommandError("this project has no model", "contract-not-found", 404);
76670
+ const model = acceptSteelModel(snapshot.contract, { appId: project.app, projectId: project.id });
76671
+ const joint = (model.joints ?? []).find((j) => j && j.id === jointId);
76672
+ if (!joint) throw new ConnectionCommandError(`unknown connection: ${jointId}`, "joint-not-found", 404);
76673
+ if (joint.kind !== "custom") {
76674
+ throw new ConnectionCommandError(`"${jointId}" is a ${joint.kind}, not an imported connection`, "not-custom", 422);
76675
+ }
76676
+ if (verb === "sign-off") {
76677
+ if (!ifMatch) {
76678
+ throw new PreconditionRequiredError("marking a connection reviewed requires If-Match \u2014 the model generation you looked at");
76679
+ }
76680
+ if (ifMatch !== snapshot.etag) {
76681
+ throw new ConnectionCommandError(
76682
+ "the model changed while you were looking at this connection \u2014 reload and check it again before marking it reviewed",
76683
+ "contract-changed",
76684
+ 412
76685
+ );
76686
+ }
76687
+ }
76688
+ const file = readReviewFile(project.id);
76689
+ const membersById = new Map((model.members ?? []).map((m) => [m.id, m]));
76690
+ const row = file.joints[jointId];
76691
+ const next = Object.assign(emptyJoints(), file.joints);
76692
+ let changed = false;
76693
+ if (verb === "sign-off") {
76694
+ const agg = signOffAggregateFor(row, joint, membersById);
76695
+ if (agg === null) {
76696
+ throw new ConnectionCommandError(
76697
+ "this connection is not being watched, so there is nothing to mark as reviewed \u2014 place it again to start watching it",
76698
+ "not-tracked",
76699
+ 422
76700
+ );
76701
+ }
76702
+ if (!row || !("baseline" in row)) throw new ConnectionCommandError("this connection is not being watched", "not-tracked", 422);
76703
+ if (row.signedOff !== agg) {
76704
+ next[jointId] = { baseline: row.baseline, signedOff: agg };
76705
+ changed = true;
76706
+ }
76707
+ } else if (verb === "reopen") {
76708
+ if (row && "baseline" in row && row.signedOff !== void 0) {
76709
+ next[jointId] = { baseline: row.baseline };
76710
+ changed = true;
76711
+ }
76712
+ } else {
76713
+ if (!row || !("untracked" in row)) {
76714
+ next[jointId] = { untracked: "placed-outside-a-placement-command" };
76715
+ changed = true;
76716
+ }
76717
+ }
76718
+ if (!changed) {
76719
+ return { file, summary: connectionReviewSummary(file, model), etag: snapshot.etag, storeRevision: snapshot.storeRevision, changed };
76720
+ }
76721
+ if (file.reviewRevision !== expected) {
76722
+ throw new ConnectionCommandError(
76723
+ "this connection was reviewed somewhere else while you were looking at it \u2014 reload and try again",
76724
+ "review-revision-conflict",
76725
+ 409
76726
+ );
76727
+ }
76728
+ const committed = { version: 1, reviewRevision: file.reviewRevision + 1, joints: next };
76729
+ writeReviewFile(project.id, committed);
76730
+ broadcast(reviewChangedEvent(project.app, project.id, committed.reviewRevision));
76731
+ return {
76732
+ file: committed,
76733
+ summary: connectionReviewSummary(committed, model),
76734
+ etag: snapshot.etag,
76735
+ storeRevision: snapshot.storeRevision,
76736
+ changed
76737
+ };
76738
+ });
76739
+ }
76740
+ function registerReviewVerb(app, verb, path) {
76741
+ app.post(path, async (req, reply) => {
76742
+ try {
76743
+ const expected = expectedReviewRevisionOf(req.body?.reviewRevision);
76744
+ const ifMatch = typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : void 0;
76745
+ const out = await applyReviewVerb(verb, req.params.id, req.params.jointId, expected, ifMatch);
76746
+ return {
76747
+ ok: true,
76748
+ // The contract tag is returned UNCHANGED and is asserted to be so by test: a client that stored it
76749
+ // must be able to keep using it for its next ordinary save.
76750
+ etag: out.etag,
76751
+ storeRevision: out.storeRevision,
76752
+ reviewRevision: out.file.reviewRevision,
76753
+ review: out.summary,
76754
+ changed: out.changed
76755
+ };
76756
+ } catch (error) {
76757
+ return commandFailure2(reply, error);
76758
+ }
76759
+ });
76760
+ }
76761
+ function registerConnectionRoutes(app) {
76762
+ app.post("/api/projects/:id/connections/place", async (req, reply) => {
76763
+ try {
76764
+ const project = getProject(req.params.id);
76765
+ if (!project) throw new ConnectionCommandError(`unknown project: ${req.params.id}`, "project-not-found", 404);
76766
+ const snapshot = await readContractSnapshot({ appId: project.app, projectId: project.id });
76767
+ if (!snapshot) throw new ConnectionCommandError("this project has no model", "contract-not-found", 404);
76768
+ const model = acceptSteelModel(snapshot.contract, { appId: project.app, projectId: project.id });
76769
+ const joint = jointOf(req.body?.joint);
76770
+ const memberIds = memberIdsOf(req.body?.memberIds);
76771
+ const ifMatch = ifMatchOf2(req.headers["if-match"]);
76772
+ const mutationId = typeof req.headers["x-floless-mutation-id"] === "string" ? req.headers["x-floless-mutation-id"] : void 0;
76773
+ const joints = Array.isArray(model.joints) ? model.joints : [];
76774
+ const existing = joints.find((j) => j && j.id === joint.id);
76775
+ if (existing && existing.kind !== "custom") {
76776
+ throw new ConnectionCommandError(`"${joint.id}" is a ${existing.kind}, not an imported connection`, "not-custom", 422);
76777
+ }
76778
+ const next = { ...model, joints: joints.some((j) => j && j.id === joint.id) ? joints.map((j) => j && j.id === joint.id ? joint : j) : [...joints, joint] };
76779
+ const publication = await withLifecycleLock("project", project.id, async () => {
76780
+ const written = await writeConnectionPlacementChecked(project.app, next, project.id, ifMatch, { jointId: joint.id, memberIds });
76781
+ broadcast(contractChangedEvent(project.app, project.id, written.etag, written.storeRevision, mutationId));
76782
+ return written;
76783
+ });
76784
+ return { ok: true, contract: publication.contract, etag: publication.etag, storeRevision: publication.storeRevision, memberIds };
76785
+ } catch (error) {
76786
+ return commandFailure2(reply, error);
76787
+ }
76788
+ });
76789
+ registerReviewVerb(app, "sign-off", "/api/projects/:id/connections/:jointId/sign-off");
76790
+ registerReviewVerb(app, "reopen", "/api/projects/:id/connections/:jointId/reopen");
76791
+ registerReviewVerb(app, "untrack", "/api/projects/:id/connections/:jointId/untrack");
76792
+ }
76793
+
75710
76794
  // steel-intersection-ref.ts
75711
76795
  var label = (v) => {
75712
76796
  if (typeof v !== "string") return null;
@@ -86884,7 +87968,13 @@ function nothingToApprove(contract) {
86884
87968
  // steel-model-score.ts
86885
87969
  var DISSENT_CAP_MIN_CONFIDENCE = 50;
86886
87970
  var norm = {
86887
- profile: (v) => typeof v === "string" ? canonProfile(v) : null,
87971
+ // The CATALOGUE designation on both sides (#860). A drawing marked `W14X26 FLAT` produces an
87972
+ // observation whose observed profile keeps the marker — that is the evidence, and it should keep
87973
+ // saying what the drawing said — while the canonical member is stored `W14X26` with `rot: 90`.
87974
+ // Comparing the raw strings makes 92-confidence evidence CONTRADICT the very member it produced,
87975
+ // capping that member's confidence to null. They are the same section; only the placement differs,
87976
+ // and placement is not what this field is scoring.
87977
+ profile: (v) => typeof v === "string" ? canonProfile(withoutRollMarker(v)) : null,
86888
87978
  // Strip a leading ASTM designation: the spec and the drawing routinely disagree on whether to print it.
86889
87979
  // Shared with the BOM's Grade grouping (`canonMaterial`, beside canonProfile) so a grade this calls
86890
87980
  // "unchanged" can never be a grade the bill splits into two separate buys.
@@ -96319,6 +97409,7 @@ async function startServer() {
96319
97409
  });
96320
97410
  registerRevisionRoutes(app);
96321
97411
  registerMemberEndRoutes(app);
97412
+ registerConnectionRoutes(app);
96322
97413
  registerSteelPrepassRoute(app, { getProject, clearApproval, broadcast });
96323
97414
  registerKnowledgeRoutes(app);
96324
97415
  registerKbPinRoutes(app, { broadcast });
@@ -96961,7 +98052,20 @@ async function startServer() {
96961
98052
  }
96962
98053
  const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "request-body");
96963
98054
  if (!steel.accepted) return reply.status(400).send(steel.refusal);
96964
- return { ok: true, ...contractToScene(steel.doc) };
98055
+ return { ok: true, ...contractToScene(steel.doc, project ? sceneReviewLift(project, steel.doc) : void 0) };
98056
+ }
98057
+ function sceneReviewLift(projectId, doc) {
98058
+ try {
98059
+ const map = connectionReviewSceneMap(readReviewFile(projectId), doc);
98060
+ return map.size ? map : void 0;
98061
+ } catch (e) {
98062
+ console.error("[connection-review] could not build the scene review lift", e, { projectId });
98063
+ try {
98064
+ return connectionReviewUnavailableSceneMap(doc);
98065
+ } catch {
98066
+ return void 0;
98067
+ }
98068
+ }
96965
98069
  }
96966
98070
  app.get("/api/contract/:appId/exports", async (req, reply) => {
96967
98071
  const project = req.query.project;