@tiangong-lca/foundry 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +19 -5
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +47 -15
  5. package/docs/public-runtime-contract.md +77 -5
  6. package/docs/runtime-context-contract.md +21 -5
  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 +351 -137
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +258 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  13. package/package-dist/scripts/lib/bundle-sample-utils.d.ts +4 -4
  14. package/package-dist/scripts/lib/bundle-source-context.d.ts +6 -4
  15. package/package-dist/scripts/lib/bundle-source-context.js +10 -8
  16. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +16 -6
  17. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +2 -1
  18. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +28 -1
  19. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  20. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  21. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  22. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  23. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  24. package/package-dist/scripts/lib/foundry-execution-admission.js +4 -1
  25. package/package-dist/scripts/lib/foundry-finalize-owners.js +64 -17
  26. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  27. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  28. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  29. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  30. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  31. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  32. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  33. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  34. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  35. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  36. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  37. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  38. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  39. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  40. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  41. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  42. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  43. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +22 -0
  44. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +213 -0
  45. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  46. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  47. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  48. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  49. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  50. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  51. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  52. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  53. package/package-dist/scripts/lib/foundry-runtime-identity.js +3 -1
  54. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  55. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  56. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  57. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  58. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  59. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  60. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  61. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  62. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  63. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  64. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  65. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  66. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  67. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  68. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  69. package/package-dist/scripts/lib/foundry-workflow-assessment.js +149 -18
  70. package/package-dist/scripts/lib/foundry-workflow-authorization.js +17 -4
  71. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  72. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  73. package/package-dist/scripts/lib/foundry-workflow-context.js +37 -8
  74. package/package-dist/scripts/lib/foundry-workflow-finalize.js +37 -0
  75. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  76. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  77. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  78. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +676 -0
  79. package/package-dist/scripts/lib/foundry-workflow-identity.js +10 -1
  80. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  81. package/package-dist/scripts/lib/foundry-workflow-io.js +79 -13
  82. package/package-dist/scripts/lib/foundry-workflow-semantic.js +27 -13
  83. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  84. package/package-dist/scripts/lib/foundry-workflow-state.js +175 -22
  85. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  86. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  87. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +5 -0
  88. package/package-dist/scripts/lib/identity-preflight-proof.js +73 -1
  89. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  90. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  91. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  92. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  93. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +6 -1
  94. package/package-dist/scripts/lib/import-curation/curation-gate.js +48 -2
  95. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  96. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  97. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  98. package/package-dist/scripts/lib/tidas-adapter.js +38 -15
  99. package/package-dist/scripts/lib/tidas-process-flow-context.d.ts +12 -0
  100. package/package-dist/scripts/lib/tidas-process-flow-context.js +96 -0
  101. package/package-dist/scripts/package-entry.js +2 -3
  102. package/package-dist/scripts/public-api.d.ts +5 -0
  103. package/package-dist/scripts/public-api.js +2 -0
  104. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  105. package/package-dist/scripts/runtime-entry.js +42 -15
  106. package/package.json +6 -2
  107. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  108. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  109. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  110. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  111. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  112. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  113. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  114. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -6,6 +6,7 @@ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.
6
6
  import { verifyFoundryRuntimeIdentity, } from "./foundry-runtime-identity.js";
7
7
  import { createFoundryAuthenticationEnvironment } from "./foundry-authentication-environment.js";
8
8
  import { createFoundryIsolatedChildEnvironment, copyFoundryIsolatedExecutable, } from "./foundry-runtime-environment.js";
9
+ import { WorkflowChildFailure } from "./foundry-workflow-child-failure.js";
9
10
  import { createFoundryFinalizeOwners } from "./foundry-finalize-owners.js";
10
11
  import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
11
12
  import { runFoundryTaskOperation, withFoundryTaskMetadata } from "./foundry-task-store.js";
@@ -14,12 +15,14 @@ import { readTaskBytes } from "./foundry-task-io.js";
14
15
  import { loadFoundryTaskAuthorization } from "./foundry-task-authorization.js";
15
16
  import { taskAuthorizationMatches } from "./task-authorization.js";
16
17
  import { createHash } from "node:crypto";
18
+ import { loadFoundryQualityReview } from "./foundry-quality-review.js";
17
19
  export async function finalizeFoundryWorkflow(context, qualified, entries, authentication = { mode: "oauth" }, approval, executionProgress) {
18
20
  assertQualifiedFoundryRuntime(context, qualified);
19
21
  const state = currentWorkflowState(context, entries), rows = state.rows;
20
22
  if (!rows || !state.assessment || !state.assessmentComplete)
21
23
  throw new FoundryContextError("workflow_assessment_required", "Assess the current rows before finalization.");
22
24
  const referenceOptions = new Map();
25
+ const qualityReview = loadFoundryQualityReview(context, qualified, entries);
23
26
  for (const set of rows.value.sets) {
24
27
  if (executionProgress?.scopes.has(set.type))
25
28
  continue;
@@ -166,6 +169,9 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
166
169
  type: ["unitgroup", "flowproperty"].includes(set.type) ? "support" : set.type,
167
170
  rowsFile: set.file,
168
171
  ...referenceOptions.get(set.type),
172
+ ...(set.type === "process" && qualityReview
173
+ ? { qualityReview, qaReferenceRows: [...qualityReview.qaReferenceRows] }
174
+ : {}),
169
175
  outDir: path.join(output, set.type),
170
176
  profile,
171
177
  ...(approval?.datasetType === set.type && authorization
@@ -261,11 +267,17 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
261
267
  options: {
262
268
  nonce,
263
269
  rows_report: rows.file,
270
+ ...(state.qualityReviewSha256
271
+ ? { quality_review_sha256: state.qualityReviewSha256 }
272
+ : {}),
264
273
  ...(state.referenceInputsSha256
265
274
  ? { reference_inputs_sha256: state.referenceInputsSha256 }
266
275
  : {}),
267
276
  },
268
277
  validateCurrent(index) {
278
+ if (currentWorkflowState(context, index).qualityReviewSha256 !== state.qualityReviewSha256)
279
+ throw new FoundryContextError("quality_review_changed", "Quality review changed during finalization.");
280
+ qualityReview?.validate();
269
281
  const current = currentWorkflowState(context, index);
270
282
  if (current.rows?.entry.sha256 !== rows.entry.sha256)
271
283
  throw new FoundryContextError("workflow_rows_changed", "Rows changed during finalization.");
@@ -291,6 +303,9 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
291
303
  ? { reference_inputs_sha256: state.referenceInputsSha256 }
292
304
  : {}),
293
305
  assessment_report: state.assessment.file,
306
+ ...(state.qualityReviewSha256
307
+ ? { quality_review_sha256: state.qualityReviewSha256 }
308
+ : {}),
294
309
  owner_base: context.assetRoot,
295
310
  approval_source_sha256: approval?.sourceSha256 ?? null,
296
311
  approval_authorization_sha256: approval?.authorizationSha256 ?? null,
@@ -302,6 +317,28 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
302
317
  return result;
303
318
  });
304
319
  }
320
+ catch (error) {
321
+ if (!(error instanceof WorkflowChildFailure))
322
+ throw error;
323
+ // The read/local call already occurred outside the replayable transaction. Register only
324
+ // its actual captured failure; the callback cannot dispatch or reconstruct an earlier call.
325
+ return await runFoundryTaskOperation(context, {
326
+ command: "dataset-workflow-finalize",
327
+ options: {
328
+ nonce,
329
+ rows_report: rows.file,
330
+ failure_execution_id: error.evidence.execution_id,
331
+ ...(state.qualityReviewSha256
332
+ ? { quality_review_sha256: state.qualityReviewSha256 }
333
+ : {}),
334
+ ...(state.referenceInputsSha256
335
+ ? { reference_inputs_sha256: state.referenceInputsSha256 }
336
+ : {}),
337
+ },
338
+ }, () => {
339
+ throw error;
340
+ });
341
+ }
305
342
  finally {
306
343
  delete environment.TIANGONG_LCA_ACCESS_TOKEN;
307
344
  fs.rmSync(temporary, { recursive: true, force: true });
@@ -0,0 +1,6 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ import { type AuthIdentityReceipt } from "./identity-preflight-proof.ts";
4
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ /** A new local interpretation, retaining the original failed attempts and their query/auth facts. */
6
+ export declare function recoverFoundryWorkflowIdentity(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, entries: readonly ArtifactEntry[], currentAuth: AuthIdentityReceipt): Promise<Record<string, unknown> | null>;
@@ -0,0 +1,450 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { assertCliRuntimeMatches } from "@tiangong-lca/cli/runtime";
5
+ import { readFoundryTaskRuntimeAdoptionChain } from "./foundry-task-runtime-adoption.js";
6
+ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
7
+ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
8
+ import { currentWorkflowState, workflowObject } from "./foundry-workflow-state.js";
9
+ import { runFoundryTaskOperation } from "./foundry-task-store.js";
10
+ import { readTaskBytes } from "./foundry-task-io.js";
11
+ import { createFileArtifactFact, createFoundryCommandSpec } from "./foundry-command-spec.js";
12
+ import { createIdentityPreflightBinding, sha256Text, sha256Json, stableJson, validateIdentityPreflightExecution, parseFreshIntentBoundAuthReceipt, } from "./identity-preflight-proof.js";
13
+ import { validateIdentityPreflightRecoveryEvidence, observeRetainedIdentityExecutable, verifyRetainedIdentityCliInventory, } from "./identity-preflight-recovery-proof.js";
14
+ import { assertNoPendingFoundryIdentityStage } from "./foundry-identity-stage-state.js";
15
+ function fail(reason = "evidence") {
16
+ throw new FoundryContextError("identity_preflight_recovery_unproven", `Retained manual-review evidence cannot be recovered under its original producer binding (${reason}). No new search was dispatched.`);
17
+ }
18
+ /** A new local interpretation, retaining the original failed attempts and their query/auth facts. */
19
+ export async function recoverFoundryWorkflowIdentity(context, qualified, entries, currentAuth) {
20
+ assertQualifiedFoundryRuntime(context, qualified);
21
+ assertNoPendingFoundryIdentityStage(context, entries);
22
+ try {
23
+ return await recoverRetainedIdentity(context, qualified, entries, currentAuth);
24
+ }
25
+ catch (error) {
26
+ if (error instanceof FoundryContextError &&
27
+ error.code === "identity_preflight_recovery_unproven")
28
+ throw error;
29
+ return fail("original-evidence-unreadable");
30
+ }
31
+ }
32
+ async function recoverRetainedIdentity(context, qualified, entries, currentAuth) {
33
+ const state = currentWorkflowState(context, entries), original = state.identity, rows = state.rows, assessment = state.retainedAssessment ?? state.assessment;
34
+ if (!original || original.value.status !== "blocked")
35
+ return null;
36
+ if (original.value.explicit_new_stage === true)
37
+ throw new FoundryContextError("identity_stage_unproven", "The explicitly dispatched new read-only stage remains unproven. Inspect its retained claim and outcome evidence; ordinary resume cannot dispatch another query.");
38
+ if (!rows || !assessment || !Array.isArray(original.value.sets) || !original.value.sets.length)
39
+ fail("original-stage-context-missing");
40
+ const originalSets = original.value.sets.map(workflowObject);
41
+ const producerBase = String(original.value.owner_base ?? assessment.value.owner_base);
42
+ const resolve = (file) => {
43
+ if (typeof file !== "string")
44
+ fail("locator");
45
+ return resolveFoundryOutput(context, path.resolve(producerBase, file));
46
+ };
47
+ const fact = (file, sameProducer = true) => {
48
+ const entry = entries.find((item) => resolveFoundryOutput(context, item.path) === file);
49
+ if (!entry || (sameProducer && entry.operation_id !== original.entry.operation_id))
50
+ fail("native-producer");
51
+ const bytes = readFoundryInput(context, file);
52
+ if (bytes.length !== entry.bytes || sha256Text(bytes.toString("utf8")) !== entry.sha256)
53
+ fail("artifact-bytes");
54
+ return { path: file, bytes: entry.bytes, sha256: entry.sha256 };
55
+ };
56
+ const json = (file) => workflowObject(JSON.parse(readFoundryInput(context, file).toString("utf8")));
57
+ const runs = originalSets
58
+ .map((set) => ({ set, file: resolve(set.report) }))
59
+ .map(({ set, file }) => ({ set, file, value: json(file) }));
60
+ if (runs.some(({ value }) => !Array.isArray(value.results) || !value.results.length))
61
+ fail("original-attempt-results-missing");
62
+ // Only the previously rejected, known manual-review contract is eligible. Other failures keep their normal retry contract.
63
+ const diagnosticRows = runs.flatMap(({ value }) => Array.isArray(value.results) ? value.results.map(workflowObject) : []);
64
+ if (runs.some(({ value }) => !Array.isArray(value.results) ||
65
+ !value.results.length ||
66
+ value.results.some((item) => {
67
+ const row = workflowObject(item);
68
+ return (row.report_status !== "needs_review" ||
69
+ row.decision !== "manual_review" ||
70
+ row.failure_code !== "identity_preflight_cli_exit_nonzero" ||
71
+ row.cli_exit_code !== 1);
72
+ }))) {
73
+ if (diagnosticRows.every((row) => row.status === "failed" && row.report_status === "failed" && !row.decision)) {
74
+ const provenFailedReports = diagnosticRows.every((row) => {
75
+ const file = resolve(row.report_file), stdout = resolve(row.stdout_log);
76
+ fact(file);
77
+ fact(stdout);
78
+ const report = json(file);
79
+ return (report.status === "failed" &&
80
+ !report.decision &&
81
+ stableJson(report) ===
82
+ stableJson(JSON.parse(readFoundryInput(context, stdout).toString("utf8"))));
83
+ });
84
+ if (provenFailedReports)
85
+ return null;
86
+ }
87
+ fail("mixed-or-unknown-original-attempt");
88
+ }
89
+ const expectedSets = rows.value.sets.filter((set) => ["flow", "process"].includes(set.type));
90
+ if (runs.length !== expectedSets.length ||
91
+ new Set(runs.map(({ set }) => set.type)).size !== expectedSets.length)
92
+ fail("row-coverage");
93
+ const output = resolveFoundryOutput(context, `outputs/identity-recovery/${randomUUID()}`);
94
+ const receiptPath = resolveFoundryOutput(context, original.entry.receipt.path), receiptBytes = readTaskBytes(context, original.entry.receipt.path), receipt = workflowObject(JSON.parse(receiptBytes.toString("utf8")));
95
+ if (sha256Text(receiptBytes.toString("utf8")) !== original.entry.receipt.sha256)
96
+ fail("producer-receipt");
97
+ const planPath = resolveFoundryOutput(context, String(workflowObject(receipt.plan).path));
98
+ const planFact = captureFoundryInput(planPath), receiptFact = captureFoundryInput(receiptPath), jobFact = captureFoundryInput(resolveFoundryOutput(context, "foundry-job.json"));
99
+ const recoveries = [];
100
+ const recoveredAt = new Date().toISOString();
101
+ const interpretationAuth = {
102
+ project_ref: currentAuth.project.project_ref,
103
+ user_id: currentAuth.identity.user_id,
104
+ receipt_scope_sha256: currentAuth.receipt_scope_sha256,
105
+ captured_at_utc: currentAuth.captured_at_utc,
106
+ };
107
+ for (const { set, file: runFile, value: run } of runs) {
108
+ const selected = expectedSets.find((item) => item.type === set.type);
109
+ if (!selected ||
110
+ selected.file !== set.rows ||
111
+ run.status !== "failed" ||
112
+ run.command !== "dataset-identity-preflight-run" ||
113
+ run.remote_write_mode !== "read-only")
114
+ fail("row-source");
115
+ const indexFile = resolve(set.index), sourceRun = fact(runFile), indexFact = fact(indexFile);
116
+ const indexRows = readFoundryInput(context, indexFile)
117
+ .toString("utf8")
118
+ .trim()
119
+ .split(/\r?\n/u)
120
+ .map((line) => workflowObject(JSON.parse(line)));
121
+ const results = run.results.map(workflowObject), options = workflowObject(run.runtime_options), cli = workflowObject(options.cli), originalAuth = workflowObject(options.auth_receipt);
122
+ const prefix = cli.args_prefix;
123
+ if (indexRows.length !== results.length ||
124
+ indexRows.length !== selected.count ||
125
+ options.max_attempts !== 1 ||
126
+ options.retry_failed !== null ||
127
+ ![
128
+ "@tiangong-lca/cli@0.1.22",
129
+ "@tiangong-lca/cli@0.1.27",
130
+ "@tiangong-lca/cli@0.1.28",
131
+ ].includes(String(cli.package)) ||
132
+ !Array.isArray(prefix) ||
133
+ prefix.length !== 1 ||
134
+ typeof prefix[0] !== "string" ||
135
+ originalAuth.project_ref !== interpretationAuth.project_ref ||
136
+ originalAuth.user_id !== interpretationAuth.user_id ||
137
+ typeof originalAuth.receipt_scope_sha256 !== "string")
138
+ fail("cli-account-runtime");
139
+ const retainedNode = observeRetainedIdentityExecutable(String(cli.executable));
140
+ if (!retainedNode || retainedNode.sha256 !== qualified.cli.expectation.node_sha256)
141
+ fail("retained-original-node-unproven");
142
+ const parent = path.dirname(path.dirname(indexFile)), preparedFile = path.join(parent, "dataset-identity-preflight-requests-build-report.json"), auditFile = path.join(parent, "query-audit", "dataset-identity-preflight-query-audit-report.json"), prepared = json(preparedFile), audit = json(auditFile);
143
+ if (prepared.status !== "ready" ||
144
+ audit.status !== "passed" ||
145
+ !Array.isArray(audit.blockers) ||
146
+ audit.blockers.length ||
147
+ resolve(run.index_file) !== indexFile)
148
+ fail("query-audit");
149
+ // A digest-only producer summary is not the original authenticated receipt.
150
+ // Recovery never substitutes the new interpreter's receipt for that missing preimage.
151
+ if (typeof originalAuth.file !== "string")
152
+ fail("original-authentication-receipt-missing");
153
+ const authLocator = path.resolve(producerBase, originalAuth.file);
154
+ if (!entries.some((entry) => entry.operation_id === original.entry.operation_id &&
155
+ resolveFoundryOutput(context, entry.path) === authLocator))
156
+ fail("original-authentication-receipt-missing");
157
+ const originalAuthFile = resolve(originalAuth.file);
158
+ const originalAuthFact = fact(originalAuthFile);
159
+ let originalReceipt;
160
+ try {
161
+ originalReceipt = parseFreshIntentBoundAuthReceipt(json(originalAuthFile), {
162
+ nowMs: Date.parse(String(prepared.generated_at_utc)),
163
+ // Preserve the original read-only owner's receipt policy; this does not
164
+ // change the current task's independent 60-second permission admission.
165
+ maxAgeMs: 300_000,
166
+ expectedProjectRef: interpretationAuth.project_ref,
167
+ expectedUserId: interpretationAuth.user_id,
168
+ });
169
+ }
170
+ catch {
171
+ fail("original-authentication-receipt-invalid");
172
+ }
173
+ if (originalReceipt.receipt_scope_sha256 !== originalAuth.receipt_scope_sha256 ||
174
+ `${originalReceipt.cli.package_name}@${originalReceipt.cli.package_version}` !== cli.package)
175
+ fail("original-authentication-receipt-binding");
176
+ const originalCliIntegrity = `sha256-${sha256Text(readCli(prefix[0]))}`;
177
+ const originalCliVersion = String(cli.package).slice("@tiangong-lca/cli@".length);
178
+ const chain = readFoundryTaskRuntimeAdoptionChain(context);
179
+ const prior = chain?.plans.find((plan) => {
180
+ const entry = workflowObject(workflowObject(plan.selection).original_entry);
181
+ return (typeof entry.path === "string" && path.resolve(entry.path, "../../..") === producerBase);
182
+ });
183
+ const currentCli = assertCliRuntimeMatches(qualified.cli.expectation);
184
+ const selectedCli = prior
185
+ ? workflowObject(workflowObject(workflowObject(prior.selection).qualification).original_cli)
186
+ : { expectation: qualified.cli.expectation, files: currentCli.files };
187
+ const expectedCli = workflowObject(selectedCli.expectation);
188
+ if (expectedCli.package_version !== originalCliVersion || !Array.isArray(selectedCli.files))
189
+ fail("retained-original-cli-inventory-unqualified");
190
+ const cliInventory = {
191
+ role: "current_retained_cli_inventory",
192
+ root: fs.realpathSync(path.dirname(path.dirname(prefix[0]))),
193
+ package_version: originalCliVersion,
194
+ content_sha256: String(expectedCli.content_sha256),
195
+ files: selectedCli.files,
196
+ };
197
+ try {
198
+ verifyRetainedIdentityCliInventory(cliInventory, prefix[0]);
199
+ }
200
+ catch {
201
+ fail("retained-original-cli-inventory-changed");
202
+ }
203
+ const resultsFile = resolve(workflowObject(run.files).results), resultsText = readFoundryInput(context, resultsFile).toString("utf8").trim();
204
+ if (stableJson(resultsText.split(/\r?\n/u).map((line) => JSON.parse(line))) !==
205
+ stableJson(results))
206
+ fail("original-results");
207
+ const destination = path.join(output, String(set.type));
208
+ const proofs = [], recoveredRows = [];
209
+ for (const requestRow of indexRows) {
210
+ const result = results.find((row) => row.dataset_type === requestRow.dataset_type &&
211
+ row.dataset_id === requestRow.dataset_id &&
212
+ row.dataset_version === requestRow.dataset_version);
213
+ if (!result ||
214
+ result.status !== "failed" ||
215
+ result.attempt !== 1 ||
216
+ result.attempts !== 1 ||
217
+ (result.signal ?? null) !== null)
218
+ fail("attempt");
219
+ const requestFile = resolve(requestRow.request_file), reportFile = resolve(requestRow.expected_report_file), outputDir = resolve(requestRow.output_dir), sourceFile = resolve(requestRow.source_file), stdoutFile = resolve(result.stdout_log), stderrFile = resolve(result.stderr_log);
220
+ const requestText = readFoundryInput(context, requestFile).toString("utf8"), request = workflowObject(JSON.parse(requestText));
221
+ if (sourceFile !== selected.file ||
222
+ requestRow.request_bytes_sha256 !== sha256Text(requestText) ||
223
+ requestRow.request_json_sha256 !== sha256Text(JSON.stringify(request)) ||
224
+ requestRow.target_sha256 !== sha256Text(JSON.stringify(request.target)))
225
+ fail("request-source-hashes");
226
+ const timeout = String(options.timeout_ms), argv = [
227
+ String(set.type),
228
+ "identity-preflight",
229
+ "--input",
230
+ requestFile,
231
+ "--out-dir",
232
+ outputDir,
233
+ "--json",
234
+ "--timeout-ms",
235
+ timeout,
236
+ ];
237
+ if (stableJson(result.cli_args) !== stableJson(argv) ||
238
+ result.executable !== cli.executable ||
239
+ result.cli_package !== cli.package ||
240
+ resolve(result.request_file) !== requestFile ||
241
+ resolve(result.report_file) !== reportFile)
242
+ fail("argv");
243
+ const spec = createFoundryCommandSpec({
244
+ executable: String(cli.executable),
245
+ argv: [...prefix, ...argv],
246
+ binding: {
247
+ artifacts: [
248
+ createFileArtifactFact({
249
+ role: "identity_preflight_request",
250
+ path: String(requestRow.request_file),
251
+ filePath: requestFile,
252
+ }),
253
+ ],
254
+ },
255
+ });
256
+ if (stableJson(result.command_spec) !== stableJson(spec))
257
+ fail("command-spec");
258
+ const binding = createIdentityPreflightBinding({
259
+ datasetType: String(set.type),
260
+ datasetId: String(requestRow.dataset_id),
261
+ datasetVersion: String(requestRow.dataset_version),
262
+ targetSha256: String(requestRow.target_sha256),
263
+ requestText,
264
+ semanticArgv: [String(set.type), "identity-preflight", "--json", "--timeout-ms", timeout],
265
+ cli: {
266
+ packageName: "@tiangong-lca/cli",
267
+ packageVersion: originalCliVersion,
268
+ packageIntegrity: originalCliIntegrity,
269
+ },
270
+ authReceipt: originalReceipt,
271
+ relevantInputHashes: {
272
+ ...workflowObject(requestRow.relevant_input_hashes ?? {}),
273
+ source_file: fact(sourceFile, false).sha256,
274
+ },
275
+ });
276
+ if (binding.binding_sha256 !== result.binding_sha256)
277
+ fail("binding");
278
+ const reportText = readFoundryInput(context, reportFile).toString("utf8"), report = workflowObject(JSON.parse(reportText));
279
+ const checked = validateIdentityPreflightExecution({
280
+ binding,
281
+ exitCode: 1,
282
+ stdoutText: readFoundryInput(context, stdoutFile).toString("utf8"),
283
+ diskReportText: reportText,
284
+ startedAtMs: Date.parse(String(prepared.generated_at_utc)),
285
+ diskReportMtimeMs: fs.statSync(reportFile).mtimeMs,
286
+ completedAtUtc: String(run.generated_at_utc),
287
+ requestFile,
288
+ outputDir,
289
+ reportFile,
290
+ stderrText: readFoundryInput(context, stderrFile).toString("utf8"),
291
+ signal: null,
292
+ });
293
+ if (!checked.ok)
294
+ fail(String(checked.code));
295
+ const { inputs: _inputs, ...evidence } = binding;
296
+ const scope = {
297
+ schema: "tiangong-foundry.identity-preflight-recovery.v1",
298
+ task_id: context.taskId,
299
+ actor_id: context.actorId,
300
+ new_cli_execution: false,
301
+ binding: evidence,
302
+ binding_sha256: binding.binding_sha256,
303
+ original: {
304
+ producer_base: producerBase,
305
+ attempt: 1,
306
+ status: "failed",
307
+ failure_code: "identity_preflight_cli_exit_nonzero",
308
+ cli_exit_code: 1,
309
+ producer_auth: {
310
+ project_ref: String(originalAuth.project_ref),
311
+ user_id: String(originalAuth.user_id),
312
+ receipt_scope_sha256: originalAuth.receipt_scope_sha256,
313
+ captured_at_utc: originalReceipt.captured_at_utc,
314
+ },
315
+ batch_prepared_at_utc: String(prepared.generated_at_utc),
316
+ query_generated_at_utc: String(report.generated_at_utc),
317
+ batch_completed_at_utc: String(run.generated_at_utc),
318
+ facts: {
319
+ assessment: fact(assessment.file, false),
320
+ auth_receipt: originalAuthFact,
321
+ source_file: fact(sourceFile, false),
322
+ stage: fact(original.file),
323
+ run: sourceRun,
324
+ results: fact(resultsFile),
325
+ preparation: fact(preparedFile),
326
+ audit: fact(auditFile),
327
+ request: fact(requestFile),
328
+ stdout: fact(stdoutFile),
329
+ stderr: fact(stderrFile),
330
+ report: fact(reportFile),
331
+ producer_receipt: receiptFact,
332
+ producer_plan: planFact,
333
+ job: jobFact,
334
+ index: indexFact,
335
+ },
336
+ },
337
+ current_owner_interpretation_auth: interpretationAuth,
338
+ recovered_at_utc: recoveredAt,
339
+ current_retained_runtime_observation: {
340
+ role: "current_retained_runtime_observation",
341
+ observed_at_utc: recoveredAt,
342
+ original_executable: retainedNode,
343
+ qualified_node_sha256: qualified.cli.expectation.node_sha256,
344
+ },
345
+ current_retained_cli_inventory: cliInventory,
346
+ };
347
+ const proof = { ...scope, proof_sha256: sha256Json(scope) };
348
+ if (!validateIdentityPreflightRecoveryEvidence(proof, {
349
+ requestText,
350
+ reportText,
351
+ datasetType: binding.dataset.type,
352
+ datasetId: binding.dataset.id,
353
+ datasetVersion: binding.dataset.version,
354
+ targetSha256: binding.dataset.target_sha256,
355
+ expectedProjectRef: interpretationAuth.project_ref,
356
+ expectedUserId: interpretationAuth.user_id,
357
+ expectedRetainedCliContentSha256: cliInventory.content_sha256,
358
+ }).ok)
359
+ fail("recovery-contract");
360
+ const proofFile = path.join(destination, `${binding.dataset.id}.recovery.json`);
361
+ proofs.push({ file: proofFile, proof });
362
+ recoveredRows.push({
363
+ ...requestRow,
364
+ source_file: sourceFile,
365
+ request_file: requestFile,
366
+ output_dir: outputDir,
367
+ expected_report_file: reportFile,
368
+ expected_candidates_file: resolve(requestRow.expected_candidates_file),
369
+ expected_candidate_sources_file: resolve(requestRow.expected_candidate_sources_file),
370
+ recovery_manifest_file: proofFile,
371
+ recovery_cli_content_sha256: cliInventory.content_sha256,
372
+ });
373
+ }
374
+ recoveries.push({
375
+ type: String(set.type),
376
+ rows: selected.file,
377
+ index: path.join(destination, "identity-preflight-requests.jsonl"),
378
+ report: path.join(destination, "dataset-identity-preflight-recovery-report.json"),
379
+ proofs,
380
+ indexRows: recoveredRows,
381
+ sourceRun,
382
+ });
383
+ }
384
+ return runFoundryTaskOperation(context, {
385
+ command: "dataset-workflow-identity",
386
+ options: { recovery_of: original.entry.sha256, rows_report: rows.file },
387
+ validateCurrent(index) {
388
+ if (currentWorkflowState(context, index).identity?.entry.sha256 !== original.entry.sha256 ||
389
+ currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
390
+ fail("current-generation");
391
+ },
392
+ }, (operation) => {
393
+ for (const recovered of recoveries) {
394
+ for (const item of recovered.proofs)
395
+ operation.writeJson(item.file, item.proof);
396
+ operation.writeText(recovered.index, recovered.indexRows.map((item) => JSON.stringify(item)).join("\n") + "\n");
397
+ operation.writeJson(recovered.report, {
398
+ schema: "tiangong-foundry.identity-recovery-stage.v1",
399
+ status: "completed_with_identity_findings",
400
+ new_cli_execution: false,
401
+ original_run: recovered.sourceRun,
402
+ recovered_queries: recovered.proofs.length,
403
+ current_owner_interpretation_auth: interpretationAuth,
404
+ proofs: recovered.proofs.map((item) => ({
405
+ file: item.file,
406
+ sha256: item.proof.proof_sha256,
407
+ })),
408
+ });
409
+ }
410
+ const combined = path.join(output, "identity-preflight-requests.jsonl");
411
+ operation.writeText(combined, recoveries
412
+ .flatMap((item) => item.indexRows)
413
+ .map((item) => JSON.stringify(item))
414
+ .join("\n") + "\n");
415
+ const result = {
416
+ schema: "tiangong-foundry.identity-stage.v1",
417
+ status: "completed",
418
+ mode: "registered-manual-review-recovery",
419
+ new_cli_execution: false,
420
+ rows_report: rows.file,
421
+ owner_base: context.assetRoot,
422
+ account: {
423
+ project_ref: interpretationAuth.project_ref,
424
+ user_id: interpretationAuth.user_id,
425
+ },
426
+ checked_at_utc: recoveredAt,
427
+ original_identity_report: fact(original.file),
428
+ index: combined,
429
+ sets: recoveries.map(({ type, rows: file, index, report }) => ({
430
+ type,
431
+ rows: file,
432
+ index,
433
+ report,
434
+ status: "completed_with_identity_findings",
435
+ })),
436
+ blockers: [],
437
+ };
438
+ operation.writeJson(path.join(output, "foundry-identity.json"), result);
439
+ return result;
440
+ });
441
+ }
442
+ function readCli(file) {
443
+ return readIdentityCli(file);
444
+ }
445
+ function readIdentityCli(file) {
446
+ const canonical = fs.realpathSync(file);
447
+ if (!fs.lstatSync(file).isFile() || !fs.statSync(canonical).isFile())
448
+ fail("cli-entry");
449
+ return fs.readFileSync(canonical, "utf8");
450
+ }
@@ -0,0 +1,9 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ import { type FoundryAuthentication } from "./foundry-runtime-identity.ts";
4
+ import { type SelectedFoundryIdentityStageInput } from "./foundry-identity-stage-input.ts";
5
+ import type { ArtifactEntry, JsonRecord } from "./foundry-task-types.ts";
6
+ /** An explicit new read-only execution. Its local transactions only prepare or capture evidence. */
7
+ export declare function runExplicitFoundryIdentityStage(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, entries: readonly ArtifactEntry[], selected: SelectedFoundryIdentityStageInput, authentication?: FoundryAuthentication, options?: {
8
+ readonly signal?: AbortSignal;
9
+ }): Promise<JsonRecord>;