@tiangong-lca/foundry 0.1.18 → 0.1.19

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 (84) hide show
  1. package/docs/package-distribution-contract.md +5 -5
  2. package/docs/public-runtime-contract.md +12 -0
  3. package/docs/runtime-context-contract.md +2 -0
  4. package/package-dist/assets/foundry-package-descriptor.json +268 -98
  5. package/package-dist/scripts/foundry-facade.js +3 -0
  6. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  7. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  8. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  9. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  10. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  11. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  12. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  13. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  14. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  15. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  16. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  17. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  18. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  19. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  20. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  21. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  22. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  23. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  24. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  25. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  26. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  27. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  28. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  29. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  30. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  31. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  32. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  33. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  34. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  35. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  36. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  37. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  38. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  39. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  40. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  41. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  42. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  43. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  44. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  45. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  46. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  47. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  48. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  49. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  50. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  51. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  52. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  53. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  54. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  55. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  56. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  57. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  58. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  59. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  60. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  61. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  62. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  63. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  64. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  65. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  66. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  67. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  68. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  69. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  70. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  71. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  72. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  73. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  74. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  75. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  76. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  77. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  78. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  79. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  80. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  81. package/package.json +2 -2
  82. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  83. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  84. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,224 @@
1
+ // Deterministic Process QA retained from TianGong LCA CLI 0.1.28 (MIT).
2
+ import { datasetRoot } from "./import-curation/internal/dataset-payload.js";
3
+ import { sha256Json } from "./identity-preflight-proof.js";
4
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
+ const token = (value) => typeof value === "string" || typeof value === "number" ? String(value).trim() : "";
6
+ const object = (value) => (isRecord(value) ? value : {});
7
+ const array = (value) => Array.isArray(value) ? value : value === undefined ? [] : [value];
8
+ function requireValue(condition, message) {
9
+ if (!condition)
10
+ throw new Error(message);
11
+ }
12
+ function numeric(value) {
13
+ if ((typeof value !== "number" && typeof value !== "string") || !token(value))
14
+ return null;
15
+ const number = Number(value);
16
+ return Number.isFinite(number) && number >= 0 ? number : null;
17
+ }
18
+ function recognizedUnit(value) {
19
+ // SI symbols retain case and token boundaries; descriptive names may be case folded.
20
+ const name = token(value).normalize("NFKC");
21
+ const lowerName = name.toLowerCase();
22
+ const massSymbols = {
23
+ kg: 1,
24
+ g: 1e-3,
25
+ mg: 1e-6,
26
+ ug: 1e-9,
27
+ μg: 1e-9,
28
+ Mg: 1e3,
29
+ t: 1e3,
30
+ };
31
+ const massNames = {
32
+ kilogram: 1,
33
+ kilograms: 1,
34
+ gram: 1e-3,
35
+ grams: 1e-3,
36
+ milligram: 1e-6,
37
+ milligrams: 1e-6,
38
+ microgram: 1e-9,
39
+ micrograms: 1e-9,
40
+ megagram: 1e3,
41
+ tonne: 1e3,
42
+ tonnes: 1e3,
43
+ };
44
+ const kilograms = Object.hasOwn(massSymbols, name)
45
+ ? massSymbols[name]
46
+ : Object.hasOwn(massNames, lowerName)
47
+ ? massNames[lowerName]
48
+ : null;
49
+ if (kilograms !== null)
50
+ return { name, dimension: "mass", kilograms };
51
+ const dimensions = [
52
+ [
53
+ "count",
54
+ ["1"],
55
+ ["item", "items", "item(s)", "piece", "pieces", "unit", "units", "unit(s)", "count"],
56
+ ],
57
+ ["energy", ["J", "kJ", "MJ", "GJ", "mJ", "Wh", "kWh", "MWh"], []],
58
+ ["length", ["m", "km", "cm", "mm"], []],
59
+ ["area", ["m2", "km2", "ha"], []],
60
+ ["volume", ["m3", "cm3", "l", "L"], ["litre", "liter"]],
61
+ [
62
+ "time",
63
+ ["s", "min", "h", "d", "a", "yr"],
64
+ ["second", "seconds", "hour", "hours", "year", "years"],
65
+ ],
66
+ ["area_time", ["m2*a"], []],
67
+ ];
68
+ const matched = dimensions.find(([, symbols, names]) => symbols.includes(name) || names.includes(lowerName));
69
+ return matched ? { name, dimension: matched[0], kilograms: null } : null;
70
+ }
71
+ function resolveExchange(evidence, exchange, index, uoms) {
72
+ const observation = {
73
+ exchange_index: index,
74
+ exchange_internal_id: token(exchange["@dataSetInternalID"]),
75
+ amount: numeric(exchange.meanAmount ?? exchange.resultingAmount),
76
+ unit: null,
77
+ mass_kg: null,
78
+ references: [],
79
+ error: null,
80
+ };
81
+ const select = (value, kind) => {
82
+ const ref = object(value), id = token(ref["@refObjectId"]), version = token(ref["@version"]);
83
+ requireValue(id && version, "An exact reference UUID and version are required.");
84
+ const type = {
85
+ flow: "flow data set",
86
+ flowproperty: "flow property data set",
87
+ unitgroup: "unit group data set",
88
+ }[kind];
89
+ requireValue(ref["@type"] === undefined || ref["@type"] === type, "Reference type contradicts its physical-unit chain.");
90
+ const row = evidence.rows.get(`${kind}/${id}/${version}`);
91
+ requireValue(row, "The exact reference payload is missing from selected evidence.");
92
+ observation.references.push({ kind, id, version, payload_sha256: row.sha256 });
93
+ return datasetRoot(row.payload, kind);
94
+ };
95
+ try {
96
+ requireValue(observation.amount !== null, "Exchange quantity must be finite and nonnegative.");
97
+ const flow = select(exchange.referenceToFlowDataSet, "flow");
98
+ const referenceProperty = token(object(object(flow.flowInformation).quantitativeReference).referenceToReferenceFlowProperty);
99
+ const properties = array(object(flow.flowProperties).flowProperty)
100
+ .map(object)
101
+ .filter((value) => token(value["@dataSetInternalID"]) === referenceProperty);
102
+ requireValue(referenceProperty && properties.length === 1, "Flow reference property must select one exact property occurrence.");
103
+ requireValue(numeric(properties[0].meanValue) === 1, "The reference flow property must have meanValue one.");
104
+ const property = select(properties[0].referenceToFlowPropertyDataSet, "flowproperty");
105
+ const group = select(object(object(property.flowPropertiesInformation).quantitativeReference)
106
+ .referenceToReferenceUnitGroup, "unitgroup");
107
+ const referenceUnit = token(object(object(group.unitGroupInformation).quantitativeReference).referenceToReferenceUnit);
108
+ const units = array(object(group.units).unit)
109
+ .map(object)
110
+ .filter((value) => token(value["@dataSetInternalID"]) === referenceUnit);
111
+ requireValue(referenceUnit && units.length === 1, "Unit Group reference unit must select one exact unit occurrence.");
112
+ requireValue(numeric(units[0].meanValue) === 1, "The reference unit must have meanValue one.");
113
+ const unit = recognizedUnit(units[0].name);
114
+ requireValue(unit, "The exact reference unit has an unknown or ambiguous physical dimension.");
115
+ for (const tag of uoms) {
116
+ const tagged = recognizedUnit(tag);
117
+ requireValue(tagged && tagged.dimension === unit.dimension && tagged.kilograms === unit.kilograms, "Exchange unit tag conflicts with exact reference-unit evidence.");
118
+ }
119
+ observation.unit = unit;
120
+ if (unit.kilograms !== null) {
121
+ observation.mass_kg = observation.amount * unit.kilograms;
122
+ requireValue(Number.isFinite(observation.mass_kg), "Normalized mass quantity overflows.");
123
+ }
124
+ }
125
+ catch (error) {
126
+ observation.mass_kg = null;
127
+ observation.error = String(error);
128
+ }
129
+ return observation;
130
+ }
131
+ export function assessProcessMassBalance(input) {
132
+ const categories = input.exchanges.map(input.classify);
133
+ const observations = input.exchanges.map((exchange, index) => resolveExchange(input.references, exchange, index, categories[index].uoms));
134
+ const findings = observations.flatMap((observation) => observation.error
135
+ ? [
136
+ {
137
+ code: "process_mass_unit_unresolved",
138
+ message: observation.error,
139
+ exchange_index: observation.exchange_index,
140
+ },
141
+ ]
142
+ : []);
143
+ const reference = observations.filter((observation) => input.referenceFlowId !== null && observation.exchange_internal_id === input.referenceFlowId);
144
+ const result = {
145
+ process_file: input.processFile,
146
+ process_payload_sha256: sha256Json(input.processPayload),
147
+ status: "unresolved",
148
+ unit: "kg",
149
+ reference_exchange_id: input.referenceFlowId,
150
+ exchanges: observations,
151
+ raw_input: null,
152
+ product: null,
153
+ byproduct: null,
154
+ waste: null,
155
+ other_output: null,
156
+ energy_excluded: null,
157
+ input_mass_kg: null,
158
+ output_mass_kg: null,
159
+ delta: null,
160
+ relative_deviation: null,
161
+ findings,
162
+ };
163
+ if (reference.length !== 1) {
164
+ findings.push({
165
+ code: "process_mass_reference_unresolved",
166
+ message: "Physical mass applicability requires one exact reference exchange.",
167
+ });
168
+ return result;
169
+ }
170
+ if (reference[0].unit && reference[0].unit.dimension !== "mass" && !reference[0].error) {
171
+ result.status = "not_applicable";
172
+ return result;
173
+ }
174
+ if (findings.length)
175
+ return result;
176
+ let raw = 0, product = 0, byproduct = 0, waste = 0, other = 0;
177
+ for (const [index, observation] of observations.entries()) {
178
+ if (observation.mass_kg === null)
179
+ continue;
180
+ const direction = token(input.exchanges[index].exchangeDirection).toLowerCase();
181
+ if (direction === "input")
182
+ raw += observation.mass_kg;
183
+ else if (direction === "output") {
184
+ const category = categories[index].classification;
185
+ if (category === "product_output")
186
+ product += observation.mass_kg;
187
+ else if (category === "byproduct_output")
188
+ byproduct += observation.mass_kg;
189
+ else if (category === "waste_output")
190
+ waste += observation.mass_kg;
191
+ else
192
+ other += observation.mass_kg;
193
+ }
194
+ else
195
+ findings.push({
196
+ code: "process_mass_direction_unresolved",
197
+ message: "Mass exchange direction must be Input or Output.",
198
+ exchange_index: index,
199
+ });
200
+ }
201
+ const output = product + byproduct + waste + other, delta = output - raw;
202
+ const deviation = raw > 0 ? Math.abs(delta) / raw : null;
203
+ if (![raw, output, delta].every(Number.isFinite) ||
204
+ (deviation !== null && !Number.isFinite(deviation)))
205
+ findings.push({
206
+ code: "process_mass_sum_overflow",
207
+ message: "Mass inventory aggregation must remain finite.",
208
+ });
209
+ if (findings.length)
210
+ return result;
211
+ Object.assign(result, {
212
+ status: "applicable",
213
+ raw_input: raw,
214
+ product,
215
+ byproduct,
216
+ waste,
217
+ other_output: other,
218
+ input_mass_kg: raw,
219
+ output_mass_kg: output,
220
+ delta,
221
+ relative_deviation: deviation,
222
+ });
223
+ return result;
224
+ }
@@ -0,0 +1,19 @@
1
+ import { type MassReferenceEvidence } from "./foundry-process-mass-balance.ts";
2
+ type JsonRecord = Record<string, unknown>;
3
+ type ProcessQaFinding = {
4
+ process_file: string;
5
+ severity: "info" | "warning" | "blocker";
6
+ code: string;
7
+ methodology_rule_id: string | null;
8
+ message: string;
9
+ source: "rule";
10
+ evidence?: JsonRecord;
11
+ };
12
+ export declare function foundryProcessQa(rows: readonly unknown[], references: MassReferenceEvidence): {
13
+ status: string;
14
+ policy_decision_owner: string;
15
+ qa_mode: string;
16
+ mass_balance: import("./foundry-process-mass-balance.ts").ProcessMassBalance[];
17
+ findings: ProcessQaFinding[];
18
+ };
19
+ export {};
@@ -0,0 +1,423 @@
1
+ // Deterministic Process QA retained from TianGong LCA CLI 0.1.28 (MIT).
2
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
3
+ import { FoundryContextError } from "./foundry-runtime-error.js";
4
+ import { assessProcessMassBalance, } from "./foundry-process-mass-balance.js";
5
+ const methodologyRules = {
6
+ process_missing_source_base_name: "tidas.process.name.base-name.align-reference-flow",
7
+ process_missing_functional_unit: "tidas.process.quantitative-reference.required",
8
+ process_missing_quantitative_reference: "tidas.process.quantitative-reference.required",
9
+ process_missing_exchange_amount: "tidas.process.exchange.amount.required",
10
+ process_material_balance_deviation: "tidas.process.exchange.amount.required",
11
+ process_missing_system_boundary: "tidas.process.evidence.field-bindings.required",
12
+ process_missing_time: "tidas.process.evidence.field-bindings.required",
13
+ process_missing_geography: "tidas.process.evidence.field-bindings.required",
14
+ process_missing_technology: "tidas.process.evidence.field-bindings.required",
15
+ process_missing_admin_metadata: "tidas.process.evidence.field-bindings.required",
16
+ process_exchange_unit_semantic_mismatch: "tidas.process.exchange.amount.required",
17
+ };
18
+ const KIND_RE = /\[tg_io_kind_tag=([^\]]+)\]/gu;
19
+ const UOM_RE = /\[tg_io_uom_tag=([^\]]+)\]/giu;
20
+ const ENERGY_WORDS = [
21
+ "electric",
22
+ "electricity",
23
+ "kwh",
24
+ "mj",
25
+ "heat",
26
+ "steam",
27
+ "fuel",
28
+ "diesel",
29
+ "gas",
30
+ "power",
31
+ "电",
32
+ "能",
33
+ ];
34
+ const RAW_WORDS = [
35
+ "raw material",
36
+ "feedstock",
37
+ "fertilizer",
38
+ "water",
39
+ "seed",
40
+ "pesticide",
41
+ "原材料",
42
+ "投入",
43
+ "肥料",
44
+ "种子",
45
+ "农药",
46
+ "用水",
47
+ ];
48
+ const BYP_WORDS = ["by-product", "co-product", "副产品", "联产"];
49
+ const WASTE_WORDS = ["waste", "废", "residue", "sludge"];
50
+ function isRecord(value) {
51
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
52
+ }
53
+ function textFromValue(value) {
54
+ if (Array.isArray(value)) {
55
+ return value
56
+ .filter(isRecord)
57
+ .map((item) => String(item["#text"] ?? ""))
58
+ .join(" ");
59
+ }
60
+ if (isRecord(value)) {
61
+ return String(value["#text"] ?? "");
62
+ }
63
+ return String(value ?? "");
64
+ }
65
+ function deepGet(value, pathParts) {
66
+ let current = value;
67
+ for (const key of pathParts) {
68
+ if (!isRecord(current)) {
69
+ return undefined;
70
+ }
71
+ current = current[key];
72
+ if (current === undefined || current === null) {
73
+ return undefined;
74
+ }
75
+ }
76
+ return current;
77
+ }
78
+ function hasNonEmpty(value) {
79
+ if (value === null || value === undefined) {
80
+ return false;
81
+ }
82
+ if (typeof value === "string") {
83
+ return value.trim().length > 0;
84
+ }
85
+ if (Array.isArray(value)) {
86
+ return value.some((item) => hasNonEmpty(item));
87
+ }
88
+ if (isRecord(value)) {
89
+ if ("#text" in value) {
90
+ return hasNonEmpty(value["#text"]);
91
+ }
92
+ return Object.values(value).some((item) => hasNonEmpty(item));
93
+ }
94
+ return true;
95
+ }
96
+ function extractBaseNames(processPayload) {
97
+ const base = deepGet(processPayload, [
98
+ "processDataSet",
99
+ "processInformation",
100
+ "dataSetInformation",
101
+ "name",
102
+ "baseName",
103
+ ]);
104
+ const items = Array.isArray(base) ? base : base ? [base] : [];
105
+ const values = [];
106
+ items.forEach((item) => {
107
+ if (!isRecord(item)) {
108
+ return;
109
+ }
110
+ const text = String(item["#text"] ?? "").trim();
111
+ if (!text) {
112
+ return;
113
+ }
114
+ values.push(text);
115
+ });
116
+ return [values.length > 0, values];
117
+ }
118
+ function sourceTracePayload(exchange) {
119
+ const payload = deepGet(exchange, ["common:other", "tidasimport:sourceTrace", "payload"]);
120
+ if (!isRecord(payload)) {
121
+ return null;
122
+ }
123
+ return isRecord(payload.sourceTrace) ? payload.sourceTrace : payload;
124
+ }
125
+ function sourceClassification(exchange) {
126
+ const payload = sourceTracePayload(exchange);
127
+ return payload && isRecord(payload.sourceClassification) ? payload.sourceClassification : {};
128
+ }
129
+ function sourceGroup(exchange, groupName) {
130
+ const value = sourceClassification(exchange)[groupName];
131
+ const text = String(value ?? "").trim();
132
+ return text || null;
133
+ }
134
+ function classifyExchange(exchange, referenceFlowId = null) {
135
+ const comments = `${textFromValue(exchange.commonComment)} ${textFromValue(exchange.generalComment)}`;
136
+ const flowDescription = textFromValue(isRecord(exchange.referenceToFlowDataSet)
137
+ ? exchange.referenceToFlowDataSet["common:shortDescription"]
138
+ : undefined);
139
+ const rawBlob = `${comments} ${flowDescription}`.trim();
140
+ const blob = rawBlob.toLowerCase();
141
+ const kinds = Array.from(blob.matchAll(KIND_RE), (match) => match[1].toLowerCase());
142
+ const kindSet = new Set(kinds);
143
+ const uoms = Array.from(rawBlob.matchAll(UOM_RE), (match) => match[1]);
144
+ const direction = String(exchange.exchangeDirection ?? "").toLowerCase();
145
+ const inputGroup = sourceGroup(exchange, "inputGroup");
146
+ const outputGroup = sourceGroup(exchange, "outputGroup");
147
+ const internalId = String(exchange["@dataSetInternalID"] ?? "").trim();
148
+ const isReferenceFlow = Boolean(referenceFlowId && internalId === referenceFlowId);
149
+ const meta = {
150
+ kinds,
151
+ uoms,
152
+ blob,
153
+ source_input_group: inputGroup,
154
+ source_output_group: outputGroup,
155
+ reference_flow: isReferenceFlow,
156
+ };
157
+ const isEnergy = ENERGY_WORDS.some((word) => blob.includes(word)) ||
158
+ uoms.some((uom) => uom === "kwh" || uom === "mj" || uom === "gj");
159
+ if (direction === "input") {
160
+ if (kindSet.has("energy") || isEnergy) {
161
+ return { classification: "energy_input", ...meta };
162
+ }
163
+ if (kindSet.has("waste")) {
164
+ return { classification: "other_input", ...meta };
165
+ }
166
+ if (inputGroup === "4" || kindSet.has("raw_material") || kindSet.has("resource")) {
167
+ return { classification: "raw_material_input", ...meta };
168
+ }
169
+ if (kindSet.has("product") || RAW_WORDS.some((word) => blob.includes(word))) {
170
+ return { classification: "raw_material_input", ...meta };
171
+ }
172
+ return { classification: "other_input", ...meta };
173
+ }
174
+ if (direction === "output") {
175
+ if (isReferenceFlow || outputGroup === "0") {
176
+ return { classification: "product_output", ...meta };
177
+ }
178
+ if (kindSet.has("waste") ||
179
+ outputGroup === "4" ||
180
+ outputGroup === "5" ||
181
+ WASTE_WORDS.some((word) => blob.includes(word))) {
182
+ return { classification: "waste_output", ...meta };
183
+ }
184
+ if (BYP_WORDS.some((word) => blob.includes(word))) {
185
+ return { classification: "byproduct_output", ...meta };
186
+ }
187
+ if (kindSet.has("product")) {
188
+ return { classification: "product_output", ...meta };
189
+ }
190
+ return { classification: "other_output", ...meta };
191
+ }
192
+ return { classification: "other", ...meta };
193
+ }
194
+ function unitIssueCheck(exchange, uoms, blob) {
195
+ const flowUuid = isRecord(exchange.referenceToFlowDataSet)
196
+ ? String(exchange.referenceToFlowDataSet["@refObjectId"] ?? "")
197
+ : "";
198
+ if (!flowUuid) {
199
+ return [];
200
+ }
201
+ const currentUnit = (uoms[0] ?? "").toLowerCase();
202
+ if (["electric", "electricity", "交流电", "电力"].some((word) => blob.includes(word)) &&
203
+ currentUnit &&
204
+ !["kwh", "mj", "gj"].includes(currentUnit)) {
205
+ return [
206
+ {
207
+ flow_uuid: flowUuid,
208
+ current_unit: currentUnit,
209
+ suggested_unit: "kWh",
210
+ basis: "flow 描述为电力/电能,但 uom 标签非能量单位",
211
+ confidence: "高",
212
+ },
213
+ ];
214
+ }
215
+ if (["water", "用水", "工艺用水"].some((word) => blob.includes(word)) &&
216
+ currentUnit &&
217
+ ["kwh", "mj", "gj"].includes(currentUnit)) {
218
+ return [
219
+ {
220
+ flow_uuid: flowUuid,
221
+ current_unit: currentUnit,
222
+ suggested_unit: "m3 或 kg",
223
+ basis: "flow 描述为水,但 uom 标签为能量单位",
224
+ confidence: "高",
225
+ },
226
+ ];
227
+ }
228
+ if (["co2", "carbon dioxide", "二氧化碳"].some((word) => blob.includes(word)) &&
229
+ currentUnit &&
230
+ ["kwh", "mj", "gj"].includes(currentUnit)) {
231
+ return [
232
+ {
233
+ flow_uuid: flowUuid,
234
+ current_unit: currentUnit,
235
+ suggested_unit: "kg",
236
+ basis: "排放流通常质量单位计,当前为能量单位",
237
+ confidence: "中",
238
+ },
239
+ ];
240
+ }
241
+ return [];
242
+ }
243
+ function hasNumericAmount(exchange) {
244
+ for (const key of ["meanAmount", "resultingAmount"]) {
245
+ const value = exchange[key];
246
+ if (typeof value === "number" && Number.isFinite(value)) {
247
+ return true;
248
+ }
249
+ if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) {
250
+ return true;
251
+ }
252
+ }
253
+ return false;
254
+ }
255
+ function createProcessQaFinding(options) {
256
+ const methodologyRuleId = methodologyRules[options.code] ?? null;
257
+ return {
258
+ process_file: options.processFile,
259
+ severity: options.severity,
260
+ code: options.code,
261
+ methodology_rule_id: methodologyRuleId,
262
+ message: options.message,
263
+ source: "rule",
264
+ ...(options.evidence ? { evidence: options.evidence } : {}),
265
+ };
266
+ }
267
+ function reviewFindingsForBase(processFile, base) {
268
+ const findings = [];
269
+ if (!base.source_name_ok) {
270
+ findings.push(createProcessQaFinding({
271
+ processFile,
272
+ severity: "warning",
273
+ code: "process_missing_source_base_name",
274
+ message: "Process baseName should include a usable source-language entry before Foundry authoring is complete.",
275
+ evidence: { base_names: base.base_names },
276
+ }));
277
+ }
278
+ if (!base.functional_unit_ok) {
279
+ findings.push(createProcessQaFinding({
280
+ processFile,
281
+ severity: "warning",
282
+ code: "process_missing_functional_unit",
283
+ message: "Process quantitative reference functionalUnitOrOther is missing and should be curated by Foundry.",
284
+ }));
285
+ }
286
+ for (const [ok, code, message] of [
287
+ [
288
+ base.system_boundary_ok,
289
+ "process_missing_system_boundary",
290
+ "Process system boundary or typeOfDataSet context is missing.",
291
+ ],
292
+ [base.time_ok, "process_missing_time", "Process time coverage is missing."],
293
+ [base.geo_ok, "process_missing_geography", "Process geography is missing."],
294
+ [base.tech_ok, "process_missing_technology", "Process technology description is missing."],
295
+ [
296
+ base.admin_ok,
297
+ "process_missing_admin_metadata",
298
+ "Process administrative metadata is missing.",
299
+ ],
300
+ ]) {
301
+ if (!ok) {
302
+ findings.push(createProcessQaFinding({
303
+ processFile,
304
+ severity: "warning",
305
+ code,
306
+ message,
307
+ }));
308
+ }
309
+ }
310
+ return findings;
311
+ }
312
+ function baseInfoCheck(processPayload) {
313
+ const [sourceNameOk, values] = extractBaseNames(processPayload);
314
+ const functionalUnit = deepGet(processPayload, [
315
+ "processDataSet",
316
+ "processInformation",
317
+ "quantitativeReference",
318
+ "functionalUnitOrOther",
319
+ ]);
320
+ const mixAndLocation = deepGet(processPayload, [
321
+ "processDataSet",
322
+ "processInformation",
323
+ "geography",
324
+ "mixAndLocationTypes",
325
+ ]);
326
+ const route = deepGet(processPayload, [
327
+ "processDataSet",
328
+ "modellingAndValidation",
329
+ "LCIMethodAndAllocation",
330
+ "typeOfDataSet",
331
+ ]);
332
+ const time = deepGet(processPayload, ["processDataSet", "processInformation", "time"]);
333
+ const geography = deepGet(processPayload, ["processDataSet", "processInformation", "geography"]);
334
+ const technology = deepGet(processPayload, ["processDataSet", "modellingAndValidation"]);
335
+ const administrativeInformation = deepGet(processPayload, [
336
+ "processDataSet",
337
+ "administrativeInformation",
338
+ ]);
339
+ const functionalUnitOk = hasNonEmpty(functionalUnit);
340
+ const systemBoundaryOk = hasNonEmpty(mixAndLocation) || hasNonEmpty(route);
341
+ const timeOk = hasNonEmpty(time);
342
+ const geographyOk = hasNonEmpty(geography);
343
+ const technologyOk = hasNonEmpty(technology);
344
+ const administrativeOk = hasNonEmpty(administrativeInformation);
345
+ const completenessScore = [
346
+ sourceNameOk,
347
+ functionalUnitOk,
348
+ systemBoundaryOk,
349
+ timeOk,
350
+ geographyOk,
351
+ technologyOk,
352
+ administrativeOk,
353
+ ].filter(Boolean).length;
354
+ return {
355
+ source_name_ok: sourceNameOk,
356
+ functional_unit_ok: functionalUnitOk,
357
+ system_boundary_ok: systemBoundaryOk,
358
+ time_ok: timeOk,
359
+ geo_ok: geographyOk,
360
+ tech_ok: technologyOk,
361
+ admin_ok: administrativeOk,
362
+ completeness_score: completenessScore,
363
+ base_names: values,
364
+ };
365
+ }
366
+ export function foundryProcessQa(rows, references) {
367
+ const findings = [];
368
+ const massBalance = rows.map((row, index) => {
369
+ const { id, version, payload } = datasetIdentity(row, index, "process");
370
+ if (!isRecord(payload))
371
+ throw new FoundryContextError("workflow_qa_failed", "Process QA requires a complete dataset.");
372
+ const rawExchanges = deepGet(payload, ["processDataSet", "exchanges", "exchange"]);
373
+ const exchanges = (Array.isArray(rawExchanges) ? rawExchanges : [rawExchanges]).filter(isRecord);
374
+ const referenceFlowId = String(deepGet(payload, [
375
+ "processDataSet",
376
+ "processInformation",
377
+ "quantitativeReference",
378
+ "referenceToReferenceFlow",
379
+ ]) ?? "").trim() || null;
380
+ const processFile = `${id}__${version}.json`;
381
+ const base = baseInfoCheck(payload);
382
+ findings.push(...reviewFindingsForBase(processFile, base));
383
+ const addFinding = (code, message, evidence) => findings.push(createProcessQaFinding({ processFile, severity: "warning", code, message, evidence }));
384
+ for (const exchange of exchanges) {
385
+ const classified = classifyExchange(exchange, referenceFlowId);
386
+ if (!hasNumericAmount(exchange))
387
+ addFinding("process_missing_exchange_amount", "Process exchange is missing both numeric meanAmount and resultingAmount and should be curated by Foundry.", {
388
+ exchange_internal_id: String(exchange["@dataSetInternalID"] ?? ""),
389
+ direction: String(exchange.exchangeDirection ?? ""),
390
+ });
391
+ for (const issue of unitIssueCheck(exchange, classified.uoms, classified.blob))
392
+ addFinding("process_exchange_unit_semantic_mismatch", "Exchange unit tag conflicts with flow description semantics.", issue);
393
+ }
394
+ const mass = assessProcessMassBalance({
395
+ processFile,
396
+ processPayload: payload,
397
+ exchanges,
398
+ referenceFlowId,
399
+ references,
400
+ classify: (exchange) => classifyExchange(exchange, referenceFlowId),
401
+ });
402
+ for (const finding of mass.findings)
403
+ addFinding(finding.code, finding.message, { ...finding, unit: "kg" });
404
+ if ((mass.relative_deviation !== null && mass.relative_deviation > 0.05) ||
405
+ (mass.input_mass_kg === 0 && (mass.output_mass_kg ?? 0) > 0))
406
+ addFinding("process_material_balance_deviation", "Comparable mass inputs and outputs require review: positive output has zero input, or the relative kg deviation exceeds the QA threshold.", {
407
+ raw_input: mass.raw_input,
408
+ product: mass.product,
409
+ byproduct: mass.byproduct,
410
+ waste: mass.waste,
411
+ relative_deviation: mass.relative_deviation,
412
+ policy_decision_owner: "foundry",
413
+ });
414
+ return mass;
415
+ });
416
+ return {
417
+ status: "completed_local_process_qa",
418
+ policy_decision_owner: "foundry",
419
+ qa_mode: "deterministic_qa_report",
420
+ mass_balance: massBalance,
421
+ findings,
422
+ };
423
+ }