@tiangong-lca/foundry 0.1.19 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/docs/architecture.md +5 -3
- package/docs/foundry-task-contracts.md +2 -0
- package/docs/package-distribution-contract.md +5 -3
- package/docs/public-runtime-contract.md +41 -3
- package/docs/runtime-context-contract.md +5 -3
- package/docs/task-authorization-contract.md +2 -0
- package/package-dist/assets/foundry-package-descriptor.json +142 -74
- package/package-dist/scripts/foundry-facade.d.ts +6 -0
- package/package-dist/scripts/foundry-facade.js +35 -0
- package/package-dist/scripts/foundry-runtime.d.ts +2 -1
- package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
- package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
- package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
- package/package-dist/scripts/lib/final-delivery-review.js +108 -0
- package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
- package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +3 -0
- package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +90 -1
- package/package-dist/scripts/lib/foundry-edge-session.d.ts +18 -1
- package/package-dist/scripts/lib/foundry-edge-session.js +137 -3
- package/package-dist/scripts/lib/foundry-edge-support.d.ts +1 -1
- package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
- package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
- package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
- package/package-dist/scripts/lib/foundry-owner-readback.d.ts +3 -2
- package/package-dist/scripts/lib/foundry-owner-readback.js +21 -2
- package/package-dist/scripts/lib/foundry-package-contract.d.ts +3 -3
- package/package-dist/scripts/lib/foundry-package-contract.js +7 -1
- package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
- package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
- package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
- package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
- package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
- package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
- package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
- package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
- package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
- package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
- package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
- package/package-dist/scripts/lib/foundry-workflow-execution.js +3 -0
- package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
- package/package-dist/scripts/lib/foundry-workflow-repair.js +151 -0
- package/package-dist/scripts/public-api.d.ts +6 -0
- package/package-dist/scripts/runtime-entry.js +15 -6
- package/package.json +4 -1
- package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
- package/specs/schemas/foundry-operation-result.schema.json +1 -0
- package/specs/schemas/foundry-package-descriptor.schema.json +4 -1
- package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
- package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
- package/specs/schemas/foundry-task-start.schema.json +10 -2
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { createFoundryEdgeActor } from "./foundry-edge-session.js";
|
|
5
|
+
import { FoundryContextError } from "./foundry-runtime-context.js";
|
|
6
|
+
import { sha256Json } from "./identity-preflight-proof.js";
|
|
7
|
+
import { workflowObject } from "./foundry-workflow-state.js";
|
|
8
|
+
const tables = {
|
|
9
|
+
process: "processes",
|
|
10
|
+
flow: "flows",
|
|
11
|
+
flowproperty: "flowproperties",
|
|
12
|
+
unitgroup: "unitgroups",
|
|
13
|
+
source: "sources",
|
|
14
|
+
contact: "contacts",
|
|
15
|
+
lciamethod: "lciamethods",
|
|
16
|
+
model: "lifecyclemodels",
|
|
17
|
+
};
|
|
18
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
19
|
+
const version = /^[0-9]{2}\.[0-9]{2}\.[0-9]{3}$/u;
|
|
20
|
+
const maximumRows = 100_000;
|
|
21
|
+
const maximumBytes = 64 * 1024 * 1024;
|
|
22
|
+
const maximumTransferBytes = 1024 * 1024 * 1024;
|
|
23
|
+
function reject(message) {
|
|
24
|
+
throw new FoundryContextError("repair_census_unproven", message);
|
|
25
|
+
}
|
|
26
|
+
function array(value) {
|
|
27
|
+
if (!Array.isArray(value) || value.length > maximumRows)
|
|
28
|
+
reject("Repair census input needs a bounded full inventory.");
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
function identity(id, revision) {
|
|
32
|
+
if (typeof id !== "string" ||
|
|
33
|
+
!uuid.test(id) ||
|
|
34
|
+
typeof revision !== "string" ||
|
|
35
|
+
!version.test(revision))
|
|
36
|
+
reject("Repair census identities require explicit UUIDs and exact versions.");
|
|
37
|
+
return `${id.toLowerCase()}@${revision}`;
|
|
38
|
+
}
|
|
39
|
+
function visible(row, actor) {
|
|
40
|
+
return row.state_code === 100 || (row.state_code === 0 && row.user_id === actor);
|
|
41
|
+
}
|
|
42
|
+
function records(page, query) {
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = JSON.parse(page.raw);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
reject("Repair census returned malformed JSON.");
|
|
49
|
+
}
|
|
50
|
+
const rows = array(parsed).map(workflowObject);
|
|
51
|
+
const range = page.contentRange?.match(/^(?:(\d+)-(\d+)|\*)\/(\d+)$/u);
|
|
52
|
+
if (![200, 206].includes(page.status) || !range || rows.length > query.limit)
|
|
53
|
+
reject("Repair census requires successful bounded pages with an exact Content-Range total.");
|
|
54
|
+
const total = Number(range[3]);
|
|
55
|
+
if (!Number.isSafeInteger(total) || total > maximumRows || total < 0)
|
|
56
|
+
reject("Repair census exceeds the supported 100000-row scope or has an invalid exact count.");
|
|
57
|
+
if (rows.length
|
|
58
|
+
? Number(range[1]) !== query.offset ||
|
|
59
|
+
Number(range[2]) !== query.offset + rows.length - 1 ||
|
|
60
|
+
query.offset + rows.length > total
|
|
61
|
+
: total !== 0 || query.offset !== 0 || range[1] !== undefined)
|
|
62
|
+
reject("Repair census page range, offset and row count do not agree.");
|
|
63
|
+
return { rows, total };
|
|
64
|
+
}
|
|
65
|
+
function reference(value) {
|
|
66
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
67
|
+
reject("A directory reference is malformed; family separation is uncertain.");
|
|
68
|
+
const item = value;
|
|
69
|
+
if (typeof item["@refObjectId"] !== "string" || !uuid.test(item["@refObjectId"]))
|
|
70
|
+
reject("A directory reference has no provable UUID; family separation is uncertain.");
|
|
71
|
+
const revision = item["@version"];
|
|
72
|
+
return {
|
|
73
|
+
id: item["@refObjectId"].toLowerCase(),
|
|
74
|
+
version: revision === undefined || revision === null || revision === "" ? null : revision,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function nestedReferences(value) {
|
|
78
|
+
const found = [];
|
|
79
|
+
const visit = (current, depth) => {
|
|
80
|
+
if (depth > 64 || found.length > maximumRows)
|
|
81
|
+
reject("Directory reference nesting exceeds its bound.");
|
|
82
|
+
if (Array.isArray(current)) {
|
|
83
|
+
for (const child of current)
|
|
84
|
+
visit(child, depth + 1);
|
|
85
|
+
}
|
|
86
|
+
else if (current && typeof current === "object") {
|
|
87
|
+
const item = current;
|
|
88
|
+
if (Object.hasOwn(item, "@refObjectId"))
|
|
89
|
+
found.push(reference(item));
|
|
90
|
+
for (const child of Object.values(item))
|
|
91
|
+
visit(child, depth + 1);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
visit(value, 0);
|
|
95
|
+
if (!found.length)
|
|
96
|
+
reject("A directory reference has no provable UUID; family separation is uncertain.");
|
|
97
|
+
return found;
|
|
98
|
+
}
|
|
99
|
+
function occurrences(value) {
|
|
100
|
+
if (value === undefined || value === null)
|
|
101
|
+
return [];
|
|
102
|
+
const values = Array.isArray(value) ? value : [value];
|
|
103
|
+
if (values.length > maximumRows)
|
|
104
|
+
reject("Directory reference occurrence limit exceeded.");
|
|
105
|
+
return values.map(workflowObject);
|
|
106
|
+
}
|
|
107
|
+
function field(row, alias, path) {
|
|
108
|
+
if (Object.hasOwn(row, alias))
|
|
109
|
+
return row[alias];
|
|
110
|
+
if (!Object.hasOwn(row, "json"))
|
|
111
|
+
reject("Directory response omitted a required projection.");
|
|
112
|
+
let value = row.json;
|
|
113
|
+
for (const key of path) {
|
|
114
|
+
if (value === undefined || value === null)
|
|
115
|
+
return null;
|
|
116
|
+
if (typeof value !== "object" || Array.isArray(value))
|
|
117
|
+
reject("Directory JSON path is malformed.");
|
|
118
|
+
value = value[key];
|
|
119
|
+
}
|
|
120
|
+
return value ?? null;
|
|
121
|
+
}
|
|
122
|
+
function directoryRow(type, row) {
|
|
123
|
+
for (const key of ["id", "version", "user_id", "state_code"])
|
|
124
|
+
if (!Object.hasOwn(row, key))
|
|
125
|
+
reject("Directory response omitted identity or eligibility.");
|
|
126
|
+
identity(row.id, row.version);
|
|
127
|
+
const common = {
|
|
128
|
+
id: String(row.id).toLowerCase(),
|
|
129
|
+
version: row.version,
|
|
130
|
+
user_id: row.user_id,
|
|
131
|
+
state_code: row.state_code,
|
|
132
|
+
};
|
|
133
|
+
if (type === "process") {
|
|
134
|
+
for (const key of ["model_id", "model_version", "team_id", "review_id"])
|
|
135
|
+
if (!Object.hasOwn(row, key))
|
|
136
|
+
reject("Directory Process lineage metadata is incomplete.");
|
|
137
|
+
const exchanges = field(row, "exchanges", ["processDataSet", "exchanges", "exchange"]);
|
|
138
|
+
const references = occurrences(exchanges).flatMap((exchange) => nestedReferences(exchange.referenceToFlowDataSet));
|
|
139
|
+
return {
|
|
140
|
+
...common,
|
|
141
|
+
model_id: row.model_id,
|
|
142
|
+
model_version: row.model_version,
|
|
143
|
+
team_id: row.team_id,
|
|
144
|
+
review_id: row.review_id,
|
|
145
|
+
flow_references: references,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
if (type === "model") {
|
|
149
|
+
const result = field(row, "result_process", [
|
|
150
|
+
"lifeCycleModelDataSet",
|
|
151
|
+
"lifeCycleModelInformation",
|
|
152
|
+
"dataSetInformation",
|
|
153
|
+
"referenceToResultingProcess",
|
|
154
|
+
]);
|
|
155
|
+
const components = field(row, "process_instances", [
|
|
156
|
+
"lifeCycleModelDataSet",
|
|
157
|
+
"lifeCycleModelInformation",
|
|
158
|
+
"technology",
|
|
159
|
+
"processes",
|
|
160
|
+
"processInstance",
|
|
161
|
+
]);
|
|
162
|
+
return {
|
|
163
|
+
...common,
|
|
164
|
+
process_references: [
|
|
165
|
+
...occurrences(result).flatMap(nestedReferences),
|
|
166
|
+
...occurrences(components).flatMap((item) => nestedReferences(item.referenceToProcess)),
|
|
167
|
+
],
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const declared = field(row, "declared_type", [
|
|
171
|
+
"flowDataSet",
|
|
172
|
+
"modellingAndValidation",
|
|
173
|
+
"LCIMethod",
|
|
174
|
+
"typeOfDataSet",
|
|
175
|
+
]);
|
|
176
|
+
return { ...common, declared_type: typeof declared === "string" ? declared.trim() : null };
|
|
177
|
+
}
|
|
178
|
+
function digest(rows) {
|
|
179
|
+
const hash = createHash("sha256");
|
|
180
|
+
for (const key of [...rows.keys()].sort())
|
|
181
|
+
hash.update(`${key}\0${sha256Json(rows.get(key))}\n`);
|
|
182
|
+
return hash.digest("hex");
|
|
183
|
+
}
|
|
184
|
+
function directoryDigest(directory) {
|
|
185
|
+
return sha256Json({
|
|
186
|
+
process: digest(directory.process),
|
|
187
|
+
model: digest(directory.model),
|
|
188
|
+
flow: digest(directory.flow),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
function flowHeads(flows) {
|
|
192
|
+
const heads = new Map();
|
|
193
|
+
for (const row of flows.values()) {
|
|
194
|
+
const id = String(row.id), revision = String(row.version);
|
|
195
|
+
if (!heads.has(id) || heads.get(id) < revision)
|
|
196
|
+
heads.set(id, revision);
|
|
197
|
+
}
|
|
198
|
+
return heads;
|
|
199
|
+
}
|
|
200
|
+
/** A conservative identity component, without provider signs, weights or numerical selection. */
|
|
201
|
+
function boundedFamily(directory, expected, workerInput) {
|
|
202
|
+
const adjacency = new Map();
|
|
203
|
+
const connect = (left, right) => {
|
|
204
|
+
if (!adjacency.has(left))
|
|
205
|
+
adjacency.set(left, new Set());
|
|
206
|
+
if (!adjacency.has(right))
|
|
207
|
+
adjacency.set(right, new Set());
|
|
208
|
+
adjacency.get(left).add(right);
|
|
209
|
+
adjacency.get(right).add(left);
|
|
210
|
+
};
|
|
211
|
+
const heads = flowHeads(directory.flow);
|
|
212
|
+
const connectProcess = (row) => {
|
|
213
|
+
const node = `process:${String(row.id).toLowerCase()}`;
|
|
214
|
+
if (!adjacency.has(node))
|
|
215
|
+
adjacency.set(node, new Set());
|
|
216
|
+
for (const value of array(row.flow_references)) {
|
|
217
|
+
const ref = workflowObject(value);
|
|
218
|
+
const revision = ref.version ?? heads.get(String(ref.id));
|
|
219
|
+
const flow = typeof revision === "string" && version.test(revision)
|
|
220
|
+
? directory.flow.get(identity(ref.id, revision))
|
|
221
|
+
: undefined;
|
|
222
|
+
// Only an explicitly declared, exact visible Elementary revision is safely excluded.
|
|
223
|
+
if (flow?.declared_type === "Elementary flow")
|
|
224
|
+
continue;
|
|
225
|
+
connect(node, `flow:${ref.id}`);
|
|
226
|
+
}
|
|
227
|
+
if (row.model_id !== null && row.model_id !== undefined) {
|
|
228
|
+
if (typeof row.model_id !== "string" || !uuid.test(row.model_id))
|
|
229
|
+
reject("Directory Process model identity is uncertain.");
|
|
230
|
+
connect(node, `model:${row.model_id.toLowerCase()}`);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
for (const row of directory.process.values())
|
|
234
|
+
connectProcess(row);
|
|
235
|
+
for (const row of directory.model.values()) {
|
|
236
|
+
const node = `model:${row.id}`;
|
|
237
|
+
if (!adjacency.has(node))
|
|
238
|
+
adjacency.set(node, new Set());
|
|
239
|
+
for (const value of array(row.process_references))
|
|
240
|
+
connect(node, `process:${workflowObject(value).id}`);
|
|
241
|
+
}
|
|
242
|
+
// The approved after-body may introduce references absent from the live before directory.
|
|
243
|
+
for (const value of array(workerInput.overlays ?? [])) {
|
|
244
|
+
const overlay = workflowObject(value), selected = workflowObject(overlay.identity);
|
|
245
|
+
if (selected.dataset_type === "process") {
|
|
246
|
+
const source = expected.get("process")?.get(identity(selected.id, selected.version));
|
|
247
|
+
if (!source)
|
|
248
|
+
reject("Candidate Process is absent from the frozen family.");
|
|
249
|
+
const metadata = directory.process.get(identity(selected.id, selected.version));
|
|
250
|
+
if (!metadata)
|
|
251
|
+
reject("Candidate Process is absent from the authenticated directory.");
|
|
252
|
+
connectProcess(directoryRow("process", {
|
|
253
|
+
...metadata,
|
|
254
|
+
id: selected.id,
|
|
255
|
+
version: selected.version,
|
|
256
|
+
json: overlay.document,
|
|
257
|
+
}));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const pending = [
|
|
261
|
+
...[...(expected.get("process")?.values() ?? [])].map((item) => `process:${workflowObject(item.identity).id}`),
|
|
262
|
+
...[...(expected.get("model")?.values() ?? [])].map((item) => `model:${item.id}`),
|
|
263
|
+
...array(workerInput.overlays ?? []).flatMap((value) => {
|
|
264
|
+
const selected = workflowObject(workflowObject(value).identity);
|
|
265
|
+
return selected.dataset_type === "flow" ? [`flow:${selected.id}`] : [];
|
|
266
|
+
}),
|
|
267
|
+
].map((node) => node.toLowerCase());
|
|
268
|
+
const nodes = new Set();
|
|
269
|
+
while (pending.length) {
|
|
270
|
+
const node = pending.pop();
|
|
271
|
+
if (nodes.has(node))
|
|
272
|
+
continue;
|
|
273
|
+
nodes.add(node);
|
|
274
|
+
for (const neighbor of adjacency.get(node) ?? [])
|
|
275
|
+
if (!nodes.has(neighbor))
|
|
276
|
+
pending.push(neighbor);
|
|
277
|
+
}
|
|
278
|
+
const select = (type) => {
|
|
279
|
+
const rows = new Map([...directory[type]].filter(([, row]) => nodes.has(`${type}:${row.id}`)));
|
|
280
|
+
const selected = expected.get(type) ?? new Map();
|
|
281
|
+
if (rows.size !== selected.size || [...rows.keys()].some((key) => !selected.has(key)))
|
|
282
|
+
reject(`Repair frozen ${type} inventory omits a connected family member or visible historical revision.`);
|
|
283
|
+
for (const row of rows.values()) {
|
|
284
|
+
const references = type === "model" ? array(row.process_references) : array(row.flow_references);
|
|
285
|
+
if (references.some((value) => {
|
|
286
|
+
const ref = workflowObject(value);
|
|
287
|
+
return ((type === "model" || ref.version !== null) &&
|
|
288
|
+
(typeof ref.version !== "string" || !version.test(ref.version)));
|
|
289
|
+
}))
|
|
290
|
+
reject("A connected family reference has an unresolved exact revision.");
|
|
291
|
+
}
|
|
292
|
+
return [...new Set([...rows.values()].map((row) => String(row.id)))].sort();
|
|
293
|
+
};
|
|
294
|
+
return { process: select("process"), model: select("model"), nodes: nodes.size, heads };
|
|
295
|
+
}
|
|
296
|
+
/** Two complete compact directory scans prove a bounded family's separation from all visible peers. */
|
|
297
|
+
export async function readFoundryRepairCensus(workerInput, actor, read, phase = "before", observe) {
|
|
298
|
+
if (!uuid.test(actor))
|
|
299
|
+
reject("Repair census requires an explicit actor UUID.");
|
|
300
|
+
const baseline = workflowObject(workerInput.baseline);
|
|
301
|
+
const documents = array(baseline.documents)
|
|
302
|
+
.map(workflowObject)
|
|
303
|
+
.map((item) => ({ ...item }));
|
|
304
|
+
if (phase !== "before" && phase !== "after")
|
|
305
|
+
reject("Repair census observation phase is invalid.");
|
|
306
|
+
if (phase === "after") {
|
|
307
|
+
const changed = new Set();
|
|
308
|
+
for (const raw of array(workerInput.overlays)) {
|
|
309
|
+
const overlay = workflowObject(raw), selected = workflowObject(overlay.identity);
|
|
310
|
+
const key = `${String(selected.dataset_type)}:${identity(selected.id, selected.version)}`;
|
|
311
|
+
if (changed.has(key))
|
|
312
|
+
reject("Repair census overlays contain duplicate identities.");
|
|
313
|
+
changed.add(key);
|
|
314
|
+
const matches = documents.filter((item) => {
|
|
315
|
+
const current = workflowObject(item.identity);
|
|
316
|
+
return (current.dataset_type === selected.dataset_type &&
|
|
317
|
+
identity(current.id, current.version) === identity(selected.id, selected.version));
|
|
318
|
+
});
|
|
319
|
+
if (matches.length !== 1)
|
|
320
|
+
reject("Repair census overlay must select one frozen document.");
|
|
321
|
+
matches[0].document = overlay.document;
|
|
322
|
+
matches[0].document_sha256 = overlay.candidate_sha256;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const expected = new Map();
|
|
326
|
+
for (const item of documents) {
|
|
327
|
+
const selected = workflowObject(item.identity), type = selected.dataset_type;
|
|
328
|
+
if (typeof type !== "string" || !Object.hasOwn(tables, type) || type === "model")
|
|
329
|
+
reject("Repair census document type is unsupported.");
|
|
330
|
+
const key = identity(selected.id, selected.version), group = expected.get(type) ?? new Map();
|
|
331
|
+
if (group.has(key))
|
|
332
|
+
reject("Repair census frozen inventory contains duplicate identities.");
|
|
333
|
+
group.set(key, item);
|
|
334
|
+
expected.set(type, group);
|
|
335
|
+
}
|
|
336
|
+
const models = new Map();
|
|
337
|
+
for (const item of array(baseline.models).map(workflowObject)) {
|
|
338
|
+
const key = identity(item.id, item.version);
|
|
339
|
+
if (models.has(key))
|
|
340
|
+
reject("Repair census frozen models contain duplicate identities.");
|
|
341
|
+
models.set(key, item);
|
|
342
|
+
}
|
|
343
|
+
expected.set("model", models);
|
|
344
|
+
let transferredBytes = 0, projectionBytes = 0, exactBytes = 0, readPages = 0;
|
|
345
|
+
const observations = [];
|
|
346
|
+
const query = async (input) => {
|
|
347
|
+
const page = await read(input);
|
|
348
|
+
transferredBytes += Buffer.byteLength(page.raw);
|
|
349
|
+
if (transferredBytes > maximumTransferBytes)
|
|
350
|
+
reject("Repair census transfer exceeds its 1 GiB scan bound.");
|
|
351
|
+
const parsed = records(page, input);
|
|
352
|
+
const type = Object.entries(tables).find(([, table]) => table === input.table)[0];
|
|
353
|
+
const rows = input.projection
|
|
354
|
+
? parsed.rows.map((row) => directoryRow(type, row))
|
|
355
|
+
: parsed.rows;
|
|
356
|
+
const retained = input.projection ? JSON.stringify(rows) : page.raw;
|
|
357
|
+
if (input.projection)
|
|
358
|
+
projectionBytes += Buffer.byteLength(retained);
|
|
359
|
+
else
|
|
360
|
+
exactBytes += Buffer.byteLength(retained);
|
|
361
|
+
if (projectionBytes > maximumBytes || exactBytes > maximumBytes)
|
|
362
|
+
reject("Repair census compact projections or selected family evidence exceed their 64 MiB bound.");
|
|
363
|
+
const observation = {
|
|
364
|
+
query: input,
|
|
365
|
+
page: { ...page, raw: retained },
|
|
366
|
+
response_sha256: createHash("sha256").update(page.raw).digest("hex"),
|
|
367
|
+
};
|
|
368
|
+
readPages++;
|
|
369
|
+
if (observe)
|
|
370
|
+
observe(observation);
|
|
371
|
+
else
|
|
372
|
+
observations.push(observation);
|
|
373
|
+
return { rows, total: parsed.total };
|
|
374
|
+
};
|
|
375
|
+
const scan = async (type, projection, ids) => {
|
|
376
|
+
const found = new Map();
|
|
377
|
+
const groups = ids
|
|
378
|
+
? Array.from({ length: Math.ceil(ids.length / 100) }, (_, index) => ids.slice(index * 100, (index + 1) * 100))
|
|
379
|
+
: [undefined];
|
|
380
|
+
for (const group of groups)
|
|
381
|
+
for (const state of [100, 0]) {
|
|
382
|
+
let offset = 0, total, prior = "";
|
|
383
|
+
do {
|
|
384
|
+
const page = await query({
|
|
385
|
+
table: tables[type],
|
|
386
|
+
...(group ? { ids: group } : {}),
|
|
387
|
+
...(projection ? { projection: "dependencies" } : {}),
|
|
388
|
+
state,
|
|
389
|
+
...(state === 0 ? { owner: actor } : {}),
|
|
390
|
+
offset,
|
|
391
|
+
limit: 100,
|
|
392
|
+
});
|
|
393
|
+
if (total !== undefined && page.total !== total)
|
|
394
|
+
reject("Repair census membership count changed during pagination.");
|
|
395
|
+
total = page.total;
|
|
396
|
+
for (const row of page.rows) {
|
|
397
|
+
const key = identity(row.id, row.version);
|
|
398
|
+
if ((group && !group.includes(String(row.id).toLowerCase())) ||
|
|
399
|
+
key <= prior ||
|
|
400
|
+
found.has(key) ||
|
|
401
|
+
row.state_code !== state ||
|
|
402
|
+
!visible(row, actor))
|
|
403
|
+
reject("Repair census contains unordered, duplicate or out-of-scope rows.");
|
|
404
|
+
prior = key;
|
|
405
|
+
found.set(key, row);
|
|
406
|
+
if (found.size > maximumRows)
|
|
407
|
+
reject("Repair census combined visibility scope exceeds 100000 rows.");
|
|
408
|
+
}
|
|
409
|
+
offset += page.rows.length;
|
|
410
|
+
if (!page.rows.length && offset < total)
|
|
411
|
+
reject("Repair census stopped before its exact total.");
|
|
412
|
+
} while (offset < total);
|
|
413
|
+
}
|
|
414
|
+
return found;
|
|
415
|
+
};
|
|
416
|
+
const directory = async () => ({
|
|
417
|
+
process: await scan("process", true),
|
|
418
|
+
model: await scan("model", true),
|
|
419
|
+
flow: await scan("flow", true),
|
|
420
|
+
});
|
|
421
|
+
const match = (type, actual) => {
|
|
422
|
+
const selected = expected.get(type) ?? new Map();
|
|
423
|
+
if (actual.size !== selected.size)
|
|
424
|
+
reject(`Repair census ${type} membership differs from the frozen family.`);
|
|
425
|
+
for (const [key, item] of selected) {
|
|
426
|
+
const row = actual.get(key);
|
|
427
|
+
if (row &&
|
|
428
|
+
[
|
|
429
|
+
"id",
|
|
430
|
+
"version",
|
|
431
|
+
"user_id",
|
|
432
|
+
"state_code",
|
|
433
|
+
"json",
|
|
434
|
+
...(type === "process" ? ["model_id", "model_version", "team_id", "review_id"] : []),
|
|
435
|
+
].some((field) => !Object.hasOwn(row, field)))
|
|
436
|
+
reject("Repair census response omitted required content, ownership, state or lineage fields.");
|
|
437
|
+
if (!row ||
|
|
438
|
+
!visible(row, actor) ||
|
|
439
|
+
(row.user_id ?? null) !== (item.user_id ?? null) ||
|
|
440
|
+
row.state_code !== item.state_code ||
|
|
441
|
+
sha256Json(row.json) !== sha256Json(item.document))
|
|
442
|
+
reject(`Repair census ${type} content, owner or state changed.`);
|
|
443
|
+
if (type === "process" &&
|
|
444
|
+
["model_id", "model_version", "team_id", "review_id"].some((field) => (row[field] ?? null) !== (item[field] ?? null)))
|
|
445
|
+
reject("Repair census Process model lineage or collaboration metadata changed.");
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
const supports = async (heads) => {
|
|
449
|
+
const result = new Map();
|
|
450
|
+
for (const [type, items] of expected) {
|
|
451
|
+
if (type === "process" || type === "model")
|
|
452
|
+
continue;
|
|
453
|
+
for (const [key, item] of items) {
|
|
454
|
+
const selected = workflowObject(item.identity);
|
|
455
|
+
const page = await query({
|
|
456
|
+
table: tables[type],
|
|
457
|
+
id: String(selected.id),
|
|
458
|
+
version: String(selected.version),
|
|
459
|
+
offset: 0,
|
|
460
|
+
limit: 1,
|
|
461
|
+
});
|
|
462
|
+
if (page.total !== 1 ||
|
|
463
|
+
page.rows.length !== 1 ||
|
|
464
|
+
identity(page.rows[0].id, page.rows[0].version) !== key)
|
|
465
|
+
reject("Repair census exact dependency is missing or ambiguous.");
|
|
466
|
+
const row = page.rows[0];
|
|
467
|
+
if (["id", "version", "user_id", "state_code", "json"].some((field) => !Object.hasOwn(row, field)))
|
|
468
|
+
reject("Repair census dependency response omitted required fields.");
|
|
469
|
+
const eligible = visible(row, actor) || (type !== "flow" && row.state_code === 200);
|
|
470
|
+
if (!eligible ||
|
|
471
|
+
(row.user_id ?? null) !== (item.user_id ?? null) ||
|
|
472
|
+
row.state_code !== item.state_code ||
|
|
473
|
+
sha256Json(row.json) !== sha256Json(item.document))
|
|
474
|
+
reject("Repair census exact dependency content or eligibility changed.");
|
|
475
|
+
result.set(`${type}:${key}`, row);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
for (const flow of array(baseline.omitted_flow_resolutions ?? []).map(workflowObject)) {
|
|
479
|
+
const key = identity(flow.id, flow.version);
|
|
480
|
+
if (!expected.get("flow")?.has(key) ||
|
|
481
|
+
heads.get(String(flow.id).toLowerCase()) !== flow.version)
|
|
482
|
+
reject("Versionless references must select the latest visible Flow version.");
|
|
483
|
+
}
|
|
484
|
+
return result;
|
|
485
|
+
};
|
|
486
|
+
const firstDirectory = await directory();
|
|
487
|
+
const family = boundedFamily(firstDirectory, expected, workerInput);
|
|
488
|
+
const exact = async () => {
|
|
489
|
+
const result = {
|
|
490
|
+
process: await scan("process", false, family.process),
|
|
491
|
+
model: await scan("model", false, family.model),
|
|
492
|
+
};
|
|
493
|
+
match("process", result.process);
|
|
494
|
+
match("model", result.model);
|
|
495
|
+
return result;
|
|
496
|
+
};
|
|
497
|
+
const first = await exact(), firstSupport = await supports(family.heads);
|
|
498
|
+
const secondDirectory = await directory();
|
|
499
|
+
if (directoryDigest(firstDirectory) !== directoryDigest(secondDirectory))
|
|
500
|
+
reject("Repair census changed between its complete directory passes.");
|
|
501
|
+
boundedFamily(secondDirectory, expected, workerInput);
|
|
502
|
+
const second = await exact(), secondSupport = await supports(flowHeads(secondDirectory.flow));
|
|
503
|
+
if (digest(first.process) !== digest(second.process) ||
|
|
504
|
+
digest(first.model) !== digest(second.model) ||
|
|
505
|
+
digest(firstSupport) !== digest(secondSupport))
|
|
506
|
+
reject("Repair census changed between its complete exact family passes.");
|
|
507
|
+
return {
|
|
508
|
+
proof: {
|
|
509
|
+
schema: "tiangong-foundry.repair-census.v1",
|
|
510
|
+
status: "verified",
|
|
511
|
+
observation_phase: phase,
|
|
512
|
+
input_object_sha256: sha256Json(workerInput),
|
|
513
|
+
scope: "public-state100-plus-current-owner-state0",
|
|
514
|
+
actor_user_id: actor,
|
|
515
|
+
transaction_snapshot: false,
|
|
516
|
+
double_scan: true,
|
|
517
|
+
body_scope: "closed_conservative_family",
|
|
518
|
+
directory_complete: true,
|
|
519
|
+
directory_body_content_observed: false,
|
|
520
|
+
directory_projection_version: "dependency-identities-v1",
|
|
521
|
+
excluded_process_rows: firstDirectory.process.size - first.process.size,
|
|
522
|
+
excluded_model_rows: firstDirectory.model.size - first.model.size,
|
|
523
|
+
family_separation: "all-visible-revisions-shared-technosphere-uuid-and-model-lineage",
|
|
524
|
+
directory_process_rows: firstDirectory.process.size,
|
|
525
|
+
directory_model_rows: firstDirectory.model.size,
|
|
526
|
+
directory_flow_rows: firstDirectory.flow.size,
|
|
527
|
+
directory_sha256: directoryDigest(firstDirectory),
|
|
528
|
+
family_nodes: family.nodes,
|
|
529
|
+
process_rows: first.process.size,
|
|
530
|
+
model_rows: first.model.size,
|
|
531
|
+
exact_support_rows: firstSupport.size,
|
|
532
|
+
process_census_sha256: digest(first.process),
|
|
533
|
+
model_census_sha256: digest(first.model),
|
|
534
|
+
support_census_sha256: digest(firstSupport),
|
|
535
|
+
baseline_sha256: sha256Json(baseline),
|
|
536
|
+
read_pages: readPages,
|
|
537
|
+
transferred_bytes: transferredBytes,
|
|
538
|
+
retained_projection_bytes: projectionBytes,
|
|
539
|
+
exact_family_bytes: exactBytes,
|
|
540
|
+
completed_at_utc: new Date().toISOString(),
|
|
541
|
+
},
|
|
542
|
+
observations,
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
export async function verifyFoundryRepairCensus(context, qualified, authentication, workerInput, directory, phase = "before") {
|
|
546
|
+
if (!context.accountIntent)
|
|
547
|
+
reject("Repair census requires explicit account intent.");
|
|
548
|
+
const actor = await createFoundryEdgeActor(context, qualified, authentication);
|
|
549
|
+
const root = directory;
|
|
550
|
+
fs.mkdirSync(root, { recursive: false, mode: 0o700 });
|
|
551
|
+
const files = [];
|
|
552
|
+
const receipt = path.join(root, "identity-receipt.json");
|
|
553
|
+
fs.writeFileSync(receipt, JSON.stringify(actor.receipt, null, 2) + "\n", {
|
|
554
|
+
mode: 0o600,
|
|
555
|
+
flag: "wx",
|
|
556
|
+
});
|
|
557
|
+
files.push(receipt);
|
|
558
|
+
const observed = await readFoundryRepairCensus(workerInput, context.accountIntent.userId, (query) => actor.readDataPage(query), phase, (observation) => {
|
|
559
|
+
const file = path.join(root, `page-${String(files.length).padStart(6, "0")}.json`);
|
|
560
|
+
fs.writeFileSync(file, JSON.stringify(observation, null, 2) + "\n", {
|
|
561
|
+
mode: 0o600,
|
|
562
|
+
flag: "wx",
|
|
563
|
+
});
|
|
564
|
+
files.push(file);
|
|
565
|
+
});
|
|
566
|
+
const proofValue = { ...observed.proof, project_ref: context.accountIntent.projectRef };
|
|
567
|
+
const proof = path.join(root, "proof.json");
|
|
568
|
+
fs.writeFileSync(proof, JSON.stringify(proofValue, null, 2) + "\n", {
|
|
569
|
+
mode: 0o600,
|
|
570
|
+
flag: "wx",
|
|
571
|
+
});
|
|
572
|
+
files.push(proof);
|
|
573
|
+
return { proof: proofValue, files };
|
|
574
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { type ScientificRepairEvidence } from "./foundry-scientific-repair.ts";
|
|
1
2
|
type JsonRecord = Record<string, unknown>;
|
|
2
3
|
/** Phase 1 admits only Process, and only the two reviewed administrative display-text regions. */
|
|
3
4
|
export declare const FOUNDRY_REPAIR_SELECTION_KIND: "existing-owner-draft-metadata";
|
|
5
|
+
export declare const FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND: "existing-owner-draft-scientific";
|
|
4
6
|
export declare const FOUNDRY_REPAIR_ALLOWED_DATASET_TYPE: "process";
|
|
5
7
|
export declare const FOUNDRY_REPAIR_EDIT_PATHS: readonly [string, string];
|
|
6
8
|
/**
|
|
@@ -9,7 +11,7 @@ export declare const FOUNDRY_REPAIR_EDIT_PATHS: readonly [string, string];
|
|
|
9
11
|
*/
|
|
10
12
|
export declare const FOUNDRY_REPAIR_SHARED_SCIENCE_PREFIXES: readonly ["processDataSet.exchanges", "processDataSet.quantitativeReference", "processDataSet.modellingAndValidation.dataSourcesTreatmentAndRepresentativeness.annualSupplyOrProductionVolume", "processDataSet.modellingAndValidation.LCIMethod", "processDataSet.processInformation.dataSetInformation.name", "processDataSet.processInformation.dataSetInformation.classificationInformation", "processDataSet.processInformation.dataSetInformation.common:other", "processDataSet.processInformation.geography", "processDataSet.administrativeInformation.publicationAndOwnership.common:dataSetVersion", "flowDataSet", "flowPropertyDataSet", "unitGroupDataSet"];
|
|
11
13
|
export interface FoundryRepairSelection {
|
|
12
|
-
readonly kind: typeof FOUNDRY_REPAIR_SELECTION_KIND;
|
|
14
|
+
readonly kind: typeof FOUNDRY_REPAIR_SELECTION_KIND | typeof FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND;
|
|
13
15
|
readonly contract: string;
|
|
14
16
|
readonly before: string;
|
|
15
17
|
readonly candidate: string;
|
|
@@ -17,13 +19,15 @@ export interface FoundryRepairSelection {
|
|
|
17
19
|
task_id: string;
|
|
18
20
|
receipt_sha256: string;
|
|
19
21
|
}> | null;
|
|
22
|
+
readonly scientific?: string;
|
|
20
23
|
}
|
|
21
24
|
export interface FoundryRepairDiffBlocker {
|
|
22
25
|
readonly path: string;
|
|
23
26
|
readonly reason: "provider_impact_diagnostics_missing" | "unsupported_path" | "structure_change";
|
|
24
27
|
}
|
|
25
28
|
export interface FoundryRepairScope {
|
|
26
|
-
readonly kind: typeof FOUNDRY_REPAIR_SELECTION_KIND;
|
|
29
|
+
readonly kind: typeof FOUNDRY_REPAIR_SELECTION_KIND | typeof FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND;
|
|
30
|
+
readonly scientific?: ScientificRepairEvidence;
|
|
27
31
|
readonly status: "dispatchable" | "satisfied";
|
|
28
32
|
readonly contract_sha256: string;
|
|
29
33
|
readonly rows_sha256: string;
|
|
@@ -58,6 +62,8 @@ export declare function classifyRepairMetadataDiff(before: JsonRecord, after: Js
|
|
|
58
62
|
readonly allowed: boolean;
|
|
59
63
|
readonly blockers: readonly FoundryRepairDiffBlocker[];
|
|
60
64
|
};
|
|
65
|
+
/** Scientific review cannot widen administrative ownership, permissions or technical-header scope. */
|
|
66
|
+
export declare function assertScientificRepairPaths(before: JsonRecord, candidate: JsonRecord): void;
|
|
61
67
|
/**
|
|
62
68
|
* Validate one repair task: the CLI execution contract, the CLI-fresh before rows and the candidate rows
|
|
63
69
|
* must agree on the exact same Process identities, every action must be a save_draft against an existing
|
|
@@ -72,5 +78,12 @@ export declare function readFoundryRepairScope(input: {
|
|
|
72
78
|
verifiedProjectRef: string;
|
|
73
79
|
stateCode: string;
|
|
74
80
|
relativePath: (file: string) => string;
|
|
81
|
+
scientific?: {
|
|
82
|
+
descriptorFile: string;
|
|
83
|
+
actorId: string;
|
|
84
|
+
selectedFiles: readonly string[];
|
|
85
|
+
excludedRuntimeRoots: readonly string[];
|
|
86
|
+
read: (file: string) => Buffer;
|
|
87
|
+
};
|
|
75
88
|
}): Readonly<FoundryRepairScope>;
|
|
76
89
|
export {};
|