@floless/app 0.174.0 → 0.175.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/autostart.mjs +117 -10
  2. package/dist/floless-server.cjs +2 -2
  3. package/dist/pdf-engine/floless_pdf/__init__.py +53 -0
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +823 -0
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +245 -0
  6. package/dist/pdf-engine/floless_pdf/geometry.py +115 -0
  7. package/dist/pdf-engine/floless_pdf/images.py +75 -0
  8. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  9. package/dist/pdf-engine/floless_pdf/textrules.py +200 -0
  10. package/dist/schemas/steel.model.v2.schema.json +45 -1
  11. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  12. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  13. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  14. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  15. package/dist/skills/floless-app-steel-model/SKILL.md +14 -1
  16. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  17. package/dist/skills/floless-app-steel-takeoff/SKILL.md +18 -7
  18. package/dist/skills/floless-app-tweak-contract/SKILL.md +3 -2
  19. package/dist/web/agents.js +1 -1
  20. package/dist/web/app.css +120 -15
  21. package/dist/web/app.js +89 -38
  22. package/dist/web/aware-hold.js +10 -0
  23. package/dist/web/aware.js +405 -51
  24. package/dist/web/boot-watchdog.js +249 -0
  25. package/dist/web/card-details.js +88 -0
  26. package/dist/web/chat.css +29 -0
  27. package/dist/web/chat.js +430 -128
  28. package/dist/web/commands-connection-design.js +23 -0
  29. package/dist/web/commands-revit.js +3 -0
  30. package/dist/web/commands-shell.js +226 -10
  31. package/dist/web/commands-steel.js +95 -5
  32. package/dist/web/commands-tekla-parser.js +21 -1
  33. package/dist/web/connection-design-editor.html +71 -0
  34. package/dist/web/connection-design-editor.js +794 -61
  35. package/dist/web/connection-design-handles.js +9 -3
  36. package/dist/web/element-approval.js +74 -0
  37. package/dist/web/element-context.js +76 -6
  38. package/dist/web/element-geometry.js +8 -2
  39. package/dist/web/element-holds.js +68 -5
  40. package/dist/web/element-type-actions.js +22 -3
  41. package/dist/web/element-types.js +12 -5
  42. package/dist/web/element-words.js +15 -11
  43. package/dist/web/grid-place.js +51 -0
  44. package/dist/web/guide.js +2 -0
  45. package/dist/web/index.html +13 -16
  46. package/dist/web/instructor.js +5 -2
  47. package/dist/web/missed-routines.js +6 -1
  48. package/dist/web/model-change-findings.js +147 -32
  49. package/dist/web/model-change-review.js +435 -32
  50. package/dist/web/model-clash-check.css +100 -0
  51. package/dist/web/model-clash-check.js +681 -0
  52. package/dist/web/model-clip-box.js +204 -0
  53. package/dist/web/model-clip-list.js +153 -3
  54. package/dist/web/model-clip-session.js +3 -3
  55. package/dist/web/model-clip-three-overlay.js +135 -25
  56. package/dist/web/model-editor.css +2 -0
  57. package/dist/web/model-elements.js +273 -18
  58. package/dist/web/model-fit-checks.js +354 -0
  59. package/dist/web/model-spatial-panel.js +9 -3
  60. package/dist/web/model-spatial-tools.js +12 -3
  61. package/dist/web/model-tekla-selection.js +74 -0
  62. package/dist/web/model-view-query.js +70 -14
  63. package/dist/web/model-viewport-revit-adapter.js +8 -7
  64. package/dist/web/model-viewport-toolbar.js +8 -4
  65. package/dist/web/pages.js +78 -1
  66. package/dist/web/project-history.js +31 -1
  67. package/dist/web/revit-editor.css +34 -1
  68. package/dist/web/revit-editor.js +176 -55
  69. package/dist/web/run-history.js +8 -0
  70. package/dist/web/sketch-editor.js +141 -2
  71. package/dist/web/sketches.js +192 -6
  72. package/dist/web/start-place.js +46 -0
  73. package/dist/web/steel-3d-core.js +70 -0
  74. package/dist/web/steel-3d-view.js +288 -47
  75. package/dist/web/steel-change-review.css +29 -0
  76. package/dist/web/steel-custom-connection.js +6 -0
  77. package/dist/web/steel-editor.html +532 -33
  78. package/dist/web/steel-filter.html +8 -3
  79. package/dist/web/steel-model-checks.css +76 -0
  80. package/dist/web/steel-model-commands.js +1 -1
  81. package/dist/web/steel-model-v2-commands.js +17 -0
  82. package/dist/web/steel-view-generation.js +6 -2
  83. package/dist/web/teams.js +259 -19
  84. package/dist/web/tekla-editor.html +1 -0
  85. package/dist/web/terminal-requests.js +6 -0
  86. package/dist/web/vendor/connection-engine.js +890 -89
  87. package/dist/web/workspaces.js +630 -48
  88. package/package.json +4 -1
  89. package/preferences-file.mjs +27 -0
@@ -26,8 +26,9 @@ import { CATALOGUE_ENTRY_KEYS, CATALOGUE_NS, ENVELOPE_VERSION, FOOTING, MODEL_NS
26
26
  import { elementEnvironment, evaluationContextFor } from './element-context.js';
27
27
  import { catalogueTypeId, makeCatalogueType, parseCatalogueInputs, sealModelType, typeDisplayName, typeIdHolds, typeInputs } from './element-types.js';
28
28
  import { drawableGeometry, isPoint2, signedArea } from './element-geometry.js';
29
- import { acceptanceBinds } from './element-binding.js';
30
- import { TYPE_CARD, TYPE_CHOICE_OPEN, TYPE_NOT_MADE_HERE, evaluateElements, statusesOf, typeNamesFor, waysOnOf } from './element-holds.js';
29
+ import { acceptanceBinds, boundDensityAssumption, elementBase } from './element-binding.js';
30
+ import { HOLD_CODES, TYPE_CARD, TYPE_CHOICE_OPEN, TYPE_NOT_MADE_HERE, evaluateElements, statusesOf, typeNamesFor, waysOnOf } from './element-holds.js';
31
+ import { approvalDensityDrift, approvedRowOf, approvedSourcesOf, catalogueStateOf } from './element-approval.js';
31
32
 
32
33
  export {
33
34
  CATALOGUE_NS, ELEMENT_ID_PATTERN, ELEMENT_KINDS, ENVELOPE_VERSION, EVALUATOR_VERSION, ElementError, FOOTING,
@@ -36,7 +37,7 @@ export {
36
37
  materialProblems, modelTypeKeyOf, modelTypeKeysOf, typeIdsOf, typeKeysOf
37
38
  } from './element-base.js';
38
39
  export {
39
- elementEnvironment, useMaterialCatalogue
40
+ elementEnvironment, serializableEvaluation, useMaterialCatalogue
40
41
  } from './element-context.js';
41
42
  export {
42
43
  assignmentV1Problems, catalogueDensity, catalogueTypeId, catalogueTypeProblem, derivePayload,
@@ -51,7 +52,7 @@ export {
51
52
  acceptanceBinds, boundDensityAssumption, densityBinding, elementBase, elementInputsDigest, storedValuesHold
52
53
  } from './element-binding.js';
53
54
  export {
54
- ELEMENT_FIT_NOT_CHECKED, elementPlanNote
55
+ ELEMENT_FIT_UNREAD, STEEL_MEETS_CONCRETE_NOT_CHECKED, elementPlanNote
55
56
  } from './element-words.js';
56
57
  export {
57
58
  HOLD_CODES, ELEMENT_STATUSES, KEEP_HELD, ACCEPT_DENSITY, personDensitySentence, densityMissingSentence, TYPE_CARD, REGISTRY_UNCHECKED_SENTENCE, TYPE_CHOICE_OPEN, TYPE_NOT_MADE_HERE, TYPE_RECORD_UNCHECKED, KIND_VERSION_UNREADABLE, TYPE_NOT_CATALOGUE, TYPE_OTHER_KIND, DENSITY_MISSING, PLACEMENT_INVALID, INPUT_INVALID, CORNER_INVALID, CORNER_PARTNER_HELD, UNDER_HELD_WALL, typeNamesFor, typeChoiceSentence, unmodelledSentence, evaluateElements, holdsFor, holdsOfModel, statusOf, statusesOf, keepRecord, keepHeldAllowed, endedKeepExplanation, endLapsedKeeps, reasonsOf, reasonKey, nothingKeptSentence, nothingKeptCard, cornerPostBuildFault, waysOnOf, wayActionsOf, savedValueOffers, savedResultBinds,
@@ -499,10 +500,161 @@ export function verifyElements(doc, opts = {}) {
499
500
 
500
501
  /**
501
502
  * Where an element's densities come from, said on every element a reply describes (plain B1 of the 2026-11-17
502
- * round-9-stop ruling): today's catalogue, never a comparison with the approved version, which this FloLess does not
503
- * make yet.
503
+ * round-9-stop ruling): today's catalogue, compared with the approved version where the project has one (#3680 part C;
504
+ * what the comparison found is each element's `densityChangedSinceApproval`, never folded into this sentence).
504
505
  */
505
- export const DENSITY_BASIS = 'worked out from the current catalogue; FloLess does not compare densities with the approved version yet';
506
+ export const DENSITY_BASIS = 'worked out from the current catalogue; compared with the approved version where one exists';
507
+
508
+ // ---- the comparison with the approved version, in words (#3680 part C, C1; plan 2026-11-22-e1c-part-c-PLAN.md) ----
509
+
510
+ /** The day of an approval, as every label says it. */
511
+ const dayOf = (at) => (typeof at === 'string' && /^\d{4}-\d{2}-\d{2}/.test(at) ? at.slice(0, 10) : 'an unknown date');
512
+ /** The one wording of "nothing changed" (X33): always with its date, never a bare "Unchanged". */
513
+ export const densitiesUnchangedLabel = (at) => `Densities unchanged since approval on ${dayOf(at)}`;
514
+ /** An element the approved version did not hold. */
515
+ export const newSinceApprovalLabel = (version) => `New since approval v${version}; its density was not part of that approval`;
516
+ /** An element the approved version holds with no saved values: there is nothing to compare. */
517
+ export const NOT_COMPARED_LABEL = 'Not compared: the approved version has no saved values for it';
518
+ /** An element approved with saved values that name no material layer. */
519
+ export const NO_LAYERS_LABEL = 'Not compared: the approved version names no material for it';
520
+
521
+ /**
522
+ * Why the approved version could not be proven (`server/approval-ledger.ts` `ApprovalUnavailableReason`), in a
523
+ * detailer's words. An unknown code still reads as a reason, never as "nothing to compare".
524
+ */
525
+ const UNAVAILABLE_WORDS = Object.freeze({
526
+ 'project-unknown': 'FloLess could not find this project\'s record',
527
+ 'ledger-missing': 'the list of saved versions is missing, though the project shows an approval',
528
+ 'ledger-unreadable': 'the saved versions could not be read just now; try again',
529
+ 'ledger-invalid': 'the list of saved versions is damaged',
530
+ 'ledger-over-budget': 'the list of saved versions is too large to check',
531
+ 'versions-unreadable': 'the saved versions could not be read just now; try again',
532
+ 'snapshot-orphaned': 'a saved version is not in the list of saved versions',
533
+ 'snapshot-unreadable': 'a saved version is missing, damaged or not this project\'s',
534
+ 'snapshot-over-budget': 'the approved versions are too large to check',
535
+ 'approval-unproven': 'an approved version carries no approval record',
536
+ 'approval-malformed': 'an approval record is not on an approved version',
537
+ 'approval-foreign': 'an approval record belongs to another project',
538
+ 'approval-hash': 'the approved version does not match the model that was approved',
539
+ 'approval-operation': 'an approval was started, but no saved version matches it',
540
+ 'approved-at-unaccounted': 'the project says it was approved, but no approved version is saved',
541
+ });
542
+ /** What a save warning offers for a density changed since approval (C5): never "resolve-save corrected" alone. */
543
+ export const DRIFT_ANSWERS = 're-approve to accept the new catalogue value (the approval screen), or keep the saved values as an unverified assumption (keep-held-as-assumption)';
544
+ /** "Could not compare…" with its reason, for a code. */
545
+ export const comparisonUnavailableLabel = (reason) => `Could not compare densities with the approved version: ${UNAVAILABLE_WORDS[reason] ?? 'the saved versions could not be checked'}`;
546
+
547
+ /** A layer's catalogue state, as a label says it. */
548
+ function stateWords(c, other) {
549
+ if (!isObj(c)) return 'not in the catalogue';
550
+ const d = c.kgM3 === null ? 'no density in the catalogue' : `${c.kgM3} kg/m³`;
551
+ // The same figure from another catalogue version or source: say which, or the change reads as no change at all.
552
+ const same = isObj(other) && other.kgM3 === c.kgM3;
553
+ return same ? `${d} (${c.providerId ?? 'unknown catalogue'} ${c.providerVersion ?? ''}${other.providerVersion === c.providerVersion && c.sourceSha256 ? `, source ${c.sourceSha256.slice(0, 12)}` : ''})`.replace(/ \)/, ')') : d;
554
+ }
555
+ /** A material row's short name: `eu-material:C30/37` → `C30/37`. */
556
+ const rowName = (catalogId) => (typeof catalogId === 'string' && catalogId.includes(':') ? catalogId.slice(catalogId.indexOf(':') + 1) : String(catalogId ?? 'its material'));
557
+
558
+ /**
559
+ * What the comparison says of one element (`densityChangedSinceApproval` on every element reply, and the sinks'
560
+ * `densityComparison`): `changed` (with the approved version, its date, each changed layer's was/now and whether the
561
+ * person keeps the saved values), `unchanged`, `new` (not in the approval), `not-compared` (approved with no saved
562
+ * values), `unavailable` (the approval could not be proven, with its reason), or null when the project has no approval.
563
+ * It reads the same frozen approval and catalogue snapshot the engine held on, so a label never disagrees with a hold.
564
+ * @param {any} ctx an `evaluationContextFor` context
565
+ * @param {string} id
566
+ * @param {any} [result] the element's `evaluateElements` result, to say whether the change is kept
567
+ */
568
+ export function densityComparisonOf(ctx, id, result = undefined) {
569
+ const a = ctx?.approval;
570
+ if (!isObj(a) || a.state === 'none') return null;
571
+ if (a.state !== 'approved') return { state: 'unavailable', reason: String(a.reason ?? 'approval-malformed'), label: comparisonUnavailableLabel(a.reason) };
572
+ const sources = approvedSourcesOf(a, id);
573
+ if (sources === undefined) return { state: 'new', approvedVersion: a.version, label: newSinceApprovalLabel(a.version) };
574
+ if (!Array.isArray(sources)) return { state: 'not-compared', approvedVersion: a.version, approvedAt: a.at, label: NOT_COMPARED_LABEL };
575
+ if (!sources.length) return { state: 'not-compared', approvedVersion: a.version, approvedAt: a.at, label: NO_LAYERS_LABEL };
576
+ const d = approvalDensityDrift(a, id, ctx.resolve);
577
+ if (!d) return { state: 'unchanged', approvedVersion: a.version, approvedAt: a.at, label: densitiesUnchangedLabel(a.at) };
578
+ const changes = d.layers.map((l) => ({ class: l.class, environment: l.environment, catalogId: l.catalogId, was: l.was, now: l.now }));
579
+ const words = changes.map((l) => `${rowName(l.catalogId)} was ${stateWords(l.was, l.now)}, now ${stateWords(l.now, l.was)}`).join('; ');
580
+ const kept = !!(result?.holds?.keptBy && [...result.holds.reasons.values()].some((r) => r.code === HOLD_CODES.DENSITY_CHANGED_SINCE_APPROVAL));
581
+ return {
582
+ state: 'changed', approvedVersion: d.approvedVersion, approvedAt: d.approvedAt, changes, kept,
583
+ label: `Density changed since approval v${d.approvedVersion} on ${dayOf(d.approvedAt)}: ${words}`,
584
+ };
585
+ }
586
+
587
+ /** What approving does to an element whose density the approval compares (C4), as the approval screen says it. */
588
+ export const APPROVAL_DENSITY_OUTCOMES = Object.freeze({
589
+ cleared: 'its saved values are worked out on today\'s density, so approving records that density and clears the flag',
590
+ 'stays-flagged': 'its saved values in this approval are still on the old density, so it stays flagged after approving until they are worked out again',
591
+ 'no-stored-result': 'it has no saved values; approving records it without a density result, and it will read "no stored result" until its values are worked out',
592
+ });
593
+
594
+ /**
595
+ * The approval screen's comparison (#3680 part C, C4): for each wall, slab and footing of the approval `candidate`
596
+ * whose density changed since the approved version, or that the approved version does not hold yet, what approving
597
+ * does to it, judged on the CANDIDATE itself (never the draft): `cleared` when its stored result is on today's row,
598
+ * `stays-flagged` when it holds values on the old row (a change left pending included), `no-stored-result` when it has
599
+ * no saved values. `previous` is the evaluation against the approval in force; `prospective` the same with the
600
+ * candidate itself as the approval (`approvalContextFromCandidate`). Approval works nothing out. An approval that
601
+ * could not be proven gives no list: its reason is said once (`densityComparisonUnavailable`). Pure.
602
+ * @param {any} candidate
603
+ * @param {EvaluationOptions & { approval?: any }} previous
604
+ * @param {EvaluationOptions & { approval?: any }} prospective
605
+ */
606
+ export function approvalDensityChanges(candidate, previous = {}, prospective = {}) {
607
+ if (!Array.isArray(candidate?.elements)) return [];
608
+ const before = evaluationContextFor(candidate, previous);
609
+ if (isObj(before.approval) && before.approval.state !== 'none' && before.approval.state !== 'approved') return [];
610
+ const after = evaluationContextFor(candidate, prospective);
611
+ const out = [];
612
+ for (const e of candidate.elements) {
613
+ if (!isObj(e) || typeof e.id !== 'string' || !SOLID_KINDS.includes(e.kind)) continue;
614
+ // No approval at all: everything in the first approval is compared for the first time.
615
+ const was = densityComparisonOf(before, e.id) ?? { state: 'new', approvedVersion: null };
616
+ if (was.state !== 'changed' && was.state !== 'new') continue;
617
+ const now = densityComparisonOf(after, e.id);
618
+ const outcome = now?.state === 'unchanged' ? 'cleared' : now?.state === 'not-compared' ? 'no-stored-result' : 'stays-flagged';
619
+ const t = (Array.isArray(candidate.element_types) ? candidate.element_types : []).find((x) => isObj(x) && x.id === e.typeId);
620
+ const kind = kindWord(e.kind, isObj(t) ? typeInputs(t)?.form : undefined);
621
+ out.push({
622
+ elementId: e.id, kind: kind.toLowerCase(), state: was.state, approvedVersion: was.approvedVersion ?? null,
623
+ layers: was.state === 'changed' ? was.changes.map((l) => ({ catalogId: l.catalogId, approved: l.was?.kgM3 ?? null, today: l.now?.kgM3 ?? null })) : [],
624
+ outcome,
625
+ sentence: `${kind} ${e.id}: ${was.state === 'changed' ? 'its density changed since the approved version; ' : 'not in the approved version yet; '}${APPROVAL_DENSITY_OUTCOMES[outcome]}.`,
626
+ });
627
+ }
628
+ return out.sort((a, b) => (a.elementId < b.elementId ? -1 : a.elementId > b.elementId ? 1 : 0));
629
+ }
630
+
631
+ /** The whole-reply form of an approval that could not be proven, or null: said once beside the element list. */
632
+ export function densityComparisonUnavailable(ctx) {
633
+ const a = ctx?.approval;
634
+ return isObj(a) && a.state !== 'none' && a.state !== 'approved' ? { state: 'unavailable', reason: String(a.reason ?? 'approval-malformed'), label: comparisonUnavailableLabel(a.reason) } : null;
635
+ }
636
+
637
+ /** The same for a model and its evaluation options: what a save reply carries when its model has elements. */
638
+ export function densityComparisonAnswer(doc, opts = {}) {
639
+ if (!Array.isArray(doc?.elements) || !doc.elements.some(isObj)) return {};
640
+ const u = densityComparisonUnavailable(evaluationContextFor(doc, opts));
641
+ return u ? { densityComparison: u } : {};
642
+ }
643
+
644
+ /**
645
+ * Whether an element's own saved values are still on a density the catalogue no longer gives (C5's stale case): a
646
+ * layer whose saved catalogue state is not today's for the same row. Such an element stays flagged after approving
647
+ * until its values are worked out again.
648
+ */
649
+ function savedOnOldDensity(e, ctx) {
650
+ const mats = Array.isArray(e?.evaluated?.semantics?.materials) ? e.evaluated.semantics.materials : [];
651
+ return mats.some((m) => {
652
+ const ref = m?.material?.ref;
653
+ if (!isObj(ref)) return false;
654
+ const row = typeof ctx.resolve === 'function' ? ctx.resolve(approvedRowOf({ class: m.material.class, environment: ref.environment, catalogId: ref.catalogId })) : null;
655
+ return canonicalJson(catalogueStateOf(m.material)) !== canonicalJson(catalogueStateOf(row));
656
+ });
657
+ }
506
658
 
507
659
  /**
508
660
  * The records on an element that are the person's to make: their acceptance of saved values, and a density they
@@ -511,26 +663,63 @@ export const DENSITY_BASIS = 'worked out from the current catalogue; FloLess doe
511
663
  */
512
664
  const PERSON_RECORDS = Object.freeze(['storedValues', 'densityAssumption']);
513
665
 
666
+ /**
667
+ * The approval candidate's rule for the person's records (#3963 item 4, part C round-3 fold 3): DROP ONLY. A record the
668
+ * candidate holds stays only when the working copy holds it byte for byte; every other one is removed from the
669
+ * candidate and listed, and nothing is ever taken from the working copy (unlike `guardElementAcceptances`, which puts
670
+ * the stored record back and would carry a replacement density left pending into the approval). An element whose
671
+ * record is dropped is then held in the approved version for its own reason. Pure.
672
+ * @param {any} candidate the document about to be approved
673
+ * @param {any} working the working copy the person reviewed
674
+ * @returns {{ doc: any, dropped: Array<{ elementId: string, record: 'storedValues' | 'densityAssumption', sentence: string }> }}
675
+ */
676
+ export function dropUnheldPersonRecords(candidate, working) {
677
+ if (!isObj(candidate) || !Array.isArray(candidate.elements)) return { doc: candidate, dropped: [] };
678
+ const live = new Map((Array.isArray(working?.elements) ? working.elements : []).filter(isObj).map((e) => [e.id, e]));
679
+ const dropped = [];
680
+ const elements = candidate.elements.map((e) => {
681
+ if (!isObj(e)) return e;
682
+ const w = live.get(e.id);
683
+ let next = e;
684
+ for (const key of PERSON_RECORDS) {
685
+ if (next[key] === undefined) continue;
686
+ if (w?.[key] !== undefined && canonicalJson(w[key]) === canonicalJson(next[key])) continue;
687
+ const { [key]: _drop, ...rest } = next;
688
+ next = rest;
689
+ const what = key === 'densityAssumption' ? `The person's density on ${e.id}` : `The person's acceptance of the saved values of ${e.id}`;
690
+ dropped.push({ elementId: String(e.id), record: key, sentence: `${what} is not carried into the approval: it had ended or changed in the working copy.` });
691
+ }
692
+ return next;
693
+ });
694
+ return dropped.length ? { doc: { ...candidate, elements }, dropped } : { doc: candidate, dropped: [] };
695
+ }
696
+
514
697
  /**
515
698
  * The person's records are theirs to make (design §5.5, density plan §3): only the acceptance routes write a new or
516
699
  * changed `storedValues`. Any other save is held to the stored ones, the way the gateway holds
517
700
  * server-minted joint fields: a changed record goes back to the stored one, a new one is dropped. Taking one away is
518
- * always allowed (it makes the record claim less). `allowed` names the elements an acceptance route is writing.
701
+ * always allowed (it makes the record claim less). `allowed` names the exact records an acceptance route is writing
702
+ * (S3 E1c R1a, part C round-1 fold 6): `{ elementId, record, value }`, one per record, with the value the route
703
+ * composed. Only that record of that element, with that value byte for byte, gets through; any other change to the
704
+ * same element's records is put back like an ungranted one. An entry that is not of that shape grants nothing.
519
705
  * @param {any} current the stored model (or null)
520
706
  * @param {any} doc the model being saved
521
- * @param {readonly string[]} [allowed]
707
+ * @param {ReadonlyArray<{ elementId: string, record: 'storedValues' | 'densityAssumption', value: unknown }>} [allowed]
522
708
  * @returns {{ doc: any, reverted: string[] }}
523
709
  */
524
710
  export function guardElementAcceptances(current, doc, allowed = []) {
525
711
  if (!isObj(doc) || !Array.isArray(doc.elements)) return { doc, reverted: [] };
526
712
  const prior = new Map((Array.isArray(current?.elements) ? current.elements : []).filter(isObj).map((e) => [e.id, e]));
713
+ const granted = (id, key, value) => allowed.some((g) => isObj(g) && g.elementId === id && g.record === key && value !== undefined
714
+ && canonicalJson(g.value) === canonicalJson(value));
527
715
  const reverted = new Set();
528
716
  const elements = doc.elements.map((e) => {
529
- if (!isObj(e) || allowed.includes(e.id)) return e;
717
+ if (!isObj(e)) return e;
530
718
  const before = prior.get(e.id);
531
719
  let next = e;
532
720
  for (const key of PERSON_RECORDS) {
533
721
  if (next[key] === undefined) continue;
722
+ if (granted(e.id, key, next[key])) continue;
534
723
  if (before?.[key] !== undefined && canonicalJson(before[key]) === canonicalJson(next[key])) continue;
535
724
  reverted.add(String(e.id));
536
725
  const { [key]: _drop, ...rest } = next;
@@ -541,6 +730,43 @@ export function guardElementAcceptances(current, doc, allowed = []) {
541
730
  return reverted.size ? { doc: { ...doc, elements }, reverted: [...reverted] } : { doc, reverted: [] };
542
731
  }
543
732
 
733
+ /**
734
+ * A result worked out on the person's density is the evidence of that density (#3963 item 2, parent plan R6/R1b; #3680
735
+ * "leaving a result off"): a save that leaves it off, or sends another one, while the element's base is unchanged gets
736
+ * the stored result (`evaluated` and `typeDigest`) back, and the element is listed so the reply can say so. Only the
737
+ * person replaces it, by supplying another density on a new card or by changing what the element is worked out from: a
738
+ * changed base takes the result that came with it. Guarded only where the stored element's result records the person's
739
+ * density and that density binds in the stored model; every other result is an ordinary save. `allowed` names the
740
+ * exact results a route worked out itself (the density card, `resolve-save`, an edit's re-evaluation): only that
741
+ * result of that element, byte for byte, goes through. Pure; nothing is ever refused.
742
+ * @param {any} current the stored model (or null)
743
+ * @param {any} doc the model being saved, after its type ids are settled and its type moves put back
744
+ * @param {{ allowed?: ReadonlyArray<{ elementId: string, evaluated: unknown, typeDigest?: unknown }>, storedOptions?: EvaluationOptions, options?: EvaluationOptions }} [opts]
745
+ * @returns {{ doc: any, kept: Array<{ element: string, kgM3: number, basis: string }> }}
746
+ */
747
+ export function guardPersonDensityResults(current, doc, { allowed = [], storedOptions = {}, options = {} } = {}) {
748
+ if (!isObj(doc) || !Array.isArray(doc.elements) || !isObj(current) || !Array.isArray(current.elements)) return { doc, kept: [] };
749
+ const prior = new Map(current.elements.filter(isObj).map((e) => [e.id, e]));
750
+ const resultOf = (e) => canonicalJson({ evaluated: e?.evaluated ?? null, typeDigest: e?.typeDigest ?? null });
751
+ const granted = (e) => allowed.some((g) => isObj(g) && g.elementId === e.id && g.evaluated !== undefined
752
+ && resultOf(g) === resultOf(e));
753
+ const onPersonDensity = (s) => isObj(s?.evaluated) && Array.isArray(s.evaluated.semantics?.materials)
754
+ && s.evaluated.semantics.materials.some((m) => m?.material?.density?.status === 'person');
755
+ const kept = [];
756
+ const elements = doc.elements.map((e) => {
757
+ if (!isObj(e)) return e;
758
+ const s = prior.get(e.id);
759
+ if (!s || !onPersonDensity(s) || resultOf(e) === resultOf(s) || granted(e)) return e;
760
+ const a = boundDensityAssumption(s, current, storedOptions);
761
+ if (!a) return e;
762
+ if (e.kind !== s.kind || elementBase(e, doc, options) !== elementBase(s, current, storedOptions)) return e;
763
+ kept.push({ element: String(e.id), kgM3: a.kgM3, basis: a.basis });
764
+ const { evaluated: _e, typeDigest: _d, ...rest } = e;
765
+ return { ...rest, evaluated: s.evaluated, ...(s.typeDigest !== undefined ? { typeDigest: s.typeDigest } : {}) };
766
+ });
767
+ return kept.length ? { doc: { ...doc, elements }, kept } : { doc, kept: [] };
768
+ }
769
+
544
770
  /**
545
771
  * What an imported project's person record binds to, instead of its digest: never a digest, so it never binds. The
546
772
  * archive's own digest follows it, kept for audit with every word of the record (Codex part A r2 finding 1).
@@ -601,7 +827,9 @@ export function countableElements(doc, verification = undefined, opts = {}) {
601
827
  * an acceptance is never withdrawn in silence (reviews E1a r1), and nothing is called worked out when it was not.
602
828
  * @param {any} doc
603
829
  * @param {Set<string>} [only]
604
- * @param {{ replace?: Set<string>, before?: Map<string, { status: string }> } & EvaluationOptions} [opts]
830
+ * `correctOnTodaysRow` names the elements `resolve-save` works out again while a density changed since approval holds
831
+ * them (#3680 part C, step 4); each is written only where the engine's `correctable` says so.
832
+ * @param {{ replace?: Set<string>, correctOnTodaysRow?: Set<string>, before?: Map<string, { status: string }> } & EvaluationOptions} [opts]
605
833
  * @returns {{ doc: any, errors: Map<string, string>, replaced: Array<{ id: string, was: string, reason?: string, acceptanceEnded?: boolean, hasValues?: boolean }> }}
606
834
  */
607
835
  export function materializeElements(doc, only = undefined, opts = {}) {
@@ -621,7 +849,11 @@ export function materializeElements(doc, only = undefined, opts = {}) {
621
849
  if (only && !only.has(e.id)) return e;
622
850
  if (acceptanceBinds(e, doc, ctx) && !opts.replace?.has(e.id)) return e;
623
851
  const r = results.get(e.id);
624
- const fresh = r && r.holds.reasons.size === 0 ? r.fresh : null;
852
+ // #3680 part C, step 4: an element the route names in `correctOnTodaysRow` is worked out again while its density
853
+ // changed since approval holds it, only when the engine says that drift (and reasons the person's keep covers) is
854
+ // all that holds it. Its drift is untouched: it stays held and uncounted until a person re-approves.
855
+ const correcting = opts.correctOnTodaysRow?.has(e.id) === true && r?.correctable === true;
856
+ const fresh = r && (r.holds.reasons.size === 0 || correcting) ? r.fresh : null;
625
857
  if (!fresh) {
626
858
  errors.set(e.id, r?.status?.reason ?? r?.freshFindings?.[0]?.text ?? 'it could not be evaluated');
627
859
  if (e.evaluated === undefined && e.storedValues === undefined) return e;
@@ -633,7 +865,8 @@ export function materializeElements(doc, only = undefined, opts = {}) {
633
865
  const { storedValues: _s, ...rest } = e;
634
866
  return rest;
635
867
  }
636
- if (isObj(e.evaluated) && canonicalJson(e.evaluated) === canonicalJson(fresh) && e.storedValues === undefined) return e;
868
+ // Values already FloLess's own today: nothing is replaced, and a keep of them (while drift holds it) stays.
869
+ if (isObj(e.evaluated) && canonicalJson(e.evaluated) === canonicalJson(fresh) && (e.storedValues === undefined || correcting)) return e;
637
870
  note(e);
638
871
  const { storedValues: _s, ...rest } = e; // a new result invalidates values the person accepted for the old one
639
872
  const type = (doc.element_types ?? []).find((t) => isObj(t) && t.id === e.typeId);
@@ -829,7 +1062,8 @@ export function elementSaveWarning(doc, opts = {}) {
829
1062
  const rows = [];
830
1063
  // Which answers a held element gets is the engine's set (its reasons and whether every one is keepable), never its
831
1064
  // first code.
832
- const results = evaluateElements(doc, opts);
1065
+ const ctx = evaluationContextFor(doc, opts);
1066
+ const results = evaluateElements(doc, ctx);
833
1067
  // The ways on are the engine's one list, the same the evaluate reply's `choices` show (ruling 13.2).
834
1068
  const ways = waysOnOf(doc, results);
835
1069
  for (const [id, r] of results) {
@@ -847,15 +1081,29 @@ export function elementSaveWarning(doc, opts = {}) {
847
1081
  const drifted = ids('drifted');
848
1082
  // Every held or unreadable element gets the engine's own ways on, the list its evaluate reply shows; elements with
849
1083
  // the same list share one sentence. A strip under a held wall names the wall's decision first (ruling 13.3).
1084
+ // A density changed since approval is said on its own line (C5): the two answers that settle it, and, where the
1085
+ // element's saved values are still on the old density, that approving alone will not clear it. An element held for
1086
+ // that alone is not repeated in the generic lines; one with other reasons too keeps their ways there.
1087
+ const DRIFT = HOLD_CODES.DENSITY_CHANGED_SINCE_APPROVAL;
1088
+ const codesOf = (id) => [...(results.get(id)?.holds?.reasons?.values() ?? [])].map((x) => x.code);
1089
+ const densityChanged = rows.filter((r) => codesOf(r.id).includes(DRIFT)).map((r) => r.id);
1090
+ const onlyDrift = new Set(densityChanged.filter((id) => codesOf(id).every((c) => c === DRIFT)));
1091
+ const stale = densityChanged.filter((id) => savedOnOldDensity(results.get(id)?.element, ctx));
1092
+ const both = (list) => (list.length > 1 ? `${listed(list.slice(0, -1))} and ${list[list.length - 1]}` : listed(list));
1093
+ const driftLines = densityChanged.length ? [
1094
+ `Density changed since approval for ${both(densityChanged)}: ${DRIFT_ANSWERS}.`,
1095
+ ...stale.map((id) => `${id}: its saved values in this copy still use the old density. Work them out again first, or it stays flagged after approving.`),
1096
+ ] : [];
850
1097
  const byWays = new Map();
851
1098
  for (const r of rows) {
852
- if (!r.waysOn) continue;
1099
+ if (!r.waysOn || onlyDrift.has(r.id)) continue;
853
1100
  const k = JSON.stringify(r.waysOn);
854
1101
  if (!byWays.has(k)) byWays.set(k, { ids: [], ways: r.waysOn });
855
1102
  byWays.get(k).ids.push(r.id);
856
1103
  }
857
1104
  const asks = rows.filter((r) => r.ask).map((r) => r.ask.text);
858
1105
  const answers = [
1106
+ ...driftLines,
859
1107
  ...[...byWays.values()].map((g) => `For ${listed(g.ids)}: ${g.ways.join('; or ')}.`),
860
1108
  ...asks,
861
1109
  ];
@@ -864,6 +1112,7 @@ export function elementSaveWarning(doc, opts = {}) {
864
1112
  message: `${n === 1 ? '1 wall, slab or footing was' : `${n} walls, slabs and footings were`} saved with values FloLess cannot verify: ${shown}${n > 20 ? `; and ${n - 20} more` : ''}. `
865
1113
  + `${n === 1 ? 'It is' : 'They are'} labelled and held out of quantities and exports. ${answers.join(' ')}`,
866
1114
  elements: rows,
1115
+ ...(densityChanged.length ? { densityChanged } : {}),
867
1116
  };
868
1117
  }
869
1118
 
@@ -897,7 +1146,7 @@ export function glbMaterialExtras(evaluated) {
897
1146
  // ---- the sinks (E1b, plan 2026-11-17-s3-e1b-sinks-PLAN.md revision 2) ------------------------------------
898
1147
 
899
1148
  /** What a sink says of a result FloLess worked out itself (its stored values match what FloLess works out now). */
900
- // It says what FloLess did, never that the element was checked: its fit is only partly checked (ELEMENT_FIT_NOT_CHECKED).
1149
+ // It says what FloLess did, never that the element was checked: its fit is a separate measurement (fitSummarySentence).
901
1150
  export const CHECKED_LABEL = 'quantities worked out by FloLess from its type';
902
1151
  /** What a sink says of the person's accepted values: drawn and counted as theirs, never as checked. */
903
1152
  export const ACCEPTED_LABEL = "the person's accepted values, not checked by FloLess";
@@ -908,10 +1157,11 @@ export const ACCEPTED_LABEL = "the person's accepted values, not checked by FloL
908
1157
  * label wording and, for a keep that no longer lifts its hold, the ask. Nothing here picks geometry or decides a status.
909
1158
  * @param {any} doc
910
1159
  * @param {EvaluationOptions} [opts]
911
- * @returns {Map<string, { element: any, status: string, reason?: string, counted: boolean, source: 'floless'|'stored'|null, evaluated: any, drawable: boolean, label: string, ask?: any }>}
1160
+ * @returns {Map<string, { element: any, status: string, reason?: string, counted: boolean, source: 'floless'|'stored'|null, evaluated: any, drawable: boolean, label: string, ask?: any, densityComparison?: any }>}
912
1161
  */
913
1162
  export function elementSinkResults(doc, opts = {}) {
914
- const evaluation = evaluateElements(doc, opts);
1163
+ const ctx = evaluationContextFor(doc, opts);
1164
+ const evaluation = evaluateElements(doc, ctx);
915
1165
  const out = new Map();
916
1166
  for (const [id, r] of evaluation) {
917
1167
  const s = r.status;
@@ -919,9 +1169,13 @@ export function elementSinkResults(doc, opts = {}) {
919
1169
  const label = s.status === 'verified' ? CHECKED_LABEL
920
1170
  : s.status === 'accepted' || s.status === 'assumed' ? `${ACCEPTED_LABEL}${s.reason ? `: ${s.reason}` : ''}`
921
1171
  : `not counted: ${s.reason ?? s.status}`;
1172
+ // What the comparison with the approved version says of it (C1, round-1 fold 9): every sink carries it beside its
1173
+ // quantities, so an unproven approval or a kept change is never left out of a bill, a file or a view.
1174
+ const comparison = densityComparisonOf(ctx, id, r);
922
1175
  out.set(id, {
923
1176
  element: r.element, status: s.status, ...(s.reason ? { reason: s.reason } : {}), counted: sel.counted, source: sel.source,
924
1177
  evaluated: sel.evaluated, drawable: sel.drawable, label, ...(s.ask ? { ask: s.ask } : {}),
1178
+ ...(comparison ? { densityComparison: comparison } : {}),
925
1179
  });
926
1180
  }
927
1181
  return out;
@@ -953,6 +1207,7 @@ export function elementSinkMeta(doc, r) {
953
1207
  status: r.status, ...(r.reason ? { reason: r.reason } : {}), counted: r.counted, label: r.label,
954
1208
  ...(r.source ? { source: r.source } : {}),
955
1209
  ...(materials.length ? { materials, densityBasis: DENSITY_BASIS } : {}),
1210
+ ...(r.densityComparison ? { densityComparison: r.densityComparison } : {}),
956
1211
  ...(r.counted && isObj(r.evaluated?.quantities) ? { quantities: r.evaluated.quantities } : {}),
957
1212
  };
958
1213
  }