@floless/app 0.138.0 → 0.138.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61975,40 +61975,46 @@ function componentsOf(intervals) {
61975
61975
  }
61976
61976
  return merged;
61977
61977
  }
61978
- function longestChain(edges, axisCount, unit2) {
61979
- const byPair = /* @__PURE__ */ new Map();
61980
- for (const edge of edges) {
61981
- const key3 = `${edge.i}\0${edge.j}`;
61982
- const held2 = byPair.get(key3);
61983
- if (!held2 || byCodeUnit(edge.textId, held2.textId) < 0) byPair.set(key3, edge);
61984
- }
61985
- const out = /* @__PURE__ */ new Map();
61986
- for (const edge of byPair.values()) {
61987
- const held2 = out.get(edge.i);
61988
- if (held2) held2.push(edge);
61989
- else out.set(edge.i, [edge]);
61990
- }
61991
- const best = [];
61992
- for (let i = axisCount - 1; i >= 0; i--) {
61993
- let winner = { length: 0, to: i, totalMm: 0, members: [] };
61994
- const outgoing = [...out.get(i) ?? []].sort((a, b) => a.j - b.j || byCodeUnit(a.textId, b.textId));
61995
- for (const edge of outgoing) {
61996
- const next = best[edge.j] ?? { length: 0, to: edge.j, totalMm: 0, members: [] };
61997
- const length2 = 1 + next.length;
61998
- if (length2 > winner.length) {
61999
- winner = { length: length2, to: next.to, totalMm: mmUnder(edge, unit2) + next.totalMm, members: [edge, ...next.members] };
62000
- }
61978
+ function rowsOfTexts(texts) {
61979
+ const sorted = [...texts].sort((a, b) => a.acrossPt - b.acrossPt || byCodeUnit(a.textId, b.textId));
61980
+ const rows2 = [];
61981
+ let current = [];
61982
+ let anchor = 0;
61983
+ for (const text6 of sorted) {
61984
+ if (!current.length) {
61985
+ current = [text6];
61986
+ anchor = text6.acrossPt;
61987
+ continue;
61988
+ }
61989
+ if (text6.acrossPt - anchor <= ROW_TOL_PT) current.push(text6);
61990
+ else {
61991
+ rows2.push(current);
61992
+ current = [text6];
61993
+ anchor = text6.acrossPt;
62001
61994
  }
62002
- best[i] = winner;
62003
61995
  }
62004
- let overall = null;
62005
- for (let i = 0; i < axisCount; i++) {
62006
- const held2 = best[i];
62007
- if (held2.length >= MIN_CHAIN && (!overall || held2.length > overall.length)) {
62008
- overall = { length: held2.length, from: i, to: held2.to, totalMm: held2.totalMm, members: held2.members };
61996
+ if (current.length) rows2.push(current);
61997
+ for (const row of rows2) row.sort((a, b) => a.alongPt - b.alongPt || byCodeUnit(a.textId, b.textId));
61998
+ return rows2;
61999
+ }
62000
+ function tilingRuns(row, selected, familyId) {
62001
+ const runs = [];
62002
+ let current = [];
62003
+ const flush = () => {
62004
+ if (current.length >= MIN_CHAIN) runs.push(current);
62005
+ current = [];
62006
+ };
62007
+ for (const text6 of row) {
62008
+ const hypothesis = selected.get(text6.textId);
62009
+ if (!hypothesis || hypothesis.familyId !== familyId) {
62010
+ flush();
62011
+ continue;
62009
62012
  }
62013
+ if (current.length && current[current.length - 1].j !== hypothesis.i) flush();
62014
+ current.push(hypothesis);
62010
62015
  }
62011
- return overall;
62016
+ flush();
62017
+ return runs.sort((a, b) => b.length - a.length || a[0].i - b[0].i || byCodeUnit(a[0].textId, b[0].textId));
62012
62018
  }
62013
62019
  function buildCandidate(args) {
62014
62020
  const { component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed } = args;
@@ -62040,36 +62046,92 @@ function buildCandidate(args) {
62040
62046
  const anchorElementIds = [];
62041
62047
  let implausible = false;
62042
62048
  for (const { family, axes } of ordered) {
62043
- const mine = [...refined.values()].filter((h) => h.familyId === family.familyId);
62044
- if (!mine.length) continue;
62045
- const chain2 = longestChain(mine, axes.length, unit2);
62046
- if (!chain2) continue;
62047
- const memberSpansMm = chain2.members.map((h) => mmUnder(h, unit2));
62048
- if (memberSpansMm.some((mm3) => mm3 < MIN_BAY_MM || mm3 > MAX_BAY_MM)) {
62049
- implausible = true;
62049
+ const seats = args.familyTexts.get(family.familyId) ?? EMPTY_SEATING;
62050
+ if (!seats.seats.length) continue;
62051
+ let chain2 = null;
62052
+ let sawImplausible = false;
62053
+ let trims = 0;
62054
+ const longestFirst = (a, b) => b.length - a.length || a[0].i - b[0].i || byCodeUnit(a[0].textId, b[0].textId);
62055
+ for (const row of seats.rows) {
62056
+ const queue = tilingRuns(row, refined, family.familyId);
62057
+ while (queue.length) {
62058
+ const members = queue.shift();
62059
+ const fromPt2 = axes[members[0].i].atRaw;
62060
+ const toPt2 = axes[members[members.length - 1].j].atRaw;
62061
+ const used = new Set(members.map((m) => m.textId));
62062
+ let acrossLo = Infinity;
62063
+ let acrossHi = -Infinity;
62064
+ for (const m of members) {
62065
+ const seat2 = seats.byId.get(m.textId);
62066
+ acrossLo = Math.min(acrossLo, seat2.acrossPt);
62067
+ acrossHi = Math.max(acrossHi, seat2.acrossPt);
62068
+ }
62069
+ let barrier = null;
62070
+ for (const seat2 of seats.seats) {
62071
+ if (used.has(seat2.textId)) continue;
62072
+ if (!(seat2.alongPt > fromPt2 && seat2.alongPt < toPt2)) continue;
62073
+ if (!(seat2.acrossPt > acrossLo - BARRIER_TOL_PT && seat2.acrossPt < acrossHi + BARRIER_TOL_PT)) continue;
62074
+ if (!barrier || seat2.alongPt < barrier.alongPt || seat2.alongPt === barrier.alongPt && byCodeUnit(seat2.textId, barrier.textId) < 0) barrier = seat2;
62075
+ }
62076
+ if (!barrier) {
62077
+ if (members.some((m) => {
62078
+ const mm3 = mmUnder(m, unit2);
62079
+ return mm3 < MIN_BAY_MM || mm3 > MAX_BAY_MM;
62080
+ })) {
62081
+ sawImplausible = true;
62082
+ continue;
62083
+ }
62084
+ const totalMm = members.reduce((sum2, m) => sum2 + mmUnder(m, unit2), 0);
62085
+ const found = { from: members[0].i, to: members[members.length - 1].j, totalMm, members };
62086
+ if (!chain2 || found.members.length > chain2.members.length) chain2 = found;
62087
+ break;
62088
+ }
62089
+ if (trims >= MAX_RUN_TRIMS) continue;
62090
+ trims += 1;
62091
+ const at = barrier.alongPt;
62092
+ for (const half of [
62093
+ members.filter((m) => axes[m.j].atRaw <= at),
62094
+ members.filter((m) => axes[m.i].atRaw >= at)
62095
+ ]) {
62096
+ if (half.length >= MIN_CHAIN) queue.push(half);
62097
+ }
62098
+ queue.sort(longestFirst);
62099
+ }
62100
+ }
62101
+ if (!chain2) {
62102
+ implausible = implausible || sawImplausible;
62050
62103
  continue;
62051
62104
  }
62105
+ const memberSpansMm = chain2.members.map((h) => mmUnder(h, unit2));
62052
62106
  const fromLabel = axes[chain2.from].label;
62053
62107
  const toLabel = axes[chain2.to].label;
62054
62108
  if (!usableLabel(fromLabel) || !usableLabel(toLabel)) continue;
62055
- const runPt = axes[chain2.to].atRaw - axes[chain2.from].atRaw;
62109
+ const fromPt = axes[chain2.from].atRaw;
62110
+ const toPt = axes[chain2.to].atRaw;
62111
+ const runPt = toPt - fromPt;
62112
+ const memberIds = new Set(chain2.members.map((m) => m.textId));
62113
+ const centreAllowance = Math.max(runPt * ANCHOR_CENTRE_FRAC, ANCHOR_CENTRE_MIN_PT);
62114
+ const seatOf = seats.byId;
62056
62115
  const anchor = printed.filter((p) => {
62057
62116
  const mm3 = p.explicitUnit === "mm" ? p.magnitude : p.magnitude * (unit2 === "cm" ? 10 : 1);
62058
- return mm3 === chain2.totalMm && Math.abs(mm3 / mmPerPx - runPt) <= METRIC_INLIER_TOL_PT;
62117
+ if (mm3 !== chain2.totalMm || Math.abs(mm3 / mmPerPx - runPt) > METRIC_INLIER_TOL_PT) return false;
62118
+ if (memberIds.has(p.id)) return false;
62119
+ const seat2 = seatOf.get(p.id);
62120
+ return !!seat2 && Math.abs(seat2.alongPt - (fromPt + toPt) / 2) <= centreAllowance;
62059
62121
  }).sort((a, b) => byCodeUnit(a.id, b.id))[0] ?? null;
62060
62122
  if (anchor) anchorElementIds.push(anchor.id);
62061
62123
  const evidence = {
62062
62124
  familyId: family.familyId,
62063
62125
  fromLabel,
62064
62126
  toLabel,
62065
- length: chain2.length,
62127
+ length: chain2.members.length,
62066
62128
  worldTotalMm: chain2.totalMm,
62067
62129
  anchoredByOverall: anchor !== null,
62068
62130
  anchorElementId: anchor ? anchor.id : null,
62069
62131
  memberSpansMm: memberSpansMm.slice(0, MAX_CHAIN_MEMBERS)
62070
62132
  };
62071
- if (family.axis === "x" && (!chains.x || chain2.length > chains.x.length)) chains.x = evidence;
62072
- if (family.axis === "y" && (!chains.y || chain2.length > chains.y.length)) chains.y = evidence;
62133
+ if (family.axis === "x" && (!chains.x || evidence.length > chains.x.length)) chains.x = evidence;
62134
+ if (family.axis === "y" && (!chains.y || evidence.length > chains.y.length)) chains.y = evidence;
62073
62135
  }
62074
62136
  if (!chains.x && !chains.y) return implausible ? "span-implausible" : "no-chain";
62075
62137
  return {
@@ -62105,10 +62167,10 @@ function selectPerText(hypotheses, unit2, mmPerPx) {
62105
62167
  return out;
62106
62168
  }
62107
62169
  function rankSurvivors(a, b) {
62108
- return anchoredRank(b) - anchoredRank(a) || weakerChain(b) - weakerChain(a) || strongerChain(b) - strongerChain(a) || b.candidate.stringsExplained - a.candidate.stringsExplained || a.rawResidual - b.rawResidual || byCodeUnit(survivorIdentity(a), survivorIdentity(b));
62170
+ return weakerChain(b) - weakerChain(a) || strongerChain(b) - strongerChain(a) || b.candidate.stringsExplained - a.candidate.stringsExplained || a.rawResidual - b.rawResidual || byCodeUnit(survivorIdentity(a), survivorIdentity(b));
62109
62171
  }
62110
62172
  function separatesSurvivors(a, b) {
62111
- return anchoredRank(a) !== anchoredRank(b) || weakerChain(a) !== weakerChain(b) || strongerChain(a) !== strongerChain(b) || a.candidate.stringsExplained !== b.candidate.stringsExplained || a.rawResidual !== b.rawResidual;
62173
+ return weakerChain(a) !== weakerChain(b) || strongerChain(a) !== strongerChain(b) || a.candidate.stringsExplained !== b.candidate.stringsExplained || a.rawResidual !== b.rawResidual;
62112
62174
  }
62113
62175
  function fitMetricScale(input) {
62114
62176
  const empty = { leader: null, runnersUp: [], tied: [], hypothesesConsidered: 0 };
@@ -62165,6 +62227,26 @@ function fitMetricScale(input) {
62165
62227
  if (!hypotheses.length) {
62166
62228
  return { ...empty, refusal: { code: "out-of-band", detail: "no metric dimension string could be matched to any axis pair in this scope" } };
62167
62229
  }
62230
+ const familyTexts = /* @__PURE__ */ new Map();
62231
+ for (const { family, axes } of ordered) {
62232
+ const along = family.axis === "x" ? 0 : 1;
62233
+ const across = along === 0 ? 1 : 0;
62234
+ const lo = axes[0].atRaw;
62235
+ const hi = axes[axes.length - 1].atRaw;
62236
+ const seats = [];
62237
+ for (const token2 of tokens) {
62238
+ const acrossPt = token2.centre[across] - family.at;
62239
+ if (Math.abs(acrossPt) > METRIC_MAX_ACROSS_PT) continue;
62240
+ const alongPt = token2.centre[along];
62241
+ if (alongPt < lo - 2 || alongPt > hi + 2) continue;
62242
+ seats.push({ textId: token2.id, acrossPt, alongPt });
62243
+ }
62244
+ familyTexts.set(family.familyId, {
62245
+ seats,
62246
+ rows: rowsOfTexts(seats),
62247
+ byId: new Map(seats.map((seat2) => [seat2.textId, seat2]))
62248
+ });
62249
+ }
62168
62250
  const printed = tokens.map((t) => ({ id: t.id, magnitude: t.parsed.magnitude, explicitUnit: t.parsed.explicitUnit }));
62169
62251
  const survivors = [];
62170
62252
  let overflowed = false;
@@ -62195,7 +62277,7 @@ function fitMetricScale(input) {
62195
62277
  components.sort((a, b) => b.distinct - a.distinct || a.start - b.start);
62196
62278
  const perReading = [];
62197
62279
  components.forEach((component, componentIndex) => {
62198
- const built = buildCandidate({ component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed });
62280
+ const built = buildCandidate({ component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed, familyTexts });
62199
62281
  if (built === "span-implausible") {
62200
62282
  spanRejected = true;
62201
62283
  return;
@@ -62252,7 +62334,7 @@ function fitMetricScale(input) {
62252
62334
  hypothesesConsidered: hypotheses.length
62253
62335
  };
62254
62336
  }
62255
- var METRIC_INLIER_TOL_PT, METRIC_MIN_INLIERS, METRIC_MIN_SPAN_PT, METRIC_MAX_ACROSS_PT, MAX_PLOT_SCALING, MIN_BAY_MM, MAX_BAY_MM, MAX_METRIC_RATIOS, MAX_RETAINED_COMPONENTS, MAX_METRIC_CANDIDATES, METRIC_UNITS_PER_RATIO, MAX_CHAIN_MEMBERS, MIN_CHAIN, MAX_AXIS_LABEL_CHARS, METRIC_MAX_AXES_PER_FAMILY, METRIC_MAX_HYPOTHESES, METRIC_RATIOS, PT_PER_INCH, MM_PER_PT_AT_1_TO_1, nominalMmPerPx, centreOf2, finite3, round6, mmUnder, usableLabel, anchoredRank, weakerChain, strongerChain, survivorIdentity;
62337
+ var METRIC_INLIER_TOL_PT, METRIC_MIN_INLIERS, METRIC_MIN_SPAN_PT, METRIC_MAX_ACROSS_PT, ROW_TOL_PT, BARRIER_TOL_PT, ANCHOR_CENTRE_FRAC, ANCHOR_CENTRE_MIN_PT, MAX_RUN_TRIMS, MAX_PLOT_SCALING, MIN_BAY_MM, MAX_BAY_MM, MAX_METRIC_RATIOS, MAX_RETAINED_COMPONENTS, MAX_METRIC_CANDIDATES, METRIC_UNITS_PER_RATIO, MAX_CHAIN_MEMBERS, MIN_CHAIN, MAX_AXIS_LABEL_CHARS, METRIC_MAX_AXES_PER_FAMILY, METRIC_MAX_HYPOTHESES, METRIC_RATIOS, PT_PER_INCH, MM_PER_PT_AT_1_TO_1, nominalMmPerPx, centreOf2, finite3, round6, mmUnder, usableLabel, EMPTY_SEATING, weakerChain, strongerChain, survivorIdentity;
62256
62338
  var init_steel_scale_metric = __esm({
62257
62339
  "steel-scale-metric.ts"() {
62258
62340
  "use strict";
@@ -62262,6 +62344,11 @@ var init_steel_scale_metric = __esm({
62262
62344
  METRIC_MIN_INLIERS = 3;
62263
62345
  METRIC_MIN_SPAN_PT = 5;
62264
62346
  METRIC_MAX_ACROSS_PT = 200;
62347
+ ROW_TOL_PT = 3;
62348
+ BARRIER_TOL_PT = 8;
62349
+ ANCHOR_CENTRE_FRAC = 0.05;
62350
+ ANCHOR_CENTRE_MIN_PT = 6;
62351
+ MAX_RUN_TRIMS = 64;
62265
62352
  MAX_PLOT_SCALING = 1.33;
62266
62353
  MIN_BAY_MM = 1500;
62267
62354
  MAX_BAY_MM = 3e4;
@@ -62283,7 +62370,7 @@ var init_steel_scale_metric = __esm({
62283
62370
  round6 = (n) => Number(n.toFixed(6));
62284
62371
  mmUnder = (h, unit2) => h.explicitUnit === "mm" ? h.magnitude : h.magnitude * (unit2 === "cm" ? 10 : 1);
62285
62372
  usableLabel = (label2) => typeof label2 === "string" && label2.length > 0 && label2.length <= MAX_AXIS_LABEL_CHARS;
62286
- anchoredRank = (s) => s.chains.x?.anchoredByOverall || s.chains.y?.anchoredByOverall ? 1 : 0;
62373
+ EMPTY_SEATING = Object.freeze({ seats: [], rows: [], byId: /* @__PURE__ */ new Map() });
62287
62374
  weakerChain = (s) => Math.min(s.candidate.chainX, s.candidate.chainY);
62288
62375
  strongerChain = (s) => Math.max(s.candidate.chainX, s.candidate.chainY);
62289
62376
  survivorIdentity = (s) => `${s.candidate.standard} ${s.candidate.unit} ${String(s.candidate.componentIndex).padStart(4, "0")}`;
@@ -62738,20 +62825,18 @@ function proposeOne(elements, identity, declaredGrammar, spent, environment, det
62738
62825
  });
62739
62826
  const relevant = elements.filter((e) => e.kind === "circle" || e.kind === "text");
62740
62827
  const anonymous = relevant.filter((e) => !usableId(e.elementId)).length;
62741
- if (grammar === "ambiguous" && anonymous > 0) return grammarAmbiguous();
62742
- if (anonymous > 0) {
62828
+ const repeated = relevant.length - new Set(relevant.map((e) => e.elementId)).size;
62829
+ const unidentified = anonymous + repeated;
62830
+ if (grammar === "ambiguous" && unidentified > 0) return grammarAmbiguous();
62831
+ if (unidentified > 0) {
62832
+ const detail = anonymous > 0 ? `${anonymous} of this sheet's ${relevant.length} grid and text elements carry no usable element id, so no fit over them would describe the sheet` : `${repeated} of this sheet's ${relevant.length} grid and text elements repeat another element's id, so a fit over them would silently merge distinct dimensions`;
62743
62833
  return {
62744
62834
  spent,
62745
62835
  proposal: {
62746
62836
  ...head,
62747
62837
  grammar: reported,
62748
62838
  grammarBasis,
62749
- outcome: ask(
62750
- "missing-element-identities",
62751
- `${anonymous} of this sheet's ${relevant.length} grid and text elements carry no usable element id, so no fit over them would describe the sheet`,
62752
- [],
62753
- null
62754
- )
62839
+ outcome: ask("missing-element-identities", detail, [], null)
62755
62840
  }
62756
62841
  };
62757
62842
  }
@@ -63475,6 +63560,44 @@ function steelReadRequestStoreKey(requestId) {
63475
63560
  function root3() {
63476
63561
  return (0, import_node_path19.join)(process.env.FLOLESS_HOME ?? (0, import_node_path19.join)((0, import_node_os16.homedir)(), ".floless"), ".steel-read-manifests");
63477
63562
  }
63563
+ function validInspection2(value) {
63564
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
63565
+ const row = value;
63566
+ if (!onlyKeys3(row, /* @__PURE__ */ new Set(["version", "requestId", "projectId", "appId", "baseVersion", "extractorVersion", "sources", "pages"]))) return false;
63567
+ if (row.version !== 1 || !isPersistedRequestId(row.requestId) || !safeText(row.projectId, 256) || !safeText(row.appId, 256) || !Number.isSafeInteger(row.baseVersion) || Number(row.baseVersion) < 0 || !safeText(row.extractorVersion, 128) || !Array.isArray(row.sources) || !Array.isArray(row.pages) || row.sources.length < 1 || row.sources.length > STEEL_READ_MAX_SOURCES || row.pages.length < 1 || row.pages.length > STEEL_READ_MAX_PAGES) return false;
63568
+ const sourceHashes = /* @__PURE__ */ new Set();
63569
+ for (const source of row.sources) {
63570
+ if (!source || typeof source !== "object" || Array.isArray(source) || !onlyKeys3(source, /* @__PURE__ */ new Set(["name", "sha256", "ext", "bytes"])) || !safeText(source.name, 512) || typeof source.sha256 !== "string" || !SHA2562.test(source.sha256) || !safeText(source.ext, 32) || !Number.isSafeInteger(source.bytes) || source.bytes < 0 || sourceHashes.has(source.sha256)) return false;
63571
+ sourceHashes.add(source.sha256);
63572
+ }
63573
+ const pageIds = /* @__PURE__ */ new Set();
63574
+ for (const page of row.pages) {
63575
+ if (!page || typeof page !== "object" || Array.isArray(page) || !onlyKeys3(page, /* @__PURE__ */ new Set(["id", "sourceHash", "page", "bounds", "sheetCandidates", "trustedSheetCandidate", "title", "suggestedTitle", "evidenceKind", "streamBytes"])) || typeof page.id !== "string" || !SHA2562.test(page.id) || typeof page.sourceHash !== "string" || !sourceHashes.has(page.sourceHash) || !Number.isSafeInteger(page.page) || page.page < 1 || !Array.isArray(page.bounds) || page.bounds.length !== 4 || !page.bounds.every(finite5) || page.bounds[2] < page.bounds[0] || page.bounds[3] < page.bounds[1] || !Array.isArray(page.sheetCandidates) || page.sheetCandidates.length > 20 || !page.sheetCandidates.every((candidate2) => safeText(candidate2, 40)) || page.trustedSheetCandidate !== void 0 && !safeText(page.trustedSheetCandidate, 40) || page.title !== void 0 && !safeText(page.title, 160) || page.suggestedTitle !== void 0 && !safeText(page.suggestedTitle, 160) || !STEEL_EVIDENCE_KINDS.has(page.evidenceKind) || page.streamBytes !== void 0 && (!Number.isSafeInteger(page.streamBytes) || page.streamBytes < 0) || pageIds.has(page.id)) return false;
63576
+ pageIds.add(page.id);
63577
+ }
63578
+ return true;
63579
+ }
63580
+ function writeSteelPageInspection(value, now2 = (/* @__PURE__ */ new Date()).toISOString()) {
63581
+ if (!validInspection2(value)) throw new SteelReadManifestInvalidError("steel page inspection is invalid");
63582
+ const stored2 = { ...value, createdAt: now2, contentHash: hashOf(value) };
63583
+ writeRecord(inspectionPath(value.requestId), `${canonicalJson(stored2)}
63584
+ `);
63585
+ }
63586
+ function readSteelPageInspection(requestId) {
63587
+ try {
63588
+ const path = inspectionPath(requestId);
63589
+ if (!(0, import_node_fs23.existsSync)(path)) return null;
63590
+ const stored2 = JSON.parse((0, import_node_fs23.readFileSync)(path, "utf8"));
63591
+ const { createdAt, contentHash: contentHash2, ...value } = stored2;
63592
+ if (typeof createdAt !== "string" || typeof contentHash2 !== "string" || !SHA2562.test(contentHash2) || !validInspection2(value) || hashOf(value) !== contentHash2) return null;
63593
+ return value;
63594
+ } catch {
63595
+ return null;
63596
+ }
63597
+ }
63598
+ function steelPageInspectionMatches(value, expected) {
63599
+ return value.requestId === expected.requestId && value.projectId === expected.projectId && value.appId === expected.appId && value.baseVersion === expected.baseVersion && value.extractorVersion === expected.extractorVersion && hashOf(value.sources) === hashOf(expected.sources);
63600
+ }
63478
63601
  function isRecord(value) {
63479
63602
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
63480
63603
  const row = value;
@@ -63613,13 +63736,20 @@ function dropSteelReadManifest(requestId) {
63613
63736
  (0, import_node_fs23.rmSync)(recordPath(requestId), { force: true });
63614
63737
  } catch {
63615
63738
  }
63739
+ try {
63740
+ (0, import_node_fs23.rmSync)(inspectionPath(requestId), { force: true });
63741
+ } catch {
63742
+ }
63616
63743
  }
63617
63744
  function removeSteelReadManifest(requestId, remove = (path) => (0, import_node_fs23.rmSync)(path, { force: true })) {
63618
63745
  const path = recordPath(requestId);
63746
+ const inspected = inspectionPath(requestId);
63619
63747
  remove(path);
63748
+ remove(inspected);
63620
63749
  if ((0, import_node_fs23.existsSync)(path)) throw new Error("the discarded steel-read manifest is still present");
63750
+ if ((0, import_node_fs23.existsSync)(inspected)) throw new Error("the discarded steel-read inspection is still present");
63621
63751
  }
63622
- var import_node_crypto16, import_node_fs23, import_node_os16, import_node_path19, STEEL_FILTER_EXTRACTOR_VERSION, STEEL_READ_MAX_SOURCES, STEEL_READ_MAX_PAGES, STEEL_READ_MAX_PAGE_ELEMENTS, STEEL_READ_MAX_TOTAL_ELEMENTS, STEEL_EXCLUSION_SIGNOFF_DOMAIN, STEEL_FILTER_CONTROLS_DOMAIN, UUID, SHA2562, SERVER_ELEMENT_ID2, hasExactKeys, hasOnlyKeys2, recordPath, SteelFilterCheckpointRejectedError, SteelReadManifestInvalidError, SteelReadPageBudgetError, SteelManifestMovedError, SteelSetKnowledgeRejectedError, SteelReadManifestUnavailableError;
63752
+ var import_node_crypto16, import_node_fs23, import_node_os16, import_node_path19, STEEL_FILTER_EXTRACTOR_VERSION, STEEL_READ_MAX_SOURCES, STEEL_READ_MAX_PAGES, STEEL_READ_MAX_PAGE_ELEMENTS, STEEL_READ_MAX_TOTAL_ELEMENTS, STEEL_EXCLUSION_SIGNOFF_DOMAIN, STEEL_FILTER_CONTROLS_DOMAIN, UUID, SHA2562, SERVER_ELEMENT_ID2, hasExactKeys, hasOnlyKeys2, recordPath, inspectionPath, finite5, safeText, onlyKeys3, SteelFilterCheckpointRejectedError, SteelReadManifestInvalidError, SteelReadPageBudgetError, SteelManifestMovedError, SteelSetKnowledgeRejectedError, SteelReadManifestUnavailableError;
63623
63753
  var init_steel_read_manifest = __esm({
63624
63754
  "steel-read-manifest.ts"() {
63625
63755
  "use strict";
@@ -63652,6 +63782,10 @@ var init_steel_read_manifest = __esm({
63652
63782
  return required.every((key3) => Object.prototype.hasOwnProperty.call(value, key3)) && Object.keys(value).every((key3) => allowed.has(key3));
63653
63783
  };
63654
63784
  recordPath = (requestId) => (0, import_node_path19.join)(root3(), `${steelReadRequestStoreKey(requestId)}.json`);
63785
+ inspectionPath = (requestId) => (0, import_node_path19.join)(root3(), `${steelReadRequestStoreKey(requestId)}.inspection.json`);
63786
+ finite5 = (value) => typeof value === "number" && Number.isFinite(value);
63787
+ safeText = (value, max2 = 160) => typeof value === "string" && value.length > 0 && value.length <= max2;
63788
+ onlyKeys3 = (value, allowed) => Object.keys(value).every((key3) => allowed.has(key3));
63655
63789
  SteelFilterCheckpointRejectedError = class extends Error {
63656
63790
  constructor(message) {
63657
63791
  super(message);
@@ -64312,9 +64446,6 @@ function currentSteelFilterResult(value) {
64312
64446
  }
64313
64447
  return value;
64314
64448
  }
64315
- function steelInspectionTimeoutMs(sourceCount, sourceBytes) {
64316
- return clamp2(6e4, 3e4 + 1e4 * sourceCount + 5e3 * Math.ceil(sourceBytes / MIB), 12e4);
64317
- }
64318
64449
  function steelStreamBytesOf(pages) {
64319
64450
  let total = 0;
64320
64451
  for (const page of pages) {
@@ -75460,8 +75591,8 @@ function evaluateSteelRead(context) {
75460
75591
  continue;
75461
75592
  }
75462
75593
  for (const fact of evidence.facts) {
75463
- const finite5 = Number.isFinite(fact.actualMm) && Number.isFinite(fact.limitMm) && Number.isFinite(fact.toleranceMm);
75464
- const passes = finite5 && (fact.relation === "equal" ? Math.abs(fact.actualMm - fact.limitMm) <= fact.toleranceMm : fact.relation === "at-least" ? fact.actualMm + fact.toleranceMm >= fact.limitMm : fact.actualMm - fact.toleranceMm <= fact.limitMm);
75594
+ const finite6 = Number.isFinite(fact.actualMm) && Number.isFinite(fact.limitMm) && Number.isFinite(fact.toleranceMm);
75595
+ const passes = finite6 && (fact.relation === "equal" ? Math.abs(fact.actualMm - fact.limitMm) <= fact.toleranceMm : fact.relation === "at-least" ? fact.actualMm + fact.toleranceMm >= fact.limitMm : fact.actualMm - fact.toleranceMm <= fact.limitMm);
75465
75596
  if (!passes) {
75466
75597
  fitFailures.push(`${joint.id}:${fact.id}:${fact.actualMm}:${fact.relation}:${fact.limitMm}`);
75467
75598
  fitFaults.push({ jointId: joint.id, factId: fact.id, fault: `${fact.id} measured ${fact.actualMm} against ${fact.relation} ${fact.limitMm}` });
@@ -83415,7 +83546,7 @@ function appVersion() {
83415
83546
  return resolveVersion({
83416
83547
  isSea: isSea2(),
83417
83548
  sqVersionXml: readSqVersionXml(),
83418
- define: true ? "0.138.0" : void 0,
83549
+ define: true ? "0.138.1" : void 0,
83419
83550
  pkgVersion: readPkgVersion()
83420
83551
  });
83421
83552
  }
@@ -83431,7 +83562,7 @@ function resolveChannel(s) {
83431
83562
  function appChannel() {
83432
83563
  return resolveChannel({
83433
83564
  isSea: isSea2(),
83434
- define: true ? "0.138.0" : void 0,
83565
+ define: true ? "0.138.1" : void 0,
83435
83566
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
83436
83567
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
83437
83568
  modulePath: process.argv[1]
@@ -86121,6 +86252,14 @@ function steelPreparationTimeoutWhy(req) {
86121
86252
  if (!detail || typeof detail.diagnosticId !== "string" || !/^[0-9a-f-]{36}$/i.test(detail.diagnosticId) || !["inspection", "evidence", "model"].includes(detail.phase) || !Number.isSafeInteger(detail.elapsedMs) || detail.elapsedMs < 0 || !Number.isSafeInteger(detail.timeoutMs) || detail.timeoutMs < 0 || !Number.isSafeInteger(detail.workload?.sourceCount) || detail.workload.sourceCount < 0) return base;
86122
86253
  return `${base} Diagnostic ${detail.diagnosticId}; ${detail.phase} phase; ${detail.elapsedMs} ms of ${detail.timeoutMs} ms; ${detail.workload.sourceCount} source(s).`;
86123
86254
  }
86255
+ function hasRetryableInspectionRefusal(req) {
86256
+ const authorities = [
86257
+ ...req.refusalCode === "steel-manifest-extraction-timeout" ? [req.steelPreparationTimeout] : [],
86258
+ ...req.run?.refusalCode === "steel-manifest-extraction-timeout" ? [req.run.steelPreparationTimeout] : []
86259
+ ];
86260
+ const nonNegativeIntegerOrNull = (value) => value === null || Number.isSafeInteger(value) && Number(value) >= 0;
86261
+ return authorities.length > 0 && authorities.every((detail) => detail !== void 0 && detail !== null && typeof detail === "object" && !Array.isArray(detail) && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(detail.diagnosticId) && detail.phase === "inspection" && Number.isSafeInteger(detail.elapsedMs) && detail.elapsedMs >= 0 && Number.isSafeInteger(detail.timeoutMs) && detail.timeoutMs >= 0 && Number.isSafeInteger(detail.workload?.sourceCount) && detail.workload.sourceCount >= 0 && Number.isSafeInteger(detail.workload?.sourceBytes) && detail.workload.sourceBytes >= 0 && nonNegativeIntegerOrNull(detail.workload?.totalPageCount) && nonNegativeIntegerOrNull(detail.workload?.selectedPageCount));
86262
+ }
86124
86263
  function runEligibilityFor(req) {
86125
86264
  const policy = policyFor(req.type);
86126
86265
  if (!policy.runnable) return policy;
@@ -86128,7 +86267,8 @@ function runEligibilityFor(req) {
86128
86267
  return { runnable: false, why: "workflow tours are conversations \u2014 use Copy to continue in your terminal" };
86129
86268
  }
86130
86269
  if (req.type !== "revision-read") return { runnable: true, policy };
86131
- if (req.refusalCode === "steel-manifest-extraction-timeout" || req.run?.refusalCode === "steel-manifest-extraction-timeout") {
86270
+ const retryableInspection = hasRetryableInspectionRefusal(req);
86271
+ if (!retryableInspection && (req.refusalCode === "steel-manifest-extraction-timeout" || req.run?.refusalCode === "steel-manifest-extraction-timeout")) {
86132
86272
  return {
86133
86273
  runnable: false,
86134
86274
  why: steelPreparationTimeoutWhy(req)
@@ -86140,10 +86280,10 @@ function runEligibilityFor(req) {
86140
86280
  if (req.status === "staged") {
86141
86281
  return { runnable: false, why: "this drawing read is complete and waiting for review in Drawing Filter" };
86142
86282
  }
86143
- if (req.status === "failed") {
86283
+ if (req.status === "failed" && !retryableInspection) {
86144
86284
  return { runnable: false, why: "this drawing read failed \u2014 attach the drawing set again to retry" };
86145
86285
  }
86146
- if (req.status !== "pending") {
86286
+ if (req.status !== "pending" && !retryableInspection) {
86147
86287
  return { runnable: false, why: "this drawing read has a status this version of FloLess cannot safely start \u2014 open Requests for details or update FloLess" };
86148
86288
  }
86149
86289
  if (req.prepassReady === true) {
@@ -86292,7 +86432,8 @@ function registerRunRelay(app, deps, origin) {
86292
86432
  return reply.send(jsonRpc(msg.id, toolRefusal(`no such tool: ${String(params?.name)}`)));
86293
86433
  }
86294
86434
  const durableRequest = deps.codex.getRequest(lease);
86295
- if (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout") {
86435
+ const retryableInspection = hasRetryableInspectionRefusal(durableRequest ?? {});
86436
+ if (!retryableInspection && (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout")) {
86296
86437
  completedRevisionPrepasses.add(lease.leaseId);
86297
86438
  recordCodexTool(lease, params.name, "denied");
86298
86439
  return reply.send(jsonRpc(msg.id, toolRefusal("Steel Filter preparation timed out. Do not retry this request unchanged. Close it and attach a smaller drawing set.")));
@@ -86397,7 +86538,8 @@ function registerRunRelay(app, deps, origin) {
86397
86538
  return reply.send(jsonRpc(msg.id, toolRefusal(`no such tool: ${String(params?.name)}`)));
86398
86539
  }
86399
86540
  const durableRequest = deps.codex?.getRequest(lease);
86400
- if (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout") {
86541
+ const retryableInspection = hasRetryableInspectionRefusal(durableRequest ?? {});
86542
+ if (!retryableInspection && (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout")) {
86401
86543
  completedRevisionPrepasses.add(lease.leaseId);
86402
86544
  return reply.send(jsonRpc(msg.id, toolRefusal("Steel Filter preparation timed out. Do not retry this request unchanged. Close it and attach a smaller drawing set.")));
86403
86545
  }
@@ -86961,8 +87103,8 @@ My note: ${req.instruction}` : "") + ((req.appTemplateId || req.appId) === "vect
86961
87103
  For an unbuilt-connection relationship question, a verified connection marker is the drawing destination: say FloLess associated that recorded marker with the question, never that the drawing proves the intended support. Its model destination is the main member and endpoint because the omitted connection has no parts to select. An unbuilt connection caused only by an unknown elevation has no verified marker destination and opens the affected member endpoint instead.`);
86962
87104
  const messageHint = isInitialRead ? "<plain-English what was read>" : "<plain-English what changed>";
86963
87105
  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 }.`;
86964
- 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/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so if you cannot establish a plan view elevation from the set, ASK THE USER for it before you read members from that sheet - one question per view, not one per member. 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" or "unreviewed", 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), 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), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the strongest corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. Name every outcome.runnersUp row too \u2014 a competing reading at exactly half the value is the failure this arm exists to put in front of a person, not a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. Regeneration is not always available: it is refused with 409 revision-filter-prepared when this request has already published its Filter checkpoint and the saved Filter still matches the manifest's own copy of it. If that happens, STOP and tell the user what the questions say \u2014 do not retry, because nothing you can send will change that answer. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. 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; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: group them by kind, lead with the ones that change the model most (a member with no elevation before a layer nobody could classify), name what each one is about the way a detailer would (the mark and the sheet, not an element id), and say how many there are in total when you summarise rather than listing hundreds. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. 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 }.`;
86965
- const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}; only it inventories pages and mints Filter ids. On sheet-identification-required, inspect listed pages, identify each, then retry with { bindings: [{ pageId, sheet, title?, evidenceKind }] }; never guess from other pages or build Filter geometry. On steel-manifest-preparation-busy, wait at least retryAfterMs; retry this step. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator clears it. On steel-manifest-extraction-timeout, STOP; do not retry the same drawing set. Relay error and recovery, then phase, elapsed/limit, counts and diagnostic id; null page counts are unknown. Never relay commands, stderr, source, filenames, or paths. A smaller set is required. On steel-manifest-over-budget, STOP and relay recovery. Page scope: remove or split that dense sheet. Total scope: smaller revisions. Bytes scope is drawing-data weight, not element count: move or split the heaviest sheets first; one sheet over the limit cannot be isolated to help. Null scope means extraction overflowed before measurement: no breakdown; the set must be far smaller. Only complete true covers the whole set; with false or null the figures are lower bounds and the recovery may not suffice. On steel-manifest-extraction-failed, STOP and relay the diagnostic; an identical retry fails. Never rename Filter geometry or mint element ids.`;
87106
+ 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/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so if you cannot establish a plan view elevation from the set, ASK THE USER for it before you read members from that sheet - one question per view, not one per member. 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" or "unreviewed", 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), 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), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the best corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. It is CORROBORATION AND NOT A VERDICT \u2014 it does not decide which reading the proposer chose, so do not present it as the reason the number is right. Name every outcome.runnersUp row too. A competing reading is now RARER than it was: the proposer reads each chain out of a single printed dimension row and refuses one that skips a dimension sitting alongside it, which removes most sub-multiple readings before they are ever reported. So an EMPTY runnersUp is the normal case and is not itself reassurance, while a row that does survive is a reading the drawing genuinely supports twice over \u2014 say so, and never as a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. Regeneration is not always available: it is refused with 409 revision-filter-prepared when this request has already published its Filter checkpoint and the saved Filter still matches the manifest's own copy of it. If that happens, STOP and tell the user what the questions say \u2014 do not retry, because nothing you can send will change that answer. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. 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; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: group them by kind, lead with the ones that change the model most (a member with no elevation before a layer nobody could classify), name what each one is about the way a detailer would (the mark and the sheet, not an element id), and say how many there are in total when you summarise rather than listing hundreds. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. 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 }.`;
87107
+ const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}; only it inventories pages and mints Filter ids. On sheet-identification-required, inspect listed pages, identify each, then retry with { bindings: [{ pageId, sheet, title?, evidenceKind }] }; never guess from other pages or build Filter geometry. On steel-manifest-preparation-busy, wait at least retryAfterMs; retry this step. On steel-manifest-inspection-interrupted, wait at least retryAfterMs and retry the SAME request; the request and its drawing set remain attached. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator clears it. On steel-manifest-extraction-timeout, STOP; do not retry the same drawing set. Relay error and recovery, then phase, elapsed/limit, counts and diagnostic id; null page counts are unknown. Never relay commands, stderr, source, filenames, or paths. A smaller set is required. On steel-manifest-over-budget, STOP and relay recovery. Page scope: remove or split that dense sheet. Total scope: smaller revisions. Bytes scope is drawing-data weight, not element count: move or split the heaviest sheets first; one sheet over the limit cannot be isolated to help. Null scope means extraction overflowed before measurement: no breakdown; the set must be far smaller. Only complete true covers the whole set; with false or null the figures are lower bounds and the recovery may not suffice. On steel-manifest-extraction-failed, STOP and relay the diagnostic; an identical retry fails. Never rename Filter geometry or mint element ids.`;
86966
87108
  if ((req.appTemplateId || req.appId) === "vectorize") {
86967
87109
  if (isInitialRead) {
86968
87110
  return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing was attached \u2014 trace it into this project as its first version (do NOT create a new project). Vectorize the drawing per the floless-app-vectorize skill into a drawing.vector/v1 contract: emit clean, editable 2D vector geometry (sheets \u2192 elements: lines / polylines / curves / text, each on its layer), NOT steel members or a takeoff. A vector PDF is read deterministically (exact geometry, no guessing); a photo, scan or hand sketch is traced by a fenced vision extraction that flags every uncertain stroke (low confidence) for the user's review. ${vectorPost}${snaps}${note}`;
@@ -87183,10 +87325,11 @@ function withPrompt(r, base = selfOrigin()) {
87183
87325
  const prompt = instructionFor(r);
87184
87326
  const marker = markerFor(r, base, prompt);
87185
87327
  const eligibility = runEligibilityFor(r);
87186
- const terminalPreparationRefusal = r.type === "revision-read" && (r.refusalCode === "steel-manifest-extraction-timeout" || r.run?.refusalCode === "steel-manifest-extraction-timeout");
87187
- const retryableAttempt = r.type === "revision-read" && r.run !== void 0 && ["failed", "contract-violation", "exited-unresolved"].includes(r.run.state) && r.run.refusalCode !== "steel-manifest-extraction-timeout" && !getLease(r.run.leaseId);
87328
+ const retryableInspectionRefusal = r.type === "revision-read" && hasRetryableInspectionRefusal(r);
87329
+ const terminalPreparationRefusal = !retryableInspectionRefusal && r.type === "revision-read" && (r.refusalCode === "steel-manifest-extraction-timeout" || r.run?.refusalCode === "steel-manifest-extraction-timeout");
87330
+ const retryableAttempt = r.type === "revision-read" && r.run !== void 0 && ["failed", "contract-violation", "exited-unresolved"].includes(r.run.state) && (r.run.refusalCode !== "steel-manifest-extraction-timeout" || retryableInspectionRefusal) && !getLease(r.run.leaseId);
87188
87331
  const hasAttempt = r.type === "revision-read" && r.run !== void 0 && !retryableAttempt || r.type === "guide" && r.run?.state === "answered";
87189
- const projectedRun = r.type === "revision-read" && r.status !== "pending" ? void 0 : r.run?.state === "answered" && !validatedInstructorAnswer(r) ? { ...r.run, state: "contract-violation", answer: void 0, lastOutput: "The stored Instructor answer failed validation." } : r.run;
87332
+ const projectedRun = r.type === "revision-read" && r.status !== "pending" && !retryableInspectionRefusal ? void 0 : r.run?.state === "answered" && !validatedInstructorAnswer(r) ? { ...r.run, state: "contract-violation", answer: void 0, lastOutput: "The stored Instructor answer failed validation." } : r.run;
87190
87333
  const clearPolicy = requestClearPolicyFor(r);
87191
87334
  return {
87192
87335
  ...r,
@@ -90779,7 +90922,7 @@ var profileMismatchFact = (memberId, live, answered, sameSection) => rollDegrees
90779
90922
  var profileMismatchAction = (fact, answered) => `${fact}. Set it to ${answered} here, or close this RFI and reopen it to record a different answer.`;
90780
90923
  var needsSizeTruth = (action, disposition) => action === "apply" || action === "close" && disposition === "resolved";
90781
90924
  var isObj16 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
90782
- var onlyKeys3 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
90925
+ var onlyKeys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
90783
90926
  var RFI_ACTIONS = /* @__PURE__ */ new Set(["send", "answer", "apply", "close", "reopen"]);
90784
90927
  function viewOf(record4, truth, projectName, file) {
90785
90928
  const sighting = latestSighting(record4);
@@ -91197,7 +91340,7 @@ function registerRfiRoutes(app, options = {}) {
91197
91340
  const project = resolveProject(req.params.id);
91198
91341
  if (!project.ok) return send(project.code, { ok: false, error: project.error });
91199
91342
  const body = isObj16(req.body) ? req.body : {};
91200
- if (!onlyKeys3(body, ["operationKey", "memberId", "action", "expectedRfiId", "expectedRfiRevision", "to", "via", "answer"])) {
91343
+ if (!onlyKeys4(body, ["operationKey", "memberId", "action", "expectedRfiId", "expectedRfiRevision", "to", "via", "answer"])) {
91201
91344
  return send(400, { ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
91202
91345
  }
91203
91346
  if (!isAddressField(body.operationKey, MAX_OPERATION_KEY)) {
@@ -91322,7 +91465,7 @@ function registerRfiRoutes(app, options = {}) {
91322
91465
  const action = req.params.action;
91323
91466
  if (!RFI_ACTIONS.has(action)) return send(404, { ok: false, error: `unknown action: ${action}` });
91324
91467
  const body = isObj16(req.body) ? req.body : {};
91325
- if (!onlyKeys3(body, ["operationKey", "recordRevision", "to", "via", "answer", "disposition", "note", "why"])) {
91468
+ if (!onlyKeys4(body, ["operationKey", "recordRevision", "to", "via", "answer", "disposition", "note", "why"])) {
91326
91469
  return send(400, { ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
91327
91470
  }
91328
91471
  if (!isAddressField(body.operationKey, MAX_OPERATION_KEY)) {
@@ -92840,7 +92983,7 @@ var productionDeps = {
92840
92983
  now: () => (/* @__PURE__ */ new Date()).toISOString()
92841
92984
  };
92842
92985
  var isObject3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
92843
- var onlyKeys4 = (value, allowed) => Object.keys(value).every((key3) => allowed.includes(key3));
92986
+ var onlyKeys5 = (value, allowed) => Object.keys(value).every((key3) => allowed.includes(key3));
92844
92987
  function attemptIdFor(projectUuid, operationKey) {
92845
92988
  return `gmail-${(0, import_node_crypto41.createHash)("sha256").update(JSON.stringify([projectUuid, operationKey])).digest("hex")}`;
92846
92989
  }
@@ -93049,7 +93192,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
93049
93192
  const project = resolveProject(req.params.id);
93050
93193
  if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
93051
93194
  const body = isObject3(req.body) ? req.body : {};
93052
- if (!onlyKeys4(body, ["operationKey", "recordRevision", "to"])) {
93195
+ if (!onlyKeys5(body, ["operationKey", "recordRevision", "to"])) {
93053
93196
  return reply.status(400).send({ ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
93054
93197
  }
93055
93198
  if (!isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
@@ -93101,7 +93244,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
93101
93244
  const project = resolveProject(req.params.id);
93102
93245
  if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
93103
93246
  const body = isObject3(req.body) ? req.body : {};
93104
- if (!onlyKeys4(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
93247
+ if (!onlyKeys5(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
93105
93248
  return reply.status(400).send({ ok: false, code: "rfi-operation-key-required", error: "every recovery carries an operation key" });
93106
93249
  }
93107
93250
  const release = acquireProjectDeliveryLease(req.params.id);
@@ -93160,7 +93303,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
93160
93303
  const project = resolveProject(req.params.id);
93161
93304
  if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
93162
93305
  const body = isObject3(req.body) ? req.body : {};
93163
- if (!onlyKeys4(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
93306
+ if (!onlyKeys5(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
93164
93307
  return reply.status(400).send({ ok: false, code: "rfi-operation-key-required", error: "every confirmation carries an operation key" });
93165
93308
  }
93166
93309
  const written = await mutateRfiDeliveryFile(req.params.id, (file) => {
@@ -95838,466 +95981,569 @@ function registerRevisionRoutes(app, deps = {}) {
95838
95981
  app.post(
95839
95982
  "/api/projects/:id/revision-requests/:reqId/steel-manifest",
95840
95983
  { bodyLimit: 256 * 1024 },
95841
- async (req, reply) => withLifecycleLock("project", req.params.id, async () => {
95842
- const project = getProject(req.params.id);
95843
- const request = getRequest(req.params.reqId);
95844
- const copiedTerminalRefusal = request?.refusalCode === "steel-manifest-extraction-timeout";
95845
- if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.appId !== project.app || request.status !== "pending" && !copiedTerminalRefusal || request.settledVersion !== void 0) {
95846
- return reply.status(404).send({ ok: false, error: "unknown pending steel revision request" });
95847
- }
95848
- let refusalLease = null;
95849
- if (request.run?.refusalCode !== "steel-manifest-extraction-timeout" && request.run?.leaseId) {
95850
- try {
95851
- refusalLease = getLease(request.run.leaseId);
95852
- } catch {
95853
- return reply.status(409).send({
95854
- ok: false,
95855
- code: "revision-read-lifecycle-unavailable",
95856
- error: "FloLess could not verify whether this drawing read is still owned by a terminal run.",
95857
- recovery: "Restart FloLess, then open Requests before trying again."
95858
- });
95859
- }
95860
- }
95861
- if (copiedTerminalRefusal || request.run?.refusalCode === "steel-manifest-extraction-timeout" || refusalLease?.terminalRefusalCode === "steel-manifest-extraction-timeout") {
95862
- const diagnostics = storedSteelTimeoutDiagnostics(
95863
- copiedTerminalRefusal ? request.steelPreparationTimeout : request.run?.steelPreparationTimeout
95864
- );
95865
- return reply.status(409).send({
95866
- ok: false,
95867
- code: "steel-manifest-extraction-timeout",
95868
- error: "Steel Filter preparation did not finish within the allowed time.",
95869
- recovery: "Do not retry this request unchanged. Close it and attach a smaller drawing set.",
95870
- ...diagnostics ?? {}
95871
- });
95872
- }
95873
- if (request.prepassReady === true && !preparedManifestNeedsRegeneration(project, request)) {
95874
- return reply.status(409).send({
95875
- ok: false,
95876
- code: "revision-filter-prepared",
95877
- error: "this drawing read already prepared its Drawing Filter \u2014 review and save that checkpoint instead of preparing it again"
95878
- });
95879
- }
95880
- let ownedHeadlessRun = false;
95881
- if (request.run && (request.run.state === "queued" || request.run.state === "running")) {
95882
- const rawToken = req.headers["x-floless-run-token"];
95883
- const token2 = Array.isArray(rawToken) ? rawToken[0] : rawToken;
95884
- const lease = typeof token2 === "string" ? leaseForToken(token2) : null;
95885
- if (!lease || lease.leaseId !== request.run.leaseId || lease.requestId !== request.id || lease.requestType !== "revision-read" || lease.project !== project.id || lease.appId !== project.app) {
95886
- return reply.status(409).send({
95887
- ok: false,
95888
- code: "revision-read-owned",
95889
- error: "this drawing read is already running \u2014 wait for it to prepare the Drawing Filter or stop it in Requests"
95890
- });
95891
- }
95892
- ownedHeadlessRun = true;
95893
- }
95894
- if (request.steelAuditPolicy !== 1 || resolveTemplateId(project.app) !== "steel-model") {
95895
- return reply.status(409).send({ ok: false, code: "steel-manifest-not-applicable", error: "this request is not governed by the Steel Model completion policy" });
95896
- }
95897
- const head = listVersions(project.id)[0]?.n ?? 0;
95898
- if ((request.baseVersion ?? 0) !== head) {
95899
- return reply.status(409).send({ ok: false, code: "revision-base-changed", error: `project changed since this read started (base v${request.baseVersion ?? 0}, now v${head})` });
95900
- }
95901
- let sources;
95902
- let inspected;
95903
- const now2 = deps.now ?? (() => import_node_perf_hooks2.performance.now());
95904
- let subprocessStartedAt = 0;
95905
- let hardDeadline = 0;
95906
- let inspectionEndedAt = 0;
95907
- let inspectionWorkload = null;
95984
+ async (req, reply) => {
95908
95985
  try {
95909
- sources = verifiedSteelSources(project.id, request);
95910
- const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
95911
- subprocessStartedAt = now2();
95912
- hardDeadline = steelOperationDeadlineAt(subprocessStartedAt);
95913
- inspectionWorkload = {
95914
- sourceCount: sources.extractorSources.length,
95915
- sourceBytes,
95916
- totalPageCount: null,
95917
- selectedPageCount: null
95918
- };
95919
- const inspectionTimeout = Math.min(steelInspectionTimeoutMs(sources.extractorSources.length, sourceBytes), Math.max(0, Math.floor(hardDeadline - now2())));
95920
- inspected = await (deps.inspectSteelSourcePages ?? inspectSteelSourcePages)(sources.extractorSources, {
95921
- timeoutMs: inspectionTimeout,
95922
- workload: inspectionWorkload
95923
- });
95924
- inspectionEndedAt = now2();
95925
- } catch (error) {
95926
- if (error instanceof SteelFilterCleanupStateError) {
95927
- return reply.status(409).send({
95928
- ok: false,
95929
- code: "steel-manifest-preparation-blocked",
95930
- error: error.message,
95931
- recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
95932
- });
95933
- }
95934
- if (error instanceof SteelFilterCleanupPendingError) {
95935
- reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
95936
- return reply.status(409).send(steelCleanupPendingBody(error));
95937
- }
95938
- if (error instanceof SteelFilterTimeoutError) {
95939
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, elapsedMs: error.elapsedMs, timeoutMs: error.timeoutMs, ...error.workload }, "steel manifest preparation timed out");
95940
- if (!ownedHeadlessRun) {
95941
- const body = steelTimeoutBody(error);
95942
- const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
95943
- status: "failed",
95944
- refusalCode: "steel-manifest-extraction-timeout",
95945
- steelPreparationTimeout: steelTimeoutDiagnostics(error),
95946
- error: `${body.error} ${body.recovery} Diagnostic id: ${body.diagnosticId}.`
95986
+ return await withLifecycleLock("project", req.params.id, async () => {
95987
+ const project = getProject(req.params.id);
95988
+ let request = getRequest(req.params.reqId);
95989
+ const resumableLegacyInspection = request ? hasRetryableInspectionRefusal(request) : false;
95990
+ const hasPreparationTimeoutAuthority = request?.refusalCode === "steel-manifest-extraction-timeout" || request?.run?.refusalCode === "steel-manifest-extraction-timeout";
95991
+ if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.appId !== project.app || request.status !== "pending" && !hasPreparationTimeoutAuthority || request.settledVersion !== void 0) {
95992
+ return reply.status(404).send({ ok: false, error: "unknown pending steel revision request" });
95993
+ }
95994
+ let ownedHeadlessRun = false;
95995
+ let refusalLease = null;
95996
+ if (request.run?.leaseId) {
95997
+ try {
95998
+ refusalLease = getLease(request.run.leaseId);
95999
+ } catch {
96000
+ return reply.status(409).send({
96001
+ ok: false,
96002
+ code: "revision-read-lifecycle-unavailable",
96003
+ error: "FloLess could not verify whether this drawing read is still owned by a terminal run.",
96004
+ recovery: "Restart FloLess, then open Requests before trying again."
96005
+ });
96006
+ }
96007
+ }
96008
+ if (request.run && (request.run.state === "queued" || request.run.state === "running")) {
96009
+ const rawToken = req.headers["x-floless-run-token"];
96010
+ const token2 = Array.isArray(rawToken) ? rawToken[0] : rawToken;
96011
+ const lease = typeof token2 === "string" ? leaseForToken(token2) : null;
96012
+ if (!lease || lease.leaseId !== request.run.leaseId || lease.requestId !== request.id || lease.requestType !== "revision-read" || lease.project !== project.id || lease.appId !== project.app) {
96013
+ return reply.status(409).send({
96014
+ ok: false,
96015
+ code: "revision-read-owned",
96016
+ error: "this drawing read is already running \u2014 wait for it to prepare the Drawing Filter or stop it in Requests"
96017
+ });
96018
+ }
96019
+ ownedHeadlessRun = true;
96020
+ }
96021
+ if (resumableLegacyInspection && !ownedHeadlessRun && refusalLease?.terminalRefusalCode === "steel-manifest-extraction-timeout") {
96022
+ const rawToken = req.headers["x-floless-run-token"];
96023
+ const token2 = Array.isArray(rawToken) ? rawToken[0] : rawToken;
96024
+ const lease = typeof token2 === "string" ? leaseForToken(token2) : null;
96025
+ if (!lease || lease.leaseId !== request.run?.leaseId || lease.requestId !== request.id || lease.requestType !== "revision-read" || lease.project !== project.id || lease.appId !== project.app) {
96026
+ return reply.status(409).send({
96027
+ ok: false,
96028
+ code: "revision-read-owned",
96029
+ error: "this interrupted drawing inspection is retained by its original terminal run \u2014 continue or stop that run in Requests"
96030
+ });
96031
+ }
96032
+ ownedHeadlessRun = true;
96033
+ }
96034
+ if (resumableLegacyInspection && ownedHeadlessRun && refusalLease?.terminalRefusalCode === "steel-manifest-extraction-timeout") {
96035
+ let cleared = null;
96036
+ try {
96037
+ cleared = (deps.patchLease ?? patchLease)(refusalLease.leaseId, refusalLease.generation, { terminalRefusalCode: null });
96038
+ } catch {
96039
+ }
96040
+ if (!cleared) {
96041
+ return reply.status(409).send({
96042
+ ok: false,
96043
+ code: "revision-read-lifecycle-unavailable",
96044
+ error: "FloLess could not reconcile the interrupted drawing inspection with its active run.",
96045
+ recovery: "Restart FloLess, then open Requests before trying again."
96046
+ });
96047
+ }
96048
+ refusalLease = cleared;
96049
+ }
96050
+ if (resumableLegacyInspection) {
96051
+ request = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
96052
+ status: "pending",
96053
+ refusalCode: void 0,
96054
+ steelPreparationTimeout: void 0,
96055
+ error: void 0,
96056
+ ...request.run ? { run: { ...request.run, refusalCode: void 0, steelPreparationTimeout: void 0 } } : {}
95947
96057
  });
95948
- if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its terminal refusal" });
96058
+ if (!request) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while making its interrupted inspection resumable" });
95949
96059
  broadcast({ type: "requests-changed" });
95950
96060
  }
95951
- return reply.status(400).send(steelTimeoutBody(error));
95952
- }
95953
- if (error instanceof SteelFilterProcessError) {
95954
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, category: error.category, exitCode: error.exitCode, signal: error.signal, stderrSha256: error.stderrSha256 }, "steel manifest source inspection refused");
95955
- return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: error.message, diagnosticId: error.diagnosticId });
95956
- }
95957
- const diagnosticId = (0, import_node_crypto42.randomUUID)();
95958
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "source-validation" }, "steel manifest source inspection refused");
95959
- return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: "Steel source inspection failed.", diagnosticId });
95960
- }
95961
- const rawBindings = Array.isArray(req.body?.bindings) ? req.body.bindings : [];
95962
- if (rawBindings.length > inspected.length) return reply.status(400).send({ ok: false, error: "too many page bindings" });
95963
- const bindingByPage = /* @__PURE__ */ new Map();
95964
- for (const raw of rawBindings) {
95965
- const pageId = typeof raw?.pageId === "string" ? raw.pageId : "";
95966
- const sheet = typeof raw?.sheet === "string" ? raw.sheet.trim() : "";
95967
- const evidenceKind = typeof raw?.evidenceKind === "string" && EVIDENCE_KINDS.has(raw.evidenceKind) ? raw.evidenceKind : null;
95968
- if (!inspected.some((page) => page.id === pageId) || !SHEET_ID.test(sheet) || !evidenceKind || bindingByPage.has(pageId)) {
95969
- return reply.status(400).send({ ok: false, code: "sheet-binding-invalid", error: "each page binding must name one inspected page, a safe unique sheet id, and a valid evidenceKind" });
95970
- }
95971
- const title = typeof raw.title === "string" && raw.title.trim() ? raw.title.trim().slice(0, 160) : void 0;
95972
- bindingByPage.set(pageId, { sheet, ...title ? { title } : {}, evidenceKind });
95973
- }
95974
- const current = readAcceptedForRequest(project.app, project.id, "read");
95975
- const currentObj = current && typeof current === "object" && !Array.isArray(current) ? current : null;
95976
- const currentPlans = Array.isArray(currentObj?.plans) ? currentObj.plans.filter((p) => !!p && typeof p === "object" && !Array.isArray(p)) : [];
95977
- const existingBySheet = new Map(currentPlans.flatMap((plan) => typeof plan.sheet === "string" ? [[normalizedSheet(plan.sheet), plan]] : []));
95978
- const unresolved = [];
95979
- const pages = [];
95980
- for (const page of inspected) {
95981
- const explicit = bindingByPage.get(page.id);
95982
- const trustedSheet = page.trustedSheetCandidate;
95983
- const existingMatches = trustedSheet ? [normalizedSheet(trustedSheet)].flatMap((candidate2) => existingBySheet.has(candidate2) ? [existingBySheet.get(candidate2)] : []) : [];
95984
- let binding = explicit;
95985
- if (!binding && page.title && page.evidenceKind !== "other" && existingMatches.length === 1 && typeof existingMatches[0].sheet === "string") {
95986
- const existing = existingMatches[0];
95987
- binding = { sheet: existing.sheet, title: page.title, evidenceKind: page.evidenceKind };
95988
- }
95989
- if (!binding && trustedSheet && page.title && page.evidenceKind !== "other") binding = { sheet: trustedSheet, title: page.title, evidenceKind: page.evidenceKind };
95990
- if (!binding) {
95991
- unresolved.push({ pageId: page.id, sourceHash: page.sourceHash, page: page.page, candidates: page.sheetCandidates, suggestedKind: page.evidenceKind, ...page.suggestedTitle ? { suggestedTitle: page.suggestedTitle } : page.title ? { suggestedTitle: page.title } : {} });
95992
- continue;
95993
- }
95994
- const viewKind = modelViewKindForEvidence(binding.evidenceKind);
95995
- pages.push({
95996
- id: page.id,
95997
- sourceHash: page.sourceHash,
95998
- page: page.page,
95999
- bounds: page.bounds,
96000
- sheetCandidates: page.sheetCandidates,
96001
- sheet: binding.sheet,
96002
- ...binding.title ? { title: binding.title } : {},
96003
- evidenceKind: binding.evidenceKind,
96004
- ...viewKind ? { viewKind } : {}
96005
- });
96006
- }
96007
- if (unresolved.length) return reply.status(409).send({ ok: false, code: "sheet-identification-required", pages: unresolved.slice(0, 100), total: unresolved.length });
96008
- const duplicateSheets = pages.map((page) => normalizedSheet(page.sheet)).filter((sheet, index, all) => all.indexOf(sheet) !== index);
96009
- if (duplicateSheets.length) return reply.status(400).send({ ok: false, code: "sheet-binding-duplicate", error: `more than one source page is bound to ${[...new Set(duplicateSheets)].join(", ")}` });
96010
- const modelPages = pages.filter(isModelPage);
96011
- if (!modelPages.some((page) => page.viewKind === "plan")) return reply.status(409).send({ ok: false, code: "plan-view-required", error: "the drawing set requires at least one bound framing plan" });
96012
- let filter;
96013
- let evidenceFilter;
96014
- try {
96015
- const extractor = deps.extractSteelFilter ?? extractSteelFilter;
96016
- const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
96017
- const streamBytes = steelStreamBytesOf(inspected);
96018
- const extractionDeadline = steelExtractionDeadlineAt(subprocessStartedAt, inspected.length, sources.extractorSources.length, sourceBytes, streamBytes);
96019
- req.log.info({
96020
- projectId: project.id,
96021
- requestId: request.id,
96022
- deadlineMs: Math.round(extractionDeadline - subprocessStartedAt),
96023
- hardDeadlineMs: STEEL_OPERATION_HARD_DEADLINE_MS,
96024
- budgetMs: steelExtractionBudgetMs(inspected.length, sources.extractorSources.length, sourceBytes, streamBytes),
96025
- inspectionMs: Math.round(inspectionEndedAt - subprocessStartedAt),
96026
- // Logged beside the budget it selected, so a timeout can be read against the input that
96027
- // chose its deadline rather than leaving the reader to guess which arm won.
96028
- pages: inspected.length,
96029
- sources: sources.extractorSources.length,
96030
- sourceBytes,
96031
- streamBytes
96032
- }, "steel filter extraction starting");
96033
- const workloadFor = (selectedPageCount) => ({
96034
- sourceCount: sources.extractorSources.length,
96035
- sourceBytes,
96036
- totalPageCount: inspected.length,
96037
- selectedPageCount
96038
- });
96039
- const remaining2 = (phase2, workload) => {
96040
- const value = Math.floor(extractionDeadline - now2());
96041
- if (value <= 0) throw new SteelFilterTimeoutError(
96042
- phase2,
96043
- Math.max(0, Math.round(now2() - subprocessStartedAt)),
96044
- Math.max(0, Math.round(extractionDeadline - subprocessStartedAt)),
96045
- workload
96046
- );
96047
- return Math.max(1, value);
96048
- };
96049
- const evidenceWorkload = workloadFor(pages.length);
96050
- evidenceFilter = await extractor({
96051
- sources: sources.extractorSources,
96052
- plans: pages.map((_page, index) => ({ sheet: `E${index + 1}` })),
96053
- pages: pages.map((page, index) => ({ sourceHash: page.sourceHash, page: page.page, sheet: `E${index + 1}` }))
96054
- }, { phase: "evidence", timeoutMs: remaining2("evidence", evidenceWorkload), workload: evidenceWorkload });
96055
- const modelWorkload = workloadFor(modelPages.length);
96056
- filter = await extractor({
96057
- sources: sources.extractorSources,
96058
- plans: modelPages.map((page) => ({ sheet: page.sheet, ...page.title ? { title: page.title } : {} })),
96059
- pages: modelPages.map((page) => ({ sourceHash: page.sourceHash, page: page.page, sheet: page.sheet })),
96060
- ...currentObj?.filter === void 0 ? {} : { filter: currentObj.filter }
96061
- }, { phase: "model", timeoutMs: remaining2("model", modelWorkload), workload: modelWorkload });
96062
- evidenceFilter = currentSteelFilterResult(evidenceFilter);
96063
- filter = currentSteelFilterResult(filter);
96064
- } catch (error) {
96065
- if (error instanceof SteelFilterCleanupStateError) {
96066
- return reply.status(409).send({
96067
- ok: false,
96068
- code: "steel-manifest-preparation-blocked",
96069
- error: error.message,
96070
- recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
96071
- });
96072
- }
96073
- if (error instanceof SteelFilterCleanupPendingError) {
96074
- reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
96075
- return reply.status(409).send(steelCleanupPendingBody(error));
96076
- }
96077
- if (error instanceof SteelFilterTimeoutError) {
96078
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, elapsedMs: error.elapsedMs, timeoutMs: error.timeoutMs, ...error.workload }, "steel manifest preparation timed out");
96079
- if (!ownedHeadlessRun) {
96080
- const body = steelTimeoutBody(error);
96081
- const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
96082
- status: "failed",
96083
- refusalCode: "steel-manifest-extraction-timeout",
96084
- steelPreparationTimeout: steelTimeoutDiagnostics(error),
96085
- error: `${body.error} ${body.recovery} Diagnostic id: ${body.diagnosticId}.`
96061
+ const copiedTerminalRefusal = request.refusalCode === "steel-manifest-extraction-timeout";
96062
+ if (copiedTerminalRefusal || request.run?.refusalCode === "steel-manifest-extraction-timeout" || refusalLease?.terminalRefusalCode === "steel-manifest-extraction-timeout") {
96063
+ const diagnostics = storedSteelTimeoutDiagnostics(
96064
+ copiedTerminalRefusal ? request.steelPreparationTimeout : request.run?.steelPreparationTimeout
96065
+ );
96066
+ return reply.status(409).send({
96067
+ ok: false,
96068
+ code: "steel-manifest-extraction-timeout",
96069
+ error: "Steel Filter preparation did not finish within the allowed time.",
96070
+ recovery: "Do not retry this request unchanged. Close it and attach a smaller drawing set.",
96071
+ ...diagnostics ?? {}
96086
96072
  });
96087
- if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its terminal refusal" });
96088
- broadcast({ type: "requests-changed" });
96089
96073
  }
96090
- return reply.status(400).send(steelTimeoutBody(error));
96091
- }
96092
- if (error instanceof SteelFilterBudgetError) {
96093
- const labelByPage = new Map(pages.map((page) => [`${page.sourceHash} ${page.page}`, page.sheet]));
96094
- const nameByHash = new Map(sources.manifestSources.map((source) => [source.sha256, source.name]));
96095
- const overBudget = error.pages.map((row) => ({
96096
- sheet: labelByPage.get(`${row.sourceHash} ${row.page}`) ?? `${nameByHash.get(row.sourceHash) ?? "source"} p.${row.page}`,
96097
- sourceHash: row.sourceHash,
96098
- page: row.page,
96099
- count: row.count,
96100
- bytes: row.bytes,
96101
- // #1015: how much of this sheet was ALREADY dropped for painting nothing before it still
96102
- // breached. Omitted rather than defaulted to 0 when the extractor did not report it -
96103
- // a 0 would claim a measurement nobody made. Without this the field would be parsed and
96104
- // then discarded here, which is a diagnostic that reaches nobody.
96105
- ...row.blankFills !== void 0 ? { blankFills: row.blankFills } : {}
96106
- }));
96107
- const bytesScope = error.scope === "bytes";
96108
- req.log.warn({
96109
- projectId: project.id,
96110
- requestId: request.id,
96111
- scope: error.scope,
96112
- detectedBy: error.detectedBy,
96113
- bytes: error.bytes,
96114
- total: error.total,
96115
- pages: error.pages.length,
96116
- // Summed, not per-page: the log answers "how much was already removed and it STILL
96117
- // breached", which is the operational question (#1015). Present ONLY when every row
96118
- // reported it - the field is optional, so summing with `?? 0` over a partially-reporting
96119
- // set would log a total that is silently short and read as a real measurement. That is the
96120
- // same "absent is not zero" rule the refusal row above follows, and it has to hold here
96121
- // too or the two disagree about what silence means.
96122
- ...error.pages.every((row) => row.blankFills !== void 0) ? { blankFills: error.pages.reduce((sum2, row) => sum2 + (row.blankFills ?? 0), 0) } : {}
96123
- }, "steel filter extraction refused: over budget");
96124
- const soleHeavySheet = bytesScope && (error.pages[0]?.bytes ?? 0) > (error.byteLimit ?? Infinity) ? overBudget[0] : void 0;
96125
- const whole = error.complete === true;
96126
- const measured = error.measuredPages;
96127
- const sheetsSoFar = measured === null ? "The sheets measured so far" : `${measured} measured sheet${measured === 1 ? "" : "s"}`;
96128
- const producePhrase = measured === 1 ? "produces" : "produce";
96129
- const carryPhrase = measured === 1 ? "carries" : "carry";
96130
- const unknownTail = error.totalPages === null && !whole ? " How much of the set that is was not established here." : "";
96131
- const coverageNote = whole ? "" : error.totalPages === null ? "How much of the set this covers could not be established, so what follows is one limit it breaches, not necessarily the only one. " : `The read stopped after ${measured} of ${error.totalPages} sheets, as soon as a limit was proved \u2014 so what follows is necessary, but the sheets it did not measure may breach a limit too. `;
96132
- return reply.status(400).send({
96133
- ok: false,
96134
- code: "steel-manifest-over-budget",
96135
- scope: error.scope,
96136
- error: error.scope === "page" ? `Sheet ${overBudget[0]?.sheet ?? "unknown"} carries ${overBudget[0]?.count ?? 0} drawing elements, over the ${error.elementLimit}-element limit for a single sheet.` : bytesScope ? whole ? `This drawing set produces ${asMegabytes(error.bytes)} of drawing data, over the ${asMegabytes(error.byteLimit ?? 0)} a single read can process.` : `${sheetsSoFar} already ${producePhrase} ${asMegabytes(error.bytes)} of drawing data, over the ${asMegabytes(error.byteLimit ?? 0)} a single read can process.${unknownTail}` : whole ? `This drawing set carries ${error.total} elements, over the ${error.elementLimit}-element limit for a single read.` : `${sheetsSoFar} already ${carryPhrase} ${error.total} elements, over the ${error.elementLimit}-element limit for a single read.${unknownTail}`,
96137
- recovery: coverageNote + (error.scope === "page" ? `Close this request and re-submit without that sheet, or split its content across sheets so each stays under ${error.elementLimit} elements.` : soleHeavySheet ? `Sheet ${soleHeavySheet.sheet} alone produces ${asMegabytes(soleHeavySheet.bytes)}, more than a single read can process \u2014 so it has to come out of the set, or its drawings split across several sheets. Re-submitting the rest as smaller revisions will not help while that sheet is in.` : bytesScope ? `Close this request and re-submit the drawing set as smaller revisions. The list below is ordered by weight, heaviest first \u2014 move those sheets into a revision of their own, or thin the drawings on them.` : `Close this request and re-submit the drawing set as smaller revisions \u2014 split the sheets so each revision stays under ${error.elementLimit} elements.`),
96138
- // `total`/`limit` are ELEMENT counts, `bytes`/`byteLimit` are output size. Shipping the
96139
- // whole-set count beside a per-sheet limit, or an element count beside a byte limit,
96140
- // invites the reader to compare two numbers that answer different questions — so each is
96141
- // null wherever it is not the bound. The unit split itself is decided once, on the error.
96142
- total: error.scope === "page" ? null : bytesScope ? null : error.total,
96143
- limit: error.elementLimit,
96144
- bytes: error.bytes,
96145
- byteLimit: error.byteLimit,
96146
- // What the figures above actually cover, and every bound the measured sheets breach.
96147
- complete: error.complete,
96148
- measuredPages: error.measuredPages,
96149
- totalPages: error.totalPages,
96150
- breaches: error.breaches,
96151
- overBudget: overBudget.slice(0, STEEL_READ_MAX_PAGES)
96152
- });
96153
- }
96154
- if (error instanceof SteelFilterOutputTooLargeError) {
96155
- return reply.status(400).send({
96156
- ok: false,
96157
- code: "steel-manifest-over-budget",
96158
- error: "This drawing set is too large to process in a single read.",
96159
- recovery: "Close this request and re-submit the drawing set as several materially smaller revisions.",
96160
- // `scope: null` deliberately, not an omitted key: the terminal AI branches on `scope`
96161
- // (see request-instruction.ts), and a branch table has to be total. This condition is not
96162
- // one of the three bounds — it is the last-resort overflow, with nothing measured.
96163
- //
96164
- // `complete: null`, NOT false: overflow proves no coverage fact at all and can happen
96165
- // before or after a full traversal. `false` is reserved for a VERIFIED proper subset of a
96166
- // known page set, which is a different claim.
96167
- scope: null,
96168
- total: null,
96169
- limit: null,
96170
- bytes: null,
96171
- byteLimit: null,
96172
- complete: null,
96173
- measuredPages: null,
96174
- totalPages: null,
96175
- breaches: [],
96176
- overBudget: []
96074
+ if (request.prepassReady === true && !preparedManifestNeedsRegeneration(project, request)) {
96075
+ return reply.status(409).send({
96076
+ ok: false,
96077
+ code: "revision-filter-prepared",
96078
+ error: "this drawing read already prepared its Drawing Filter \u2014 review and save that checkpoint instead of preparing it again"
96079
+ });
96080
+ }
96081
+ if (request.steelAuditPolicy !== 1 || resolveTemplateId(project.app) !== "steel-model") {
96082
+ return reply.status(409).send({ ok: false, code: "steel-manifest-not-applicable", error: "this request is not governed by the Steel Model completion policy" });
96083
+ }
96084
+ const head = listVersions(project.id)[0]?.n ?? 0;
96085
+ if ((request.baseVersion ?? 0) !== head) {
96086
+ return reply.status(409).send({ ok: false, code: "revision-base-changed", error: `project changed since this read started (base v${request.baseVersion ?? 0}, now v${head})` });
96087
+ }
96088
+ let sources;
96089
+ let inspected;
96090
+ const now2 = deps.now ?? (() => import_node_perf_hooks2.performance.now());
96091
+ let subprocessStartedAt = 0;
96092
+ let inspectionStartedAt = 0;
96093
+ let hardDeadline = 0;
96094
+ let inspectionEndedAt = 0;
96095
+ let inspectionWorkload = null;
96096
+ let freshInspection = false;
96097
+ try {
96098
+ sources = verifiedSteelSources(project.id, request);
96099
+ const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
96100
+ inspectionStartedAt = now2();
96101
+ subprocessStartedAt = inspectionStartedAt;
96102
+ inspectionWorkload = {
96103
+ sourceCount: sources.extractorSources.length,
96104
+ sourceBytes,
96105
+ totalPageCount: null,
96106
+ selectedPageCount: null
96107
+ };
96108
+ const cachedInspection = readSteelPageInspection(request.id);
96109
+ if (cachedInspection && steelPageInspectionMatches(cachedInspection, {
96110
+ requestId: request.id,
96111
+ projectId: project.id,
96112
+ appId: project.app,
96113
+ baseVersion: request.baseVersion ?? 0,
96114
+ extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
96115
+ sources: sources.manifestSources
96116
+ })) {
96117
+ inspected = cachedInspection.pages;
96118
+ } else {
96119
+ inspected = await (deps.inspectSteelSourcePages ?? inspectSteelSourcePages)(sources.extractorSources, {
96120
+ // This is process-liveness containment, not a model-capacity refusal. Expiry leaves the
96121
+ // request attached and retryable; ordinary successful inventories become checkpoints.
96122
+ timeoutMs: STEEL_OPERATION_HARD_DEADLINE_MS,
96123
+ workload: inspectionWorkload
96124
+ });
96125
+ freshInspection = true;
96126
+ }
96127
+ inspectionEndedAt = now2();
96128
+ subprocessStartedAt = now2();
96129
+ hardDeadline = steelOperationDeadlineAt(subprocessStartedAt);
96130
+ } catch (error) {
96131
+ if (error instanceof SteelFilterCleanupStateError) {
96132
+ return reply.status(409).send({
96133
+ ok: false,
96134
+ code: "steel-manifest-preparation-blocked",
96135
+ error: error.message,
96136
+ recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
96137
+ });
96138
+ }
96139
+ if (error instanceof SteelFilterCleanupPendingError) {
96140
+ reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
96141
+ return reply.status(409).send(steelCleanupPendingBody(error));
96142
+ }
96143
+ if (error instanceof SteelFilterTimeoutError) {
96144
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, elapsedMs: error.elapsedMs, timeoutMs: error.timeoutMs, ...error.workload }, "steel manifest preparation timed out");
96145
+ if (error.phase === "inspection") {
96146
+ reply.header("Retry-After", "1");
96147
+ return reply.status(409).send({
96148
+ ...steelTimeoutBody(error),
96149
+ code: "steel-manifest-inspection-interrupted",
96150
+ error: "Drawing page inspection was interrupted before it finished.",
96151
+ recovery: "Retry this request. FloLess will continue with the same drawing set.",
96152
+ retryAfterMs: 1e3
96153
+ });
96154
+ }
96155
+ if (!ownedHeadlessRun) {
96156
+ const body = steelTimeoutBody(error);
96157
+ const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
96158
+ status: "failed",
96159
+ refusalCode: "steel-manifest-extraction-timeout",
96160
+ steelPreparationTimeout: steelTimeoutDiagnostics(error),
96161
+ error: `${body.error} ${body.recovery} Diagnostic id: ${body.diagnosticId}.`
96162
+ });
96163
+ if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its terminal refusal" });
96164
+ broadcast({ type: "requests-changed" });
96165
+ }
96166
+ return reply.status(400).send(steelTimeoutBody(error));
96167
+ }
96168
+ if (error instanceof SteelFilterProcessError) {
96169
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, category: error.category, exitCode: error.exitCode, signal: error.signal, stderrSha256: error.stderrSha256 }, "steel manifest source inspection refused");
96170
+ return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: error.message, diagnosticId: error.diagnosticId });
96171
+ }
96172
+ const diagnosticId = (0, import_node_crypto42.randomUUID)();
96173
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "source-validation" }, "steel manifest source inspection refused");
96174
+ return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: "Steel source inspection failed.", diagnosticId });
96175
+ }
96176
+ if (freshInspection) {
96177
+ writeSteelPageInspection({
96178
+ version: 1,
96179
+ requestId: request.id,
96180
+ projectId: project.id,
96181
+ appId: project.app,
96182
+ baseVersion: request.baseVersion ?? 0,
96183
+ extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
96184
+ sources: sources.manifestSources,
96185
+ pages: inspected
96186
+ });
96187
+ }
96188
+ const rawBindings = Array.isArray(req.body?.bindings) ? req.body.bindings : [];
96189
+ if (rawBindings.length > inspected.length) return reply.status(400).send({ ok: false, error: "too many page bindings" });
96190
+ const bindingByPage = /* @__PURE__ */ new Map();
96191
+ for (const raw of rawBindings) {
96192
+ const pageId = typeof raw?.pageId === "string" ? raw.pageId : "";
96193
+ const sheet = typeof raw?.sheet === "string" ? raw.sheet.trim() : "";
96194
+ const evidenceKind = typeof raw?.evidenceKind === "string" && EVIDENCE_KINDS.has(raw.evidenceKind) ? raw.evidenceKind : null;
96195
+ if (!inspected.some((page) => page.id === pageId) || !SHEET_ID.test(sheet) || !evidenceKind || bindingByPage.has(pageId)) {
96196
+ return reply.status(400).send({ ok: false, code: "sheet-binding-invalid", error: "each page binding must name one inspected page, a safe unique sheet id, and a valid evidenceKind" });
96197
+ }
96198
+ const title = typeof raw.title === "string" && raw.title.trim() ? raw.title.trim().slice(0, 160) : void 0;
96199
+ bindingByPage.set(pageId, { sheet, ...title ? { title } : {}, evidenceKind });
96200
+ }
96201
+ const current = readAcceptedForRequest(project.app, project.id, "read");
96202
+ const currentObj = current && typeof current === "object" && !Array.isArray(current) ? current : null;
96203
+ const currentPlans = Array.isArray(currentObj?.plans) ? currentObj.plans.filter((p) => !!p && typeof p === "object" && !Array.isArray(p)) : [];
96204
+ const existingBySheet = new Map(currentPlans.flatMap((plan) => typeof plan.sheet === "string" ? [[normalizedSheet(plan.sheet), plan]] : []));
96205
+ const unresolved = [];
96206
+ const pages = [];
96207
+ for (const page of inspected) {
96208
+ const explicit = bindingByPage.get(page.id);
96209
+ const trustedSheet = page.trustedSheetCandidate;
96210
+ const existingMatches = trustedSheet ? [normalizedSheet(trustedSheet)].flatMap((candidate2) => existingBySheet.has(candidate2) ? [existingBySheet.get(candidate2)] : []) : [];
96211
+ let binding = explicit;
96212
+ if (!binding && page.title && page.evidenceKind !== "other" && existingMatches.length === 1 && typeof existingMatches[0].sheet === "string") {
96213
+ const existing = existingMatches[0];
96214
+ binding = { sheet: existing.sheet, title: page.title, evidenceKind: page.evidenceKind };
96215
+ }
96216
+ if (!binding && trustedSheet && page.title && page.evidenceKind !== "other") binding = { sheet: trustedSheet, title: page.title, evidenceKind: page.evidenceKind };
96217
+ if (!binding) {
96218
+ unresolved.push({ pageId: page.id, sourceHash: page.sourceHash, page: page.page, candidates: page.sheetCandidates, suggestedKind: page.evidenceKind, ...page.suggestedTitle ? { suggestedTitle: page.suggestedTitle } : page.title ? { suggestedTitle: page.title } : {} });
96219
+ continue;
96220
+ }
96221
+ const viewKind = modelViewKindForEvidence(binding.evidenceKind);
96222
+ pages.push({
96223
+ id: page.id,
96224
+ sourceHash: page.sourceHash,
96225
+ page: page.page,
96226
+ bounds: page.bounds,
96227
+ sheetCandidates: page.sheetCandidates,
96228
+ sheet: binding.sheet,
96229
+ ...binding.title ? { title: binding.title } : {},
96230
+ evidenceKind: binding.evidenceKind,
96231
+ ...viewKind ? { viewKind } : {}
96232
+ });
96233
+ }
96234
+ if (unresolved.length) return reply.status(409).send({ ok: false, code: "sheet-identification-required", pages: unresolved.slice(0, 100), total: unresolved.length });
96235
+ const duplicateSheets = pages.map((page) => normalizedSheet(page.sheet)).filter((sheet, index, all) => all.indexOf(sheet) !== index);
96236
+ if (duplicateSheets.length) return reply.status(400).send({ ok: false, code: "sheet-binding-duplicate", error: `more than one source page is bound to ${[...new Set(duplicateSheets)].join(", ")}` });
96237
+ const modelPages = pages.filter(isModelPage);
96238
+ if (!modelPages.some((page) => page.viewKind === "plan")) return reply.status(409).send({ ok: false, code: "plan-view-required", error: "the drawing set requires at least one bound framing plan" });
96239
+ let filter;
96240
+ let evidenceFilter;
96241
+ try {
96242
+ const extractor = deps.extractSteelFilter ?? extractSteelFilter;
96243
+ const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
96244
+ const streamBytes = steelStreamBytesOf(inspected);
96245
+ const extractionDeadline = steelExtractionDeadlineAt(subprocessStartedAt, inspected.length, sources.extractorSources.length, sourceBytes, streamBytes);
96246
+ req.log.info({
96247
+ projectId: project.id,
96248
+ requestId: request.id,
96249
+ deadlineMs: Math.round(extractionDeadline - subprocessStartedAt),
96250
+ hardDeadlineMs: STEEL_OPERATION_HARD_DEADLINE_MS,
96251
+ budgetMs: steelExtractionBudgetMs(inspected.length, sources.extractorSources.length, sourceBytes, streamBytes),
96252
+ inspectionMs: Math.round(inspectionEndedAt - inspectionStartedAt),
96253
+ // Logged beside the budget it selected, so a timeout can be read against the input that
96254
+ // chose its deadline rather than leaving the reader to guess which arm won.
96255
+ pages: inspected.length,
96256
+ sources: sources.extractorSources.length,
96257
+ sourceBytes,
96258
+ streamBytes
96259
+ }, "steel filter extraction starting");
96260
+ const workloadFor = (selectedPageCount) => ({
96261
+ sourceCount: sources.extractorSources.length,
96262
+ sourceBytes,
96263
+ totalPageCount: inspected.length,
96264
+ selectedPageCount
96265
+ });
96266
+ const remaining2 = (phase2, workload) => {
96267
+ const value = Math.floor(extractionDeadline - now2());
96268
+ if (value <= 0) throw new SteelFilterTimeoutError(
96269
+ phase2,
96270
+ Math.max(0, Math.round(now2() - subprocessStartedAt)),
96271
+ Math.max(0, Math.round(extractionDeadline - subprocessStartedAt)),
96272
+ workload
96273
+ );
96274
+ return Math.max(1, value);
96275
+ };
96276
+ const evidenceWorkload = workloadFor(pages.length);
96277
+ evidenceFilter = await extractor({
96278
+ sources: sources.extractorSources,
96279
+ plans: pages.map((_page, index) => ({ sheet: `E${index + 1}` })),
96280
+ pages: pages.map((page, index) => ({ sourceHash: page.sourceHash, page: page.page, sheet: `E${index + 1}` }))
96281
+ }, { phase: "evidence", timeoutMs: remaining2("evidence", evidenceWorkload), workload: evidenceWorkload });
96282
+ const modelWorkload = workloadFor(modelPages.length);
96283
+ filter = await extractor({
96284
+ sources: sources.extractorSources,
96285
+ plans: modelPages.map((page) => ({ sheet: page.sheet, ...page.title ? { title: page.title } : {} })),
96286
+ pages: modelPages.map((page) => ({ sourceHash: page.sourceHash, page: page.page, sheet: page.sheet })),
96287
+ ...currentObj?.filter === void 0 ? {} : { filter: currentObj.filter }
96288
+ }, { phase: "model", timeoutMs: remaining2("model", modelWorkload), workload: modelWorkload });
96289
+ evidenceFilter = currentSteelFilterResult(evidenceFilter);
96290
+ filter = currentSteelFilterResult(filter);
96291
+ } catch (error) {
96292
+ if (error instanceof SteelFilterCleanupStateError) {
96293
+ return reply.status(409).send({
96294
+ ok: false,
96295
+ code: "steel-manifest-preparation-blocked",
96296
+ error: error.message,
96297
+ recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
96298
+ });
96299
+ }
96300
+ if (error instanceof SteelFilterCleanupPendingError) {
96301
+ reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
96302
+ return reply.status(409).send(steelCleanupPendingBody(error));
96303
+ }
96304
+ if (error instanceof SteelFilterTimeoutError) {
96305
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, elapsedMs: error.elapsedMs, timeoutMs: error.timeoutMs, ...error.workload }, "steel manifest preparation timed out");
96306
+ if (!ownedHeadlessRun) {
96307
+ const body = steelTimeoutBody(error);
96308
+ const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
96309
+ status: "failed",
96310
+ refusalCode: "steel-manifest-extraction-timeout",
96311
+ steelPreparationTimeout: steelTimeoutDiagnostics(error),
96312
+ error: `${body.error} ${body.recovery} Diagnostic id: ${body.diagnosticId}.`
96313
+ });
96314
+ if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its terminal refusal" });
96315
+ broadcast({ type: "requests-changed" });
96316
+ }
96317
+ return reply.status(400).send(steelTimeoutBody(error));
96318
+ }
96319
+ if (error instanceof SteelFilterBudgetError) {
96320
+ const labelByPage = new Map(pages.map((page) => [`${page.sourceHash} ${page.page}`, page.sheet]));
96321
+ const nameByHash = new Map(sources.manifestSources.map((source) => [source.sha256, source.name]));
96322
+ const overBudget = error.pages.map((row) => ({
96323
+ sheet: labelByPage.get(`${row.sourceHash} ${row.page}`) ?? `${nameByHash.get(row.sourceHash) ?? "source"} p.${row.page}`,
96324
+ sourceHash: row.sourceHash,
96325
+ page: row.page,
96326
+ count: row.count,
96327
+ bytes: row.bytes,
96328
+ // #1015: how much of this sheet was ALREADY dropped for painting nothing before it still
96329
+ // breached. Omitted rather than defaulted to 0 when the extractor did not report it -
96330
+ // a 0 would claim a measurement nobody made. Without this the field would be parsed and
96331
+ // then discarded here, which is a diagnostic that reaches nobody.
96332
+ ...row.blankFills !== void 0 ? { blankFills: row.blankFills } : {}
96333
+ }));
96334
+ const bytesScope = error.scope === "bytes";
96335
+ req.log.warn({
96336
+ projectId: project.id,
96337
+ requestId: request.id,
96338
+ scope: error.scope,
96339
+ detectedBy: error.detectedBy,
96340
+ bytes: error.bytes,
96341
+ total: error.total,
96342
+ pages: error.pages.length,
96343
+ // Summed, not per-page: the log answers "how much was already removed and it STILL
96344
+ // breached", which is the operational question (#1015). Present ONLY when every row
96345
+ // reported it - the field is optional, so summing with `?? 0` over a partially-reporting
96346
+ // set would log a total that is silently short and read as a real measurement. That is the
96347
+ // same "absent is not zero" rule the refusal row above follows, and it has to hold here
96348
+ // too or the two disagree about what silence means.
96349
+ ...error.pages.every((row) => row.blankFills !== void 0) ? { blankFills: error.pages.reduce((sum2, row) => sum2 + (row.blankFills ?? 0), 0) } : {}
96350
+ }, "steel filter extraction refused: over budget");
96351
+ const soleHeavySheet = bytesScope && (error.pages[0]?.bytes ?? 0) > (error.byteLimit ?? Infinity) ? overBudget[0] : void 0;
96352
+ const whole = error.complete === true;
96353
+ const measured = error.measuredPages;
96354
+ const sheetsSoFar = measured === null ? "The sheets measured so far" : `${measured} measured sheet${measured === 1 ? "" : "s"}`;
96355
+ const producePhrase = measured === 1 ? "produces" : "produce";
96356
+ const carryPhrase = measured === 1 ? "carries" : "carry";
96357
+ const unknownTail = error.totalPages === null && !whole ? " How much of the set that is was not established here." : "";
96358
+ const coverageNote = whole ? "" : error.totalPages === null ? "How much of the set this covers could not be established, so what follows is one limit it breaches, not necessarily the only one. " : `The read stopped after ${measured} of ${error.totalPages} sheets, as soon as a limit was proved \u2014 so what follows is necessary, but the sheets it did not measure may breach a limit too. `;
96359
+ return reply.status(400).send({
96360
+ ok: false,
96361
+ code: "steel-manifest-over-budget",
96362
+ scope: error.scope,
96363
+ error: error.scope === "page" ? `Sheet ${overBudget[0]?.sheet ?? "unknown"} carries ${overBudget[0]?.count ?? 0} drawing elements, over the ${error.elementLimit}-element limit for a single sheet.` : bytesScope ? whole ? `This drawing set produces ${asMegabytes(error.bytes)} of drawing data, over the ${asMegabytes(error.byteLimit ?? 0)} a single read can process.` : `${sheetsSoFar} already ${producePhrase} ${asMegabytes(error.bytes)} of drawing data, over the ${asMegabytes(error.byteLimit ?? 0)} a single read can process.${unknownTail}` : whole ? `This drawing set carries ${error.total} elements, over the ${error.elementLimit}-element limit for a single read.` : `${sheetsSoFar} already ${carryPhrase} ${error.total} elements, over the ${error.elementLimit}-element limit for a single read.${unknownTail}`,
96364
+ recovery: coverageNote + (error.scope === "page" ? `Close this request and re-submit without that sheet, or split its content across sheets so each stays under ${error.elementLimit} elements.` : soleHeavySheet ? `Sheet ${soleHeavySheet.sheet} alone produces ${asMegabytes(soleHeavySheet.bytes)}, more than a single read can process \u2014 so it has to come out of the set, or its drawings split across several sheets. Re-submitting the rest as smaller revisions will not help while that sheet is in.` : bytesScope ? `Close this request and re-submit the drawing set as smaller revisions. The list below is ordered by weight, heaviest first \u2014 move those sheets into a revision of their own, or thin the drawings on them.` : `Close this request and re-submit the drawing set as smaller revisions \u2014 split the sheets so each revision stays under ${error.elementLimit} elements.`),
96365
+ // `total`/`limit` are ELEMENT counts, `bytes`/`byteLimit` are output size. Shipping the
96366
+ // whole-set count beside a per-sheet limit, or an element count beside a byte limit,
96367
+ // invites the reader to compare two numbers that answer different questions — so each is
96368
+ // null wherever it is not the bound. The unit split itself is decided once, on the error.
96369
+ total: error.scope === "page" ? null : bytesScope ? null : error.total,
96370
+ limit: error.elementLimit,
96371
+ bytes: error.bytes,
96372
+ byteLimit: error.byteLimit,
96373
+ // What the figures above actually cover, and every bound the measured sheets breach.
96374
+ complete: error.complete,
96375
+ measuredPages: error.measuredPages,
96376
+ totalPages: error.totalPages,
96377
+ breaches: error.breaches,
96378
+ overBudget: overBudget.slice(0, STEEL_READ_MAX_PAGES)
96379
+ });
96380
+ }
96381
+ if (error instanceof SteelFilterOutputTooLargeError) {
96382
+ return reply.status(400).send({
96383
+ ok: false,
96384
+ code: "steel-manifest-over-budget",
96385
+ error: "This drawing set is too large to process in a single read.",
96386
+ recovery: "Close this request and re-submit the drawing set as several materially smaller revisions.",
96387
+ // `scope: null` deliberately, not an omitted key: the terminal AI branches on `scope`
96388
+ // (see request-instruction.ts), and a branch table has to be total. This condition is not
96389
+ // one of the three bounds — it is the last-resort overflow, with nothing measured.
96390
+ //
96391
+ // `complete: null`, NOT false: overflow proves no coverage fact at all and can happen
96392
+ // before or after a full traversal. `false` is reserved for a VERIFIED proper subset of a
96393
+ // known page set, which is a different claim.
96394
+ scope: null,
96395
+ total: null,
96396
+ limit: null,
96397
+ bytes: null,
96398
+ byteLimit: null,
96399
+ complete: null,
96400
+ measuredPages: null,
96401
+ totalPages: null,
96402
+ breaches: [],
96403
+ overBudget: []
96404
+ });
96405
+ }
96406
+ if (error instanceof SteelFilterProcessError) {
96407
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, category: error.category, exitCode: error.exitCode, signal: error.signal, stderrSha256: error.stderrSha256 }, "steel manifest extraction failed");
96408
+ return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: error.message, diagnosticId: error.diagnosticId });
96409
+ }
96410
+ const diagnosticId = (0, import_node_crypto42.randomUUID)();
96411
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "result-validation" }, "steel manifest extraction failed");
96412
+ return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: "Steel Filter extraction failed.", diagnosticId });
96413
+ }
96414
+ filter = mergeWholeSetLayerCensus({ modelFilter: filter, evidenceFilter, priorFilter: currentObj?.filter });
96415
+ if (currentObj?.filter !== void 0 && hasCanonicalMode(currentObj.filter)) {
96416
+ filter = withPriorMode(filter, currentObj.filter);
96417
+ } else {
96418
+ filter = withUsableDefaultMode(filter);
96419
+ }
96420
+ filter = currentSteelFilterResult(filter);
96421
+ const evidenceSheets = evidenceFilter && typeof evidenceFilter === "object" && !Array.isArray(evidenceFilter) && Array.isArray(evidenceFilter.sheets) ? evidenceFilter.sheets : [];
96422
+ let stored2;
96423
+ try {
96424
+ const manifestPages = buildCompactManifestPages(pages, evidenceSheets, filter);
96425
+ const scaleProposals = proposeSheetScales({
96426
+ filter,
96427
+ pages: manifestPages.map((page) => ({
96428
+ sheet: page.sheet ?? "",
96429
+ sourceHash: page.sourceHash,
96430
+ pageId: page.id,
96431
+ page: page.page,
96432
+ ...page.viewKind === void 0 ? {} : { viewKind: page.viewKind }
96433
+ })).filter((page) => page.sheet !== ""),
96434
+ environment: project.environment,
96435
+ // The SAME operation deadline the extraction ran under, WITH the clock it is expressed in —
96436
+ // one object, because they are meaningless apart: this deadline is a `performance.now()`
96437
+ // value, and comparing it against a `Date.now()` clock would exceed the budget on every
96438
+ // sheet and silently return the reader to hand-fitting. And the same VARIABLE, not the same
96439
+ // arithmetic re-derived: `steelOperationDeadlineAt` exists so that sum has one home.
96440
+ budget: { deadlineAt: hardDeadline, now: now2 }
96441
+ });
96442
+ stored2 = writeSteelReadManifest({
96443
+ version: 1,
96444
+ extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
96445
+ requestId: request.id,
96446
+ projectId: project.id,
96447
+ appId: project.app,
96448
+ sources: sources.manifestSources,
96449
+ pages: manifestPages,
96450
+ filter,
96451
+ candidatesRepr: "v2-compact",
96452
+ // Minted in the SAME write as the merged filter, so the marker and the thing it describes
96453
+ // cannot disagree. A manifest without it is a pre-slice-2a, model-pages-only census: it
96454
+ // still reads and audits, it simply cannot carry a layer sign-off until it is regenerated.
96455
+ censusScope: "whole-set"
96456
+ }, void 0, { scaleProposals });
96457
+ } catch (error) {
96458
+ if (error instanceof SteelReadPageBudgetError) {
96459
+ req.log.warn({ projectId: project.id, requestId: request.id, pages: error.pages.slice(0, 20) }, "steel manifest sheet over the per-sheet element budget");
96460
+ return reply.status(400).send({
96461
+ ok: false,
96462
+ code: "steel-manifest-over-budget",
96463
+ scope: "page",
96464
+ error: error.message,
96465
+ recovery: `Close this request and re-submit without that sheet, or split its content across sheets so each stays under ${error.limit} elements.`,
96466
+ total: null,
96467
+ limit: error.limit,
96468
+ bytes: null,
96469
+ byteLimit: null,
96470
+ // Complete by construction: this measures a manifest that was already built in full, so
96471
+ // there is no early stop and no subset — unlike the extractor's own refusal above.
96472
+ complete: true,
96473
+ measuredPages: error.pages.length,
96474
+ totalPages: error.pages.length,
96475
+ breaches: [{ scope: "page", limit: error.limit }],
96476
+ // `bytes: null` on every row, so a consumer sees ONE row shape under this code rather
96477
+ // than having to discover that the write path omits the key the read path always sends.
96478
+ overBudget: error.pages.slice(0, STEEL_READ_MAX_PAGES).map((row) => ({ sheet: row.sheet ?? `${row.sourceHash.slice(0, 8)} p.${row.page}`, sourceHash: row.sourceHash, page: row.page, count: row.count, bytes: null }))
96479
+ });
96480
+ }
96481
+ if (!(error instanceof SteelManifestCoverageError) && !(error instanceof SteelReadManifestInvalidError)) throw error;
96482
+ const diagnostic = error instanceof SteelManifestCoverageError ? error.diagnostic : void 0;
96483
+ req.log.warn({ projectId: project.id, requestId: request.id, diagnostic, error: error.message }, "steel manifest could not be represented deterministically");
96484
+ return reply.status(400).send({
96485
+ ok: false,
96486
+ code: "steel-manifest-extraction-failed",
96487
+ error: "the extracted drawing set could not be represented deterministically for a completion proof",
96488
+ // The client here is the terminal AI, and this condition is NOT user-authorable — the two
96489
+ // extraction passes disagreed about the same page bytes. Say so, so it stops rather than
96490
+ // retrying a call that will fail identically every time.
96491
+ recovery: "This is a defect in the drawing extraction, not something the drawing set can be edited to fix. Do not retry \u2014 report it with the diagnostic below.",
96492
+ ...diagnostic ? { diagnostic } : {}
96493
+ });
96494
+ }
96495
+ let writtenEtag;
96496
+ if (currentObj) {
96497
+ if (declaredTypeOf(currentObj) !== STEEL_V2) return reply.status(409).send({ ok: false, code: "steel-model-required", error: "the project contract is not steel.model/v2" });
96498
+ try {
96499
+ const written = await writeContractChecked(project.app, { ...currentObj, filter }, project.id, { origin: "internal", why: "server-owned steel source manifest" });
96500
+ writtenEtag = written.etag;
96501
+ clearApproval(project.id);
96502
+ broadcast(contractChangedWithReason(project.app, project.id, written.etag, written.storeRevision, "revision-read"));
96503
+ } catch (error) {
96504
+ if (error instanceof ContractError) return reply.status(400).send({ ok: false, code: error.code, error: error.message });
96505
+ throw error;
96506
+ }
96507
+ }
96508
+ const updated = patchRequest(request.id, {
96509
+ prepassReady: writtenEtag !== void 0,
96510
+ prepassEtag: writtenEtag,
96511
+ filterSaved: false,
96512
+ filterSavedEtag: void 0,
96513
+ steelManifestHash: stored2.manifestHash,
96514
+ steelSavedFilterHash: void 0
96177
96515
  });
96178
- }
96179
- if (error instanceof SteelFilterProcessError) {
96180
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId: error.diagnosticId, phase: error.phase, category: error.category, exitCode: error.exitCode, signal: error.signal, stderrSha256: error.stderrSha256 }, "steel manifest extraction failed");
96181
- return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: error.message, diagnosticId: error.diagnosticId });
96182
- }
96183
- const diagnosticId = (0, import_node_crypto42.randomUUID)();
96184
- req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "result-validation" }, "steel manifest extraction failed");
96185
- return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: "Steel Filter extraction failed.", diagnosticId });
96186
- }
96187
- filter = mergeWholeSetLayerCensus({ modelFilter: filter, evidenceFilter, priorFilter: currentObj?.filter });
96188
- if (currentObj?.filter !== void 0 && hasCanonicalMode(currentObj.filter)) {
96189
- filter = withPriorMode(filter, currentObj.filter);
96190
- } else {
96191
- filter = withUsableDefaultMode(filter);
96192
- }
96193
- filter = currentSteelFilterResult(filter);
96194
- const evidenceSheets = evidenceFilter && typeof evidenceFilter === "object" && !Array.isArray(evidenceFilter) && Array.isArray(evidenceFilter.sheets) ? evidenceFilter.sheets : [];
96195
- let stored2;
96196
- try {
96197
- const manifestPages = buildCompactManifestPages(pages, evidenceSheets, filter);
96198
- const scaleProposals = proposeSheetScales({
96199
- filter,
96200
- pages: manifestPages.map((page) => ({
96201
- sheet: page.sheet ?? "",
96202
- sourceHash: page.sourceHash,
96203
- pageId: page.id,
96204
- page: page.page,
96205
- ...page.viewKind === void 0 ? {} : { viewKind: page.viewKind }
96206
- })).filter((page) => page.sheet !== ""),
96207
- environment: project.environment,
96208
- // The SAME operation deadline the extraction ran under, WITH the clock it is expressed in —
96209
- // one object, because they are meaningless apart: this deadline is a `performance.now()`
96210
- // value, and comparing it against a `Date.now()` clock would exceed the budget on every
96211
- // sheet and silently return the reader to hand-fitting. And the same VARIABLE, not the same
96212
- // arithmetic re-derived: `steelOperationDeadlineAt` exists so that sum has one home.
96213
- budget: { deadlineAt: hardDeadline, now: now2 }
96516
+ if (!updated) return reply.status(409).send({ ok: false, error: "the revision request changed while publishing its steel manifest" });
96517
+ broadcast({ type: "request-added", request: requestView(updated) });
96518
+ return {
96519
+ ok: true,
96520
+ manifestHash: stored2.manifestHash,
96521
+ etag: writtenEtag ?? null,
96522
+ requiresCheckpointCreate: !currentObj,
96523
+ pages: stored2.manifest.pages,
96524
+ filter,
96525
+ ...stored2.scaleProposals === void 0 ? {} : { scaleProposals: stored2.scaleProposals }
96526
+ };
96527
+ }, {
96528
+ // A retry must not wait 60 seconds behind the long inventory and then start a second scan.
96529
+ // The first handler keeps running after an HTTP disconnect; this projection makes later calls
96530
+ // fail fast as busy until that handler publishes the durable checkpoint.
96531
+ label: "inspecting steel drawings",
96532
+ expectedMs: 2 * 60 * 6e4
96214
96533
  });
96215
- stored2 = writeSteelReadManifest({
96216
- version: 1,
96217
- extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
96218
- requestId: request.id,
96219
- projectId: project.id,
96220
- appId: project.app,
96221
- sources: sources.manifestSources,
96222
- pages: manifestPages,
96223
- filter,
96224
- candidatesRepr: "v2-compact",
96225
- // Minted in the SAME write as the merged filter, so the marker and the thing it describes
96226
- // cannot disagree. A manifest without it is a pre-slice-2a, model-pages-only census: it
96227
- // still reads and audits, it simply cannot carry a layer sign-off until it is regenerated.
96228
- censusScope: "whole-set"
96229
- }, void 0, { scaleProposals });
96230
96534
  } catch (error) {
96231
- if (error instanceof SteelReadPageBudgetError) {
96232
- req.log.warn({ projectId: project.id, requestId: request.id, pages: error.pages.slice(0, 20) }, "steel manifest sheet over the per-sheet element budget");
96233
- return reply.status(400).send({
96234
- ok: false,
96235
- code: "steel-manifest-over-budget",
96236
- scope: "page",
96237
- error: error.message,
96238
- recovery: `Close this request and re-submit without that sheet, or split its content across sheets so each stays under ${error.limit} elements.`,
96239
- total: null,
96240
- limit: error.limit,
96241
- bytes: null,
96242
- byteLimit: null,
96243
- // Complete by construction: this measures a manifest that was already built in full, so
96244
- // there is no early stop and no subset — unlike the extractor's own refusal above.
96245
- complete: true,
96246
- measuredPages: error.pages.length,
96247
- totalPages: error.pages.length,
96248
- breaches: [{ scope: "page", limit: error.limit }],
96249
- // `bytes: null` on every row, so a consumer sees ONE row shape under this code rather
96250
- // than having to discover that the write path omits the key the read path always sends.
96251
- overBudget: error.pages.slice(0, STEEL_READ_MAX_PAGES).map((row) => ({ sheet: row.sheet ?? `${row.sourceHash.slice(0, 8)} p.${row.page}`, sourceHash: row.sourceHash, page: row.page, count: row.count, bytes: null }))
96252
- });
96253
- }
96254
- if (!(error instanceof SteelManifestCoverageError) && !(error instanceof SteelReadManifestInvalidError)) throw error;
96255
- const diagnostic = error instanceof SteelManifestCoverageError ? error.diagnostic : void 0;
96256
- req.log.warn({ projectId: project.id, requestId: request.id, diagnostic, error: error.message }, "steel manifest could not be represented deterministically");
96257
- return reply.status(400).send({
96535
+ if (!(error instanceof LifecycleLockBusyError)) throw error;
96536
+ const retryAfterMs = Math.max(1e3, Math.min(3e4, error.busy.remainingMs ?? 5e3));
96537
+ reply.header("Retry-After", String(Math.ceil(retryAfterMs / 1e3)));
96538
+ return reply.status(409).send({
96258
96539
  ok: false,
96259
- code: "steel-manifest-extraction-failed",
96260
- error: "the extracted drawing set could not be represented deterministically for a completion proof",
96261
- // The client here is the terminal AI, and this condition is NOT user-authorable — the two
96262
- // extraction passes disagreed about the same page bytes. Say so, so it stops rather than
96263
- // retrying a call that will fail identically every time.
96264
- recovery: "This is a defect in the drawing extraction, not something the drawing set can be edited to fix. Do not retry \u2014 report it with the diagnostic below.",
96265
- ...diagnostic ? { diagnostic } : {}
96540
+ code: "steel-manifest-preparation-busy",
96541
+ error: "This drawing set is already being inspected.",
96542
+ recovery: "Wait, then retry this same request. The active inspection will publish a reusable checkpoint when it finishes.",
96543
+ retryAfterMs
96266
96544
  });
96267
96545
  }
96268
- let writtenEtag;
96269
- if (currentObj) {
96270
- if (declaredTypeOf(currentObj) !== STEEL_V2) return reply.status(409).send({ ok: false, code: "steel-model-required", error: "the project contract is not steel.model/v2" });
96271
- try {
96272
- const written = await writeContractChecked(project.app, { ...currentObj, filter }, project.id, { origin: "internal", why: "server-owned steel source manifest" });
96273
- writtenEtag = written.etag;
96274
- clearApproval(project.id);
96275
- broadcast(contractChangedWithReason(project.app, project.id, written.etag, written.storeRevision, "revision-read"));
96276
- } catch (error) {
96277
- if (error instanceof ContractError) return reply.status(400).send({ ok: false, code: error.code, error: error.message });
96278
- throw error;
96279
- }
96280
- }
96281
- const updated = patchRequest(request.id, {
96282
- prepassReady: writtenEtag !== void 0,
96283
- prepassEtag: writtenEtag,
96284
- filterSaved: false,
96285
- filterSavedEtag: void 0,
96286
- steelManifestHash: stored2.manifestHash,
96287
- steelSavedFilterHash: void 0
96288
- });
96289
- if (!updated) return reply.status(409).send({ ok: false, error: "the revision request changed while publishing its steel manifest" });
96290
- broadcast({ type: "request-added", request: requestView(updated) });
96291
- return {
96292
- ok: true,
96293
- manifestHash: stored2.manifestHash,
96294
- etag: writtenEtag ?? null,
96295
- requiresCheckpointCreate: !currentObj,
96296
- pages: stored2.manifest.pages,
96297
- filter,
96298
- ...stored2.scaleProposals === void 0 ? {} : { scaleProposals: stored2.scaleProposals }
96299
- };
96300
- })
96546
+ }
96301
96547
  );
96302
96548
  app.get(
96303
96549
  "/api/projects/:id/revision-requests/:reqId/steel-manifest",
@@ -116286,7 +116532,18 @@ async function finish(deps, lease, patch2, options = {}) {
116286
116532
  }
116287
116533
  cleanupMcpConfig(lease.leaseId);
116288
116534
  if (contained) {
116289
- const leaseTerminalRefusal = lease.terminalRefusalCode === "steel-manifest-extraction-timeout";
116535
+ let leaseTerminalRefusal;
116536
+ try {
116537
+ leaseTerminalRefusal = ((deps.readLease ?? getLease)(lease.leaseId) ?? lease).terminalRefusalCode === "steel-manifest-extraction-timeout";
116538
+ } catch (error) {
116539
+ locallyRevokedRelayLeases.add(lease.leaseId);
116540
+ try {
116541
+ revokeLeaseRelay(lease.leaseId, lease.generation);
116542
+ } catch {
116543
+ }
116544
+ console.error(`[terminal-run] could not verify terminal refusal authority for ${lease.requestId}; lease held:`, error);
116545
+ return;
116546
+ }
116290
116547
  let requestTerminalRefusal = false;
116291
116548
  try {
116292
116549
  requestTerminalRefusal = deps.getRequest(lease.requestId)?.run?.refusalCode === "steel-manifest-extraction-timeout";
@@ -116933,10 +117190,36 @@ function registerTerminalRunRoutes(app, deps) {
116933
117190
  error: "floless can\u2019t compose an instruction for this request, so there is nothing to hand a terminal AI. Clear it and queue it again."
116934
117191
  });
116935
117192
  }
116936
- const req = Object.freeze({ ...resolvedRequest });
117193
+ let req = Object.freeze({ ...resolvedRequest });
116937
117194
  const eligibility = deps.eligibility?.(req) ?? runEligibilityFor(req);
116938
117195
  if (!eligibility.runnable) return reply.status(400).send({ ok: false, error: eligibility.why, code: "not-runnable" });
116939
117196
  const policy = eligibility.policy;
117197
+ if (req.type === "revision-read" && req.status === "failed" && hasRetryableInspectionRefusal(req)) {
117198
+ try {
117199
+ const migrated = deps.patchRequestDurable(req.id, {
117200
+ status: "pending",
117201
+ refusalCode: void 0,
117202
+ steelPreparationTimeout: void 0,
117203
+ error: void 0
117204
+ });
117205
+ if (!migrated) {
117206
+ return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "The drawing read changed before its interrupted inspection could resume." });
117207
+ }
117208
+ const enriched = deps.resolveRequest ? deps.resolveRequest(migrated) : migrated;
117209
+ if (!enriched) {
117210
+ return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "The drawing read changed before its interrupted inspection could resume." });
117211
+ }
117212
+ req = Object.freeze({ ...enriched });
117213
+ deps.broadcast({ type: "requests-changed" });
117214
+ } catch (error) {
117215
+ request.log.error({ err: String(error) }, "legacy inspection retry migration failed");
117216
+ return reply.status(503).send({
117217
+ ok: false,
117218
+ code: "revision-request-unavailable",
117219
+ error: "FloLess could not make the interrupted drawing inspection resumable. Restart FloLess and try again."
117220
+ });
117221
+ }
117222
+ }
116940
117223
  const requestPrompt = deps.buildPrompt(req);
116941
117224
  if (!requestPrompt.trim()) {
116942
117225
  return reply.status(400).send({