@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.
Files changed (51) hide show
  1. package/README.md +5 -3
  2. package/docs/architecture.md +5 -3
  3. package/docs/foundry-task-contracts.md +2 -0
  4. package/docs/package-distribution-contract.md +5 -3
  5. package/docs/public-runtime-contract.md +41 -3
  6. package/docs/runtime-context-contract.md +5 -3
  7. package/docs/task-authorization-contract.md +2 -0
  8. package/package-dist/assets/foundry-package-descriptor.json +142 -74
  9. package/package-dist/scripts/foundry-facade.d.ts +6 -0
  10. package/package-dist/scripts/foundry-facade.js +35 -0
  11. package/package-dist/scripts/foundry-runtime.d.ts +2 -1
  12. package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
  13. package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
  14. package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
  15. package/package-dist/scripts/lib/final-delivery-review.js +108 -0
  16. package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
  17. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +3 -0
  18. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +90 -1
  19. package/package-dist/scripts/lib/foundry-edge-session.d.ts +18 -1
  20. package/package-dist/scripts/lib/foundry-edge-session.js +137 -3
  21. package/package-dist/scripts/lib/foundry-edge-support.d.ts +1 -1
  22. package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
  23. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  24. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  25. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +3 -2
  26. package/package-dist/scripts/lib/foundry-owner-readback.js +21 -2
  27. package/package-dist/scripts/lib/foundry-package-contract.d.ts +3 -3
  28. package/package-dist/scripts/lib/foundry-package-contract.js +7 -1
  29. package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
  30. package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
  31. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
  32. package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
  33. package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
  34. package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
  35. package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
  36. package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
  37. package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
  38. package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
  39. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
  40. package/package-dist/scripts/lib/foundry-workflow-execution.js +3 -0
  41. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
  42. package/package-dist/scripts/lib/foundry-workflow-repair.js +151 -0
  43. package/package-dist/scripts/public-api.d.ts +6 -0
  44. package/package-dist/scripts/runtime-entry.js +15 -6
  45. package/package.json +4 -1
  46. package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
  47. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  48. package/specs/schemas/foundry-package-descriptor.schema.json +4 -1
  49. package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
  50. package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
  51. package/specs/schemas/foundry-task-start.schema.json +10 -2
@@ -0,0 +1,145 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ export const MANIFEST_SCHEMA = "foundry-final-delivery-manifest.v1";
5
+ export const REPORT_SCHEMA = "foundry-final-delivery-promotion-report.v1";
6
+ export const LEDGER_SCHEMA = "foundry-final-delivery-promotion-ledger-row.v1";
7
+ export const SEAL_SCHEMA = "foundry-final-delivery-promotion-seal.v1";
8
+ export const MAX_ZIP_ENTRIES = 10_000;
9
+ export const MAX_ZIP_ENTRY_BYTES = 32 * 1024 * 1024;
10
+ export const MAX_ZIP_TOTAL_BYTES = 64 * 1024 * 1024;
11
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/u;
12
+ export function sha256(value) {
13
+ return crypto.createHash("sha256").update(value).digest("hex");
14
+ }
15
+ export function compareText(left, right) {
16
+ if (left < right)
17
+ return -1;
18
+ if (left > right)
19
+ return 1;
20
+ return 0;
21
+ }
22
+ function stableValue(value) {
23
+ if (Array.isArray(value))
24
+ return value.map(stableValue);
25
+ if (isPlainObject(value)) {
26
+ return Object.fromEntries(Object.entries(value)
27
+ .sort(([left], [right]) => compareText(left, right))
28
+ .map(([key, child]) => [key, stableValue(child)]));
29
+ }
30
+ return value;
31
+ }
32
+ // Content-addressed evidence must hash the same regardless of object key insertion order.
33
+ export function stableJson(value) {
34
+ return JSON.stringify(stableValue(value));
35
+ }
36
+ export function isPlainObject(value) {
37
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
38
+ }
39
+ export function isSha256(value) {
40
+ return typeof value === "string" && SHA256_PATTERN.test(value);
41
+ }
42
+ export function pathIsInside(root, candidate) {
43
+ const relative = path.relative(root, candidate);
44
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
45
+ }
46
+ export function safeRelativePath(value) {
47
+ return Boolean(typeof value === "string" &&
48
+ value.length > 0 &&
49
+ !path.posix.isAbsolute(value) &&
50
+ !value.includes("\\") &&
51
+ !value.split("/").includes("..") &&
52
+ path.posix.normalize(value) === value);
53
+ }
54
+ // Every promotion artifact is written with an exclusive create so earlier evidence is never
55
+ // overwritten, and a failed run leaves no partial replacement of prior bytes.
56
+ export function writeExclusive(filePath, content) {
57
+ fs.writeFileSync(filePath, content, { flag: "wx" });
58
+ }
59
+ export function writeJsonExclusive(filePath, value) {
60
+ writeExclusive(filePath, `${JSON.stringify(value, null, 2)}\n`);
61
+ }
62
+ export function relativeToRepo(repoRoot, filePath) {
63
+ return pathIsInside(repoRoot, filePath) ? path.relative(repoRoot, filePath) : filePath;
64
+ }
65
+ function collectStrings(value, out) {
66
+ // Keys are collected as well as values: a decoded key reaches a reader exactly like a value does,
67
+ // and an escaped key can carry a literal a raw-byte scan never sees.
68
+ if (typeof value === "string") {
69
+ out.push(value);
70
+ return;
71
+ }
72
+ if (Array.isArray(value)) {
73
+ for (const item of value)
74
+ collectStrings(item, out);
75
+ return;
76
+ }
77
+ if (isPlainObject(value)) {
78
+ for (const [key, child] of Object.entries(value)) {
79
+ out.push(key);
80
+ collectStrings(child, out);
81
+ }
82
+ }
83
+ }
84
+ // JSON string escaping can hide a literal from a raw byte scan, so the decoded keys and values of
85
+ // already-parsed content are scanned alongside the exact source bytes.
86
+ export function scanTextWithDecodedStrings(raw, value) {
87
+ const decoded = [];
88
+ collectStrings(value, decoded);
89
+ return decoded.length > 0 ? `${raw}\n${decoded.join("\n")}` : raw;
90
+ }
91
+ // Tab, newline and carriage return are the only control characters a supported text artifact may
92
+ // carry; any other C0 control or DEL means the bytes are not the text they claim to be.
93
+ function hasUnsupportedControl(text) {
94
+ for (const character of text) {
95
+ const code = character.codePointAt(0) ?? 0;
96
+ if (code === 0x09 || code === 0x0a || code === 0x0d)
97
+ continue;
98
+ if (code < 0x20 || code === 0x7f)
99
+ return true;
100
+ }
101
+ return false;
102
+ }
103
+ // The supported text encoding is strict UTF-8. Silent replacement would scan text that is not the
104
+ // artifact's own content, so an undecodable byte fails closed instead.
105
+ export function decodeArtifactText(buffer) {
106
+ let text;
107
+ try {
108
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buffer);
109
+ }
110
+ catch {
111
+ throw new PromotionArtifactError("artifact_text_encoding_invalid", "A text artifact must be valid UTF-8 and cannot contain undecodable bytes.");
112
+ }
113
+ if (hasUnsupportedControl(text)) {
114
+ throw new PromotionArtifactError("artifact_control_byte", "A text artifact cannot contain an unsupported control byte.");
115
+ }
116
+ return text;
117
+ }
118
+ // Every parse failure carries a stable category. The message is for local debugging only and is
119
+ // never written into the promotion ledger or report, so raw artifact text cannot leak outward.
120
+ export class PromotionArtifactError extends Error {
121
+ code;
122
+ constructor(code, message) {
123
+ super(message);
124
+ this.name = "PromotionArtifactError";
125
+ this.code = code;
126
+ }
127
+ }
128
+ export function artifactErrorCode(error) {
129
+ return error instanceof PromotionArtifactError ? error.code : "artifact_parse_failed";
130
+ }
131
+ export function checkCollector() {
132
+ const rows = [];
133
+ function add(checkId, passed, severity, detail, evidence = null) {
134
+ rows.push({
135
+ schema_version: LEDGER_SCHEMA,
136
+ check_id: checkId,
137
+ status: passed ? "PASS" : "FAIL",
138
+ severity: passed ? null : severity,
139
+ detail,
140
+ evidence,
141
+ });
142
+ return passed;
143
+ }
144
+ return { add, rows };
145
+ }
@@ -0,0 +1,37 @@
1
+ import { type JsonRecord } from "./final-delivery-manifest.ts";
2
+ export type ReviewerDeclaration = JsonRecord & {
3
+ reviewer_id?: string;
4
+ artifact_id?: string;
5
+ required_artifact_ids?: unknown;
6
+ };
7
+ export type ReviewerReport = JsonRecord & {
8
+ reviewer_id?: string;
9
+ status?: string;
10
+ reviewed_artifacts?: unknown;
11
+ findings?: {
12
+ p0?: number;
13
+ p1?: number;
14
+ };
15
+ };
16
+ export type ReviewedArtifactBinding = {
17
+ artifact_id: string;
18
+ sha256: string;
19
+ bytes: number;
20
+ };
21
+ export declare function reviewerDeclarations(manifest: JsonRecord): ReviewerDeclaration[];
22
+ export declare function reviewerIdentityValid(reviewer: ReviewerDeclaration, producerId: unknown, seenReviewerIds: ReadonlySet<string>, seenArtifactIds: ReadonlySet<string>): boolean;
23
+ export declare function reviewerPassValid(report: unknown, reviewerId: unknown): boolean;
24
+ export type ReviewScope = {
25
+ bindings: ReviewedArtifactBinding[];
26
+ duplicateIds: string[];
27
+ malformedCount: number;
28
+ };
29
+ export declare function reviewScope(report: unknown): ReviewScope | null;
30
+ export declare function reviewerCoverageValid(report: unknown, required: readonly unknown[], currentBindings: ReadonlyMap<string, {
31
+ sha256: string;
32
+ bytes: number;
33
+ }>, reviewerArtifactId: unknown): boolean;
34
+ export declare function reviewerContentBindingValid(report: unknown, required: readonly unknown[], currentBindings: ReadonlyMap<string, {
35
+ sha256: string;
36
+ bytes: number;
37
+ }>): boolean;
@@ -0,0 +1,108 @@
1
+ import { isPlainObject, isSha256 } from "./final-delivery-manifest.js";
2
+ export function reviewerDeclarations(manifest) {
3
+ const reviewers = manifest.reviewers;
4
+ if (!Array.isArray(reviewers))
5
+ return [];
6
+ return reviewers.filter(isPlainObject);
7
+ }
8
+ // The reviewer identity must be present, independent of the producer, and used at most once.
9
+ export function reviewerIdentityValid(reviewer, producerId, seenReviewerIds, seenArtifactIds) {
10
+ const reviewerId = reviewer?.reviewer_id;
11
+ const artifactId = reviewer?.artifact_id;
12
+ return Boolean(reviewerId &&
13
+ reviewerId !== producerId &&
14
+ !seenReviewerIds.has(reviewerId) &&
15
+ artifactId &&
16
+ !seenArtifactIds.has(artifactId));
17
+ }
18
+ // A PASS disposition is only meaningful when the report names the same reviewer and declares
19
+ // zero P0 and P1 findings, so a producer cannot close its own evidence gap.
20
+ export function reviewerPassValid(report, reviewerId) {
21
+ if (!isPlainObject(report))
22
+ return false;
23
+ const typed = report;
24
+ return (typed.reviewer_id === reviewerId &&
25
+ typed.status === "PASS" &&
26
+ typed.findings?.p0 === 0 &&
27
+ typed.findings?.p1 === 0);
28
+ }
29
+ function reviewedBinding(value) {
30
+ if (!isPlainObject(value))
31
+ return null;
32
+ const artifactId = value.artifact_id;
33
+ const sha256 = value.sha256;
34
+ const bytes = value.bytes;
35
+ if (typeof artifactId !== "string" || artifactId.length === 0)
36
+ return null;
37
+ if (!isSha256(sha256))
38
+ return null;
39
+ if (!Number.isInteger(bytes) || bytes < 0)
40
+ return null;
41
+ return { artifact_id: artifactId, sha256: sha256, bytes: bytes };
42
+ }
43
+ export function reviewScope(report) {
44
+ if (!isPlainObject(report))
45
+ return null;
46
+ const reviewed = report.reviewed_artifacts;
47
+ if (!Array.isArray(reviewed) || reviewed.length === 0)
48
+ return null;
49
+ const bindings = [];
50
+ const seen = new Set();
51
+ const duplicateIds = [];
52
+ let malformedCount = 0;
53
+ for (const entry of reviewed) {
54
+ const binding = reviewedBinding(entry);
55
+ if (!binding) {
56
+ malformedCount += 1;
57
+ continue;
58
+ }
59
+ if (seen.has(binding.artifact_id))
60
+ duplicateIds.push(binding.artifact_id);
61
+ seen.add(binding.artifact_id);
62
+ bindings.push(binding);
63
+ }
64
+ return { bindings, duplicateIds, malformedCount };
65
+ }
66
+ // Review coverage is content-bound. Each manifest-required artifact must be individually bound to
67
+ // the exact SHA-256 and byte count the reviewer saw, and those values must still match the bytes
68
+ // the manifest currently binds. The reviewer's own report artifact is excluded so the binding
69
+ // cannot be made circular by hashing the report that carries the hash.
70
+ export function reviewerCoverageValid(report, required, currentBindings, reviewerArtifactId) {
71
+ const scope = reviewScope(report);
72
+ if (!scope)
73
+ return false;
74
+ if (scope.malformedCount > 0 || scope.duplicateIds.length > 0)
75
+ return false;
76
+ const boundIds = new Set(scope.bindings.map((binding) => binding.artifact_id));
77
+ if (typeof reviewerArtifactId === "string" && boundIds.has(reviewerArtifactId))
78
+ return false;
79
+ // A binding for an artifact that is not in the manifest is an unknown identity, not coverage.
80
+ for (const id of boundIds) {
81
+ if (!currentBindings.has(id))
82
+ return false;
83
+ }
84
+ if (required.length === 0 || new Set(required).size !== required.length)
85
+ return false;
86
+ return required.every((id) => typeof id === "string" && boundIds.has(id));
87
+ }
88
+ export function reviewerContentBindingValid(report, required, currentBindings) {
89
+ const scope = reviewScope(report);
90
+ if (!scope)
91
+ return false;
92
+ if (scope.malformedCount > 0 || scope.duplicateIds.length > 0)
93
+ return false;
94
+ // Every binding the report declares must match the current bytes, not only the required ones: a
95
+ // stale or wrong digest on a voluntarily-included artifact is still a false claim.
96
+ for (const binding of scope.bindings) {
97
+ const current = currentBindings.get(binding.artifact_id);
98
+ if (!current)
99
+ return false;
100
+ if (binding.sha256 !== current.sha256 || binding.bytes !== current.bytes)
101
+ return false;
102
+ }
103
+ // `required_artifact_ids` sets the minimum coverage, not the set to verify.
104
+ const boundIds = new Set(scope.bindings.map((binding) => binding.artifact_id));
105
+ return (required.length > 0 &&
106
+ new Set(required).size === required.length &&
107
+ required.every((id) => typeof id === "string" && boundIds.has(id)));
108
+ }
@@ -81,9 +81,10 @@ export function readNativeDraftHandoff(input) {
81
81
  token(action.id) !== id ||
82
82
  token(action.version) !== version ||
83
83
  identity.id !== id ||
84
- identity.version !== version ||
85
- action.desired_sha256 !== sha256Json(identity.payload))
86
- fail("Contract action does not bind the exact final payload, identity and draft operation.");
84
+ identity.version !== version)
85
+ fail("Contract action does not bind the exact identity and draft operation.");
86
+ if (action.desired_sha256 !== sha256Json(identity.payload))
87
+ fail("Action desired_sha256 must match the canonical digest of the parsed dataset payload. File selection uses the SHA-256 of raw file bytes.");
87
88
  if (!Array.isArray(action.dependency_action_ids))
88
89
  fail("Action dependencies must be explicit.");
89
90
  const dependencies = action.dependency_action_ids.map(token);
@@ -2,12 +2,14 @@ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-run
2
2
  import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
3
  import { type FoundryAuthentication } from "./foundry-authentication-environment.ts";
4
4
  import { type FoundryRepairExpectation } from "./foundry-repair-preflight.ts";
5
+ import type { ScientificRepairEvidence } from "./foundry-scientific-repair.ts";
5
6
  export declare function readEdgeRepairValidation(report: Record<string, unknown>, expectation: FoundryRepairExpectation): Record<string, boolean>;
6
7
  export declare function prepareEdgeProcessRepair(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, expectation: FoundryRepairExpectation, files: {
7
8
  before: string;
8
9
  candidate: string;
9
10
  temporary: string;
10
11
  directory: string;
12
+ scientific?: ScientificRepairEvidence;
11
13
  }): Promise<{
12
14
  schema: string;
13
15
  input_path: string;
@@ -18,4 +20,5 @@ export declare function prepareEdgeProcessRepair(context: FoundryRuntimeContext,
18
20
  rule_verification: Record<string, boolean>;
19
21
  reference_evidence: FoundryInputFact;
20
22
  remote_before_sha256: string;
23
+ scientific_gates?: Record<string, unknown> | undefined;
21
24
  }>;
@@ -11,6 +11,12 @@ import { readRows } from "./import-curation/internal/runtime-io.js";
11
11
  import { parseFoundryRepairValidateReport, } from "./foundry-repair-preflight.js";
12
12
  import { sha256Json } from "./identity-preflight-proof.js";
13
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";
14
20
  const invalid = (message) => new FoundryContextError("repair_edge_preflight_invalid", message);
15
21
  export function readEdgeRepairValidation(report, expectation) {
16
22
  if (report.schema !== "tiangong-foundry.typed-process-qa.v1" || !Array.isArray(report.rows))
@@ -51,7 +57,31 @@ export async function prepareEdgeProcessRepair(context, qualified, authenticatio
51
57
  if (typeof referenceReport !== "string")
52
58
  throw invalid("Repair dependency evidence is missing.");
53
59
  const documents = path.join(directory, "validation-references.json");
54
- save(documents, references.referenceDocuments);
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);
55
85
  const validate = (file, directory) => {
56
86
  const validation = runFoundryTypedDatasetQa(context, qualified, temporary, save, "process", file, directory, {
57
87
  referenceFiles: [documents],
@@ -63,7 +93,65 @@ export async function prepareEdgeProcessRepair(context, qualified, authenticatio
63
93
  };
64
94
  const complete = validate(candidate, path.join(directory, "validation"));
65
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.");
66
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
+ }
67
155
  const beforeEvidence = requiresBeforeValidation
68
156
  ? validate(before, path.join(directory, "before-validation"))
69
157
  : null;
@@ -114,6 +202,7 @@ export async function prepareEdgeProcessRepair(context, qualified, authenticatio
114
202
  rule_verification: ruleVerification,
115
203
  reference_evidence: captureFoundryInput(referenceReport),
116
204
  remote_before_sha256: sha256Json(checked.responses),
205
+ ...(scientificGates ? { scientific_gates: scientificGates } : {}),
117
206
  };
118
207
  save(path.join(directory, "owner-report.json"), report);
119
208
  return report;
@@ -5,7 +5,24 @@ type IdentityEndpoint = "flow_hybrid_search" | "process_hybrid_search";
5
5
  type EdgeEndpoint = IdentityEndpoint | "app_dataset_create" | "app_dataset_save_draft" | "app_dataset_verify_remote";
6
6
  export declare function foundryEdgeProjectOrigin(value: string): string;
7
7
  export declare function createFoundryEdgeActor(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication): Promise<{
8
- receipt: import("@tiangong-lca/cli/auth-identity-receipt").AuthIdentityReceipt;
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
+ }>;
9
26
  post(endpoint: EdgeEndpoint, body: Record<string, unknown>): Promise<unknown>;
10
27
  }>;
11
28
  export declare function queryFoundryEdgeIdentity(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, endpoint: IdentityEndpoint, body: Record<string, unknown>): Promise<{
@@ -12,6 +12,35 @@ export function foundryEdgeProjectOrigin(value) {
12
12
  throw new FoundryContextError("edge_project_invalid", "Expected an explicit project base URL.");
13
13
  return url.origin;
14
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
+ }
15
44
  export async function createFoundryEdgeActor(context, qualified, authentication) {
16
45
  const credentials = authentication.mode === "headless"
17
46
  ? { ...authentication }
@@ -25,20 +54,125 @@ export async function createFoundryEdgeActor(context, qualified, authentication)
25
54
  const origin = configured ? foundryEdgeProjectOrigin(configured) : verifiedOrigin;
26
55
  if (origin !== verifiedOrigin)
27
56
  throw new FoundryContextError("edge_project_mismatch", "Edge target must match the verified operator project.");
28
- const token = credentials.mode === "headless"
57
+ let token = credentials.mode === "headless"
29
58
  ? credentials.accessToken
30
59
  : await resolveFoundryEdgeOAuth(origin, identity.receipt.identity.user_id, credentials.configuration);
31
60
  const publishableKey = credentials.mode === "headless"
32
61
  ? credentials.publishableKey
33
62
  : credentials.configuration.publishableKey;
34
63
  // Browser authorization can take longer than the CLI receipt window.
35
- const current = credentials.mode === "headless"
64
+ let current = credentials.mode === "headless"
36
65
  ? identity
37
66
  : verifyFoundryRuntimeIdentity(context, credentials, process.env, qualified);
38
67
  if (foundryEdgeProjectOrigin(current.receipt.project.project_base_url) !== origin)
39
68
  throw new FoundryContextError("edge_project_mismatch", "The OAuth project changed during authentication.");
40
69
  return {
41
- receipt: current.receipt,
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
+ },
42
176
  async post(endpoint, body) {
43
177
  assertVerifiedFoundryIdentity(context, current, qualified);
44
178
  const url = new URL(`/functions/v1/${endpoint}`, origin);
@@ -1,6 +1,6 @@
1
1
  import type { createFoundryEdgeActor } from "./foundry-edge-session.ts";
2
2
  import type { EdgeSupportPlan, EdgeSupportRoot } from "./foundry-edge-support-plan.ts";
3
- type Actor = Awaited<ReturnType<typeof createFoundryEdgeActor>>;
3
+ type Actor = Pick<Awaited<ReturnType<typeof createFoundryEdgeActor>>, "receipt" | "post">;
4
4
  type RootContent = {
5
5
  root: EdgeSupportRoot;
6
6
  content: Record<string, unknown>;