@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
@@ -34,7 +34,9 @@ export declare function workflowObject(value: unknown): Record<string, unknown>;
34
34
  export declare function readWorkflowArtifact(context: FoundryRuntimeContext, entry: ArtifactEntry): WorkflowArtifact<Record<string, unknown>>;
35
35
  export declare function currentWorkflowState(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): {
36
36
  rows: WorkflowArtifact<WorkflowRows> | null;
37
+ currentContextReports: string[];
37
38
  assessment: WorkflowArtifact<WorkflowAssessment> | null;
39
+ retainedAssessment: WorkflowArtifact<WorkflowAssessment> | null;
38
40
  assessmentComplete: boolean;
39
41
  assessmentRemainingTypes: string[];
40
42
  interactionSha256: string | null;
@@ -44,4 +46,6 @@ export declare function currentWorkflowState(context: FoundryRuntimeContext, ent
44
46
  preparedApproval: WorkflowArtifact<Record<string, unknown>> | null;
45
47
  referenceInputs: Map<string, WorkflowArtifact<Record<string, unknown>>>;
46
48
  referenceInputsSha256: string | null;
49
+ qualityReview: WorkflowArtifact<Record<string, unknown>> | null;
50
+ qualityReviewSha256: string | null;
47
51
  };
@@ -5,6 +5,12 @@ import { captureFoundryInput, FoundryContextError, resolveFoundryOutput, } from
5
5
  import { readTaskBytes } from "./foundry-task-io.js";
6
6
  import { sha256Json } from "./identity-preflight-proof.js";
7
7
  import { applicableFoundryInteractionDigest } from "./foundry-interaction-projection.js";
8
+ import { qualityReviewInteractionDigest } from "./foundry-quality-review-context.js";
9
+ import { readRows } from "./import-curation/internal/runtime-io.js";
10
+ import { projectFoundryValidationReferences } from "./foundry-validation-reference-context.js";
11
+ import { parseFoundryPreparationCliReport } from "./foundry-preparation-cli-validation.js";
12
+ import { readFoundryTaskRuntimeAdoption, readFoundryTaskRuntimeAdoptionChain, } from "./foundry-task-runtime-adoption.js";
13
+ import { verifyRegisteredAssessmentProducer } from "./foundry-assessment-producer.js";
8
14
  /**
9
15
  * The repair producer's registration of the preparation report. These two values are repeated here
10
16
  * rather than imported so this projection module stays a graph leaf; the public repair suite fails
@@ -58,6 +64,30 @@ export function readWorkflowArtifact(context, entry) {
58
64
  }
59
65
  }
60
66
  export function currentWorkflowState(context, entries) {
67
+ let adoption;
68
+ const runtimeAdoption = () => {
69
+ if (adoption === undefined)
70
+ adoption = readFoundryTaskRuntimeAdoption(context);
71
+ return adoption;
72
+ };
73
+ let retainedRuntimeRoots;
74
+ const assessmentOwner = (value, entry, report) => {
75
+ if (value === context.assetRoot)
76
+ return "current";
77
+ if (retainedRuntimeRoots === undefined) {
78
+ runtimeAdoption();
79
+ retainedRuntimeRoots =
80
+ readFoundryTaskRuntimeAdoptionChain(context)?.retained_runtime_roots ?? [];
81
+ }
82
+ if (typeof value === "string" && retainedRuntimeRoots.includes(value)) {
83
+ verifyRegisteredAssessmentProducer(context, entry, report, entries);
84
+ return "adopted_original";
85
+ }
86
+ if (!runtimeAdoption() &&
87
+ verifyRegisteredAssessmentProducer(context, entry, report, entries) === value)
88
+ return "current";
89
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment owner is neither the current runtime nor its verified adopted predecessor.");
90
+ };
61
91
  const rowEntry = entries.findLast((entry) => ["dataset-workflow-rows", "dataset-semantic-apply"].includes(entry.command) &&
62
92
  path.basename(entry.path) === "foundry-rows.json");
63
93
  let rows = null;
@@ -123,16 +153,78 @@ export function currentWorkflowState(context, entries) {
123
153
  throw new FoundryContextError("workflow_interaction_invalid", "Registered task decisions are invalid.");
124
154
  const interaction = interactionValue;
125
155
  const contextShaByType = new Map();
156
+ const contextFilesByType = new Map();
157
+ const originalContextFacts = new Map((readFoundryTaskRuntimeAdoptionChain(context)?.prior_context_reports ?? []).map((item) => {
158
+ const fact = workflowObject(item);
159
+ return [fact.path, fact];
160
+ }));
126
161
  for (const entry of entries) {
127
162
  if (entry.command !== "dataset-context-pack" ||
128
163
  path.basename(entry.path) !== "contract-report.json")
129
164
  continue;
130
165
  const report = readWorkflowArtifact(context, entry).value;
131
- if (report.status === "completed" && typeof report.type === "string")
166
+ const original = originalContextFacts.get(entry.path);
167
+ if (original && original.sha256 === entry.sha256 && original.bytes === entry.bytes)
168
+ continue;
169
+ if (report.status === "completed" && typeof report.type === "string") {
132
170
  contextShaByType.set(report.type, entry.sha256);
171
+ contextFilesByType.set(report.type, resolveFoundryOutput(context, entry.path));
172
+ }
173
+ }
174
+ const referenceInputs = new Map();
175
+ for (const entry of entries) {
176
+ if (entry.command !== "dataset-workflow-reference-input" ||
177
+ path.basename(entry.path) !== "foundry-reference-input.json")
178
+ continue;
179
+ const found = readWorkflowArtifact(context, entry);
180
+ if (found.value.schema !== "tiangong-foundry.reference-selection.v1" ||
181
+ found.value.status !== "selected" ||
182
+ typeof found.value.dataset_type !== "string")
183
+ throw new FoundryContextError("reference_input_invalid", "Registered reference selection is invalid.");
184
+ referenceInputs.set(found.value.dataset_type, found);
185
+ }
186
+ const referenceInputsSha256 = referenceInputs.size
187
+ ? createHash("sha256")
188
+ .update(JSON.stringify([...referenceInputs]
189
+ .sort(([a], [b]) => a.localeCompare(b))
190
+ .map(([type, found]) => [type, found.entry.sha256])))
191
+ .digest("hex")
192
+ : null;
193
+ const qualityEntry = entries.findLast((entry) => entry.command === "dataset-workflow-quality-review" &&
194
+ path.basename(entry.path) === "foundry-quality-review.json");
195
+ const qualityReview = qualityEntry ? readWorkflowArtifact(context, qualityEntry) : null;
196
+ let qualityReviewSha256 = null;
197
+ if (qualityReview) {
198
+ const value = qualityReview.value;
199
+ if (value.schema !== "tiangong-foundry.quality-review-receipt.v1" ||
200
+ value.status !== "accepted" ||
201
+ value.grants_permission !== false)
202
+ throw new FoundryContextError("quality_review_invalid", "Registered quality review is invalid.");
203
+ const input = workflowObject(value.input), bound = workflowObject(input.binding);
204
+ const processRows = rows?.value.sets.find((set) => set.type === "process");
205
+ const now = Date.now();
206
+ if (input.rows_manifest_sha256 === rows?.entry.sha256 &&
207
+ input.context_sha256 === contextShaByType.get("process") &&
208
+ input.reference_inputs_sha256 === referenceInputsSha256 &&
209
+ sha256Json(value.runtime) === sha256Json(context.runtime) &&
210
+ bound.workspace_id === context.workspaceId &&
211
+ bound.task_id === context.taskId &&
212
+ bound.actor_id === context.actorId &&
213
+ bound.project_ref === context.accountIntent?.projectRef &&
214
+ bound.user_id === context.accountIntent?.userId &&
215
+ processRows &&
216
+ input.interaction_context_sha256 ===
217
+ qualityReviewInteractionDigest(interaction, readRows(processRows.file)) &&
218
+ bound.input_scope_sha256 === captureFoundryInput(processRows.file).sha256 &&
219
+ typeof input.issued_at_utc === "string" &&
220
+ Date.parse(input.issued_at_utc) <= now &&
221
+ typeof input.expires_at_utc === "string" &&
222
+ Date.parse(input.expires_at_utc) > now)
223
+ qualityReviewSha256 = qualityReview.entry.sha256;
133
224
  }
134
225
  const queueScopeSha256 = rows ? workflowAssessmentQueueScopeSha256(rows.value.sets) : null;
135
226
  let assessment = null;
227
+ let retainedAssessment = null;
136
228
  if (rows) {
137
229
  for (const entry of [...entries].reverse()) {
138
230
  if (entry.command !== "dataset-workflow-assessment" ||
@@ -140,10 +232,11 @@ export function currentWorkflowState(context, entries) {
140
232
  continue;
141
233
  const found = readWorkflowArtifact(context, entry), value = found.value;
142
234
  if (value.schema !== "tiangong-foundry.assessment-stage.v1" ||
143
- value.owner_base !== context.assetRoot ||
235
+ typeof value.owner_base !== "string" ||
144
236
  !["in_progress", "completed"].includes(String(value.status)) ||
145
237
  !Array.isArray(value.sets))
146
238
  throw new FoundryContextError("workflow_assessment_invalid", "Registered assessment metadata is invalid.");
239
+ const owner = assessmentOwner(value.owner_base, entry, value);
147
240
  const sets = value.sets.map(workflowObject);
148
241
  const reportRowsEntry = entries.find((candidate) => ["dataset-workflow-rows", "dataset-semantic-apply"].includes(candidate.command) &&
149
242
  path.basename(candidate.path) === "foundry-rows.json" &&
@@ -198,6 +291,14 @@ export function currentWorkflowState(context, entries) {
198
291
  else if (value.status === "in_progress") {
199
292
  throw new FoundryContextError("workflow_assessment_invalid", "Partial assessment must identify its predecessor boundary.");
200
293
  }
294
+ // Keep verified predecessor reports as immutable history, but qualify machine
295
+ // assessment afresh with the explicitly adopted runtime and CLI combination.
296
+ if (owner === "adopted_original") {
297
+ if (!retainedAssessment &&
298
+ sets.every((set) => rows.value.sets.some((row) => row.type === set.type && row.file === set.rows)))
299
+ retainedAssessment = { ...found, value: value };
300
+ continue;
301
+ }
201
302
  const identityMatches = (value.identity_report ?? null) ===
202
303
  (identity?.value.status === "completed" ? identity.file : null);
203
304
  const currentSets = identityMatches
@@ -205,9 +306,21 @@ export function currentWorkflowState(context, entries) {
205
306
  const row = rows.value.sets.find((candidate) => candidate.type === set.type);
206
307
  if (!row || row.file !== set.rows)
207
308
  return false;
309
+ if (row.type === "process" &&
310
+ (set.quality_review_sha256 ?? null) !== qualityReviewSha256)
311
+ return false;
208
312
  if ((set.interaction_digest ?? null) !==
209
313
  applicableFoundryInteractionDigest(interaction, row.type))
210
314
  return false;
315
+ if (["flow", "process"].includes(row.type) &&
316
+ rows.value.sets.some((set) => set.type === "process")) {
317
+ const selected = referenceInputs.get("process");
318
+ const expected = Array.isArray(selected?.value.qa_files) && selected.value.qa_files.length
319
+ ? selected.entry.sha256
320
+ : null;
321
+ if ((set.reference_input_sha256 ?? null) !== expected)
322
+ return false;
323
+ }
211
324
  const expectedContext = contextShaByType.get(row.type);
212
325
  if ((set.context_report_sha256 !== undefined &&
213
326
  set.context_report_sha256 !== expectedContext) ||
@@ -236,6 +349,50 @@ export function currentWorkflowState(context, entries) {
236
349
  const validationFile = resolveFoundryOutput(context, set.cli_validation_report);
237
350
  if (captureFoundryInput(validationFile).sha256 !== set.cli_validation_report_sha256)
238
351
  throw new FoundryContextError("workflow_assessment_invalid", "CLI validation evidence has changed.");
352
+ let validationInput = set.rows;
353
+ let validationRows = readRows(validationInput);
354
+ const selected = referenceInputs.get("process");
355
+ const qa = Array.isArray(selected?.value.qa_files) ? selected.value.qa_files : [];
356
+ if (qa.length) {
357
+ const source = workflowObject(set.cli_validation_source_rows);
358
+ const derived = workflowObject(set.cli_validation_input);
359
+ const original = captureFoundryInput(validationInput);
360
+ if (sha256Json(source) !== sha256Json(original) ||
361
+ set.cli_validation_reference_input_sha256 !== selected.entry.sha256 ||
362
+ sha256Json(set.cli_validation_reference_files) !== sha256Json(qa) ||
363
+ typeof derived.path !== "string" ||
364
+ !registeredAssessmentFile(context, entries, derived.path))
365
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation projection lineage differs from current rows or selected references.");
366
+ const references = qa.flatMap((raw) => {
367
+ const fact = workflowObject(raw);
368
+ if (typeof fact.path !== "string" ||
369
+ !registeredAssessmentFile(context, entries, fact.path) ||
370
+ sha256Json(captureFoundryInput(fact.path)) !== sha256Json(fact))
371
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation reference snapshot changed.");
372
+ return readRows(fact.path);
373
+ });
374
+ validationRows = projectFoundryValidationReferences(validationRows, references);
375
+ validationInput = derived.path;
376
+ const expected = Buffer.from(`${JSON.stringify(validationRows, null, 2)}\n`);
377
+ const actual = captureFoundryInput(validationInput);
378
+ if (sha256Json(actual) !== sha256Json(derived) ||
379
+ !fs.readFileSync(validationInput).equals(expected))
380
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation-only rows differ from the registered deterministic projection.");
381
+ files.push(validationInput);
382
+ }
383
+ else if (set.cli_validation_input !== undefined ||
384
+ set.cli_validation_source_rows !== undefined ||
385
+ set.cli_validation_reference_input_sha256 !== undefined ||
386
+ set.cli_validation_reference_files !== undefined) {
387
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation projection requires current selected Flow evidence.");
388
+ }
389
+ parseFoundryPreparationCliReport({
390
+ report: JSON.parse(fs.readFileSync(validationFile, "utf8")),
391
+ input: validationInput,
392
+ outDir: path.dirname(path.dirname(validationFile)),
393
+ rows: validationRows,
394
+ exit: set.cli_validation_exit,
395
+ });
239
396
  files.push(set.cli_validation_report);
240
397
  }
241
398
  if (set.interaction_context !== undefined)
@@ -277,25 +434,6 @@ export function currentWorkflowState(context, entries) {
277
434
  const assessmentRemainingTypes = rows
278
435
  ? rows.value.sets.filter((set) => !coveredTypes.has(set.type)).map((set) => set.type)
279
436
  : [];
280
- const referenceInputs = new Map();
281
- for (const entry of entries) {
282
- if (entry.command !== "dataset-workflow-reference-input" ||
283
- path.basename(entry.path) !== "foundry-reference-input.json")
284
- continue;
285
- const found = readWorkflowArtifact(context, entry);
286
- if (found.value.schema !== "tiangong-foundry.reference-selection.v1" ||
287
- found.value.status !== "selected" ||
288
- typeof found.value.dataset_type !== "string")
289
- throw new FoundryContextError("reference_input_invalid", "Registered reference selection is invalid.");
290
- referenceInputs.set(found.value.dataset_type, found);
291
- }
292
- const referenceInputsSha256 = referenceInputs.size
293
- ? createHash("sha256")
294
- .update(JSON.stringify([...referenceInputs]
295
- .sort(([a], [b]) => a.localeCompare(b))
296
- .map(([type, found]) => [type, found.entry.sha256])))
297
- .digest("hex")
298
- : null;
299
437
  let finalization = null;
300
438
  if (rows && assessmentComplete && assessment) {
301
439
  for (const entry of [...entries].reverse()) {
@@ -309,7 +447,8 @@ export function currentWorkflowState(context, entries) {
309
447
  throw new FoundryContextError("workflow_finalize_invalid", "Registered finalization metadata is invalid.");
310
448
  if (found.value.rows_report === rows.file &&
311
449
  found.value.assessment_report === assessment.file &&
312
- (found.value.reference_inputs_sha256 ?? null) === referenceInputsSha256) {
450
+ (found.value.reference_inputs_sha256 ?? null) === referenceInputsSha256 &&
451
+ (found.value.quality_review_sha256 ?? null) === qualityReviewSha256) {
313
452
  finalization = found;
314
453
  break;
315
454
  }
@@ -383,7 +522,9 @@ export function currentWorkflowState(context, entries) {
383
522
  }
384
523
  return {
385
524
  rows,
525
+ currentContextReports: [...contextFilesByType.values()],
386
526
  assessment,
527
+ retainedAssessment,
387
528
  assessmentComplete,
388
529
  assessmentRemainingTypes,
389
530
  interactionSha256,
@@ -393,5 +534,7 @@ export function currentWorkflowState(context, entries) {
393
534
  preparedApproval,
394
535
  referenceInputs,
395
536
  referenceInputsSha256,
537
+ qualityReview,
538
+ qualityReviewSha256,
396
539
  };
397
540
  }
@@ -1,8 +1,5 @@
1
1
  import type { FoundryCommandSpec } from "./foundry-command-spec.ts";
2
2
  type UnknownRecord = Record<string, unknown>;
3
- interface TextNode extends UnknownRecord {
4
- "#text"?: unknown;
5
- }
6
3
  interface NamedReference extends UnknownRecord {
7
4
  "common:shortDescription"?: unknown;
8
5
  shortDescription?: unknown;
@@ -26,10 +23,10 @@ interface ProcessDataSetRecord extends UnknownRecord {
26
23
  processInformation?: {
27
24
  dataSetInformation?: UnknownRecord & {
28
25
  name?: {
29
- baseName?: TextNode;
30
- treatmentStandardsRoutes?: TextNode;
31
- mixAndLocationTypes?: TextNode;
32
- functionalUnitFlowProperties?: TextNode;
26
+ baseName?: unknown;
27
+ treatmentStandardsRoutes?: unknown;
28
+ mixAndLocationTypes?: unknown;
29
+ functionalUnitFlowProperties?: unknown;
33
30
  };
34
31
  };
35
32
  quantitativeReference?: {
@@ -1,6 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { namePartText } from "./bundle-source-context.js";
3
4
  import { createFileArtifactFact, createFoundryCommandSpec } from "./foundry-command-spec.js";
5
+ import { FoundryContextError } from "./foundry-runtime-error.js";
4
6
  function isUnknownRecord(value) {
5
7
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
6
8
  }
@@ -122,10 +124,10 @@ export function createIdentityPreflightArtifactUtils({ asText, bundleClassificat
122
124
  function processNameParts(payload) {
123
125
  const name = payload?.processDataSet?.processInformation?.dataSetInformation?.name ?? {};
124
126
  return {
125
- base_name: asText(name.baseName?.["#text"] ?? name.baseName),
126
- treatment_standards_routes: asText(name.treatmentStandardsRoutes?.["#text"] ?? name.treatmentStandardsRoutes),
127
- mix_and_location_types: asText(name.mixAndLocationTypes?.["#text"] ?? name.mixAndLocationTypes),
128
- functional_unit_flow_properties: asText(name.functionalUnitFlowProperties?.["#text"] ?? name.functionalUnitFlowProperties),
127
+ base_name: namePartText(name.baseName, asText),
128
+ treatment_standards_routes: namePartText(name.treatmentStandardsRoutes, asText),
129
+ mix_and_location_types: namePartText(name.mixAndLocationTypes, asText),
130
+ functional_unit_flow_properties: namePartText(name.functionalUnitFlowProperties, asText),
129
131
  };
130
132
  }
131
133
  function valuesByKeys(payload, keys, limit = 6) {
@@ -409,7 +411,18 @@ export function createIdentityPreflightArtifactUtils({ asText, bundleClassificat
409
411
  function readSourceTracesFromFile(sourceFile) {
410
412
  if (!sourceFile || !fileExists(sourceFile))
411
413
  return [];
412
- return collectSourceTracePayloads(readJson(sourceFile));
414
+ let source;
415
+ try {
416
+ source = sourceFile.toLowerCase().endsWith(".jsonl")
417
+ ? readJsonLines(sourceFile)
418
+ : readJson(sourceFile);
419
+ }
420
+ catch (error) {
421
+ if (isUnknownRecord(error) && typeof error.code === "string")
422
+ throw error;
423
+ throw new FoundryContextError("source_trace_invalid", "The selected identity source trace is not valid JSON or JSONL. Check the original source evidence before continuing.");
424
+ }
425
+ return collectSourceTracePayloads(source);
413
426
  }
414
427
  function buildIdentityPreflightArtifacts({ rowsByType, sourceByType, outDir, cliBin, }) {
415
428
  const cliPrefix = Array.isArray(cliBin) ? cliBin : [cliBin];
@@ -95,7 +95,13 @@ export declare function validateIdentityPreflightExecution(input: {
95
95
  startedAtMs: number;
96
96
  diskReportMtimeMs: number | null;
97
97
  completedAtUtc: string;
98
+ requestFile?: string;
99
+ outputDir?: string;
100
+ reportFile?: string;
101
+ stderrText?: string;
102
+ signal?: string | null;
98
103
  }): ValidationFailure | ValidationSuccess;
104
+ export declare function createIdentityPreflightExecutionManifest(binding: IdentityPreflightBinding, reportText: string, completedAtUtc: string): ExecutionManifest;
99
105
  export declare function validateBoundExecutionManifest(value: unknown, binding: IdentityPreflightBinding, reportText: string | null): {
100
106
  ok: boolean;
101
107
  code?: string;
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import path from "node:path";
2
3
  import { parseAuthIdentityReceipt, } from "@tiangong-lca/cli/auth-identity-receipt";
3
4
  const SHA256_PATTERN = /^[0-9a-f]{64}$/u;
4
5
  const ALLOWED_REPORT_STATUSES = new Set(["passed", "blocked", "needs_review"]);
@@ -146,8 +147,76 @@ function parseReport(text, code) {
146
147
  function isFailure(value) {
147
148
  return value.ok === false && typeof value.code === "string" && typeof value.message === "string";
148
149
  }
150
+ function isSelectedDiagnosticPath(reported, expected) {
151
+ return (reported === expected || (path.isAbsolute(expected) && reported === path.resolve(expected)));
152
+ }
153
+ /** Current and retained qualified CLI contracts return one for manual review and execution failures. */
154
+ function isPinnedManualReviewDiagnostic(input, report) {
155
+ const binding = input.binding;
156
+ const argv = binding.command.semantic_argv;
157
+ if (binding.cli.package_name !== "@tiangong-lca/cli" ||
158
+ !["0.1.22", "0.1.27", "0.1.28"].includes(binding.cli.package_version) ||
159
+ !/^sha256-[0-9a-f]{64}$/u.test(binding.cli.package_integrity ?? "") ||
160
+ binding.inputs.authReceipt?.cli.package_name !== binding.cli.package_name ||
161
+ binding.inputs.authReceipt.cli.package_version !== binding.cli.package_version ||
162
+ !["flow", "process"].includes(binding.dataset.type) ||
163
+ argv.length !== 5 ||
164
+ argv[0] !== binding.dataset.type ||
165
+ argv[1] !== "identity-preflight" ||
166
+ argv[2] !== "--json" ||
167
+ argv[3] !== "--timeout-ms" ||
168
+ !/^[1-9][0-9]*$/u.test(argv[4]) ||
169
+ report.schema_version !== 1 ||
170
+ report.kind !== binding.dataset.type ||
171
+ report.status !== "needs_review" ||
172
+ report.decision !== "manual_review" ||
173
+ report.next_action !== "queue_manual_review" ||
174
+ !isRecord(report.target) ||
175
+ report.target.id !== binding.dataset.id ||
176
+ report.target.version !== binding.dataset.version ||
177
+ typeof input.requestFile !== "string" ||
178
+ typeof input.outputDir !== "string" ||
179
+ typeof input.reportFile !== "string" ||
180
+ !isSelectedDiagnosticPath(report.input_path, input.requestFile) ||
181
+ !isSelectedDiagnosticPath(report.out_dir, input.outputDir) ||
182
+ !isRecord(report.files) ||
183
+ !isSelectedDiagnosticPath(report.files.identity_decision, input.reportFile) ||
184
+ input.stderrText !== "" ||
185
+ input.signal !== null ||
186
+ !Array.isArray(report.candidates) ||
187
+ !Array.isArray(report.candidate_sources) ||
188
+ !Array.isArray(report.findings) ||
189
+ !Array.isArray(report.blockers) ||
190
+ report.blockers.length !== 0 ||
191
+ Object.hasOwn(report, "error") ||
192
+ (Object.hasOwn(report, "errors") &&
193
+ (!Array.isArray(report.errors) || report.errors.length !== 0)))
194
+ return false;
195
+ const generated = Date.parse(String(report.generated_at_utc ?? ""));
196
+ if (!Number.isFinite(generated) ||
197
+ generated < input.startedAtMs ||
198
+ generated > Date.parse(input.completedAtUtc))
199
+ return false;
200
+ try {
201
+ const current = createIdentityPreflightBinding(binding.inputs);
202
+ return stableJson(bindingEvidence(current)) === stableJson(bindingEvidence(binding));
203
+ }
204
+ catch {
205
+ return false;
206
+ }
207
+ }
149
208
  export function validateIdentityPreflightExecution(input) {
150
- if (input.exitCode !== 0) {
209
+ try {
210
+ const request = exactRecord(JSON.parse(input.binding.inputs.requestText), "Identity request");
211
+ if (sha256Text(JSON.stringify(request.target)) !== input.binding.dataset.target_sha256 ||
212
+ stableJson(bindingEvidence(createIdentityPreflightBinding(input.binding.inputs))) !==
213
+ stableJson(bindingEvidence(input.binding)))
214
+ return failure("identity_preflight_execution_binding_mismatch", "Identity request or execution binding changed.");
215
+ }
216
+ catch {
217
+ return failure("identity_preflight_execution_binding_mismatch", "Identity request or execution binding is invalid.");
218
+ }
219
+ if (input.exitCode !== 0 && input.exitCode !== 1) {
151
220
  return failure("identity_preflight_cli_exit_nonzero", "Identity-preflight CLI exited nonzero.");
152
221
  }
153
222
  const stdoutReport = parseReport(input.stdoutText, "identity_preflight_stdout_missing_or_non_json");
@@ -165,6 +234,9 @@ export function validateIdentityPreflightExecution(input) {
165
234
  if (Object.hasOwn(diskReport, "ok") && diskReport.ok !== true) {
166
235
  return failure("identity_preflight_report_not_ok", "Identity-preflight report has ok != true.");
167
236
  }
237
+ if (input.exitCode === 1 && !isPinnedManualReviewDiagnostic(input, diskReport)) {
238
+ return failure("identity_preflight_cli_exit_nonzero", "Identity-preflight CLI exited nonzero without a bound manual-review diagnostic.");
239
+ }
168
240
  const status = typeof diskReport.status === "string" ? diskReport.status : "";
169
241
  if (!ALLOWED_REPORT_STATUSES.has(status)) {
170
242
  return failure("identity_preflight_report_status_invalid", `Identity-preflight report status ${status || "missing"} is not accepted.`);
@@ -173,10 +245,21 @@ export function validateIdentityPreflightExecution(input) {
173
245
  if (!authReceipt || !input.binding.account) {
174
246
  return failure("identity_preflight_auth_receipt_missing", "Identity-preflight execution requires account receipt evidence.");
175
247
  }
248
+ return {
249
+ ok: true,
250
+ report: diskReport,
251
+ manifest: createIdentityPreflightExecutionManifest(input.binding, input.diskReportText, input.completedAtUtc),
252
+ };
253
+ }
254
+ export function createIdentityPreflightExecutionManifest(binding, reportText, completedAtUtc) {
255
+ const report = exactRecord(JSON.parse(reportText), "Identity-preflight report");
256
+ const authReceipt = binding.inputs.authReceipt;
257
+ if (!authReceipt || !binding.account || !ALLOWED_REPORT_STATUSES.has(String(report.status)))
258
+ throw new Error("Identity-preflight report needs current account evidence and an accepted status.");
176
259
  const manifestScope = {
177
260
  schema: "tiangong-foundry.identity-preflight-execution.v1",
178
- binding_sha256: input.binding.binding_sha256,
179
- binding: bindingEvidence(input.binding),
261
+ binding_sha256: binding.binding_sha256,
262
+ binding: bindingEvidence(binding),
180
263
  producer_auth: {
181
264
  project_ref: authReceipt.project.project_ref,
182
265
  user_id: authReceipt.identity.user_id,
@@ -184,18 +267,14 @@ export function validateIdentityPreflightExecution(input) {
184
267
  captured_at_utc: authReceipt.captured_at_utc,
185
268
  },
186
269
  report: {
187
- bytes_sha256: sha256Text(input.diskReportText ?? ""),
188
- canonical_sha256: sha256Json(diskReport),
189
- status,
190
- decision: typeof diskReport.decision === "string" ? diskReport.decision : null,
270
+ bytes_sha256: sha256Text(reportText),
271
+ canonical_sha256: sha256Json(report),
272
+ status: String(report.status),
273
+ decision: typeof report.decision === "string" ? report.decision : null,
191
274
  },
192
- completed_at_utc: input.completedAtUtc,
193
- };
194
- return {
195
- ok: true,
196
- report: diskReport,
197
- manifest: { ...manifestScope, manifest_sha256: sha256Json(manifestScope) },
275
+ completed_at_utc: completedAtUtc,
198
276
  };
277
+ return { ...manifestScope, manifest_sha256: sha256Json(manifestScope) };
199
278
  }
200
279
  export function validateBoundExecutionManifest(value, binding, reportText) {
201
280
  if (!isRecord(value) || value.schema !== "tiangong-foundry.identity-preflight-execution.v1") {
@@ -0,0 +1,78 @@
1
+ import { type IdentityPreflightBindingEvidence } from "./identity-preflight-proof.ts";
2
+ export interface IdentityRecoveryFact {
3
+ path: string;
4
+ bytes: number;
5
+ sha256: string;
6
+ }
7
+ export interface RetainedIdentityCliInventory {
8
+ role: "current_retained_cli_inventory";
9
+ root: string;
10
+ package_version: string;
11
+ content_sha256: string;
12
+ files: Array<{
13
+ path: string;
14
+ bytes: number;
15
+ sha256: string;
16
+ }>;
17
+ }
18
+ /** Compare retained executable dependencies with the independent current/transition inventory. */
19
+ export declare function verifyRetainedIdentityCliInventory(value: RetainedIdentityCliInventory, bin: string): void;
20
+ export interface IdentityPreflightRecoveryProof {
21
+ schema: "tiangong-foundry.identity-preflight-recovery.v1";
22
+ task_id: string;
23
+ actor_id: string;
24
+ new_cli_execution: false;
25
+ binding: IdentityPreflightBindingEvidence;
26
+ binding_sha256: string;
27
+ original: {
28
+ producer_base: string;
29
+ attempt: 1;
30
+ status: "failed";
31
+ failure_code: "identity_preflight_cli_exit_nonzero";
32
+ cli_exit_code: 1;
33
+ producer_auth: {
34
+ project_ref: string;
35
+ user_id: string;
36
+ receipt_scope_sha256: string;
37
+ captured_at_utc: string;
38
+ };
39
+ batch_prepared_at_utc: string;
40
+ query_generated_at_utc: string;
41
+ batch_completed_at_utc: string;
42
+ facts: Record<string, IdentityRecoveryFact>;
43
+ };
44
+ current_owner_interpretation_auth: {
45
+ project_ref: string;
46
+ user_id: string;
47
+ receipt_scope_sha256: string;
48
+ captured_at_utc: string;
49
+ };
50
+ recovered_at_utc: string;
51
+ current_retained_runtime_observation: {
52
+ role: "current_retained_runtime_observation";
53
+ observed_at_utc: string;
54
+ original_executable: IdentityRecoveryFact;
55
+ qualified_node_sha256: string;
56
+ };
57
+ current_retained_cli_inventory: RetainedIdentityCliInventory;
58
+ proof_sha256: string;
59
+ }
60
+ /** Current readback of a retained executable; it does not claim a query-time runtime capture. */
61
+ export declare function observeRetainedIdentityExecutable(file: string): IdentityRecoveryFact | null;
62
+ /** Read only the exact named regular original evidence; never discover reports or reconstruct attempts. */
63
+ export declare function readIdentityRecoveryFact(fact: IdentityRecoveryFact): Buffer;
64
+ export declare function validateIdentityPreflightRecoveryEvidence(value: unknown, input: {
65
+ requestText: string | null;
66
+ reportText: string | null;
67
+ datasetType: string;
68
+ datasetId: string;
69
+ datasetVersion: string;
70
+ targetSha256: string;
71
+ expectedProjectRef?: string | null;
72
+ expectedUserId?: string | null;
73
+ expectedRetainedCliContentSha256?: string;
74
+ }): {
75
+ ok: boolean;
76
+ code?: string;
77
+ binding?: IdentityPreflightBindingEvidence;
78
+ };