@tiangong-lca/foundry 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +5 -3
  2. package/docs/architecture.md +5 -3
  3. package/docs/foundry-task-contracts.md +2 -0
  4. package/docs/package-distribution-contract.md +10 -8
  5. package/docs/public-runtime-contract.md +53 -3
  6. package/docs/runtime-context-contract.md +7 -3
  7. package/docs/task-authorization-contract.md +2 -0
  8. package/package-dist/assets/foundry-package-descriptor.json +374 -136
  9. package/package-dist/scripts/foundry-facade.d.ts +6 -0
  10. package/package-dist/scripts/foundry-facade.js +38 -0
  11. package/package-dist/scripts/foundry-runtime.d.ts +3 -2
  12. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  13. package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
  14. package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
  15. package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
  16. package/package-dist/scripts/lib/final-delivery-review.js +108 -0
  17. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  18. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  19. package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  21. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  22. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  23. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  24. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  25. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  26. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  27. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  28. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  29. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  30. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  31. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  32. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  33. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +24 -0
  34. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +209 -0
  35. package/package-dist/scripts/lib/foundry-edge-session.d.ts +32 -0
  36. package/package-dist/scripts/lib/foundry-edge-session.js +203 -0
  37. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  38. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  39. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  40. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  41. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  42. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  43. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  44. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  45. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  46. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  47. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  48. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  49. package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
  50. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  51. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  52. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  53. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  54. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  55. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +21 -0
  56. package/package-dist/scripts/lib/foundry-owner-readback.js +61 -0
  57. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  58. package/package-dist/scripts/lib/foundry-package-contract.js +8 -2
  59. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  60. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  61. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  62. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  63. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  64. package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
  65. package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
  66. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  67. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
  68. package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
  69. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  70. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  71. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  72. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  73. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  74. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  75. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  76. package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
  77. package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
  78. package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
  79. package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
  80. package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
  81. package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
  82. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
  83. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  84. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  85. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  86. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  87. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  88. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  89. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  90. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  91. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  92. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  93. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  94. package/package-dist/scripts/lib/foundry-workflow-execution.js +57 -5
  95. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  96. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  97. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  98. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  99. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  100. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
  101. package/package-dist/scripts/lib/foundry-workflow-repair.js +204 -2
  102. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  103. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  104. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  105. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  106. package/package-dist/scripts/public-api.d.ts +6 -0
  107. package/package-dist/scripts/runtime-entry.js +15 -6
  108. package/package.json +5 -2
  109. package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
  110. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  111. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  112. package/specs/schemas/foundry-package-descriptor.schema.json +5 -2
  113. package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
  114. package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
  115. package/specs/schemas/foundry-task-start.schema.json +10 -2
  116. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,226 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FoundryContextError, captureFoundryInput, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
4
+ import { canonicalPayloadSha256 } from "./post-write-root-proof.js";
5
+ import { datasetIdentity, detectDatasetType } from "./import-curation/internal/dataset-payload.js";
6
+ import { foundryProcessQa } from "./foundry-process-qa.js";
7
+ import { sha256Text } from "./identity-preflight-proof.js";
8
+ import { projectFoundryValidationReferences } from "./foundry-validation-reference-context.js";
9
+ import { readRows } from "./import-curation/internal/runtime-io.js";
10
+ import { assertWorkflowReportArtifact, runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
11
+ function invalid() {
12
+ throw new FoundryContextError("workflow_qa_failed", "The complete typed dataset validation does not match the selected row and receipt.");
13
+ }
14
+ function object(value) {
15
+ if (!value || typeof value !== "object" || Array.isArray(value))
16
+ return invalid();
17
+ return value;
18
+ }
19
+ const operationFor = (type) => `dataset ${type === "lifecyclemodel" ? "model" : type} validate`;
20
+ function projectValidation(type, row, output, exit, receipt, bytes) {
21
+ const report = object(receipt);
22
+ const artifact = Array.isArray(report.artifacts) ? object(report.artifacts[0]) : invalid();
23
+ if (report.schemaVersion !== 1 ||
24
+ report.operation !== operationFor(type) ||
25
+ report.status !== "completed" ||
26
+ report.error !== null ||
27
+ artifact.path !== output ||
28
+ artifact.purpose !== "complete_result" ||
29
+ artifact.bytes !== bytes.length)
30
+ return invalid();
31
+ const complete = object(JSON.parse(bytes.toString("utf8")));
32
+ const preview = object(object(report.data).validation);
33
+ const issues = complete.issues;
34
+ const previewIssues = preview.issues;
35
+ const receiptKeys = [
36
+ "id",
37
+ "type",
38
+ "version",
39
+ "status",
40
+ "validator",
41
+ "issue_count",
42
+ "payload_sha256",
43
+ ];
44
+ const status = complete.status;
45
+ const admittedStatuses = type === "process" ? ["passed", "failed", "incomplete"] : ["passed", "failed"];
46
+ if (!admittedStatuses.includes(String(status)) ||
47
+ exit !== (status === "passed" ? 0 : 1) ||
48
+ report.outcome !== `validation_${status}` ||
49
+ complete.type !== type ||
50
+ complete.index !== 0 ||
51
+ complete.id !== row.id ||
52
+ complete.version !== row.version ||
53
+ complete.payload_sha256 !== canonicalPayloadSha256(row.payload) ||
54
+ JSON.stringify(complete.checks) !== '["schema","business"]' ||
55
+ !Array.isArray(issues) ||
56
+ !Array.isArray(previewIssues) ||
57
+ complete.issue_count !== issues.length ||
58
+ (status === "passed" && issues.length !== 0) ||
59
+ (status === "failed" && issues.length === 0) ||
60
+ receiptKeys.some((key) => complete[key] !== preview[key]) ||
61
+ canonicalPayloadSha256(previewIssues) !==
62
+ canonicalPayloadSha256(issues.slice(0, previewIssues.length)))
63
+ return invalid();
64
+ const ownerIssues = [...issues];
65
+ if (type === "process" && status === "incomplete") {
66
+ const names = object(complete.flow_reference_names);
67
+ if (names.status === "unresolved" && Array.isArray(names.issues))
68
+ ownerIssues.push(...names.issues);
69
+ }
70
+ const findings = ownerIssues.map((raw) => {
71
+ const { code, path: issuePath, message } = object(raw);
72
+ if (typeof code !== "string" ||
73
+ !code ||
74
+ typeof issuePath !== "string" ||
75
+ typeof message !== "string" ||
76
+ !message)
77
+ return invalid();
78
+ return {
79
+ entity_id: row.id,
80
+ version: row.version,
81
+ severity: "error",
82
+ code,
83
+ path: issuePath,
84
+ message,
85
+ };
86
+ });
87
+ if (status === "incomplete" && findings.length === 0)
88
+ findings.push({
89
+ entity_id: row.id,
90
+ version: row.version,
91
+ severity: "error",
92
+ code: "process_business_validation_incomplete",
93
+ path: "$",
94
+ message: "Resolve exact Process reference evidence and repeat CLI business validation.",
95
+ });
96
+ return { complete, findings };
97
+ }
98
+ export function projectFlowValidation(row, output, exit, receipt, bytes) {
99
+ return projectValidation("flow", row, output, exit, receipt, bytes).findings;
100
+ }
101
+ export function runFoundryTypedDatasetQa(context, qualified, temporary, writeJson, type, rowsFile, output, options = {}) {
102
+ const directory = resolveFoundryOutput(context, output);
103
+ return runTypedDatasetQa(type, rowsFile, directory, options, {
104
+ writeJson,
105
+ readRowsFile: options.readRowsFile ?? ((file) => readFoundryInput(context, file).toString("utf8")),
106
+ readResult: (file) => fs.readFileSync(assertWorkflowReportArtifact(context, file, directory)),
107
+ run: (argv) => runWorkflowLocalCliResult(context, qualified, temporary, argv),
108
+ });
109
+ }
110
+ export function runTypedDatasetQa(type, rowsFile, directory, options, { writeJson, readRowsFile, readResult, run }) {
111
+ const rows = readRows(rowsFile, readRowsFile);
112
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
113
+ const referenceEvidence = [...new Set(options.referenceFiles ?? [])].map((file) => {
114
+ const fact = captureFoundryInput(file);
115
+ const contents = readRowsFile(file);
116
+ if (sha256Text(contents) !== fact.sha256)
117
+ return invalid();
118
+ return { fact, rows: readRows(file, () => contents) };
119
+ });
120
+ const references = referenceEvidence.flatMap(({ rows }) => rows);
121
+ const projected = type === "process" ? projectFoundryValidationReferences(rows, references) : rows;
122
+ const massReferences = { rows: new Map() };
123
+ const support = [];
124
+ for (const source of references) {
125
+ const kind = detectDatasetType(source);
126
+ if (kind !== "flow" && kind !== "unitgroup" && kind !== "flowproperty")
127
+ return invalid();
128
+ const supplied = datasetIdentity(source, 0, kind);
129
+ const { id, version, payload } = datasetIdentity(supplied.payload, 0, kind);
130
+ const key = `${kind}/${id}/${version}`;
131
+ if (!id || !version || id === "row-1" || id !== supplied.id || version !== supplied.version)
132
+ return invalid();
133
+ const sha256 = canonicalPayloadSha256(payload);
134
+ const prior = massReferences.rows.get(key);
135
+ if (prior && prior.sha256 !== sha256)
136
+ return invalid();
137
+ if (!prior) {
138
+ massReferences.rows.set(key, { payload: object(payload), sha256 });
139
+ if (kind !== "flow")
140
+ support.push(payload);
141
+ }
142
+ }
143
+ const operation = operationFor(type);
144
+ const validations = rows.map((source, index) => {
145
+ const row = datasetIdentity(source, index, type);
146
+ const input = path.join(directory, `${type}-${index + 1}.json`);
147
+ const resultFile = path.join(directory, `validation-${index + 1}.json`);
148
+ // 0.4 checks the typed root before its validation reader unwraps json and reads
149
+ // semantic_context. The complete result must still hash to the original payload.
150
+ const processInput = type === "process" ? object(projected[index]) : null;
151
+ writeJson(input, processInput
152
+ ? {
153
+ ...object(row.payload),
154
+ json: row.payload,
155
+ semantic_context: processInput.semantic_context,
156
+ ...(processInput.allocation_transformation === undefined
157
+ ? {}
158
+ : { allocation_transformation: processInput.allocation_transformation }),
159
+ }
160
+ : row.payload);
161
+ const argv = [
162
+ ...operation.split(" "),
163
+ "--input",
164
+ input,
165
+ "--checks",
166
+ "schema,business",
167
+ "--output",
168
+ resultFile,
169
+ "--json",
170
+ ];
171
+ let referenceDocuments;
172
+ if (type === "process") {
173
+ const flowDocs = object(processInput?.semantic_context).flow_documents;
174
+ if (!Array.isArray(flowDocs))
175
+ return invalid();
176
+ const documents = [
177
+ ...new Map([...flowDocs, ...support].map((document) => [canonicalPayloadSha256(document), document])).values(),
178
+ ];
179
+ if (documents.length) {
180
+ referenceDocuments = path.join(directory, `references-${index + 1}.json`);
181
+ writeJson(referenceDocuments, { documents });
182
+ argv.push("--reference-documents", referenceDocuments);
183
+ }
184
+ }
185
+ const validation = run(argv);
186
+ const result = validation.validate(() => projectValidation(type, row, resultFile, validation.exit, validation.report, readResult(resultFile)));
187
+ return {
188
+ id: row.id,
189
+ version: row.version,
190
+ result: resultFile,
191
+ reference_documents: referenceDocuments ?? null,
192
+ ...result,
193
+ };
194
+ });
195
+ const reportFile = type === "process"
196
+ ? path.join(directory, "outputs", "validation-report.json")
197
+ : path.join(directory, `${type}-qa-report.json`);
198
+ const report = {
199
+ schema: `tiangong-foundry.typed-${type}-qa.v1`,
200
+ status: `completed_typed_${type}_validation`,
201
+ rows_file: rowsFile,
202
+ validation_input: options.validationInput ?? rowsFile,
203
+ validation_operation: operation,
204
+ validations: validations.map(({ complete, findings: _findings, ...validation }) => ({
205
+ ...validation,
206
+ complete_sha256: canonicalPayloadSha256(complete),
207
+ })),
208
+ rows: validations.map(({ complete, findings }) => ({ ...complete, findings })),
209
+ findings: validations.flatMap(({ findings }) => findings),
210
+ files: { report: reportFile },
211
+ };
212
+ writeJson(reportFile, report);
213
+ const exit = validations.some(({ complete }) => complete.status !== "passed") ? 1 : 0;
214
+ if (type !== "process")
215
+ return { reportFile, report, exit, validationReportFile: reportFile };
216
+ const qaFile = path.join(directory, "process-qa-report.json");
217
+ const qa = {
218
+ ...foundryProcessQa(rows, massReferences),
219
+ schema: "tiangong-foundry.process-qa.v1",
220
+ rows_file: rowsFile,
221
+ reference_evidence: referenceEvidence.map(({ fact }) => fact),
222
+ files: { report: qaFile },
223
+ };
224
+ writeJson(qaFile, qa);
225
+ return { reportFile: qaFile, report: qa, exit, validationReportFile: reportFile };
226
+ }
@@ -0,0 +1,6 @@
1
+ import { type FoundryAuthentication } from "./foundry-authentication-environment.ts";
2
+ import type { createFoundryEdgeActor } from "./foundry-edge-session.ts";
3
+ import type { EdgeSupportRoot } from "./foundry-edge-support-plan.ts";
4
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
5
+ import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
6
+ export declare function createFoundryTypedModelDraft(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, receipt: Awaited<ReturnType<typeof createFoundryEdgeActor>>["receipt"], originalRequest: string, root: EdgeSupportRoot, content: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,59 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createFoundryAuthenticationEnvironment, } from "./foundry-authentication-environment.js";
3
+ import { FoundryContextError } from "./foundry-runtime-context.js";
4
+ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
5
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
6
+ import { workflowObject } from "./foundry-workflow-state.js";
7
+ import { sha256Json, sha256Text } from "./identity-preflight-proof.js";
8
+ export function createFoundryTypedModelDraft(context, qualified, authentication, receipt, originalRequest, root, content) {
9
+ assertQualifiedFoundryRuntime(context, qualified);
10
+ const cli = resolveInstalledTiangongLcaCliPackage();
11
+ const expectedActor = receipt.identity.user_id;
12
+ const expectedEnvironment = new URL(receipt.project.project_base_url).origin;
13
+ const request = {
14
+ id: root.id,
15
+ version: root.version,
16
+ content,
17
+ requestId: sha256Json({ originalRequest, id: root.id, version: root.version }),
18
+ expectedActor,
19
+ expectedEnvironment,
20
+ };
21
+ const environment = createFoundryAuthenticationEnvironment(authentication, context.accountIntent?.sessionReference, process.env);
22
+ let child;
23
+ try {
24
+ child = spawnSync(process.execPath, [cli.binPath, "dataset", "model", "create", "--input", "-", "--json"], {
25
+ cwd: context.workspaceRoot,
26
+ env: environment,
27
+ input: JSON.stringify(request),
28
+ encoding: "utf8",
29
+ shell: false,
30
+ timeout: 60_000,
31
+ maxBuffer: 8 * 1024 * 1024,
32
+ });
33
+ }
34
+ finally {
35
+ delete environment.TIANGONG_LCA_ACCESS_TOKEN;
36
+ }
37
+ const unproven = () => new FoundryContextError("model_draft_result_unproven", "The original Model write requires independent exact readback.");
38
+ if (child.status !== 0 || child.signal || child.error || child.stderr)
39
+ throw unproven();
40
+ const envelope = workflowObject(JSON.parse(child.stdout));
41
+ const data = workflowObject(envelope.data);
42
+ const subject = workflowObject(data.subject);
43
+ const provenance = workflowObject(envelope.context);
44
+ if (envelope.schemaVersion !== 1 ||
45
+ envelope.operation !== "dataset model create" ||
46
+ envelope.status !== "completed" ||
47
+ envelope.outcome !== "dataset_written" ||
48
+ envelope.error !== null ||
49
+ subject.type !== "model" ||
50
+ subject.id !== root.id ||
51
+ subject.version !== root.version ||
52
+ data.contentDigest !== sha256Text(JSON.stringify(content)) ||
53
+ provenance.environment !== expectedEnvironment ||
54
+ workflowObject(provenance.actor).id !== expectedActor ||
55
+ provenance.requestId !== request.requestId ||
56
+ workflowObject(data.readback).contentMatchesIntent !== true)
57
+ throw unproven();
58
+ return envelope;
59
+ }
@@ -12,6 +12,8 @@ import { runDatasetCurationGate } from "./import-curation/curation-gate.js";
12
12
  import { loadFoundryQualityReview } from "./foundry-quality-review.js";
13
13
  import { runDatasetAuthoringTaskBuild } from "./import-curation/authoring-packages.js";
14
14
  import { readRows } from "./import-curation/internal/runtime-io.js";
15
+ import { runFoundryTypedDatasetQa } from "./foundry-typed-flow-qa.js";
16
+ import { buildFoundryCurationQueue } from "./foundry-curation-queue.js";
15
17
  import { projectFoundryValidationReferences, selectedFoundryExternalFlowReferences, } from "./foundry-validation-reference-context.js";
16
18
  import { parseFoundryPreparationCliReport } from "./foundry-preparation-cli-validation.js";
17
19
  import { routeFoundryDecisionAction } from "./foundry-decision-routing.js";
@@ -407,8 +409,23 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
407
409
  args.push("--external-flow-ref", external.file);
408
410
  }
409
411
  const currentQueueDir = queueDir;
410
- const queue = runWorkflowLocalCliResult(context, qualified, temporary, args);
411
- queue.validate(() => assertCurrentQueueBuild(context, currentQueueDir, queue, selectedSets, external));
412
+ if (qualified.cli.expectation.package_version === "0.4.0") {
413
+ const report = buildFoundryCurationQueue({
414
+ processes: processes.file,
415
+ flows: selectedSets.find((set) => set.type === "flow")?.file,
416
+ support: selectedSets
417
+ .filter((set) => ["contact", "source", "unitgroup", "flowproperty"].includes(String(set.type)))
418
+ .map((set) => String(set.file)),
419
+ external: external ? [external.file] : [],
420
+ outDir: currentQueueDir,
421
+ readInput: (file) => file === external?.file ? fs.readFileSync(file) : readFoundryInput(context, file),
422
+ });
423
+ assertCurrentQueueBuild(context, currentQueueDir, { report, exit: report.status === "ready" ? 0 : 1 }, selectedSets, external);
424
+ }
425
+ else {
426
+ const queue = runWorkflowLocalCliResult(context, qualified, temporary, args);
427
+ queue.validate(() => assertCurrentQueueBuild(context, currentQueueDir, queue, selectedSets, external));
428
+ }
412
429
  }
413
430
  const assessed = previousSets.map(record);
414
431
  const toAssess = options.scopeType
@@ -467,18 +484,55 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
467
484
  registerWorkflowStageFiles(context, operation, output);
468
485
  return result;
469
486
  }
470
- const qaDir = path.join(output, set.type, "qa");
487
+ let cliValidation;
488
+ let validationProjection;
489
+ const typed = qualified.cli.expectation.package_version === "0.4.0";
490
+ const datasetType = set.type;
491
+ const qaDir = path.join(output, datasetType, "qa");
492
+ const processReferenceFiles = datasetType === "process"
493
+ ? [
494
+ ...selectedSets
495
+ .filter((ref) => ["flow", "flowproperty", "unitgroup"].includes(String(ref.type)))
496
+ .map((ref) => String(ref.file)),
497
+ ...qaReferenceFiles,
498
+ ]
499
+ : [];
500
+ const validationDir = typed ? qaDir : path.join(output, datasetType, "cli-validation");
501
+ let validationInput = set.file;
502
+ let validationRows = [];
503
+ if (datasetType === "process") {
504
+ validationRows = readRows(set.file, (name) => readFoundryInput(context, name).toString("utf8"));
505
+ if (qaReferenceFiles.length) {
506
+ validationRows = projectFoundryValidationReferences(validationRows, qaReferenceFiles.flatMap((file) => readRows(file, (name) => readFoundryInput(context, name).toString("utf8"))));
507
+ validationInput = path.join(validationDir, "validation-only.process.rows.json");
508
+ operation.writeJson(validationInput, validationRows);
509
+ validationProjection = {
510
+ cli_validation_input: captureFoundryInput(validationInput),
511
+ cli_validation_source_rows: captureFoundryInput(set.file),
512
+ cli_validation_reference_input_sha256: referenceInputSha256,
513
+ cli_validation_reference_files: reference.value.qa_files,
514
+ };
515
+ }
516
+ }
471
517
  let qaReport;
472
- if (["flow", "process", "lifecyclemodel"].includes(set.type)) {
518
+ if (typed &&
519
+ (datasetType === "flow" ||
520
+ datasetType === "process" ||
521
+ datasetType === "lifecyclemodel")) {
522
+ const result = runFoundryTypedDatasetQa(context, qualified, temporary, (file, value) => operation.writeJson(file, value), datasetType, set.file, qaDir, { referenceFiles: processReferenceFiles, validationInput });
523
+ qaReport = result.reportFile;
524
+ if (datasetType === "process")
525
+ cliValidation = {
526
+ report: result.validationReportFile,
527
+ exit: result.exit,
528
+ ...(validationProjection ? { input: captureFoundryInput(validationInput) } : {}),
529
+ };
530
+ }
531
+ else if (["flow", "process", "lifecyclemodel"].includes(set.type)) {
473
532
  const qaArgv = ["qa", set.type, "--rows-file", set.file, "--out-dir", qaDir, "--json"];
474
- if (set.type === "process") {
475
- for (const referenceSet of selectedSets) {
476
- if (["flow", "flowproperty", "unitgroup"].includes(String(referenceSet.type))) {
477
- readFoundryInput(context, String(referenceSet.file));
478
- qaArgv.push("--reference-rows-file", String(referenceSet.file));
479
- }
480
- }
481
- qaArgv.push(...qaReferenceFiles.flatMap((file) => ["--reference-rows-file", file]));
533
+ for (const file of processReferenceFiles) {
534
+ readFoundryInput(context, file);
535
+ qaArgv.push("--reference-rows-file", file);
482
536
  }
483
537
  const qa = runWorkflowLocalCliResult(context, qualified, temporary, qaArgv);
484
538
  qaReport = qa.validate(() => {
@@ -500,23 +554,7 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
500
554
  });
501
555
  }
502
556
  const gateDir = path.join(output, set.type, "curation");
503
- let cliValidation;
504
- let validationProjection;
505
- if (set.type === "process") {
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
- }
557
+ if (set.type === "process" && !typed) {
520
558
  const validation = runWorkflowLocalCliResult(context, qualified, temporary, [
521
559
  "dataset",
522
560
  "validate",
@@ -15,6 +15,8 @@ import { createFoundryExecutionCapsule } from "./foundry-execution-admission.js"
15
15
  import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
16
16
  import { createFoundryCommandSpec, createFileArtifactFact } from "./foundry-command-spec.js";
17
17
  import { parseFoundryCommandSpec } from "@tiangong-lca/cli/command-spec";
18
+ import { buildEdgeSupportPlan, isFoundryEdgeDraftType } from "./foundry-edge-support-plan.js";
19
+ import { readRows } from "./import-curation/internal/runtime-io.js";
18
20
  import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
19
21
  import { foundryRepairSelection, readFoundryRepairPreparation } from "./foundry-workflow-repair.js";
20
22
  import { createFoundryRepairHandoffPlan } from "./foundry-repair-handoff.js";
@@ -293,8 +295,34 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
293
295
  : {}),
294
296
  }));
295
297
  handoff = bindHandoffCommands(context, handoff, inputFile);
298
+ const commands = workflowObject(handoff.commands);
299
+ const edgeType = request.datasetType;
300
+ if (commands.commit &&
301
+ qualified.cli.expectation.package_version === "0.4.0" &&
302
+ isFoundryEdgeDraftType(edgeType)) {
303
+ const finalizePath = resolveFoundryOutput(context, path.resolve(context.assetRoot, String(scope.report)));
304
+ const finalized = workflowObject(JSON.parse(readFoundryInput(context, finalizePath).toString("utf8")));
305
+ const verifyPath = resolveFoundryOutput(context, path.resolve(context.assetRoot, String(workflowObject(finalized.files).remote_verify_report)));
306
+ const referenceEvidence = {
307
+ fact: captureFoundryInput(verifyPath),
308
+ report: JSON.parse(readFoundryInput(context, verifyPath).toString("utf8")),
309
+ };
310
+ commands.commit = buildEdgeSupportPlan(edgeType, captureFoundryInput(inputFile), {
311
+ project_ref: context.accountIntent.projectRef,
312
+ user_id: context.accountIntent.userId,
313
+ }, readRows(inputFile, (file) => readFoundryInput(context, file).toString("utf8")), referenceEvidence, undefined, request.executionContract && captureFoundryInput(request.executionContract.path));
314
+ commands.post_write_verify = null;
315
+ handoff.account_write_guard = {
316
+ ...workflowObject(handoff.account_write_guard),
317
+ execution_precondition: "Foundry must seal the exact Edge create plan for the verified owner.",
318
+ };
319
+ handoff.policy = {
320
+ ...workflowObject(handoff.policy),
321
+ commit_boundary: "The owner submits the sealed Edge create plan and verifies the exact draft and dependencies.",
322
+ };
323
+ }
296
324
  fs.writeFileSync(path.join(output, "handoff", "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
297
- const command = workflowObject(handoff.commands).commit;
325
+ const command = commands.commit;
298
326
  if (command) {
299
327
  const requiredActions = authorization.allowed_actions.filter((action) => request.datasetType === "flow"
300
328
  ? action === "elementary_flow_write" || action === "elementary_flow_create_new"
@@ -334,6 +362,59 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
334
362
  contractFile: request.executionContract.path,
335
363
  outDir: handoffDir,
336
364
  }), inputFile);
365
+ if (qualified.cli.expectation.package_version === "0.4.0") {
366
+ const contract = captureFoundryInput(request.executionContract.path);
367
+ const preparation = captureFoundryInput(request.repairPreparation.path);
368
+ readFoundryInput(context, preparation.path);
369
+ const before = captureFoundryInput(resolveFoundryInputPath(context, foundryRepairSelection(context).before));
370
+ const read = (file) => readFoundryInput(context, file).toString("utf8");
371
+ const preparedEvidence = workflowObject(workflowObject(JSON.parse(read(preparation.path))).evidence);
372
+ const preflight = Array.isArray(preparedEvidence.detail)
373
+ ? preparedEvidence.detail
374
+ .map(workflowObject)
375
+ .find((item) => item.role === "edge_preflight")
376
+ : undefined;
377
+ const ruleVerification = workflowObject(workflowObject(preflight?.report ?? {}).rule_verification ?? {});
378
+ const dependencyFact = Array.isArray(preparedEvidence.files)
379
+ ? preparedEvidence.files
380
+ .map(workflowObject)
381
+ .find((file) => file.role === "edge-repair:out/references/edge-support-precommit.json")
382
+ : undefined;
383
+ if (typeof dependencyFact?.path !== "string")
384
+ throw new FoundryContextError("repair_edge_scope_changed", "Guarded update requires the exact dependency report registered during preparation.");
385
+ const dependencies = resolveFoundryOutput(context, dependencyFact.path);
386
+ const dependencyFile = captureFoundryInput(dependencies);
387
+ if (dependencyFile.sha256 !== dependencyFact.sha256 ||
388
+ dependencyFile.bytes !== dependencyFact.bytes)
389
+ throw new FoundryContextError("repair_edge_scope_changed", "The registered dependency report changed after preparation.");
390
+ const commands = workflowObject(handoff.commands);
391
+ commands.commit = buildEdgeSupportPlan("process", captureFoundryInput(inputFile), {
392
+ project_ref: context.accountIntent.projectRef,
393
+ user_id: context.accountIntent.userId,
394
+ }, readRows(inputFile, read), {
395
+ fact: dependencyFile,
396
+ report: JSON.parse(read(dependencies)),
397
+ }, {
398
+ binding: {
399
+ before,
400
+ contract,
401
+ preparation,
402
+ rule_verification: ruleVerification,
403
+ },
404
+ rows: readRows(before.path, read),
405
+ });
406
+ commands.post_write_verify = null;
407
+ handoff.account_write_guard = {
408
+ target_user_id: context.accountIntent.userId,
409
+ commit_account_binding: "sealed_guarded_edge_update",
410
+ execution_precondition: "Compare the exact reviewed before document inside the Edge save-draft transaction.",
411
+ };
412
+ handoff.policy = {
413
+ commit_boundary: "The sealed owner attempt sends one guarded update and recovers exclusively through exact readback.",
414
+ post_write_verify_required: true,
415
+ compare_root_payload_required: true,
416
+ };
417
+ }
337
418
  fs.writeFileSync(path.join(handoffDir, "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
338
419
  const command = workflowObject(handoff.commands).commit;
339
420
  if (command) {
@@ -3,13 +3,14 @@ import path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { FoundryContextError, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
5
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
6
- import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
6
+ import { withFoundryIsolatedLocalCliEnvironment } from "./foundry-runtime-environment.js";
7
7
  import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
8
8
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
9
9
  import { supportedDatasetTypes } from "./import-curation/internal/dataset-types.js";
10
10
  import { bindWorkflowChildExecution, workflowChildFailure, } from "./foundry-workflow-child-failure.js";
11
11
  import { createWorkflowDirectory } from "./foundry-workflow-io.js";
12
12
  import { readFoundryTaskRuntimeAdoption } from "./foundry-task-runtime-adoption.js";
13
+ import { createTypedContextCommand, projectTypedContext } from "./foundry-typed-context.js";
13
14
  export async function prepareFoundryWorkflowContext(context, qualified, selectedTypes) {
14
15
  assertQualifiedFoundryRuntime(context, qualified);
15
16
  if (!selectedTypes.length || selectedTypes.some((type) => !supportedDatasetTypes.has(type)))
@@ -17,12 +18,13 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
17
18
  const types = [
18
19
  ...new Set(selectedTypes.flatMap((type) => type === "support" ? ["contact", "source", "flowproperty", "unitgroup"] : [type])),
19
20
  ].sort();
21
+ const typed = qualified.cli.expectation.package_version === "0.4.0";
20
22
  const adoption = readFoundryTaskRuntimeAdoption(context);
21
23
  return runFoundryTaskOperation(context, {
22
24
  command: "dataset-context-pack",
23
25
  options: {
24
26
  types,
25
- profile: "ai-import",
27
+ profile: typed ? "default" : "ai-import",
26
28
  ...(adoption ? { runtime_adoption_plan_sha256: adoption.plan_sha256 } : {}),
27
29
  },
28
30
  }, (operation) => {
@@ -39,31 +41,37 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
39
41
  const temporary = createWorkflowDirectory(context, path.join(context.tempRoot, "context-"));
40
42
  try {
41
43
  const cli = resolveInstalledTiangongLcaCliPackage();
42
- const environment = createFoundryIsolatedChildEnvironment({ tempRoot: temporary });
43
44
  const reports = [];
44
45
  for (const type of types) {
45
46
  assertQualifiedFoundryRuntime(context, qualified);
46
47
  const destination = path.join(output, type);
47
- const argv = [
48
- "dataset",
49
- "context-pack",
50
- "--type",
51
- type,
52
- "--profile",
53
- "ai-import",
54
- "--out-dir",
55
- destination,
56
- "--json",
57
- ];
48
+ const outputDirectory = path.join(destination, "outputs");
49
+ const reportPath = path.join(outputDirectory, "contract-report.json");
50
+ const resultPath = path.join(outputDirectory, "contract-result.json");
51
+ if (typed)
52
+ fs.mkdirSync(outputDirectory, { recursive: true, mode: 0o700 });
53
+ const argv = typed
54
+ ? createTypedContextCommand(type, resultPath)
55
+ : [
56
+ "dataset",
57
+ "context-pack",
58
+ "--type",
59
+ type,
60
+ "--profile",
61
+ "ai-import",
62
+ "--out-dir",
63
+ destination,
64
+ "--json",
65
+ ];
58
66
  const execution = bindWorkflowChildExecution(context, qualified, cli.binPath, argv);
59
- const child = spawnSync(process.execPath, [cli.binPath, ...argv], {
67
+ const child = withFoundryIsolatedLocalCliEnvironment(temporary, (env) => spawnSync(process.execPath, [cli.binPath, ...argv], {
60
68
  cwd: context.workspaceRoot,
61
- env: environment,
69
+ env,
62
70
  encoding: "utf8",
63
71
  shell: false,
64
72
  maxBuffer: 8 * 1024 * 1024,
65
73
  timeout: 120_000,
66
- });
74
+ }));
67
75
  const kind = child.error
68
76
  ? "spawn_error"
69
77
  : child.signal
@@ -90,7 +98,40 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
90
98
  !("status" in value) ||
91
99
  value.status !== "completed")
92
100
  throw workflowChildFailure(execution, child, "invalid_report");
93
- reports.push({ type, report: path.join(destination, "outputs/contract-report.json") });
101
+ if (typed) {
102
+ let projected;
103
+ try {
104
+ projected = projectTypedContext(type, resultPath, value, fs.readFileSync(resultPath));
105
+ }
106
+ catch (error) {
107
+ throw workflowChildFailure(execution, child, "invalid_report", error);
108
+ }
109
+ const manifestPath = path.join(outputDirectory, "contract-manifest.json");
110
+ const files = {
111
+ manifest: manifestPath,
112
+ result: resultPath,
113
+ report: reportPath,
114
+ };
115
+ for (const { key, name, text } of projected.files) {
116
+ const file = path.join(outputDirectory, name);
117
+ fs.writeFileSync(file, text, { flag: "wx", mode: 0o600 });
118
+ files[key] = file;
119
+ }
120
+ fs.writeFileSync(manifestPath, JSON.stringify(projected.manifest, null, 2), {
121
+ flag: "wx",
122
+ mode: 0o600,
123
+ });
124
+ fs.writeFileSync(reportPath, JSON.stringify({
125
+ schema_version: 1,
126
+ status: "completed",
127
+ type,
128
+ profile: projected.profile,
129
+ source: projected.source,
130
+ manifest: projected.manifest,
131
+ files,
132
+ }), { flag: "wx", mode: 0o600 });
133
+ }
134
+ reports.push({ type, report: reportPath });
94
135
  }
95
136
  const files = [];
96
137
  const register = (directory) => {