@floless/app 0.169.0 → 0.171.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 (87) hide show
  1. package/dist/floless-server.cjs +65531 -43728
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +12 -2
  3. package/dist/schemas/steel.model.v2.schema.json +196 -4
  4. package/dist/skills/floless-app-bridge/SKILL.md +3 -3
  5. package/dist/skills/floless-app-knowledge/SKILL.md +46 -15
  6. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -1
  7. package/dist/skills/floless-app-onboarding/SKILL.md +5 -4
  8. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +0 -3
  9. package/dist/skills/floless-app-queue/SKILL.md +2 -3
  10. package/dist/skills/floless-app-report-issue/SKILL.md +2 -2
  11. package/dist/skills/floless-app-routines/SKILL.md +2 -2
  12. package/dist/skills/floless-app-routines/references/routines-api.md +20 -8
  13. package/dist/skills/floless-app-steel-model/SKILL.md +42 -39
  14. package/dist/skills/floless-app-steel-model/references/custom-connections.md +47 -0
  15. package/dist/skills/floless-app-steel-model/references/custom-sections.md +32 -0
  16. package/dist/skills/floless-app-steel-takeoff/SKILL.md +31 -1
  17. package/dist/skills/floless-app-ui/SKILL.md +71 -126
  18. package/dist/skills/floless-app-workflows/SKILL.md +22 -3
  19. package/dist/skills/floless-app-workflows/references/agent-steps.md +40 -6
  20. package/dist/skills/floless-app-workflows/references/exec-contract.md +27 -0
  21. package/dist/skills/floless-app-workflows/references/script-runner.md +105 -0
  22. package/dist/web/add-ons.js +407 -0
  23. package/dist/web/agent-steps.js +89 -18
  24. package/dist/web/agents.js +32 -22
  25. package/dist/web/analytics.js +1 -1
  26. package/dist/web/app.css +331 -190
  27. package/dist/web/app.js +33 -13
  28. package/dist/web/aware.js +926 -218
  29. package/dist/web/chat.css +6 -1
  30. package/dist/web/chat.js +316 -112
  31. package/dist/web/checkpoint-standard.js +5 -3
  32. package/dist/web/commands-drawing-check.js +1 -0
  33. package/dist/web/commands-filter.js +23 -0
  34. package/dist/web/commands-shell.js +479 -78
  35. package/dist/web/commands-steel.js +69 -2
  36. package/dist/web/commands-tekla-parser.js +23 -0
  37. package/dist/web/connections.js +14 -3
  38. package/dist/web/drawing-check-editor.js +352 -88
  39. package/dist/web/failure-copy.js +33 -2
  40. package/dist/web/filter-ai-proposal.js +11 -8
  41. package/dist/web/flo-3d.js +1 -1
  42. package/dist/web/guide.js +36 -29
  43. package/dist/web/index.html +98 -57
  44. package/dist/web/instructor.js +101 -17
  45. package/dist/web/kb-categories.js +64 -7
  46. package/dist/web/left-pane.js +4 -1
  47. package/dist/web/local-discovery.js +8 -7
  48. package/dist/web/missed-routines.js +239 -0
  49. package/dist/web/model-change-findings.js +430 -0
  50. package/dist/web/model-change-review.js +414 -0
  51. package/dist/web/model-editor-steel-adapter.js +2 -2
  52. package/dist/web/model-measure.js +6 -0
  53. package/dist/web/model-spatial-panel.js +19 -4
  54. package/dist/web/model-spatial-tools.js +3 -3
  55. package/dist/web/model-viewport-revit-adapter.js +3 -3
  56. package/dist/web/origin-rule.js +155 -0
  57. package/dist/web/project-access.js +1 -1
  58. package/dist/web/project-history.js +7 -1
  59. package/dist/web/project-modules.js +2 -2
  60. package/dist/web/project-rfis.js +6 -1
  61. package/dist/web/project-workflows.js +2 -2
  62. package/dist/web/revit-editor.css +85 -0
  63. package/dist/web/revit-editor.js +58 -9
  64. package/dist/web/run-history.js +12 -1
  65. package/dist/web/sha256-sync.js +62 -0
  66. package/dist/web/steel-3d-core.js +46 -9
  67. package/dist/web/steel-3d-flo.js +153 -7
  68. package/dist/web/steel-3d-view.js +33 -5
  69. package/dist/web/steel-ai-marks.js +3 -1
  70. package/dist/web/steel-custom-connection.js +161 -0
  71. package/dist/web/steel-custom-sections.js +1796 -0
  72. package/dist/web/steel-editor.html +732 -161
  73. package/dist/web/steel-environments.js +297 -0
  74. package/dist/web/steel-filter-usage.js +299 -0
  75. package/dist/web/steel-filter.html +104 -6
  76. package/dist/web/steel-model-v2-client-validation.js +11 -1
  77. package/dist/web/steel-model-v2-commands.js +116 -13
  78. package/dist/web/steel-model-v2-projection.js +1 -1
  79. package/dist/web/steel-read-confidence.js +1 -56
  80. package/dist/web/step-rename.js +3 -2
  81. package/dist/web/tekla-editor.html +1 -0
  82. package/dist/web/terminal-requests.js +1 -1
  83. package/dist/web/tool-updates.js +7 -6
  84. package/dist/web/workspaces.js +1968 -138
  85. package/launch.mjs +87 -9
  86. package/package.json +4 -1
  87. package/dist/web/panels.js +0 -831
@@ -0,0 +1,297 @@
1
+ /*
2
+ * steel-environments.js — the ONE registry of steel-environment TRAITS.
3
+ *
4
+ * A steel environment is the standard a project is built to: which section catalogue its designations
5
+ * resolve against, which units it speaks, which grade it defaults to, which scale grammar its sheets
6
+ * print. Before this file the answer to each of those questions was an id comparison scattered over
7
+ * ~40 sites (`environment === 'UK'`, `!== 'US'`), and every one of them was a two-arm switch: anything
8
+ * that was not the named id fell into the other arm. That is a binary, not a vocabulary, and a third
9
+ * environment had nowhere to stand — it would silently resolve against whichever arm its spelling
10
+ * happened to miss (EU epic #3197, §2.1 and §6).
11
+ *
12
+ * THE RULE THIS FILE EXISTS TO ENFORCE: a site that needs to know something about an environment reads
13
+ * a TRAIT from here. It never compares an id. `npm run verify:no-environment-id-compare` ratchets that
14
+ * (shrink-only), and the per-site tests in `server/steel-environment-traits.test.ts` are the proof; the
15
+ * guard is only the backstop.
16
+ *
17
+ * SHARED BY SERVER AND BROWSER. `server/*.ts` imports it by the established `../web/*.js` pattern, and
18
+ * the pages load it as a module. It therefore imports nothing but the unit constants' leaf module and
19
+ * touches no DOM, no `window`, no `process`.
20
+ *
21
+ * A `Map`, for the reason `checkpoint-standard.js` states about its label table: a plain object indexed
22
+ * by an untrusted value is two holes (`{UK:…}[['UK']]` resolves through array-to-string coercion, and
23
+ * `{…}['constructor']` returns a function). `Map.get` compares by identity and has no prototype chain.
24
+ *
25
+ * ONE OWNER PER FACT. Rows, payloads, aliases, resolution notes and suspect reasons belong to the
26
+ * server's `CatalogProvider`. What lives here is what BOTH sides need before any payload exists — most
27
+ * visibly the shapes route path, because the editor's first fetch happens before it holds a contract's
28
+ * catalogue. `CatalogProvider.shapesPath` READS it from here, so the path is one literal with two
29
+ * readers.
30
+ *
31
+ * TWO LOOKUPS, deliberately, because an absent environment and an unknown one are different facts:
32
+ * - `traitsOf(id)` strict. `undefined` for anything not registered. Use it where "was a standard
33
+ * STATED, and do we know it" is the question (scale grammar, the chip's sentence).
34
+ * - `traitsFor(id)` total. An unstated or unregistered id resolves as the compatibility fallback
35
+ * (US), exactly as `normalizeEnvironment` does on the server. Use it where a
36
+ * behaviour must be chosen anyway. The fallback is a MACHINE meaning, never a claim
37
+ * that US is the normal case (see `server/steel-environment.ts`).
38
+ */
39
+
40
+ import { FT_TO_MM, IN_TO_MM } from './steel-units.js';
41
+
42
+ /**
43
+ * How far BELOW a plan's cut level a column may end and still be drawn as "column below": one foot for
44
+ * an imperial standard, a round 300 mm for a metric one (owner ruling, Pawel, 2026-10-23 — a UK
45
+ * detailer read "Columns ending up to 304.8 mm under this level" off an artefact of a converted foot).
46
+ * Keyed on the ENVIRONMENT and not the display units: the view toggle flips at any time and the server
47
+ * decides what a sheet draws with no display preference at all.
48
+ */
49
+ export const COLUMN_BELOW_REACH_MM_IMPERIAL = FT_TO_MM;
50
+ export const COLUMN_BELOW_REACH_MM_METRIC = 300;
51
+
52
+ /** How far ABOVE the cut a column's base may sit and still be drawn (#2815): 2 in, or a round 50 mm. */
53
+ export const COLUMN_NEAR_CUT_MM_IMPERIAL = 2 * IN_TO_MM;
54
+ export const COLUMN_NEAR_CUT_MM_METRIC = 50;
55
+
56
+ /**
57
+ * Every environment this build can resolve. A tuple (not derived from the Map) so TypeScript sees the
58
+ * literal union `'US' | 'UK' | 'EU'`; `steel-environments` tests assert it equals the Map's keys, so adding an
59
+ * entry to one and not the other fails.
60
+ *
61
+ * @type {readonly ['US', 'UK', 'EU']}
62
+ */
63
+ export const STEEL_ENVIRONMENT_IDS = Object.freeze(['US', 'UK', 'EU']);
64
+
65
+ /**
66
+ * @typedef {object} DefaultGradeTraits
67
+ * @property {string} rolled the grade of an open (rolled) section
68
+ * @property {string} hollow the grade of a hollow section
69
+ * @property {ReadonlyArray<readonly [string, string]>} rolledByName [name pattern source, grade] — a
70
+ * rolled family with its own default (the US wide flange), checked after the hollow test
71
+ * @property {string} hollowNamePattern how a hollow section reads BY NAME — the fallback for a
72
+ * designation that resolved to no catalogue row
73
+ * @property {readonly string[] | null} hollowRowShapes a resolved row is hollow when its `sectionShape` is one of these
74
+ * @property {readonly string[] | null} hollowRowFamilies …or when its `family` is one of these
75
+ */
76
+
77
+ /**
78
+ * @typedef {object} SteelEnvironmentTraits
79
+ * @property {'US'|'UK'|'EU'} id
80
+ * @property {string} label how the standard names itself to a person ("US · AISC/ASTM")
81
+ * @property {string} subLabel the project-setup button's second line
82
+ * @property {'imperial'|'metric'} unitSystem
83
+ * @property {'ft-in'|'mm'} defaultDisplayUnits what the environment implies where an owner never chose
84
+ * @property {string} shapesPath the route serving this environment's catalogue to the browser
85
+ * @property {string} catalogueNoun what to CALL the section table when telling a person a designation is not in it
86
+ * @property {'metric'|'imperial'} scaleGrammar which drawing-scale grammar a sheet of this standard prints
87
+ * @property {number} columnBelowReachMm
88
+ * @property {number} columnNearCutMm
89
+ * @property {'in'|'mm'} designationTokenUnit the unit a designation's size tokens are written in — a double angle (the one shape no catalogue tabulates) is parsed from its name in every environment, and this is the unit of those tokens
90
+ * @property {boolean} aiscInchTable whether designations resolve through the legacy AISC INCHES table and its token heuristics (the US catalogue); false means the provider's own catalogue answers every shape
91
+ * @property {boolean} exportPrimarySpelling whether a host export sends the catalogue's PRIMARY spelling of a section (the host refuses the folded spelling) rather than the canonical folded one
92
+ * @property {DefaultGradeTraits} defaultGrade
93
+ * @property {string | null} foreignSectionPattern source of a case-insensitive pattern naming designations that are correctly spelled in ANOTHER environment's catalogue — the RFI reason uses it to say "not a typo, a different catalogue". null when this environment declares none
94
+ * @property {string} foreignSectionNoun what to CALL a designation that is correctly spelled in another environment's catalogue, in that RFI reason ("European/British section")
95
+ * @property {string} shapesHeldNote what this catalogue holds, for that RFI reason
96
+ * @property {string} chipTip the editor header chip's sentence for a project that states this standard
97
+ * @property {string} detailerAgent the AWARE detailing agent installed for a project of this standard
98
+ */
99
+
100
+ const US = {
101
+ id: 'US',
102
+ label: 'US · AISC/ASTM',
103
+ subLabel: 'AISC sections · A992 / A36',
104
+ unitSystem: 'imperial',
105
+ defaultDisplayUnits: 'ft-in',
106
+ shapesPath: '/api/aisc-shapes',
107
+ catalogueNoun: 'AISC',
108
+ scaleGrammar: 'imperial',
109
+ columnBelowReachMm: COLUMN_BELOW_REACH_MM_IMPERIAL,
110
+ columnNearCutMm: COLUMN_NEAR_CUT_MM_IMPERIAL,
111
+ designationTokenUnit: 'in',
112
+ aiscInchTable: true,
113
+ exportPrimarySpelling: false,
114
+ defaultGrade: {
115
+ rolled: 'A36',
116
+ hollow: 'A500-GR.B',
117
+ rolledByName: [['^W\\d', 'A992']],
118
+ hollowNamePattern: '^HSS',
119
+ // The US HSS family only. A `Pipe` row is also round, and its default has always been A36: deciding
120
+ // by SHAPE here would have moved 102 pipe rows to A500-GR.B and changed shipped US output.
121
+ hollowRowShapes: null,
122
+ hollowRowFamilies: ['HSS'],
123
+ },
124
+ foreignSectionPattern: '^(IPE|HE[ABM]?|UB|UC|UKB|UKC|UKA|PFC|UPN|UPE)\\s*\\d',
125
+ foreignSectionNoun: 'European/British section',
126
+ shapesHeldNote: 'AISC (US) shapes only',
127
+ chipTip: 'This model resolves every section against the US catalogue (AISC sections, A992/A36 default grade). Chosen when the project was created and fixed for its life.',
128
+ detailerAgent: 'steel-detailer-us',
129
+ };
130
+
131
+ const UK = {
132
+ id: 'UK',
133
+ label: 'UK · BS/EN',
134
+ subLabel: 'BS EN sections · S355',
135
+ unitSystem: 'metric',
136
+ defaultDisplayUnits: 'mm',
137
+ shapesPath: '/api/uk-shapes',
138
+ catalogueNoun: 'UK section',
139
+ scaleGrammar: 'metric',
140
+ columnBelowReachMm: COLUMN_BELOW_REACH_MM_METRIC,
141
+ columnNearCutMm: COLUMN_NEAR_CUT_MM_METRIC,
142
+ designationTokenUnit: 'mm',
143
+ aiscInchTable: false,
144
+ exportPrimarySpelling: true,
145
+ defaultGrade: {
146
+ rolled: 'S355',
147
+ hollow: 'S355J2H',
148
+ rolledByName: [],
149
+ hollowNamePattern: '^(CHS|SHS|RHS|EHS)',
150
+ // Decided by the catalogue ROW's `sectionShape`, with the name pattern as the fallback for a designation
151
+ // that resolved to no row. EU-0b (#3199) flipped this from name-only: 839 of the 5,963 UK designations
152
+ // and aliases are hollow sections spelled with the family as a SUFFIX (`450X150X16.0 RHS`), which the
153
+ // prefix pattern misses, so a UK member written that way got S355 where S355J2H is right.
154
+ hollowRowShapes: ['rhs', 'chs', 'ehs'],
155
+ hollowRowFamilies: null,
156
+ },
157
+ // The UK catalogue resolves BS and European names alike, so there is no family it would call foreign.
158
+ foreignSectionPattern: null,
159
+ foreignSectionNoun: 'section from another standard',
160
+ shapesHeldNote: 'UK sections only',
161
+ chipTip: 'This model resolves every section against the UK catalogue (BS EN sections, S355 default grade). Chosen when the project was created and fixed for its life.',
162
+ detailerAgent: 'steel-detailer-uk',
163
+ };
164
+
165
+ const EU = {
166
+ id: 'EU',
167
+ label: 'EU · EN',
168
+ subLabel: 'EN sections · S355',
169
+ unitSystem: 'metric',
170
+ defaultDisplayUnits: 'mm',
171
+ shapesPath: '/api/eu-shapes',
172
+ catalogueNoun: 'EU section',
173
+ scaleGrammar: 'metric',
174
+ columnBelowReachMm: COLUMN_BELOW_REACH_MM_METRIC,
175
+ columnNearCutMm: COLUMN_NEAR_CUT_MM_METRIC,
176
+ designationTokenUnit: 'mm',
177
+ aiscInchTable: false,
178
+ // The catalogue's PRIMARY spelling (`KK200/100/5`) is the name a host export sends. Whether Tekla accepts
179
+ // it needs a Tekla EU/NL environment this repo's machines lack, so the host bake is unverified (#3204).
180
+ exportPrimarySpelling: true,
181
+ defaultGrade: {
182
+ rolled: 'S355',
183
+ hollow: 'S355J2H',
184
+ rolledByName: [],
185
+ // A European hollow section is named `KK…` / `KW…` / `N…`, which no `RHS|SHS|CHS` test would catch, so
186
+ // the catalogue ROW decides (its shape). The pattern is the fallback for a designation the catalogue
187
+ // does not hold at all (`RHS160*100*4`, which the importer leaves unresolved on purpose).
188
+ hollowNamePattern: '^(CHS|SHS|RHS|EHS|KK\\d|KW\\d|N\\d)',
189
+ hollowRowShapes: ['rhs', 'chs', 'ehs'],
190
+ hollowRowFamilies: null,
191
+ },
192
+ // American and British names are correctly spelled in THEIR catalogues, not typos here.
193
+ foreignSectionPattern: '^((W|WWF|WRF|HP|HSS|WT|MT|ST|M|S|MC|C|PIPE)\\d|(UB|UC|UKB|UKBP|UKC|UKA|UKT|UKPFC|PFC|RSJ|RSA|RSC|JUMBO|TEE)\\s*-?\\d)',
194
+ foreignSectionNoun: 'American or British section',
195
+ shapesHeldNote: 'EU sections only',
196
+ chipTip: 'This model resolves every section against the EU catalogue (EN sections, S355 default grade). Chosen when the project was created and fixed for its life.',
197
+ detailerAgent: 'steel-detailer-eu',
198
+ };
199
+
200
+ /** @type {Readonly<Record<'US'|'UK'|'EU', Readonly<SteelEnvironmentTraits>>>} */
201
+ const BY_ID = { US: Object.freeze(US), UK: Object.freeze(UK), EU: Object.freeze(EU) };
202
+
203
+ /** @type {ReadonlyMap<string, Readonly<SteelEnvironmentTraits>>} */
204
+ export const STEEL_ENVIRONMENT_TRAITS = new Map(STEEL_ENVIRONMENT_IDS.map((id) => [id, BY_ID[id]]));
205
+
206
+ /**
207
+ * The environment an UNSTATED (or unregistered) one resolves as. A compatibility default so projects
208
+ * and contracts written before the field existed keep their behaviour — never a claim that US is the
209
+ * standard case. `server/steel-environment.ts` re-exports it.
210
+ *
211
+ * @type {'US'}
212
+ */
213
+ export const FALLBACK_ENVIRONMENT_ID = 'US';
214
+
215
+ /**
216
+ * Strict: the traits of a REGISTERED environment, else `undefined` (absent, unknown, or not a string).
217
+ *
218
+ * @param {unknown} id
219
+ * @returns {Readonly<SteelEnvironmentTraits> | undefined}
220
+ */
221
+ export function traitsOf(id) {
222
+ return STEEL_ENVIRONMENT_TRAITS.get(/** @type {string} */ (id));
223
+ }
224
+
225
+ /**
226
+ * Total: an unstated or unregistered id resolves as the compatibility fallback.
227
+ *
228
+ * @param {unknown} id
229
+ * @returns {Readonly<SteelEnvironmentTraits>}
230
+ */
231
+ export function traitsFor(id) {
232
+ return /** @type {Readonly<SteelEnvironmentTraits>} */ (
233
+ traitsOf(id) ?? STEEL_ENVIRONMENT_TRAITS.get(FALLBACK_ENVIRONMENT_ID));
234
+ }
235
+
236
+ /**
237
+ * The default material grade for a section — the SAME mechanism in every environment (a default per
238
+ * section family), with each environment's own grades.
239
+ *
240
+ * HOLLOW is decided by the catalogue ROW when one resolved (its `sectionShape` or `family`, per the
241
+ * environment's declaration), never by a name regex alone: a European hollow section is named `KK…` or
242
+ * `N…`, which no `RHS|SHS|CHS` pattern would catch. A designation that resolved to no row falls back to
243
+ * the environment's name pattern — the grade of a section the catalogue does not hold is still a
244
+ * labelled default, not a refusal.
245
+ *
246
+ * @param {unknown} id the project's stated environment (absent resolves as the fallback)
247
+ * @param {string} canonicalName the designation, already folded by `canonicalDesignation`
248
+ * @param {{ sectionShape?: string, family?: string } | null | undefined} row the catalogue row, when one resolved
249
+ * @returns {string}
250
+ */
251
+ export function defaultGradeFor(id, canonicalName, row) {
252
+ return gradeFromTraits(traitsFor(id).defaultGrade, canonicalName, row);
253
+ }
254
+
255
+ /**
256
+ * The mechanism behind `defaultGradeFor`, over an explicit declaration — so a rule no registered environment uses yet is still exercised.
257
+ *
258
+ * @param {DefaultGradeTraits} g
259
+ * @param {string} canonicalName
260
+ * @param {{ sectionShape?: string, family?: string } | null | undefined} row
261
+ * @returns {string}
262
+ */
263
+ export function gradeFromTraits(g, canonicalName, row) {
264
+ let hollow;
265
+ if (row && (g.hollowRowShapes || g.hollowRowFamilies)) {
266
+ hollow = (g.hollowRowShapes ? g.hollowRowShapes.includes(row.sectionShape) : false)
267
+ || (g.hollowRowFamilies ? g.hollowRowFamilies.includes(row.family) : false);
268
+ } else {
269
+ hollow = compiled(g.hollowNamePattern, '').test(canonicalName);
270
+ }
271
+ if (hollow) return g.hollow;
272
+ for (const [pattern, grade] of g.rolledByName) if (compiled(pattern, '').test(canonicalName)) return grade;
273
+ return g.rolled;
274
+ }
275
+
276
+ /** A pattern compiled once per source/flags: the scene bake asks per member, and none of these carry state (no `g`/`y` flag). */
277
+ const PATTERNS = new Map();
278
+ function compiled(source, flags) {
279
+ const key = `${flags}/${source}`;
280
+ let re = PATTERNS.get(key);
281
+ if (!re) { re = new RegExp(source, flags); PATTERNS.set(key, re); }
282
+ return re;
283
+ }
284
+
285
+ /**
286
+ * Whether a designation that THIS environment's catalogue has no row for is spelled like a section
287
+ * another environment's catalogue carries — "European/British section, correctly spelled, simply not
288
+ * in a US catalogue". The caller establishes the first half (no row); this answers the second.
289
+ *
290
+ * @param {unknown} id
291
+ * @param {unknown} designation
292
+ * @returns {boolean}
293
+ */
294
+ export function looksLikeForeignSection(id, designation) {
295
+ const pattern = traitsFor(id).foreignSectionPattern;
296
+ return pattern !== null && compiled(pattern, 'i').test(String(designation ?? '').trim());
297
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Used lines (2026-11-10 plan, docs/superpowers/specs/2026-11-10-filter-used-lines-overlay-PLAN.md): which Drawing
3
+ * Filter lines the steel model was built from, and which selected lines nothing in the model uses.
4
+ *
5
+ * A view over the record, never a new claim. Every state below is read from what the model already cites:
6
+ * - `member` an ACTIVE member observation cites the line (`plans[].memberObservations[].evidence.source`), or a
7
+ * source-view member's drawing target does (`provisional_members[].geometry.drawingTarget`);
8
+ * - `evidence` something else the model holds cites it: a callout, an elevation reading, a registration control,
9
+ * a detail-size claim (owner ruling F3, 2026-11-10: "used" means member lines plus other evidence);
10
+ * - `superseded` only superseded or archived observations cite it (used before a re-read or a delete);
11
+ * - `unused` the Filter selects it and nothing cites it.
12
+ * A selected line nothing cites is "not used", never "missed": the model does not record why a reader set a line
13
+ * aside (owner ruling F2, 2026-11-10), so this module cannot tell a deliberate skip from an oversight and must not
14
+ * pretend to.
15
+ *
16
+ * Element ids are content-addressed over source, sheet, index and element (server/steel-filter-contract.ts), so a
17
+ * bare id names exactly one Filter element: matching on the id alone is matching on (sourceHash, sheet, element).
18
+ */
19
+ import { textBox } from './steel-filter-core.js';
20
+
21
+ export const USED_STORAGE_KEY = 'floless:filter-used';
22
+ /** Draw order, bottom to top: the state a person must not miss is painted last. */
23
+ export const USAGE_STATES = Object.freeze(['superseded', 'evidence', 'member', 'unused']);
24
+
25
+ const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
26
+ const rows = (v) => (Array.isArray(v) ? v : []);
27
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : '');
28
+
29
+ /** Keys that name a Filter element wherever they appear in the model (schemas/steel.model.v2.schema.json). */
30
+ const ID_KEYS = new Set(['elementId', 'elementIds', 'sourceElementIds', 'referenceElementId']);
31
+ /**
32
+ * Top-level parts of the model that are not things the model is built from: the Filter itself (every element id is
33
+ * in it), and the server-written records of questions, decisions and notes, where an id names a line ASKED about.
34
+ */
35
+ const NOT_EVIDENCE = new Set(['filter', 'ai_decisions', 'read_notes', 'read_coverage', 'sheet_previews', 'origin', 'environment', 'source']);
36
+
37
+ function addRef(map, id, state, memberIds) {
38
+ const key = str(id);
39
+ if (!key) return;
40
+ let row = map.get(key);
41
+ if (!row) { row = { member: false, evidence: false, superseded: false, memberIds: new Set() }; map.set(key, row); }
42
+ row[state] = true;
43
+ for (const m of memberIds || []) if (str(m)) row.memberIds.add(str(m));
44
+ }
45
+
46
+ /** Every element id cited anywhere under `node`, skipping the subtrees `skip` names. */
47
+ function collectIds(node, out, skip) {
48
+ if (Array.isArray(node)) { for (const v of node) collectIds(v, out, skip); return; }
49
+ if (!obj(node)) return;
50
+ for (const [k, v] of Object.entries(node)) {
51
+ if (skip && skip(node, k)) continue;
52
+ if (ID_KEYS.has(k)) {
53
+ if (typeof v === 'string') out.push(v);
54
+ else if (Array.isArray(v)) for (const id of v) if (typeof id === 'string') out.push(id);
55
+ continue;
56
+ }
57
+ collectIds(v, out, skip);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * The model's citations of Filter elements.
63
+ * @returns {{ byId: Map<string, {member:boolean, evidence:boolean, superseded:boolean, memberIds:Set<string>}>,
64
+ * memberCount: number, cited: number, manual: string[], memberLines: Map<string, Set<string>> }}
65
+ */
66
+ export function usageIndex(contract) {
67
+ const byId = new Map();
68
+ const memberLines = new Map(); // member id → the element ids its ACTIVE observations cite
69
+ const c = obj(contract) ? contract : {};
70
+ for (const plan of rows(c.plans)) {
71
+ if (!obj(plan)) continue;
72
+ for (const o of rows(plan.memberObservations)) {
73
+ if (!obj(o)) continue;
74
+ const id = str(obj(o.evidence) && obj(o.evidence.source) ? o.evidence.source.elementId : '');
75
+ const bound = rows(obj(o.binding) ? o.binding.memberIds : []).map(str).filter(Boolean);
76
+ // The lifecycle lives on the binding (schemas/steel.model.v2.schema.json $defs/observationBinding).
77
+ const active = (obj(o.binding) ? o.binding.status : undefined) === 'active';
78
+ if (id) addRef(byId, id, active ? 'member' : 'superseded', active ? bound : []);
79
+ if (active && id) for (const m of bound) { if (!memberLines.has(m)) memberLines.set(m, new Set()); memberLines.get(m).add(id); }
80
+ if (active && obj(o.evidence)) {
81
+ const more = [];
82
+ collectIds(o.evidence, more, (parent, k) => parent === o.evidence && k === 'source');
83
+ for (const ref of more) addRef(byId, ref, 'evidence');
84
+ }
85
+ }
86
+ const more = [];
87
+ collectIds(plan, more, (parent, k) => parent === plan && k === 'memberObservations');
88
+ for (const ref of more) addRef(byId, ref, 'evidence');
89
+ }
90
+ for (const p of rows(c.provisional_members)) {
91
+ if (!obj(p)) continue;
92
+ const target = obj(p.geometry) && obj(p.geometry.drawingTarget) ? p.geometry.drawingTarget : null;
93
+ const pid = str(p.id);
94
+ if (target && str(target.elementId)) {
95
+ addRef(byId, target.elementId, 'member', pid ? [pid] : []);
96
+ if (pid) { if (!memberLines.has(pid)) memberLines.set(pid, new Set()); memberLines.get(pid).add(str(target.elementId)); }
97
+ }
98
+ }
99
+ for (const [k, v] of Object.entries(c)) {
100
+ if (k === 'plans' || k === 'provisional_members' || NOT_EVIDENCE.has(k)) continue;
101
+ const more = [];
102
+ collectIds(v, more);
103
+ for (const ref of more) addRef(byId, ref, 'evidence');
104
+ }
105
+ const members = rows(c.members).filter(obj);
106
+ const manual = members.filter((m) => m.provenance === 'manual' && !memberLines.has(str(m.id))).map((m) => str(m.id));
107
+ return { byId, memberLines, memberCount: members.length + rows(c.provisional_members).length, cited: byId.size, manual };
108
+ }
109
+
110
+ /**
111
+ * One element's state, or '' for a line the Filter does not select. A filtered-out line is never marked, cited or
112
+ * not: it is not in the selection the model reads, and on a raster sheet it is not even drawn (plan, States).
113
+ */
114
+ export function elementUsage(index, el, selected) {
115
+ if (!selected) return '';
116
+ const row = index && el && index.byId.get(str(el.elementId));
117
+ if (row && row.member) return 'member';
118
+ if (row && row.evidence) return 'evidence';
119
+ if (row && row.superseded) return 'superseded';
120
+ return 'unused';
121
+ }
122
+
123
+ /**
124
+ * Members whose drawing lines are on none of the Filter's sheets: read from an earlier revision of the drawing,
125
+ * whose lines the current Filter does not hold.
126
+ */
127
+ export function membersFromElsewhere(index, sheets) {
128
+ if (!index) return 0;
129
+ const present = new Set();
130
+ for (const sh of rows(sheets)) for (const el of rows(sh && sh.elements)) if (str(el && el.elementId)) present.add(str(el.elementId));
131
+ let n = 0;
132
+ for (const ids of index.memberLines.values()) if (![...ids].some((id) => present.has(id))) n++;
133
+ return n;
134
+ }
135
+
136
+ /** SVG path data that traces one element: its own `d`, a circle, or the box a text run sits in. */
137
+ export function elementPathData(el) {
138
+ if (!el) return '';
139
+ if (el.kind === 'text') {
140
+ const box = textBox(el.bbox);
141
+ if (!box) return '';
142
+ const [x0, y0, x1, y1] = box, pad = 2;
143
+ return `M${x0 - pad} ${y0 - pad}H${x1 + pad}V${y1 + pad}H${x0 - pad}Z`;
144
+ }
145
+ if (typeof el.d === 'string' && el.d.trim()) return el.d;
146
+ if (el.kind === 'circle' && [el.cx, el.cy, el.r].every(Number.isFinite) && el.r > 0) {
147
+ const { cx, cy, r } = el;
148
+ return `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0`;
149
+ }
150
+ return '';
151
+ }
152
+
153
+ /**
154
+ * One sheet's marks: path data per state (each state is ONE <path>, so the overlay adds four nodes, not thousands)
155
+ * and the counts the chip shows. `isSelected(el)` is the Filter's own current selection.
156
+ */
157
+ export function sheetUsage(index, elements, isSelected) {
158
+ const parts = { member: [], evidence: [], superseded: [], unused: [] };
159
+ const counts = { member: 0, evidence: 0, superseded: 0, unused: 0 };
160
+ for (const el of rows(elements)) {
161
+ const state = elementUsage(index, el, !!(isSelected && isSelected(el)));
162
+ if (!state) continue;
163
+ counts[state]++;
164
+ const d = elementPathData(el);
165
+ if (d) parts[state].push(d);
166
+ }
167
+ const paths = {};
168
+ for (const k of USAGE_STATES) paths[k] = parts[k].join(' ');
169
+ return { paths, counts };
170
+ }
171
+
172
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
173
+
174
+ /**
175
+ * What the chip says. Plain words, and true ones: "not used" rather than "missed", and an empty model says that
176
+ * lines are marked once the model takes them in rather than showing a sheet-wide wall of amber.
177
+ * @returns {{ kind: 'empty'|'none-here'|'counts', used: number, unused: number, lead: string, extras: string[], showUnused: boolean }}
178
+ */
179
+ export function usageChip(index, counts, elsewhere) {
180
+ const used = (counts.member || 0) + (counts.evidence || 0);
181
+ const extras = [];
182
+ if (counts.superseded) extras.push(plural(counts.superseded, 'line used before a re-read', 'lines used before a re-read'));
183
+ if (elsewhere) extras.push(plural(elsewhere, 'member from an earlier drawing revision', 'members from an earlier drawing revision'));
184
+ if (index && index.manual.length) extras.push(plural(index.manual.length, 'member added by hand, with no drawing line', 'members added by hand, with no drawing line'));
185
+ if (!index || (!index.cited && !index.memberCount)) {
186
+ return { kind: 'empty', used: 0, unused: 0, lead: 'No members yet. Lines are marked once the model takes them in.', extras: [], showUnused: false };
187
+ }
188
+ if (!used) return { kind: 'none-here', used: 0, unused: counts.unused || 0, lead: 'Nothing in the model uses a line on this sheet yet.', extras, showUnused: false };
189
+ return { kind: 'counts', used, unused: counts.unused || 0, lead: `${used} used`, extras, showUnused: true };
190
+ }
191
+
192
+ /** The one sentence a screen reader hears. */
193
+ export function usageAnnouncement(chip) {
194
+ if (chip.kind !== 'counts') return 'Used lines: ' + chip.lead;
195
+ return `Used lines: ${chip.used} used, ${chip.unused} not used on this sheet.` + (chip.extras.length ? ' ' + chip.extras.join('. ') + '.' : '');
196
+ }
197
+
198
+ const TOGGLE_TIP = '. Marks the drawing lines the steel model was built from (solid green, or dashed for callouts and other readings) and the selected lines nothing in the model uses yet (dotted amber). It changes nothing in the filter or the model.';
199
+ /** How long after a person asks (the toggle, a sheet switch) the count is said, so a burst of repaints says it once. */
200
+ export const USED_ANNOUNCE_MS = 1500;
201
+
202
+ /**
203
+ * The Used lines overlay on the Drawing Filter stage: the marks, the toggle in the bottom-left bar, and the count
204
+ * chip above it. On by default and remembered on this computer; "Only not used" lasts for this visit only. The page
205
+ * calls `render()` on every repaint (a selection, mode or sheet change); a commit to the model reloads the page, so
206
+ * the marks follow each saved read without a poll of their own.
207
+ */
208
+ export function mountUsedLines(o) {
209
+ const paths = Object.fromEntries(USAGE_STATES.map((k) => [k, o.g.querySelector('.u-' + k)]));
210
+ let on = true;
211
+ try { on = !o.storage || o.storage.getItem(USED_STORAGE_KEY) !== 'off'; } catch { on = true; }
212
+ let onlyUnused = false, chip = null, timer = 0, lastSheet = null, index = null, indexFor = null, elsewhere = 0;
213
+
214
+ function indexNow() {
215
+ const c = o.contract();
216
+ if (index && indexFor === c) return index;
217
+ index = usageIndex(c); indexFor = c;
218
+ elsewhere = membersFromElsewhere(index, o.sheets());
219
+ return index;
220
+ }
221
+ function announce() {
222
+ clearTimeout(timer);
223
+ timer = setTimeout(() => { if (on && chip) o.live.textContent = usageAnnouncement(chip); }, USED_ANNOUNCE_MS);
224
+ }
225
+ function render() {
226
+ if (!o.ready()) { o.chip.hidden = true; o.stage.style.setProperty('--used-chip-h', '0px'); return; }
227
+ // Off costs nothing per repaint: the marks keep their last shape while they fade, and are rebuilt when turned on.
228
+ if (!on) {
229
+ o.g.classList.add('off');
230
+ o.chip.hidden = true;
231
+ o.stage.classList.remove('used-only-unused', 'used-on');
232
+ o.toggle.setAttribute('aria-pressed', 'false');
233
+ o.toggle.dataset.tip = 'Show used lines' + TOGGLE_TIP;
234
+ o.stage.style.setProperty('--used-chip-h', '0px');
235
+ lastSheet = o.active();
236
+ if (o.afterLayout) o.afterLayout();
237
+ return;
238
+ }
239
+ const sheets = o.sheets(), active = o.active();
240
+ const els = (sheets[active] && sheets[active].elements) || [];
241
+ const idx = indexNow();
242
+ const { paths: d, counts } = sheetUsage(idx, els, o.isSelected);
243
+ chip = usageChip(idx, counts, elsewhere);
244
+ // No amber until something on this sheet is used: before a read lands, every selected line would be "not used".
245
+ for (const k of USAGE_STATES) paths[k].setAttribute('d', k === 'unused' && !chip.showUnused ? '' : d[k]);
246
+ const reviewable = chip.showUnused && chip.unused > 0;
247
+ if (!reviewable) onlyUnused = false;
248
+ // Every selected line used: say so in words rather than offer a review switch with nothing to review.
249
+ o.lead.textContent = chip.showUnused && !chip.unused ? chip.lead + ' · none left unused' : chip.lead;
250
+ o.swUsed.hidden = chip.kind !== 'counts';
251
+ o.onlyBtn.hidden = !reviewable;
252
+ o.unusedN.textContent = chip.unused + ' not used';
253
+ o.onlyBtn.setAttribute('aria-pressed', String(onlyUnused));
254
+ o.onlyBtn.dataset.tip = onlyUnused ? 'Show every mark again' : 'Show only the selected lines nothing in the model uses, over a fainter drawing';
255
+ o.extras.textContent = chip.extras.join(' · ');
256
+ o.extras.hidden = !chip.extras.length;
257
+ o.g.classList.toggle('off', !on);
258
+ o.chip.hidden = !on;
259
+ o.stage.classList.toggle('used-only-unused', on && onlyUnused);
260
+ o.stage.classList.toggle('used-on', on);
261
+ o.toggle.setAttribute('aria-pressed', String(on));
262
+ o.toggle.dataset.tip = (on ? 'Hide used lines' : 'Show used lines') + TOGGLE_TIP;
263
+ layout();
264
+ if (lastSheet !== null && lastSheet !== active) announce();
265
+ lastSheet = active;
266
+ if (o.afterLayout) o.afterLayout();
267
+ }
268
+ /**
269
+ * The chip sits just above the bottom-left bar, whatever height the bar has wrapped to, and tells the page its own
270
+ * height so the hover note stacks above it. Called on every render and whenever the bar or the chip resizes.
271
+ */
272
+ function layout() {
273
+ const barH = (o.bar && o.bar.offsetHeight) || 0;
274
+ if (barH) o.chip.style.bottom = (12 + barH + 6) + 'px';
275
+ o.stage.style.setProperty('--used-chip-h', o.chip.hidden ? '0px' : ((o.chip.offsetHeight || 0) + 6) + 'px');
276
+ }
277
+ o.toggle.addEventListener('click', () => {
278
+ on = !on;
279
+ try { if (o.storage) o.storage.setItem(USED_STORAGE_KEY, on ? 'on' : 'off'); } catch { /* private window: this visit only */ }
280
+ if (!on) { onlyUnused = false; clearTimeout(timer); o.live.textContent = ''; }
281
+ render();
282
+ if (on) announce();
283
+ });
284
+ o.onlyBtn.addEventListener('click', () => {
285
+ if (!chip || !chip.showUnused || !chip.unused) return;
286
+ onlyUnused = !onlyUnused;
287
+ render();
288
+ });
289
+ return {
290
+ render,
291
+ layout,
292
+ isOn: () => on,
293
+ /** For a real browser pass to read the outcome; it drives nothing. */
294
+ state: () => ({
295
+ on, onlyUnused, chip: o.chip.hidden ? null : String(o.chip.textContent || '').replace(/\s+/g, ' ').trim(), counts: chip,
296
+ d: Object.fromEntries(USAGE_STATES.map((k) => [k, (paths[k].getAttribute('d') || '').length])), live: o.live.textContent,
297
+ }),
298
+ };
299
+ }