@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
@@ -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,76 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ type RecordValue = Record<string, unknown>;
4
+ type PatchDestinations = {
5
+ input: string;
6
+ patch: string;
7
+ output: string;
8
+ directory: string;
9
+ writeJson: (file: string, value: unknown) => void;
10
+ writeText: (file: string, value: string) => void;
11
+ };
12
+ type PatchExecution = {
13
+ readInput: (file: string) => Buffer;
14
+ readResult: (file: string) => Buffer;
15
+ workspace: string;
16
+ run: (argv: string[]) => {
17
+ exit: number;
18
+ report: RecordValue;
19
+ validate: <T>(check: () => T) => T;
20
+ };
21
+ };
22
+ export declare function applyFoundryTypedAuthoringPatch(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, temporary: string, options: PatchDestinations & {
23
+ type: string;
24
+ packageDirectory: string;
25
+ }): {
26
+ report: {
27
+ schema_version: number;
28
+ generated_at_utc: string;
29
+ status: string;
30
+ input_path: string;
31
+ patch_path: string;
32
+ out_path: string;
33
+ row_count: number;
34
+ patch_count: number;
35
+ operation_count: number;
36
+ applied_operation_count: number;
37
+ evidence_count: number;
38
+ closed_action_item_count: number;
39
+ blockers: RecordValue[];
40
+ files: {
41
+ report: string;
42
+ patched_rows: string;
43
+ patch_evidence: string;
44
+ };
45
+ };
46
+ exit: number;
47
+ };
48
+ export declare function applyTypedAuthoringPatch(options: PatchDestinations & {
49
+ type?: string;
50
+ packageDirectory?: string;
51
+ requirePackage: boolean;
52
+ requireClosure: boolean;
53
+ }, execution: PatchExecution): {
54
+ report: {
55
+ schema_version: number;
56
+ generated_at_utc: string;
57
+ status: string;
58
+ input_path: string;
59
+ patch_path: string;
60
+ out_path: string;
61
+ row_count: number;
62
+ patch_count: number;
63
+ operation_count: number;
64
+ applied_operation_count: number;
65
+ evidence_count: number;
66
+ closed_action_item_count: number;
67
+ blockers: RecordValue[];
68
+ files: {
69
+ report: string;
70
+ patched_rows: string;
71
+ patch_evidence: string;
72
+ };
73
+ };
74
+ exit: number;
75
+ };
76
+ export {};
@@ -0,0 +1,237 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readFoundryInput } from "./foundry-runtime-context.js";
4
+ import { datasetIdentity, detectDatasetType } from "./import-curation/internal/dataset-payload.js";
5
+ import { readRows } from "./import-curation/internal/runtime-io.js";
6
+ import { operationHasEvidence, patchPayloadPatchSets, patchSetAuthoringPackage, patchSetDatasetId, patchSetOperations, } from "./import-curation/internal/workflow-authoring-tasks.js";
7
+ import { operationClosureKeys, taskActionItemKeys, } from "./import-curation/internal/workflow-patch-evidence.js";
8
+ import { assertWorkflowReportArtifact, runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
9
+ import { workflowObject } from "./foundry-workflow-state.js";
10
+ import { sha256Text } from "./identity-preflight-proof.js";
11
+ export function applyFoundryTypedAuthoringPatch(context, qualified, temporary, options) {
12
+ return applyTypedAuthoringPatch({ ...options, requirePackage: true, requireClosure: true }, {
13
+ readInput: (file) => readFoundryInput(context, file),
14
+ readResult: (file) => fs.readFileSync(assertWorkflowReportArtifact(context, file, options.directory)),
15
+ workspace: options.directory,
16
+ run: (argv) => runWorkflowLocalCliResult(context, qualified, temporary, argv),
17
+ });
18
+ }
19
+ export function applyTypedAuthoringPatch(options, execution) {
20
+ const rows = readRows(options.input, (file) => execution.readInput(file).toString("utf8"));
21
+ const patches = patchPayloadPatchSets(JSON.parse(fs.readFileSync(options.patch, "utf8")));
22
+ const candidates = [...rows];
23
+ const blockers = [];
24
+ const evidence = [];
25
+ let operationCount = 0;
26
+ if (!patches.length)
27
+ blockers.push({
28
+ code: "patch_payload_invalid",
29
+ message: "At least one dataset patch set is required.",
30
+ });
31
+ for (const [patchIndex, raw] of patches.entries()) {
32
+ const patch = workflowObject(raw);
33
+ const packageName = patchSetAuthoringPackage(patch);
34
+ const declaredId = patchSetDatasetId(patch);
35
+ const declaredVersion = patch.dataset_version ?? patch.version;
36
+ const declaredIndex = patch.row_index ?? patch.rowIndex;
37
+ if ((!packageName || !options.packageDirectory) &&
38
+ (options.requirePackage || options.requireClosure)) {
39
+ blockers.push({ code: "authoring_package_required", patch_index: patchIndex });
40
+ continue;
41
+ }
42
+ const packageBytes = packageName && options.packageDirectory
43
+ ? execution.readInput(path.join(options.packageDirectory, path.basename(packageName)))
44
+ : null;
45
+ const authoring = packageBytes
46
+ ? workflowObject(JSON.parse(packageBytes.toString("utf8")))
47
+ : null;
48
+ const packageId = authoring?.entity_id ?? authoring?.process_id;
49
+ const packageVersion = authoring?.version;
50
+ const matches = rows.flatMap((row, index) => {
51
+ const type = options.type ?? detectDatasetType(row);
52
+ if (!type)
53
+ return [];
54
+ const identity = datasetIdentity(row, index, type);
55
+ const expectedIndex = authoring ||
56
+ declaredIndex === undefined ||
57
+ (/^\d+$/u.test(String(declaredIndex)) && Number(declaredIndex) === index);
58
+ const expectedId = !declaredId || identity.id === declaredId;
59
+ const expectedVersion = declaredVersion === undefined || identity.version === declaredVersion;
60
+ const expectedPackage = !authoring || (identity.id === packageId && identity.version === packageVersion);
61
+ return expectedIndex && expectedId && expectedVersion && expectedPackage
62
+ ? [{ index, identity, type }]
63
+ : [];
64
+ });
65
+ const selected = matches[0];
66
+ const reject = (code, message) => blockers.push({
67
+ code,
68
+ message,
69
+ patch_index: patchIndex,
70
+ row_index: selected?.index,
71
+ dataset_id: selected?.identity.id ?? declaredId,
72
+ dataset_version: selected?.identity.version ?? declaredVersion,
73
+ });
74
+ const contradictoryIndex = authoring &&
75
+ declaredIndex !== undefined &&
76
+ (!/^\d+$/u.test(String(declaredIndex)) || Number(declaredIndex) !== selected?.index);
77
+ if (matches.length !== 1 ||
78
+ contradictoryIndex ||
79
+ (!authoring && !declaredId && declaredIndex === undefined)) {
80
+ reject("authoring_patch_scope_mismatch", "Select one exact dataset row and its required authoring package.");
81
+ continue;
82
+ }
83
+ const { index: rowIndex, identity: { id, version }, type, } = selected;
84
+ const operationName = `dataset ${type === "lifecyclemodel" ? "model" : type} patch`;
85
+ const rawOperations = patchSetOperations(patch);
86
+ if (!rawOperations?.length) {
87
+ reject("patch_operations_missing", "Authoring patch must contain an operation.");
88
+ continue;
89
+ }
90
+ operationCount += rawOperations.length;
91
+ const required = taskActionItemKeys({
92
+ ...authoring,
93
+ action_items: Array.isArray(authoring?.action_items)
94
+ ? authoring.action_items.filter((value) => {
95
+ const item = workflowObject(value);
96
+ return (item.ai_required !== false &&
97
+ ![
98
+ "identity_decision_authoring",
99
+ "classification_decision_authoring",
100
+ "location_decision_authoring",
101
+ ].includes(String(item.action_kind ?? item.actionKind)));
102
+ })
103
+ : [],
104
+ });
105
+ const closed = rawOperations.flatMap((item) => item.op === "test" ? [] : operationClosureKeys(item));
106
+ const matchesClosure = (left, right) => {
107
+ const [leftCode, leftPath] = left.split("\u0000");
108
+ const [rightCode, rightPath] = right.split("\u0000");
109
+ return leftCode === rightCode && (!leftPath || !rightPath || leftPath === rightPath);
110
+ };
111
+ if (options.requireClosure &&
112
+ (closed.some((closure) => !required.some((item) => matchesClosure(closure, item))) ||
113
+ required.some((item) => !closed.some((closure) => matchesClosure(closure, item))))) {
114
+ reject("authoring_action_item_closure_invalid", "Patch closure must match the selected authoring package.");
115
+ continue;
116
+ }
117
+ if (rawOperations.some((item) => item.op !== "test" && !operationHasEvidence(item))) {
118
+ reject("patch_evidence_required", "Each mutation needs its source evidence or basis.");
119
+ continue;
120
+ }
121
+ const row = workflowObject(candidates[rowIndex]);
122
+ const original = datasetIdentity(row, rowIndex, type);
123
+ const wrapper = original.payload === row
124
+ ? null
125
+ : Object.keys(row).find((name) => row[name] === original.payload);
126
+ const prefix = wrapper ? `/${wrapper}` : "";
127
+ const operations = rawOperations.map((item) => {
128
+ const operation = workflowObject(item);
129
+ const location = typeof operation.path === "string" ? operation.path : "";
130
+ return {
131
+ op: operation.op,
132
+ path: location.startsWith(prefix + "/") ? location.slice(prefix.length) : null,
133
+ ...(Object.hasOwn(operation, "value") ? { value: operation.value } : {}),
134
+ ...(operation.op === "test"
135
+ ? {}
136
+ : {
137
+ basis: typeof operation.basis === "string" && operation.basis.trim()
138
+ ? operation.basis
139
+ : "Source evidence retained in the selected Foundry authoring patch.",
140
+ }),
141
+ };
142
+ });
143
+ if (operations.some((operation) => operation.path === null)) {
144
+ reject("patch_path_invalid", "Authoring patch pointer must select a field inside the dataset payload.");
145
+ continue;
146
+ }
147
+ const input = path.join(execution.workspace, `request-${patchIndex + 1}.json`);
148
+ const output = path.join(execution.workspace, `result-${patchIndex + 1}.json`);
149
+ options.writeJson(input, {
150
+ content: original.payload,
151
+ expectedDigest: sha256Text(JSON.stringify(original.payload)),
152
+ operations,
153
+ });
154
+ const result = execution.run([
155
+ ...operationName.split(" "),
156
+ "--input",
157
+ input,
158
+ "--output",
159
+ output,
160
+ "--json",
161
+ ]);
162
+ if (result.exit !== 0) {
163
+ const error = workflowObject(result.report.error);
164
+ reject(String(error.code), String(error.message));
165
+ continue;
166
+ }
167
+ const content = result.validate(() => {
168
+ const bytes = execution.readResult(output);
169
+ const payload = workflowObject(JSON.parse(bytes.toString("utf8")));
170
+ const identity = datasetIdentity(payload, rowIndex, type);
171
+ const artifact = Array.isArray(result.report.artifacts)
172
+ ? workflowObject(result.report.artifacts[0])
173
+ : {};
174
+ if (result.report.schemaVersion !== 1 ||
175
+ result.report.operation !== operationName ||
176
+ result.report.status !== "completed" ||
177
+ result.report.outcome !== "content_processed" ||
178
+ result.report.error !== null ||
179
+ artifact.path !== output ||
180
+ artifact.purpose !== "complete_result" ||
181
+ artifact.bytes !== bytes.length ||
182
+ workflowObject(result.report.data).contentDigest !== sha256Text(JSON.stringify(payload)) ||
183
+ identity.id !== id ||
184
+ identity.version !== version)
185
+ throw new Error("Typed patch receipt does not bind the exact output and selected row.");
186
+ return payload;
187
+ });
188
+ candidates[rowIndex] = wrapper ? { ...row, [wrapper]: content } : content;
189
+ rawOperations.forEach((item, operationIndex) => {
190
+ if (item.op === "test")
191
+ return;
192
+ evidence.push({
193
+ row_index: rowIndex,
194
+ dataset_id: id,
195
+ dataset_version: version,
196
+ patch_index: patchIndex,
197
+ operation_index: operationIndex,
198
+ op: item.op,
199
+ path: item.path,
200
+ basis: item.basis ?? null,
201
+ evidence: item.evidence ?? null,
202
+ resolution: item.resolution ?? null,
203
+ authoring_package: packageName || null,
204
+ authoring_package_sha256: packageBytes ? sha256Text(packageBytes.toString("utf8")) : null,
205
+ closes_action_items: operationClosureKeys(item).map((key) => {
206
+ const [code, itemPath] = key.split("\u0000");
207
+ return { code, path: itemPath || null };
208
+ }),
209
+ });
210
+ });
211
+ }
212
+ const accepted = !blockers.length;
213
+ const reportFile = path.join(options.directory, "outputs", "dataset-patch-apply-report.json");
214
+ const evidenceFile = path.join(options.directory, "outputs", "patch-evidence.jsonl");
215
+ options.writeText(options.output, (accepted ? candidates : rows).map((row) => JSON.stringify(row) + "\n").join(""));
216
+ options.writeText(evidenceFile, accepted ? evidence.map((row) => JSON.stringify(row) + "\n").join("") : "");
217
+ const report = {
218
+ schema_version: 1,
219
+ generated_at_utc: new Date().toISOString(),
220
+ status: accepted ? "completed" : "blocked",
221
+ input_path: options.input,
222
+ patch_path: options.patch,
223
+ out_path: options.output,
224
+ row_count: rows.length,
225
+ patch_count: patches.length,
226
+ operation_count: operationCount,
227
+ applied_operation_count: accepted ? evidence.length : 0,
228
+ evidence_count: accepted ? evidence.length : 0,
229
+ closed_action_item_count: accepted
230
+ ? evidence.reduce((sum, row) => sum + row.closes_action_items.length, 0)
231
+ : 0,
232
+ blockers,
233
+ files: { report: reportFile, patched_rows: options.output, patch_evidence: evidenceFile },
234
+ };
235
+ options.writeJson(reportFile, report);
236
+ return { report, exit: accepted ? 0 : 1 };
237
+ }
@@ -0,0 +1,11 @@
1
+ export declare function createTypedContextCommand(type: string, output: string): string[];
2
+ export declare function projectTypedContext(type: string, output: string, receipt: unknown, bytes: Buffer): {
3
+ source: unknown;
4
+ manifest: Record<string, unknown>;
5
+ profile: string;
6
+ files: {
7
+ key: "methodology" | "ruleset" | "schema";
8
+ name: "methodology.yaml" | "runtime-ruleset.json" | "schema.json";
9
+ text: string;
10
+ }[];
11
+ };
@@ -0,0 +1,79 @@
1
+ import { createHash } from "node:crypto";
2
+ import { FoundryContextError } from "./foundry-runtime-context.js";
3
+ const components = [
4
+ { key: "schema", name: "schema.json" },
5
+ { key: "methodology", name: "methodology.yaml" },
6
+ { key: "ruleset", name: "runtime-ruleset.json" },
7
+ ];
8
+ function cliType(type) {
9
+ return type === "lifecyclemodel" ? "model" : type;
10
+ }
11
+ export function createTypedContextCommand(type, output) {
12
+ return [
13
+ "dataset",
14
+ cliType(type),
15
+ "contract",
16
+ "--include",
17
+ components.map(({ key }) => key).join(","),
18
+ "--output",
19
+ output,
20
+ "--json",
21
+ ];
22
+ }
23
+ function record(value) {
24
+ return value && typeof value === "object" && !Array.isArray(value)
25
+ ? value
26
+ : {};
27
+ }
28
+ function reject(message) {
29
+ throw new FoundryContextError("workflow_context_invalid", message);
30
+ }
31
+ export function projectTypedContext(type, output, receipt, bytes) {
32
+ const result = record(receipt);
33
+ const artifact = Array.isArray(result.artifacts) ? record(result.artifacts[0]) : {};
34
+ if (result.schemaVersion !== 1 ||
35
+ result.operation !== `dataset ${cliType(type)} contract` ||
36
+ result.status !== "completed" ||
37
+ result.outcome !== "contract_read" ||
38
+ artifact.path !== output ||
39
+ artifact.purpose !== "complete_result" ||
40
+ artifact.bytes !== bytes.length)
41
+ return reject("Invalid typed CLI contract receipt for the current task scope.");
42
+ let parsed;
43
+ try {
44
+ parsed = JSON.parse(bytes.toString("utf8"));
45
+ }
46
+ catch {
47
+ return reject("Typed CLI contract output must be valid JSON.");
48
+ }
49
+ const contract = record(parsed);
50
+ const manifest = record(contract.manifest);
51
+ if (!["sdk-contract-api", "sdk-runtime-assets"].includes(String(contract.source)) ||
52
+ manifest.kind !== type ||
53
+ typeof manifest.profile !== "string" ||
54
+ !Array.isArray(contract.unavailable))
55
+ return reject("Typed CLI contract manifest does not match the task dataset type.");
56
+ const payload = record(contract.components);
57
+ const files = [];
58
+ for (const { key, name } of components) {
59
+ const value = payload[key];
60
+ const fact = record(manifest[key]);
61
+ if (value === null &&
62
+ manifest[key] === null &&
63
+ contract.unavailable.includes(key) &&
64
+ key !== "schema" &&
65
+ type !== "flow" &&
66
+ type !== "process")
67
+ continue;
68
+ const text = key === "ruleset" && value && typeof value === "object" && !Array.isArray(value)
69
+ ? JSON.stringify(value, null, 2)
70
+ : value;
71
+ if (typeof text !== "string" || !text.length || contract.unavailable.includes(key))
72
+ return reject(`Typed CLI contract is missing ${key} for ${type}.`);
73
+ if (Buffer.byteLength(text) !== fact.bytes ||
74
+ createHash("sha256").update(text).digest("hex") !== fact.sha256)
75
+ return reject(`Typed CLI contract ${key} digest does not match its manifest.`);
76
+ files.push({ key, name, text });
77
+ }
78
+ return { source: contract.source, manifest, profile: manifest.profile, files };
79
+ }