@tiangong-lca/foundry 0.1.17 → 0.1.19

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 (162) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +15 -3
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +45 -13
  5. package/docs/public-runtime-contract.md +85 -5
  6. package/docs/runtime-context-contract.md +22 -4
  7. package/docs/task-authorization-contract.md +15 -3
  8. package/docs/workspace-migration-contract.md +5 -3
  9. package/package-dist/assets/foundry-package-descriptor.json +541 -177
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +261 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +2 -2
  13. package/package-dist/scripts/lib/bundle-sample-utils.d.ts +4 -4
  14. package/package-dist/scripts/lib/bundle-source-context.d.ts +6 -4
  15. package/package-dist/scripts/lib/bundle-source-context.js +10 -8
  16. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +18 -6
  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/post-authoring.d.ts +11 -1
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +65 -9
  21. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  22. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  23. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  24. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  25. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  26. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  27. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  28. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  29. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  30. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  31. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  32. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  33. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  34. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  35. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  36. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  37. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  38. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  39. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  40. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  41. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  42. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  43. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  44. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  45. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  46. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  47. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  48. package/package-dist/scripts/lib/foundry-execution-admission.js +28 -3
  49. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  50. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  51. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  52. package/package-dist/scripts/lib/foundry-finalize-owners.js +126 -13
  53. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  54. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  55. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  56. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  57. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  58. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  59. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  60. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  61. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  62. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  63. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  64. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  65. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  66. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  67. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  68. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  69. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  70. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  71. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  72. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  73. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  74. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +2 -0
  75. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +96 -3
  76. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  77. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  78. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  79. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  80. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  81. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  82. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  83. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  84. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  85. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  86. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  87. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  88. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  89. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  90. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  91. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  92. package/package-dist/scripts/lib/foundry-runtime-identity.js +22 -2
  93. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  94. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  95. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  96. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  97. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  98. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  99. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  100. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  101. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  102. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  103. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  104. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  105. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  106. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  107. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  108. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  109. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  110. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  111. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  112. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  113. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  114. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  115. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  116. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  117. package/package-dist/scripts/lib/foundry-workflow-assessment.js +165 -34
  118. package/package-dist/scripts/lib/foundry-workflow-authorization.js +99 -5
  119. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  120. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  121. package/package-dist/scripts/lib/foundry-workflow-context.js +92 -22
  122. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  123. package/package-dist/scripts/lib/foundry-workflow-finalize.js +64 -3
  124. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  125. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  126. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  127. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +717 -0
  128. package/package-dist/scripts/lib/foundry-workflow-identity.js +26 -11
  129. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  130. package/package-dist/scripts/lib/foundry-workflow-io.js +102 -16
  131. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  132. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  133. package/package-dist/scripts/lib/foundry-workflow-semantic.js +65 -31
  134. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  135. package/package-dist/scripts/lib/foundry-workflow-state.js +165 -22
  136. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  137. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  138. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +6 -0
  139. package/package-dist/scripts/lib/identity-preflight-proof.js +92 -13
  140. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  141. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  142. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  143. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  144. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +1 -0
  145. package/package-dist/scripts/lib/import-curation/curation-gate.js +19 -1
  146. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  147. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  148. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  149. package/package-dist/scripts/package-entry.js +2 -3
  150. package/package-dist/scripts/public-api.d.ts +5 -0
  151. package/package-dist/scripts/public-api.js +2 -0
  152. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  153. package/package-dist/scripts/runtime-entry.js +42 -15
  154. package/package.json +6 -2
  155. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  156. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  157. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  158. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  159. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  160. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  161. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  162. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -9,21 +9,25 @@ import { runFoundryTaskOperation } from "./foundry-task-store.js";
9
9
  import { runTidasRowsValidation } from "./tidas-adapter.js";
10
10
  import { nativeFailureFileName, nativeFailureResultName, nativeValidationFailureEvidence, } from "./foundry-native-validation-failure.js";
11
11
  import { runDatasetCurationGate } from "./import-curation/curation-gate.js";
12
+ import { loadFoundryQualityReview } from "./foundry-quality-review.js";
12
13
  import { runDatasetAuthoringTaskBuild } from "./import-curation/authoring-packages.js";
13
14
  import { readRows } from "./import-curation/internal/runtime-io.js";
15
+ import { runFoundryTypedDatasetQa } from "./foundry-typed-flow-qa.js";
16
+ import { buildFoundryCurationQueue } from "./foundry-curation-queue.js";
17
+ import { projectFoundryValidationReferences, selectedFoundryExternalFlowReferences, } from "./foundry-validation-reference-context.js";
14
18
  import { parseFoundryPreparationCliReport } from "./foundry-preparation-cli-validation.js";
15
19
  import { routeFoundryDecisionAction } from "./foundry-decision-routing.js";
16
20
  import { prepareFoundryDecisionWork } from "./foundry-workflow-decisions.js";
17
21
  import { currentWorkflowState, workflowAssessmentQueueScopeSha256, } from "./foundry-workflow-state.js";
18
22
  import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
19
23
  import { applicableFoundryInteractionDigest, applicableFoundryInteractionProjection, } from "./foundry-interaction-projection.js";
20
- import { createWorkflowStageDirectory, createWorkflowDirectory, registerWorkflowStageFiles, runWorkflowLocalCli, runWorkflowLocalCliResult, } from "./foundry-workflow-io.js";
24
+ import { createWorkflowStageDirectory, createWorkflowDirectory, registerWorkflowStageFiles, runWorkflowLocalCliResult, } from "./foundry-workflow-io.js";
21
25
  function record(value) {
22
26
  if (!value || typeof value !== "object" || Array.isArray(value))
23
27
  throw new FoundryContextError("workflow_report_invalid", "Stage metadata must be an object.");
24
28
  return value;
25
29
  }
26
- function assertCurrentQueueBuild(context, queueDir, result, sets) {
30
+ function assertCurrentQueueBuild(context, queueDir, result, sets, external) {
27
31
  const invalid = () => {
28
32
  throw new FoundryContextError("workflow_queue_invalid", "The local curation queue report does not match current rows and bounded output files.");
29
33
  };
@@ -101,13 +105,15 @@ function assertCurrentQueueBuild(context, queueDir, result, sets) {
101
105
  if (!expectedPath(inputs.processes, processes.file) ||
102
106
  (flows ? !expectedPath(inputs.flows, flows.file) : inputs.flows !== null) ||
103
107
  !exactJson(inputs.support, supportPaths) ||
104
- !exactJson(inputs.external_flow_refs, []))
108
+ !exactJson(inputs.external_flow_refs, external ? [external.file] : []))
105
109
  invalid();
106
110
  const expectedHashes = new Map(selected.map((set) => {
107
111
  const file = set.file;
108
112
  readFoundryInput(context, file);
109
113
  return [file, captureFoundryInput(file).sha256];
110
114
  }));
115
+ if (external)
116
+ expectedHashes.set(external.file, captureFoundryInput(external.file).sha256);
111
117
  const hashes = object(object(report.hashes).inputs);
112
118
  const taskRecords = Array.isArray(report.tasks) ? report.tasks.map(object) : invalid();
113
119
  const taskIds = taskRecords.map((task) => {
@@ -155,7 +161,7 @@ function assertCurrentQueueBuild(context, queueDir, result, sets) {
155
161
  if (counts.process_rows !== processes.count ||
156
162
  counts.flow_rows !== (flows?.count ?? 0) ||
157
163
  counts.support_rows !== supportCount ||
158
- counts.external_flow_refs !== 0 ||
164
+ counts.external_flow_refs !== (external?.count ?? 0) ||
159
165
  counts.tasks !== expectedTasks ||
160
166
  counts.blockers !== blockers.length ||
161
167
  tasks.length !== expectedTasks ||
@@ -207,12 +213,19 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
207
213
  throw new FoundryContextError("workflow_assessment_invalid", "An assessment predecessor requires a selected row set.");
208
214
  let selectedState = null;
209
215
  let selectedInteraction = null;
216
+ let qualityReview = null;
210
217
  return runFoundryTaskOperation(context, {
211
218
  command: "dataset-workflow-assessment",
212
219
  options: {
213
220
  rows_report: rowsReport,
214
221
  context_reports: contextReports,
215
222
  identity_report: identityReport ?? null,
223
+ ...(() => {
224
+ const references = context.inputs.filter((fact) => path.basename(fact.path) === "foundry-reference-input.json");
225
+ return references.length
226
+ ? { reference_inputs: references.map(({ path: file, sha256 }) => ({ file, sha256 })) }
227
+ : {};
228
+ })(),
216
229
  ...(options.scopeType
217
230
  ? {
218
231
  scope_type: options.scopeType,
@@ -220,10 +233,16 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
220
233
  }
221
234
  : {}),
222
235
  ...(options.interactionSha256 ? { interaction_sha256: options.interactionSha256 } : {}),
236
+ ...(options.qualityReviewSha256
237
+ ? { quality_review_sha256: options.qualityReviewSha256 }
238
+ : {}),
223
239
  },
224
240
  validateCurrent(index) {
225
241
  const state = currentWorkflowState(context, index);
226
242
  selectedState = state;
243
+ if (state.qualityReviewSha256 !== (options.qualityReviewSha256 ?? null))
244
+ throw new FoundryContextError("quality_review_changed", "Quality review changed before reassessment.");
245
+ qualityReview = loadFoundryQualityReview(context, qualified, index);
227
246
  selectedInteraction = currentFoundryInteractionState(context, index);
228
247
  if (state.rows?.file !== rowsReport)
229
248
  throw new FoundryContextError("workflow_rows_changed", "Current rows changed before assessment.");
@@ -294,6 +313,30 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
294
313
  throw new FoundryContextError("workflow_rows_invalid", "A row set is invalid.");
295
314
  readFoundryInput(context, set.file);
296
315
  }
316
+ const processSet = selectedSets.find((set) => set.type === "process");
317
+ const reference = selectedState?.referenceInputs.get("process");
318
+ let qaReferenceFiles = [];
319
+ if (reference &&
320
+ processSet &&
321
+ (!options.scopeType || ["flow", "process"].includes(options.scopeType))) {
322
+ const intended = record(reference.value.input);
323
+ const current = captureFoundryInput(String(processSet.file));
324
+ if (current.sha256 !== intended.sha256 || current.bytes !== intended.bytes)
325
+ throw new FoundryContextError("reference_input_stale", "Select reference evidence for the current Process rows before assessment.");
326
+ if (!Array.isArray(reference.value.qa_files))
327
+ throw new FoundryContextError("reference_input_invalid", "Registered QA reference facts are invalid.");
328
+ qaReferenceFiles = reference.value.qa_files.map((value) => {
329
+ const fact = record(value);
330
+ if (typeof fact.path !== "string")
331
+ throw new FoundryContextError("reference_input_invalid", "Reference path is missing.");
332
+ const bytes = readFoundryInput(context, fact.path);
333
+ if (bytes.length !== fact.bytes ||
334
+ createHash("sha256").update(bytes).digest("hex") !== fact.sha256)
335
+ throw new FoundryContextError("reference_input_invalid", "Reference snapshot changed.");
336
+ return fact.path;
337
+ });
338
+ }
339
+ const referenceInputSha256 = qaReferenceFiles.length ? reference.entry.sha256 : null;
297
340
  const previousReport = previous
298
341
  ? record(JSON.parse(readFoundryInput(context, previous.path).toString("utf8")))
299
342
  : null;
@@ -353,7 +396,36 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
353
396
  else if (["contact", "source", "unitgroup", "flowproperty"].includes(String(set.type)))
354
397
  args.push("--support", set.file);
355
398
  }
356
- assertCurrentQueueBuild(context, queueDir, runWorkflowLocalCliResult(context, qualified, temporary, args), selectedSets);
399
+ // Existing Flow evidence closes only exact selected interfaces. It is never a row set or write target.
400
+ const externalRows = selectedFoundryExternalFlowReferences(readRows(processes.file, (name) => readFoundryInput(context, name).toString("utf8")), qaReferenceFiles.flatMap((file) => readRows(file, (name) => readFoundryInput(context, name).toString("utf8"))));
401
+ const external = externalRows.length
402
+ ? {
403
+ file: path.join(output, "selected-external-flow-refs.json"),
404
+ count: externalRows.length,
405
+ }
406
+ : undefined;
407
+ if (external) {
408
+ operation.writeJson(external.file, externalRows);
409
+ args.push("--external-flow-ref", external.file);
410
+ }
411
+ const currentQueueDir = queueDir;
412
+ if (qualified.cli.expectation.package_version === "0.4.0") {
413
+ const report = buildFoundryCurationQueue({
414
+ processes: processes.file,
415
+ flows: selectedSets.find((set) => set.type === "flow")?.file,
416
+ support: selectedSets
417
+ .filter((set) => ["contact", "source", "unitgroup", "flowproperty"].includes(String(set.type)))
418
+ .map((set) => String(set.file)),
419
+ external: external ? [external.file] : [],
420
+ outDir: currentQueueDir,
421
+ readInput: (file) => file === external?.file ? fs.readFileSync(file) : readFoundryInput(context, file),
422
+ });
423
+ assertCurrentQueueBuild(context, currentQueueDir, { report, exit: report.status === "ready" ? 0 : 1 }, selectedSets, external);
424
+ }
425
+ else {
426
+ const queue = runWorkflowLocalCliResult(context, qualified, temporary, args);
427
+ queue.validate(() => assertCurrentQueueBuild(context, currentQueueDir, queue, selectedSets, external));
428
+ }
357
429
  }
358
430
  const assessed = previousSets.map(record);
359
431
  const toAssess = options.scopeType
@@ -412,23 +484,67 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
412
484
  registerWorkflowStageFiles(context, operation, output);
413
485
  return result;
414
486
  }
415
- const qaDir = path.join(output, set.type, "qa");
487
+ let cliValidation;
488
+ let validationProjection;
489
+ const typed = qualified.cli.expectation.package_version === "0.4.0";
490
+ const datasetType = set.type;
491
+ const qaDir = path.join(output, datasetType, "qa");
492
+ const processReferenceFiles = datasetType === "process"
493
+ ? [
494
+ ...selectedSets
495
+ .filter((ref) => ["flow", "flowproperty", "unitgroup"].includes(String(ref.type)))
496
+ .map((ref) => String(ref.file)),
497
+ ...qaReferenceFiles,
498
+ ]
499
+ : [];
500
+ const validationDir = typed ? qaDir : path.join(output, datasetType, "cli-validation");
501
+ let validationInput = set.file;
502
+ let validationRows = [];
503
+ if (datasetType === "process") {
504
+ validationRows = readRows(set.file, (name) => readFoundryInput(context, name).toString("utf8"));
505
+ if (qaReferenceFiles.length) {
506
+ validationRows = projectFoundryValidationReferences(validationRows, qaReferenceFiles.flatMap((file) => readRows(file, (name) => readFoundryInput(context, name).toString("utf8"))));
507
+ validationInput = path.join(validationDir, "validation-only.process.rows.json");
508
+ operation.writeJson(validationInput, validationRows);
509
+ validationProjection = {
510
+ cli_validation_input: captureFoundryInput(validationInput),
511
+ cli_validation_source_rows: captureFoundryInput(set.file),
512
+ cli_validation_reference_input_sha256: referenceInputSha256,
513
+ cli_validation_reference_files: reference.value.qa_files,
514
+ };
515
+ }
516
+ }
416
517
  let qaReport;
417
- if (["flow", "process", "lifecyclemodel"].includes(set.type)) {
518
+ if (typed &&
519
+ (datasetType === "flow" ||
520
+ datasetType === "process" ||
521
+ datasetType === "lifecyclemodel")) {
522
+ const result = runFoundryTypedDatasetQa(context, qualified, temporary, (file, value) => operation.writeJson(file, value), datasetType, set.file, qaDir, { referenceFiles: processReferenceFiles, validationInput });
523
+ qaReport = result.reportFile;
524
+ if (datasetType === "process")
525
+ cliValidation = {
526
+ report: result.validationReportFile,
527
+ exit: result.exit,
528
+ ...(validationProjection ? { input: captureFoundryInput(validationInput) } : {}),
529
+ };
530
+ }
531
+ else if (["flow", "process", "lifecyclemodel"].includes(set.type)) {
418
532
  const qaArgv = ["qa", set.type, "--rows-file", set.file, "--out-dir", qaDir, "--json"];
419
- if (set.type === "process") {
420
- for (const referenceSet of selectedSets) {
421
- if (["flow", "flowproperty", "unitgroup"].includes(String(referenceSet.type))) {
422
- readFoundryInput(context, String(referenceSet.file));
423
- qaArgv.push("--reference-rows-file", String(referenceSet.file));
424
- }
425
- }
533
+ for (const file of processReferenceFiles) {
534
+ readFoundryInput(context, file);
535
+ qaArgv.push("--reference-rows-file", file);
426
536
  }
427
- const qa = runWorkflowLocalCli(context, qualified, temporary, qaArgv);
428
- const file = record(qa.files).report;
429
- if (typeof file !== "string")
430
- throw new FoundryContextError("workflow_qa_failed", "QA returned no report file.");
431
- qaReport = file;
537
+ const qa = runWorkflowLocalCliResult(context, qualified, temporary, qaArgv);
538
+ qaReport = qa.validate(() => {
539
+ if (![0, 2].includes(qa.exit))
540
+ throw new FoundryContextError("workflow_qa_failed", "QA did not return an admitted report.");
541
+ const file = record(qa.report.files).report;
542
+ if (typeof file !== "string")
543
+ throw new FoundryContextError("workflow_qa_failed", "QA returned no report file.");
544
+ // This locator is supplied by the child; retain its rejection as that call's failure.
545
+ qa.verifyReportFile(file);
546
+ return file;
547
+ });
432
548
  }
433
549
  else {
434
550
  qaReport = path.join(qaDir, "qa-not-required.json");
@@ -438,32 +554,36 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
438
554
  });
439
555
  }
440
556
  const gateDir = path.join(output, set.type, "curation");
441
- let cliValidation;
442
- if (set.type === "process") {
443
- const validationDir = path.join(output, set.type, "cli-validation");
557
+ if (set.type === "process" && !typed) {
444
558
  const validation = runWorkflowLocalCliResult(context, qualified, temporary, [
445
559
  "dataset",
446
560
  "validate",
447
561
  "--input",
448
- set.file,
562
+ validationInput,
449
563
  "--type",
450
564
  "process",
451
565
  "--out-dir",
452
566
  validationDir,
453
567
  "--json",
454
568
  ]);
455
- parseFoundryPreparationCliReport({
456
- report: validation.report,
457
- input: set.file,
458
- outDir: validationDir,
459
- rows: readRows(set.file),
460
- exit: validation.exit,
461
- });
462
569
  const reportFile = path.join(validationDir, "outputs", "validation-report.json");
463
- if (JSON.stringify(JSON.parse(fs.readFileSync(reportFile, "utf8"))) !==
464
- JSON.stringify(validation.report))
465
- throw new FoundryContextError("workflow_validation_invalid", "CLI validation file differs from its returned report.");
466
- cliValidation = { report: reportFile, exit: validation.exit };
570
+ validation.validate(() => {
571
+ parseFoundryPreparationCliReport({
572
+ report: validation.report,
573
+ input: validationInput,
574
+ outDir: validationDir,
575
+ rows: validationRows,
576
+ exit: validation.exit,
577
+ });
578
+ if (JSON.stringify(JSON.parse(fs.readFileSync(reportFile, "utf8"))) !==
579
+ JSON.stringify(validation.report))
580
+ throw new FoundryContextError("workflow_validation_invalid", "CLI validation file differs from its returned report.");
581
+ });
582
+ cliValidation = {
583
+ report: reportFile,
584
+ exit: validation.exit,
585
+ ...(validationProjection ? { input: captureFoundryInput(validationInput) } : {}),
586
+ };
467
587
  }
468
588
  const rewrite = identityRewriteReports.findLast((report) => report.dataset_type === set.type);
469
589
  const gate = runDatasetCurationGate({
@@ -476,6 +596,7 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
476
596
  rowsFile: set.file,
477
597
  schemaReport: schema.report_file,
478
598
  qaReport,
599
+ ...(set.type === "process" && qualityReview ? { qualityReview } : {}),
479
600
  outDir: gateDir,
480
601
  includeExecutionCommands: false,
481
602
  profile: operation.job.target_profile,
@@ -534,7 +655,14 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
534
655
  cli_validation_exit: cliValidation.exit,
535
656
  }
536
657
  : {}),
658
+ ...(validationProjection ?? {}),
537
659
  qa_report: qaReport,
660
+ ...(set.type === "process"
661
+ ? { runtime_qualification_sha256: qualified.qualification_sha256 }
662
+ : {}),
663
+ ...(set.type === "process" && qualityReview
664
+ ? { quality_review_sha256: qualityReview.receipt_sha256 }
665
+ : {}),
538
666
  curation_report: gateReport,
539
667
  curation_status: gate.status,
540
668
  curation_counts: gate.counts,
@@ -550,6 +678,9 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
550
678
  (options.scopeType || selectedInteraction)
551
679
  ? { queue_scope_sha256: queueScopeSha256 }
552
680
  : {}),
681
+ ...(referenceInputSha256 && ["flow", "process"].includes(set.type)
682
+ ? { reference_input_sha256: referenceInputSha256 }
683
+ : {}),
553
684
  ...(interactionDigest ? { interaction_digest: interactionDigest } : {}),
554
685
  ...(interactionContext ? { interaction_context: interactionContext } : {}),
555
686
  });
@@ -15,11 +15,14 @@ import { createFoundryExecutionCapsule } from "./foundry-execution-admission.js"
15
15
  import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
16
16
  import { createFoundryCommandSpec, createFileArtifactFact } from "./foundry-command-spec.js";
17
17
  import { parseFoundryCommandSpec } from "@tiangong-lca/cli/command-spec";
18
+ import { buildEdgeSupportPlan, isFoundryEdgeDraftType } from "./foundry-edge-support-plan.js";
19
+ import { readRows } from "./import-curation/internal/runtime-io.js";
18
20
  import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
19
21
  import { foundryRepairSelection, readFoundryRepairPreparation } from "./foundry-workflow-repair.js";
20
22
  import { createFoundryRepairHandoffPlan } from "./foundry-repair-handoff.js";
21
23
  import { readTaskJson } from "./foundry-task-io.js";
22
24
  import { assertFoundryInteractionWriteReady } from "./foundry-workflow-object-scope.js";
25
+ import { assertFoundryQualityReviewForExecution } from "./foundry-quality-review.js";
23
26
  export async function authorizeFoundryWorkflow(context, qualified, entries, selected, authentication = { mode: "oauth" }) {
24
27
  assertSelectedAuthorizationInput(selected);
25
28
  assertQualifiedFoundryRuntime(context, qualified);
@@ -41,9 +44,15 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
41
44
  if (typeof inputFile !== "string" || captureFoundryInput(inputFile).sha256 !== spec.input_sha256)
42
45
  throw new FoundryContextError("authorization_input_mismatch", "Approval input must match the exact current scope bytes.");
43
46
  readFoundryInput(context, inputFile);
47
+ if (spec.input_kind === "final_rows")
48
+ assertFoundryQualityReviewForExecution(context, qualified, entries, inputFile);
44
49
  if (spec.input_kind === "final_rows" && scope.status !== "ready_for_remote_write")
45
50
  throw new FoundryContextError("authorization_scope_not_ready", "Final-row approval requires a ready owner scope.");
46
- const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
51
+ let identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
52
+ const refreshIdentity = () => {
53
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
54
+ return identity;
55
+ };
47
56
  if (selected.executionContract) {
48
57
  try {
49
58
  readNativeDraftHandoff({
@@ -77,8 +86,9 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
77
86
  })),
78
87
  expectedPreviousSha256: spec.expected_previous_sha256,
79
88
  validateCurrent: (_, index) => current(index),
89
+ refreshIdentity,
80
90
  }, qualified);
81
- const authorization = await loadFoundryTaskAuthorization(context, identity, inputFile, qualified);
91
+ const authorization = await loadFoundryTaskAuthorization(context, identity, inputFile, qualified, refreshIdentity);
82
92
  return recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, {
83
93
  inputFile,
84
94
  approvedInputFile: inputFile,
@@ -173,7 +183,11 @@ async function authorizeFoundryRepair(context, qualified, entries, selected, aut
173
183
  reported.desired_sha256 !== action.desired_sha256)
174
184
  throw new FoundryContextError("authorization_repair_action_mismatch", "Registered repair actions must equal the signed native contract actions.");
175
185
  }
176
- const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
186
+ let identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
187
+ const refreshIdentity = () => {
188
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
189
+ return identity;
190
+ };
177
191
  const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
178
192
  const current = (index) => {
179
193
  assertSelectedAuthorizationInput(selected);
@@ -193,8 +207,9 @@ async function authorizeFoundryRepair(context, qualified, entries, selected, aut
193
207
  })),
194
208
  expectedPreviousSha256: spec.expected_previous_sha256,
195
209
  validateCurrent: (_, index) => current(index),
210
+ refreshIdentity,
196
211
  }, qualified);
197
- const authorization = await loadFoundryTaskAuthorization(context, identity, candidateFile, qualified);
212
+ const authorization = await loadFoundryTaskAuthorization(context, identity, candidateFile, qualified, refreshIdentity);
198
213
  return recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, {
199
214
  inputFile: candidateFile,
200
215
  approvedInputFile: candidateFile,
@@ -280,8 +295,34 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
280
295
  : {}),
281
296
  }));
282
297
  handoff = bindHandoffCommands(context, handoff, inputFile);
298
+ const commands = workflowObject(handoff.commands);
299
+ const edgeType = request.datasetType;
300
+ if (commands.commit &&
301
+ qualified.cli.expectation.package_version === "0.4.0" &&
302
+ isFoundryEdgeDraftType(edgeType)) {
303
+ const finalizePath = resolveFoundryOutput(context, path.resolve(context.assetRoot, String(scope.report)));
304
+ const finalized = workflowObject(JSON.parse(readFoundryInput(context, finalizePath).toString("utf8")));
305
+ const verifyPath = resolveFoundryOutput(context, path.resolve(context.assetRoot, String(workflowObject(finalized.files).remote_verify_report)));
306
+ const referenceEvidence = {
307
+ fact: captureFoundryInput(verifyPath),
308
+ report: JSON.parse(readFoundryInput(context, verifyPath).toString("utf8")),
309
+ };
310
+ commands.commit = buildEdgeSupportPlan(edgeType, captureFoundryInput(inputFile), {
311
+ project_ref: context.accountIntent.projectRef,
312
+ user_id: context.accountIntent.userId,
313
+ }, readRows(inputFile, (file) => readFoundryInput(context, file).toString("utf8")), referenceEvidence, undefined, request.executionContract && captureFoundryInput(request.executionContract.path));
314
+ commands.post_write_verify = null;
315
+ handoff.account_write_guard = {
316
+ ...workflowObject(handoff.account_write_guard),
317
+ execution_precondition: "Foundry must seal the exact Edge create plan for the verified owner.",
318
+ };
319
+ handoff.policy = {
320
+ ...workflowObject(handoff.policy),
321
+ commit_boundary: "The owner submits the sealed Edge create plan and verifies the exact draft and dependencies.",
322
+ };
323
+ }
283
324
  fs.writeFileSync(path.join(output, "handoff", "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
284
- const command = workflowObject(handoff.commands).commit;
325
+ const command = commands.commit;
285
326
  if (command) {
286
327
  const requiredActions = authorization.allowed_actions.filter((action) => request.datasetType === "flow"
287
328
  ? action === "elementary_flow_write" || action === "elementary_flow_create_new"
@@ -321,6 +362,59 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
321
362
  contractFile: request.executionContract.path,
322
363
  outDir: handoffDir,
323
364
  }), inputFile);
365
+ if (qualified.cli.expectation.package_version === "0.4.0") {
366
+ const contract = captureFoundryInput(request.executionContract.path);
367
+ const preparation = captureFoundryInput(request.repairPreparation.path);
368
+ readFoundryInput(context, preparation.path);
369
+ const before = captureFoundryInput(resolveFoundryInputPath(context, foundryRepairSelection(context).before));
370
+ const read = (file) => readFoundryInput(context, file).toString("utf8");
371
+ const preparedEvidence = workflowObject(workflowObject(JSON.parse(read(preparation.path))).evidence);
372
+ const preflight = Array.isArray(preparedEvidence.detail)
373
+ ? preparedEvidence.detail
374
+ .map(workflowObject)
375
+ .find((item) => item.role === "edge_preflight")
376
+ : undefined;
377
+ const ruleVerification = workflowObject(workflowObject(preflight?.report ?? {}).rule_verification ?? {});
378
+ const dependencyFact = Array.isArray(preparedEvidence.files)
379
+ ? preparedEvidence.files
380
+ .map(workflowObject)
381
+ .find((file) => file.role === "edge-repair:out/references/edge-support-precommit.json")
382
+ : undefined;
383
+ if (typeof dependencyFact?.path !== "string")
384
+ throw new FoundryContextError("repair_edge_scope_changed", "Guarded update requires the exact dependency report registered during preparation.");
385
+ const dependencies = resolveFoundryOutput(context, dependencyFact.path);
386
+ const dependencyFile = captureFoundryInput(dependencies);
387
+ if (dependencyFile.sha256 !== dependencyFact.sha256 ||
388
+ dependencyFile.bytes !== dependencyFact.bytes)
389
+ throw new FoundryContextError("repair_edge_scope_changed", "The registered dependency report changed after preparation.");
390
+ const commands = workflowObject(handoff.commands);
391
+ commands.commit = buildEdgeSupportPlan("process", captureFoundryInput(inputFile), {
392
+ project_ref: context.accountIntent.projectRef,
393
+ user_id: context.accountIntent.userId,
394
+ }, readRows(inputFile, read), {
395
+ fact: dependencyFile,
396
+ report: JSON.parse(read(dependencies)),
397
+ }, {
398
+ binding: {
399
+ before,
400
+ contract,
401
+ preparation,
402
+ rule_verification: ruleVerification,
403
+ },
404
+ rows: readRows(before.path, read),
405
+ });
406
+ commands.post_write_verify = null;
407
+ handoff.account_write_guard = {
408
+ target_user_id: context.accountIntent.userId,
409
+ commit_account_binding: "sealed_guarded_edge_update",
410
+ execution_precondition: "Compare the exact reviewed before document inside the Edge save-draft transaction.",
411
+ };
412
+ handoff.policy = {
413
+ commit_boundary: "The sealed owner attempt sends one guarded update and recovers exclusively through exact readback.",
414
+ post_write_verify_required: true,
415
+ compare_root_payload_required: true,
416
+ };
417
+ }
324
418
  fs.writeFileSync(path.join(handoffDir, "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
325
419
  const command = workflowObject(handoff.commands).commit;
326
420
  if (command) {
@@ -0,0 +1,44 @@
1
+ import type { SpawnSyncReturns } from "node:child_process";
2
+ import { FoundryContextError, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
3
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
4
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ export declare const workflowFailureCommand = "dataset-workflow-failure";
6
+ export declare const workflowFailureFile = "workflow-child-failure.json";
7
+ export declare const workflowFailureArtifactLimit: number;
8
+ export declare const workflowFailurePreviewLimit = 4096;
9
+ /** Bound the complete persisted wrapper, including JSON escaping, indentation and task fields. */
10
+ export declare function serializeWorkflowFailureResult(result: Record<string, unknown>): Buffer;
11
+ export declare class WorkflowChildFailure extends FoundryContextError {
12
+ readonly evidence: Record<string, unknown>;
13
+ retainedArtifact?: Readonly<{
14
+ path: string;
15
+ bytes: number;
16
+ sha256: string;
17
+ }>;
18
+ constructor(evidence: Record<string, unknown>);
19
+ }
20
+ export declare function bindWorkflowChildExecution(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, cliPath: string, argv: readonly string[], cwd?: string, executable?: string): Readonly<{
21
+ execution_id: `${string}-${string}-${string}-${string}-${string}`;
22
+ started_at_utc: string;
23
+ invocation: Readonly<{
24
+ argv: readonly string[];
25
+ argv_count: number;
26
+ argv_truncated: boolean;
27
+ executable: string;
28
+ executable_sha256: string;
29
+ cli_path: string;
30
+ cli_sha256: string;
31
+ argv_sha256: string;
32
+ cwd: string;
33
+ cwd_relative: string;
34
+ cwd_sha256: string;
35
+ qualification_sha256: string;
36
+ }>;
37
+ }>;
38
+ export declare function workflowChildFailure(execution: ReturnType<typeof bindWorkflowChildExecution>, child: SpawnSyncReturns<string>, kind: string, rejection?: unknown): WorkflowChildFailure;
39
+ /** Read-only proof of a failed local operation. Failure artifacts never enter producer lineage. */
40
+ export declare function readWorkflowChildFailure(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): {
41
+ entry: ArtifactEntry;
42
+ result: import("./foundry-task-types.ts").JsonRecord;
43
+ failure: import("./foundry-task-types.ts").JsonRecord;
44
+ } | null;