@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
@@ -74,6 +74,10 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
74
74
  const graceMs = Math.min(5_000, Math.max(250, Math.ceil(timeoutMs * 0.1)));
75
75
  return timeoutMs + graceMs;
76
76
  }
77
+ function identityPreflightRunPath(value) {
78
+ const resolved = resolveRepoPath(value);
79
+ return resolved ? path.resolve(resolved) : null;
80
+ }
77
81
  function identityPreflightRunReportFile(row) {
78
82
  const explicit = row.expected_report_file ||
79
83
  row.identity_decision_file ||
@@ -81,21 +85,21 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
81
85
  row.report_file ||
82
86
  row.reportFile;
83
87
  if (explicit)
84
- return resolveRepoPath(explicit);
88
+ return identityPreflightRunPath(explicit);
85
89
  const outputDir = row.output_dir || row.outputDir;
86
90
  return outputDir
87
- ? path.join(resolveRepoPath(outputDir), "outputs", "identity-decision.json")
91
+ ? path.join(identityPreflightRunPath(outputDir), "outputs", "identity-decision.json")
88
92
  : null;
89
93
  }
90
94
  function identityPreflightRunOutputDir(row) {
91
95
  const outputDir = row.output_dir || row.outputDir;
92
96
  if (outputDir)
93
- return resolveRepoPath(outputDir);
97
+ return identityPreflightRunPath(outputDir);
94
98
  const reportFile = identityPreflightRunReportFile(row);
95
99
  return reportFile ? path.dirname(path.dirname(reportFile)) : null;
96
100
  }
97
101
  function identityPreflightRunRequestFile(row) {
98
- return resolveRepoPath(row.request_file || row.requestFile || row.input);
102
+ return identityPreflightRunPath(row.request_file || row.requestFile || row.input);
99
103
  }
100
104
  function identityPreflightRunRowKey(row, index) {
101
105
  return [
@@ -286,6 +290,9 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
286
290
  maxAgeMs: positiveIntegerOption(options.authReceiptMaxAgeMs, 300_000) ?? 300_000,
287
291
  expectedProjectRef,
288
292
  expectedUserId,
293
+ sessionMode: ["access-token", "access_token"].includes(executionEnvironment.TIANGONG_LCA_AUTH_MODE ?? "")
294
+ ? "headless"
295
+ : "oauth",
289
296
  });
290
297
  }
291
298
  const logDir = path.join(outDir, "logs");
@@ -594,6 +601,11 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
594
601
  startedAtMs,
595
602
  diskReportMtimeMs: reportFile && fileExists(reportFile) ? fs.statSync(reportFile).mtimeMs : null,
596
603
  completedAtUtc: nowIso(),
604
+ requestFile: requestFile ?? undefined,
605
+ outputDir,
606
+ reportFile: reportFile ?? undefined,
607
+ stderrText: result.stderr || "",
608
+ signal: result.signal,
597
609
  });
598
610
  if (executionValidation?.ok) {
599
611
  writeJson(executionManifestFile, executionValidation.manifest);
@@ -770,8 +782,8 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
770
782
  blockers: blockers.length,
771
783
  },
772
784
  policy: {
773
- fail_closed_execution: "Every nonzero CLI exit, missing/malformed stdout or disk report, stale disk report, stdout/disk mismatch, ok:false, failed/error status, or execution-binding drift fails the selected row and batch.",
774
- valid_identity_findings: "A blocked/needs_review report remains diagnostic evidence only when the CLI exits zero and stdout/disk bytes are bound by a valid execution manifest.",
785
+ fail_closed_execution: "Nonzero CLI exits fail except the qualified CLI 0.1.28 complete, bound, error-free needs_review/manual_review exit 1 diagnostic. Missing/malformed or stale reports, stdout/disk mismatch, ok:false, failed/error status, execution signals/stderr and binding drift remain failures.",
786
+ valid_identity_findings: "A blocked/needs_review report remains scientific diagnostic evidence only with a valid execution manifest; the pinned manual-review exit 1 contract does not resolve identity or grant a write.",
775
787
  curation_gate_usage: "Pass this same index to dataset-curation-gate with --identity-preflight-index so authoring packages include current and dependency identity-preflight context.",
776
788
  },
777
789
  files: {
@@ -3,7 +3,8 @@ type CliResolution = {
3
3
  command: string;
4
4
  args: string[];
5
5
  display: string;
6
- package: JsonRecord | null;
6
+ package: string | JsonRecord | null;
7
+ package_version?: string | null;
7
8
  };
8
9
  export type CliWrapperOptions = Record<string, unknown> & {
9
10
  help?: unknown;
@@ -48,5 +49,75 @@ export type CliWrapperFactoryDependencies = {
48
49
  export declare function createCliWrapperCommands({ executionEnvironment, executionCwd, appendOption, appendRepeatedOptions, repoRoot, resolveTiangongLcaCliCommand, resolveTiangongLcaCliBin, }: CliWrapperFactoryDependencies): {
49
50
  runDatasetCurationQueueBuild: (options: CliWrapperOptions) => JsonRecord;
50
51
  runDatasetPatchApply: (options: CliWrapperOptions) => JsonRecord;
52
+ runDatasetQaStage: (stage: string, argv: string[]) => {
53
+ stage: string;
54
+ exit_code: number;
55
+ report: {
56
+ schema: string;
57
+ status: string;
58
+ rows_file: string;
59
+ validation_input: string;
60
+ validation_operation: string;
61
+ validations: {
62
+ id: string;
63
+ version: string;
64
+ result: string;
65
+ reference_documents: string | null;
66
+ complete_sha256: string;
67
+ }[];
68
+ rows: {
69
+ findings: {
70
+ entity_id: string;
71
+ version: string;
72
+ severity: string;
73
+ code: string;
74
+ path: string;
75
+ message: string;
76
+ }[];
77
+ }[];
78
+ findings: {
79
+ entity_id: string;
80
+ version: string;
81
+ severity: string;
82
+ code: string;
83
+ path: string;
84
+ message: string;
85
+ }[];
86
+ files: {
87
+ report: string;
88
+ };
89
+ } | {
90
+ status: string;
91
+ policy_decision_owner: string;
92
+ qa_mode: string;
93
+ mass_balance: import("../foundry-process-mass-balance.ts").ProcessMassBalance[];
94
+ findings: {
95
+ process_file: string;
96
+ severity: "info" | "warning" | "blocker";
97
+ code: string;
98
+ methodology_rule_id: string | null;
99
+ message: string;
100
+ source: "rule";
101
+ evidence?: {
102
+ [x: string]: unknown;
103
+ };
104
+ }[];
105
+ schema: string;
106
+ rows_file: string;
107
+ reference_evidence: import("../foundry-runtime-context-types.ts").FoundryInputFact[];
108
+ files: {
109
+ report: string;
110
+ };
111
+ };
112
+ report_file: string;
113
+ cli_validation?: {
114
+ report: string;
115
+ exit: number;
116
+ } | undefined;
117
+ status: string;
118
+ command: string;
119
+ args: string[];
120
+ stderr: string;
121
+ } | null;
51
122
  };
52
123
  export {};
@@ -1,8 +1,14 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
2
4
  import path from "node:path";
3
5
  import process from "node:process";
6
+ import { buildFoundryCurationQueue } from "../foundry-curation-queue.js";
7
+ import { applyTypedAuthoringPatch } from "../foundry-typed-authoring-patch.js";
8
+ import { runTypedDatasetQa } from "../foundry-typed-flow-qa.js";
9
+ import { createFoundryIsolatedChildEnvironment } from "../foundry-runtime-environment.js";
4
10
  export function createCliWrapperCommands({ executionEnvironment = process.env, executionCwd, appendOption, appendRepeatedOptions, repoRoot, resolveTiangongLcaCliCommand, resolveTiangongLcaCliBin, }) {
5
- function runJsonCli(cliArgs, errorMessage) {
11
+ function runJsonCli(cliArgs, errorMessage, temporary) {
6
12
  const cli = resolveTiangongLcaCliCommand
7
13
  ? resolveTiangongLcaCliCommand()
8
14
  : {
@@ -13,8 +19,10 @@ export function createCliWrapperCommands({ executionEnvironment = process.env, e
13
19
  };
14
20
  const spawnArgs = [...cli.args, ...cliArgs];
15
21
  const result = spawnSync(cli.command, spawnArgs, {
16
- cwd: executionCwd ?? repoRoot,
17
- env: executionEnvironment,
22
+ cwd: temporary ?? executionCwd ?? repoRoot,
23
+ env: temporary
24
+ ? createFoundryIsolatedChildEnvironment({ tempRoot: temporary })
25
+ : executionEnvironment,
18
26
  encoding: "utf8",
19
27
  // Mega-scope stages emit large JSON payloads on stdout; the 1MB spawnSync
20
28
  // default overflows with ENOBUFS. Cap below V8's max string length.
@@ -46,6 +54,57 @@ export function createCliWrapperCommands({ executionEnvironment = process.env, e
46
54
  stderr: result.stderr || "",
47
55
  };
48
56
  }
57
+ const localPath = (name) => path.resolve(executionCwd ?? repoRoot, String(name));
58
+ function writeLocalText(file, value) {
59
+ fs.mkdirSync(path.dirname(file), { recursive: true });
60
+ fs.writeFileSync(file, value, { mode: 0o600 });
61
+ }
62
+ const localStage = (temporary) => ({
63
+ workspace: temporary,
64
+ readInput: fs.readFileSync,
65
+ readRowsFile: (file) => fs.readFileSync(file, "utf8"),
66
+ readResult(file) {
67
+ if (!fs.lstatSync(file).isFile())
68
+ throw new Error("Expected a regular typed CLI result file.");
69
+ return fs.readFileSync(file);
70
+ },
71
+ writeJson: (file, value) => writeLocalText(file, JSON.stringify(value, null, 2) + "\n"),
72
+ run(args) {
73
+ const { exitCode, report } = runJsonCli(args, "Typed CLI stage did not emit JSON.", temporary);
74
+ return { exit: exitCode, report, validate: (check) => check() };
75
+ },
76
+ });
77
+ function runDatasetQaStage(stage, argv) {
78
+ const qaType = argv[0] === "qa" ? argv[1] : null;
79
+ if (qaType !== "flow" && qaType !== "process" && qaType !== "lifecyclemodel")
80
+ return null;
81
+ const cli = resolveTiangongLcaCliCommand?.();
82
+ if (cli?.package_version !== "0.4.0")
83
+ return null;
84
+ const rowsFile = localPath(argv[argv.indexOf("--rows-file") + 1]);
85
+ const directory = localPath(argv[argv.indexOf("--out-dir") + 1]);
86
+ const referenceFiles = argv.flatMap((value, index) => value === "--reference-rows-file" ? [localPath(argv[index + 1])] : []);
87
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "foundry-local-qa-"));
88
+ try {
89
+ const result = runTypedDatasetQa(qaType, rowsFile, directory, { referenceFiles }, localStage(temporary));
90
+ return {
91
+ stage,
92
+ exit_code: result.exit || (qaType !== "process" && result.report.findings.length) ? 2 : 0,
93
+ report: result.report,
94
+ report_file: result.reportFile,
95
+ ...(qaType === "process"
96
+ ? { cli_validation: { report: result.validationReportFile, exit: result.exit } }
97
+ : {}),
98
+ status: result.report.status,
99
+ command: cli.command,
100
+ args: [...cli.args, "dataset", qaType === "lifecyclemodel" ? "model" : qaType, "validate"],
101
+ stderr: "",
102
+ };
103
+ }
104
+ finally {
105
+ fs.rmSync(temporary, { recursive: true, force: true });
106
+ }
107
+ }
49
108
  function runDatasetCurationQueueBuild(options) {
50
109
  if (options.help) {
51
110
  return {
@@ -73,6 +132,33 @@ export function createCliWrapperCommands({ executionEnvironment = process.env, e
73
132
  appendRepeatedOptions(cliArgs, "--exclude-process-id", options.excludeProcessId || options.excludeProcessIds);
74
133
  appendOption(cliArgs, "--process-limit", options.processLimit);
75
134
  appendOption(cliArgs, "--out-dir", outDir);
135
+ const cliVersion = resolveTiangongLcaCliCommand?.().package_version;
136
+ if (cliVersion === "0.4.0") {
137
+ const cwd = executionCwd ?? repoRoot;
138
+ const file = (name) => path.resolve(cwd, name);
139
+ const repeated = (flag) => cliArgs.flatMap((name, index) => (name === flag ? [cliArgs[index + 1]] : []));
140
+ const processLimit = repeated("--process-limit")[0];
141
+ const limit = processLimit === undefined ? undefined : Number.parseInt(processLimit, 10);
142
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1))
143
+ throw new Error("--process-limit must be a positive integer.");
144
+ const [processesFile] = repeated("--processes");
145
+ if (!processesFile)
146
+ throw new Error("--processes requires a Process rows file.");
147
+ const [flowsFile] = repeated("--flows");
148
+ const report = buildFoundryCurationQueue({
149
+ processes: file(processesFile),
150
+ flows: flowsFile ? file(flowsFile) : null,
151
+ support: repeated("--support").map(file),
152
+ external: repeated("--external-flow-ref").map(file),
153
+ excludeProcessIds: repeated("--exclude-process-id"),
154
+ processLimit: limit,
155
+ outDir: file(String(outDir)),
156
+ });
157
+ return {
158
+ ...report,
159
+ foundry_wrapper: { exit_code: report.blockers.length ? 1 : 0, owner: "foundry" },
160
+ };
161
+ }
76
162
  const { cliBin, cli, spawnArgs, exitCode, report, stderr } = runJsonCli(cliArgs, "tiangong-lca dataset curation-queue build did not emit JSON.");
77
163
  return {
78
164
  ...report,
@@ -110,6 +196,39 @@ export function createCliWrapperCommands({ executionEnvironment = process.env, e
110
196
  const patch = options.patch || options.patchFile || options.patches || options.suggestions;
111
197
  const outDir = (options.outDir || ".foundry/workspaces/dataset-patch-apply");
112
198
  const out = options.out || options.outFile || path.join(outDir, "patched-rows.jsonl");
199
+ if (resolveTiangongLcaCliCommand?.().package_version === "0.4.0") {
200
+ if (!input || !patch)
201
+ throw new Error("Dataset patch apply requires --input and --patch.");
202
+ const packageDir = options.authoringPackageDir || options.authoringPackagesDir;
203
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "foundry-local-patch-"));
204
+ const io = localStage(temporary);
205
+ try {
206
+ const result = applyTypedAuthoringPatch({
207
+ input: localPath(input),
208
+ patch: localPath(patch),
209
+ output: localPath(out),
210
+ directory: localPath(outDir),
211
+ packageDirectory: packageDir ? localPath(packageDir) : undefined,
212
+ requirePackage: options.requireAuthoringPackage === true ||
213
+ options.requireAuthoringPackage === "true",
214
+ requireClosure: options.requireActionItemClosure === true ||
215
+ options.requireActionItemClosure === "true",
216
+ writeText: writeLocalText,
217
+ writeJson: io.writeJson,
218
+ }, io);
219
+ return {
220
+ ...result.report,
221
+ foundry_wrapper: {
222
+ exit_code: result.exit,
223
+ owner: "tiangong-lca-cli",
224
+ remote_write_mode: "read-only",
225
+ },
226
+ };
227
+ }
228
+ finally {
229
+ fs.rmSync(temporary, { recursive: true, force: true });
230
+ }
231
+ }
113
232
  const cliArgs = ["dataset", "patch", "apply", "--json"];
114
233
  appendOption(cliArgs, "--input", input);
115
234
  appendOption(cliArgs, "--patch", patch);
@@ -142,5 +261,6 @@ export function createCliWrapperCommands({ executionEnvironment = process.env, e
142
261
  return {
143
262
  runDatasetCurationQueueBuild,
144
263
  runDatasetPatchApply,
264
+ runDatasetQaStage,
145
265
  };
146
266
  }
@@ -104,6 +104,10 @@ interface FinalizeStage extends JsonRecord {
104
104
  stderr?: string;
105
105
  report?: FinalizeStage;
106
106
  report_file?: string | null;
107
+ cli_validation?: {
108
+ report: string;
109
+ exit: number;
110
+ };
107
111
  rust_report?: unknown;
108
112
  binary_version?: unknown;
109
113
  counts?: CountMap;
@@ -204,6 +208,7 @@ interface FinalizeDependencies {
204
208
  repoRoot: string;
205
209
  reportFileFromCliStage: (stage: FinalizeStage, paths: string[], fallback: string) => string | null;
206
210
  readRowsFile: (filePath: string) => DatasetRow[];
211
+ readReferenceBytes?: (filePath: string) => Buffer;
207
212
  repairTrueSourceClassification: (row: DatasetRow, context: JsonRecord) => void;
208
213
  repairTrueSourceDescription: (row: DatasetRow, context: JsonRecord) => void;
209
214
  repairTrueSourceIdentity: (row: DatasetRow, context: JsonRecord) => void;
@@ -228,7 +233,12 @@ interface FinalizeDependencies {
228
233
  writeJson: (filePath: string, value: unknown) => void;
229
234
  writeJsonLines: (filePath: string, rows: readonly unknown[]) => void;
230
235
  }
231
- export declare function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }: FinalizeDependencies): {
236
+ export declare function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, readReferenceBytes, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }: FinalizeDependencies): {
232
237
  runDatasetPostAuthoringFinalize: (options: FinalizeOptions) => FinalizeStage;
238
+ finalizeStages: (options: FinalizeOptions, asynchronousIdentity: boolean) => Generator<{
239
+ rowsFile: string;
240
+ outDir: string;
241
+ options: FinalizeOptions;
242
+ }, FinalizeStage, FinalizeStage>;
233
243
  };
234
244
  export {};
@@ -1,8 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { taskAuthorizationAllows } from "../task-authorization.js";
4
5
  import { readOnlyStageContract } from "../stage-contract.js";
5
6
  import { selectFinalizeReferenceInputs } from "./finalize-reference-inputs.js";
7
+ import { readRows } from "../import-curation/internal/runtime-io.js";
6
8
  const postAuthoringFinalizeStageContract = readOnlyStageContract([
7
9
  {
8
10
  stage: "prepare_scope",
@@ -18,6 +20,7 @@ const postAuthoringFinalizeStageContract = readOnlyStageContract([
18
20
  purpose: "Apply identity reference rewrites, unresolved exchange externalization, BAFU source/contact rewrites, canonical support rewrites, and deterministic curation cleanup.",
19
21
  inputs: [
20
22
  "input rows",
23
+ "selected read-only Process validation references",
21
24
  "identity/preflight indexes",
22
25
  "BAFU source/contact policy",
23
26
  "canonical support cache",
@@ -87,7 +90,7 @@ function verifiedReferenceLedgerFilesForDir(ledgerDir) {
87
90
  .map((name) => path.join(ledgerDir, name))
88
91
  .filter((filePath) => fs.existsSync(filePath) && fs.statSync(filePath).isFile());
89
92
  }
90
- export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }) {
93
+ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, readReferenceBytes = (file) => fs.readFileSync(file), repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }) {
91
94
  function stageStatus(value) {
92
95
  if (!value || typeof value !== "object")
93
96
  return "completed";
@@ -620,7 +623,7 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
620
623
  output_rows_file: repoRelativePath(outputRowsFile),
621
624
  };
622
625
  }
623
- function runDatasetPostAuthoringFinalize(options) {
626
+ function* finalizeStages(options, asynchronousIdentity) {
624
627
  const finalizeStartedAtUtc = nowIso();
625
628
  const finalizeStartedAtMs = Date.now();
626
629
  const finalizeTimings = [];
@@ -781,8 +784,32 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
781
784
  source: "canonical_support_rewrites",
782
785
  severity: blocker.severity || "error",
783
786
  }));
787
+ const validationReferences = referenceInputs.qaFiles.map((file) => {
788
+ const content = readReferenceBytes(file);
789
+ // The reader uses this path only to select JSON/JSONL; parsing and hashing
790
+ // must share the captured bytes rather than reopen a mutable selection.
791
+ const rows = readRows(file.toLowerCase(), () => content.toString("utf8"));
792
+ if (!fs.readFileSync(file).equals(content))
793
+ throw new Error("Selected Process validation reference bytes changed during capture.");
794
+ return {
795
+ rows,
796
+ fact: {
797
+ path: repoRelativePath(file),
798
+ bytes: content.length,
799
+ sha256: createHash("sha256").update(content).digest("hex"),
800
+ },
801
+ };
802
+ });
784
803
  const cleanup = timeStage("curation_cleanup", () => runDatasetCurationCleanup({
785
804
  repoRoot,
805
+ ...(validationReferences.length
806
+ ? {
807
+ processValidationReferences: {
808
+ rows: validationReferences.flatMap((reference) => reference.rows),
809
+ files: validationReferences.map((reference) => reference.fact),
810
+ },
811
+ }
812
+ : {}),
786
813
  options: {
787
814
  ...options,
788
815
  type: datasetType,
@@ -1011,14 +1038,27 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1011
1038
  if (sourceContactSupportFinalizeRequested) {
1012
1039
  sourceContactSupportFinalize = timeStage("source_contact_support_finalize", finalizeSourceContactSupport);
1013
1040
  }
1014
- const identityPreflightRunStage = timeStage("identity_preflight_run", () => runFinalizeIdentityPreflightStage({
1041
+ const identityRequest = {
1015
1042
  rowsFile: cleanedRowsFile,
1016
1043
  outDir,
1017
- options: {
1018
- ...options,
1019
- type: datasetType,
1020
- },
1021
- }));
1044
+ options: { ...options, type: datasetType },
1045
+ };
1046
+ let identityPreflightRunStage;
1047
+ if (asynchronousIdentity && booleanOption(options.runIdentityPreflight)) {
1048
+ const started_at_utc = nowIso();
1049
+ const startedAt = Date.now();
1050
+ identityPreflightRunStage = yield identityRequest;
1051
+ finalizeTimings.push({
1052
+ stage: "identity_preflight_run",
1053
+ status: stageStatus(identityPreflightRunStage),
1054
+ started_at_utc,
1055
+ finished_at_utc: nowIso(),
1056
+ duration_ms: Date.now() - startedAt,
1057
+ });
1058
+ }
1059
+ else {
1060
+ identityPreflightRunStage = timeStage("identity_preflight_run", () => runFinalizeIdentityPreflightStage(identityRequest));
1061
+ }
1022
1062
  const curationQueueStage = timeStage("curation_queue", () => runFinalizeAutoCurationQueue({
1023
1063
  datasetType,
1024
1064
  rowsFile,
@@ -1124,6 +1164,7 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1124
1164
  const curationGate = timeStage("post_authoring_curation_gate", () => requiresCurationGate
1125
1165
  ? runDatasetCurationGate({
1126
1166
  repoRoot,
1167
+ cliValidation: qaStage.cli_validation,
1127
1168
  options: {
1128
1169
  ...options,
1129
1170
  type: datasetType,
@@ -1287,6 +1328,15 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1287
1328
  if (prewriteGateReady) {
1288
1329
  stage.report_file = reportFileFromCliStage(stage, ["files.report"], path.join(remoteOutDir, "outputs", "remote-verification-report.json"));
1289
1330
  remoteVerifyReportFile = stage.report_file;
1331
+ if (stage.report?.schema === "tiangong-foundry.edge-support-precommit.v1" &&
1332
+ stage.status !== "passed_remote_verification") {
1333
+ prewriteGateBlockers.push({
1334
+ code: "edge_precommit_verification_blocked",
1335
+ stage: "remote_verify_precommit",
1336
+ message: "Resolve the exact remote identity and dependency checks before requesting write approval.",
1337
+ report: repoRelativeMaybe(remoteVerifyReportFile),
1338
+ });
1339
+ }
1290
1340
  }
1291
1341
  return stage;
1292
1342
  });
@@ -1729,5 +1779,11 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1729
1779
  },
1730
1780
  };
1731
1781
  }
1732
- return { runDatasetPostAuthoringFinalize };
1782
+ function runDatasetPostAuthoringFinalize(options) {
1783
+ const result = finalizeStages(options, false).next();
1784
+ if (!result.done)
1785
+ throw new Error("Unexpected asynchronous identity stage.");
1786
+ return result.value;
1787
+ }
1788
+ return { runDatasetPostAuthoringFinalize, finalizeStages };
1733
1789
  }
@@ -0,0 +1,6 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ /** Retain producer locator meaning; this proof permits no execution of the old package or old stages. */
4
+ export declare function verifyRegisteredAssessmentProducer(context: FoundryRuntimeContext, entry: ArtifactEntry, value: Record<string, unknown>, entries: readonly ArtifactEntry[]): string;
5
+ /** A retained set keeps the locator base of the operation that actually produced its manifest. */
6
+ export declare function registeredAssessmentSetProducerBase(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], set: Record<string, unknown>): string;