@tiangong-lca/foundry 0.1.17 → 0.1.18

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 (111) 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 +73 -5
  6. package/docs/runtime-context-contract.md +20 -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 +333 -139
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +258 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  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 +16 -6
  17. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +2 -1
  18. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +28 -1
  19. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  20. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  21. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  22. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  23. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  24. package/package-dist/scripts/lib/foundry-execution-admission.js +4 -1
  25. package/package-dist/scripts/lib/foundry-finalize-owners.js +64 -17
  26. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  27. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  28. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  29. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  30. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  31. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  32. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  33. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  34. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  35. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  36. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  37. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  38. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  39. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  40. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  41. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  42. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  43. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +2 -0
  44. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +25 -3
  45. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  46. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  47. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  48. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  49. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  50. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  51. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  52. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  53. package/package-dist/scripts/lib/foundry-runtime-identity.js +3 -1
  54. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  55. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  56. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  57. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  58. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  59. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  60. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  61. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  62. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  63. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  64. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  65. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  66. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  67. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  68. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  69. package/package-dist/scripts/lib/foundry-workflow-assessment.js +115 -22
  70. package/package-dist/scripts/lib/foundry-workflow-authorization.js +17 -4
  71. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  72. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  73. package/package-dist/scripts/lib/foundry-workflow-context.js +37 -8
  74. package/package-dist/scripts/lib/foundry-workflow-finalize.js +37 -0
  75. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  76. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  77. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  78. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +676 -0
  79. package/package-dist/scripts/lib/foundry-workflow-identity.js +10 -1
  80. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  81. package/package-dist/scripts/lib/foundry-workflow-io.js +76 -11
  82. package/package-dist/scripts/lib/foundry-workflow-semantic.js +27 -13
  83. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  84. package/package-dist/scripts/lib/foundry-workflow-state.js +165 -22
  85. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  86. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  87. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +5 -0
  88. package/package-dist/scripts/lib/identity-preflight-proof.js +73 -1
  89. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  90. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  91. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  92. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  93. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +1 -0
  94. package/package-dist/scripts/lib/import-curation/curation-gate.js +19 -1
  95. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  96. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  97. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  98. package/package-dist/scripts/package-entry.js +2 -3
  99. package/package-dist/scripts/public-api.d.ts +5 -0
  100. package/package-dist/scripts/public-api.js +2 -0
  101. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  102. package/package-dist/scripts/runtime-entry.js +42 -15
  103. package/package.json +6 -2
  104. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  105. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  106. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  107. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  108. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  109. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  110. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  111. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -6,6 +6,7 @@ import { captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, wri
6
6
  import { sha256Json } from "./identity-preflight-proof.js";
7
7
  import { fail, object, exact, timestamp, bytes, digest, taskPath, relative, readTaskBytes, readTaskJson, reference, facts, sameFact, shaPattern, maxIndexBytes, } from "./foundry-task-io.js";
8
8
  import { requiredTask, createTask, loadTask, bindAccountIntent, } from "./foundry-task-registration.js";
9
+ import { WorkflowChildFailure, workflowFailureCommand, workflowFailureFile, readWorkflowChildFailure, serializeWorkflowFailureResult, } from "./foundry-workflow-child-failure.js";
9
10
  /**
10
11
  * The synchronous verified snapshot of one task: registered job, bound account intent, hash-chained
11
12
  * artifact index and re-verified frozen sources. It is the same verification the locked metadata
@@ -16,7 +17,7 @@ export function readVerifiedTaskSnapshot(context, options = {}) {
16
17
  requiredTask(context);
17
18
  const task = loadTask(context, {});
18
19
  bindAccountIntent(context);
19
- const index = readIndex(context);
20
+ const index = readFoundryTaskArtifactIndex(context);
20
21
  const extra = index
21
22
  .filter((entry) => options.verifyCommands?.includes(entry.command))
22
23
  .map((entry) => ({
@@ -137,7 +138,7 @@ export async function assertFoundryTaskInputLineage(context, ancestorFile, deriv
137
138
  return fail("task_lineage_scope_mismatch", "Derived input is valid task output but does not descend from the approved input scope.");
138
139
  });
139
140
  }
140
- function readIndex(context) {
141
+ export function readFoundryTaskArtifactIndex(context) {
141
142
  const content = readTaskBytes(context, "artifact-index.jsonl", maxIndexBytes).toString("utf8");
142
143
  if (content && !content.endsWith("\n"))
143
144
  fail("task_index_incomplete", "Artifact index is truncated; do not infer missing entries as permission.");
@@ -278,6 +279,14 @@ function verifyInputs(context, task, index, inputs = context.inputs) {
278
279
  fail("input_changed", "Current operation input changed after selection.");
279
280
  }
280
281
  }
282
+ /** Reuse the producer/source verifier for every indexed artifact without selecting a new runtime. */
283
+ export function verifyFoundryTaskArtifactLineage(context, task, index) {
284
+ verifyInputs(context, task, index, index.map((entry) => ({
285
+ path: taskPath(context, entry.path),
286
+ bytes: entry.bytes,
287
+ sha256: entry.sha256,
288
+ })));
289
+ }
281
290
  function replaceIndex(context, entries, before) {
282
291
  const target = taskPath(context, "artifact-index.jsonl");
283
292
  const content = Buffer.from(entries.map((entry) => JSON.stringify(entry)).join("\n") + (entries.length ? "\n" : ""));
@@ -322,7 +331,7 @@ export async function runFoundryTaskOperation(context, input, operation) {
322
331
  : createTask(context, input.task ?? {});
323
332
  bindAccountIntent(context);
324
333
  const indexBefore = readTaskBytes(context, "artifact-index.jsonl", maxIndexBytes);
325
- const index = readIndex(context);
334
+ const index = readFoundryTaskArtifactIndex(context);
326
335
  verifyInputs(context, task, index);
327
336
  input.validateCurrent?.(Object.freeze(index.map((entry) => Object.freeze({ ...entry, receipt: Object.freeze({ ...entry.receipt }) }))));
328
337
  const inputScopeSha256 = sha256Json(context.inputs);
@@ -375,9 +384,22 @@ export async function runFoundryTaskOperation(context, input, operation) {
375
384
  const planRef = { path: planPath, sha256: digest(readTaskBytes(context, planPath)) };
376
385
  let receipt;
377
386
  let result;
387
+ let childFailure;
378
388
  if (fs.existsSync(taskPath(context, receiptPath))) {
379
389
  const old = readTaskJson(context, receiptPath);
380
390
  exact(old, ["schema", "mode", "status", "plan", "job_sha256", "outputs", "result"]);
391
+ if (old.status === "failed") {
392
+ const retained = readWorkflowChildFailure(context, index.filter((entry) => entry.operation_id === operationId));
393
+ if (!retained)
394
+ fail("workflow_failure_receipt_invalid", "Failed local operation has no indexed original diagnostic receipt; do not rerun it.");
395
+ const failure = new WorkflowChildFailure(retained.failure);
396
+ failure.retainedArtifact = {
397
+ path: taskPath(context, retained.entry.path),
398
+ bytes: retained.entry.bytes,
399
+ sha256: retained.entry.sha256,
400
+ };
401
+ throw failure;
402
+ }
381
403
  if (old.schema !== "tiangong-foundry.operation-receipt.v1" ||
382
404
  old.mode !== "deterministic-local" ||
383
405
  old.status !== "completed" ||
@@ -431,10 +453,54 @@ export async function runFoundryTaskOperation(context, input, operation) {
431
453
  sha256: digest(data),
432
454
  });
433
455
  },
456
+ registerExistingFiles(files) {
457
+ if (!active)
458
+ fail("task_operation_closed", "Operation writers cannot escape the task transaction.");
459
+ if (!files.length)
460
+ return;
461
+ const roster = [...files];
462
+ const verifyCurrent = () => {
463
+ assertFoundryWorkspaceWrite(context);
464
+ const current = loadTask(context, input.task ?? {});
465
+ if (current.jobSha256 !== task.jobSha256)
466
+ fail("task_operation_changed", "Task registration changed during output capture.");
467
+ verifyInputs(context, task, index);
468
+ };
469
+ const capture = (file) => {
470
+ assertFoundryWorkspaceWrite(context);
471
+ const relativePath = relative(context, file);
472
+ if (!/^(?:outputs|evidence)\//u.test(relativePath))
473
+ fail("task_output_role_invalid", "Existing outputs cannot register task control records.");
474
+ return { relativePath, fact: captureFoundryInput(taskPath(context, file)) };
475
+ };
476
+ // This read-only capture executes no owner command and writes no file bytes.
477
+ // Fresh writer/runtime/input bookends precede a second guarded read of every output.
478
+ verifyCurrent();
479
+ const captured = roster.map(capture);
480
+ verifyCurrent();
481
+ const rechecked = roster.map(capture);
482
+ for (const [position, current] of rechecked.entries()) {
483
+ const previous = captured[position];
484
+ if (current.relativePath !== previous.relativePath ||
485
+ !sameFact(current.fact, previous.fact))
486
+ fail("task_artifact_changed", "Existing output changed during capture.");
487
+ }
488
+ verifyCurrent();
489
+ for (const { relativePath, fact } of rechecked)
490
+ outputs.set(relativePath, {
491
+ path: relativePath,
492
+ bytes: fact.bytes,
493
+ sha256: fact.sha256,
494
+ });
495
+ },
434
496
  });
435
497
  const resultRef = jsonObjects.get(digest(bytes(result)));
436
498
  if (!resultRef)
437
499
  fail("task_result_not_recorded", "Local operation must write its exact returned report as an artifact.");
500
+ assertFoundryWorkspaceWrite(context);
501
+ const currentTask = loadTask(context, input.task ?? {});
502
+ if (currentTask.jobSha256 !== task.jobSha256)
503
+ fail("task_operation_changed", "Task registration changed before receipt publication.");
438
504
  verifyInputs(context, task, index);
439
505
  receipt = {
440
506
  schema: "tiangong-foundry.operation-receipt.v1",
@@ -447,6 +513,40 @@ export async function runFoundryTaskOperation(context, input, operation) {
447
513
  };
448
514
  writeFoundryArtifact(context, receiptPath, bytes(receipt));
449
515
  }
516
+ catch (error) {
517
+ if (!(error instanceof WorkflowChildFailure))
518
+ throw error;
519
+ // Retain diagnostic evidence only after the same fresh publication checks as success.
520
+ assertFoundryWorkspaceWrite(context);
521
+ const currentTask = loadTask(context, input.task ?? {});
522
+ if (currentTask.jobSha256 !== task.jobSha256)
523
+ fail("task_operation_changed", "Task registration changed before receipt publication.");
524
+ verifyInputs(context, task, index);
525
+ childFailure = error;
526
+ // Partial stage outputs are never indexed as completed business producers.
527
+ const failurePath = `evidence/failures/${operationId}/${workflowFailureFile}`;
528
+ result = {
529
+ schema: "tiangong-foundry.workflow-operation-failure.v1",
530
+ status: "failed",
531
+ task_id: context.taskId,
532
+ operation_id: operationId,
533
+ command: input.command,
534
+ input_scope_sha256: inputScopeSha256,
535
+ failure: error.evidence,
536
+ };
537
+ const content = serializeWorkflowFailureResult(result);
538
+ writeFoundryArtifact(context, failurePath, content);
539
+ receipt = {
540
+ schema: "tiangong-foundry.operation-receipt.v1",
541
+ mode: "deterministic-local",
542
+ status: "failed",
543
+ plan: planRef,
544
+ job_sha256: task.jobSha256,
545
+ outputs: [{ path: failurePath, bytes: content.length, sha256: digest(content) }],
546
+ result: { path: failurePath, sha256: digest(content) },
547
+ };
548
+ writeFoundryArtifact(context, receiptPath, bytes(receipt));
549
+ }
450
550
  finally {
451
551
  active = false;
452
552
  }
@@ -463,7 +563,7 @@ export async function runFoundryTaskOperation(context, input, operation) {
463
563
  sequence: next.length + 1,
464
564
  previous_sha256: next.at(-1)?.record_sha256 ?? null,
465
565
  operation_id: operationId,
466
- command: input.command,
566
+ command: receipt.status === "failed" ? workflowFailureCommand : input.command,
467
567
  input_scope_sha256: inputScopeSha256,
468
568
  receipt: receiptRef,
469
569
  ...fact,
@@ -472,6 +572,15 @@ export async function runFoundryTaskOperation(context, input, operation) {
472
572
  }
473
573
  if (next.length !== index.length)
474
574
  replaceIndex(context, next, indexBefore);
575
+ if (childFailure) {
576
+ const fact = receipt.outputs[0];
577
+ childFailure.retainedArtifact = {
578
+ path: taskPath(context, fact.path),
579
+ bytes: fact.bytes,
580
+ sha256: fact.sha256,
581
+ };
582
+ throw childFailure;
583
+ }
475
584
  return result;
476
585
  });
477
586
  }
@@ -91,7 +91,7 @@ export interface OperationPlan {
91
91
  export interface OperationReceipt {
92
92
  schema: "tiangong-foundry.operation-receipt.v1";
93
93
  mode: "deterministic-local";
94
- status: "completed";
94
+ status: "completed" | "failed";
95
95
  plan: FileReference;
96
96
  job_sha256: string;
97
97
  outputs: ArtifactFact[];
@@ -117,4 +117,5 @@ export interface FoundryTaskOperation {
117
117
  readonly nowIso: () => string;
118
118
  writeText(filePath: string, bytes: string | NodeJS.ArrayBufferView): void;
119
119
  writeJson(filePath: string, value: unknown): void;
120
+ registerExistingFiles(filePaths: readonly string[]): void;
120
121
  }
@@ -0,0 +1,8 @@
1
+ /** Queue interfaces from selected complete bodies; metadata is not exact-version evidence. */
2
+ export declare function selectedFoundryExternalFlowReferences(processRows: readonly unknown[], referenceRows: readonly unknown[]): Array<{
3
+ id: string;
4
+ version: string;
5
+ source: "selected_read_only_qa_reference";
6
+ }>;
7
+ /** Pure exact-version projection for CLI validation only; no scientific payload or write row changes. */
8
+ export declare function projectFoundryValidationReferences(processRows: readonly unknown[], referenceRows: readonly unknown[]): unknown[];
@@ -0,0 +1,115 @@
1
+ import { FoundryContextError } from "./foundry-runtime-error.js";
2
+ import { sha256Json } from "./identity-preflight-proof.js";
3
+ import { datasetRoot, unwrapDatasetPayload } from "./import-curation/internal/dataset-payload.js";
4
+ function object(value) {
5
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
6
+ }
7
+ function invalid(message) {
8
+ throw new FoundryContextError("workflow_validation_reference_invalid", message);
9
+ }
10
+ function flowKey(document) {
11
+ const flow = object(object(document)?.flowDataSet);
12
+ const information = object(object(flow?.flowInformation)?.dataSetInformation);
13
+ const publication = object(object(flow?.administrativeInformation)?.publicationAndOwnership);
14
+ const id = information?.["common:UUID"], version = publication?.["common:dataSetVersion"];
15
+ return typeof id === "string" && id && typeof version === "string" && version
16
+ ? JSON.stringify([id, version])
17
+ : null;
18
+ }
19
+ /** Queue interfaces from selected complete bodies; metadata is not exact-version evidence. */
20
+ export function selectedFoundryExternalFlowReferences(processRows, referenceRows) {
21
+ const available = new Set();
22
+ for (const row of referenceRows) {
23
+ const key = flowKey(unwrapDatasetPayload(row, "flow"));
24
+ if (key)
25
+ available.add(key);
26
+ }
27
+ const byId = new Map();
28
+ for (const row of processRows) {
29
+ const raw = datasetRoot(unwrapDatasetPayload(row, "process"), "process").exchanges?.exchange;
30
+ for (const exchange of raw ? (Array.isArray(raw) ? raw : [raw]) : []) {
31
+ const ref = object(object(exchange)?.referenceToFlowDataSet);
32
+ const id = ref?.["@refObjectId"];
33
+ if (typeof id !== "string" || !id)
34
+ continue;
35
+ const versions = byId.get(id) ?? new Set();
36
+ versions.add(typeof ref?.["@version"] === "string" ? ref["@version"] : "");
37
+ byId.set(id, versions);
38
+ }
39
+ }
40
+ return [...byId].flatMap(([id, versions]) => [...versions].every((version) => version && available.has(JSON.stringify([id, version])))
41
+ ? [...versions].map((version) => ({
42
+ id,
43
+ version,
44
+ source: "selected_read_only_qa_reference",
45
+ }))
46
+ : []);
47
+ }
48
+ /** Pure exact-version projection for CLI validation only; no scientific payload or write row changes. */
49
+ export function projectFoundryValidationReferences(processRows, referenceRows) {
50
+ const flows = new Map();
51
+ const remember = (document) => {
52
+ const key = flowKey(document);
53
+ if (!key)
54
+ return;
55
+ const hash = sha256Json(document), prior = flows.get(key);
56
+ if (prior && prior.hash !== hash)
57
+ invalid("Exact Flow evidence has conflicting complete bodies.");
58
+ if (!prior)
59
+ flows.set(key, { document, hash });
60
+ };
61
+ for (const row of referenceRows) {
62
+ const document = object(unwrapDatasetPayload(row, "flow"));
63
+ if (document?.flowDataSet)
64
+ remember(document);
65
+ }
66
+ return processRows.map((original) => {
67
+ const source = object(original);
68
+ if (!source)
69
+ invalid("Process validation row must be an object.");
70
+ const payload = unwrapDatasetPayload(original, "process");
71
+ const root = datasetRoot(payload, "process");
72
+ const rawContext = source.semantic_context;
73
+ const context = rawContext === undefined ? {} : object(rawContext);
74
+ if (!context)
75
+ invalid("Existing Process semantic context must be an object.");
76
+ const supplied = context.flow_documents;
77
+ if (supplied !== undefined && !Array.isArray(supplied))
78
+ invalid("Existing Process Flow documents must be an array.");
79
+ const documents = [];
80
+ const included = new Map();
81
+ for (const raw of supplied ?? []) {
82
+ const document = object(raw);
83
+ if (!document?.flowDataSet)
84
+ invalid("Existing Process context must contain complete Flow documents.");
85
+ const key = flowKey(document);
86
+ if (key) {
87
+ const prior = flows.get(key);
88
+ if (prior && prior.hash !== sha256Json(document))
89
+ invalid("Selected Flow evidence conflicts with original Process context.");
90
+ const priorHash = included.get(key);
91
+ if (priorHash && priorHash !== sha256Json(document))
92
+ invalid("Original Process context has conflicting exact Flow bodies.");
93
+ included.set(key, sha256Json(document));
94
+ }
95
+ documents.push(document);
96
+ }
97
+ const raw = root.exchanges?.exchange;
98
+ for (const exchange of raw ? (Array.isArray(raw) ? raw : [raw]) : []) {
99
+ const ref = object(object(exchange)?.referenceToFlowDataSet);
100
+ const id = ref?.["@refObjectId"], version = ref?.["@version"];
101
+ if (typeof id !== "string" || !id || typeof version !== "string" || !version)
102
+ continue;
103
+ const key = JSON.stringify([id, version]), selected = flows.get(key);
104
+ if (selected && !included.has(key)) {
105
+ documents.push(selected.document);
106
+ included.set(key, selected.hash);
107
+ }
108
+ }
109
+ const wrapper = payload === original ? { json: payload } : { ...source };
110
+ const projected = { ...wrapper, semantic_context: { ...context, flow_documents: documents } };
111
+ if (sha256Json(unwrapDatasetPayload(projected, "process")) !== sha256Json(payload))
112
+ invalid("Validation projection changed the Process scientific payload.");
113
+ return projected;
114
+ });
115
+ }
@@ -5,5 +5,6 @@ export interface FoundryAssessmentOptions {
5
5
  scopeType?: string;
6
6
  previousAssessment?: string;
7
7
  interactionSha256?: string | null;
8
+ qualityReviewSha256?: string | null;
8
9
  }
9
10
  export declare function assessFoundryWorkflowRows(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, rowsReport: string, contextReports: readonly string[], identityReport?: string, options?: FoundryAssessmentOptions): Promise<import("./foundry-task-types.ts").JsonRecord>;
@@ -9,21 +9,23 @@ 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 { projectFoundryValidationReferences, selectedFoundryExternalFlowReferences, } from "./foundry-validation-reference-context.js";
14
16
  import { parseFoundryPreparationCliReport } from "./foundry-preparation-cli-validation.js";
15
17
  import { routeFoundryDecisionAction } from "./foundry-decision-routing.js";
16
18
  import { prepareFoundryDecisionWork } from "./foundry-workflow-decisions.js";
17
19
  import { currentWorkflowState, workflowAssessmentQueueScopeSha256, } from "./foundry-workflow-state.js";
18
20
  import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
19
21
  import { applicableFoundryInteractionDigest, applicableFoundryInteractionProjection, } from "./foundry-interaction-projection.js";
20
- import { createWorkflowStageDirectory, createWorkflowDirectory, registerWorkflowStageFiles, runWorkflowLocalCli, runWorkflowLocalCliResult, } from "./foundry-workflow-io.js";
22
+ import { createWorkflowStageDirectory, createWorkflowDirectory, registerWorkflowStageFiles, runWorkflowLocalCliResult, } from "./foundry-workflow-io.js";
21
23
  function record(value) {
22
24
  if (!value || typeof value !== "object" || Array.isArray(value))
23
25
  throw new FoundryContextError("workflow_report_invalid", "Stage metadata must be an object.");
24
26
  return value;
25
27
  }
26
- function assertCurrentQueueBuild(context, queueDir, result, sets) {
28
+ function assertCurrentQueueBuild(context, queueDir, result, sets, external) {
27
29
  const invalid = () => {
28
30
  throw new FoundryContextError("workflow_queue_invalid", "The local curation queue report does not match current rows and bounded output files.");
29
31
  };
@@ -101,13 +103,15 @@ function assertCurrentQueueBuild(context, queueDir, result, sets) {
101
103
  if (!expectedPath(inputs.processes, processes.file) ||
102
104
  (flows ? !expectedPath(inputs.flows, flows.file) : inputs.flows !== null) ||
103
105
  !exactJson(inputs.support, supportPaths) ||
104
- !exactJson(inputs.external_flow_refs, []))
106
+ !exactJson(inputs.external_flow_refs, external ? [external.file] : []))
105
107
  invalid();
106
108
  const expectedHashes = new Map(selected.map((set) => {
107
109
  const file = set.file;
108
110
  readFoundryInput(context, file);
109
111
  return [file, captureFoundryInput(file).sha256];
110
112
  }));
113
+ if (external)
114
+ expectedHashes.set(external.file, captureFoundryInput(external.file).sha256);
111
115
  const hashes = object(object(report.hashes).inputs);
112
116
  const taskRecords = Array.isArray(report.tasks) ? report.tasks.map(object) : invalid();
113
117
  const taskIds = taskRecords.map((task) => {
@@ -155,7 +159,7 @@ function assertCurrentQueueBuild(context, queueDir, result, sets) {
155
159
  if (counts.process_rows !== processes.count ||
156
160
  counts.flow_rows !== (flows?.count ?? 0) ||
157
161
  counts.support_rows !== supportCount ||
158
- counts.external_flow_refs !== 0 ||
162
+ counts.external_flow_refs !== (external?.count ?? 0) ||
159
163
  counts.tasks !== expectedTasks ||
160
164
  counts.blockers !== blockers.length ||
161
165
  tasks.length !== expectedTasks ||
@@ -207,12 +211,19 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
207
211
  throw new FoundryContextError("workflow_assessment_invalid", "An assessment predecessor requires a selected row set.");
208
212
  let selectedState = null;
209
213
  let selectedInteraction = null;
214
+ let qualityReview = null;
210
215
  return runFoundryTaskOperation(context, {
211
216
  command: "dataset-workflow-assessment",
212
217
  options: {
213
218
  rows_report: rowsReport,
214
219
  context_reports: contextReports,
215
220
  identity_report: identityReport ?? null,
221
+ ...(() => {
222
+ const references = context.inputs.filter((fact) => path.basename(fact.path) === "foundry-reference-input.json");
223
+ return references.length
224
+ ? { reference_inputs: references.map(({ path: file, sha256 }) => ({ file, sha256 })) }
225
+ : {};
226
+ })(),
216
227
  ...(options.scopeType
217
228
  ? {
218
229
  scope_type: options.scopeType,
@@ -220,10 +231,16 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
220
231
  }
221
232
  : {}),
222
233
  ...(options.interactionSha256 ? { interaction_sha256: options.interactionSha256 } : {}),
234
+ ...(options.qualityReviewSha256
235
+ ? { quality_review_sha256: options.qualityReviewSha256 }
236
+ : {}),
223
237
  },
224
238
  validateCurrent(index) {
225
239
  const state = currentWorkflowState(context, index);
226
240
  selectedState = state;
241
+ if (state.qualityReviewSha256 !== (options.qualityReviewSha256 ?? null))
242
+ throw new FoundryContextError("quality_review_changed", "Quality review changed before reassessment.");
243
+ qualityReview = loadFoundryQualityReview(context, qualified, index);
227
244
  selectedInteraction = currentFoundryInteractionState(context, index);
228
245
  if (state.rows?.file !== rowsReport)
229
246
  throw new FoundryContextError("workflow_rows_changed", "Current rows changed before assessment.");
@@ -294,6 +311,30 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
294
311
  throw new FoundryContextError("workflow_rows_invalid", "A row set is invalid.");
295
312
  readFoundryInput(context, set.file);
296
313
  }
314
+ const processSet = selectedSets.find((set) => set.type === "process");
315
+ const reference = selectedState?.referenceInputs.get("process");
316
+ let qaReferenceFiles = [];
317
+ if (reference &&
318
+ processSet &&
319
+ (!options.scopeType || ["flow", "process"].includes(options.scopeType))) {
320
+ const intended = record(reference.value.input);
321
+ const current = captureFoundryInput(String(processSet.file));
322
+ if (current.sha256 !== intended.sha256 || current.bytes !== intended.bytes)
323
+ throw new FoundryContextError("reference_input_stale", "Select reference evidence for the current Process rows before assessment.");
324
+ if (!Array.isArray(reference.value.qa_files))
325
+ throw new FoundryContextError("reference_input_invalid", "Registered QA reference facts are invalid.");
326
+ qaReferenceFiles = reference.value.qa_files.map((value) => {
327
+ const fact = record(value);
328
+ if (typeof fact.path !== "string")
329
+ throw new FoundryContextError("reference_input_invalid", "Reference path is missing.");
330
+ const bytes = readFoundryInput(context, fact.path);
331
+ if (bytes.length !== fact.bytes ||
332
+ createHash("sha256").update(bytes).digest("hex") !== fact.sha256)
333
+ throw new FoundryContextError("reference_input_invalid", "Reference snapshot changed.");
334
+ return fact.path;
335
+ });
336
+ }
337
+ const referenceInputSha256 = qaReferenceFiles.length ? reference.entry.sha256 : null;
297
338
  const previousReport = previous
298
339
  ? record(JSON.parse(readFoundryInput(context, previous.path).toString("utf8")))
299
340
  : null;
@@ -353,7 +394,21 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
353
394
  else if (["contact", "source", "unitgroup", "flowproperty"].includes(String(set.type)))
354
395
  args.push("--support", set.file);
355
396
  }
356
- assertCurrentQueueBuild(context, queueDir, runWorkflowLocalCliResult(context, qualified, temporary, args), selectedSets);
397
+ // Existing Flow evidence closes only exact selected interfaces. It is never a row set or write target.
398
+ const externalRows = selectedFoundryExternalFlowReferences(readRows(processes.file, (name) => readFoundryInput(context, name).toString("utf8")), qaReferenceFiles.flatMap((file) => readRows(file, (name) => readFoundryInput(context, name).toString("utf8"))));
399
+ const external = externalRows.length
400
+ ? {
401
+ file: path.join(output, "selected-external-flow-refs.json"),
402
+ count: externalRows.length,
403
+ }
404
+ : undefined;
405
+ if (external) {
406
+ operation.writeJson(external.file, externalRows);
407
+ args.push("--external-flow-ref", external.file);
408
+ }
409
+ const currentQueueDir = queueDir;
410
+ const queue = runWorkflowLocalCliResult(context, qualified, temporary, args);
411
+ queue.validate(() => assertCurrentQueueBuild(context, currentQueueDir, queue, selectedSets, external));
357
412
  }
358
413
  const assessed = previousSets.map(record);
359
414
  const toAssess = options.scopeType
@@ -423,12 +478,19 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
423
478
  qaArgv.push("--reference-rows-file", String(referenceSet.file));
424
479
  }
425
480
  }
481
+ qaArgv.push(...qaReferenceFiles.flatMap((file) => ["--reference-rows-file", file]));
426
482
  }
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;
483
+ const qa = runWorkflowLocalCliResult(context, qualified, temporary, qaArgv);
484
+ qaReport = qa.validate(() => {
485
+ if (![0, 2].includes(qa.exit))
486
+ throw new FoundryContextError("workflow_qa_failed", "QA did not return an admitted report.");
487
+ const file = record(qa.report.files).report;
488
+ if (typeof file !== "string")
489
+ throw new FoundryContextError("workflow_qa_failed", "QA returned no report file.");
490
+ // This locator is supplied by the child; retain its rejection as that call's failure.
491
+ qa.verifyReportFile(file);
492
+ return file;
493
+ });
432
494
  }
433
495
  else {
434
496
  qaReport = path.join(qaDir, "qa-not-required.json");
@@ -439,31 +501,51 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
439
501
  }
440
502
  const gateDir = path.join(output, set.type, "curation");
441
503
  let cliValidation;
504
+ let validationProjection;
442
505
  if (set.type === "process") {
443
506
  const validationDir = path.join(output, set.type, "cli-validation");
507
+ let validationInput = String(set.file);
508
+ let validationRows = readRows(validationInput);
509
+ if (qaReferenceFiles.length) {
510
+ validationRows = projectFoundryValidationReferences(validationRows, qaReferenceFiles.flatMap((file) => readRows(file, (name) => readFoundryInput(context, name).toString("utf8"))));
511
+ validationInput = path.join(validationDir, "validation-only.process.rows.json");
512
+ operation.writeJson(validationInput, validationRows);
513
+ validationProjection = {
514
+ cli_validation_input: captureFoundryInput(validationInput),
515
+ cli_validation_source_rows: captureFoundryInput(String(set.file)),
516
+ cli_validation_reference_input_sha256: referenceInputSha256,
517
+ cli_validation_reference_files: reference.value.qa_files,
518
+ };
519
+ }
444
520
  const validation = runWorkflowLocalCliResult(context, qualified, temporary, [
445
521
  "dataset",
446
522
  "validate",
447
523
  "--input",
448
- set.file,
524
+ validationInput,
449
525
  "--type",
450
526
  "process",
451
527
  "--out-dir",
452
528
  validationDir,
453
529
  "--json",
454
530
  ]);
455
- parseFoundryPreparationCliReport({
456
- report: validation.report,
457
- input: set.file,
458
- outDir: validationDir,
459
- rows: readRows(set.file),
460
- exit: validation.exit,
461
- });
462
531
  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 };
532
+ validation.validate(() => {
533
+ parseFoundryPreparationCliReport({
534
+ report: validation.report,
535
+ input: validationInput,
536
+ outDir: validationDir,
537
+ rows: validationRows,
538
+ exit: validation.exit,
539
+ });
540
+ if (JSON.stringify(JSON.parse(fs.readFileSync(reportFile, "utf8"))) !==
541
+ JSON.stringify(validation.report))
542
+ throw new FoundryContextError("workflow_validation_invalid", "CLI validation file differs from its returned report.");
543
+ });
544
+ cliValidation = {
545
+ report: reportFile,
546
+ exit: validation.exit,
547
+ ...(validationProjection ? { input: captureFoundryInput(validationInput) } : {}),
548
+ };
467
549
  }
468
550
  const rewrite = identityRewriteReports.findLast((report) => report.dataset_type === set.type);
469
551
  const gate = runDatasetCurationGate({
@@ -476,6 +558,7 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
476
558
  rowsFile: set.file,
477
559
  schemaReport: schema.report_file,
478
560
  qaReport,
561
+ ...(set.type === "process" && qualityReview ? { qualityReview } : {}),
479
562
  outDir: gateDir,
480
563
  includeExecutionCommands: false,
481
564
  profile: operation.job.target_profile,
@@ -534,7 +617,14 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
534
617
  cli_validation_exit: cliValidation.exit,
535
618
  }
536
619
  : {}),
620
+ ...(validationProjection ?? {}),
537
621
  qa_report: qaReport,
622
+ ...(set.type === "process"
623
+ ? { runtime_qualification_sha256: qualified.qualification_sha256 }
624
+ : {}),
625
+ ...(set.type === "process" && qualityReview
626
+ ? { quality_review_sha256: qualityReview.receipt_sha256 }
627
+ : {}),
538
628
  curation_report: gateReport,
539
629
  curation_status: gate.status,
540
630
  curation_counts: gate.counts,
@@ -550,6 +640,9 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
550
640
  (options.scopeType || selectedInteraction)
551
641
  ? { queue_scope_sha256: queueScopeSha256 }
552
642
  : {}),
643
+ ...(referenceInputSha256 && ["flow", "process"].includes(set.type)
644
+ ? { reference_input_sha256: referenceInputSha256 }
645
+ : {}),
553
646
  ...(interactionDigest ? { interaction_digest: interactionDigest } : {}),
554
647
  ...(interactionContext ? { interaction_context: interactionContext } : {}),
555
648
  });