@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.
Files changed (116) 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 +10 -8
  5. package/docs/public-runtime-contract.md +53 -3
  6. package/docs/runtime-context-contract.md +7 -3
  7. package/docs/task-authorization-contract.md +2 -0
  8. package/package-dist/assets/foundry-package-descriptor.json +374 -136
  9. package/package-dist/scripts/foundry-facade.d.ts +6 -0
  10. package/package-dist/scripts/foundry-facade.js +38 -0
  11. package/package-dist/scripts/foundry-runtime.d.ts +3 -2
  12. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  13. package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
  14. package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
  15. package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
  16. package/package-dist/scripts/lib/final-delivery-review.js +108 -0
  17. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  18. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  19. package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  21. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  22. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  23. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  24. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  25. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  26. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  27. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  28. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  29. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  30. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  31. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  32. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  33. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +24 -0
  34. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +209 -0
  35. package/package-dist/scripts/lib/foundry-edge-session.d.ts +32 -0
  36. package/package-dist/scripts/lib/foundry-edge-session.js +203 -0
  37. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  38. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  39. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  40. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  41. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  42. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  43. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  44. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  45. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  46. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  47. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  48. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  49. package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
  50. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  51. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  52. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  53. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  54. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  55. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +21 -0
  56. package/package-dist/scripts/lib/foundry-owner-readback.js +61 -0
  57. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  58. package/package-dist/scripts/lib/foundry-package-contract.js +8 -2
  59. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  60. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  61. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  62. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  63. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  64. package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
  65. package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
  66. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  67. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
  68. package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
  69. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  70. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  71. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  72. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  73. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  74. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  75. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  76. package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
  77. package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
  78. package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
  79. package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
  80. package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
  81. package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
  82. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
  83. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  84. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  85. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  86. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  87. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  88. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  89. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  90. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  91. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  92. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  93. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  94. package/package-dist/scripts/lib/foundry-workflow-execution.js +57 -5
  95. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  96. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  97. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  98. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  99. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  100. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
  101. package/package-dist/scripts/lib/foundry-workflow-repair.js +204 -2
  102. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  103. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  104. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  105. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  106. package/package-dist/scripts/public-api.d.ts +6 -0
  107. package/package-dist/scripts/runtime-entry.js +15 -6
  108. package/package.json +5 -2
  109. package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
  110. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  111. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  112. package/specs/schemas/foundry-package-descriptor.schema.json +5 -2
  113. package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
  114. package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
  115. package/specs/schemas/foundry-task-start.schema.json +10 -2
  116. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -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;
@@ -0,0 +1,160 @@
1
+ import { registeredAssessmentSetProducerBase } from "./foundry-assessment-producer.js";
2
+ import path from "node:path";
3
+ import { captureFoundryInput, FoundryContextError, resolveFoundryOutput, } from "./foundry-runtime-context.js";
4
+ import { assertNotFoundrySessionFile, migrationCredentialPath } from "./foundry-private-path.js";
5
+ import { advanceFoundryInteractionState, currentFoundryInteractionState, parseFoundryInteractionInput, } from "./foundry-interaction-input.js";
6
+ import { parseFoundrySemanticInput, readSelectedSemanticBytes } from "./foundry-semantic-input.js";
7
+ import { currentFoundryObjectScopes, verifiedFoundryObjectProofs, } from "./foundry-workflow-object-scope.js";
8
+ import { foundryInteractionObjectKey } from "./foundry-interaction-scope.js";
9
+ import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
10
+ function invalid(message) {
11
+ throw new FoundryContextError("task_input_draft_invalid", message);
12
+ }
13
+ function exact(value, keys) {
14
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
15
+ invalid("Input draft has missing or unsupported fields.");
16
+ }
17
+ function selectedFile(context, value) {
18
+ if (typeof value !== "string" || !value || value.length > 4096 || /[\0\r\n]/u.test(value))
19
+ invalid("Input draft file selection must be one bounded path.");
20
+ const file = path.resolve(context.workspaceRoot, value);
21
+ if (migrationCredentialPath(path.relative(context.workspaceRoot, file)))
22
+ invalid("Private files cannot be input draft selections.");
23
+ assertNotFoundrySessionFile(file, context.accountIntent?.sessionReference);
24
+ const fact = captureFoundryInput(file);
25
+ readSelectedSemanticBytes(fact);
26
+ return fact;
27
+ }
28
+ function registeredFile(context, entries, value) {
29
+ const fact = selectedFile(context, value);
30
+ const registered = context.inputs.find((item) => item.path === fact.path) ??
31
+ entries.find((entry) => resolveFoundryOutput(context, entry.path) === fact.path);
32
+ if (!registered || registered.sha256 !== fact.sha256 || registered.bytes !== fact.bytes)
33
+ invalid("Input draft evidence must match a current registered source or artifact's raw file bytes.");
34
+ return fact;
35
+ }
36
+ function currentSemanticTasks(context, entries) {
37
+ const state = currentWorkflowState(context, entries);
38
+ if (!state.assessment)
39
+ invalid("Semantic input preparation requires a current registered assessment.");
40
+ const tasks = new Map();
41
+ for (const set of state.assessment.value.sets) {
42
+ const ownerBase = registeredAssessmentSetProducerBase(context, entries, set);
43
+ for (const raw of Array.isArray(set.decisions) ? set.decisions : []) {
44
+ const decision = workflowObject(raw);
45
+ if (typeof decision.task === "string" && typeof decision.kind === "string")
46
+ tasks.set(path.resolve(ownerBase, decision.task), decision.kind);
47
+ }
48
+ const manifest = registeredFile(context, entries, set.authoring_manifest);
49
+ const entry = entries.find((item) => resolveFoundryOutput(context, item.path) === manifest.path);
50
+ const value = readWorkflowArtifact(context, entry).value;
51
+ if (!Array.isArray(value.tasks))
52
+ invalid("Current assessment authoring manifest has no tasks.");
53
+ for (const raw of value.tasks) {
54
+ const files = workflowObject(workflowObject(raw).files);
55
+ if (typeof files.task_json !== "string")
56
+ invalid("Current authoring task path is missing.");
57
+ tasks.set(path.resolve(ownerBase, files.task_json), "patch");
58
+ }
59
+ }
60
+ return { assessment: state.assessment, tasks };
61
+ }
62
+ /** Derive a strict submission from current indexed facts without registering or executing it. */
63
+ export function prepareFoundryTaskInput(context, entries, targetEntities, kind, draftFile) {
64
+ const selected = selectedFile(context, draftFile);
65
+ let draft;
66
+ try {
67
+ draft = workflowObject(JSON.parse(readSelectedSemanticBytes(selected).toString("utf8")));
68
+ }
69
+ catch (error) {
70
+ if (error instanceof FoundryContextError)
71
+ throw error;
72
+ invalid("Input draft must contain complete JSON.");
73
+ }
74
+ const interaction = currentFoundryInteractionState(context, entries);
75
+ if (kind === "interaction") {
76
+ exact(draft, ["schema", "events"]);
77
+ if (draft.schema !== "tiangong-foundry.interaction-draft.v1" ||
78
+ !Array.isArray(draft.events) ||
79
+ draft.events.length > 16)
80
+ invalid("Interaction draft requires its v1 schema and at most 16 events.");
81
+ const objects = currentFoundryObjectScopes(context, entries);
82
+ const events = draft.events.map((raw) => {
83
+ const event = workflowObject(raw);
84
+ if (Object.hasOwn(event, "evidence_sha256"))
85
+ invalid("Interaction drafts select evidence_files. Submit existing strict digest descriptors directly through resume.");
86
+ const { evidence_files, object_scope, ...fields } = event;
87
+ if (!Array.isArray(evidence_files) || evidence_files.length > 16)
88
+ invalid("Each interaction draft event requires at most 16 evidence_files.");
89
+ const hashes = evidence_files.map((file) => registeredFile(context, entries, file).sha256);
90
+ let scope;
91
+ if (object_scope !== undefined) {
92
+ const selectedScope = workflowObject(object_scope);
93
+ exact(selectedScope, ["entity_id", "version"]);
94
+ if (typeof event.dataset_type !== "string" ||
95
+ typeof selectedScope.entity_id !== "string" ||
96
+ typeof selectedScope.version !== "string")
97
+ invalid("Object scope requires a concrete dataset type, entity_id and version.");
98
+ const current = objects.get(foundryInteractionObjectKey(event.dataset_type, selectedScope.entity_id, selectedScope.version));
99
+ if (!current)
100
+ invalid("Object scope must select one unique current registered row.");
101
+ scope = {
102
+ entity_id: current.entity_id,
103
+ version: current.version,
104
+ row_sha256: current.row_sha256,
105
+ };
106
+ }
107
+ return { ...fields, evidence_sha256: hashes, ...(scope ? { object_scope: scope } : {}) };
108
+ });
109
+ const descriptor = parseFoundryInteractionInput({
110
+ schema: "tiangong-foundry.interaction-input.v1",
111
+ task_id: context.taskId,
112
+ actor_id: context.actorId,
113
+ expected_state_sha256: interaction?.entry.sha256 ?? null,
114
+ events,
115
+ });
116
+ advanceFoundryInteractionState(interaction?.state ?? null, descriptor, interaction?.entry.sha256 ?? null, new Set([
117
+ ...context.inputs.map((item) => item.sha256),
118
+ ...entries.map((item) => item.sha256),
119
+ ]), new Set(targetEntities), verifiedFoundryObjectProofs(context, entries));
120
+ return descriptor;
121
+ }
122
+ exact(draft, ["schema", "submissions"]);
123
+ if (draft.schema !== "tiangong-foundry.semantic-draft.v1" ||
124
+ !Array.isArray(draft.submissions) ||
125
+ draft.submissions.length > 1000)
126
+ invalid("Semantic draft requires its v1 schema and at most 1000 submissions.");
127
+ const current = currentSemanticTasks(context, entries);
128
+ let bytes = selected.bytes;
129
+ const submissions = draft.submissions.map((raw) => {
130
+ const item = workflowObject(raw);
131
+ exact(item, [
132
+ "kind",
133
+ "authoring_task",
134
+ "file",
135
+ ...(Object.hasOwn(item, "decision_ids") ? ["decision_ids"] : []),
136
+ ]);
137
+ const task = registeredFile(context, entries, item.authoring_task);
138
+ if (current.tasks.get(task.path) !== item.kind)
139
+ invalid("Semantic work must select a matching task from the current assessment.");
140
+ const file = selectedFile(context, item.file);
141
+ bytes += file.bytes;
142
+ if (bytes > 64 * 1024 * 1024)
143
+ invalid("Semantic draft selection exceeds 64 MiB.");
144
+ return {
145
+ kind: item.kind,
146
+ authoring_task_sha256: task.sha256,
147
+ file: file.path,
148
+ sha256: file.sha256,
149
+ ...(Object.hasOwn(item, "decision_ids") ? { decision_ids: item.decision_ids } : {}),
150
+ };
151
+ });
152
+ return parseFoundrySemanticInput({
153
+ schema: "tiangong-foundry.semantic-input.v1",
154
+ task_id: context.taskId,
155
+ actor_id: context.actorId,
156
+ assessment_sha256: current.assessment.entry.sha256,
157
+ ...(interaction ? { interaction_sha256: interaction.entry.sha256 } : {}),
158
+ submissions,
159
+ });
160
+ }
@@ -2,7 +2,7 @@ import { assertTaskRuntimeIdentity } from "./foundry-task-runtime-adoption.js";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
- import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, resolveFoundryAsset, resolveFoundryOutput, resolveFoundryInputPath, writeFoundryArtifact, } from "./foundry-runtime-context.js";
5
+ import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, readFoundryInput, resolveFoundryAsset, resolveFoundryOutput, resolveFoundryInputPath, writeFoundryArtifact, } from "./foundry-runtime-context.js";
6
6
  import { sha256Json } from "./identity-preflight-proof.js";
7
7
  import { parseFoundryRepairSelection, readFoundryRepairScope, } from "./foundry-repair-scope.js";
8
8
  import { fail, object, exact, timestamp, bytes, digest, taskPath, readTaskBytes, readTaskJson, reference, facts, sameFact, maxDocumentBytes, } from "./foundry-task-io.js";
@@ -239,6 +239,8 @@ export function createTask(context, options) {
239
239
  : null;
240
240
  if (repairSelection && (options.targetEntities ?? []).join(",") !== "process")
241
241
  fail("task_spec_repair_invalid", "Phase 1 repair admits exactly one target entity type: process.");
242
+ if (repairSelection?.scientific && profileId !== "generic")
243
+ fail("repair_scientific_profile_unsupported", "Scientific repair currently admits the generic profile with complete validation and no profile waivers.");
242
244
  if (![
243
245
  "external-dataset-curated-import",
244
246
  "source-evidence-dataset-development",
@@ -328,6 +330,21 @@ export function createTask(context, options) {
328
330
  verifiedProjectRef: projectRef,
329
331
  stateCode: "0",
330
332
  relativePath: (file) => path.relative(context.workspaceRoot, file),
333
+ ...(repairSelection.scientific
334
+ ? {
335
+ scientific: {
336
+ descriptorFile: boundPath(repairSelection.scientific),
337
+ actorId: context.actorId,
338
+ selectedFiles: context.inputs.map((input) => input.path),
339
+ excludedRuntimeRoots: [
340
+ context.workspaceRoot,
341
+ context.cacheRoot,
342
+ ...context.inputs.map((input) => input.path),
343
+ ],
344
+ read: (file) => readFoundryInput(context, file, 64 * 1024 * 1024),
345
+ },
346
+ }
347
+ : {}),
331
348
  });
332
349
  repairDocuments = [
333
350
  [
@@ -340,6 +357,7 @@ export function createTask(context, options) {
340
357
  rows_sha256: scope.rows_sha256,
341
358
  changed_paths: [...scope.changed_paths],
342
359
  actions: scope.actions.map((action) => ({ ...action })),
360
+ ...(scope.scientific ? { scientific: scope.scientific } : {}),
343
361
  remote_state_verified: false,
344
362
  }),
345
363
  ],