@vulcan-energy/mcp-helper 0.3.1 → 0.3.3

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.
@@ -2091,14 +2091,141 @@ var require_polygon_clipping_umd = __commonJS({
2091
2091
  }
2092
2092
  });
2093
2093
 
2094
+ // ../hem-target-runtime/src/hem/epc_design_heat_loss.py?raw
2095
+ var require_epc_design_heat_loss = __commonJS({
2096
+ "../hem-target-runtime/src/hem/epc_design_heat_loss.py?raw"(exports, module) {
2097
+ module.exports = `# SPDX-FileCopyrightText: 2026 Home Energy Foundry Limited and contributors
2098
+ # SPDX-License-Identifier: AGPL-3.0-only
2099
+ # This file is subject to Vulcan Origin Terms v1.0; see scripts/hem-targets/licensing/ADDITIONAL_TERMS.md.
2100
+ """Static design heat loss of a HEM:EPC core input (the wrapper's preproc.json).
2101
+
2102
+ The Python HEM Core's own calc_HTC_HLP (hem_core/project.py), the function behind the
2103
+ results_static "Heat transfer coefficient" row. No simulation runs. Same contract and method as
2104
+ hem-target-core/src/design_heat_loss.rs: the engine only returns a total per zone, so thermal
2105
+ bridging and fabric are isolated by rerunning it with each zeroed (ventilation reads element
2106
+ geometry, never U-values or resistances).
2107
+ """
2108
+ import copy
2109
+ import json
2110
+
2111
+ from hem_core.project import calc_HTC_HLP
2112
+
2113
+
2114
+ def _zone_htcs(model):
2115
+ # calc_HTC_HLP writes derived values into the elements it reads.
2116
+ return calc_HTC_HLP(copy.deepcopy(model))[2]
2117
+
2118
+
2119
+ def vulcan_design_heat_loss(model):
2120
+ temperatures = (model.get("ExternalConditions") or {}).get("air_temperatures")
2121
+ if not temperatures:
2122
+ raise ValueError("No weather data: the core input has no air temperatures")
2123
+ if "temp_internal_air_static_calcs" not in model:
2124
+ raise ValueError("The core input has no temp_internal_air_static_calcs")
2125
+ # The internal air temperature of the engine's own static calculation. The EPC wrapper sets
2126
+ # it to 21 (epc_wrapper/models/input.py temp_internal_air_static_calcs), as FHS's 21/20 max.
2127
+ setpoint = model["temp_internal_air_static_calcs"]
2128
+ coldest = min(temperatures)
2129
+
2130
+ total = _zone_htcs(model)
2131
+ model = copy.deepcopy(model)
2132
+ for zone in model["Zone"].values():
2133
+ zone["ThermalBridging"] = 0.0
2134
+ without_bridges = _zone_htcs(model)
2135
+ for zone in model["Zone"].values():
2136
+ for element in zone["BuildingElement"].values():
2137
+ if element["type"] == "BuildingElementGround":
2138
+ # Ground loss is area x u_value; the Core also converts u_value to a resistance,
2139
+ # so it cannot be exactly 0.
2140
+ element["u_value"] = 1e-300
2141
+ elif element.pop("u_value", None) is not None or "thermal_resistance_construction" in element:
2142
+ # U = 1/(R + Rsi + Rse) ~ 1e-300 W/m2K: fabric loss vanishes.
2143
+ element["thermal_resistance_construction"] = 1e300
2144
+ ventilation_only = _zone_htcs(model)
2145
+
2146
+ return {
2147
+ "coldestHourC": coldest,
2148
+ "setpointC": setpoint,
2149
+ "zones": {
2150
+ name: {
2151
+ "htcWPerK": htc,
2152
+ "fabricWPerK": without_bridges[name] - ventilation_only[name],
2153
+ "thermalBridgesWPerK": htc - without_bridges[name],
2154
+ "ventilationWPerK": ventilation_only[name],
2155
+ "designLossKw": htc * (setpoint - coldest) / 1000.0,
2156
+ }
2157
+ for name, htc in total.items()
2158
+ },
2159
+ }
2160
+
2161
+
2162
+ def vulcan_design_heat_loss_file(path):
2163
+ """The JSON contract for the core input at \`path\`."""
2164
+ with open(path) as file:
2165
+ return json.dumps(vulcan_design_heat_loss(json.load(file)))
2166
+ `;
2167
+ }
2168
+ });
2169
+
2094
2170
  // ../community/packages/geometry-editor/src/lib/issueTarget.ts
2095
2171
  var issuePathSegments = (path) => (path ?? "").split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
2096
2172
 
2097
2173
  // ../community/packages/geometry-editor/src/lib/hemieFabric.ts
2098
2174
  var ENGLAND_AREAS = new Set("AL B BA BB BD BH BL BN BR BS CB CM CO CR CT CV CW DA DE DH DL DN DT DY E EC EN EX FY GL GU HA HD HG HP HU HX IG IP KT L LA LE LN LS LU M ME MK N NE NG NN NR NW OL OX PE PL PO PR RG RH RM S SE SG SK SL SM SN SO SP SR SS ST SW TA TF TN TQ TR TS TW UB W WA WC WD WF WN WR WS WV YO".split(" "));
2099
2175
  var HEMIE_NATION = "HEMIE_nation";
2176
+ var ROOF_DETAILS = ["ceiling_thickness", "ceiling_thermal_conductivity", "joist_depth", "percentage_area_of_timber_joists", "insulation_thermal_conductivity"];
2177
+ var LOFT_DETAILS = [...ROOF_DETAILS, "rafter_depth", "percentage_area_of_timber_rafters", "roof_characteristics", "air_gap_thermal_resistance"];
2178
+ var WALL_FINISHES = {
2179
+ Brick: "BrickFinish",
2180
+ Render: "RenderFinish",
2181
+ Timber: "TimberFinish",
2182
+ "Metal (uncoated)": "MetalUncoatedFinish",
2183
+ "Metal (coated)": "MetalCoatedFinish",
2184
+ "Fibre-cement": "FibreCementWallFinish",
2185
+ "Composite panels (metal skins)": "CompositePanelsFinish"
2186
+ };
2187
+ var ROOF_FINISHES = {
2188
+ "Concrete roof tile": "ConcreteRoofTileFinish",
2189
+ "Clay tile": "ClayTileFinish",
2190
+ Slate: "SlateFinish",
2191
+ Asphalt: "AsphaltFinish",
2192
+ Timber: "TimberFinish",
2193
+ "Metal (uncoated)": "MetalUncoatedFinish",
2194
+ "Metal (coated)": "MetalCoatedFinish",
2195
+ "Fibre-cement": "FibreCementRoofFinish",
2196
+ "Composite panels (metal skins)": "CompositePanelsFinish"
2197
+ };
2198
+ var DOOR_FINISHES = {
2199
+ Timber: "TimberFinish",
2200
+ "Metal (uncoated)": "MetalUncoatedFinish",
2201
+ "Metal (coated)": "MetalCoatedFinish",
2202
+ "Composite panels (metal skins)": "CompositePanelsFinish"
2203
+ };
2204
+ var PARK_HOME_WALL_FINISHES = {
2205
+ "uPVC vinyl / Plastic": "ParkHomePlasticFinish",
2206
+ "Stucco / Aggregate paint": "ParkHomePaintFinish",
2207
+ "Timber / Wood cladding": "ParkHomeTimberFinish",
2208
+ "CanExel / Engineered HDF": "ParkHomeHDFFinish"
2209
+ };
2210
+ var SURFACE_FINISHES = {
2211
+ external_wall: WALL_FINISHES,
2212
+ external_door: DOOR_FINISHES,
2213
+ park_home_wall: PARK_HOME_WALL_FINISHES,
2214
+ flat_roof: ROOF_FINISHES,
2215
+ unheated_pitched_roof: ROOF_FINISHES,
2216
+ heated_pitched_roof: ROOF_FINISHES,
2217
+ mini_flat_roof: ROOF_FINISHES,
2218
+ mini_pitched_roof: ROOF_FINISHES,
2219
+ park_home_flat_roof: ROOF_FINISHES,
2220
+ park_home_pitched_roof: ROOF_FINISHES
2221
+ };
2222
+ var OUTSIDE_SURFACE_TYPES = /* @__PURE__ */ new Set([...Object.keys(SURFACE_FINISHES), "above_external_area_floor", "park_home_floor", "thatched_roof"]);
2100
2223
  var words = (value) => value.charAt(0).toUpperCase() + value.slice(1).replace(/_/g, " ");
2101
- var hemieConstructionTypeLabel = words;
2224
+ var CONSTRUCTION_TYPE_LABELS = {
2225
+ not_edge_insulated_ground_attached_floor: "Ground floor, no edge insulation",
2226
+ edge_insulated_ground_attached_floor: "Ground floor, edge insulated"
2227
+ };
2228
+ var hemieConstructionTypeLabel = (type) => CONSTRUCTION_TYPE_LABELS[type] ?? words(type);
2102
2229
 
2103
2230
  // ../community/packages/geometry-editor/src/lib/zoneDerivation.ts
2104
2231
  var import_polygon_clipping2 = __toESM(require_polygon_clipping_umd(), 1);
@@ -2106,24 +2233,6 @@ var import_polygon_clipping2 = __toESM(require_polygon_clipping_umd(), 1);
2106
2233
  // ../community/packages/geometry-editor/src/lib/polygonSync.ts
2107
2234
  var import_polygon_clipping = __toESM(require_polygon_clipping_umd(), 1);
2108
2235
 
2109
- // ../community/packages/geometry-editor-host/src/schemaPort.ts
2110
- function unavailable(operation) {
2111
- throw new Error(`Geometry schema ${operation} is unavailable`);
2112
- }
2113
- var unavailableGeometrySchemaPort = Object.freeze({
2114
- availability: "unavailable",
2115
- preload: async () => unavailable("preload"),
2116
- getRootSchema: () => unavailable("root lookup"),
2117
- getElementSubschema: () => unavailable("element lookup"),
2118
- getBaseFieldsForElementType: () => unavailable("base-field lookup"),
2119
- getApplianceKeys: () => unavailable("appliance-key lookup"),
2120
- getStrictestIntegerKeysForElementType: () => unavailable("numeric-typing lookup"),
2121
- getSchemaSubtypeForElementData: () => unavailable("subtype lookup"),
2122
- getConditionalRequiredFields: () => unavailable("conditional-required lookup"),
2123
- validateProperty: () => unavailable("property validation"),
2124
- findParameter: () => unavailable("parameter lookup")
2125
- });
2126
-
2127
2236
  // ../community/packages/geometry-editor/src/lib/roofCutouts.ts
2128
2237
  var import_polygon_clipping4 = __toESM(require_polygon_clipping_umd(), 1);
2129
2238
 
@@ -2170,6 +2279,25 @@ var FHS_MASS_CLASS_COMMENTARY = {
2170
2279
  "M: Mass concentrated inside": MASS_CLASS_MEANINGS.M
2171
2280
  };
2172
2281
 
2282
+ // ../community/packages/geometry-editor-host/src/schemaPort.ts
2283
+ var A7_AREAL_HEAT_CAPACITY_INPUT = Object.freeze({ classes: "surface", numberTypes: Object.freeze([]) });
2284
+ function unavailable(operation) {
2285
+ throw new Error(`Geometry schema ${operation} is unavailable`);
2286
+ }
2287
+ var unavailableGeometrySchemaPort = Object.freeze({
2288
+ availability: "unavailable",
2289
+ preload: async () => unavailable("preload"),
2290
+ getRootSchema: () => unavailable("root lookup"),
2291
+ getElementSubschema: () => unavailable("element lookup"),
2292
+ getBaseFieldsForElementType: () => unavailable("base-field lookup"),
2293
+ getApplianceKeys: () => unavailable("appliance-key lookup"),
2294
+ getStrictestIntegerKeysForElementType: () => unavailable("numeric-typing lookup"),
2295
+ getSchemaSubtypeForElementData: () => unavailable("subtype lookup"),
2296
+ getConditionalRequiredFields: () => unavailable("conditional-required lookup"),
2297
+ validateProperty: () => unavailable("property validation"),
2298
+ findParameter: () => unavailable("parameter lookup")
2299
+ });
2300
+
2173
2301
  // ../community/packages/geometry-editor/src/lib/overrideProvenance.ts
2174
2302
  var SLOPED_WIDTH_OVERRIDE_DESCRIPTOR = {
2175
2303
  flag: "_widthUserOverride",
@@ -2289,10 +2417,11 @@ var DWELLING_FIELD_KEYS = /* @__PURE__ */ new Set([
2289
2417
  "BuildingLength",
2290
2418
  "BuildingWidth",
2291
2419
  "KitchenExtractorHoodExternal",
2292
- "HasElectricitySmartMeter"
2420
+ "HasElectricitySmartMeter",
2421
+ "ElectricitySmartMeterGUID"
2293
2422
  ]);
2294
2423
  function globalSettingsFieldSection(key) {
2295
- if (key.startsWith("DefaultAssembly")) return "defaults";
2424
+ if (key === "DefaultsPath" || key.startsWith("DefaultAssembly") || key.startsWith("FabricRow_") || key === "HEMIE_age_band" || key.startsWith("HEMIE_construction_")) return "fabric";
2296
2425
  if (key === "TargetBundleId" || key === "IsExistingBuilding" || key.startsWith("HEMIE_")) return "target";
2297
2426
  if (key.startsWith("AirPermeability_test_")) return "airTightness";
2298
2427
  if (key.startsWith("Ventilation_") || key === "AirPermeability_ventilation_zone_height") return "ventilation";
@@ -2300,6 +2429,42 @@ function globalSettingsFieldSection(key) {
2300
2429
  if (key.startsWith("General_") || key.startsWith("NumberOf") || key.startsWith("Appliances_") || DWELLING_FIELD_KEYS.has(key)) return "dwelling";
2301
2430
  return null;
2302
2431
  }
2432
+ var METADATA_INPUT_LABELS = {
2433
+ NumberOfBedrooms: "Number of bedrooms",
2434
+ NumberOfWetRooms: "Number of wet rooms",
2435
+ GroundFloorArea: "Ground floor area (m\xB2)",
2436
+ HeatingControlType: "Heating control type",
2437
+ PartGcompliance: "Part G compliance",
2438
+ PartO_active_cooling_required: "Part O active cooling required",
2439
+ AirPermeability_test_pressure: "Test pressure",
2440
+ AirPermeability_test_result: "Test result",
2441
+ AirPermeability_ventilation_zone_height: "Ventilation zone height (m)",
2442
+ Ventilation_shield_class: "Shield class",
2443
+ Ventilation_terrain_class: "Terrain class",
2444
+ Ventilation_altitude: "Altitude (m)",
2445
+ Ventilation_ventilation_zone_base_height: "Ventilation zone base height (m)",
2446
+ Ventilation_noise_nuisance: "Noise nuisance",
2447
+ BuildingLength: "Building length (m)",
2448
+ BuildingWidth: "Building width (m)",
2449
+ NumberOfHotTappedRooms: "Number of hot-tapped rooms",
2450
+ NumberOfUtilityRooms: "Number of utility rooms",
2451
+ NumberOfBathrooms: "Number of bathrooms",
2452
+ NumberOfSanitaryAccommodations: "Number of sanitary accommodations",
2453
+ NumberOfHabitableRooms: "Number of habitable rooms",
2454
+ KitchenExtractorHoodExternal: "Kitchen cooker hood extracts to outside",
2455
+ General_build_type: "Build type",
2456
+ General_built_form: "SAP built form",
2457
+ General_storeys_in_dwelling: "Storeys in dwelling",
2458
+ General_storey_of_dwelling: "Storey of dwelling",
2459
+ General_storeys_in_building: "Storeys in building",
2460
+ HasElectricitySmartMeter: "Electricity smart meter",
2461
+ ElectricitySmartMeterGUID: "Smart meter GUID",
2462
+ IsExistingBuilding: "Existing building",
2463
+ Ventilation_cross_vent_possible: "Cross ventilation possible",
2464
+ Appliances_has_dryer: "Has a clothes dryer",
2465
+ Appliances_has_dishwasher: "Has a dishwasher",
2466
+ Appliances_has_separate_fridge_or_freezer: "Has a separate fridge or freezer"
2467
+ };
2303
2468
  var TARGET_INPUT_ROWS = [
2304
2469
  "HasElectricitySmartMeter",
2305
2470
  "IsExistingBuilding",
@@ -2312,12 +2477,12 @@ var TARGET_INPUT_ROW_SET = new Set(TARGET_INPUT_ROWS);
2312
2477
 
2313
2478
  // ../community/packages/geometry-editor/src/lib/buildErrorDisplay.ts
2314
2479
  var SECTION_LOCATIONS = {
2315
- defaults: "Global Settings > Defaults",
2480
+ fabric: "Global Settings > Fabric",
2316
2481
  target: "Global Settings",
2317
- dwelling: "Global Settings > Dwelling Details",
2318
- airTightness: "Global Settings > Air Tightness",
2319
- ventilation: "Global Settings > Ventilation Environment",
2320
- thermalBridging: "Global Settings > Thermal Bridging"
2482
+ dwelling: "Global Settings > Dwelling details",
2483
+ airTightness: "Global Settings > Air tightness",
2484
+ ventilation: "Global Settings > Ventilation environment",
2485
+ thermalBridging: "Global Settings > Thermal bridging"
2321
2486
  };
2322
2487
  var VENTILATION_SETTINGS = /* @__PURE__ */ new Set(["cross_vent_possible", "terrain_class", "altitude", "shield_class", "noise_nuisance", "ventilation_zone_base_height"]);
2323
2488
  var settingsRow = (segments) => {
@@ -2350,7 +2515,7 @@ var buildErrorLocation = (path) => {
2350
2515
  if (segments[0] === "Metadata" && segments[1]?.startsWith("HEMIE_")) {
2351
2516
  const constructionType = segments[1].match(/^HEMIE_construction_(.+)$/)?.[1];
2352
2517
  return {
2353
- location: segments[1] === HEMIE_NATION ? "Global Settings > Dwelling Details" : `Global Settings > Defaults > Fabric${constructionType ? ` > ${hemieConstructionTypeLabel(constructionType)}` : ""}`
2518
+ location: segments[1] === HEMIE_NATION ? "Global Settings > Dwelling details" : `Global Settings > Fabric${constructionType ? ` > ${hemieConstructionTypeLabel(constructionType)}` : ""}`
2354
2519
  };
2355
2520
  }
2356
2521
  const row = settingsRow(segments);
@@ -2402,9 +2567,13 @@ var formatBuildErrorForDisplay = (item) => {
2402
2567
  const maximum = maximumFromMessage(item.message);
2403
2568
  const unexpectedFields = unexpectedFieldsFromMessage(item.message);
2404
2569
  const explicitUserMessage = item.userMessage?.trim();
2570
+ const unstatedInput = item.code === "E_EPC_REQUIRED_INPUT" && pathSegments[0] === "Metadata" && pathSegments[1] ? METADATA_INPUT_LABELS[pathSegments[1]] : void 0;
2405
2571
  let userMessage;
2406
2572
  if (explicitUserMessage) {
2407
2573
  userMessage = explicitUserMessage;
2574
+ } else if (unstatedInput) {
2575
+ const label = /^[A-Z][a-z]/.test(unstatedInput) && !/^Part\b/.test(unstatedInput) ? unstatedInput[0].toLowerCase() + unstatedInput.slice(1) : unstatedInput;
2576
+ userMessage = TARGET_INPUT_ROW_SET.has(pathSegments[1]) ? `Choose yes or no for ${label}.` : `Enter ${label}.`;
2408
2577
  } else if (location === "Appliances" && (item.message.includes("is not allowed for {}") || item.message.includes("has less than"))) {
2409
2578
  userMessage = "Add at least one appliance entry.";
2410
2579
  } else if (pathSegments[0] === "HotWaterDemand" && (item.message.includes("has less than") || keyword === "minProperties")) {
@@ -2428,7 +2597,7 @@ var formatBuildErrorForDisplay = (item) => {
2428
2597
  } else if (keyword === "const" || keyword === "allOf" || item.message.includes("is not allowed for")) {
2429
2598
  userMessage = location === "Appliances" ? "Check the appliance entries against the selected schema." : "These settings conflict with the selected schema.";
2430
2599
  } else if (!isSchemaKeywordError(item)) {
2431
- userMessage = item.message;
2600
+ userMessage = item.message.split("\n")[0];
2432
2601
  } else {
2433
2602
  userMessage = fieldLabel ? `Check ${fieldLabel}.` : "Check this section.";
2434
2603
  }
@@ -2479,10 +2648,11 @@ function pythonFailureMessage(text) {
2479
2648
  return `HEM could not calculate this model. ${exception.join(" ")}`;
2480
2649
  }
2481
2650
  var TargetRunError = class extends Error {
2482
- constructor(message, failure, traceback) {
2651
+ constructor(message, failure, traceback, report) {
2483
2652
  super(message);
2484
2653
  this.failure = failure;
2485
2654
  this.traceback = traceback;
2655
+ this.report = report;
2486
2656
  }
2487
2657
  };
2488
2658
  function targetRunFailureOf(error) {
@@ -2492,6 +2662,21 @@ function targetRunFailureOf(error) {
2492
2662
  return void 0;
2493
2663
  }
2494
2664
  var pointer = (segments) => segments.map((segment) => `/${segment.replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
2665
+ var segmentsOf = (path) => path.split("/").slice(1).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
2666
+ function authored(segments, provenance) {
2667
+ for (let length = segments.length; length >= Math.max(segments.length - 1, 1); length -= 1) {
2668
+ const source = provenance[pointer(segments.slice(0, length))];
2669
+ if (source !== void 0) return [...segmentsOf(source), ...segments.slice(length)];
2670
+ }
2671
+ return void 0;
2672
+ }
2673
+ function wallNamed(model, message) {
2674
+ const [, storey, edge] = message.match(/for wall 'storey(\d+)_wall(\d+)'/) ?? [];
2675
+ if (storey === void 0) return void 0;
2676
+ const parts = model.Zone?.building_parts ?? {};
2677
+ const found = Object.entries(parts).flatMap(([part, { walls = [] }]) => walls.flatMap((wall, index) => wall.storey_index === Number(storey) && wall.floorplan_index === Number(edge) ? [pointer(["Zone", "building_parts", part, "walls", String(index)])] : []));
2678
+ return found.length === 1 ? found[0] : void 0;
2679
+ }
2495
2680
  var SYSTEM_SECTIONS = /* @__PURE__ */ new Set(["HotWaterSource", "HeatSourceWet", "SpaceHeatSystem", "SpaceCoolSystem"]);
2496
2681
  function walk(input, loc, type) {
2497
2682
  const segments = [];
@@ -2576,21 +2761,27 @@ var readable = (field, text) => text.replace(
2576
2761
  /^Input should be (.*?)\.?$/,
2577
2762
  (_, rule) => `${field.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase())} must be ${rule}.`
2578
2763
  );
2579
- function targetRunError(report, input) {
2764
+ function targetRunError(report, input, provenance = {}) {
2580
2765
  const model = JSON.parse(input);
2581
2766
  const walked = chosenArms((report.errors ?? []).map((error) => ({ ...walk(model, error.loc, error.type), type: error.type, msg: error.msg })));
2582
2767
  const notes = /* @__PURE__ */ new Set();
2583
2768
  const issues = [];
2584
- for (const { segments, building, missing, msg } of walked) {
2585
- const field = segments[segments.length - 1] ?? "";
2769
+ for (const { segments: converted, building, missing, msg } of walked) {
2770
+ const field = converted[converted.length - 1] ?? "";
2771
+ const segments = building && !SYNTHESISED_FIELDS.has(field) ? authored(converted, provenance) ?? converted : converted;
2772
+ const located = segments !== converted;
2586
2773
  if (building && SYNTHESISED_FIELDS.has(field)) notes.add(VULCAN_FAULT);
2587
- else if (building) {
2774
+ else if (building && !located) {
2588
2775
  const reason = missing ? `${field.replace(/_/g, " ")} is missing` : readable(field, firstLine(msg ?? "")).replace(/\.$/, "");
2589
2776
  notes.add(`The EPC calculation could not use this existing building: ${reason} (${buildingPlace(segments)}). Check the elements it is built from; if they are correct, report it to Vulcan support.`);
2590
2777
  } else issues.push(missing ? { path: pointer(segments.slice(0, -1)), keyword: "required", message: `"${field}" is a required property` } : { path: pointer(segments), message: readable(field, firstLine(msg ?? "")) });
2591
2778
  }
2592
2779
  const conversionStage = report.stage === "existing_building_conversion";
2593
- if (!walked.length && conversionStage) {
2780
+ const wall = !walked.length && conversionStage ? wallNamed(model, report.message) : void 0;
2781
+ const wallSource = wall && provenance[wall];
2782
+ if (wallSource && /wall area is less than zero/.test(report.message)) {
2783
+ issues.push({ path: wallSource, message: "The windows, doors and bay in this wall take more than its area. Make them smaller, or check the wall length and height." });
2784
+ } else if (!walked.length && conversionStage) {
2594
2785
  notes.add(CODE_FAULTS.has(report.kind) ? VULCAN_FAULT : `The EPC calculation could not use this existing building: ${firstLine(report.message)}. Check the elements it is built from; if they are correct, report it to Vulcan support.`);
2595
2786
  }
2596
2787
  const cause = notes.size ? "conversion" : issues.length || ["input_check", "product_lookup"].includes(report.stage) ? "input" : "simulation";
@@ -2599,9 +2790,41 @@ function targetRunError(report, input) {
2599
2790
  }
2600
2791
  const rows = displayBuildErrorRows(issues.map((issue) => ({ source: "schema", ...issue })), () => ({ ownerKey: "" }));
2601
2792
  const message = [...notes, ...rows.length ? [`The EPC calculation found ${rows.length === 1 ? "an error" : `${rows.length} errors`} in the model. ${rows.map((row) => `${row.location}: ${row.userMessage}`).join(" ")}`] : []].join(" ");
2602
- return new TargetRunError(message, { stage: report.stage, kind: report.kind, cause, issues, notes: [...notes] }, report.traceback);
2793
+ return new TargetRunError(message, { stage: report.stage, kind: report.kind, cause, issues, notes: [...notes] }, report.traceback, report);
2603
2794
  }
2604
2795
 
2796
+ // ../hem-target-runtime/src/hem/epcAssumptions.ts
2797
+ var EPC_ASSUMPTIONS_PYTHON = `
2798
+ def vulcan_epc_estimated_leaks(model):
2799
+ """Assumption pending DESNZ E17. An existing building with no air test states only HEMIE's
2800
+ three leakage-estimate inputs (GeometryInfiltrationProperties). The wrapper resolves them from
2801
+ the Geometry, but the pinned Orchestrator parses Leaks before that step and rejects the form. This makes the same calls on
2802
+ the same Zone and hands the Orchestrator the result: HEMIE's estimated Pulse test. If DESNZ
2803
+ fixes the Orchestrator, delete this function and its call; the input is unchanged."""
2804
+ from hemie.models.geometry import Geometry
2805
+ from hemie.models.infiltration_properties import infiltration_properties_from_geometry
2806
+ from hemie.models.leaks import GeometryInfiltrationProperties, Leaks
2807
+ zone = model.get('Zone')
2808
+ leaks = (model.get('InfiltrationVentilation') or {}).get('Leaks')
2809
+ if not (isinstance(zone, dict) and zone.get('model_type') == 'hemie' and isinstance(leaks, dict)
2810
+ and isinstance(leaks.get('infiltration_properties'), dict)):
2811
+ return model
2812
+ # The mechanical ventilation system still names its products here (the Orchestrator
2813
+ # substitutes them later), and none of HEMIE's infiltration properties reads it.
2814
+ geometry = Geometry.model_validate({key: value for key, value in zone.items() if key != 'mechanical_ventilation_system'})
2815
+ stated = {key: value for key, value in leaks.items() if key != 'infiltration_properties'}
2816
+ manual = GeometryInfiltrationProperties.model_validate(leaks['infiltration_properties'])
2817
+ properties = infiltration_properties_from_geometry(geometry,
2818
+ number_of_open_fireplaces=manual.number_of_open_fireplaces, heat_loss_corridor=manual.heat_loss_corridor,
2819
+ double_glazing_installation_period=manual.double_glazing_installation_period)
2820
+ estimated = Leaks.model_validate({**stated, 'infiltration_properties': properties})
2821
+ model['InfiltrationVentilation']['Leaks'] = {**stated, 'test_pressure': estimated.test_pressure, 'test_result': estimated.test_result}
2822
+ return model
2823
+ `;
2824
+
2825
+ // ../hem-target-runtime/src/hem/designHeatLoss.ts
2826
+ var PINNED_WEATHER_NAME = "Bedford";
2827
+
2605
2828
  // ../hem-target-runtime/src/hem/targets.ts
2606
2829
  var WRAPPERS = {
2607
2830
  fhs: {
@@ -2671,9 +2894,9 @@ var HEM_TARGETS = [
2671
2894
  // The Rust a9 that ECaaS runs in production (epb-ecaas-api e1c090e, lambda/Cargo.lock). Its wrapper
2672
2895
  // schema equals the Python a9 one, so it keeps that conversion profile's wire name. It is built
2673
2896
  // with the carried patch set fhs-a9-schema-v1 (targetSchemaCorrections.ts); build and parity:
2674
- // docs/development/HEM_Rust_A9_Target.md.
2897
+ // docs/development/HEM_Rust_A9_Target.md. v2: v1's pins and patch set plus the design_heat_loss export.
2675
2898
  {
2676
- id: "rust-fhs-a9-9e41af89-f2c2425f-v1",
2899
+ id: "rust-fhs-a9-9e41af89-f2c2425f-v2",
2677
2900
  label: "HEM:FHS 1.0.0a9",
2678
2901
  runtime: "rust",
2679
2902
  version: "1.0.0a9",
@@ -2683,8 +2906,11 @@ var HEM_TARGETS = [
2683
2906
  engineCommit: "9e41af890cc62a1cec08957340231c3591956dac",
2684
2907
  wrapperCommit: "f2c2425f00870e1611750bd2ac1be20132301e0d",
2685
2908
  conversionProfile: "python_fhs_a9",
2686
- // Measured, example_semi_detached in wasm-browser-cli at load 13-19 (13 November): actual mode
2687
- // 5.9-9.0 s, all four modes 48.3-48.6 s (docs/development/HEM_Rust_A9_Target.md).
2909
+ arealHeatCapacity: { classes: "full_depth", numberTypes: ["BuildingElementAdjacentConditionedSpace", "BuildingElementAdjacentUnconditionedSpace_Simple"] },
2910
+ // Measured, example_semi_detached at load 15-21 (15 November): Quick sim click to headline in
2911
+ // the app 7.1-8.6 s (engine 4.9 s, results write 0.7 s); wasm-browser-cli 5.2-7.1 s.
2912
+ // Compliance, all four modes: 48.3-48.6 s in wasm-browser-cli at load 13-19 (13 November).
2913
+ // Method: docs/development/HEM_Rust_A9_Target.md, "Run time".
2688
2914
  status: "provisional",
2689
2915
  typicalRunMinutes: { fhs_assumptions: 0.15, fhs_compliance: 0.8 }
2690
2916
  },
@@ -2699,37 +2925,45 @@ var HEM_TARGETS = [
2699
2925
  engineCommit: "62d3df705690f33b3fc3e905c9971d4f3743bf2e",
2700
2926
  wrapperCommit: "c5ba2673fbd886cfe4fb528f61b376bdf406ebbd",
2701
2927
  conversionProfile: "current_rust_fhs",
2702
- // Actual mode: house_two_storey 7.4 s and 8.1 s through wasm-browser-cli at load 16-20 (13 November). Compliance not measured.
2928
+ arealHeatCapacity: { classes: "surface", numberTypes: [] },
2929
+ // Actual mode, example_semi_detached at load 17-22 (15 November): Quick sim click to headline in
2930
+ // the app 7.9-8.7 s; wasm-browser-cli 6.1-7.1 s. Compliance not measured.
2703
2931
  status: "legacy",
2704
2932
  typicalRunMinutes: { fhs_assumptions: 0.12 }
2705
2933
  }
2706
2934
  ];
2707
2935
  var RECOMMENDED_HEM_TARGET = HEM_TARGETS[0].id;
2936
+ var HEM_EPC_0_13_2 = {
2937
+ id: "python-epc-0.13.2-6367f1ec-18032feb-v1",
2938
+ label: "HEM:EPC 0.13.2",
2939
+ runtime: "python",
2940
+ version: "0.13.2",
2941
+ engineVersion: "2.0.0a4",
2942
+ wrapperVersion: "0.13.2",
2943
+ wrapper: "epc",
2944
+ engineCommit: "6367f1ecb101c7f72a2006a921c732c790b0d338",
2945
+ wrapperCommit: "18032feb59294b323fc28af4fb032d34bd44bf67",
2946
+ conversionProfile: "epc_full_input_v1",
2947
+ arealHeatCapacity: { classes: "full_depth", numberTypes: "all" },
2948
+ components: {
2949
+ "hem-epc-orchestrator": { version: "0.13.2a0", commit: "993463233ad0c416e83c4de3b84889280d3c4619" },
2950
+ hemie: { version: "0.18.1", commit: "2876e2ec1c7bad2b738c9c3b3685d86860a91f41" },
2951
+ "hem-db-client": { version: "1.0.0a10", commit: "9eeb026dd52a612197b5552ca113d8121fa72679" }
2952
+ },
2953
+ // db-client/data/*.csv at the hem-db-client commit.
2954
+ productDataSha256: "d0acf4ebf050e80f3dc576ffbb1295ebeb1176e9fd4a9ec1d151a9e8f4df7457",
2955
+ // Quick, measured in wasm-browser-cli at load 9-20 (15 November, UAT bundle on main): house_two_storey
2956
+ // new build 473 s, as an existing building 365 s (HEM_EPC_Integration_Plan.md, Status).
2957
+ // Full, estimated: 35 min natively at the measured 2.4-2.6x browser ratio (same plan, Measured).
2958
+ status: "preview",
2959
+ typicalRunMinutes: { epc_quick: 8, epc_full: 90 },
2960
+ estimatedRunMinutes: ["epc_full"]
2961
+ };
2708
2962
  var UNRELEASED_HEM_TARGETS = [
2709
- {
2710
- id: "python-epc-0.13.2-6367f1ec-18032feb-v1",
2711
- label: "HEM:EPC 0.13.2",
2712
- runtime: "python",
2713
- version: "0.13.2",
2714
- engineVersion: "2.0.0a4",
2715
- wrapperVersion: "0.13.2",
2716
- wrapper: "epc",
2717
- engineCommit: "6367f1ecb101c7f72a2006a921c732c790b0d338",
2718
- wrapperCommit: "18032feb59294b323fc28af4fb032d34bd44bf67",
2719
- conversionProfile: "epc_full_input_v1",
2720
- components: {
2721
- "hem-epc-orchestrator": { version: "0.13.2a0", commit: "993463233ad0c416e83c4de3b84889280d3c4619" },
2722
- hemie: { version: "0.18.1", commit: "2876e2ec1c7bad2b738c9c3b3685d86860a91f41" },
2723
- "hem-db-client": { version: "1.0.0a10", commit: "9eeb026dd52a612197b5552ca113d8121fa72679" }
2724
- },
2725
- // db-client/data/*.csv at the hem-db-client commit.
2726
- productDataSha256: "d0acf4ebf050e80f3dc576ffbb1295ebeb1176e9fd4a9ec1d151a9e8f4df7457",
2727
- // Quick, measured: house_two_storey 491-535 s in wasm-browser-cli (HEM_EPC_Integration_Plan.md, Status).
2728
- // Full, estimated: 35 min natively at the measured 2.4-2.6x browser ratio (same plan, Measured).
2729
- status: "provisional",
2730
- typicalRunMinutes: { epc_quick: 9, epc_full: 90 },
2731
- estimatedRunMinutes: ["epc_full"]
2732
- }
2963
+ HEM_EPC_0_13_2,
2964
+ // The same pins with the HEM Core engine patch set (scripts/hem-targets/stage-python-core.mjs):
2965
+ // byte-identical outputs, faster passive-duct runs. A short-term fix; not the default until the owner's UAT.
2966
+ { ...HEM_EPC_0_13_2, id: "python-epc-0.13.2-6367f1ec-18032feb-v2", label: "HEM:EPC 0.13.2 (faster)" }
2733
2967
  ];
2734
2968
  var findHemTarget = (id) => [...HEM_TARGETS, ...UNRELEASED_HEM_TARGETS].find((target2) => target2.id === id);
2735
2969
  function resolveHemTarget(id) {
@@ -2832,6 +3066,7 @@ def vulcan_epc_stage(error, existing):
2832
3066
  stage = 'unclassified'
2833
3067
  for frame in traceback.extract_tb(error.__traceback__):
2834
3068
  if frame.name == 'orchestrator_input': stage = 'input_check'
3069
+ elif frame.name == 'vulcan_epc_estimated_leaks': stage = 'existing_building_conversion'
2835
3070
  elif frame.name in ('_add_metadata_to_input', '_write_epc_input_file') or '/hem_db_client/' in frame.filename: stage = 'product_lookup'
2836
3071
  elif frame.filename.endswith('/bin/epc.py') and frame.name == 'main':
2837
3072
  line = frame.line or ''
@@ -2839,6 +3074,8 @@ def vulcan_epc_stage(error, existing):
2839
3074
  return stage
2840
3075
  def vulcan_epc_run(input_path, output_dir, options):
2841
3076
  try:
3077
+ model = json.loads(Path(input_path).read_text())
3078
+ Path(input_path).write_text(json.dumps(vulcan_epc_estimated_leaks(model)))
2842
3079
  orchestrator = Orchestrator(db_config_file=vulcan_epc_config, input_file=Path(input_path), output_dir=Path(output_dir))
2843
3080
  orchestrator.client = hem_db_client.Client(engine_url=vulcan_epc_engine)
2844
3081
  orchestrator.run(**options, core_output_formats=(OutputFormat.CSV,))
@@ -2849,7 +3086,17 @@ def vulcan_epc_run(input_path, output_dir, options):
2849
3086
  message = f'a value named {error.args[0]} was not found' if isinstance(error, KeyError) and error.args else str(error)
2850
3087
  return json.dumps({'stage': vulcan_epc_stage(error, existing), 'kind': type(error).__name__, 'message': message,
2851
3088
  'errors': [{'loc': list(e['loc']), 'type': e['type'], 'msg': e['msg']} for e in errors],
2852
- 'traceback': ''.join(traceback.format_exception(error))})`);
3089
+ 'traceback': ''.join(traceback.format_exception(error))})
3090
+ def vulcan_epc_design_heat_loss(source, core_input):
3091
+ # Loaded on use, so a Core without calc_HTC_HLP still runs every other job.
3092
+ import hem_core.project, runpy
3093
+ if not hasattr(hem_core.project, 'calc_HTC_HLP'): return None
3094
+ return runpy.run_path(source)['vulcan_design_heat_loss_file'](core_input)
3095
+ def vulcan_epc_overheating_input(core_input):
3096
+ # Read-only: the core input HEMIE expanded the existing building into, the EPC energy run's own.
3097
+ model = json.loads(Path(core_input).read_text())
3098
+ return json.dumps({key: model[key] for key in ('Zone', 'InfiltrationVentilation')})
3099
+ ${EPC_ASSUMPTIONS_PYTHON}`);
2853
3100
  },
2854
3101
  call({ input, output, weather }, modes) {
2855
3102
  if (weather) throw new Error("HEM:EPC runs on its pinned weather; it does not accept a custom weather file");
@@ -2859,6 +3106,12 @@ def vulcan_epc_run(input_path, output_dir, options):
2859
3106
  check({ input, output }) {
2860
3107
  return `vulcan_epc_run(${JSON.stringify(input)}, ${JSON.stringify(output)}, {'preprocess_only': True})`;
2861
3108
  },
3109
+ designHeatLoss(source, coreInput) {
3110
+ return `vulcan_epc_design_heat_loss(${JSON.stringify(source)}, ${JSON.stringify(coreInput)})`;
3111
+ },
3112
+ overheatingInput(coreInput) {
3113
+ return `vulcan_epc_overheating_input(${JSON.stringify(coreInput)})`;
3114
+ },
2862
3115
  outputs(files) {
2863
3116
  const metrics = Object.keys(files).filter((name) => name.endsWith("_metrics.json"));
2864
3117
  if (metrics.length !== 1) throw new Error(`An EPC run must write exactly one metrics file, found ${metrics.length}`);
@@ -2927,6 +3180,30 @@ async function checkPythonTargetJob(py, target2, input) {
2927
3180
  if (!check) throw new Error(`${target2.label} has no preprocess-only run`);
2928
3181
  await inJobFolder(py, input, (folder) => runEntry(py, check({ input: `${folder}/model.json`, output: `${folder}/model__results` }), input));
2929
3182
  }
3183
+ var NO_PYTHON_DESIGN_HEAT_LOSS = "This HEM target's engine has no static heat loss calculation, so it cannot size the heating.";
3184
+ async function withCoreInput(py, check, input, read) {
3185
+ return inJobFolder(py, input, async (folder) => {
3186
+ const output = `${folder}/model__results`;
3187
+ await runEntry(py, check({ input: `${folder}/model.json`, output }), input);
3188
+ return read(`${output}/preproc.json`, folder);
3189
+ });
3190
+ }
3191
+ async function designHeatLossPythonTargetJob(py, target2, input) {
3192
+ const { check, designHeatLoss } = pythonEntry(target2);
3193
+ if (!check || !designHeatLoss) return { status: "unavailable", reason: NO_PYTHON_DESIGN_HEAT_LOSS };
3194
+ return withCoreInput(py, check, input, async (coreInput, folder) => {
3195
+ const source = `${folder}/epc_design_heat_loss.py`;
3196
+ py.FS.writeFile(source, (await Promise.resolve().then(() => __toESM(require_epc_design_heat_loss(), 1))).default);
3197
+ const loss = await py.runPythonAsync(designHeatLoss(source, coreInput));
3198
+ if (typeof loss !== "string") return { status: "unavailable", reason: NO_PYTHON_DESIGN_HEAT_LOSS };
3199
+ return { status: "ready", model: JSON.parse(py.FS.readFile(coreInput, { encoding: "utf8" })), designHeatLoss: { ...JSON.parse(loss), weatherName: PINNED_WEATHER_NAME } };
3200
+ });
3201
+ }
3202
+ async function overheatingInputPythonTargetJob(py, target2, input) {
3203
+ const { check, overheatingInput } = pythonEntry(target2);
3204
+ if (!check || !overheatingInput) throw new Error(`${target2.label} has no core input for overheating`);
3205
+ return withCoreInput(py, check, input, async (coreInput) => JSON.parse(String(await py.runPythonAsync(overheatingInput(coreInput)))));
3206
+ }
2930
3207
 
2931
3208
  // ../hem-target-runtime/src/hem/targetAssets.ts
2932
3209
  var CACHE = "vulcan-hem-artifacts-v1";
@@ -3070,7 +3347,7 @@ var FS_REQUEST_TYPE = "file_system";
3070
3347
  var FS_RESPONSE_TYPE = "file_system_response";
3071
3348
 
3072
3349
  // ../hem-target-runtime/src/workers/batchWorkerFileSystemBridge.ts
3073
- var DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS = 3e4;
3350
+ var DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS = 5 * 6e4;
3074
3351
  var BatchWorkerFileSystemAcknowledgements = class {
3075
3352
  constructor(timeoutMs = DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS) {
3076
3353
  this.timeoutMs = timeoutMs;
@@ -3105,9 +3382,10 @@ var BatchWorkerFileSystemAcknowledgements = class {
3105
3382
  settled: false
3106
3383
  };
3107
3384
  entry.timer = setTimeout(() => {
3385
+ const limit = this.timeoutMs >= 6e4 ? `${Math.round(this.timeoutMs / 6e4)} minutes` : `${Math.round(this.timeoutMs / 1e3)} seconds`;
3108
3386
  this.settleFailure(
3109
3387
  request.messageId,
3110
- `Timed out after ${this.timeoutMs}ms waiting for ${request.operation} acknowledgement for '${request.path}'`
3388
+ `${request.operation === "write_file" ? "Saving" : "Deleting"} '${request.path}' did not finish within ${limit}. Check that the workspace folder is still available, then run again.`
3111
3389
  );
3112
3390
  }, this.timeoutMs);
3113
3391
  this.pending.set(request.messageId, entry);
@@ -3166,6 +3444,17 @@ var BatchWorkerFileSystemAcknowledgements = class {
3166
3444
  }
3167
3445
  };
3168
3446
 
3447
+ // ../hem-target-runtime/src/hem/workspaceName.ts
3448
+ var NON_PORTABLE_NAME_CHARACTERS = /[<>:"|?*]/;
3449
+ var hasControlCharacter = (name) => [...name].some((character) => character.charCodeAt(0) < 32);
3450
+ function isWorkspaceName(name) {
3451
+ return typeof name === "string" && name.trim() !== "" && !/[\\/]/.test(name) && !NON_PORTABLE_NAME_CHARACTERS.test(name) && !hasControlCharacter(name) && !name.startsWith(".") && !/[. ]$/.test(name);
3452
+ }
3453
+ function isRunOutputPath(path) {
3454
+ const segments = path.split("/");
3455
+ return segments[0] === "output" && segments.length > 1 && segments.slice(1).every(isWorkspaceName);
3456
+ }
3457
+
3169
3458
  // ../hem-target-runtime/src/hem/heatingProfile.ts
3170
3459
  function parseHeatingProfile(value) {
3171
3460
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Heating profile must be an object");
@@ -3196,9 +3485,9 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
3196
3485
  const { resultsKind } = targetWrapper(resolveHemTarget(manifest2.bundleId));
3197
3486
  const reservedNames = /* @__PURE__ */ new Set(["model.json", "source.csv", "weather.epw", "target-run.json"]);
3198
3487
  for (const job of jobs) {
3199
- if (!/^[a-zA-Z0-9_./ -]+$/.test(job.outputDirectory) || job.outputDirectory.split("/").some((segment) => segment === "..") || !job.outputDirectory.startsWith("output/")) throw new Error("Invalid run output path");
3488
+ if (!isRunOutputPath(job.outputDirectory)) throw new Error(`Invalid run output path: ${JSON.stringify(job.outputDirectory)}`);
3200
3489
  if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
3201
- if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
3490
+ if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || !isRunOutputPath(job.archiveDirectory))) throw new Error(`Invalid archive path: ${JSON.stringify(job.archiveDirectory)}`);
3202
3491
  if (job.heatingProfile) {
3203
3492
  parseHeatingProfile(job.heatingProfile);
3204
3493
  if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
@@ -3206,13 +3495,15 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
3206
3495
  }
3207
3496
  const scenario = (job) => `Scenario ${job.name}${job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : ""}`;
3208
3497
  const traceback = (error) => error instanceof TargetRunError ? { traceback: error.traceback } : {};
3498
+ const located = (error, job) => error instanceof TargetRunError && error.report && job.provenance ? targetRunError(error.report, job.input, job.provenance) : error;
3209
3499
  if (check) {
3210
3500
  const failures = [];
3211
3501
  for (const [index, job] of jobs.entries()) {
3212
3502
  progress(index, jobs.length, "Checking");
3213
3503
  try {
3214
3504
  await check(job.input);
3215
- } catch (error) {
3505
+ } catch (caught) {
3506
+ const error = located(caught, job);
3216
3507
  failures.push({ job, error, message: error instanceof Error ? error.message : String(error) });
3217
3508
  }
3218
3509
  }
@@ -3234,12 +3525,11 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
3234
3525
  const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, resultsKind, inputSha256, ...job.preparedBy ? { preparedBy: job.preparedBy } : {}, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
3235
3526
  try {
3236
3527
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
3237
- if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
3238
3528
  await write2(`${archive}/model.json`, job.input);
3239
3529
  if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
3240
3530
  if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
3241
3531
  progress(index, jobs.length);
3242
- const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
3532
+ const files = await execute(job.input, job.modes, job.weather, job.heatingProfile, job.detailedHeating);
3243
3533
  const names = Object.keys(files);
3244
3534
  if (!names.length) throw new Error("Calculation produced no result files");
3245
3535
  for (const [name, content] of Object.entries(files)) {
@@ -3247,11 +3537,13 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
3247
3537
  await write2(`${archive}/${name}`, content);
3248
3538
  }
3249
3539
  if (archive !== job.outputDirectory) {
3540
+ await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
3250
3541
  for (const [name, content] of Object.entries(files)) await write2(`${job.outputDirectory}/${name}`, content);
3251
- await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names, archive }));
3252
3542
  }
3253
3543
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
3254
- } catch (error) {
3544
+ if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names, archive }));
3545
+ } catch (caught) {
3546
+ const error = located(caught, job);
3255
3547
  const message = error instanceof Error ? error.message : String(error);
3256
3548
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, ...traceback(error) }));
3257
3549
  if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
@@ -3350,7 +3642,13 @@ self.onmessage = async ({ data }) => {
3350
3642
  try {
3351
3643
  if (data.type === "initialize") await initialize(data.manifest);
3352
3644
  else if (data.type === "run_prepared_batch") await run(data.jobId, data.targetBundleId, data.jobs);
3353
- else throw new Error(`Unsupported Python worker message ${data.type}`);
3645
+ else if (data.type === "design_heat_loss") {
3646
+ if (!runtime || !target) throw new Error("Python worker is not initialized");
3647
+ send({ type: "design_heat_loss_result", jobId: data.jobId, result: await designHeatLossPythonTargetJob(runtime, target, data.input) });
3648
+ } else if (data.type === "overheating_input") {
3649
+ if (!runtime || !target) throw new Error("Python worker is not initialized");
3650
+ send({ type: "overheating_input_result", jobId: data.jobId, result: await overheatingInputPythonTargetJob(runtime, target, data.input) });
3651
+ } else throw new Error(`Unsupported Python worker message ${data.type}`);
3354
3652
  } catch (error) {
3355
3653
  const text = error instanceof Error ? error.message : String(error);
3356
3654
  console.error(text);