@floless/app 0.138.0 → 0.138.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/floless-server.cjs +1219 -604
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +5 -1
- package/dist/web/aware.js +85 -20
- package/dist/web/commands-shell.js +5 -0
- package/dist/web/workspaces.js +42 -0
- package/package.json +1 -1
package/dist/floless-server.cjs
CHANGED
|
@@ -51021,6 +51021,7 @@ function busyMeta(owner2) {
|
|
|
51021
51021
|
function subjectFor(kind2) {
|
|
51022
51022
|
if (kind2 === "project") return "This project";
|
|
51023
51023
|
if (kind2 === "app") return "This workflow";
|
|
51024
|
+
if (kind2 === "steel-extraction") return "Steel drawing preparation";
|
|
51024
51025
|
return "This app";
|
|
51025
51026
|
}
|
|
51026
51027
|
function remainingPhrase(remainingMs) {
|
|
@@ -51331,10 +51332,12 @@ async function acquire(path, kind2, key3, options) {
|
|
|
51331
51332
|
const generation = staleGeneration(path);
|
|
51332
51333
|
if (generation) {
|
|
51333
51334
|
if (retireStaleLock(path, generation)) continue;
|
|
51335
|
+
if (options.failFast) throw busyError(kind2, key3, null);
|
|
51334
51336
|
} else {
|
|
51335
51337
|
const owner2 = readOwner(path);
|
|
51336
51338
|
const startedMs = owner2 ? Date.parse(owner2.acquiredAt) : NaN;
|
|
51337
51339
|
const expected = owner2 ? busyMeta(owner2).expectedMs : null;
|
|
51340
|
+
if (options.failFast) throw busyError(kind2, key3, owner2);
|
|
51338
51341
|
if (owner2 && expected != null && startedMs + expected > deadline) {
|
|
51339
51342
|
throw busyError(kind2, key3, owner2);
|
|
51340
51343
|
}
|
|
@@ -51351,6 +51354,9 @@ async function withLifecycleLock(kind2, key3, fn, options = {}) {
|
|
|
51351
51354
|
const budget = options.timeoutMsForTest ?? TIMEOUT_MS;
|
|
51352
51355
|
const enteredAt = Date.now();
|
|
51353
51356
|
const { at: freeAt, blocker } = localProjectedFreeAt(token2, enteredAt);
|
|
51357
|
+
if (options.failFast && localIntents.get(token2)?.size) {
|
|
51358
|
+
throw blocker ? localBusyError(kind2, key3, freeAt, blocker, enteredAt) : busyError(kind2, key3, null);
|
|
51359
|
+
}
|
|
51354
51360
|
if (freeAt > enteredAt + budget) {
|
|
51355
51361
|
throw blocker ? localBusyError(kind2, key3, freeAt, blocker, enteredAt) : busyError(kind2, key3, null);
|
|
51356
51362
|
}
|
|
@@ -61975,40 +61981,46 @@ function componentsOf(intervals) {
|
|
|
61975
61981
|
}
|
|
61976
61982
|
return merged;
|
|
61977
61983
|
}
|
|
61978
|
-
function
|
|
61979
|
-
const
|
|
61980
|
-
|
|
61981
|
-
|
|
61982
|
-
|
|
61983
|
-
|
|
61984
|
-
|
|
61985
|
-
|
|
61986
|
-
|
|
61987
|
-
|
|
61988
|
-
|
|
61989
|
-
|
|
61990
|
-
|
|
61991
|
-
|
|
61992
|
-
|
|
61993
|
-
|
|
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
|
-
}
|
|
61984
|
+
function rowsOfTexts(texts) {
|
|
61985
|
+
const sorted = [...texts].sort((a, b) => a.acrossPt - b.acrossPt || byCodeUnit(a.textId, b.textId));
|
|
61986
|
+
const rows2 = [];
|
|
61987
|
+
let current = [];
|
|
61988
|
+
let anchor = 0;
|
|
61989
|
+
for (const text6 of sorted) {
|
|
61990
|
+
if (!current.length) {
|
|
61991
|
+
current = [text6];
|
|
61992
|
+
anchor = text6.acrossPt;
|
|
61993
|
+
continue;
|
|
61994
|
+
}
|
|
61995
|
+
if (text6.acrossPt - anchor <= ROW_TOL_PT) current.push(text6);
|
|
61996
|
+
else {
|
|
61997
|
+
rows2.push(current);
|
|
61998
|
+
current = [text6];
|
|
61999
|
+
anchor = text6.acrossPt;
|
|
62001
62000
|
}
|
|
62002
|
-
best[i] = winner;
|
|
62003
62001
|
}
|
|
62004
|
-
|
|
62005
|
-
for (
|
|
62006
|
-
|
|
62007
|
-
|
|
62008
|
-
|
|
62002
|
+
if (current.length) rows2.push(current);
|
|
62003
|
+
for (const row of rows2) row.sort((a, b) => a.alongPt - b.alongPt || byCodeUnit(a.textId, b.textId));
|
|
62004
|
+
return rows2;
|
|
62005
|
+
}
|
|
62006
|
+
function tilingRuns(row, selected, familyId) {
|
|
62007
|
+
const runs = [];
|
|
62008
|
+
let current = [];
|
|
62009
|
+
const flush = () => {
|
|
62010
|
+
if (current.length >= MIN_CHAIN) runs.push(current);
|
|
62011
|
+
current = [];
|
|
62012
|
+
};
|
|
62013
|
+
for (const text6 of row) {
|
|
62014
|
+
const hypothesis = selected.get(text6.textId);
|
|
62015
|
+
if (!hypothesis || hypothesis.familyId !== familyId) {
|
|
62016
|
+
flush();
|
|
62017
|
+
continue;
|
|
62009
62018
|
}
|
|
62019
|
+
if (current.length && current[current.length - 1].j !== hypothesis.i) flush();
|
|
62020
|
+
current.push(hypothesis);
|
|
62010
62021
|
}
|
|
62011
|
-
|
|
62022
|
+
flush();
|
|
62023
|
+
return runs.sort((a, b) => b.length - a.length || a[0].i - b[0].i || byCodeUnit(a[0].textId, b[0].textId));
|
|
62012
62024
|
}
|
|
62013
62025
|
function buildCandidate(args) {
|
|
62014
62026
|
const { component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed } = args;
|
|
@@ -62034,60 +62046,155 @@ function buildCandidate(args) {
|
|
|
62034
62046
|
if (!now2) return null;
|
|
62035
62047
|
if (now2.familyId !== was.familyId || now2.i !== was.i || now2.j !== was.j) return null;
|
|
62036
62048
|
}
|
|
62037
|
-
|
|
62038
|
-
|
|
62039
|
-
|
|
62040
|
-
|
|
62041
|
-
|
|
62042
|
-
|
|
62043
|
-
const
|
|
62044
|
-
|
|
62045
|
-
|
|
62046
|
-
|
|
62047
|
-
|
|
62048
|
-
|
|
62049
|
-
|
|
62050
|
-
|
|
62049
|
+
const buildChains = (value, assignment) => {
|
|
62050
|
+
const chains2 = { x: null, y: null };
|
|
62051
|
+
const chainResidual = { x: 0, y: 0 };
|
|
62052
|
+
const members = { x: null, y: null };
|
|
62053
|
+
const anchorElementIds = [];
|
|
62054
|
+
let implausible = false;
|
|
62055
|
+
for (const { family, axes } of ordered) {
|
|
62056
|
+
const seats = args.familyTexts.get(family.familyId) ?? EMPTY_SEATING;
|
|
62057
|
+
if (!seats.seats.length) continue;
|
|
62058
|
+
let chain2 = null;
|
|
62059
|
+
let sawImplausible = false;
|
|
62060
|
+
let trims = 0;
|
|
62061
|
+
const longestFirst = (a, b) => b.length - a.length || a[0].i - b[0].i || byCodeUnit(a[0].textId, b[0].textId);
|
|
62062
|
+
for (const row of seats.rows) {
|
|
62063
|
+
const queue = tilingRuns(row, assignment, family.familyId);
|
|
62064
|
+
while (queue.length) {
|
|
62065
|
+
const members2 = queue.shift();
|
|
62066
|
+
const fromPt2 = axes[members2[0].i].atRaw;
|
|
62067
|
+
const toPt2 = axes[members2[members2.length - 1].j].atRaw;
|
|
62068
|
+
const used = new Set(members2.map((m) => m.textId));
|
|
62069
|
+
let acrossLo = Infinity;
|
|
62070
|
+
let acrossHi = -Infinity;
|
|
62071
|
+
for (const m of members2) {
|
|
62072
|
+
const seat2 = seats.byId.get(m.textId);
|
|
62073
|
+
acrossLo = Math.min(acrossLo, seat2.acrossPt);
|
|
62074
|
+
acrossHi = Math.max(acrossHi, seat2.acrossPt);
|
|
62075
|
+
}
|
|
62076
|
+
let barrier = null;
|
|
62077
|
+
for (const seat2 of seats.seats) {
|
|
62078
|
+
if (used.has(seat2.textId)) continue;
|
|
62079
|
+
if (!(seat2.alongPt > fromPt2 && seat2.alongPt < toPt2)) continue;
|
|
62080
|
+
if (!(seat2.acrossPt > acrossLo - BARRIER_TOL_PT && seat2.acrossPt < acrossHi + BARRIER_TOL_PT)) continue;
|
|
62081
|
+
if (!barrier || seat2.alongPt < barrier.alongPt || seat2.alongPt === barrier.alongPt && byCodeUnit(seat2.textId, barrier.textId) < 0) barrier = seat2;
|
|
62082
|
+
}
|
|
62083
|
+
if (!barrier) {
|
|
62084
|
+
if (members2.some((m) => {
|
|
62085
|
+
const mm3 = mmUnder(m, unit2);
|
|
62086
|
+
return mm3 < MIN_BAY_MM || mm3 > MAX_BAY_MM;
|
|
62087
|
+
})) {
|
|
62088
|
+
sawImplausible = true;
|
|
62089
|
+
continue;
|
|
62090
|
+
}
|
|
62091
|
+
const totalMm = members2.reduce((sum2, m) => sum2 + mmUnder(m, unit2), 0);
|
|
62092
|
+
const residual = members2.reduce((sum2, m) => sum2 + Math.abs(mmUnder(m, unit2) / value - m.spanPt), 0);
|
|
62093
|
+
const found = { from: members2[0].i, to: members2[members2.length - 1].j, totalMm, members: members2, residual };
|
|
62094
|
+
if (!chain2 || found.members.length > chain2.members.length || found.members.length === chain2.members.length && found.residual < chain2.residual) chain2 = found;
|
|
62095
|
+
continue;
|
|
62096
|
+
}
|
|
62097
|
+
if (chain2 && members2.length <= chain2.members.length) continue;
|
|
62098
|
+
if (trims >= MAX_RUN_TRIMS) continue;
|
|
62099
|
+
trims += 1;
|
|
62100
|
+
const at = barrier.alongPt;
|
|
62101
|
+
for (const half of [
|
|
62102
|
+
members2.filter((m) => axes[m.j].atRaw <= at),
|
|
62103
|
+
members2.filter((m) => axes[m.i].atRaw >= at)
|
|
62104
|
+
]) {
|
|
62105
|
+
if (half.length >= MIN_CHAIN) queue.push(half);
|
|
62106
|
+
}
|
|
62107
|
+
queue.sort(longestFirst);
|
|
62108
|
+
}
|
|
62109
|
+
}
|
|
62110
|
+
if (!chain2) {
|
|
62111
|
+
implausible = implausible || sawImplausible;
|
|
62112
|
+
continue;
|
|
62113
|
+
}
|
|
62114
|
+
const memberSpansMm = chain2.members.map((h) => mmUnder(h, unit2));
|
|
62115
|
+
const fromLabel = axes[chain2.from].label;
|
|
62116
|
+
const toLabel = axes[chain2.to].label;
|
|
62117
|
+
if (!usableLabel(fromLabel) || !usableLabel(toLabel)) continue;
|
|
62118
|
+
const fromPt = axes[chain2.from].atRaw;
|
|
62119
|
+
const toPt = axes[chain2.to].atRaw;
|
|
62120
|
+
const runPt = toPt - fromPt;
|
|
62121
|
+
const memberIds = new Set(chain2.members.map((m) => m.textId));
|
|
62122
|
+
const centreAllowance = Math.max(runPt * ANCHOR_CENTRE_FRAC, ANCHOR_CENTRE_MIN_PT);
|
|
62123
|
+
const seatOf = seats.byId;
|
|
62124
|
+
const anchor = printed.filter((p) => {
|
|
62125
|
+
const mm3 = p.explicitUnit === "mm" ? p.magnitude : p.magnitude * (unit2 === "cm" ? 10 : 1);
|
|
62126
|
+
if (mm3 !== chain2.totalMm || Math.abs(mm3 / value - runPt) > METRIC_INLIER_TOL_PT) return false;
|
|
62127
|
+
if (memberIds.has(p.id)) return false;
|
|
62128
|
+
const seat2 = seatOf.get(p.id);
|
|
62129
|
+
return !!seat2 && Math.abs(seat2.alongPt - (fromPt + toPt) / 2) <= centreAllowance;
|
|
62130
|
+
}).sort((a, b) => byCodeUnit(a.id, b.id))[0] ?? null;
|
|
62131
|
+
if (anchor) anchorElementIds.push(anchor.id);
|
|
62132
|
+
const evidence = {
|
|
62133
|
+
familyId: family.familyId,
|
|
62134
|
+
fromLabel,
|
|
62135
|
+
toLabel,
|
|
62136
|
+
length: chain2.members.length,
|
|
62137
|
+
worldTotalMm: chain2.totalMm,
|
|
62138
|
+
anchoredByOverall: anchor !== null,
|
|
62139
|
+
anchorElementId: anchor ? anchor.id : null,
|
|
62140
|
+
memberSpansMm: memberSpansMm.slice(0, MAX_CHAIN_MEMBERS)
|
|
62141
|
+
};
|
|
62142
|
+
const held2 = family.axis === "x" ? chains2.x : chains2.y;
|
|
62143
|
+
const heldResidual = family.axis === "x" ? chainResidual.x : chainResidual.y;
|
|
62144
|
+
if (!held2 || evidence.length > held2.length || evidence.length === held2.length && chain2.residual < heldResidual) {
|
|
62145
|
+
if (family.axis === "x") {
|
|
62146
|
+
chains2.x = evidence;
|
|
62147
|
+
chainResidual.x = chain2.residual;
|
|
62148
|
+
members.x = chain2.members;
|
|
62149
|
+
} else {
|
|
62150
|
+
chains2.y = evidence;
|
|
62151
|
+
chainResidual.y = chain2.residual;
|
|
62152
|
+
members.y = chain2.members;
|
|
62153
|
+
}
|
|
62154
|
+
}
|
|
62051
62155
|
}
|
|
62052
|
-
|
|
62053
|
-
|
|
62054
|
-
|
|
62055
|
-
|
|
62056
|
-
|
|
62057
|
-
|
|
62058
|
-
|
|
62059
|
-
|
|
62060
|
-
|
|
62061
|
-
|
|
62062
|
-
|
|
62063
|
-
|
|
62064
|
-
|
|
62065
|
-
|
|
62066
|
-
|
|
62067
|
-
|
|
62068
|
-
|
|
62069
|
-
|
|
62070
|
-
|
|
62071
|
-
|
|
62072
|
-
|
|
62073
|
-
|
|
62074
|
-
if (
|
|
62156
|
+
return { chains: chains2, chainResidual, members, anchorElementIds, implausible };
|
|
62157
|
+
};
|
|
62158
|
+
const admitted = buildChains(mmPerPx, refined);
|
|
62159
|
+
if (!admitted.chains.x && !admitted.chains.y) return admitted.implausible ? "span-implausible" : "no-chain";
|
|
62160
|
+
const chainMembers = [...admitted.members.x ?? [], ...admitted.members.y ?? []];
|
|
62161
|
+
let chainNumerator = 0;
|
|
62162
|
+
let chainDenominator = 0;
|
|
62163
|
+
for (const h of chainMembers) {
|
|
62164
|
+
const mm3 = mmUnder(h, unit2);
|
|
62165
|
+
chainNumerator += mm3 * h.spanPt;
|
|
62166
|
+
chainDenominator += mm3 * mm3;
|
|
62167
|
+
}
|
|
62168
|
+
if (!(chainDenominator > 0)) return null;
|
|
62169
|
+
const chainQ = chainNumerator / chainDenominator;
|
|
62170
|
+
if (!finite3(chainQ) || chainQ <= 0) return null;
|
|
62171
|
+
const emitted = round6(1 / chainQ);
|
|
62172
|
+
if (!finite3(emitted) || emitted <= 0 || emitted < lo || emitted > hi) return null;
|
|
62173
|
+
const atEmitted = selectPerText(hypotheses, unit2, emitted);
|
|
62174
|
+
const rebuilt = buildChains(emitted, atEmitted);
|
|
62175
|
+
if (!rebuilt.chains.x && !rebuilt.chains.y) return rebuilt.implausible ? "span-implausible" : "no-chain";
|
|
62176
|
+
const runIdentity = (members) => (members ?? []).map((m) => `${m.textId} ${m.familyId} ${m.i} ${m.j}`).join(" | ");
|
|
62177
|
+
if (runIdentity(rebuilt.members.x) !== runIdentity(admitted.members.x)) return null;
|
|
62178
|
+
if (runIdentity(rebuilt.members.y) !== runIdentity(admitted.members.y)) return null;
|
|
62179
|
+
const chains = rebuilt.chains;
|
|
62180
|
+
const unrounded = 1 / chainQ;
|
|
62181
|
+
const rankResidual = chainMembers.reduce((sum2, m) => sum2 + Math.abs(mmUnder(m, unit2) / unrounded - m.spanPt), 0);
|
|
62075
62182
|
return {
|
|
62076
62183
|
candidate: {
|
|
62077
62184
|
standard: `1:${ratio}`,
|
|
62078
62185
|
unit: unit2,
|
|
62079
62186
|
componentIndex,
|
|
62080
|
-
mmPerPx:
|
|
62081
|
-
plottedAtPct: Number((100 * nominal /
|
|
62082
|
-
stringsExplained:
|
|
62187
|
+
mmPerPx: emitted,
|
|
62188
|
+
plottedAtPct: Number((100 * nominal / emitted).toFixed(2)),
|
|
62189
|
+
stringsExplained: atEmitted.size,
|
|
62083
62190
|
chainX: chains.x ? chains.x.length : 0,
|
|
62084
62191
|
chainY: chains.y ? chains.y.length : 0,
|
|
62085
62192
|
componentsSurvived: 1
|
|
62086
62193
|
},
|
|
62087
62194
|
chains,
|
|
62088
|
-
evidenceElementIds: [...
|
|
62089
|
-
anchorElementIds: [...new Set(anchorElementIds)].sort(byCodeUnit),
|
|
62090
|
-
|
|
62195
|
+
evidenceElementIds: [...atEmitted.keys()].sort(byCodeUnit),
|
|
62196
|
+
anchorElementIds: [...new Set(rebuilt.anchorElementIds)].sort(byCodeUnit),
|
|
62197
|
+
chainResidual: rankResidual
|
|
62091
62198
|
};
|
|
62092
62199
|
}
|
|
62093
62200
|
function selectPerText(hypotheses, unit2, mmPerPx) {
|
|
@@ -62104,11 +62211,23 @@ function selectPerText(hypotheses, unit2, mmPerPx) {
|
|
|
62104
62211
|
for (const [id, held2] of best) out.set(id, held2.hypothesis);
|
|
62105
62212
|
return out;
|
|
62106
62213
|
}
|
|
62214
|
+
function compareChainScores(a, b) {
|
|
62215
|
+
const weaker = weakerChain(b) - weakerChain(a);
|
|
62216
|
+
if (weaker !== 0) return weaker;
|
|
62217
|
+
const stronger = strongerChain(b) - strongerChain(a);
|
|
62218
|
+
if (stronger !== 0) return stronger;
|
|
62219
|
+
if (fitOf(a) < fitOf(b)) return -1;
|
|
62220
|
+
if (fitOf(a) > fitOf(b)) return 1;
|
|
62221
|
+
return 0;
|
|
62222
|
+
}
|
|
62223
|
+
function orderSurvivors(a, b) {
|
|
62224
|
+
return compareChainScores(scoreOf(a), scoreOf(b));
|
|
62225
|
+
}
|
|
62107
62226
|
function rankSurvivors(a, b) {
|
|
62108
|
-
return
|
|
62227
|
+
return orderSurvivors(a, b) || byCodeUnit(survivorIdentity(a), survivorIdentity(b));
|
|
62109
62228
|
}
|
|
62110
62229
|
function separatesSurvivors(a, b) {
|
|
62111
|
-
return
|
|
62230
|
+
return orderSurvivors(a, b) !== 0;
|
|
62112
62231
|
}
|
|
62113
62232
|
function fitMetricScale(input) {
|
|
62114
62233
|
const empty = { leader: null, runnersUp: [], tied: [], hypothesesConsidered: 0 };
|
|
@@ -62165,6 +62284,26 @@ function fitMetricScale(input) {
|
|
|
62165
62284
|
if (!hypotheses.length) {
|
|
62166
62285
|
return { ...empty, refusal: { code: "out-of-band", detail: "no metric dimension string could be matched to any axis pair in this scope" } };
|
|
62167
62286
|
}
|
|
62287
|
+
const familyTexts = /* @__PURE__ */ new Map();
|
|
62288
|
+
for (const { family, axes } of ordered) {
|
|
62289
|
+
const along = family.axis === "x" ? 0 : 1;
|
|
62290
|
+
const across = along === 0 ? 1 : 0;
|
|
62291
|
+
const lo = axes[0].atRaw;
|
|
62292
|
+
const hi = axes[axes.length - 1].atRaw;
|
|
62293
|
+
const seats = [];
|
|
62294
|
+
for (const token2 of tokens) {
|
|
62295
|
+
const acrossPt = token2.centre[across] - family.at;
|
|
62296
|
+
if (Math.abs(acrossPt) > METRIC_MAX_ACROSS_PT) continue;
|
|
62297
|
+
const alongPt = token2.centre[along];
|
|
62298
|
+
if (alongPt < lo - 2 || alongPt > hi + 2) continue;
|
|
62299
|
+
seats.push({ textId: token2.id, acrossPt, alongPt });
|
|
62300
|
+
}
|
|
62301
|
+
familyTexts.set(family.familyId, {
|
|
62302
|
+
seats,
|
|
62303
|
+
rows: rowsOfTexts(seats),
|
|
62304
|
+
byId: new Map(seats.map((seat2) => [seat2.textId, seat2]))
|
|
62305
|
+
});
|
|
62306
|
+
}
|
|
62168
62307
|
const printed = tokens.map((t) => ({ id: t.id, magnitude: t.parsed.magnitude, explicitUnit: t.parsed.explicitUnit }));
|
|
62169
62308
|
const survivors = [];
|
|
62170
62309
|
let overflowed = false;
|
|
@@ -62192,10 +62331,10 @@ function fitMetricScale(input) {
|
|
|
62192
62331
|
continue;
|
|
62193
62332
|
}
|
|
62194
62333
|
if (components.length) sawInBand = true;
|
|
62195
|
-
components.sort((a, b) =>
|
|
62334
|
+
components.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
62196
62335
|
const perReading = [];
|
|
62197
62336
|
components.forEach((component, componentIndex) => {
|
|
62198
|
-
const built = buildCandidate({ component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed });
|
|
62337
|
+
const built = buildCandidate({ component, componentIndex, ratio, unit: unit2, nominal, lo, hi, hypotheses, ordered, printed, familyTexts });
|
|
62199
62338
|
if (built === "span-implausible") {
|
|
62200
62339
|
spanRejected = true;
|
|
62201
62340
|
return;
|
|
@@ -62220,7 +62359,7 @@ function fitMetricScale(input) {
|
|
|
62220
62359
|
if (sawInBand) {
|
|
62221
62360
|
return { ...empty, hypothesesConsidered: hypotheses.length, refusal: { code: "no-chain", detail: "dimension strings agree on a scale, but none of them form a run of consecutive bays, so there is no dimension chain to read this sheet from" } };
|
|
62222
62361
|
}
|
|
62223
|
-
return { ...empty, hypothesesConsidered: hypotheses.length, refusal: { code: "out-of-band", detail: `no scale within ${Math.round((MAX_PLOT_SCALING - 1) * 100)}% of a ratio this sheet prints
|
|
62362
|
+
return { ...empty, hypothesesConsidered: hypotheses.length, refusal: { code: "out-of-band", detail: `no scale within ${Math.round((MAX_PLOT_SCALING - 1) * 100)}% of a ratio this sheet prints has ${METRIC_MIN_INLIERS} or more of its dimension strings agreeing on it` } };
|
|
62224
62363
|
}
|
|
62225
62364
|
survivors.sort(rankSurvivors);
|
|
62226
62365
|
const best = survivors[0];
|
|
@@ -62252,7 +62391,7 @@ function fitMetricScale(input) {
|
|
|
62252
62391
|
hypothesesConsidered: hypotheses.length
|
|
62253
62392
|
};
|
|
62254
62393
|
}
|
|
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,
|
|
62394
|
+
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, fitOf, scoreOf;
|
|
62256
62395
|
var init_steel_scale_metric = __esm({
|
|
62257
62396
|
"steel-scale-metric.ts"() {
|
|
62258
62397
|
"use strict";
|
|
@@ -62262,6 +62401,11 @@ var init_steel_scale_metric = __esm({
|
|
|
62262
62401
|
METRIC_MIN_INLIERS = 3;
|
|
62263
62402
|
METRIC_MIN_SPAN_PT = 5;
|
|
62264
62403
|
METRIC_MAX_ACROSS_PT = 200;
|
|
62404
|
+
ROW_TOL_PT = 3;
|
|
62405
|
+
BARRIER_TOL_PT = 8;
|
|
62406
|
+
ANCHOR_CENTRE_FRAC = 0.05;
|
|
62407
|
+
ANCHOR_CENTRE_MIN_PT = 6;
|
|
62408
|
+
MAX_RUN_TRIMS = 64;
|
|
62265
62409
|
MAX_PLOT_SCALING = 1.33;
|
|
62266
62410
|
MIN_BAY_MM = 1500;
|
|
62267
62411
|
MAX_BAY_MM = 3e4;
|
|
@@ -62283,10 +62427,12 @@ var init_steel_scale_metric = __esm({
|
|
|
62283
62427
|
round6 = (n) => Number(n.toFixed(6));
|
|
62284
62428
|
mmUnder = (h, unit2) => h.explicitUnit === "mm" ? h.magnitude : h.magnitude * (unit2 === "cm" ? 10 : 1);
|
|
62285
62429
|
usableLabel = (label2) => typeof label2 === "string" && label2.length > 0 && label2.length <= MAX_AXIS_LABEL_CHARS;
|
|
62286
|
-
|
|
62287
|
-
weakerChain = (s) => Math.min(s.
|
|
62288
|
-
strongerChain = (s) => Math.max(s.
|
|
62430
|
+
EMPTY_SEATING = Object.freeze({ seats: [], rows: [], byId: /* @__PURE__ */ new Map() });
|
|
62431
|
+
weakerChain = (s) => Math.min(s.chainX, s.chainY);
|
|
62432
|
+
strongerChain = (s) => Math.max(s.chainX, s.chainY);
|
|
62289
62433
|
survivorIdentity = (s) => `${s.candidate.standard} ${s.candidate.unit} ${String(s.candidate.componentIndex).padStart(4, "0")}`;
|
|
62434
|
+
fitOf = (s) => Number.isFinite(s.chainResidual) ? s.chainResidual : Infinity;
|
|
62435
|
+
scoreOf = (s) => ({ chainX: s.candidate.chainX, chainY: s.candidate.chainY, chainResidual: s.chainResidual });
|
|
62290
62436
|
}
|
|
62291
62437
|
});
|
|
62292
62438
|
|
|
@@ -62738,20 +62884,18 @@ function proposeOne(elements, identity, declaredGrammar, spent, environment, det
|
|
|
62738
62884
|
});
|
|
62739
62885
|
const relevant = elements.filter((e) => e.kind === "circle" || e.kind === "text");
|
|
62740
62886
|
const anonymous = relevant.filter((e) => !usableId(e.elementId)).length;
|
|
62741
|
-
|
|
62742
|
-
|
|
62887
|
+
const repeated = relevant.length - new Set(relevant.map((e) => e.elementId)).size;
|
|
62888
|
+
const unidentified = anonymous + repeated;
|
|
62889
|
+
if (grammar === "ambiguous" && unidentified > 0) return grammarAmbiguous();
|
|
62890
|
+
if (unidentified > 0) {
|
|
62891
|
+
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
62892
|
return {
|
|
62744
62893
|
spent,
|
|
62745
62894
|
proposal: {
|
|
62746
62895
|
...head,
|
|
62747
62896
|
grammar: reported,
|
|
62748
62897
|
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
|
-
)
|
|
62898
|
+
outcome: ask("missing-element-identities", detail, [], null)
|
|
62755
62899
|
}
|
|
62756
62900
|
};
|
|
62757
62901
|
}
|
|
@@ -63475,6 +63619,44 @@ function steelReadRequestStoreKey(requestId) {
|
|
|
63475
63619
|
function root3() {
|
|
63476
63620
|
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
63621
|
}
|
|
63622
|
+
function validInspection2(value) {
|
|
63623
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
63624
|
+
const row = value;
|
|
63625
|
+
if (!onlyKeys3(row, /* @__PURE__ */ new Set(["version", "requestId", "projectId", "appId", "baseVersion", "extractorVersion", "sources", "pages"]))) return false;
|
|
63626
|
+
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;
|
|
63627
|
+
const sourceHashes = /* @__PURE__ */ new Set();
|
|
63628
|
+
for (const source of row.sources) {
|
|
63629
|
+
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;
|
|
63630
|
+
sourceHashes.add(source.sha256);
|
|
63631
|
+
}
|
|
63632
|
+
const pageIds = /* @__PURE__ */ new Set();
|
|
63633
|
+
for (const page of row.pages) {
|
|
63634
|
+
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;
|
|
63635
|
+
pageIds.add(page.id);
|
|
63636
|
+
}
|
|
63637
|
+
return true;
|
|
63638
|
+
}
|
|
63639
|
+
function writeSteelPageInspection(value, now2 = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
63640
|
+
if (!validInspection2(value)) throw new SteelReadManifestInvalidError("steel page inspection is invalid");
|
|
63641
|
+
const stored2 = { ...value, createdAt: now2, contentHash: hashOf(value) };
|
|
63642
|
+
writeRecord(inspectionPath(value.requestId), `${canonicalJson(stored2)}
|
|
63643
|
+
`);
|
|
63644
|
+
}
|
|
63645
|
+
function readSteelPageInspection(requestId) {
|
|
63646
|
+
try {
|
|
63647
|
+
const path = inspectionPath(requestId);
|
|
63648
|
+
if (!(0, import_node_fs23.existsSync)(path)) return null;
|
|
63649
|
+
const stored2 = JSON.parse((0, import_node_fs23.readFileSync)(path, "utf8"));
|
|
63650
|
+
const { createdAt, contentHash: contentHash2, ...value } = stored2;
|
|
63651
|
+
if (typeof createdAt !== "string" || typeof contentHash2 !== "string" || !SHA2562.test(contentHash2) || !validInspection2(value) || hashOf(value) !== contentHash2) return null;
|
|
63652
|
+
return value;
|
|
63653
|
+
} catch {
|
|
63654
|
+
return null;
|
|
63655
|
+
}
|
|
63656
|
+
}
|
|
63657
|
+
function steelPageInspectionMatches(value, expected) {
|
|
63658
|
+
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);
|
|
63659
|
+
}
|
|
63478
63660
|
function isRecord(value) {
|
|
63479
63661
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
63480
63662
|
const row = value;
|
|
@@ -63613,13 +63795,20 @@ function dropSteelReadManifest(requestId) {
|
|
|
63613
63795
|
(0, import_node_fs23.rmSync)(recordPath(requestId), { force: true });
|
|
63614
63796
|
} catch {
|
|
63615
63797
|
}
|
|
63798
|
+
try {
|
|
63799
|
+
(0, import_node_fs23.rmSync)(inspectionPath(requestId), { force: true });
|
|
63800
|
+
} catch {
|
|
63801
|
+
}
|
|
63616
63802
|
}
|
|
63617
63803
|
function removeSteelReadManifest(requestId, remove = (path) => (0, import_node_fs23.rmSync)(path, { force: true })) {
|
|
63618
63804
|
const path = recordPath(requestId);
|
|
63805
|
+
const inspected = inspectionPath(requestId);
|
|
63619
63806
|
remove(path);
|
|
63807
|
+
remove(inspected);
|
|
63620
63808
|
if ((0, import_node_fs23.existsSync)(path)) throw new Error("the discarded steel-read manifest is still present");
|
|
63809
|
+
if ((0, import_node_fs23.existsSync)(inspected)) throw new Error("the discarded steel-read inspection is still present");
|
|
63621
63810
|
}
|
|
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;
|
|
63811
|
+
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
63812
|
var init_steel_read_manifest = __esm({
|
|
63624
63813
|
"steel-read-manifest.ts"() {
|
|
63625
63814
|
"use strict";
|
|
@@ -63652,6 +63841,10 @@ var init_steel_read_manifest = __esm({
|
|
|
63652
63841
|
return required.every((key3) => Object.prototype.hasOwnProperty.call(value, key3)) && Object.keys(value).every((key3) => allowed.has(key3));
|
|
63653
63842
|
};
|
|
63654
63843
|
recordPath = (requestId) => (0, import_node_path19.join)(root3(), `${steelReadRequestStoreKey(requestId)}.json`);
|
|
63844
|
+
inspectionPath = (requestId) => (0, import_node_path19.join)(root3(), `${steelReadRequestStoreKey(requestId)}.inspection.json`);
|
|
63845
|
+
finite5 = (value) => typeof value === "number" && Number.isFinite(value);
|
|
63846
|
+
safeText = (value, max2 = 160) => typeof value === "string" && value.length > 0 && value.length <= max2;
|
|
63847
|
+
onlyKeys3 = (value, allowed) => Object.keys(value).every((key3) => allowed.has(key3));
|
|
63655
63848
|
SteelFilterCheckpointRejectedError = class extends Error {
|
|
63656
63849
|
constructor(message) {
|
|
63657
63850
|
super(message);
|
|
@@ -63969,6 +64162,27 @@ function listLeases() {
|
|
|
63969
64162
|
function getLease(leaseId) {
|
|
63970
64163
|
return listLeases().find((l) => l.leaseId === leaseId) ?? null;
|
|
63971
64164
|
}
|
|
64165
|
+
function expectedLeasePresence(expectedLeaseId, canonicalCwd) {
|
|
64166
|
+
const file = (0, import_node_path20.join)(LEASE_DIR(), leaseKey(canonicalCwd));
|
|
64167
|
+
const pathState = (path) => {
|
|
64168
|
+
try {
|
|
64169
|
+
(0, import_node_fs24.statSync)(path);
|
|
64170
|
+
return "present";
|
|
64171
|
+
} catch (error) {
|
|
64172
|
+
return error?.code === "ENOENT" ? "absent" : "unknown";
|
|
64173
|
+
}
|
|
64174
|
+
};
|
|
64175
|
+
const primary = pathState(file);
|
|
64176
|
+
const backup = pathState(lastGoodPath(file));
|
|
64177
|
+
if (primary === "unknown" || backup === "unknown") return { state: "unreadable" };
|
|
64178
|
+
if (primary === "absent" && backup === "absent") return { state: "absent" };
|
|
64179
|
+
const lease = readAttributableLease(file);
|
|
64180
|
+
if (!lease) return { state: "unreadable" };
|
|
64181
|
+
if (lease.leaseId !== expectedLeaseId || leaseKey(lease.cwd) !== leaseKey(canonicalCwd)) {
|
|
64182
|
+
return { state: "mismatched", lease };
|
|
64183
|
+
}
|
|
64184
|
+
return { state: "present", lease };
|
|
64185
|
+
}
|
|
63972
64186
|
function leaseForToken(token2) {
|
|
63973
64187
|
if (typeof token2 !== "string" || !token2) return null;
|
|
63974
64188
|
const given = Buffer.from(token2);
|
|
@@ -64312,30 +64526,40 @@ function currentSteelFilterResult(value) {
|
|
|
64312
64526
|
}
|
|
64313
64527
|
return value;
|
|
64314
64528
|
}
|
|
64315
|
-
function steelInspectionTimeoutMs(sourceCount, sourceBytes) {
|
|
64316
|
-
return clamp2(6e4, 3e4 + 1e4 * sourceCount + 5e3 * Math.ceil(sourceBytes / MIB), 12e4);
|
|
64317
|
-
}
|
|
64318
64529
|
function steelStreamBytesOf(pages) {
|
|
64319
64530
|
let total = 0;
|
|
64320
64531
|
for (const page of pages) {
|
|
64321
64532
|
const value = page.streamBytes;
|
|
64322
|
-
if (Number.isSafeInteger(value) && value >= 0) total
|
|
64533
|
+
if (Number.isSafeInteger(value) && value >= 0) total = saturatingAdd(total, value);
|
|
64323
64534
|
}
|
|
64324
|
-
return
|
|
64535
|
+
return total;
|
|
64325
64536
|
}
|
|
64326
64537
|
function steelExtractionBudgetMs(totalPages, sourceCount, sourceBytes, streamBytes = 0) {
|
|
64327
|
-
const
|
|
64328
|
-
const
|
|
64329
|
-
const
|
|
64330
|
-
|
|
64538
|
+
const pages = nonNegativeSafeInteger(totalPages);
|
|
64539
|
+
const sources = nonNegativeSafeInteger(sourceCount);
|
|
64540
|
+
const fileMib = Math.ceil(nonNegativeSafeInteger(sourceBytes) / MIB);
|
|
64541
|
+
const streamMib = Math.ceil(nonNegativeSafeInteger(streamBytes) / MIB);
|
|
64542
|
+
const sourceAllowance = saturatingMultiply(2e3, sources);
|
|
64543
|
+
const legacy = saturatingAdd(
|
|
64544
|
+
6e4,
|
|
64545
|
+
saturatingMultiply(15e3, pages),
|
|
64546
|
+
sourceAllowance,
|
|
64547
|
+
saturatingMultiply(1e3, fileMib)
|
|
64548
|
+
);
|
|
64549
|
+
const density = saturatingAdd(
|
|
64550
|
+
3e4,
|
|
64551
|
+
saturatingMultiply(8e3, streamMib),
|
|
64552
|
+
sourceAllowance
|
|
64553
|
+
);
|
|
64554
|
+
return clamp2(12e4, Math.max(legacy, density), STEEL_EXTRACTION_MAX_ATTEMPT_MS);
|
|
64331
64555
|
}
|
|
64332
64556
|
function steelOperationDeadlineAt(subprocessStartedAt) {
|
|
64333
64557
|
return subprocessStartedAt + STEEL_OPERATION_HARD_DEADLINE_MS;
|
|
64334
64558
|
}
|
|
64335
64559
|
function steelExtractionDeadlineAt(subprocessStartedAt, totalPages, sourceCount, sourceBytes, streamBytes = 0) {
|
|
64336
|
-
return
|
|
64337
|
-
|
|
64338
|
-
|
|
64560
|
+
return saturatingAdd(
|
|
64561
|
+
nonNegativeSafeInteger(subprocessStartedAt),
|
|
64562
|
+
steelExtractionBudgetMs(totalPages, sourceCount, sourceBytes, streamBytes)
|
|
64339
64563
|
);
|
|
64340
64564
|
}
|
|
64341
64565
|
function breachedScopes(counts2, bytes3, limits, perPage = { linework: counts2, text: [] }) {
|
|
@@ -64447,10 +64671,14 @@ function dropQuarantinedScriptDir(scriptDir) {
|
|
|
64447
64671
|
function readCleanupMarker(path) {
|
|
64448
64672
|
try {
|
|
64449
64673
|
const raw = JSON.parse((0, import_node_fs25.readFileSync)(path, "utf8"));
|
|
64450
|
-
if (raw.v !== 1 || !Number.isInteger(raw.pid) || raw.pid <= 0 || !Number.isFinite(raw.procStartedAt) || !Number.isInteger(raw.ownerPid) || raw.ownerPid <= 0 || !Number.isFinite(raw.ownerStartedAt) || raw.state !== "active" && raw.state !== "cleanup"
|
|
64674
|
+
if (raw.v !== 1 || !Number.isInteger(raw.pid) || raw.pid <= 0 || !Number.isFinite(raw.procStartedAt) || !Number.isInteger(raw.ownerPid) || raw.ownerPid <= 0 || !Number.isFinite(raw.ownerStartedAt) || raw.state !== "active" && raw.state !== "cleanup") {
|
|
64451
64675
|
return { state: "unknown", path };
|
|
64452
64676
|
}
|
|
64453
|
-
return {
|
|
64677
|
+
return {
|
|
64678
|
+
state: "valid",
|
|
64679
|
+
path,
|
|
64680
|
+
marker: { ...raw, expectedUntil: Number.isFinite(raw.expectedUntil) ? raw.expectedUntil : null }
|
|
64681
|
+
};
|
|
64454
64682
|
} catch {
|
|
64455
64683
|
return { state: "unknown", path };
|
|
64456
64684
|
}
|
|
@@ -64506,6 +64734,27 @@ function markCleanupState(pid, procStartedAt) {
|
|
|
64506
64734
|
if (read2.state !== "valid" || read2.marker.pid !== pid || read2.marker.procStartedAt !== procStartedAt) return;
|
|
64507
64735
|
durableReplace(path, JSON.stringify({ ...read2.marker, state: "cleanup" }), { mode: 384 });
|
|
64508
64736
|
}
|
|
64737
|
+
function cleanupRetryAfterMs(expectedUntil) {
|
|
64738
|
+
if (!Number.isFinite(expectedUntil) || expectedUntil <= Date.now()) return 1e4;
|
|
64739
|
+
return Math.max(1e3, Math.min(3e4, Math.round(expectedUntil - Date.now())));
|
|
64740
|
+
}
|
|
64741
|
+
function timeoutCleanupDisposition(pid, procStartedAt, contained) {
|
|
64742
|
+
if (contained) {
|
|
64743
|
+
clearCleanupMarker(pid, procStartedAt);
|
|
64744
|
+
return (0, import_node_fs25.existsSync)(cleanupMarkerPath(pid, procStartedAt)) ? { state: "blocked", retryAfterMs: null } : { state: "contained", retryAfterMs: 1e3 };
|
|
64745
|
+
}
|
|
64746
|
+
const path = cleanupMarkerPath(pid, procStartedAt);
|
|
64747
|
+
if (!(0, import_node_fs25.existsSync)(path)) return { state: "blocked", retryAfterMs: null };
|
|
64748
|
+
try {
|
|
64749
|
+
const raw = JSON.parse((0, import_node_fs25.readFileSync)(path, "utf8"));
|
|
64750
|
+
if (raw.v !== 1 || raw.pid !== pid || raw.procStartedAt !== procStartedAt || !Number.isInteger(raw.ownerPid) || raw.ownerPid <= 0 || !Number.isFinite(raw.ownerStartedAt) || raw.state !== "cleanup") {
|
|
64751
|
+
return { state: "blocked", retryAfterMs: null };
|
|
64752
|
+
}
|
|
64753
|
+
return { state: "pending", retryAfterMs: cleanupRetryAfterMs(Number.isFinite(raw.expectedUntil) ? raw.expectedUntil : null) };
|
|
64754
|
+
} catch {
|
|
64755
|
+
return { state: "blocked", retryAfterMs: null };
|
|
64756
|
+
}
|
|
64757
|
+
}
|
|
64509
64758
|
async function persistedCleanupPending() {
|
|
64510
64759
|
const reads = readCleanupMarkers();
|
|
64511
64760
|
if (reads.some((read2) => read2.state === "unknown")) throw new SteelFilterCleanupStateError();
|
|
@@ -64530,11 +64779,11 @@ async function persistedCleanupPending() {
|
|
|
64530
64779
|
continue;
|
|
64531
64780
|
}
|
|
64532
64781
|
if (marker.state === "cleanup") {
|
|
64533
|
-
const remaining2 =
|
|
64782
|
+
const remaining2 = cleanupRetryAfterMs(marker.expectedUntil);
|
|
64534
64783
|
return new SteelFilterCleanupPendingError(remaining2, "cleanup");
|
|
64535
64784
|
}
|
|
64536
64785
|
if (marker.ownerPid !== process.pid || Math.abs(marker.ownerStartedAt - serverStartedAt) >= 2e3) {
|
|
64537
|
-
const remaining2 =
|
|
64786
|
+
const remaining2 = cleanupRetryAfterMs(marker.expectedUntil);
|
|
64538
64787
|
return new SteelFilterCleanupPendingError(remaining2, "active");
|
|
64539
64788
|
}
|
|
64540
64789
|
}
|
|
@@ -64554,7 +64803,7 @@ async function executePython(script, input, options) {
|
|
|
64554
64803
|
for (const [pid, tracked] of unclosedPythonTrees) {
|
|
64555
64804
|
if (tracked.durableClaim) {
|
|
64556
64805
|
const stillClaimed = durableMarkers.some((marker) => marker.pid === pid && marker.procStartedAt === tracked.procStartedAt);
|
|
64557
|
-
if (!stillClaimed) {
|
|
64806
|
+
if (!stillClaimed && await killTreeAndVerify(pid, tracked.procStartedAt)) {
|
|
64558
64807
|
dropQuarantinedScriptDir(tracked.scriptDir);
|
|
64559
64808
|
unclosedPythonTrees.delete(pid);
|
|
64560
64809
|
}
|
|
@@ -64678,15 +64927,19 @@ async function executePython(script, input, options) {
|
|
|
64678
64927
|
let cleanupTimer;
|
|
64679
64928
|
let cleanupDeadlineAt;
|
|
64680
64929
|
let terminationOutcome;
|
|
64930
|
+
let terminationPromise;
|
|
64931
|
+
let terminationContained;
|
|
64681
64932
|
let timer;
|
|
64682
64933
|
const settleTermination = () => {
|
|
64683
64934
|
if (settled2 || !terminationOutcome) return;
|
|
64684
|
-
|
|
64685
|
-
|
|
64686
|
-
|
|
64935
|
+
const cleanup = child.pid ? timeoutCleanupDisposition(child.pid, procStartedAt, terminationContained) : { state: "contained", retryAfterMs: 1e3 };
|
|
64936
|
+
if (child.pid && cleanup.state === "contained") {
|
|
64937
|
+
unclosedPythonTrees.delete(child.pid);
|
|
64938
|
+
dropScriptDir();
|
|
64939
|
+
}
|
|
64687
64940
|
settled2 = true;
|
|
64688
64941
|
if (terminationOutcome === "timeout") {
|
|
64689
|
-
reject2(new SteelFilterTimeoutError(options.phase, Math.max(0, Math.round(now2() - started)), timeoutMs, options.workload, child.pid));
|
|
64942
|
+
reject2(new SteelFilterTimeoutError(options.phase, Math.max(0, Math.round(now2() - started)), timeoutMs, options.workload, child.pid, cleanup));
|
|
64690
64943
|
} else if (terminationOutcome === "stdout") {
|
|
64691
64944
|
reject2(new SteelFilterOutputTooLargeError());
|
|
64692
64945
|
} else {
|
|
@@ -64711,7 +64964,17 @@ async function executePython(script, input, options) {
|
|
|
64711
64964
|
cleanupDeadlineAt = Date.now() + (options.cleanupTimeoutMs ?? 1e4);
|
|
64712
64965
|
cleanupTimer = setTimeout(settleTermination, options.cleanupTimeoutMs ?? 1e4);
|
|
64713
64966
|
cleanupTimer.unref?.();
|
|
64714
|
-
|
|
64967
|
+
terminationPromise = Promise.resolve(terminate(child)).catch(() => false);
|
|
64968
|
+
void terminationPromise.then((contained) => {
|
|
64969
|
+
terminationContained = contained;
|
|
64970
|
+
if (!contained) return;
|
|
64971
|
+
if (child.pid) {
|
|
64972
|
+
unclosedPythonTrees.delete(child.pid);
|
|
64973
|
+
clearCleanupMarker(child.pid, procStartedAt);
|
|
64974
|
+
dropScriptDir();
|
|
64975
|
+
}
|
|
64976
|
+
if (!settled2) settleTermination();
|
|
64977
|
+
});
|
|
64715
64978
|
};
|
|
64716
64979
|
child.on("error", (error) => {
|
|
64717
64980
|
spawnError = error;
|
|
@@ -64737,7 +65000,7 @@ async function executePython(script, input, options) {
|
|
|
64737
65000
|
child.on("close", async (code, signal) => {
|
|
64738
65001
|
clearTimeout(timer);
|
|
64739
65002
|
const containmentRequired = timerWon || streamOverflow !== null;
|
|
64740
|
-
const containment = containmentRequired ? Promise.resolve(terminate(child)) : Promise.resolve(true);
|
|
65003
|
+
const containment = containmentRequired ? terminationPromise ?? Promise.resolve(terminate(child)).catch(() => false) : Promise.resolve(true);
|
|
64741
65004
|
let deadlineTimer;
|
|
64742
65005
|
const raced = containmentRequired && cleanupDeadlineAt !== void 0 ? await Promise.race([
|
|
64743
65006
|
containment.then((contained) => ({ kind: "contained", contained })),
|
|
@@ -64761,6 +65024,7 @@ async function executePython(script, input, options) {
|
|
|
64761
65024
|
return;
|
|
64762
65025
|
}
|
|
64763
65026
|
const treeContained = raced.contained;
|
|
65027
|
+
terminationContained = treeContained;
|
|
64764
65028
|
if (cleanupTimer) clearTimeout(cleanupTimer);
|
|
64765
65029
|
if (child.pid && treeContained) {
|
|
64766
65030
|
unclosedPythonTrees.delete(child.pid);
|
|
@@ -64770,7 +65034,10 @@ async function executePython(script, input, options) {
|
|
|
64770
65034
|
if (settled2) return;
|
|
64771
65035
|
settled2 = true;
|
|
64772
65036
|
const elapsedMs = Math.max(0, Math.round(now2() - started));
|
|
64773
|
-
if (timerWon)
|
|
65037
|
+
if (timerWon) {
|
|
65038
|
+
const cleanup = child.pid ? timeoutCleanupDisposition(child.pid, procStartedAt, treeContained) : { state: "contained", retryAfterMs: 1e3 };
|
|
65039
|
+
return reject2(new SteelFilterTimeoutError(options.phase, elapsedMs, timeoutMs, options.workload, child.pid, cleanup));
|
|
65040
|
+
}
|
|
64774
65041
|
const error = streamError ?? spawnError;
|
|
64775
65042
|
if (error) {
|
|
64776
65043
|
if (streamOverflow === "stdout" && isStdoutTooLarge(error)) return reject2(new SteelFilterOutputTooLargeError());
|
|
@@ -65070,7 +65337,7 @@ async function inspectSteelSourcePages(sources, options = {}) {
|
|
|
65070
65337
|
return row;
|
|
65071
65338
|
});
|
|
65072
65339
|
}
|
|
65073
|
-
var import_node_child_process6, import_node_crypto19, import_node_fs25, import_promises, import_node_os18, import_node_path21, PYTHON, PAGE_INSPECTOR, STEEL_FILTER_EXTRACTOR_PYTHON, SteelFilterBudgetError, SteelFilterOutputTooLargeError, MIB, clamp2, STEEL_OPERATION_HARD_DEADLINE_MS, SteelFilterTimeoutError, SteelFilterProcessError, SteelFilterCleanupPendingError, SteelFilterCleanupStateError, STEEL_FILTER_MAX_STDOUT_BYTES, STEEL_FILTER_MAX_OUTPUT_BYTES, STEEL_FILTER_BUDGET_LIMITS, unclosedPythonTrees, cleanupMarkerDir, cleanupMarkerPath, RFI_DRAWING_SVG, RfiDrawingRenderError, MAX_RFI_DRAWING_SOURCE_BYTES, RFI_DRAWING_READ_CHUNK_BYTES, RFI_DRAWING_SNAPSHOT_PREFIX, rfiDrawingRenderTail, available;
|
|
65340
|
+
var import_node_child_process6, import_node_crypto19, import_node_fs25, import_promises, import_node_os18, import_node_path21, PYTHON, PAGE_INSPECTOR, STEEL_FILTER_EXTRACTOR_PYTHON, SteelFilterBudgetError, SteelFilterOutputTooLargeError, MIB, clamp2, nonNegativeSafeInteger, saturatingMultiply, saturatingAdd, STEEL_EXTRACTION_MAX_ATTEMPT_MS, STEEL_OPERATION_HARD_DEADLINE_MS, SteelFilterTimeoutError, SteelFilterProcessError, SteelFilterCleanupPendingError, SteelFilterCleanupStateError, STEEL_FILTER_MAX_STDOUT_BYTES, STEEL_FILTER_MAX_OUTPUT_BYTES, STEEL_FILTER_BUDGET_LIMITS, unclosedPythonTrees, cleanupMarkerDir, cleanupMarkerPath, RFI_DRAWING_SVG, RfiDrawingRenderError, MAX_RFI_DRAWING_SOURCE_BYTES, RFI_DRAWING_READ_CHUNK_BYTES, RFI_DRAWING_SNAPSHOT_PREFIX, rfiDrawingRenderTail, available;
|
|
65074
65341
|
var init_steel_filter_prepass = __esm({
|
|
65075
65342
|
"steel-filter-prepass.ts"() {
|
|
65076
65343
|
"use strict";
|
|
@@ -66078,15 +66345,35 @@ json.dump({"pages":pages}, sys.stdout, separators=(",", ":"))
|
|
|
66078
66345
|
};
|
|
66079
66346
|
MIB = 1024 * 1024;
|
|
66080
66347
|
clamp2 = (minimum, value, maximum) => Math.max(minimum, Math.min(maximum, value));
|
|
66348
|
+
nonNegativeSafeInteger = (value) => {
|
|
66349
|
+
if (Number.isNaN(value) || value <= 0) return 0;
|
|
66350
|
+
if (!Number.isFinite(value) || value >= Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER;
|
|
66351
|
+
return Math.ceil(value);
|
|
66352
|
+
};
|
|
66353
|
+
saturatingMultiply = (left, right) => {
|
|
66354
|
+
if (left === 0 || right === 0) return 0;
|
|
66355
|
+
if (left > Math.floor(Number.MAX_SAFE_INTEGER / right)) return Number.MAX_SAFE_INTEGER;
|
|
66356
|
+
return left * right;
|
|
66357
|
+
};
|
|
66358
|
+
saturatingAdd = (...values2) => {
|
|
66359
|
+
let total = 0;
|
|
66360
|
+
for (const value of values2) {
|
|
66361
|
+
if (value >= Number.MAX_SAFE_INTEGER - total) return Number.MAX_SAFE_INTEGER;
|
|
66362
|
+
total += value;
|
|
66363
|
+
}
|
|
66364
|
+
return total;
|
|
66365
|
+
};
|
|
66366
|
+
STEEL_EXTRACTION_MAX_ATTEMPT_MS = 72e5;
|
|
66081
66367
|
STEEL_OPERATION_HARD_DEADLINE_MS = 36e4;
|
|
66082
66368
|
SteelFilterTimeoutError = class extends Error {
|
|
66083
|
-
constructor(phase2, elapsedMs, timeoutMs, workload, processId) {
|
|
66369
|
+
constructor(phase2, elapsedMs, timeoutMs, workload, processId, cleanup = { state: "contained", retryAfterMs: 1e3 }) {
|
|
66084
66370
|
super("Steel Filter preparation did not finish within the allowed time.");
|
|
66085
66371
|
this.phase = phase2;
|
|
66086
66372
|
this.elapsedMs = elapsedMs;
|
|
66087
66373
|
this.timeoutMs = timeoutMs;
|
|
66088
66374
|
this.workload = workload;
|
|
66089
66375
|
this.processId = processId;
|
|
66376
|
+
this.cleanup = cleanup;
|
|
66090
66377
|
this.name = "SteelFilterTimeoutError";
|
|
66091
66378
|
}
|
|
66092
66379
|
phase;
|
|
@@ -66094,6 +66381,7 @@ json.dump({"pages":pages}, sys.stdout, separators=(",", ":"))
|
|
|
66094
66381
|
timeoutMs;
|
|
66095
66382
|
workload;
|
|
66096
66383
|
processId;
|
|
66384
|
+
cleanup;
|
|
66097
66385
|
diagnosticId = (0, import_node_crypto19.randomUUID)();
|
|
66098
66386
|
};
|
|
66099
66387
|
SteelFilterProcessError = class extends Error {
|
|
@@ -75460,8 +75748,8 @@ function evaluateSteelRead(context) {
|
|
|
75460
75748
|
continue;
|
|
75461
75749
|
}
|
|
75462
75750
|
for (const fact of evidence.facts) {
|
|
75463
|
-
const
|
|
75464
|
-
const passes =
|
|
75751
|
+
const finite6 = Number.isFinite(fact.actualMm) && Number.isFinite(fact.limitMm) && Number.isFinite(fact.toleranceMm);
|
|
75752
|
+
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
75753
|
if (!passes) {
|
|
75466
75754
|
fitFailures.push(`${joint.id}:${fact.id}:${fact.actualMm}:${fact.relation}:${fact.limitMm}`);
|
|
75467
75755
|
fitFaults.push({ jointId: joint.id, factId: fact.id, fault: `${fact.id} measured ${fact.actualMm} against ${fact.relation} ${fact.limitMm}` });
|
|
@@ -83415,7 +83703,7 @@ function appVersion() {
|
|
|
83415
83703
|
return resolveVersion({
|
|
83416
83704
|
isSea: isSea2(),
|
|
83417
83705
|
sqVersionXml: readSqVersionXml(),
|
|
83418
|
-
define: true ? "0.138.
|
|
83706
|
+
define: true ? "0.138.2" : void 0,
|
|
83419
83707
|
pkgVersion: readPkgVersion()
|
|
83420
83708
|
});
|
|
83421
83709
|
}
|
|
@@ -83431,7 +83719,7 @@ function resolveChannel(s) {
|
|
|
83431
83719
|
function appChannel() {
|
|
83432
83720
|
return resolveChannel({
|
|
83433
83721
|
isSea: isSea2(),
|
|
83434
|
-
define: true ? "0.138.
|
|
83722
|
+
define: true ? "0.138.2" : void 0,
|
|
83435
83723
|
// argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
|
|
83436
83724
|
// carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
|
|
83437
83725
|
modulePath: process.argv[1]
|
|
@@ -86115,12 +86403,55 @@ var RUN_POLICY = {
|
|
|
86115
86403
|
},
|
|
86116
86404
|
"new-workflow": { runnable: false, why: "this one is a conversation \u2014 headless would talk to nobody" }
|
|
86117
86405
|
};
|
|
86406
|
+
function isRetryableRevisionPrepassResult(value) {
|
|
86407
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && value.ok === false && value.retryable === true;
|
|
86408
|
+
}
|
|
86118
86409
|
function steelPreparationTimeoutWhy(req) {
|
|
86119
86410
|
const base = "Steel Filter preparation timed out. Do not retry this request unchanged. Close it and attach a smaller drawing set.";
|
|
86120
86411
|
const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
|
|
86121
86412
|
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
86413
|
return `${base} Diagnostic ${detail.diagnosticId}; ${detail.phase} phase; ${detail.elapsedMs} ms of ${detail.timeoutMs} ms; ${detail.workload.sourceCount} source(s).`;
|
|
86123
86414
|
}
|
|
86415
|
+
function hasRetryablePreparationRefusal(req) {
|
|
86416
|
+
const authorities = [
|
|
86417
|
+
...req.refusalCode === "steel-manifest-extraction-timeout" ? [req.steelPreparationTimeout] : [],
|
|
86418
|
+
...req.run?.refusalCode === "steel-manifest-extraction-timeout" ? [req.run.steelPreparationTimeout] : []
|
|
86419
|
+
];
|
|
86420
|
+
const nonNegativeIntegerOrNull = (value) => value === null || Number.isSafeInteger(value) && Number(value) >= 0;
|
|
86421
|
+
return authorities.length > 0 && authorities.every((detail) => detail !== void 0 && detail !== null && typeof detail === "object" && !Array.isArray(detail) && detail.cleanupState !== "blocked" && /^[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" || detail.phase === "evidence" || detail.phase === "model") && 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));
|
|
86422
|
+
}
|
|
86423
|
+
function hasPreparationInterruptionDiagnostic(req) {
|
|
86424
|
+
const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
|
|
86425
|
+
if (!detail || typeof detail !== "object" || Array.isArray(detail)) return false;
|
|
86426
|
+
const nonNegativeIntegerOrNull = (value) => value === null || Number.isSafeInteger(value) && Number(value) >= 0;
|
|
86427
|
+
return (detail.cleanupState === void 0 || ["contained", "pending", "blocked"].includes(detail.cleanupState)) && /^[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" || detail.phase === "evidence" || detail.phase === "model") && 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);
|
|
86428
|
+
}
|
|
86429
|
+
function hasBlockedPreparationCleanup(req) {
|
|
86430
|
+
const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
|
|
86431
|
+
return hasPreparationInterruptionDiagnostic(req) && detail?.cleanupState === "blocked";
|
|
86432
|
+
}
|
|
86433
|
+
function steelPreparationEntryFor(req) {
|
|
86434
|
+
if (hasBlockedPreparationCleanup(req)) {
|
|
86435
|
+
return {
|
|
86436
|
+
allowed: false,
|
|
86437
|
+
state: "blocked",
|
|
86438
|
+
why: "the interrupted Steel Filter process could not be verified safe \u2014 check the prior process or restart FloLess before retrying"
|
|
86439
|
+
};
|
|
86440
|
+
}
|
|
86441
|
+
if (typeof req.steelManifestHash === "string" && req.steelManifestHash.length > 0) {
|
|
86442
|
+
return {
|
|
86443
|
+
allowed: false,
|
|
86444
|
+
state: "manifest-published",
|
|
86445
|
+
why: "Steel Filter extraction is complete \u2014 continue in the terminal AI that prepared it"
|
|
86446
|
+
};
|
|
86447
|
+
}
|
|
86448
|
+
return { allowed: true, state: "available" };
|
|
86449
|
+
}
|
|
86450
|
+
function preparationInterruptionDiagnosticText(req) {
|
|
86451
|
+
if (!hasPreparationInterruptionDiagnostic(req)) return null;
|
|
86452
|
+
const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
|
|
86453
|
+
return `Diagnostic ${detail.diagnosticId}; ${detail.phase} phase; ${detail.elapsedMs} ms of ${detail.timeoutMs} ms; ${detail.workload.sourceCount} source(s).`;
|
|
86454
|
+
}
|
|
86124
86455
|
function runEligibilityFor(req) {
|
|
86125
86456
|
const policy = policyFor(req.type);
|
|
86126
86457
|
if (!policy.runnable) return policy;
|
|
@@ -86128,22 +86459,19 @@ function runEligibilityFor(req) {
|
|
|
86128
86459
|
return { runnable: false, why: "workflow tours are conversations \u2014 use Copy to continue in your terminal" };
|
|
86129
86460
|
}
|
|
86130
86461
|
if (req.type !== "revision-read") return { runnable: true, policy };
|
|
86131
|
-
|
|
86132
|
-
|
|
86133
|
-
|
|
86134
|
-
why: steelPreparationTimeoutWhy(req)
|
|
86135
|
-
};
|
|
86136
|
-
}
|
|
86462
|
+
const preparationEntry = steelPreparationEntryFor(req);
|
|
86463
|
+
if (preparationEntry.state === "blocked") return { runnable: false, why: preparationEntry.why };
|
|
86464
|
+
const retryablePreparation = hasRetryablePreparationRefusal(req);
|
|
86137
86465
|
if (req.settledVersion !== void 0) {
|
|
86138
86466
|
return { runnable: false, why: "this drawing read already committed \u2014 FloLess is only retrying settlement cleanup" };
|
|
86139
86467
|
}
|
|
86140
86468
|
if (req.status === "staged") {
|
|
86141
86469
|
return { runnable: false, why: "this drawing read is complete and waiting for review in Drawing Filter" };
|
|
86142
86470
|
}
|
|
86143
|
-
if (req.status === "failed") {
|
|
86471
|
+
if (req.status === "failed" && !retryablePreparation) {
|
|
86144
86472
|
return { runnable: false, why: "this drawing read failed \u2014 attach the drawing set again to retry" };
|
|
86145
86473
|
}
|
|
86146
|
-
if (req.status !== "pending") {
|
|
86474
|
+
if (req.status !== "pending" && !retryablePreparation) {
|
|
86147
86475
|
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
86476
|
}
|
|
86149
86477
|
if (req.prepassReady === true) {
|
|
@@ -86152,6 +86480,13 @@ function runEligibilityFor(req) {
|
|
|
86152
86480
|
why: req.filterCheckpointCurrent === true ? "this Drawing Filter is saved \u2014 continue the drawing read in the terminal AI that prepared it" : "this Drawing Filter is ready \u2014 review it and press Save filter, then continue in the terminal AI that prepared it"
|
|
86153
86481
|
};
|
|
86154
86482
|
}
|
|
86483
|
+
if (!preparationEntry.allowed) return { runnable: false, why: preparationEntry.why };
|
|
86484
|
+
if (!retryablePreparation && (req.refusalCode === "steel-manifest-extraction-timeout" || req.run?.refusalCode === "steel-manifest-extraction-timeout")) {
|
|
86485
|
+
return {
|
|
86486
|
+
runnable: false,
|
|
86487
|
+
why: steelPreparationTimeoutWhy(req)
|
|
86488
|
+
};
|
|
86489
|
+
}
|
|
86155
86490
|
if (!req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0) {
|
|
86156
86491
|
return { runnable: false, why: "this is the first drawing read for the project \u2014 your terminal AI must create the starting project checkpoint and wait for you to review and save the Drawing Filter" };
|
|
86157
86492
|
}
|
|
@@ -86292,7 +86627,8 @@ function registerRunRelay(app, deps, origin) {
|
|
|
86292
86627
|
return reply.send(jsonRpc(msg.id, toolRefusal(`no such tool: ${String(params?.name)}`)));
|
|
86293
86628
|
}
|
|
86294
86629
|
const durableRequest = deps.codex.getRequest(lease);
|
|
86295
|
-
|
|
86630
|
+
const retryablePreparation = hasRetryablePreparationRefusal(durableRequest ?? {});
|
|
86631
|
+
if (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || !retryablePreparation && durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout") {
|
|
86296
86632
|
completedRevisionPrepasses.add(lease.leaseId);
|
|
86297
86633
|
recordCodexTool(lease, params.name, "denied");
|
|
86298
86634
|
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.")));
|
|
@@ -86304,8 +86640,10 @@ function registerRunRelay(app, deps, origin) {
|
|
|
86304
86640
|
activeRevisionPrepasses.add(lease.leaseId);
|
|
86305
86641
|
try {
|
|
86306
86642
|
const result = await deps.runRevisionPrepass(lease);
|
|
86307
|
-
|
|
86308
|
-
|
|
86643
|
+
if (!isRetryableRevisionPrepassResult(result)) {
|
|
86644
|
+
deps.markResolved(lease);
|
|
86645
|
+
completedRevisionPrepasses.add(lease.leaseId);
|
|
86646
|
+
}
|
|
86309
86647
|
recordCodexTool(lease, params.name, "allowed");
|
|
86310
86648
|
return reply.send(jsonRpc(msg.id, { content: [{ type: "text", text: boundedJson(result) }] }));
|
|
86311
86649
|
} catch (err2) {
|
|
@@ -86397,7 +86735,8 @@ function registerRunRelay(app, deps, origin) {
|
|
|
86397
86735
|
return reply.send(jsonRpc(msg.id, toolRefusal(`no such tool: ${String(params?.name)}`)));
|
|
86398
86736
|
}
|
|
86399
86737
|
const durableRequest = deps.codex?.getRequest(lease);
|
|
86400
|
-
|
|
86738
|
+
const retryablePreparation = hasRetryablePreparationRefusal(durableRequest ?? {});
|
|
86739
|
+
if (lease.terminalRefusalCode === "steel-manifest-extraction-timeout" || !retryablePreparation && durableRequest?.run?.refusalCode === "steel-manifest-extraction-timeout") {
|
|
86401
86740
|
completedRevisionPrepasses.add(lease.leaseId);
|
|
86402
86741
|
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
86742
|
}
|
|
@@ -86405,8 +86744,10 @@ function registerRunRelay(app, deps, origin) {
|
|
|
86405
86744
|
activeRevisionPrepasses.add(lease.leaseId);
|
|
86406
86745
|
try {
|
|
86407
86746
|
const result = await deps.runRevisionPrepass(lease);
|
|
86408
|
-
|
|
86409
|
-
|
|
86747
|
+
if (!isRetryableRevisionPrepassResult(result)) {
|
|
86748
|
+
deps.markResolved(lease);
|
|
86749
|
+
completedRevisionPrepasses.add(lease.leaseId);
|
|
86750
|
+
}
|
|
86410
86751
|
return reply.send(jsonRpc(msg.id, { content: [{ type: "text", text: boundedJson(result) }] }));
|
|
86411
86752
|
} catch (err2) {
|
|
86412
86753
|
if (err2?.name === "SteelManifestTerminalRefusalPersistenceError") {
|
|
@@ -86961,8 +87302,8 @@ My note: ${req.instruction}` : "") + ((req.appTemplateId || req.appId) === "vect
|
|
|
86961
87302
|
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
87303
|
const messageHint = isInitialRead ? "<plain-English what was read>" : "<plain-English what changed>";
|
|
86963
87304
|
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
|
|
87305
|
+
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 }.`;
|
|
87306
|
+
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, steel-manifest-inspection-interrupted, or steel-manifest-extraction-interrupted, wait at least retryAfterMs and retry this step for the SAME request; the request, completed page identification, and drawing set remain attached. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator clears it. For an interruption, 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. 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
87307
|
if ((req.appTemplateId || req.appId) === "vectorize") {
|
|
86967
87308
|
if (isInitialRead) {
|
|
86968
87309
|
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}`;
|
|
@@ -87157,6 +87498,23 @@ function requestClearPolicyFor(r) {
|
|
|
87157
87498
|
clearState: "lifecycle-owned"
|
|
87158
87499
|
};
|
|
87159
87500
|
}
|
|
87501
|
+
if (r.type === "revision-read") {
|
|
87502
|
+
const preparationEntry = steelPreparationEntryFor(r);
|
|
87503
|
+
if (preparationEntry.state === "blocked") {
|
|
87504
|
+
return {
|
|
87505
|
+
canClear: false,
|
|
87506
|
+
clearWhy: "FloLess could not verify that the earlier Steel Filter extractor stopped. Restart FloLess; if this remains blocked, follow the operator repair in Technical details.",
|
|
87507
|
+
clearState: "unavailable"
|
|
87508
|
+
};
|
|
87509
|
+
}
|
|
87510
|
+
if (preparationEntry.state === "manifest-published" && r.prepassReady !== true) {
|
|
87511
|
+
return {
|
|
87512
|
+
canClear: false,
|
|
87513
|
+
clearWhy: "Drawing preparation is complete and saved. Continue in the same terminal AI session to create the Drawing Filter before clearing this request.",
|
|
87514
|
+
clearState: "lifecycle-owned"
|
|
87515
|
+
};
|
|
87516
|
+
}
|
|
87517
|
+
}
|
|
87160
87518
|
if (r.type === "revision-read" && r.status === "staged" && r.steelAuditPolicy === 1) {
|
|
87161
87519
|
const release = requestReleasePolicyFor(r);
|
|
87162
87520
|
if (!release.canClear) return release;
|
|
@@ -87183,18 +87541,28 @@ function withPrompt(r, base = selfOrigin()) {
|
|
|
87183
87541
|
const prompt = instructionFor(r);
|
|
87184
87542
|
const marker = markerFor(r, base, prompt);
|
|
87185
87543
|
const eligibility = runEligibilityFor(r);
|
|
87186
|
-
const
|
|
87187
|
-
const
|
|
87544
|
+
const preparationEntry = r.type === "revision-read" ? steelPreparationEntryFor(r) : null;
|
|
87545
|
+
const retryablePreparationRefusal = r.type === "revision-read" && hasRetryablePreparationRefusal(r);
|
|
87546
|
+
const preparationRetryable = r.type === "revision-read" && preparationEntry?.allowed === true && (retryablePreparationRefusal || r.status === "pending" && hasPreparationInterruptionDiagnostic(r));
|
|
87547
|
+
const terminalPreparationRefusal = !retryablePreparationRefusal && r.type === "revision-read" && (r.refusalCode === "steel-manifest-extraction-timeout" || r.run?.refusalCode === "steel-manifest-extraction-timeout");
|
|
87548
|
+
const retryableAttempt = r.type === "revision-read" && r.run !== void 0 && (["failed", "contract-violation", "exited-unresolved"].includes(r.run.state) || r.run.state === "interrupted" && preparationRetryable) && (r.run.refusalCode !== "steel-manifest-extraction-timeout" || retryablePreparationRefusal) && expectedLeasePresence(r.run.leaseId, r.run.cwd).state === "absent";
|
|
87188
87549
|
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;
|
|
87550
|
+
const projectedRun = preparationRetryable && ["failed", "contract-violation", "exited-unresolved", "interrupted"].includes(r.run?.state || "") ? void 0 : r.type === "revision-read" && r.status !== "pending" && !retryablePreparationRefusal ? 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
87551
|
const clearPolicy = requestClearPolicyFor(r);
|
|
87552
|
+
const activeRun2 = projectedRun?.state === "queued" || projectedRun?.state === "running";
|
|
87553
|
+
const canCopy = marker !== "" && !activeRun2 && (r.type !== "revision-read" || r.status === "pending" && r.prepassReady !== true && preparationEntry?.allowed === true);
|
|
87191
87554
|
return {
|
|
87192
87555
|
...r,
|
|
87556
|
+
status: retryablePreparationRefusal && r.status === "failed" ? "pending" : r.status,
|
|
87193
87557
|
run: projectedRun,
|
|
87194
87558
|
prompt,
|
|
87195
87559
|
marker: terminalPreparationRefusal ? "" : marker,
|
|
87560
|
+
preparationState: preparationEntry?.state ?? null,
|
|
87561
|
+
preparationRetryable,
|
|
87562
|
+
preparationDiagnostic: hasPreparationInterruptionDiagnostic(r) ? preparationInterruptionDiagnosticText(r) : null,
|
|
87196
87563
|
canRun: eligibility.runnable && !hasAttempt,
|
|
87197
87564
|
runWhy: eligibility.runnable ? null : eligibility.why,
|
|
87565
|
+
canCopy,
|
|
87198
87566
|
...clearPolicy,
|
|
87199
87567
|
resumeCommand: terminalPreparationRefusal ? null : resumeCommandForRequest(r),
|
|
87200
87568
|
desktopHandoffs: terminalPreparationRefusal ? null : desktopHandoffsForRequest(r, base, prompt, marker)
|
|
@@ -87217,6 +87585,10 @@ function withPrompt(r, base = selfOrigin()) {
|
|
|
87217
87585
|
run: projectedRun,
|
|
87218
87586
|
prompt: r.instruction ? String(r.instruction).trim() : "",
|
|
87219
87587
|
marker: "",
|
|
87588
|
+
preparationState: null,
|
|
87589
|
+
preparationRetryable: false,
|
|
87590
|
+
preparationDiagnostic: null,
|
|
87591
|
+
canCopy: false,
|
|
87220
87592
|
canRun: false,
|
|
87221
87593
|
runWhy: null,
|
|
87222
87594
|
...clearPolicy,
|
|
@@ -90779,7 +91151,7 @@ var profileMismatchFact = (memberId, live, answered, sameSection) => rollDegrees
|
|
|
90779
91151
|
var profileMismatchAction = (fact, answered) => `${fact}. Set it to ${answered} here, or close this RFI and reopen it to record a different answer.`;
|
|
90780
91152
|
var needsSizeTruth = (action, disposition) => action === "apply" || action === "close" && disposition === "resolved";
|
|
90781
91153
|
var isObj16 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
90782
|
-
var
|
|
91154
|
+
var onlyKeys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
|
|
90783
91155
|
var RFI_ACTIONS = /* @__PURE__ */ new Set(["send", "answer", "apply", "close", "reopen"]);
|
|
90784
91156
|
function viewOf(record4, truth, projectName, file) {
|
|
90785
91157
|
const sighting = latestSighting(record4);
|
|
@@ -91197,7 +91569,7 @@ function registerRfiRoutes(app, options = {}) {
|
|
|
91197
91569
|
const project = resolveProject(req.params.id);
|
|
91198
91570
|
if (!project.ok) return send(project.code, { ok: false, error: project.error });
|
|
91199
91571
|
const body = isObj16(req.body) ? req.body : {};
|
|
91200
|
-
if (!
|
|
91572
|
+
if (!onlyKeys4(body, ["operationKey", "memberId", "action", "expectedRfiId", "expectedRfiRevision", "to", "via", "answer"])) {
|
|
91201
91573
|
return send(400, { ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
|
|
91202
91574
|
}
|
|
91203
91575
|
if (!isAddressField(body.operationKey, MAX_OPERATION_KEY)) {
|
|
@@ -91322,7 +91694,7 @@ function registerRfiRoutes(app, options = {}) {
|
|
|
91322
91694
|
const action = req.params.action;
|
|
91323
91695
|
if (!RFI_ACTIONS.has(action)) return send(404, { ok: false, error: `unknown action: ${action}` });
|
|
91324
91696
|
const body = isObj16(req.body) ? req.body : {};
|
|
91325
|
-
if (!
|
|
91697
|
+
if (!onlyKeys4(body, ["operationKey", "recordRevision", "to", "via", "answer", "disposition", "note", "why"])) {
|
|
91326
91698
|
return send(400, { ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
|
|
91327
91699
|
}
|
|
91328
91700
|
if (!isAddressField(body.operationKey, MAX_OPERATION_KEY)) {
|
|
@@ -92840,7 +93212,7 @@ var productionDeps = {
|
|
|
92840
93212
|
now: () => (/* @__PURE__ */ new Date()).toISOString()
|
|
92841
93213
|
};
|
|
92842
93214
|
var isObject3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
92843
|
-
var
|
|
93215
|
+
var onlyKeys5 = (value, allowed) => Object.keys(value).every((key3) => allowed.includes(key3));
|
|
92844
93216
|
function attemptIdFor(projectUuid, operationKey) {
|
|
92845
93217
|
return `gmail-${(0, import_node_crypto41.createHash)("sha256").update(JSON.stringify([projectUuid, operationKey])).digest("hex")}`;
|
|
92846
93218
|
}
|
|
@@ -93049,7 +93421,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
|
|
|
93049
93421
|
const project = resolveProject(req.params.id);
|
|
93050
93422
|
if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
|
|
93051
93423
|
const body = isObject3(req.body) ? req.body : {};
|
|
93052
|
-
if (!
|
|
93424
|
+
if (!onlyKeys5(body, ["operationKey", "recordRevision", "to"])) {
|
|
93053
93425
|
return reply.status(400).send({ ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" });
|
|
93054
93426
|
}
|
|
93055
93427
|
if (!isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
|
|
@@ -93101,7 +93473,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
|
|
|
93101
93473
|
const project = resolveProject(req.params.id);
|
|
93102
93474
|
if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
|
|
93103
93475
|
const body = isObject3(req.body) ? req.body : {};
|
|
93104
|
-
if (!
|
|
93476
|
+
if (!onlyKeys5(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
|
|
93105
93477
|
return reply.status(400).send({ ok: false, code: "rfi-operation-key-required", error: "every recovery carries an operation key" });
|
|
93106
93478
|
}
|
|
93107
93479
|
const release = acquireProjectDeliveryLease(req.params.id);
|
|
@@ -93160,7 +93532,7 @@ function registerRfiDeliveryRoutes(app, overrides = {}) {
|
|
|
93160
93532
|
const project = resolveProject(req.params.id);
|
|
93161
93533
|
if (!project.ok) return reply.status(project.code).send({ ok: false, error: project.error });
|
|
93162
93534
|
const body = isObject3(req.body) ? req.body : {};
|
|
93163
|
-
if (!
|
|
93535
|
+
if (!onlyKeys5(body, ["operationKey"]) || !isAddressField(body.operationKey, MAX_OPERATION_KEY2)) {
|
|
93164
93536
|
return reply.status(400).send({ ok: false, code: "rfi-operation-key-required", error: "every confirmation carries an operation key" });
|
|
93165
93537
|
}
|
|
93166
93538
|
const written = await mutateRfiDeliveryFile(req.params.id, (file) => {
|
|
@@ -95138,9 +95510,11 @@ function normalizedSheet(value) {
|
|
|
95138
95510
|
function steelTimeoutBody(error) {
|
|
95139
95511
|
return {
|
|
95140
95512
|
ok: false,
|
|
95141
|
-
code: "steel-manifest-extraction-
|
|
95142
|
-
error: "Steel Filter preparation
|
|
95143
|
-
recovery: "
|
|
95513
|
+
code: "steel-manifest-extraction-interrupted",
|
|
95514
|
+
error: "Steel Filter preparation was interrupted before it finished.",
|
|
95515
|
+
recovery: "Retry this request with the same drawing set. FloLess kept the request and completed page identification attached.",
|
|
95516
|
+
retryAfterMs: error.cleanup.retryAfterMs,
|
|
95517
|
+
cleanupState: error.cleanup.state,
|
|
95144
95518
|
diagnosticId: error.diagnosticId,
|
|
95145
95519
|
phase: error.phase,
|
|
95146
95520
|
elapsedMs: error.elapsedMs,
|
|
@@ -95148,12 +95522,34 @@ function steelTimeoutBody(error) {
|
|
|
95148
95522
|
workload: error.workload
|
|
95149
95523
|
};
|
|
95150
95524
|
}
|
|
95525
|
+
function steelTimeoutCleanupBlockedBody(error) {
|
|
95526
|
+
return {
|
|
95527
|
+
ok: false,
|
|
95528
|
+
code: "steel-manifest-preparation-blocked",
|
|
95529
|
+
error: "FloLess could not verify that the interrupted Steel Filter process is safely contained.",
|
|
95530
|
+
recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying.",
|
|
95531
|
+
diagnosticId: error.diagnosticId,
|
|
95532
|
+
phase: error.phase,
|
|
95533
|
+
cleanupState: error.cleanup.state
|
|
95534
|
+
};
|
|
95535
|
+
}
|
|
95536
|
+
function steelLifecycleBusyBody(error) {
|
|
95537
|
+
const retryAfterMs = error.busy.remainingMs && error.busy.remainingMs > 0 ? Math.max(1e3, Math.ceil(error.busy.remainingMs)) : 1e4;
|
|
95538
|
+
return {
|
|
95539
|
+
ok: false,
|
|
95540
|
+
code: "steel-manifest-preparation-busy",
|
|
95541
|
+
error: error.message,
|
|
95542
|
+
recovery: "Wait for the other drawing preparation to finish, then retry this same request.",
|
|
95543
|
+
retryAfterMs
|
|
95544
|
+
};
|
|
95545
|
+
}
|
|
95151
95546
|
function steelTimeoutDiagnostics(error) {
|
|
95152
95547
|
return {
|
|
95153
95548
|
diagnosticId: error.diagnosticId,
|
|
95154
95549
|
phase: error.phase,
|
|
95155
95550
|
elapsedMs: error.elapsedMs,
|
|
95156
95551
|
timeoutMs: error.timeoutMs,
|
|
95552
|
+
cleanupState: error.cleanup.state,
|
|
95157
95553
|
workload: error.workload
|
|
95158
95554
|
};
|
|
95159
95555
|
}
|
|
@@ -95174,12 +95570,13 @@ function storedSteelTimeoutDiagnostics(raw) {
|
|
|
95174
95570
|
const w = workload;
|
|
95175
95571
|
const integer = (candidate2) => Number.isSafeInteger(candidate2) && Number(candidate2) >= 0;
|
|
95176
95572
|
const nullable = (candidate2) => candidate2 === null || integer(candidate2);
|
|
95177
|
-
if (typeof value.diagnosticId !== "string" || !/^[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(value.diagnosticId) || !["inspection", "evidence", "model"].includes(String(value.phase)) || !integer(value.elapsedMs) || !integer(value.timeoutMs) || !integer(w.sourceCount) || !integer(w.sourceBytes) || !nullable(w.totalPageCount) || !nullable(w.selectedPageCount)) return null;
|
|
95573
|
+
if (typeof value.diagnosticId !== "string" || !/^[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(value.diagnosticId) || !["inspection", "evidence", "model"].includes(String(value.phase)) || !integer(value.elapsedMs) || !integer(value.timeoutMs) || value.cleanupState !== void 0 && !["contained", "pending", "blocked"].includes(String(value.cleanupState)) || !integer(w.sourceCount) || !integer(w.sourceBytes) || !nullable(w.totalPageCount) || !nullable(w.selectedPageCount)) return null;
|
|
95178
95574
|
return {
|
|
95179
95575
|
diagnosticId: value.diagnosticId,
|
|
95180
95576
|
phase: value.phase,
|
|
95181
95577
|
elapsedMs: value.elapsedMs,
|
|
95182
95578
|
timeoutMs: value.timeoutMs,
|
|
95579
|
+
...value.cleanupState === void 0 ? {} : { cleanupState: value.cleanupState },
|
|
95183
95580
|
workload: {
|
|
95184
95581
|
sourceCount: w.sourceCount,
|
|
95185
95582
|
sourceBytes: w.sourceBytes,
|
|
@@ -95838,466 +96235,604 @@ function registerRevisionRoutes(app, deps = {}) {
|
|
|
95838
96235
|
app.post(
|
|
95839
96236
|
"/api/projects/:id/revision-requests/:reqId/steel-manifest",
|
|
95840
96237
|
{ bodyLimit: 256 * 1024 },
|
|
95841
|
-
async (req, reply) =>
|
|
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;
|
|
96238
|
+
async (req, reply) => {
|
|
95908
96239
|
try {
|
|
95909
|
-
|
|
95910
|
-
|
|
95911
|
-
|
|
95912
|
-
|
|
95913
|
-
|
|
95914
|
-
|
|
95915
|
-
|
|
95916
|
-
|
|
95917
|
-
|
|
95918
|
-
|
|
95919
|
-
|
|
95920
|
-
|
|
95921
|
-
|
|
95922
|
-
|
|
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}.`
|
|
96240
|
+
return await withLifecycleLock("project", req.params.id, async () => {
|
|
96241
|
+
const project = getProject(req.params.id);
|
|
96242
|
+
let request = getRequest(req.params.reqId);
|
|
96243
|
+
const resumableLegacyPreparation = request ? hasRetryablePreparationRefusal(request) : false;
|
|
96244
|
+
const hasPreparationTimeoutAuthority = request?.refusalCode === "steel-manifest-extraction-timeout" || request?.run?.refusalCode === "steel-manifest-extraction-timeout";
|
|
96245
|
+
if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.appId !== project.app || request.status !== "pending" && !hasPreparationTimeoutAuthority || request.settledVersion !== void 0) {
|
|
96246
|
+
return reply.status(404).send({ ok: false, error: "unknown pending steel revision request" });
|
|
96247
|
+
}
|
|
96248
|
+
const preparationEntry = steelPreparationEntryFor(request);
|
|
96249
|
+
if (preparationEntry.state === "blocked") {
|
|
96250
|
+
return reply.status(409).send({
|
|
96251
|
+
ok: false,
|
|
96252
|
+
code: "steel-manifest-preparation-blocked",
|
|
96253
|
+
error: preparationEntry.why,
|
|
96254
|
+
recovery: "Restart FloLess, then open Requests. If preparation remains blocked, use the operator repair in Technical details."
|
|
95947
96255
|
});
|
|
95948
|
-
if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its terminal refusal" });
|
|
95949
|
-
broadcast({ type: "requests-changed" });
|
|
95950
96256
|
}
|
|
95951
|
-
|
|
95952
|
-
|
|
95953
|
-
|
|
95954
|
-
|
|
95955
|
-
|
|
95956
|
-
|
|
95957
|
-
|
|
95958
|
-
|
|
95959
|
-
|
|
95960
|
-
|
|
95961
|
-
|
|
95962
|
-
|
|
95963
|
-
|
|
95964
|
-
|
|
95965
|
-
|
|
95966
|
-
|
|
95967
|
-
|
|
95968
|
-
|
|
95969
|
-
|
|
95970
|
-
|
|
95971
|
-
|
|
95972
|
-
|
|
95973
|
-
|
|
95974
|
-
|
|
95975
|
-
|
|
95976
|
-
|
|
95977
|
-
|
|
95978
|
-
|
|
95979
|
-
|
|
95980
|
-
|
|
95981
|
-
|
|
95982
|
-
|
|
95983
|
-
|
|
95984
|
-
|
|
95985
|
-
|
|
95986
|
-
|
|
95987
|
-
|
|
95988
|
-
|
|
95989
|
-
|
|
95990
|
-
|
|
95991
|
-
|
|
95992
|
-
|
|
95993
|
-
|
|
95994
|
-
|
|
95995
|
-
|
|
95996
|
-
|
|
95997
|
-
|
|
95998
|
-
|
|
95999
|
-
|
|
96000
|
-
|
|
96001
|
-
|
|
96002
|
-
|
|
96003
|
-
|
|
96004
|
-
|
|
96005
|
-
|
|
96006
|
-
|
|
96007
|
-
|
|
96008
|
-
|
|
96009
|
-
|
|
96010
|
-
|
|
96011
|
-
|
|
96012
|
-
|
|
96013
|
-
|
|
96014
|
-
|
|
96015
|
-
|
|
96016
|
-
|
|
96017
|
-
|
|
96018
|
-
|
|
96019
|
-
|
|
96020
|
-
|
|
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}.`
|
|
96257
|
+
if (preparationEntry.state === "manifest-published" && request.prepassReady !== true) {
|
|
96258
|
+
const stored3 = readSteelReadManifest(request.id);
|
|
96259
|
+
if (!stored3 || stored3.manifestHash !== request.steelManifestHash || stored3.manifest.requestId !== request.id || stored3.manifest.projectId !== project.id || stored3.manifest.appId !== project.app) {
|
|
96260
|
+
return reply.status(409).send({
|
|
96261
|
+
ok: false,
|
|
96262
|
+
code: "steel-manifest-preparation-blocked",
|
|
96263
|
+
error: "the published Steel Filter manifest is missing, corrupt, or no longer belongs to this request",
|
|
96264
|
+
recovery: "Do not retry extraction. Restart FloLess and inspect this request before continuing."
|
|
96265
|
+
});
|
|
96266
|
+
}
|
|
96267
|
+
return {
|
|
96268
|
+
ok: true,
|
|
96269
|
+
manifestHash: stored3.manifestHash,
|
|
96270
|
+
etag: request.prepassEtag ?? null,
|
|
96271
|
+
requiresCheckpointCreate: true,
|
|
96272
|
+
pages: stored3.manifest.pages,
|
|
96273
|
+
filter: stored3.manifest.filter,
|
|
96274
|
+
...stored3.scaleProposals === void 0 ? {} : { scaleProposals: stored3.scaleProposals }
|
|
96275
|
+
};
|
|
96276
|
+
}
|
|
96277
|
+
let refusalLease = null;
|
|
96278
|
+
let refusalLeasePresence = null;
|
|
96279
|
+
if (request.run?.leaseId) {
|
|
96280
|
+
try {
|
|
96281
|
+
refusalLeasePresence = expectedLeasePresence(request.run.leaseId, request.run.cwd);
|
|
96282
|
+
refusalLease = refusalLeasePresence.state === "present" ? refusalLeasePresence.lease : null;
|
|
96283
|
+
} catch {
|
|
96284
|
+
return reply.status(409).send({
|
|
96285
|
+
ok: false,
|
|
96286
|
+
code: "revision-read-lifecycle-unavailable",
|
|
96287
|
+
error: "FloLess could not verify whether this drawing read is still owned by a terminal run.",
|
|
96288
|
+
recovery: "Restart FloLess, then open Requests before trying again."
|
|
96289
|
+
});
|
|
96290
|
+
}
|
|
96291
|
+
}
|
|
96292
|
+
if (resumableLegacyPreparation) {
|
|
96293
|
+
const migrationHead = listVersions(project.id)[0]?.n ?? 0;
|
|
96294
|
+
if ((request.baseVersion ?? 0) !== migrationHead) {
|
|
96295
|
+
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${migrationHead})` });
|
|
96296
|
+
}
|
|
96297
|
+
try {
|
|
96298
|
+
verifiedSteelSources(project.id, request);
|
|
96299
|
+
} catch {
|
|
96300
|
+
return reply.status(409).send({
|
|
96301
|
+
ok: false,
|
|
96302
|
+
code: "revision-source-changed",
|
|
96303
|
+
error: "The drawing source no longer matches the interrupted request, so its legacy refusal cannot be migrated."
|
|
96304
|
+
});
|
|
96305
|
+
}
|
|
96306
|
+
if (request.run?.leaseId && refusalLeasePresence?.state !== "absent") {
|
|
96307
|
+
return reply.status(409).send({
|
|
96308
|
+
ok: false,
|
|
96309
|
+
code: refusalLeasePresence?.state === "present" || refusalLeasePresence?.state === "mismatched" ? "revision-read-owned" : "revision-read-lifecycle-unavailable",
|
|
96310
|
+
error: refusalLeasePresence?.state === "present" || refusalLeasePresence?.state === "mismatched" ? "this interrupted drawing preparation is still owned by a terminal run \u2014 stop or recover that run before retrying" : "FloLess could not prove that the interrupted drawing preparation released its terminal run."
|
|
96311
|
+
});
|
|
96312
|
+
}
|
|
96313
|
+
if (request.run && (request.run.state === "queued" || request.run.state === "running" || request.run.processContained === false)) {
|
|
96314
|
+
return reply.status(409).send({
|
|
96315
|
+
ok: false,
|
|
96316
|
+
code: "revision-read-lifecycle-unavailable",
|
|
96317
|
+
error: "FloLess has not proved that the interrupted terminal process is contained."
|
|
96318
|
+
});
|
|
96319
|
+
}
|
|
96320
|
+
const diagnostic = request.steelPreparationTimeout ?? request.run?.steelPreparationTimeout;
|
|
96321
|
+
request = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
|
|
96322
|
+
status: "pending",
|
|
96323
|
+
refusalCode: void 0,
|
|
96324
|
+
steelPreparationTimeout: diagnostic,
|
|
96325
|
+
error: void 0,
|
|
96326
|
+
...request.run ? { run: { ...request.run, refusalCode: void 0 } } : {}
|
|
96086
96327
|
});
|
|
96087
|
-
if (!
|
|
96328
|
+
if (!request) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while making its interrupted preparation resumable" });
|
|
96088
96329
|
broadcast({ type: "requests-changed" });
|
|
96089
96330
|
}
|
|
96090
|
-
|
|
96091
|
-
|
|
96092
|
-
|
|
96093
|
-
|
|
96094
|
-
|
|
96095
|
-
|
|
96096
|
-
|
|
96097
|
-
|
|
96098
|
-
|
|
96099
|
-
|
|
96100
|
-
|
|
96101
|
-
|
|
96102
|
-
|
|
96103
|
-
|
|
96104
|
-
|
|
96105
|
-
|
|
96106
|
-
|
|
96107
|
-
|
|
96108
|
-
|
|
96109
|
-
|
|
96110
|
-
|
|
96111
|
-
|
|
96112
|
-
|
|
96113
|
-
|
|
96114
|
-
|
|
96115
|
-
|
|
96116
|
-
|
|
96117
|
-
|
|
96118
|
-
|
|
96119
|
-
|
|
96120
|
-
|
|
96121
|
-
|
|
96122
|
-
|
|
96123
|
-
|
|
96124
|
-
|
|
96125
|
-
const
|
|
96126
|
-
|
|
96127
|
-
|
|
96128
|
-
|
|
96129
|
-
|
|
96130
|
-
|
|
96131
|
-
const
|
|
96132
|
-
|
|
96133
|
-
|
|
96134
|
-
|
|
96135
|
-
|
|
96136
|
-
|
|
96137
|
-
|
|
96138
|
-
|
|
96139
|
-
|
|
96140
|
-
|
|
96141
|
-
|
|
96142
|
-
|
|
96143
|
-
|
|
96144
|
-
|
|
96145
|
-
|
|
96146
|
-
|
|
96147
|
-
|
|
96148
|
-
|
|
96149
|
-
|
|
96150
|
-
|
|
96151
|
-
|
|
96152
|
-
|
|
96153
|
-
|
|
96154
|
-
|
|
96155
|
-
|
|
96156
|
-
|
|
96157
|
-
|
|
96158
|
-
|
|
96159
|
-
|
|
96160
|
-
|
|
96161
|
-
|
|
96162
|
-
|
|
96163
|
-
|
|
96164
|
-
|
|
96165
|
-
|
|
96166
|
-
|
|
96167
|
-
|
|
96168
|
-
|
|
96169
|
-
|
|
96170
|
-
|
|
96171
|
-
|
|
96172
|
-
|
|
96173
|
-
|
|
96174
|
-
|
|
96175
|
-
|
|
96176
|
-
|
|
96331
|
+
if (request.run && (request.run.state === "queued" || request.run.state === "running")) {
|
|
96332
|
+
const rawToken = req.headers["x-floless-run-token"];
|
|
96333
|
+
const token2 = Array.isArray(rawToken) ? rawToken[0] : rawToken;
|
|
96334
|
+
const lease = typeof token2 === "string" ? leaseForToken(token2) : null;
|
|
96335
|
+
if (!lease || lease.leaseId !== request.run.leaseId || lease.requestId !== request.id || lease.requestType !== "revision-read" || lease.project !== project.id || lease.appId !== project.app) {
|
|
96336
|
+
return reply.status(409).send({
|
|
96337
|
+
ok: false,
|
|
96338
|
+
code: "revision-read-owned",
|
|
96339
|
+
error: "this drawing read is already running \u2014 wait for it to prepare the Drawing Filter or stop it in Requests"
|
|
96340
|
+
});
|
|
96341
|
+
}
|
|
96342
|
+
}
|
|
96343
|
+
const copiedTerminalRefusal = request.refusalCode === "steel-manifest-extraction-timeout";
|
|
96344
|
+
if (copiedTerminalRefusal || request.run?.refusalCode === "steel-manifest-extraction-timeout" || refusalLease?.terminalRefusalCode === "steel-manifest-extraction-timeout") {
|
|
96345
|
+
const diagnostics = storedSteelTimeoutDiagnostics(
|
|
96346
|
+
copiedTerminalRefusal ? request.steelPreparationTimeout : request.run?.steelPreparationTimeout
|
|
96347
|
+
);
|
|
96348
|
+
return reply.status(409).send({
|
|
96349
|
+
ok: false,
|
|
96350
|
+
code: "steel-manifest-extraction-timeout",
|
|
96351
|
+
error: "Steel Filter preparation did not finish within the allowed time.",
|
|
96352
|
+
recovery: "Do not retry this request unchanged. Close it and attach a smaller drawing set.",
|
|
96353
|
+
...diagnostics ?? {}
|
|
96354
|
+
});
|
|
96355
|
+
}
|
|
96356
|
+
if (request.prepassReady === true && !preparedManifestNeedsRegeneration(project, request)) {
|
|
96357
|
+
return reply.status(409).send({
|
|
96358
|
+
ok: false,
|
|
96359
|
+
code: "revision-filter-prepared",
|
|
96360
|
+
error: "this drawing read already prepared its Drawing Filter \u2014 review and save that checkpoint instead of preparing it again"
|
|
96361
|
+
});
|
|
96362
|
+
}
|
|
96363
|
+
if (request.steelAuditPolicy !== 1 || resolveTemplateId(project.app) !== "steel-model") {
|
|
96364
|
+
return reply.status(409).send({ ok: false, code: "steel-manifest-not-applicable", error: "this request is not governed by the Steel Model completion policy" });
|
|
96365
|
+
}
|
|
96366
|
+
const head = listVersions(project.id)[0]?.n ?? 0;
|
|
96367
|
+
if ((request.baseVersion ?? 0) !== head) {
|
|
96368
|
+
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})` });
|
|
96369
|
+
}
|
|
96370
|
+
let sources;
|
|
96371
|
+
let inspected;
|
|
96372
|
+
const now2 = deps.now ?? (() => import_node_perf_hooks2.performance.now());
|
|
96373
|
+
let subprocessStartedAt = 0;
|
|
96374
|
+
let inspectionStartedAt = 0;
|
|
96375
|
+
let hardDeadline = 0;
|
|
96376
|
+
let inspectionEndedAt = 0;
|
|
96377
|
+
let inspectionWorkload = null;
|
|
96378
|
+
let freshInspection = false;
|
|
96379
|
+
try {
|
|
96380
|
+
sources = verifiedSteelSources(project.id, request);
|
|
96381
|
+
const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
|
|
96382
|
+
inspectionStartedAt = now2();
|
|
96383
|
+
subprocessStartedAt = inspectionStartedAt;
|
|
96384
|
+
inspectionWorkload = {
|
|
96385
|
+
sourceCount: sources.extractorSources.length,
|
|
96386
|
+
sourceBytes,
|
|
96387
|
+
totalPageCount: null,
|
|
96388
|
+
selectedPageCount: null
|
|
96389
|
+
};
|
|
96390
|
+
const cachedInspection = readSteelPageInspection(request.id);
|
|
96391
|
+
if (cachedInspection && steelPageInspectionMatches(cachedInspection, {
|
|
96392
|
+
requestId: request.id,
|
|
96393
|
+
projectId: project.id,
|
|
96394
|
+
appId: project.app,
|
|
96395
|
+
baseVersion: request.baseVersion ?? 0,
|
|
96396
|
+
extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
|
|
96397
|
+
sources: sources.manifestSources
|
|
96398
|
+
})) {
|
|
96399
|
+
inspected = cachedInspection.pages;
|
|
96400
|
+
} else {
|
|
96401
|
+
inspected = await (deps.inspectSteelSourcePages ?? inspectSteelSourcePages)(sources.extractorSources, {
|
|
96402
|
+
// This is process-liveness containment, not a model-capacity refusal. Expiry leaves the
|
|
96403
|
+
// request attached and retryable; ordinary successful inventories become checkpoints.
|
|
96404
|
+
timeoutMs: STEEL_OPERATION_HARD_DEADLINE_MS,
|
|
96405
|
+
workload: inspectionWorkload
|
|
96406
|
+
});
|
|
96407
|
+
freshInspection = true;
|
|
96408
|
+
}
|
|
96409
|
+
inspectionEndedAt = now2();
|
|
96410
|
+
subprocessStartedAt = now2();
|
|
96411
|
+
} catch (error) {
|
|
96412
|
+
if (error instanceof SteelFilterCleanupStateError) {
|
|
96413
|
+
return reply.status(409).send({
|
|
96414
|
+
ok: false,
|
|
96415
|
+
code: "steel-manifest-preparation-blocked",
|
|
96416
|
+
error: error.message,
|
|
96417
|
+
recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
|
|
96418
|
+
});
|
|
96419
|
+
}
|
|
96420
|
+
if (error instanceof SteelFilterCleanupPendingError) {
|
|
96421
|
+
reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
|
|
96422
|
+
return reply.status(409).send(steelCleanupPendingBody(error));
|
|
96423
|
+
}
|
|
96424
|
+
if (error instanceof SteelFilterTimeoutError) {
|
|
96425
|
+
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");
|
|
96426
|
+
const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
|
|
96427
|
+
status: "pending",
|
|
96428
|
+
refusalCode: void 0,
|
|
96429
|
+
steelPreparationTimeout: steelTimeoutDiagnostics(error),
|
|
96430
|
+
error: void 0
|
|
96431
|
+
});
|
|
96432
|
+
if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its retryable interruption" });
|
|
96433
|
+
request = written;
|
|
96434
|
+
broadcast({ type: "requests-changed" });
|
|
96435
|
+
if (error.cleanup.state === "blocked") return reply.status(409).send(steelTimeoutCleanupBlockedBody(error));
|
|
96436
|
+
reply.header("Retry-After", String(Math.ceil(error.cleanup.retryAfterMs / 1e3)));
|
|
96437
|
+
if (error.phase === "inspection") {
|
|
96438
|
+
return reply.status(409).send({
|
|
96439
|
+
...steelTimeoutBody(error),
|
|
96440
|
+
code: "steel-manifest-inspection-interrupted",
|
|
96441
|
+
error: "Drawing page inspection was interrupted before it finished.",
|
|
96442
|
+
recovery: "Retry this request. FloLess will continue with the same drawing set.",
|
|
96443
|
+
retryAfterMs: error.cleanup.retryAfterMs
|
|
96444
|
+
});
|
|
96445
|
+
}
|
|
96446
|
+
return reply.status(409).send(steelTimeoutBody(error));
|
|
96447
|
+
}
|
|
96448
|
+
if (error instanceof SteelFilterProcessError) {
|
|
96449
|
+
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");
|
|
96450
|
+
return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: error.message, diagnosticId: error.diagnosticId });
|
|
96451
|
+
}
|
|
96452
|
+
const diagnosticId = (0, import_node_crypto42.randomUUID)();
|
|
96453
|
+
req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "source-validation" }, "steel manifest source inspection refused");
|
|
96454
|
+
return reply.status(400).send({ ok: false, code: "steel-manifest-source-invalid", error: "Steel source inspection failed.", diagnosticId });
|
|
96455
|
+
}
|
|
96456
|
+
if (freshInspection) {
|
|
96457
|
+
writeSteelPageInspection({
|
|
96458
|
+
version: 1,
|
|
96459
|
+
requestId: request.id,
|
|
96460
|
+
projectId: project.id,
|
|
96461
|
+
appId: project.app,
|
|
96462
|
+
baseVersion: request.baseVersion ?? 0,
|
|
96463
|
+
extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
|
|
96464
|
+
sources: sources.manifestSources,
|
|
96465
|
+
pages: inspected
|
|
96466
|
+
});
|
|
96467
|
+
}
|
|
96468
|
+
const rawBindings = Array.isArray(req.body?.bindings) ? req.body.bindings : [];
|
|
96469
|
+
if (rawBindings.length > inspected.length) return reply.status(400).send({ ok: false, error: "too many page bindings" });
|
|
96470
|
+
const bindingByPage = /* @__PURE__ */ new Map();
|
|
96471
|
+
for (const raw of rawBindings) {
|
|
96472
|
+
const pageId = typeof raw?.pageId === "string" ? raw.pageId : "";
|
|
96473
|
+
const sheet = typeof raw?.sheet === "string" ? raw.sheet.trim() : "";
|
|
96474
|
+
const evidenceKind = typeof raw?.evidenceKind === "string" && EVIDENCE_KINDS.has(raw.evidenceKind) ? raw.evidenceKind : null;
|
|
96475
|
+
if (!inspected.some((page) => page.id === pageId) || !SHEET_ID.test(sheet) || !evidenceKind || bindingByPage.has(pageId)) {
|
|
96476
|
+
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" });
|
|
96477
|
+
}
|
|
96478
|
+
const title = typeof raw.title === "string" && raw.title.trim() ? raw.title.trim().slice(0, 160) : void 0;
|
|
96479
|
+
bindingByPage.set(pageId, { sheet, ...title ? { title } : {}, evidenceKind });
|
|
96480
|
+
}
|
|
96481
|
+
const current = readAcceptedForRequest(project.app, project.id, "read");
|
|
96482
|
+
const currentObj = current && typeof current === "object" && !Array.isArray(current) ? current : null;
|
|
96483
|
+
const currentPlans = Array.isArray(currentObj?.plans) ? currentObj.plans.filter((p) => !!p && typeof p === "object" && !Array.isArray(p)) : [];
|
|
96484
|
+
const existingBySheet = new Map(currentPlans.flatMap((plan) => typeof plan.sheet === "string" ? [[normalizedSheet(plan.sheet), plan]] : []));
|
|
96485
|
+
const unresolved = [];
|
|
96486
|
+
const pages = [];
|
|
96487
|
+
for (const page of inspected) {
|
|
96488
|
+
const explicit = bindingByPage.get(page.id);
|
|
96489
|
+
const trustedSheet = page.trustedSheetCandidate;
|
|
96490
|
+
const existingMatches = trustedSheet ? [normalizedSheet(trustedSheet)].flatMap((candidate2) => existingBySheet.has(candidate2) ? [existingBySheet.get(candidate2)] : []) : [];
|
|
96491
|
+
let binding = explicit;
|
|
96492
|
+
if (!binding && page.title && page.evidenceKind !== "other" && existingMatches.length === 1 && typeof existingMatches[0].sheet === "string") {
|
|
96493
|
+
const existing = existingMatches[0];
|
|
96494
|
+
binding = { sheet: existing.sheet, title: page.title, evidenceKind: page.evidenceKind };
|
|
96495
|
+
}
|
|
96496
|
+
if (!binding && trustedSheet && page.title && page.evidenceKind !== "other") binding = { sheet: trustedSheet, title: page.title, evidenceKind: page.evidenceKind };
|
|
96497
|
+
if (!binding) {
|
|
96498
|
+
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 } : {} });
|
|
96499
|
+
continue;
|
|
96500
|
+
}
|
|
96501
|
+
const viewKind = modelViewKindForEvidence(binding.evidenceKind);
|
|
96502
|
+
pages.push({
|
|
96503
|
+
id: page.id,
|
|
96504
|
+
sourceHash: page.sourceHash,
|
|
96505
|
+
page: page.page,
|
|
96506
|
+
bounds: page.bounds,
|
|
96507
|
+
sheetCandidates: page.sheetCandidates,
|
|
96508
|
+
sheet: binding.sheet,
|
|
96509
|
+
...binding.title ? { title: binding.title } : {},
|
|
96510
|
+
evidenceKind: binding.evidenceKind,
|
|
96511
|
+
...viewKind ? { viewKind } : {}
|
|
96512
|
+
});
|
|
96513
|
+
}
|
|
96514
|
+
if (unresolved.length) return reply.status(409).send({ ok: false, code: "sheet-identification-required", pages: unresolved.slice(0, 100), total: unresolved.length });
|
|
96515
|
+
const duplicateSheets = pages.map((page) => normalizedSheet(page.sheet)).filter((sheet, index, all) => all.indexOf(sheet) !== index);
|
|
96516
|
+
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(", ")}` });
|
|
96517
|
+
const modelPages = pages.filter(isModelPage);
|
|
96518
|
+
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" });
|
|
96519
|
+
let filter;
|
|
96520
|
+
let evidenceFilter;
|
|
96521
|
+
try {
|
|
96522
|
+
const extractor = deps.extractSteelFilter ?? extractSteelFilter;
|
|
96523
|
+
const sourceBytes = sources.manifestSources.reduce((sum2, source) => sum2 + source.bytes, 0);
|
|
96524
|
+
const streamBytes = steelStreamBytesOf(inspected);
|
|
96525
|
+
const extractionBudgetMs = steelExtractionBudgetMs(inspected.length, sources.extractorSources.length, sourceBytes, streamBytes);
|
|
96526
|
+
const extractionDeadline = steelExtractionDeadlineAt(subprocessStartedAt, inspected.length, sources.extractorSources.length, sourceBytes, streamBytes);
|
|
96527
|
+
req.log.info({
|
|
96528
|
+
projectId: project.id,
|
|
96529
|
+
requestId: request.id,
|
|
96530
|
+
deadlineMs: Math.round(extractionDeadline - subprocessStartedAt),
|
|
96531
|
+
maxAttemptMs: STEEL_EXTRACTION_MAX_ATTEMPT_MS,
|
|
96532
|
+
budgetMs: extractionBudgetMs,
|
|
96533
|
+
inspectionMs: Math.round(inspectionEndedAt - inspectionStartedAt),
|
|
96534
|
+
// Logged beside the budget it selected, so a timeout can be read against the input that
|
|
96535
|
+
// chose its deadline rather than leaving the reader to guess which arm won.
|
|
96536
|
+
pages: inspected.length,
|
|
96537
|
+
sources: sources.extractorSources.length,
|
|
96538
|
+
sourceBytes,
|
|
96539
|
+
streamBytes
|
|
96540
|
+
}, "steel filter extraction starting");
|
|
96541
|
+
const workloadFor = (selectedPageCount) => ({
|
|
96542
|
+
sourceCount: sources.extractorSources.length,
|
|
96543
|
+
sourceBytes,
|
|
96544
|
+
totalPageCount: inspected.length,
|
|
96545
|
+
selectedPageCount
|
|
96546
|
+
});
|
|
96547
|
+
const remaining2 = (phase2, workload) => {
|
|
96548
|
+
const value = Math.floor(extractionDeadline - now2());
|
|
96549
|
+
if (value <= 0) throw new SteelFilterTimeoutError(
|
|
96550
|
+
phase2,
|
|
96551
|
+
Math.max(0, Math.round(now2() - subprocessStartedAt)),
|
|
96552
|
+
Math.max(0, Math.round(extractionDeadline - subprocessStartedAt)),
|
|
96553
|
+
workload
|
|
96554
|
+
);
|
|
96555
|
+
return Math.max(1, value);
|
|
96556
|
+
};
|
|
96557
|
+
await withLifecycleLock("steel-extraction", "global", async () => {
|
|
96558
|
+
const evidenceWorkload = workloadFor(pages.length);
|
|
96559
|
+
evidenceFilter = await extractor({
|
|
96560
|
+
sources: sources.extractorSources,
|
|
96561
|
+
plans: pages.map((_page, index) => ({ sheet: `E${index + 1}` })),
|
|
96562
|
+
pages: pages.map((page, index) => ({ sourceHash: page.sourceHash, page: page.page, sheet: `E${index + 1}` }))
|
|
96563
|
+
}, { phase: "evidence", timeoutMs: remaining2("evidence", evidenceWorkload), workload: evidenceWorkload });
|
|
96564
|
+
const modelWorkload = workloadFor(modelPages.length);
|
|
96565
|
+
filter = await extractor({
|
|
96566
|
+
sources: sources.extractorSources,
|
|
96567
|
+
plans: modelPages.map((page) => ({ sheet: page.sheet, ...page.title ? { title: page.title } : {} })),
|
|
96568
|
+
pages: modelPages.map((page) => ({ sourceHash: page.sourceHash, page: page.page, sheet: page.sheet })),
|
|
96569
|
+
...currentObj?.filter === void 0 ? {} : { filter: currentObj.filter }
|
|
96570
|
+
}, { phase: "model", timeoutMs: remaining2("model", modelWorkload), workload: modelWorkload });
|
|
96571
|
+
evidenceFilter = currentSteelFilterResult(evidenceFilter);
|
|
96572
|
+
filter = currentSteelFilterResult(filter);
|
|
96573
|
+
}, { label: "preparing steel drawings", expectedMs: extractionBudgetMs, failFast: true });
|
|
96574
|
+
} catch (error) {
|
|
96575
|
+
if (error instanceof LifecycleLockBusyError) {
|
|
96576
|
+
const body = steelLifecycleBusyBody(error);
|
|
96577
|
+
reply.header("Retry-After", String(Math.ceil(body.retryAfterMs / 1e3)));
|
|
96578
|
+
return reply.status(409).send(body);
|
|
96579
|
+
}
|
|
96580
|
+
if (error instanceof SteelFilterCleanupStateError) {
|
|
96581
|
+
return reply.status(409).send({
|
|
96582
|
+
ok: false,
|
|
96583
|
+
code: "steel-manifest-preparation-blocked",
|
|
96584
|
+
error: error.message,
|
|
96585
|
+
recovery: "Check the prior Steel Filter process or restart FloLess. If no process remains, remove the stale steel-filter process claim before retrying."
|
|
96586
|
+
});
|
|
96587
|
+
}
|
|
96588
|
+
if (error instanceof SteelFilterCleanupPendingError) {
|
|
96589
|
+
reply.header("Retry-After", String(Math.ceil(error.retryAfterMs / 1e3)));
|
|
96590
|
+
return reply.status(409).send(steelCleanupPendingBody(error));
|
|
96591
|
+
}
|
|
96592
|
+
if (error instanceof SteelFilterTimeoutError) {
|
|
96593
|
+
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");
|
|
96594
|
+
const written = (deps.patchRequestDurable ?? patchRequestDurable)(request.id, {
|
|
96595
|
+
status: "pending",
|
|
96596
|
+
refusalCode: void 0,
|
|
96597
|
+
steelPreparationTimeout: steelTimeoutDiagnostics(error),
|
|
96598
|
+
error: void 0
|
|
96599
|
+
});
|
|
96600
|
+
if (!written) return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "the drawing read changed while recording its retryable interruption" });
|
|
96601
|
+
request = written;
|
|
96602
|
+
broadcast({ type: "requests-changed" });
|
|
96603
|
+
if (error.cleanup.state === "blocked") return reply.status(409).send(steelTimeoutCleanupBlockedBody(error));
|
|
96604
|
+
reply.header("Retry-After", String(Math.ceil(error.cleanup.retryAfterMs / 1e3)));
|
|
96605
|
+
return reply.status(409).send(steelTimeoutBody(error));
|
|
96606
|
+
}
|
|
96607
|
+
if (error instanceof SteelFilterBudgetError) {
|
|
96608
|
+
const labelByPage = new Map(pages.map((page) => [`${page.sourceHash} ${page.page}`, page.sheet]));
|
|
96609
|
+
const nameByHash = new Map(sources.manifestSources.map((source) => [source.sha256, source.name]));
|
|
96610
|
+
const overBudget = error.pages.map((row) => ({
|
|
96611
|
+
sheet: labelByPage.get(`${row.sourceHash} ${row.page}`) ?? `${nameByHash.get(row.sourceHash) ?? "source"} p.${row.page}`,
|
|
96612
|
+
sourceHash: row.sourceHash,
|
|
96613
|
+
page: row.page,
|
|
96614
|
+
count: row.count,
|
|
96615
|
+
bytes: row.bytes,
|
|
96616
|
+
// #1015: how much of this sheet was ALREADY dropped for painting nothing before it still
|
|
96617
|
+
// breached. Omitted rather than defaulted to 0 when the extractor did not report it -
|
|
96618
|
+
// a 0 would claim a measurement nobody made. Without this the field would be parsed and
|
|
96619
|
+
// then discarded here, which is a diagnostic that reaches nobody.
|
|
96620
|
+
...row.blankFills !== void 0 ? { blankFills: row.blankFills } : {}
|
|
96621
|
+
}));
|
|
96622
|
+
const bytesScope = error.scope === "bytes";
|
|
96623
|
+
req.log.warn({
|
|
96624
|
+
projectId: project.id,
|
|
96625
|
+
requestId: request.id,
|
|
96626
|
+
scope: error.scope,
|
|
96627
|
+
detectedBy: error.detectedBy,
|
|
96628
|
+
bytes: error.bytes,
|
|
96629
|
+
total: error.total,
|
|
96630
|
+
pages: error.pages.length,
|
|
96631
|
+
// Summed, not per-page: the log answers "how much was already removed and it STILL
|
|
96632
|
+
// breached", which is the operational question (#1015). Present ONLY when every row
|
|
96633
|
+
// reported it - the field is optional, so summing with `?? 0` over a partially-reporting
|
|
96634
|
+
// set would log a total that is silently short and read as a real measurement. That is the
|
|
96635
|
+
// same "absent is not zero" rule the refusal row above follows, and it has to hold here
|
|
96636
|
+
// too or the two disagree about what silence means.
|
|
96637
|
+
...error.pages.every((row) => row.blankFills !== void 0) ? { blankFills: error.pages.reduce((sum2, row) => sum2 + (row.blankFills ?? 0), 0) } : {}
|
|
96638
|
+
}, "steel filter extraction refused: over budget");
|
|
96639
|
+
const soleHeavySheet = bytesScope && (error.pages[0]?.bytes ?? 0) > (error.byteLimit ?? Infinity) ? overBudget[0] : void 0;
|
|
96640
|
+
const whole = error.complete === true;
|
|
96641
|
+
const measured = error.measuredPages;
|
|
96642
|
+
const sheetsSoFar = measured === null ? "The sheets measured so far" : `${measured} measured sheet${measured === 1 ? "" : "s"}`;
|
|
96643
|
+
const producePhrase = measured === 1 ? "produces" : "produce";
|
|
96644
|
+
const carryPhrase = measured === 1 ? "carries" : "carry";
|
|
96645
|
+
const unknownTail = error.totalPages === null && !whole ? " How much of the set that is was not established here." : "";
|
|
96646
|
+
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. `;
|
|
96647
|
+
return reply.status(400).send({
|
|
96648
|
+
ok: false,
|
|
96649
|
+
code: "steel-manifest-over-budget",
|
|
96650
|
+
scope: error.scope,
|
|
96651
|
+
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}`,
|
|
96652
|
+
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.`),
|
|
96653
|
+
// `total`/`limit` are ELEMENT counts, `bytes`/`byteLimit` are output size. Shipping the
|
|
96654
|
+
// whole-set count beside a per-sheet limit, or an element count beside a byte limit,
|
|
96655
|
+
// invites the reader to compare two numbers that answer different questions — so each is
|
|
96656
|
+
// null wherever it is not the bound. The unit split itself is decided once, on the error.
|
|
96657
|
+
total: error.scope === "page" ? null : bytesScope ? null : error.total,
|
|
96658
|
+
limit: error.elementLimit,
|
|
96659
|
+
bytes: error.bytes,
|
|
96660
|
+
byteLimit: error.byteLimit,
|
|
96661
|
+
// What the figures above actually cover, and every bound the measured sheets breach.
|
|
96662
|
+
complete: error.complete,
|
|
96663
|
+
measuredPages: error.measuredPages,
|
|
96664
|
+
totalPages: error.totalPages,
|
|
96665
|
+
breaches: error.breaches,
|
|
96666
|
+
overBudget: overBudget.slice(0, STEEL_READ_MAX_PAGES)
|
|
96667
|
+
});
|
|
96668
|
+
}
|
|
96669
|
+
if (error instanceof SteelFilterOutputTooLargeError) {
|
|
96670
|
+
return reply.status(400).send({
|
|
96671
|
+
ok: false,
|
|
96672
|
+
code: "steel-manifest-over-budget",
|
|
96673
|
+
error: "This drawing set is too large to process in a single read.",
|
|
96674
|
+
recovery: "Close this request and re-submit the drawing set as several materially smaller revisions.",
|
|
96675
|
+
// `scope: null` deliberately, not an omitted key: the terminal AI branches on `scope`
|
|
96676
|
+
// (see request-instruction.ts), and a branch table has to be total. This condition is not
|
|
96677
|
+
// one of the three bounds — it is the last-resort overflow, with nothing measured.
|
|
96678
|
+
//
|
|
96679
|
+
// `complete: null`, NOT false: overflow proves no coverage fact at all and can happen
|
|
96680
|
+
// before or after a full traversal. `false` is reserved for a VERIFIED proper subset of a
|
|
96681
|
+
// known page set, which is a different claim.
|
|
96682
|
+
scope: null,
|
|
96683
|
+
total: null,
|
|
96684
|
+
limit: null,
|
|
96685
|
+
bytes: null,
|
|
96686
|
+
byteLimit: null,
|
|
96687
|
+
complete: null,
|
|
96688
|
+
measuredPages: null,
|
|
96689
|
+
totalPages: null,
|
|
96690
|
+
breaches: [],
|
|
96691
|
+
overBudget: []
|
|
96692
|
+
});
|
|
96693
|
+
}
|
|
96694
|
+
if (error instanceof SteelFilterProcessError) {
|
|
96695
|
+
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");
|
|
96696
|
+
return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: error.message, diagnosticId: error.diagnosticId });
|
|
96697
|
+
}
|
|
96698
|
+
const diagnosticId = (0, import_node_crypto42.randomUUID)();
|
|
96699
|
+
req.log.warn({ projectId: project.id, requestId: request.id, diagnosticId, category: "result-validation" }, "steel manifest extraction failed");
|
|
96700
|
+
return reply.status(400).send({ ok: false, code: "steel-manifest-extraction-failed", error: "Steel Filter extraction failed.", diagnosticId });
|
|
96701
|
+
}
|
|
96702
|
+
filter = mergeWholeSetLayerCensus({ modelFilter: filter, evidenceFilter, priorFilter: currentObj?.filter });
|
|
96703
|
+
if (currentObj?.filter !== void 0 && hasCanonicalMode(currentObj.filter)) {
|
|
96704
|
+
filter = withPriorMode(filter, currentObj.filter);
|
|
96705
|
+
} else {
|
|
96706
|
+
filter = withUsableDefaultMode(filter);
|
|
96707
|
+
}
|
|
96708
|
+
filter = currentSteelFilterResult(filter);
|
|
96709
|
+
const evidenceSheets = evidenceFilter && typeof evidenceFilter === "object" && !Array.isArray(evidenceFilter) && Array.isArray(evidenceFilter.sheets) ? evidenceFilter.sheets : [];
|
|
96710
|
+
let stored2;
|
|
96711
|
+
try {
|
|
96712
|
+
const manifestPages = buildCompactManifestPages(pages, evidenceSheets, filter);
|
|
96713
|
+
hardDeadline = steelOperationDeadlineAt(now2());
|
|
96714
|
+
const scaleProposals = proposeSheetScales({
|
|
96715
|
+
filter,
|
|
96716
|
+
pages: manifestPages.map((page) => ({
|
|
96717
|
+
sheet: page.sheet ?? "",
|
|
96718
|
+
sourceHash: page.sourceHash,
|
|
96719
|
+
pageId: page.id,
|
|
96720
|
+
page: page.page,
|
|
96721
|
+
...page.viewKind === void 0 ? {} : { viewKind: page.viewKind }
|
|
96722
|
+
})).filter((page) => page.sheet !== ""),
|
|
96723
|
+
environment: project.environment,
|
|
96724
|
+
// Scale fitting gets its own operation deadline after extraction, WITH the clock it is expressed in —
|
|
96725
|
+
// one object, because they are meaningless apart: this deadline is a `performance.now()`
|
|
96726
|
+
// value, and comparing it against a `Date.now()` clock would exceed the budget on every
|
|
96727
|
+
// sheet and silently return the reader to hand-fitting. `steelOperationDeadlineAt` keeps
|
|
96728
|
+
// the bounded addition in one home while this phase starts from its own current clock.
|
|
96729
|
+
budget: { deadlineAt: hardDeadline, now: now2 }
|
|
96730
|
+
});
|
|
96731
|
+
stored2 = writeSteelReadManifest({
|
|
96732
|
+
version: 1,
|
|
96733
|
+
extractorVersion: STEEL_FILTER_EXTRACTOR_VERSION,
|
|
96734
|
+
requestId: request.id,
|
|
96735
|
+
projectId: project.id,
|
|
96736
|
+
appId: project.app,
|
|
96737
|
+
sources: sources.manifestSources,
|
|
96738
|
+
pages: manifestPages,
|
|
96739
|
+
filter,
|
|
96740
|
+
candidatesRepr: "v2-compact",
|
|
96741
|
+
// Minted in the SAME write as the merged filter, so the marker and the thing it describes
|
|
96742
|
+
// cannot disagree. A manifest without it is a pre-slice-2a, model-pages-only census: it
|
|
96743
|
+
// still reads and audits, it simply cannot carry a layer sign-off until it is regenerated.
|
|
96744
|
+
censusScope: "whole-set"
|
|
96745
|
+
}, void 0, { scaleProposals });
|
|
96746
|
+
} catch (error) {
|
|
96747
|
+
if (error instanceof SteelReadPageBudgetError) {
|
|
96748
|
+
req.log.warn({ projectId: project.id, requestId: request.id, pages: error.pages.slice(0, 20) }, "steel manifest sheet over the per-sheet element budget");
|
|
96749
|
+
return reply.status(400).send({
|
|
96750
|
+
ok: false,
|
|
96751
|
+
code: "steel-manifest-over-budget",
|
|
96752
|
+
scope: "page",
|
|
96753
|
+
error: error.message,
|
|
96754
|
+
recovery: `Close this request and re-submit without that sheet, or split its content across sheets so each stays under ${error.limit} elements.`,
|
|
96755
|
+
total: null,
|
|
96756
|
+
limit: error.limit,
|
|
96757
|
+
bytes: null,
|
|
96758
|
+
byteLimit: null,
|
|
96759
|
+
// Complete by construction: this measures a manifest that was already built in full, so
|
|
96760
|
+
// there is no early stop and no subset — unlike the extractor's own refusal above.
|
|
96761
|
+
complete: true,
|
|
96762
|
+
measuredPages: error.pages.length,
|
|
96763
|
+
totalPages: error.pages.length,
|
|
96764
|
+
breaches: [{ scope: "page", limit: error.limit }],
|
|
96765
|
+
// `bytes: null` on every row, so a consumer sees ONE row shape under this code rather
|
|
96766
|
+
// than having to discover that the write path omits the key the read path always sends.
|
|
96767
|
+
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 }))
|
|
96768
|
+
});
|
|
96769
|
+
}
|
|
96770
|
+
if (!(error instanceof SteelManifestCoverageError) && !(error instanceof SteelReadManifestInvalidError)) throw error;
|
|
96771
|
+
const diagnostic = error instanceof SteelManifestCoverageError ? error.diagnostic : void 0;
|
|
96772
|
+
req.log.warn({ projectId: project.id, requestId: request.id, diagnostic, error: error.message }, "steel manifest could not be represented deterministically");
|
|
96773
|
+
return reply.status(400).send({
|
|
96774
|
+
ok: false,
|
|
96775
|
+
code: "steel-manifest-extraction-failed",
|
|
96776
|
+
error: "the extracted drawing set could not be represented deterministically for a completion proof",
|
|
96777
|
+
// The client here is the terminal AI, and this condition is NOT user-authorable — the two
|
|
96778
|
+
// extraction passes disagreed about the same page bytes. Say so, so it stops rather than
|
|
96779
|
+
// retrying a call that will fail identically every time.
|
|
96780
|
+
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.",
|
|
96781
|
+
...diagnostic ? { diagnostic } : {}
|
|
96782
|
+
});
|
|
96783
|
+
}
|
|
96784
|
+
let writtenEtag;
|
|
96785
|
+
if (currentObj) {
|
|
96786
|
+
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" });
|
|
96787
|
+
try {
|
|
96788
|
+
const written = await writeContractChecked(project.app, { ...currentObj, filter }, project.id, { origin: "internal", why: "server-owned steel source manifest" });
|
|
96789
|
+
writtenEtag = written.etag;
|
|
96790
|
+
clearApproval(project.id);
|
|
96791
|
+
broadcast(contractChangedWithReason(project.app, project.id, written.etag, written.storeRevision, "revision-read"));
|
|
96792
|
+
} catch (error) {
|
|
96793
|
+
if (error instanceof ContractError) return reply.status(400).send({ ok: false, code: error.code, error: error.message });
|
|
96794
|
+
throw error;
|
|
96795
|
+
}
|
|
96796
|
+
}
|
|
96797
|
+
const updated = patchRequest(request.id, {
|
|
96798
|
+
prepassReady: writtenEtag !== void 0,
|
|
96799
|
+
prepassEtag: writtenEtag,
|
|
96800
|
+
filterSaved: false,
|
|
96801
|
+
filterSavedEtag: void 0,
|
|
96802
|
+
steelManifestHash: stored2.manifestHash,
|
|
96803
|
+
steelSavedFilterHash: void 0
|
|
96177
96804
|
});
|
|
96178
|
-
|
|
96179
|
-
|
|
96180
|
-
|
|
96181
|
-
|
|
96182
|
-
|
|
96183
|
-
|
|
96184
|
-
|
|
96185
|
-
|
|
96186
|
-
|
|
96187
|
-
|
|
96188
|
-
|
|
96189
|
-
|
|
96190
|
-
|
|
96191
|
-
|
|
96192
|
-
|
|
96193
|
-
|
|
96194
|
-
|
|
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 }
|
|
96805
|
+
if (!updated) return reply.status(409).send({ ok: false, error: "the revision request changed while publishing its steel manifest" });
|
|
96806
|
+
broadcast({ type: "request-added", request: requestView(updated) });
|
|
96807
|
+
return {
|
|
96808
|
+
ok: true,
|
|
96809
|
+
manifestHash: stored2.manifestHash,
|
|
96810
|
+
etag: writtenEtag ?? null,
|
|
96811
|
+
requiresCheckpointCreate: !currentObj,
|
|
96812
|
+
pages: stored2.manifest.pages,
|
|
96813
|
+
filter,
|
|
96814
|
+
...stored2.scaleProposals === void 0 ? {} : { scaleProposals: stored2.scaleProposals }
|
|
96815
|
+
};
|
|
96816
|
+
}, {
|
|
96817
|
+
// A retry must not wait 60 seconds behind the long inventory and then start a second scan.
|
|
96818
|
+
// The first handler keeps running after an HTTP disconnect; this projection makes later calls
|
|
96819
|
+
// fail fast as busy until that handler publishes the durable checkpoint.
|
|
96820
|
+
label: "inspecting steel drawings",
|
|
96821
|
+
expectedMs: 2 * 60 * 6e4
|
|
96214
96822
|
});
|
|
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
96823
|
} catch (error) {
|
|
96231
|
-
if (error instanceof
|
|
96232
|
-
|
|
96233
|
-
|
|
96234
|
-
|
|
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({
|
|
96824
|
+
if (!(error instanceof LifecycleLockBusyError)) throw error;
|
|
96825
|
+
const retryAfterMs = Math.max(1e3, Math.min(3e4, error.busy.remainingMs ?? 5e3));
|
|
96826
|
+
reply.header("Retry-After", String(Math.ceil(retryAfterMs / 1e3)));
|
|
96827
|
+
return reply.status(409).send({
|
|
96258
96828
|
ok: false,
|
|
96259
|
-
code: "steel-manifest-
|
|
96260
|
-
error: "
|
|
96261
|
-
|
|
96262
|
-
|
|
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 } : {}
|
|
96829
|
+
code: "steel-manifest-preparation-busy",
|
|
96830
|
+
error: "This drawing set is already being inspected.",
|
|
96831
|
+
recovery: "Wait, then retry this same request. The active inspection will publish a reusable checkpoint when it finishes.",
|
|
96832
|
+
retryAfterMs
|
|
96266
96833
|
});
|
|
96267
96834
|
}
|
|
96268
|
-
|
|
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
|
-
})
|
|
96835
|
+
}
|
|
96301
96836
|
);
|
|
96302
96837
|
app.get(
|
|
96303
96838
|
"/api/projects/:id/revision-requests/:reqId/steel-manifest",
|
|
@@ -116286,7 +116821,20 @@ async function finish(deps, lease, patch2, options = {}) {
|
|
|
116286
116821
|
}
|
|
116287
116822
|
cleanupMcpConfig(lease.leaseId);
|
|
116288
116823
|
if (contained) {
|
|
116289
|
-
|
|
116824
|
+
let leaseTerminalRefusal;
|
|
116825
|
+
let durableLease = lease;
|
|
116826
|
+
try {
|
|
116827
|
+
durableLease = (deps.readLease ?? getLease)(lease.leaseId) ?? lease;
|
|
116828
|
+
leaseTerminalRefusal = durableLease.terminalRefusalCode === "steel-manifest-extraction-timeout";
|
|
116829
|
+
} catch (error) {
|
|
116830
|
+
locallyRevokedRelayLeases.add(lease.leaseId);
|
|
116831
|
+
try {
|
|
116832
|
+
revokeLeaseRelay(lease.leaseId, lease.generation);
|
|
116833
|
+
} catch {
|
|
116834
|
+
}
|
|
116835
|
+
console.error(`[terminal-run] could not verify terminal refusal authority for ${lease.requestId}; lease held:`, error);
|
|
116836
|
+
return;
|
|
116837
|
+
}
|
|
116290
116838
|
let requestTerminalRefusal = false;
|
|
116291
116839
|
try {
|
|
116292
116840
|
requestTerminalRefusal = deps.getRequest(lease.requestId)?.run?.refusalCode === "steel-manifest-extraction-timeout";
|
|
@@ -116348,7 +116896,7 @@ async function finish(deps, lease, patch2, options = {}) {
|
|
|
116348
116896
|
return;
|
|
116349
116897
|
}
|
|
116350
116898
|
}
|
|
116351
|
-
const terminalRecoveryForbidden = leaseTerminalRefusal || requestTerminalRefusal;
|
|
116899
|
+
const terminalRecoveryForbidden = leaseTerminalRefusal || requestTerminalRefusal || lease.requestType === "revision-read" && !durableLease.resolvedAt;
|
|
116352
116900
|
const interactive = Boolean(
|
|
116353
116901
|
lease.requestType !== "guide" && !terminalRecoveryForbidden && lease.sessionId && patch2.state && INTERACTIVE_RECOVERY_STATES.has(patch2.state) && canOfferInteractiveRecovery(lease)
|
|
116354
116902
|
);
|
|
@@ -116686,8 +117234,7 @@ function exactLeasedRequest(deps, lease) {
|
|
|
116686
117234
|
}
|
|
116687
117235
|
return req;
|
|
116688
117236
|
}
|
|
116689
|
-
function
|
|
116690
|
-
const req = exactLeasedRequest(deps, lease);
|
|
117237
|
+
function verifyRevisionRequestSources(deps, req) {
|
|
116691
117238
|
if (req.type !== "revision-read" || !req.sourceRefs?.length || req.sourceRefs.length !== req.snapshots?.length) {
|
|
116692
117239
|
throw new Error("the queued revision PDF set no longer matches this run");
|
|
116693
117240
|
}
|
|
@@ -116700,6 +117247,9 @@ function verifyRevisionSources(deps, lease) {
|
|
|
116700
117247
|
}
|
|
116701
117248
|
});
|
|
116702
117249
|
}
|
|
117250
|
+
function verifyRevisionSources(deps, lease) {
|
|
117251
|
+
verifyRevisionRequestSources(deps, exactLeasedRequest(deps, lease));
|
|
117252
|
+
}
|
|
116703
117253
|
async function runRevisionPrepass(deps, lease) {
|
|
116704
117254
|
verifyRevisionSources(deps, lease);
|
|
116705
117255
|
const req = exactLeasedRequest(deps, lease);
|
|
@@ -116717,6 +117267,25 @@ async function runRevisionPrepass(deps, lease) {
|
|
|
116717
117267
|
if (written.status === 409 && written.body?.code === "sheet-identification-required") {
|
|
116718
117268
|
return { ok: false, needsInput: true, code: "sheet-identification-required", pages: written.body.pages };
|
|
116719
117269
|
}
|
|
117270
|
+
if (written.status === 409 && ["steel-manifest-extraction-interrupted", "steel-manifest-inspection-interrupted", "steel-manifest-preparation-busy"].includes(String(written.body?.code ?? ""))) {
|
|
117271
|
+
const body = written.body;
|
|
117272
|
+
if (!Number.isSafeInteger(body.retryAfterMs) || Number(body.retryAfterMs) < 1) {
|
|
117273
|
+
throw new Error("Steel Filter preparation returned a retryable response without a valid retry delay.");
|
|
117274
|
+
}
|
|
117275
|
+
return {
|
|
117276
|
+
ok: false,
|
|
117277
|
+
retryable: true,
|
|
117278
|
+
code: body.code,
|
|
117279
|
+
retryAfterMs: body.retryAfterMs,
|
|
117280
|
+
...typeof body.error === "string" ? { error: body.error } : {},
|
|
117281
|
+
...typeof body.recovery === "string" ? { recovery: body.recovery } : {},
|
|
117282
|
+
...typeof body.diagnosticId === "string" ? { diagnosticId: body.diagnosticId } : {},
|
|
117283
|
+
...typeof body.phase === "string" ? { phase: body.phase } : {},
|
|
117284
|
+
...Number.isSafeInteger(body.elapsedMs) ? { elapsedMs: body.elapsedMs } : {},
|
|
117285
|
+
...Number.isSafeInteger(body.timeoutMs) ? { timeoutMs: body.timeoutMs } : {},
|
|
117286
|
+
...body.workload && typeof body.workload === "object" && !Array.isArray(body.workload) ? { workload: body.workload } : {}
|
|
117287
|
+
};
|
|
117288
|
+
}
|
|
116720
117289
|
if (written.status === 409 && written.body?.code === "steel-manifest-preparation-blocked") {
|
|
116721
117290
|
const blocked = new Error("Steel Filter preparation is blocked by an unverifiable prior process claim. Check or repair that claim before retrying.");
|
|
116722
117291
|
blocked.name = "SteelManifestPreparationBlockedError";
|
|
@@ -116933,10 +117502,56 @@ function registerTerminalRunRoutes(app, deps) {
|
|
|
116933
117502
|
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
117503
|
});
|
|
116935
117504
|
}
|
|
116936
|
-
|
|
117505
|
+
let req = Object.freeze({ ...resolvedRequest });
|
|
116937
117506
|
const eligibility = deps.eligibility?.(req) ?? runEligibilityFor(req);
|
|
116938
117507
|
if (!eligibility.runnable) return reply.status(400).send({ ok: false, error: eligibility.why, code: "not-runnable" });
|
|
116939
117508
|
const policy = eligibility.policy;
|
|
117509
|
+
if (req.type === "revision-read" && req.status === "failed" && hasRetryablePreparationRefusal(req)) {
|
|
117510
|
+
try {
|
|
117511
|
+
verifyRevisionRequestSources(deps, req);
|
|
117512
|
+
if (req.run?.leaseId) {
|
|
117513
|
+
const presence2 = expectedLeasePresence(req.run.leaseId, req.run.cwd);
|
|
117514
|
+
if (presence2.state !== "absent") {
|
|
117515
|
+
return reply.status(409).send({
|
|
117516
|
+
ok: false,
|
|
117517
|
+
code: presence2.state === "present" || presence2.state === "mismatched" ? "revision-read-owned" : "revision-read-lifecycle-unavailable",
|
|
117518
|
+
error: presence2.state === "present" || presence2.state === "mismatched" ? "This interrupted drawing preparation is still owned by a terminal run. Stop or recover that run before retrying." : "FloLess could not prove that the interrupted drawing preparation released its terminal run."
|
|
117519
|
+
});
|
|
117520
|
+
}
|
|
117521
|
+
}
|
|
117522
|
+
if (req.run && (req.run.state === "queued" || req.run.state === "running" || req.run.processContained === false)) {
|
|
117523
|
+
return reply.status(409).send({
|
|
117524
|
+
ok: false,
|
|
117525
|
+
code: "revision-read-lifecycle-unavailable",
|
|
117526
|
+
error: "FloLess has not proved that the interrupted terminal process is contained."
|
|
117527
|
+
});
|
|
117528
|
+
}
|
|
117529
|
+
const diagnostic = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
|
|
117530
|
+
const migrated = deps.patchRequestDurable(req.id, {
|
|
117531
|
+
status: "pending",
|
|
117532
|
+
refusalCode: void 0,
|
|
117533
|
+
steelPreparationTimeout: diagnostic,
|
|
117534
|
+
error: void 0,
|
|
117535
|
+
...req.run ? { run: { ...req.run, refusalCode: void 0 } } : {}
|
|
117536
|
+
});
|
|
117537
|
+
if (!migrated) {
|
|
117538
|
+
return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "The drawing read changed before its interrupted inspection could resume." });
|
|
117539
|
+
}
|
|
117540
|
+
const enriched = deps.resolveRequest ? deps.resolveRequest(migrated) : migrated;
|
|
117541
|
+
if (!enriched) {
|
|
117542
|
+
return reply.status(409).send({ ok: false, code: "revision-request-changed", error: "The drawing read changed before its interrupted inspection could resume." });
|
|
117543
|
+
}
|
|
117544
|
+
req = Object.freeze({ ...enriched });
|
|
117545
|
+
deps.broadcast({ type: "requests-changed" });
|
|
117546
|
+
} catch (error) {
|
|
117547
|
+
request.log.error({ err: String(error) }, "legacy preparation retry migration failed");
|
|
117548
|
+
return reply.status(503).send({
|
|
117549
|
+
ok: false,
|
|
117550
|
+
code: "revision-request-unavailable",
|
|
117551
|
+
error: "FloLess could not make the interrupted drawing preparation resumable. Restart FloLess and try again."
|
|
117552
|
+
});
|
|
117553
|
+
}
|
|
117554
|
+
}
|
|
116940
117555
|
const requestPrompt = deps.buildPrompt(req);
|
|
116941
117556
|
if (!requestPrompt.trim()) {
|
|
116942
117557
|
return reply.status(400).send({
|