@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
@@ -4,8 +4,10 @@ import { sha256Json, sha256Text } from "./identity-preflight-proof.js";
4
4
  import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
5
5
  import { readRows } from "./import-curation/internal/runtime-io.js";
6
6
  import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
7
+ import { readScientificRepairEvidence, } from "./foundry-scientific-repair.js";
7
8
  /** Phase 1 admits only Process, and only the two reviewed administrative display-text regions. */
8
9
  export const FOUNDRY_REPAIR_SELECTION_KIND = "existing-owner-draft-metadata";
10
+ export const FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND = "existing-owner-draft-scientific";
9
11
  export const FOUNDRY_REPAIR_ALLOWED_DATASET_TYPE = "process";
10
12
  export const FOUNDRY_REPAIR_EDIT_PATHS = Object.freeze([
11
13
  "processDataSet.modellingAndValidation.dataSourcesTreatmentAndRepresentativeness" +
@@ -31,6 +33,20 @@ export const FOUNDRY_REPAIR_SHARED_SCIENCE_PREFIXES = Object.freeze([
31
33
  "flowPropertyDataSet",
32
34
  "unitGroupDataSet",
33
35
  ]);
36
+ const scientificEditPrefixes = [
37
+ "processDataSet.exchanges",
38
+ "processDataSet.processInformation.quantitativeReference",
39
+ "processDataSet.processInformation.mathematicalRelations",
40
+ "processDataSet.processInformation.time",
41
+ "processDataSet.processInformation.geography",
42
+ "processDataSet.processInformation.technology",
43
+ "processDataSet.processInformation.dataSetInformation.name",
44
+ "processDataSet.processInformation.dataSetInformation.common:synonyms",
45
+ "processDataSet.processInformation.dataSetInformation.common:generalComment",
46
+ "processDataSet.processInformation.dataSetInformation.classificationInformation",
47
+ "processDataSet.modellingAndValidation.LCIMethod",
48
+ "processDataSet.modellingAndValidation.dataSourcesTreatmentAndRepresentativeness",
49
+ ];
34
50
  const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u;
35
51
  const shaPattern = /^[0-9a-f]{64}$/u;
36
52
  const blankTextSentinel = "FoundryRepairBlankLanguageText";
@@ -76,15 +92,21 @@ function selectionPath(value, code, label) {
76
92
  /** Parse the optional repair selection of a task-start spec against the independently selected sources. */
77
93
  export function parseFoundryRepairSelection(value, sources, resolveSelection = (file) => file) {
78
94
  const item = record(value, "task_spec_repair_invalid", "Repair selection");
79
- exact(item, ["kind", "contract", "before", "candidate", "predecessor"], "task_spec_repair_invalid", "Repair selection");
80
- if (item.kind !== FOUNDRY_REPAIR_SELECTION_KIND)
95
+ exact(item, item.kind === FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND
96
+ ? ["kind", "contract", "before", "candidate", "predecessor", "scientific"]
97
+ : ["kind", "contract", "before", "candidate", "predecessor"], "task_spec_repair_invalid", "Repair selection");
98
+ if (item.kind !== FOUNDRY_REPAIR_SELECTION_KIND &&
99
+ item.kind !== FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND)
81
100
  fail("task_spec_repair_invalid", "Repair selection kind is unsupported.");
82
101
  const contract = resolveSelection(selectionPath(item.contract, "task_spec_repair_invalid", "Repair contract"));
83
102
  const before = resolveSelection(selectionPath(item.before, "task_spec_repair_invalid", "Repair before rows"));
84
103
  const candidate = resolveSelection(selectionPath(item.candidate, "task_spec_repair_invalid", "Repair candidate rows"));
104
+ const scientific = item.kind === FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND
105
+ ? resolveSelection(selectionPath(item.scientific, "task_spec_repair_invalid", "Scientific repair evidence"))
106
+ : undefined;
85
107
  if (new Set([contract, before, candidate]).size !== 3)
86
108
  fail("task_spec_repair_invalid", "Repair selections must name three distinct files.");
87
- for (const selected of [contract, before, candidate])
109
+ for (const selected of [contract, before, candidate, ...(scientific ? [scientific] : [])])
88
110
  if (!sources.some((source) => source.path === selected))
89
111
  fail("task_spec_repair_invalid", "Repair contract, before rows and candidate rows must each be independently selected sources.");
90
112
  let predecessor = null;
@@ -98,11 +120,12 @@ export function parseFoundryRepairSelection(value, sources, resolveSelection = (
98
120
  predecessor = Object.freeze({ task_id: taskId, receipt_sha256: receipt });
99
121
  }
100
122
  return Object.freeze({
101
- kind: FOUNDRY_REPAIR_SELECTION_KIND,
123
+ kind: item.kind,
102
124
  contract,
103
125
  before,
104
126
  candidate,
105
127
  predecessor,
128
+ ...(scientific ? { scientific } : {}),
106
129
  });
107
130
  }
108
131
  function navigate(value, path) {
@@ -213,6 +236,14 @@ export function classifyRepairMetadataDiff(before, after) {
213
236
  ? { allowed: false, blockers }
214
237
  : { allowed: false, blockers: [{ path: "<unclassified>", reason: "structure_change" }] };
215
238
  }
239
+ /** Scientific review cannot widen administrative ownership, permissions or technical-header scope. */
240
+ export function assertScientificRepairPaths(before, candidate) {
241
+ const changes = collectRepairChangedPaths(blankRepairEditableText(before), blankRepairEditableText(candidate));
242
+ const blocked = changes.filter((changed) => changed.split(".").includes("common:other") ||
243
+ !scientificEditPrefixes.some((prefix) => changed === prefix || changed.startsWith(`${prefix}.`)));
244
+ if (blocked.length)
245
+ fail("repair_scientific_scope_unsupported", `Scientific repair changes protected identity, administrative or technical fields. Changed paths ${blocked.slice(0, 8).join(", ")}.`);
246
+ }
216
247
  /**
217
248
  * Validate one repair task: the CLI execution contract, the CLI-fresh before rows and the candidate rows
218
249
  * must agree on the exact same Process identities, every action must be a save_draft against an existing
@@ -255,6 +286,17 @@ export function readFoundryRepairScope(input) {
255
286
  if (beforeByIdentity.size !== candidateByIdentity.size ||
256
287
  [...beforeByIdentity.keys()].some((key) => !candidateByIdentity.has(key)))
257
288
  fail("repair_scope_identity_mismatch", "Repair candidate rows must cover exactly the selected before identities; versions are never minted.");
289
+ if (input.scientific)
290
+ for (const [key, candidate] of candidateByIdentity)
291
+ assertScientificRepairPaths(beforeByIdentity.get(key), candidate);
292
+ const scientific = input.scientific
293
+ ? readScientificRepairEvidence({
294
+ ...input.scientific,
295
+ beforeFile: input.beforeFile,
296
+ candidateFile: input.candidateFile,
297
+ userId: input.targetUserId,
298
+ })
299
+ : undefined;
258
300
  const changedPaths = [];
259
301
  const actions = native.contract.actions.map((action) => {
260
302
  const key = JSON.stringify([action.id, action.version]);
@@ -275,13 +317,22 @@ export function readFoundryRepairScope(input) {
275
317
  };
276
318
  const changed = collectRepairChangedPaths(beforePayload, candidatePayload);
277
319
  const verdict = classifyRepairMetadataDiff(beforePayload, candidatePayload);
278
- if (!verdict.allowed) {
279
- fail(verdict.blockers.some((blocker) => blocker.reason === "provider_impact_diagnostics_missing")
280
- ? "repair_provider_impact_diagnostics_missing"
281
- : "repair_metadata_scope_blocked", `Repair diff is outside the phase-1 metadata allowlist: ${verdict.blockers
320
+ if (!verdict.allowed && !scientific) {
321
+ const requiresProviderImpact = verdict.blockers.some((blocker) => blocker.reason === "provider_impact_diagnostics_missing");
322
+ const affectedPaths = verdict.blockers
282
323
  .slice(0, 8)
283
324
  .map((item) => item.path)
284
- .join(", ")}`);
325
+ .join(", ");
326
+ fail(requiresProviderImpact
327
+ ? "repair_provider_impact_diagnostics_missing"
328
+ : "repair_metadata_scope_blocked", requiresProviderImpact
329
+ ? `Scientific repair remains blocked for changed paths ${affectedPaths}. ` +
330
+ "Retain the exact before and candidate inputs for the Worker-owned frozen-input " +
331
+ "provider-impact diagnostic tracked at https://github.com/tiangong-lca/worker/issues/288, " +
332
+ "binding before/candidate content and affected provider/consumer closure. " +
333
+ "Foundry must separately verify field-bound source evidence, QA and curation " +
334
+ "before scientific repair can enter authorization."
335
+ : `Repair diff is outside the phase-1 metadata allowlist. Changed paths ${affectedPaths}.`);
285
336
  }
286
337
  changedPaths.push(...changed);
287
338
  return {
@@ -294,7 +345,8 @@ export function readFoundryRepairScope(input) {
294
345
  };
295
346
  });
296
347
  return Object.freeze({
297
- kind: FOUNDRY_REPAIR_SELECTION_KIND,
348
+ kind: scientific ? FOUNDRY_SCIENTIFIC_REPAIR_SELECTION_KIND : FOUNDRY_REPAIR_SELECTION_KIND,
349
+ ...(scientific ? { scientific } : {}),
298
350
  status: changedPaths.length ? "dispatchable" : "satisfied",
299
351
  contract_sha256: native.canonical_sha256,
300
352
  rows_sha256: native.rows_sha256,
@@ -0,0 +1,38 @@
1
+ import { type FoundryInputFact } from "./foundry-runtime-context.ts";
2
+ import type { FoundryRuntimeContext } from "./foundry-runtime-context.ts";
3
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
4
+ type Json = Record<string, unknown>;
5
+ export interface ScientificRepairRuntime {
6
+ readonly configuration: FoundryInputFact;
7
+ readonly executable: FoundryInputFact;
8
+ }
9
+ /** Deployment configuration is outside every task selection and survives the managed CLI host. */
10
+ export declare function readScientificRepairRuntime(excludedRoots: readonly string[]): ScientificRepairRuntime;
11
+ export interface ScientificRepairEvidence {
12
+ readonly schema: "tiangong-foundry.scientific-repair-evidence.v1";
13
+ readonly descriptor: FoundryInputFact;
14
+ readonly worker_input: FoundryInputFact;
15
+ readonly worker_report: FoundryInputFact;
16
+ readonly changes: FoundryInputFact;
17
+ readonly review: FoundryInputFact;
18
+ readonly sources: readonly FoundryInputFact[];
19
+ readonly runtime: ScientificRepairRuntime;
20
+ }
21
+ /** Exact JSON Pointer differences, with arrays of changed length covered as one complete value. */
22
+ export declare function scientificRepairChanges(before: unknown, candidate: unknown, pointer?: string): string[];
23
+ export declare function readScientificRepairEvidence(input: {
24
+ descriptorFile: string;
25
+ beforeFile: string;
26
+ candidateFile: string;
27
+ actorId: string;
28
+ userId: string;
29
+ selectedFiles: readonly string[];
30
+ excludedRuntimeRoots: readonly string[];
31
+ read: (file: string) => Buffer;
32
+ }): ScientificRepairEvidence;
33
+ /** Recompute the independently reviewed report with the exact trusted native bytes. */
34
+ export declare function runScientificRepairDiagnostic(evidence: ScientificRepairEvidence, directory: string): Json;
35
+ export declare function assertScientificRepairDiagnosticReport(report: Json, evidence: ScientificRepairEvidence): void;
36
+ /** The published CLI applies the evidence-bound edit proposal to the complete before document. */
37
+ export declare function applyScientificRepairProposals(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, temporary: string, evidence: ScientificRepairEvidence, beforeFile: string, candidateFile: string, directory: string): void;
38
+ export {};
@@ -0,0 +1,438 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import childProcess from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
7
+ import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
8
+ import { sha256Json } from "./identity-preflight-proof.js";
9
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
10
+ import { readRows } from "./import-curation/internal/runtime-io.js";
11
+ import { hasStructuredTraceEvidence } from "./import-curation/internal/workflow-patch-evidence.js";
12
+ import { reviewerPassValid, reviewerCoverageValid, reviewerContentBindingValid, } from "./final-delivery-review.js";
13
+ import { runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
14
+ const MAX_BYTES = 64 * 1024 * 1024;
15
+ const shaPattern = /^[0-9a-f]{64}$/u;
16
+ function fail(message) {
17
+ throw new FoundryContextError("repair_scientific_evidence_invalid", message);
18
+ }
19
+ function object(value, label) {
20
+ if (!value || typeof value !== "object" || Array.isArray(value))
21
+ fail(`${label} must be an object.`);
22
+ return value;
23
+ }
24
+ function exact(value, keys, label) {
25
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
26
+ fail(`${label} has missing or unsupported fields.`);
27
+ }
28
+ function text(value, label) {
29
+ if (typeof value !== "string" || !value.trim() || value.length > 16_384)
30
+ fail(`${label} must be bounded non-empty text.`);
31
+ return value;
32
+ }
33
+ function jsonFile(file, read) {
34
+ try {
35
+ return object(JSON.parse(read(file).toString("utf8")), "Scientific evidence");
36
+ }
37
+ catch (error) {
38
+ if (error instanceof FoundryContextError)
39
+ throw error;
40
+ return fail("Scientific evidence must be readable bounded JSON.");
41
+ }
42
+ }
43
+ function inside(root, file) {
44
+ const relative = path.relative(root, file);
45
+ return (relative === "" ||
46
+ (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)));
47
+ }
48
+ /** Deployment configuration is outside every task selection and survives the managed CLI host. */
49
+ export function readScientificRepairRuntime(excludedRoots) {
50
+ const configRoot = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
51
+ if (!path.isAbsolute(configRoot))
52
+ fail("Provider-impact deployment configuration requires an absolute configuration root.");
53
+ const file = path.join(configRoot, "tiangong-foundry", "provider-impact-runtime.json");
54
+ if (excludedRoots.some((root) => inside(root, file)))
55
+ fail("Provider-impact deployment configuration must be outside task, workspace and cache inputs.");
56
+ let value;
57
+ try {
58
+ const fact = captureFoundryInput(file);
59
+ if (excludedRoots.some((root) => inside(root, fact.path)))
60
+ fail("Provider-impact deployment configuration must be outside task, workspace and cache inputs.");
61
+ if (fact.bytes > 16_384)
62
+ fail("Provider-impact deployment configuration exceeds its bound.");
63
+ const configurationBytes = fs.readFileSync(file);
64
+ if (createHash("sha256").update(configurationBytes).digest("hex") !== fact.sha256 ||
65
+ captureFoundryInput(file).sha256 !== fact.sha256)
66
+ fail("Provider-impact deployment configuration changed while it was read.");
67
+ value = object(JSON.parse(configurationBytes.toString("utf8")), "Provider-impact deployment configuration");
68
+ exact(value, ["schema", "executable", "sha256"], "Provider-impact deployment configuration");
69
+ if (value.schema !== "tiangong-foundry.provider-impact-runtime.v1" ||
70
+ typeof value.executable !== "string" ||
71
+ !path.isAbsolute(value.executable) ||
72
+ typeof value.sha256 !== "string" ||
73
+ !shaPattern.test(value.sha256))
74
+ fail("Provider-impact deployment configuration must bind an absolute executable and independently trusted SHA-256.");
75
+ const executable = captureFoundryInput(value.executable);
76
+ if (excludedRoots.some((root) => inside(root, executable.path)) ||
77
+ executable.sha256 !== value.sha256)
78
+ fail("The provider-impact executable differs from its trusted deployment binding or resides in task inputs.");
79
+ return Object.freeze({ configuration: fact, executable });
80
+ }
81
+ catch (error) {
82
+ if (error instanceof FoundryContextError && error.code === "repair_scientific_evidence_invalid")
83
+ throw error;
84
+ return fail("Install the trusted provider-impact runtime configuration under the host tiangong-foundry configuration directory.");
85
+ }
86
+ }
87
+ /** Exact JSON Pointer differences, with arrays of changed length covered as one complete value. */
88
+ export function scientificRepairChanges(before, candidate, pointer = "") {
89
+ if (sha256Json(before ?? null) === sha256Json(candidate ?? null))
90
+ return [];
91
+ if (Array.isArray(before) && Array.isArray(candidate))
92
+ return Array.from({ length: Math.max(before.length, candidate.length) }, (_, index) => index < before.length && index < candidate.length
93
+ ? scientificRepairChanges(before[index], candidate[index], `${pointer}/${index}`)
94
+ : [`${pointer}/${index}`]).flat();
95
+ if (before &&
96
+ candidate &&
97
+ typeof before === "object" &&
98
+ typeof candidate === "object" &&
99
+ !Array.isArray(before) &&
100
+ !Array.isArray(candidate)) {
101
+ const left = before, right = candidate;
102
+ return [...new Set([...Object.keys(left), ...Object.keys(right)])].sort().flatMap((key) => {
103
+ const child = `${pointer}/${key.replaceAll("~", "~0").replaceAll("/", "~1")}`;
104
+ return Object.hasOwn(left, key) && Object.hasOwn(right, key)
105
+ ? scientificRepairChanges(left[key], right[key], child)
106
+ : [child];
107
+ });
108
+ }
109
+ return [pointer];
110
+ }
111
+ function pointerValue(value, pointer) {
112
+ let current = value;
113
+ for (const segment of pointer
114
+ .slice(1)
115
+ .split("/")
116
+ .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"))) {
117
+ if (!current || typeof current !== "object" || !Object.hasOwn(current, segment))
118
+ return { present: false };
119
+ current = current[segment];
120
+ }
121
+ return { present: true, value: current };
122
+ }
123
+ export function readScientificRepairEvidence(input) {
124
+ const read = (file) => {
125
+ if (!input.selectedFiles.includes(file))
126
+ fail("Every scientific evidence file must be an independently selected task source.");
127
+ const bytes = input.read(file);
128
+ if (bytes.length > MAX_BYTES)
129
+ fail("Scientific evidence exceeds its file bound.");
130
+ return bytes;
131
+ };
132
+ const descriptor = jsonFile(input.descriptorFile, read);
133
+ exact(descriptor, ["schema", "author_id", "worker_input", "worker_report", "changes", "sources", "review"], "Scientific repair descriptor");
134
+ if (descriptor.schema !== "tiangong-foundry.scientific-repair.v1" ||
135
+ descriptor.author_id !== input.actorId)
136
+ fail("Scientific repair descriptor must bind the registered task author.");
137
+ const fact = (value, label) => {
138
+ const reference = object(value, label);
139
+ exact(reference, ["file", "sha256"], label);
140
+ const file = text(reference.file, `${label} file`);
141
+ const observed = captureFoundryInput(file);
142
+ const bytes = read(file);
143
+ const hash = createHash("sha256").update(bytes).digest("hex");
144
+ const captured = captureFoundryInput(file);
145
+ if (reference.sha256 !== hash ||
146
+ observed.sha256 !== hash ||
147
+ captured.sha256 !== hash ||
148
+ observed.bytes !== bytes.length ||
149
+ captured.bytes !== bytes.length)
150
+ fail(`${label} selected bytes changed.`);
151
+ return captured;
152
+ };
153
+ const workerInput = fact(descriptor.worker_input, "Worker input");
154
+ const workerReport = fact(descriptor.worker_report, "Reviewed Worker report");
155
+ const changes = fact(descriptor.changes, "Scientific changes");
156
+ const review = fact(descriptor.review, "Independent scientific review");
157
+ if (!Array.isArray(descriptor.sources) ||
158
+ descriptor.sources.length < 1 ||
159
+ descriptor.sources.length > 128)
160
+ fail("Scientific repair requires bounded selected source evidence.");
161
+ const sources = descriptor.sources.map((source) => fact(source, "Scientific source"));
162
+ const all = [workerInput, workerReport, changes, review, ...sources];
163
+ if (new Set(all.map((item) => item.path)).size !== all.length)
164
+ fail("Scientific evidence selections must be distinct.");
165
+ const before = readRows(input.beforeFile, (file) => read(file).toString("utf8")).map((row, index) => datasetIdentity(row, index, "process"));
166
+ const candidate = readRows(input.candidateFile, (file) => read(file).toString("utf8")).map((row, index) => datasetIdentity(row, index, "process"));
167
+ const worker = jsonFile(workerInput.path, read);
168
+ const baseline = object(worker.baseline, "Worker baseline");
169
+ if (worker.schema_version !== "worker.provider-impact.input.v1" ||
170
+ worker.mode !== "matrix_only" ||
171
+ baseline.actor_user_id !== input.userId ||
172
+ !Array.isArray(worker.overlays))
173
+ fail("Worker input must bind the same actor and matrix-only provider-impact contract.");
174
+ const overlays = worker.overlays.map((value) => object(value, "Worker overlay"));
175
+ const changedRows = candidate.filter((row) => {
176
+ const old = before.find((value) => value.id === row.id && value.version === row.version);
177
+ return old && sha256Json(old.payload) !== sha256Json(row.payload);
178
+ });
179
+ if (overlays.length !== changedRows.length)
180
+ fail("Worker overlays must cover exactly the changed Process candidates.");
181
+ for (const row of changedRows) {
182
+ const matches = overlays.filter((overlay) => {
183
+ const identity = object(overlay.identity, "Worker overlay identity");
184
+ return (identity.dataset_type === "process" &&
185
+ identity.id === row.id &&
186
+ identity.version === row.version);
187
+ });
188
+ const old = before.find((value) => value.id === row.id && value.version === row.version);
189
+ const documents = Array.isArray(baseline.documents) ? baseline.documents : [];
190
+ const frozen = documents
191
+ .filter((value) => {
192
+ const record = object(value, "Worker baseline document");
193
+ const identity = object(record.identity, "Worker baseline identity");
194
+ return (identity.dataset_type === "process" &&
195
+ identity.id === row.id &&
196
+ identity.version === row.version);
197
+ })
198
+ .map((value) => object(value, "Worker baseline document"));
199
+ if (matches.length !== 1 ||
200
+ frozen.length !== 1 ||
201
+ frozen[0].state_code !== 0 ||
202
+ frozen[0].user_id !== input.userId ||
203
+ sha256Json(matches[0].document) !== sha256Json(row.payload) ||
204
+ sha256Json(frozen[0].document) !== sha256Json(old.payload))
205
+ fail("Worker baseline and overlays must contain the complete exact selected owner draft bodies.");
206
+ }
207
+ const changeReport = jsonFile(changes.path, read);
208
+ exact(changeReport, ["schema", "changes"], "Scientific changes");
209
+ if (changeReport.schema !== "tiangong-foundry.scientific-repair-changes.v1" ||
210
+ !Array.isArray(changeReport.changes) ||
211
+ changeReport.changes.length > 2_000)
212
+ fail("Scientific changes require a bounded field evidence ledger.");
213
+ const expectedChanges = new Set();
214
+ for (const row of changedRows) {
215
+ const old = before.find((value) => value.id === row.id && value.version === row.version);
216
+ for (const pointer of scientificRepairChanges(old.payload, row.payload))
217
+ expectedChanges.add(JSON.stringify([row.id, row.version, pointer]));
218
+ }
219
+ for (const value of changeReport.changes) {
220
+ const change = object(value, "Scientific field change");
221
+ exact(change, ["id", "version", "path", "before_sha256", "after_sha256", "basis", "evidence"], "Scientific field change");
222
+ const pointer = text(change.path, "Scientific field pointer");
223
+ const row = candidate.find((item) => item.id === change.id && item.version === change.version);
224
+ const old = before.find((item) => item.id === change.id && item.version === change.version);
225
+ if (!pointer.startsWith("/") ||
226
+ !row ||
227
+ !old ||
228
+ !expectedChanges.delete(JSON.stringify([change.id, change.version, pointer])) ||
229
+ change.before_sha256 !== sha256Json(pointerValue(old.payload, pointer)) ||
230
+ change.after_sha256 !== sha256Json(pointerValue(row.payload, pointer)))
231
+ fail("Scientific field evidence must cover every changed value exactly once with its before and candidate hashes.");
232
+ text(change.basis, "Scientific field basis");
233
+ if (!Array.isArray(change.evidence) || !change.evidence.length || change.evidence.length > 128)
234
+ fail("Every scientific field change requires structured source evidence.");
235
+ for (const item of change.evidence) {
236
+ const evidence = object(item, "Scientific field source evidence");
237
+ const source = sources.find((source) => evidence.source === source.path && evidence.source_sha256 === source.sha256);
238
+ if (!hasStructuredTraceEvidence(evidence) || !source)
239
+ fail("Scientific field evidence must bind a selected source and its exact bytes with a quote, trace, path or citation.");
240
+ const sourceText = read(source.path).toString("utf8");
241
+ const quoted = typeof evidence.quote === "string" &&
242
+ evidence.quote.trim().length > 0 &&
243
+ sourceText.includes(evidence.quote);
244
+ let located = false;
245
+ if (typeof evidence.path === "string" &&
246
+ evidence.path.startsWith("/") &&
247
+ !/~(?![01])/u.test(evidence.path)) {
248
+ try {
249
+ const value = object(pointerValue(JSON.parse(sourceText), evidence.path), "Scientific source locator");
250
+ located = value.present === true && evidence.value_sha256 === sha256Json(value);
251
+ }
252
+ catch {
253
+ located = false;
254
+ }
255
+ }
256
+ if (!quoted && !located)
257
+ fail("Scientific field evidence requires a quote present in the selected source bytes or an exact JSON Pointer with its located-value hash.");
258
+ }
259
+ }
260
+ if (expectedChanges.size)
261
+ fail("Scientific field evidence omits changed values.");
262
+ const reviewer = jsonFile(review.path, read);
263
+ const reviewerId = text(reviewer.reviewer_id, "Scientific reviewer identity");
264
+ const bindings = new Map([
265
+ ["before", captureFoundryInput(input.beforeFile)],
266
+ ["candidate", captureFoundryInput(input.candidateFile)],
267
+ ["worker_input", workerInput],
268
+ ["worker_report", workerReport],
269
+ ["changes", changes],
270
+ ...sources.map((source, index) => [`source_${index}`, source]),
271
+ ]);
272
+ const required = [...bindings.keys()];
273
+ if (reviewerId === input.actorId ||
274
+ reviewer.scope !== "scientific-content-and-provider-impact" ||
275
+ !reviewerPassValid(reviewer, reviewerId) ||
276
+ !reviewerCoverageValid(reviewer, required, bindings, "review") ||
277
+ !reviewerContentBindingValid(reviewer, required, bindings))
278
+ fail("Independent scientific review must pass with exact coverage of the before/candidate, source, field ledger and complete Worker input/report.");
279
+ const runtime = readScientificRepairRuntime(input.excludedRuntimeRoots);
280
+ if (worker.expected_worker_sha256 !== runtime.executable.sha256)
281
+ fail("Worker input must select the independently trusted deployed executable digest.");
282
+ return Object.freeze({
283
+ schema: "tiangong-foundry.scientific-repair-evidence.v1",
284
+ descriptor: captureFoundryInput(input.descriptorFile),
285
+ worker_input: workerInput,
286
+ worker_report: workerReport,
287
+ changes,
288
+ review,
289
+ sources: Object.freeze(sources),
290
+ runtime,
291
+ });
292
+ }
293
+ /** Recompute the independently reviewed report with the exact trusted native bytes. */
294
+ export function runScientificRepairDiagnostic(evidence, directory) {
295
+ const bound = evidence.runtime.executable;
296
+ const bytes = fs.readFileSync(bound.path);
297
+ if (createHash("sha256").update(bytes).digest("hex") !== bound.sha256)
298
+ fail("The deployed provider-impact executable changed before dispatch.");
299
+ const runtimeDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "foundry-provider-impact-"));
300
+ try {
301
+ const output = path.join(directory, "provider-impact-report.json");
302
+ const environment = createFoundryIsolatedChildEnvironment({ tempRoot: runtimeDirectory });
303
+ const result = childProcess.spawnSync(bound.path, [
304
+ "--provider-impact-input",
305
+ evidence.worker_input.path,
306
+ "--provider-impact-input-sha256",
307
+ evidence.worker_input.sha256,
308
+ "--provider-impact-out",
309
+ output,
310
+ ], {
311
+ cwd: directory,
312
+ env: environment,
313
+ shell: false,
314
+ encoding: "utf8",
315
+ timeout: 120_000,
316
+ maxBuffer: MAX_BYTES,
317
+ });
318
+ for (const [name, value] of [
319
+ ["stdout", result.stdout],
320
+ ["stderr", result.stderr],
321
+ ])
322
+ fs.writeFileSync(path.join(directory, `provider-impact.${name}.log`), value ?? "", {
323
+ flag: "wx",
324
+ mode: 0o600,
325
+ });
326
+ if (captureFoundryInput(bound.path).sha256 !== bound.sha256 ||
327
+ captureFoundryInput(evidence.runtime.configuration.path).sha256 !==
328
+ evidence.runtime.configuration.sha256)
329
+ fail("The trusted provider-impact deployment changed during native diagnosis.");
330
+ if (result.error || result.signal || result.status !== 0)
331
+ fail("The trusted Worker provider-impact diagnostic did not complete successfully. Inspect its indexed provider-impact stderr evidence and retain the original frozen inputs.");
332
+ const reportFact = captureFoundryInput(output);
333
+ if (reportFact.bytes > 128 * 1024 * 1024 || reportFact.sha256 !== evidence.worker_report.sha256)
334
+ fail("The complete native provider-impact output differs from the independently reviewed report.");
335
+ const report = object(JSON.parse(fs.readFileSync(output, "utf8")), "Native provider-impact report");
336
+ assertScientificRepairDiagnosticReport(report, evidence);
337
+ return report;
338
+ }
339
+ finally {
340
+ fs.rmSync(runtimeDirectory, { recursive: true, force: true });
341
+ }
342
+ }
343
+ export function assertScientificRepairDiagnosticReport(report, evidence) {
344
+ const runtime = object(report.runtime, "Native provider-impact runtime");
345
+ const counts = object(report.operation_counts, "Native provider-impact operation counts");
346
+ const scope = object(report.scope, "Native provider-impact scope");
347
+ const after = object(report.after, "Native provider-impact candidate phase");
348
+ const readiness = object(after.readiness, "Native provider-impact readiness");
349
+ if (report.schema_version !== "worker.provider-impact.report.v1" ||
350
+ report.mode !== "matrix_only" ||
351
+ report.status !== "diagnostic_complete" ||
352
+ report.input_sha256 !== evidence.worker_input.sha256 ||
353
+ runtime.worker_binary_sha256 !== evidence.runtime.executable.sha256 ||
354
+ counts.matrix_assemblies !== 2 ||
355
+ [
356
+ "factorizations",
357
+ "unit_solves",
358
+ "database_queries",
359
+ "queue_writes",
360
+ "object_store_operations",
361
+ ].some((key) => counts[key] !== 0) ||
362
+ scope.kind !== "supplied_finite_universe" ||
363
+ scope.frozen_selection_contract !== "worker.provider-impact.frozen-census.v1" ||
364
+ scope.online_census_verified !== false ||
365
+ scope.online_effective_selection_verified !== false ||
366
+ scope.scientific_qualified !== false ||
367
+ scope.save_admitted !== false ||
368
+ scope.publication_qualified !== false ||
369
+ !Array.isArray(readiness.blockers) ||
370
+ readiness.blockers.length ||
371
+ !Array.isArray(after.unresolved_balances) ||
372
+ after.unresolved_balances.length)
373
+ fail("Native provider-impact evidence must be exact matrix-only output with a complete candidate provider closure and explicit finite-universe limits.");
374
+ }
375
+ /** The published CLI applies the evidence-bound edit proposal to the complete before document. */
376
+ export function applyScientificRepairProposals(context, qualified, temporary, evidence, beforeFile, candidateFile, directory) {
377
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
378
+ const changes = object(JSON.parse(fs.readFileSync(evidence.changes.path, "utf8")), "Scientific changes").changes;
379
+ const before = readRows(beforeFile).map((row, index) => datasetIdentity(row, index, "process"));
380
+ const candidates = readRows(candidateFile).map((row, index) => datasetIdentity(row, index, "process"));
381
+ for (const [index, candidate] of candidates.entries()) {
382
+ const old = before.find((row) => row.id === candidate.id && row.version === candidate.version);
383
+ if (sha256Json(old.payload) === sha256Json(candidate.payload))
384
+ continue;
385
+ const selected = changes
386
+ .filter((change) => change.id === candidate.id && change.version === candidate.version)
387
+ .sort((left, right) => {
388
+ const rank = (value) => {
389
+ const previous = object(pointerValue(old.payload, String(value.path)), "Previous field");
390
+ const desired = object(pointerValue(candidate.payload, String(value.path)), "Candidate field");
391
+ return desired.present ? (previous.present ? 0 : 2) : 1;
392
+ };
393
+ const leftRank = rank(left), rightRank = rank(right);
394
+ return (leftRank - rightRank ||
395
+ (leftRank === 1
396
+ ? String(right.path).localeCompare(String(left.path), "en", { numeric: true })
397
+ : String(left.path).localeCompare(String(right.path), "en", { numeric: true })));
398
+ });
399
+ const operations = selected.flatMap((change) => {
400
+ const pointer = String(change.path);
401
+ const previous = object(pointerValue(old.payload, pointer), "Previous field");
402
+ const desired = object(pointerValue(candidate.payload, pointer), "Candidate field");
403
+ return [
404
+ ...(previous.present ? [{ op: "test", path: pointer, value: previous.value }] : []),
405
+ {
406
+ op: desired.present ? (previous.present ? "replace" : "add") : "remove",
407
+ path: pointer,
408
+ ...(desired.present ? { value: desired.value } : {}),
409
+ basis: change.basis,
410
+ evidence: change.evidence,
411
+ },
412
+ ];
413
+ });
414
+ const input = path.join(directory, `patch-input-${index}.json`);
415
+ const output = path.join(directory, `patch-output-${index}.json`);
416
+ fs.writeFileSync(input, JSON.stringify({
417
+ content: old.payload,
418
+ expectedDigest: createHash("sha256").update(JSON.stringify(old.payload)).digest("hex"),
419
+ operations,
420
+ }) + "\n", { mode: 0o600, flag: "wx" });
421
+ const run = runWorkflowLocalCliResult(context, qualified, temporary, [
422
+ "dataset",
423
+ "process",
424
+ "patch",
425
+ "--input",
426
+ input,
427
+ "--output",
428
+ output,
429
+ "--json",
430
+ ]);
431
+ run.validate(() => {
432
+ if (run.exit !== 0 ||
433
+ run.report.status !== "completed" ||
434
+ sha256Json(JSON.parse(fs.readFileSync(output, "utf8"))) !== sha256Json(candidate.payload))
435
+ fail("The published CLI patch owner did not produce the complete exact reviewed scientific candidate.");
436
+ });
437
+ }
438
+ }
@@ -136,7 +136,7 @@ export function selectFoundrySemanticInput(context, file) {
136
136
  const files = spec.submissions.map((part) => {
137
137
  const fact = select(part.file);
138
138
  if (fact.sha256 !== part.sha256)
139
- throw new FoundryContextError("semantic_input_changed", "Patch bytes do not match the submitted digest.");
139
+ throw new FoundryContextError("semantic_input_changed", "Patch raw file-byte SHA-256 differs from submissions[].sha256. Hash the exact file bytes; canonical payload digests are a separate binding.");
140
140
  readSelectedSemanticBytes(fact);
141
141
  return fact;
142
142
  });
@@ -0,0 +1,4 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ /** Derive a strict submission from current indexed facts without registering or executing it. */
4
+ export declare function prepareFoundryTaskInput(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], targetEntities: readonly string[], kind: "interaction" | "semantic", draftFile: string): import("./foundry-interaction-types.ts").FoundryInteractionInput | import("./foundry-semantic-input.ts").FoundrySemanticInput;