@tiangong-lca/foundry 0.1.18 → 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 +10 -8
- package/docs/public-runtime-contract.md +53 -3
- package/docs/runtime-context-contract.md +7 -3
- package/docs/task-authorization-contract.md +2 -0
- package/package-dist/assets/foundry-package-descriptor.json +374 -136
- package/package-dist/scripts/foundry-facade.d.ts +6 -0
- package/package-dist/scripts/foundry-facade.js +38 -0
- package/package-dist/scripts/foundry-runtime.d.ts +3 -2
- package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -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/cli-wrappers.d.ts +72 -1
- package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
- package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
- package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
- package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
- package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
- package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
- package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
- package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
- package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
- package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
- package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
- package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
- package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
- package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
- package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
- package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +24 -0
- package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +209 -0
- package/package-dist/scripts/lib/foundry-edge-session.d.ts +32 -0
- package/package-dist/scripts/lib/foundry-edge-session.js +203 -0
- package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
- package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
- package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
- package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
- package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
- package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
- package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
- package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
- package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
- package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
- package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
- package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
- package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
- package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
- 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-execution-store.d.ts +16 -16
- package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
- package/package-dist/scripts/lib/foundry-owner-readback.d.ts +21 -0
- package/package-dist/scripts/lib/foundry-owner-readback.js +61 -0
- package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
- package/package-dist/scripts/lib/foundry-package-contract.js +8 -2
- package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
- package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
- package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
- package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
- package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
- 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-execution.js +13 -2
- 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-runtime-environment.d.ts +2 -0
- package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
- package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
- package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
- package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
- package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
- package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
- 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-typed-authoring-patch.d.ts +76 -0
- package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
- package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
- package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
- package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
- package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
- package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
- package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
- package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
- package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
- package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
- package/package-dist/scripts/lib/foundry-workflow-execution.js +57 -5
- package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
- package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
- package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
- package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
- package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
- package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
- package/package-dist/scripts/lib/foundry-workflow-repair.js +204 -2
- package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
- package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
- package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
- package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
- package/package-dist/scripts/public-api.d.ts +6 -0
- package/package-dist/scripts/runtime-entry.js +15 -6
- package/package.json +5 -2
- package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
- package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
- package/specs/schemas/foundry-operation-result.schema.json +1 -0
- package/specs/schemas/foundry-package-descriptor.schema.json +5 -2
- 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
- package/specs/schemas/runtime-qualification.schema.json +1 -1
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { FoundryContextError, readFoundryInput, resolveFoundryInputPath, } from "./foundry-runtime-context.js";
|
|
3
|
+
import { bundleRowTypes } from "./bundle-row-types.js";
|
|
4
|
+
import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
|
|
5
|
+
import { collectDatasetReferences } from "./import-curation/internal/workflow-reference-closure.js";
|
|
6
|
+
import { sha256Json } from "./identity-preflight-proof.js";
|
|
7
|
+
const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu;
|
|
8
|
+
const version = /^\d{2}\.\d{2}\.\d{3}$/u;
|
|
9
|
+
const digest = /^[0-9a-f]{64}$/u;
|
|
10
|
+
const maximumFileBytes = 8 * 1024 * 1024;
|
|
11
|
+
export function edgeReferenceKey(reference) {
|
|
12
|
+
return `${reference.table}:${reference.id}@${reference.version}`;
|
|
13
|
+
}
|
|
14
|
+
function requireIntent(value, message) {
|
|
15
|
+
if (!value)
|
|
16
|
+
throw new FoundryContextError("edge_reference_intent_invalid", message);
|
|
17
|
+
}
|
|
18
|
+
function record(value, keys) {
|
|
19
|
+
requireIntent(value &&
|
|
20
|
+
typeof value === "object" &&
|
|
21
|
+
!Array.isArray(value) &&
|
|
22
|
+
Object.keys(value).length === keys.length &&
|
|
23
|
+
keys.every((key) => Object.hasOwn(value, key)), "Reference intent or review contains missing or unsupported fields.");
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
export function readEdgeReferenceSnapshot(value, actor) {
|
|
27
|
+
const snapshot = record(value, [
|
|
28
|
+
"table",
|
|
29
|
+
"id",
|
|
30
|
+
"version",
|
|
31
|
+
"payload_sha256",
|
|
32
|
+
"user_id",
|
|
33
|
+
"state_code",
|
|
34
|
+
]);
|
|
35
|
+
requireIntent(typeof snapshot.table === "string" &&
|
|
36
|
+
typeof snapshot.id === "string" &&
|
|
37
|
+
uuid.test(snapshot.id) &&
|
|
38
|
+
typeof snapshot.version === "string" &&
|
|
39
|
+
version.test(snapshot.version) &&
|
|
40
|
+
typeof snapshot.payload_sha256 === "string" &&
|
|
41
|
+
digest.test(snapshot.payload_sha256) &&
|
|
42
|
+
typeof snapshot.user_id === "string" &&
|
|
43
|
+
uuid.test(snapshot.user_id) &&
|
|
44
|
+
(snapshot.state_code === 100 ||
|
|
45
|
+
(snapshot.state_code === 0 && snapshot.user_id.toLowerCase() === actor)), "A reviewed reference must select exact content of a public version or own draft.");
|
|
46
|
+
return {
|
|
47
|
+
table: snapshot.table,
|
|
48
|
+
id: snapshot.id.toLowerCase(),
|
|
49
|
+
version: snapshot.version,
|
|
50
|
+
payload_sha256: snapshot.payload_sha256,
|
|
51
|
+
user_id: snapshot.user_id.toLowerCase(),
|
|
52
|
+
state_code: snapshot.state_code,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function readEdgeReferenceIntent(context, input, type, target, rows) {
|
|
56
|
+
const read = (inputPath) => {
|
|
57
|
+
const selected = resolveFoundryInputPath(context, inputPath);
|
|
58
|
+
const bytes = readFoundryInput(context, selected, maximumFileBytes);
|
|
59
|
+
const fact = context.inputs.find((item) => item.path === selected);
|
|
60
|
+
const file = { path: fact.path, sha256: fact.sha256, bytes: fact.bytes };
|
|
61
|
+
try {
|
|
62
|
+
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
63
|
+
return { file, value };
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new FoundryContextError("edge_reference_intent_invalid", "Reference evidence must be UTF-8 JSON.");
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const { file, value } = read(input);
|
|
70
|
+
const intent = record(value, [
|
|
71
|
+
"schema_version",
|
|
72
|
+
"project_ref",
|
|
73
|
+
"actor_user_id",
|
|
74
|
+
"consumers",
|
|
75
|
+
"references",
|
|
76
|
+
]);
|
|
77
|
+
const identities = rows.map((row, index) => datasetIdentity(row, index, type));
|
|
78
|
+
const consumers = identities.map(({ id, version, payload }, row_index) => ({
|
|
79
|
+
row_index,
|
|
80
|
+
table: bundleRowTypes[type].plural,
|
|
81
|
+
id,
|
|
82
|
+
version,
|
|
83
|
+
payload_sha256: sha256Json(payload),
|
|
84
|
+
}));
|
|
85
|
+
requireIntent(intent.schema_version === "dataset-exact-reference-intent.v1" &&
|
|
86
|
+
/^[a-z0-9]{20}$/u.test(target.project_ref) &&
|
|
87
|
+
intent.project_ref === target.project_ref &&
|
|
88
|
+
typeof intent.actor_user_id === "string" &&
|
|
89
|
+
intent.actor_user_id.toLowerCase() === target.user_id &&
|
|
90
|
+
consumers.length > 0 &&
|
|
91
|
+
Array.isArray(intent.consumers) &&
|
|
92
|
+
sha256Json(intent.consumers.map((raw) => {
|
|
93
|
+
const row = record(raw, ["row_index", "table", "id", "version", "payload_sha256"]);
|
|
94
|
+
requireIntent(typeof row.id === "string" && uuid.test(row.id), "Reference consumer UUID is invalid.");
|
|
95
|
+
return { ...row, id: row.id.toLowerCase() };
|
|
96
|
+
})) === sha256Json(consumers) &&
|
|
97
|
+
Array.isArray(intent.references) &&
|
|
98
|
+
intent.references.length > 0 &&
|
|
99
|
+
intent.references.length <= 10000, "Reference intent must bind the verified actor and every exact final consumer in order.");
|
|
100
|
+
const occurrences = identities.map(({ payload }) => collectDatasetReferences(payload));
|
|
101
|
+
const selectedOccurrences = new Set();
|
|
102
|
+
const reviewFiles = new Map();
|
|
103
|
+
const reviewed = new Map();
|
|
104
|
+
let bytes = file.bytes;
|
|
105
|
+
const references = intent.references.map((raw) => {
|
|
106
|
+
const entry = record(raw, ["row_index", "path", "selected", "review"]);
|
|
107
|
+
const selected = readEdgeReferenceSnapshot(entry.selected, target.user_id);
|
|
108
|
+
const row_index = Number(entry.row_index);
|
|
109
|
+
const pointer = entry.path;
|
|
110
|
+
const occurrence = `${row_index}:${String(pointer)}`;
|
|
111
|
+
requireIntent(typeof entry.row_index === "number" &&
|
|
112
|
+
Number.isInteger(row_index) &&
|
|
113
|
+
typeof pointer === "string" &&
|
|
114
|
+
pointer.startsWith("/") &&
|
|
115
|
+
pointer.trim() === pointer &&
|
|
116
|
+
!selectedOccurrences.has(occurrence) &&
|
|
117
|
+
occurrences[row_index]?.filter((ref) => ref.path === pointer &&
|
|
118
|
+
ref.table === selected.table &&
|
|
119
|
+
ref.id === selected.id &&
|
|
120
|
+
ref.version === selected.version).length === 1, "Review must identify one unchanged exact occurrence in the selected consumer.");
|
|
121
|
+
selectedOccurrences.add(occurrence);
|
|
122
|
+
const locator = record(entry.review, ["file", "sha256"]);
|
|
123
|
+
requireIntent(typeof locator.file === "string" &&
|
|
124
|
+
locator.file.length > 0 &&
|
|
125
|
+
locator.file.trim() === locator.file &&
|
|
126
|
+
!/[\0\r\n]/u.test(locator.file), "Review locator must preserve its exact file spelling.");
|
|
127
|
+
const reviewPath = resolveFoundryInputPath(context, path.resolve(path.dirname(file.path), locator.file));
|
|
128
|
+
let review = reviewFiles.get(reviewPath);
|
|
129
|
+
if (!review) {
|
|
130
|
+
review = read(reviewPath);
|
|
131
|
+
bytes += review.file.bytes;
|
|
132
|
+
requireIntent(bytes <= 64 * 1024 * 1024, "Reference evidence exceeds its content budget.");
|
|
133
|
+
reviewFiles.set(reviewPath, review);
|
|
134
|
+
}
|
|
135
|
+
const declared = record(review.value, [
|
|
136
|
+
"schema_version",
|
|
137
|
+
"decision",
|
|
138
|
+
"reason",
|
|
139
|
+
"selected",
|
|
140
|
+
"latest",
|
|
141
|
+
]);
|
|
142
|
+
const latest = readEdgeReferenceSnapshot(declared.latest, target.user_id);
|
|
143
|
+
const key = edgeReferenceKey(selected);
|
|
144
|
+
const snapshots = { selected, latest };
|
|
145
|
+
requireIntent(locator.sha256 === review.file.sha256 &&
|
|
146
|
+
declared.schema_version === "dataset-exact-reference-review.v1" &&
|
|
147
|
+
declared.decision === "use_selected_exact" &&
|
|
148
|
+
typeof declared.reason === "string" &&
|
|
149
|
+
declared.reason.trim() &&
|
|
150
|
+
declared.reason.length <= 8192 &&
|
|
151
|
+
sha256Json(readEdgeReferenceSnapshot(declared.selected, target.user_id)) ===
|
|
152
|
+
sha256Json(selected) &&
|
|
153
|
+
latest.table === selected.table &&
|
|
154
|
+
latest.id === selected.id &&
|
|
155
|
+
latest.version >= selected.version &&
|
|
156
|
+
(latest.version !== selected.version || sha256Json(latest) === sha256Json(selected)) &&
|
|
157
|
+
(!reviewed.has(key) || sha256Json(reviewed.get(key)) === sha256Json(snapshots)), "Review must bind unchanged selected bytes and a consistent reviewed latest version.");
|
|
158
|
+
reviewed.set(key, snapshots);
|
|
159
|
+
return { row_index, path: pointer, selected, review: { file: review.file, latest } };
|
|
160
|
+
});
|
|
161
|
+
// One remote observation covers identical exact dependencies. Every outdated occurrence still
|
|
162
|
+
// requires its own explicit review before that observation can authorize the older version.
|
|
163
|
+
occurrences.forEach((list, index) => {
|
|
164
|
+
for (const ref of list) {
|
|
165
|
+
if (!ref.table)
|
|
166
|
+
continue;
|
|
167
|
+
const review = reviewed.get(edgeReferenceKey({ ...ref, table: ref.table }));
|
|
168
|
+
requireIntent(!review ||
|
|
169
|
+
review.selected.version === review.latest.version ||
|
|
170
|
+
selectedOccurrences.has(`${index}:${ref.path}`), "Every occurrence of an outdated exact dependency requires its own explicit review.");
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
return {
|
|
174
|
+
binding: {
|
|
175
|
+
file,
|
|
176
|
+
project_ref: target.project_ref,
|
|
177
|
+
actor_user_id: target.user_id,
|
|
178
|
+
consumers,
|
|
179
|
+
references,
|
|
180
|
+
review_files: [...reviewFiles.values()].map((item) => item.file),
|
|
181
|
+
},
|
|
182
|
+
reviewed,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
|
|
2
|
+
import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
|
|
3
|
+
import { type FoundryAuthentication } from "./foundry-authentication-environment.ts";
|
|
4
|
+
import { type FoundryRepairExpectation } from "./foundry-repair-preflight.ts";
|
|
5
|
+
import type { ScientificRepairEvidence } from "./foundry-scientific-repair.ts";
|
|
6
|
+
export declare function readEdgeRepairValidation(report: Record<string, unknown>, expectation: FoundryRepairExpectation): Record<string, boolean>;
|
|
7
|
+
export declare function prepareEdgeProcessRepair(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, expectation: FoundryRepairExpectation, files: {
|
|
8
|
+
before: string;
|
|
9
|
+
candidate: string;
|
|
10
|
+
temporary: string;
|
|
11
|
+
directory: string;
|
|
12
|
+
scientific?: ScientificRepairEvidence;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
schema: string;
|
|
15
|
+
input_path: string;
|
|
16
|
+
before: FoundryInputFact;
|
|
17
|
+
contract_sha256: string;
|
|
18
|
+
validation_sha256: string;
|
|
19
|
+
before_validation_sha256: string | null;
|
|
20
|
+
rule_verification: Record<string, boolean>;
|
|
21
|
+
reference_evidence: FoundryInputFact;
|
|
22
|
+
remote_before_sha256: string;
|
|
23
|
+
scientific_gates?: Record<string, unknown> | undefined;
|
|
24
|
+
}>;
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { captureFoundryInput, FoundryContextError, readFoundryInput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
|
|
4
|
+
import { createFoundryEdgeActor } from "./foundry-edge-session.js";
|
|
5
|
+
import { buildEdgeSupportPlan } from "./foundry-edge-support-plan.js";
|
|
6
|
+
import { planFoundryEdgeSupportStage } from "./foundry-edge-support-planning.js";
|
|
7
|
+
import { verifyFoundryEdgeSupport } from "./foundry-edge-support.js";
|
|
8
|
+
import { createFoundryAuthenticationEnvironment, } from "./foundry-authentication-environment.js";
|
|
9
|
+
import { runFoundryTypedDatasetQa } from "./foundry-typed-flow-qa.js";
|
|
10
|
+
import { readRows } from "./import-curation/internal/runtime-io.js";
|
|
11
|
+
import { parseFoundryRepairValidateReport, } from "./foundry-repair-preflight.js";
|
|
12
|
+
import { sha256Json } from "./identity-preflight-proof.js";
|
|
13
|
+
import { workflowObject } from "./foundry-workflow-state.js";
|
|
14
|
+
import { runTidasRowsValidation } from "./tidas-adapter.js";
|
|
15
|
+
import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
|
|
16
|
+
import { runDatasetCurationCleanup } from "./import-curation/curation-cleanup.js";
|
|
17
|
+
import { runDatasetCurationGate } from "./import-curation/curation-gate.js";
|
|
18
|
+
import { projectFoundryValidationReferences } from "./foundry-validation-reference-context.js";
|
|
19
|
+
import { datasetIdentity, detectDatasetType } from "./import-curation/internal/dataset-payload.js";
|
|
20
|
+
const invalid = (message) => new FoundryContextError("repair_edge_preflight_invalid", message);
|
|
21
|
+
export function readEdgeRepairValidation(report, expectation) {
|
|
22
|
+
if (report.schema !== "tiangong-foundry.typed-process-qa.v1" || !Array.isArray(report.rows))
|
|
23
|
+
throw invalid("Expected the full typed Process validation evidence.");
|
|
24
|
+
parseFoundryRepairValidateReport(report, expectation);
|
|
25
|
+
const verification = {};
|
|
26
|
+
for (const raw of report.rows) {
|
|
27
|
+
const row = workflowObject(raw);
|
|
28
|
+
if (workflowObject(row.allocation_semantics).status !== "passed" ||
|
|
29
|
+
workflowObject(row.flow_reference_names).status !== "passed" ||
|
|
30
|
+
!Array.isArray(row.issues) ||
|
|
31
|
+
row.issues.some((issue) => workflowObject(issue).code !== "annual_supply_or_production_volume_missing"))
|
|
32
|
+
throw invalid("Repair must preserve qualified allocation, exact Flow names and all validation checks except the bounded unknown annual-volume gap.");
|
|
33
|
+
verification[String(row.payload_sha256)] = row.status === "passed";
|
|
34
|
+
}
|
|
35
|
+
return verification;
|
|
36
|
+
}
|
|
37
|
+
export async function prepareEdgeProcessRepair(context, qualified, authentication, expectation, files) {
|
|
38
|
+
const { before, candidate, temporary, directory } = files;
|
|
39
|
+
const actor = await createFoundryEdgeActor(context, qualified, authentication);
|
|
40
|
+
const receiptFile = path.join(directory, "identity-receipt.json");
|
|
41
|
+
const save = (file, value) => writeFoundryArtifact(context, file, JSON.stringify(value, null, 2) + "\n");
|
|
42
|
+
save(receiptFile, actor.receipt);
|
|
43
|
+
const candidateFact = captureFoundryInput(candidate);
|
|
44
|
+
const referenceDir = path.join(directory, "references");
|
|
45
|
+
const environment = createFoundryAuthenticationEnvironment(authentication, context.accountIntent?.sessionReference, process.env);
|
|
46
|
+
const references = (() => {
|
|
47
|
+
try {
|
|
48
|
+
return planFoundryEdgeSupportStage(context, qualified, environment, "process", "repair_preflight", ["--input", candidate, "--out-dir", referenceDir], true, receiptFile, candidateFact);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
delete environment.TIANGONG_LCA_ACCESS_TOKEN;
|
|
52
|
+
}
|
|
53
|
+
})();
|
|
54
|
+
if (references.exit_code !== 0 || !references.referenceDocuments)
|
|
55
|
+
throw invalid("Every exact repair dependency must be independently readable.");
|
|
56
|
+
const referenceReport = references.report.files.report;
|
|
57
|
+
if (typeof referenceReport !== "string")
|
|
58
|
+
throw invalid("Repair dependency evidence is missing.");
|
|
59
|
+
const documents = path.join(directory, "validation-references.json");
|
|
60
|
+
let validationReferences = references.referenceDocuments;
|
|
61
|
+
if (files.scientific) {
|
|
62
|
+
const input = JSON.parse(readFoundryInput(context, files.scientific.worker_input.path, 64 * 1024 * 1024).toString("utf8"));
|
|
63
|
+
const frozen = workflowObject(input.baseline).documents;
|
|
64
|
+
if (!Array.isArray(frozen))
|
|
65
|
+
throw invalid("Scientific repair requires its complete census-verified native source inventory.");
|
|
66
|
+
const additional = frozen
|
|
67
|
+
.map(workflowObject)
|
|
68
|
+
.filter((entry) => ["flow", "flowproperty", "unitgroup"].includes(String(workflowObject(entry.identity).dataset_type)))
|
|
69
|
+
.map((entry) => entry.document);
|
|
70
|
+
const byIdentity = new Map();
|
|
71
|
+
for (const row of [...validationReferences, ...additional]) {
|
|
72
|
+
const type = detectDatasetType(row);
|
|
73
|
+
if (!type || !["flow", "flowproperty", "unitgroup"].includes(type))
|
|
74
|
+
throw invalid("Scientific QA references must be exact Flow, FlowProperty or UnitGroup bodies.");
|
|
75
|
+
const identity = datasetIdentity(row, 0, type);
|
|
76
|
+
const key = `${type}:${identity.id}@${identity.version}`;
|
|
77
|
+
const prior = byIdentity.get(key);
|
|
78
|
+
if (prior && sha256Json(prior) !== sha256Json(identity.payload))
|
|
79
|
+
throw invalid("Scientific QA references contain competing exact source bodies.");
|
|
80
|
+
byIdentity.set(key, identity.payload);
|
|
81
|
+
}
|
|
82
|
+
validationReferences = [...byIdentity.values()];
|
|
83
|
+
}
|
|
84
|
+
save(documents, validationReferences);
|
|
85
|
+
const validate = (file, directory) => {
|
|
86
|
+
const validation = runFoundryTypedDatasetQa(context, qualified, temporary, save, "process", file, directory, {
|
|
87
|
+
referenceFiles: [documents],
|
|
88
|
+
readRowsFile: (file) => file === documents
|
|
89
|
+
? fs.readFileSync(documents, "utf8")
|
|
90
|
+
: readFoundryInput(context, file).toString("utf8"),
|
|
91
|
+
});
|
|
92
|
+
return JSON.parse(fs.readFileSync(validation.validationReportFile, "utf8"));
|
|
93
|
+
};
|
|
94
|
+
const complete = validate(candidate, path.join(directory, "validation"));
|
|
95
|
+
const ruleVerification = readEdgeRepairValidation(complete, expectation);
|
|
96
|
+
if (files.scientific && Object.values(ruleVerification).some((passed) => !passed))
|
|
97
|
+
throw invalid("Scientific repair requires every candidate validation layer to pass before authorization.");
|
|
98
|
+
const requiresBeforeValidation = Object.values(ruleVerification).includes(false);
|
|
99
|
+
let scientificGates = null;
|
|
100
|
+
if (files.scientific) {
|
|
101
|
+
const cleanupDirectory = path.join(directory, "cleanup");
|
|
102
|
+
const cleanup = runDatasetCurationCleanup({
|
|
103
|
+
repoRoot: context.assetRoot,
|
|
104
|
+
options: { type: "process", rowsFile: candidate, outDir: cleanupDirectory },
|
|
105
|
+
});
|
|
106
|
+
const cleanedFile = cleanup.cleaned_rows_file;
|
|
107
|
+
if (cleanup.status !== "completed" || typeof cleanedFile !== "string")
|
|
108
|
+
throw invalid("Scientific repair cleanup must complete before validation and curation.");
|
|
109
|
+
if (sha256Json(readRows(candidate)) !== sha256Json(readRows(cleanedFile)))
|
|
110
|
+
throw invalid("Cleanup changed the selected scientific candidate. Review and register that complete candidate as a new immutable repair scope.");
|
|
111
|
+
const schemaRows = path.join(directory, "schema-validation-rows.jsonl");
|
|
112
|
+
const projected = projectFoundryValidationReferences(readRows(candidate), validationReferences);
|
|
113
|
+
writeFoundryArtifact(context, schemaRows, projected.map((row) => JSON.stringify(row)).join("\n") + "\n");
|
|
114
|
+
const schema = runTidasRowsValidation({
|
|
115
|
+
repoRoot: context.assetRoot,
|
|
116
|
+
options: {
|
|
117
|
+
type: "process",
|
|
118
|
+
rowsFile: schemaRows,
|
|
119
|
+
outDir: path.join(directory, "schema"),
|
|
120
|
+
tidasBin: qualified.tidas.executable_path,
|
|
121
|
+
},
|
|
122
|
+
environment: createFoundryIsolatedChildEnvironment({
|
|
123
|
+
tempRoot: path.join(temporary, "science-schema-runtime"),
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
if (typeof schema.report_file !== "string")
|
|
127
|
+
throw invalid("Scientific repair requires the qualified native schema report.");
|
|
128
|
+
const gateDirectory = path.join(directory, "curation");
|
|
129
|
+
const gate = runDatasetCurationGate({
|
|
130
|
+
repoRoot: context.assetRoot,
|
|
131
|
+
cliValidation: {
|
|
132
|
+
report: path.join(directory, "validation", "outputs", "validation-report.json"),
|
|
133
|
+
exit: 0,
|
|
134
|
+
},
|
|
135
|
+
options: {
|
|
136
|
+
type: "process",
|
|
137
|
+
rowsFile: candidate,
|
|
138
|
+
schemaReport: schema.report_file,
|
|
139
|
+
qaReport: path.join(directory, "validation", "process-qa-report.json"),
|
|
140
|
+
cleanupReport: path.join(cleanupDirectory, "dataset-curation-cleanup-report.json"),
|
|
141
|
+
outDir: gateDirectory,
|
|
142
|
+
profile: "generic",
|
|
143
|
+
includeExecutionCommands: false,
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
if (gate.status !== "ready")
|
|
147
|
+
throw invalid("Scientific repair requires the exact candidate to pass the existing Foundry curation gate without unresolved authoring or cleanup findings.");
|
|
148
|
+
scientificGates = {
|
|
149
|
+
schema: captureFoundryInput(schema.report_file),
|
|
150
|
+
schema_projection: captureFoundryInput(schemaRows),
|
|
151
|
+
cleanup: captureFoundryInput(path.join(cleanupDirectory, "dataset-curation-cleanup-report.json")),
|
|
152
|
+
curation: captureFoundryInput(path.join(gateDirectory, "dataset-curation-gate-report.json")),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const beforeEvidence = requiresBeforeValidation
|
|
156
|
+
? validate(before, path.join(directory, "before-validation"))
|
|
157
|
+
: null;
|
|
158
|
+
if (beforeEvidence) {
|
|
159
|
+
const beforeRules = readEdgeRepairValidation(beforeEvidence, {
|
|
160
|
+
...expectation,
|
|
161
|
+
actions: expectation.actions.map((action) => ({
|
|
162
|
+
...action,
|
|
163
|
+
desired_sha256: action.before_sha256,
|
|
164
|
+
})),
|
|
165
|
+
});
|
|
166
|
+
if (expectation.actions.some((action) => !ruleVerification[action.desired_sha256] && beforeRules[action.before_sha256]))
|
|
167
|
+
throw invalid("The unknown annual-volume gap must already exist in the selected before draft.");
|
|
168
|
+
}
|
|
169
|
+
const read = (fact) => readRows(fact.path, (file) => readFoundryInput(context, file).toString("utf8"));
|
|
170
|
+
const candidateRows = read(candidateFact);
|
|
171
|
+
const beforeFact = captureFoundryInput(before);
|
|
172
|
+
const target = { project_ref: expectation.project_ref, user_id: expectation.owner_user_id };
|
|
173
|
+
const plan = buildEdgeSupportPlan("process", candidateFact, target, candidateRows, {
|
|
174
|
+
fact: captureFoundryInput(referenceReport),
|
|
175
|
+
report: references.report,
|
|
176
|
+
});
|
|
177
|
+
const beforePlan = buildEdgeSupportPlan("process", beforeFact, target, read(beforeFact));
|
|
178
|
+
const expected = new Map(expectation.actions.map((item) => [`${item.id}@${item.version}`, item]));
|
|
179
|
+
const roots = plan.roots.map((root) => {
|
|
180
|
+
const prior = beforePlan.roots.find((item) => item.id === root.id && item.version === root.version);
|
|
181
|
+
const action = expected.get(`${root.id}@${root.version}`);
|
|
182
|
+
if (!prior ||
|
|
183
|
+
!action ||
|
|
184
|
+
prior.payload_sha256 !== action.before_sha256 ||
|
|
185
|
+
root.payload_sha256 !== action.desired_sha256)
|
|
186
|
+
throw invalid("Guarded update roots must match the exact reviewed contract.");
|
|
187
|
+
return { ...root, payload_sha256: prior.payload_sha256 };
|
|
188
|
+
});
|
|
189
|
+
// The repair scope has already bound every exact reference occurrence in both documents.
|
|
190
|
+
// An older visible dependency can be retained with the same content, owner and state.
|
|
191
|
+
const checked = await verifyFoundryEdgeSupport(actor, { ...plan, roots }, "after", true);
|
|
192
|
+
save(path.join(directory, "edge-before.json"), checked.responses);
|
|
193
|
+
if (checked.blockers.length)
|
|
194
|
+
throw invalid("Current draft or a dependency differs from the exact before snapshot.");
|
|
195
|
+
const report = {
|
|
196
|
+
schema: "tiangong-foundry.edge-repair-preflight.v1",
|
|
197
|
+
input_path: candidate,
|
|
198
|
+
before: beforeFact,
|
|
199
|
+
contract_sha256: expectation.contract_sha256,
|
|
200
|
+
validation_sha256: sha256Json(complete),
|
|
201
|
+
before_validation_sha256: beforeEvidence ? sha256Json(beforeEvidence) : null,
|
|
202
|
+
rule_verification: ruleVerification,
|
|
203
|
+
reference_evidence: captureFoundryInput(referenceReport),
|
|
204
|
+
remote_before_sha256: sha256Json(checked.responses),
|
|
205
|
+
...(scientificGates ? { scientific_gates: scientificGates } : {}),
|
|
206
|
+
};
|
|
207
|
+
save(path.join(directory, "owner-report.json"), report);
|
|
208
|
+
return report;
|
|
209
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
|
|
2
|
+
import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
|
|
3
|
+
import { type FoundryAuthentication } from "./foundry-runtime-identity.ts";
|
|
4
|
+
type IdentityEndpoint = "flow_hybrid_search" | "process_hybrid_search";
|
|
5
|
+
type EdgeEndpoint = IdentityEndpoint | "app_dataset_create" | "app_dataset_save_draft" | "app_dataset_verify_remote";
|
|
6
|
+
export declare function foundryEdgeProjectOrigin(value: string): string;
|
|
7
|
+
export declare function createFoundryEdgeActor(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication): Promise<{
|
|
8
|
+
readonly receipt: import("@tiangong-lca/cli/auth-identity-receipt").AuthIdentityReceipt;
|
|
9
|
+
readDataPage(input: {
|
|
10
|
+
table: "processes" | "lifecyclemodels" | "flows" | "flowproperties" | "unitgroups" | "sources" | "contacts" | "lciamethods";
|
|
11
|
+
state?: 0 | 100;
|
|
12
|
+
owner?: string;
|
|
13
|
+
id?: string;
|
|
14
|
+
version?: string;
|
|
15
|
+
ids?: readonly string[];
|
|
16
|
+
projection?: "dependencies";
|
|
17
|
+
offset: number;
|
|
18
|
+
limit: number;
|
|
19
|
+
}): Promise<{
|
|
20
|
+
raw: string;
|
|
21
|
+
contentRange: string | null;
|
|
22
|
+
status: number;
|
|
23
|
+
identityReceipt: import("@tiangong-lca/cli/auth-identity-receipt").AuthIdentityReceipt;
|
|
24
|
+
requestedAtUtc: string;
|
|
25
|
+
}>;
|
|
26
|
+
post(endpoint: EdgeEndpoint, body: Record<string, unknown>): Promise<unknown>;
|
|
27
|
+
}>;
|
|
28
|
+
export declare function queryFoundryEdgeIdentity(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, endpoint: IdentityEndpoint, body: Record<string, unknown>): Promise<{
|
|
29
|
+
receipt: import("@tiangong-lca/cli/auth-identity-receipt").AuthIdentityReceipt;
|
|
30
|
+
result: unknown;
|
|
31
|
+
}>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { FoundryContextError } from "./foundry-runtime-context.js";
|
|
2
|
+
import { assertVerifiedFoundryIdentity, verifyFoundryRuntimeIdentity, } from "./foundry-runtime-identity.js";
|
|
3
|
+
import { resolveFoundryEdgeOAuth } from "./foundry-edge-oauth.js";
|
|
4
|
+
export function foundryEdgeProjectOrigin(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (!["https:", "http:"].includes(url.protocol) ||
|
|
7
|
+
url.username ||
|
|
8
|
+
url.password ||
|
|
9
|
+
url.search ||
|
|
10
|
+
url.hash ||
|
|
11
|
+
!["", "/functions/v1", "/rest/v1"].includes(url.pathname.replace(/\/+$/u, "")))
|
|
12
|
+
throw new FoundryContextError("edge_project_invalid", "Expected an explicit project base URL.");
|
|
13
|
+
return url.origin;
|
|
14
|
+
}
|
|
15
|
+
async function readCensusPageBody(response) {
|
|
16
|
+
const limit = 8 * 1024 * 1024;
|
|
17
|
+
const tooLarge = () => new FoundryContextError("repair_census_read_invalid", "Repair census page exceeds 8 MiB.");
|
|
18
|
+
if (!response.body)
|
|
19
|
+
throw new FoundryContextError("repair_census_read_invalid", "Repair census page is empty.");
|
|
20
|
+
if (Number(response.headers.get("content-length")) > limit) {
|
|
21
|
+
await response.body.cancel();
|
|
22
|
+
throw tooLarge();
|
|
23
|
+
}
|
|
24
|
+
const reader = response.body.getReader();
|
|
25
|
+
const chunks = [];
|
|
26
|
+
let length = 0;
|
|
27
|
+
try {
|
|
28
|
+
for (;;) {
|
|
29
|
+
const { done, value } = await reader.read();
|
|
30
|
+
if (done)
|
|
31
|
+
break;
|
|
32
|
+
length += value.byteLength;
|
|
33
|
+
if (length > limit)
|
|
34
|
+
throw tooLarge();
|
|
35
|
+
chunks.push(value);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
await reader.cancel();
|
|
40
|
+
reader.releaseLock();
|
|
41
|
+
}
|
|
42
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, length));
|
|
43
|
+
}
|
|
44
|
+
export async function createFoundryEdgeActor(context, qualified, authentication) {
|
|
45
|
+
const credentials = authentication.mode === "headless"
|
|
46
|
+
? { ...authentication }
|
|
47
|
+
: {
|
|
48
|
+
...authentication,
|
|
49
|
+
configuration: { ...authentication.configuration },
|
|
50
|
+
};
|
|
51
|
+
const identity = verifyFoundryRuntimeIdentity(context, credentials, process.env, qualified);
|
|
52
|
+
const verifiedOrigin = foundryEdgeProjectOrigin(identity.receipt.project.project_base_url);
|
|
53
|
+
const configured = credentials.mode === "headless" ? credentials.apiBaseUrl : credentials.configuration.apiBaseUrl;
|
|
54
|
+
const origin = configured ? foundryEdgeProjectOrigin(configured) : verifiedOrigin;
|
|
55
|
+
if (origin !== verifiedOrigin)
|
|
56
|
+
throw new FoundryContextError("edge_project_mismatch", "Edge target must match the verified operator project.");
|
|
57
|
+
let token = credentials.mode === "headless"
|
|
58
|
+
? credentials.accessToken
|
|
59
|
+
: await resolveFoundryEdgeOAuth(origin, identity.receipt.identity.user_id, credentials.configuration);
|
|
60
|
+
const publishableKey = credentials.mode === "headless"
|
|
61
|
+
? credentials.publishableKey
|
|
62
|
+
: credentials.configuration.publishableKey;
|
|
63
|
+
// Browser authorization can take longer than the CLI receipt window.
|
|
64
|
+
let current = credentials.mode === "headless"
|
|
65
|
+
? identity
|
|
66
|
+
: verifyFoundryRuntimeIdentity(context, credentials, process.env, qualified);
|
|
67
|
+
if (foundryEdgeProjectOrigin(current.receipt.project.project_base_url) !== origin)
|
|
68
|
+
throw new FoundryContextError("edge_project_mismatch", "The OAuth project changed during authentication.");
|
|
69
|
+
return {
|
|
70
|
+
get receipt() {
|
|
71
|
+
return current.receipt;
|
|
72
|
+
},
|
|
73
|
+
async readDataPage(input) {
|
|
74
|
+
try {
|
|
75
|
+
assertVerifiedFoundryIdentity(context, current, qualified);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!(error instanceof FoundryContextError) || error.code !== "identity_receipt_stale")
|
|
79
|
+
throw error;
|
|
80
|
+
current = verifyFoundryRuntimeIdentity(context, credentials, process.env, qualified);
|
|
81
|
+
if (foundryEdgeProjectOrigin(current.receipt.project.project_base_url) !== origin)
|
|
82
|
+
throw new FoundryContextError("edge_project_mismatch", "The census project changed during identity renewal.");
|
|
83
|
+
if (credentials.mode !== "headless")
|
|
84
|
+
token = await resolveFoundryEdgeOAuth(origin, current.receipt.identity.user_id, credentials.configuration);
|
|
85
|
+
assertVerifiedFoundryIdentity(context, current, qualified);
|
|
86
|
+
}
|
|
87
|
+
const allowed = [
|
|
88
|
+
"processes",
|
|
89
|
+
"lifecyclemodels",
|
|
90
|
+
"flows",
|
|
91
|
+
"flowproperties",
|
|
92
|
+
"unitgroups",
|
|
93
|
+
"sources",
|
|
94
|
+
"contacts",
|
|
95
|
+
"lciamethods",
|
|
96
|
+
];
|
|
97
|
+
if (!allowed.includes(input.table) ||
|
|
98
|
+
!Number.isSafeInteger(input.offset) ||
|
|
99
|
+
input.offset < 0 ||
|
|
100
|
+
!Number.isSafeInteger(input.limit) ||
|
|
101
|
+
input.limit < 1 ||
|
|
102
|
+
input.limit > 100 ||
|
|
103
|
+
(input.state !== undefined && input.state !== 0 && input.state !== 100) ||
|
|
104
|
+
(input.state === 0 && input.owner !== current.receipt.identity.user_id) ||
|
|
105
|
+
(input.id === undefined && input.state === undefined) ||
|
|
106
|
+
(input.version !== undefined && input.id === undefined))
|
|
107
|
+
throw new FoundryContextError("repair_census_query_invalid", "Select a bounded public or current-owner draft census, or an exact reference identity.");
|
|
108
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
109
|
+
if ((input.owner !== undefined && !uuid.test(input.owner)) ||
|
|
110
|
+
(input.id !== undefined &&
|
|
111
|
+
(!uuid.test(input.id) ||
|
|
112
|
+
(input.version === undefined
|
|
113
|
+
? input.table !== "flows" || input.state === undefined
|
|
114
|
+
: !/^[0-9]{2}\.[0-9]{2}\.[0-9]{3}$/u.test(input.version)))))
|
|
115
|
+
throw new FoundryContextError("repair_census_query_invalid", "Repair census reads require exact owner and versioned dataset identities.");
|
|
116
|
+
if ((input.ids !== undefined &&
|
|
117
|
+
(!Array.isArray(input.ids) ||
|
|
118
|
+
input.ids.length < 1 ||
|
|
119
|
+
input.ids.length > 100 ||
|
|
120
|
+
new Set(input.ids).size !== input.ids.length ||
|
|
121
|
+
input.ids.some((id) => !uuid.test(id)) ||
|
|
122
|
+
input.id !== undefined ||
|
|
123
|
+
input.version !== undefined ||
|
|
124
|
+
input.state === undefined)) ||
|
|
125
|
+
(input.projection !== undefined &&
|
|
126
|
+
(input.projection !== "dependencies" ||
|
|
127
|
+
!["processes", "lifecyclemodels", "flows"].includes(input.table) ||
|
|
128
|
+
input.state === undefined)))
|
|
129
|
+
throw new FoundryContextError("repair_census_query_invalid", "Select bounded exact family identities or the supported dependency directory projection.");
|
|
130
|
+
const projected = {
|
|
131
|
+
processes: "id,version,user_id,state_code,model_id,model_version,team_id,review_id,exchanges:json->processDataSet->exchanges->exchange",
|
|
132
|
+
lifecyclemodels: "id,version,user_id,state_code,result_process:json->lifeCycleModelDataSet->lifeCycleModelInformation->dataSetInformation->referenceToResultingProcess,process_instances:json->lifeCycleModelDataSet->lifeCycleModelInformation->technology->processes->processInstance",
|
|
133
|
+
flows: "id,version,user_id,state_code,declared_type:json->flowDataSet->modellingAndValidation->LCIMethod->typeOfDataSet",
|
|
134
|
+
};
|
|
135
|
+
const url = new URL(`/rest/v1/${input.table}`, origin);
|
|
136
|
+
url.searchParams.set("select", input.projection
|
|
137
|
+
? projected[input.table]
|
|
138
|
+
: `id,version,user_id,state_code,json${input.table === "processes" ? ",model_id,model_version,team_id,review_id" : ""}`);
|
|
139
|
+
if (input.ids)
|
|
140
|
+
url.searchParams.set("id", `in.(${input.ids.join(",")})`);
|
|
141
|
+
url.searchParams.set("order", "id.asc,version.asc");
|
|
142
|
+
if (input.state !== undefined)
|
|
143
|
+
url.searchParams.set("state_code", `eq.${input.state}`);
|
|
144
|
+
if (input.owner !== undefined)
|
|
145
|
+
url.searchParams.set("user_id", `eq.${input.owner}`);
|
|
146
|
+
if (input.id !== undefined)
|
|
147
|
+
url.searchParams.set("id", `eq.${input.id}`);
|
|
148
|
+
if (input.version !== undefined)
|
|
149
|
+
url.searchParams.set("version", `eq.${input.version}`);
|
|
150
|
+
const requestedAtUtc = new Date().toISOString();
|
|
151
|
+
const response = await fetch(url, {
|
|
152
|
+
method: "GET",
|
|
153
|
+
headers: {
|
|
154
|
+
Authorization: `Bearer ${token}`,
|
|
155
|
+
...(publishableKey ? { apikey: publishableKey } : {}),
|
|
156
|
+
Accept: "application/json",
|
|
157
|
+
"Accept-Profile": "public",
|
|
158
|
+
Prefer: "count=exact",
|
|
159
|
+
"Range-Unit": "items",
|
|
160
|
+
Range: `${input.offset}-${input.offset + input.limit - 1}`,
|
|
161
|
+
},
|
|
162
|
+
redirect: "error",
|
|
163
|
+
signal: AbortSignal.timeout(30_000),
|
|
164
|
+
});
|
|
165
|
+
if (!response.ok)
|
|
166
|
+
throw new FoundryContextError("repair_census_read_failed", "The authenticated read interface rejected the repair census.");
|
|
167
|
+
const raw = await readCensusPageBody(response);
|
|
168
|
+
return {
|
|
169
|
+
raw,
|
|
170
|
+
contentRange: response.headers.get("content-range"),
|
|
171
|
+
status: response.status,
|
|
172
|
+
identityReceipt: current.receipt,
|
|
173
|
+
requestedAtUtc,
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
async post(endpoint, body) {
|
|
177
|
+
assertVerifiedFoundryIdentity(context, current, qualified);
|
|
178
|
+
const url = new URL(`/functions/v1/${endpoint}`, origin);
|
|
179
|
+
const response = await fetch(url, {
|
|
180
|
+
method: "POST",
|
|
181
|
+
headers: {
|
|
182
|
+
Authorization: `Bearer ${token}`,
|
|
183
|
+
...(publishableKey ? { apikey: publishableKey } : {}),
|
|
184
|
+
"Content-Type": "application/json",
|
|
185
|
+
Accept: "application/json",
|
|
186
|
+
},
|
|
187
|
+
redirect: "error",
|
|
188
|
+
signal: AbortSignal.timeout(30_000),
|
|
189
|
+
body: JSON.stringify(body),
|
|
190
|
+
});
|
|
191
|
+
if (!response.ok && !(endpoint === "app_dataset_verify_remote" && response.status === 409))
|
|
192
|
+
throw new FoundryContextError("edge_request_failed", "The selected Edge request was rejected.");
|
|
193
|
+
const text = await response.text();
|
|
194
|
+
if (Buffer.byteLength(text) > 8 * 1024 * 1024)
|
|
195
|
+
throw new FoundryContextError("edge_response_invalid", "The Edge response exceeds the evidence limit.");
|
|
196
|
+
return JSON.parse(text);
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
export async function queryFoundryEdgeIdentity(context, qualified, authentication, endpoint, body) {
|
|
201
|
+
const actor = await createFoundryEdgeActor(context, qualified, authentication);
|
|
202
|
+
return { receipt: actor.receipt, result: await actor.post(endpoint, body) };
|
|
203
|
+
}
|