@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
@@ -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>;