@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
@@ -0,0 +1,487 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
5
+ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
6
+ import { assertSelectedFoundryQualityReviewInput, parseFoundryQualityReviewInput, materializeFoundryQualityReviewInput, FOUNDRY_QUALITY_REVIEW_DRAFT_SCHEMA, } from "./foundry-quality-review-input.js";
7
+ import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
8
+ import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
9
+ import { runFoundryTaskOperation } from "./foundry-task-store.js";
10
+ import { readTaskBytes } from "./foundry-task-io.js";
11
+ import { canonicalPayloadSha256 } from "./post-write-root-proof.js";
12
+ import { readRows } from "./import-curation/internal/runtime-io.js";
13
+ import { datasetIdentity, unwrapDatasetPayload, } from "./import-curation/internal/dataset-payload.js";
14
+ import { readQaFindings } from "./import-curation/internal/artifact-inputs.js";
15
+ import { unchangedQualityReviewRows } from "./foundry-quality-review-lineage.js";
16
+ import { qualityReviewInteractionDigest } from "./foundry-quality-review-context.js";
17
+ import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
18
+ const code = "process_material_balance_deviation";
19
+ const command = "dataset-workflow-quality-review";
20
+ const receiptName = "foundry-quality-review.json";
21
+ function invalid(message) {
22
+ throw new FoundryContextError("quality_review_scope_invalid", message);
23
+ }
24
+ function fingerprint(value) {
25
+ return canonicalPayloadSha256(value);
26
+ }
27
+ function live(spec) {
28
+ const now = Date.now();
29
+ if (Date.parse(spec.issued_at_utc) > now || Date.parse(spec.expires_at_utc) <= now)
30
+ invalid("Quality review authority is not current.");
31
+ }
32
+ /** Full JSON rows and ordered identities stay bound; serialization whitespace is not a row change. */
33
+ function rowScope(file) {
34
+ const rows = readRows(file);
35
+ const objects = rows.map((row, row_index) => {
36
+ const identity = datasetIdentity(row, row_index, "process");
37
+ const payloadIdentity = datasetIdentity(unwrapDatasetPayload(row, "process"), row_index, "process");
38
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(identity.id) ||
39
+ identity.id !== payloadIdentity.id ||
40
+ identity.version !== payloadIdentity.version ||
41
+ identity.dataset_type !== "process")
42
+ invalid("Quality review requires identified Process rows.");
43
+ return {
44
+ row_index,
45
+ id: identity.id,
46
+ version: identity.version,
47
+ payload_sha256: fingerprint(identity.payload),
48
+ };
49
+ });
50
+ // CLI finding attribution uses a process filename. An ID occurring twice cannot be reviewed
51
+ // through the existing ID-keyed curation report, even when the versions differ.
52
+ if (new Set(objects.map((item) => item.id)).size !== objects.length)
53
+ invalid("Quality review cannot select ambiguous or duplicated Process identities.");
54
+ return { rows, objects, sha256: fingerprint(rows) };
55
+ }
56
+ function reportObservation(report, findings) {
57
+ if (report.status !== "completed_local_process_qa" ||
58
+ report.policy_decision_owner !== "foundry" ||
59
+ report.qa_mode !== "deterministic_qa_report" ||
60
+ !Array.isArray(report.mass_balance) ||
61
+ !Array.isArray(report.reference_evidence))
62
+ invalid("Quality review requires the completed deterministic Process QA observation.");
63
+ const value = { ...report };
64
+ // Only named run metadata and artifact locations vary across a deterministic rerun. All
65
+ // remaining fields, including unknown future QA fields and the complete findings, are bound.
66
+ for (const key of [
67
+ "generated_at_utc",
68
+ "run_id",
69
+ "run_root",
70
+ "rows_file",
71
+ "out_dir",
72
+ "effective_processes_dir",
73
+ "files",
74
+ ])
75
+ delete value[key];
76
+ value.reference_evidence = report.reference_evidence.map((raw) => {
77
+ const fact = workflowObject(raw);
78
+ const { path: _location, ...content } = fact;
79
+ return content;
80
+ });
81
+ return fingerprint({ report: value, findings });
82
+ }
83
+ function binding(context, rows) {
84
+ if (!context.accountIntent || !context.workspaceId || !context.taskId || !context.actorId)
85
+ invalid("Select explicit current task and account intent before reviewing a QA observation.");
86
+ const profile = workflowObject(JSON.parse(readTaskBytes(context, "profile-lock.json").toString("utf8")));
87
+ return {
88
+ workspace_id: context.workspaceId,
89
+ task_id: context.taskId,
90
+ actor_id: context.actorId,
91
+ project_ref: context.accountIntent.projectRef,
92
+ user_id: context.accountIntent.userId,
93
+ profile_id: String(profile.profile_id),
94
+ profile_sha256: String(profile.profile_sha256),
95
+ input_scope_sha256: rows.sha256,
96
+ };
97
+ }
98
+ function assertUnsealed(context, entries) {
99
+ if (fs.existsSync(path.join(context.taskRoot, "authorization.json")) ||
100
+ entries.some((entry) => [
101
+ "dataset-workflow-authorization",
102
+ "dataset-workflow-native-contract",
103
+ "dataset-workflow-execution-prepare",
104
+ "dataset-workflow-execution-result",
105
+ "dataset-workflow-execution-consume",
106
+ "dataset-workflow-execution-observation",
107
+ ].includes(entry.command)) ||
108
+ (fs.existsSync(path.join(context.taskRoot, "attempts")) &&
109
+ fs.readdirSync(path.join(context.taskRoot, "attempts")).length))
110
+ throw new FoundryContextError("quality_review_scope_frozen", "Retain authorized, prepared or consumed scope evidence; quality review cannot change its authority.");
111
+ }
112
+ function registered(context, entries, file) {
113
+ const fact = captureFoundryInput(file);
114
+ if (!entries.some((entry) => path.resolve(context.taskRoot, entry.path) === fact.path &&
115
+ entry.bytes === fact.bytes &&
116
+ entry.sha256 === fact.sha256))
117
+ invalid("Quality review requires current indexed evidence with unchanged bytes.");
118
+ readSelectedSemanticBytes(fact);
119
+ return fact;
120
+ }
121
+ function registeredQa(context, entries, file) {
122
+ const fact = registered(context, entries, file);
123
+ const report = workflowObject(JSON.parse(readSelectedSemanticBytes(fact).toString("utf8")));
124
+ const files = workflowObject(report.files);
125
+ for (const key of ["rule_findings", "findings", "llm_findings"]) {
126
+ if (files[key] === undefined)
127
+ continue;
128
+ if (typeof files[key] !== "string")
129
+ invalid("Process QA finding evidence is invalid.");
130
+ const locator = String(files[key]);
131
+ const target = path.isAbsolute(locator) ? locator : path.resolve(path.dirname(file), locator);
132
+ registered(context, entries, target);
133
+ }
134
+ if (!Array.isArray(report.reference_evidence))
135
+ invalid("Process QA reference evidence is missing.");
136
+ const references = report.reference_evidence.map((raw) => {
137
+ const expected = workflowObject(raw);
138
+ if (typeof expected.path !== "string")
139
+ invalid("Process QA reference path is invalid.");
140
+ const actual = registered(context, entries, expected.path);
141
+ if (actual.bytes !== expected.bytes || actual.sha256 !== expected.sha256)
142
+ invalid("Process QA reference evidence changed after observation.");
143
+ return actual;
144
+ });
145
+ return {
146
+ fact,
147
+ report,
148
+ references,
149
+ findings: readQaFindings(context.assetRoot, report, file, "process"),
150
+ };
151
+ }
152
+ function processContext(context, entries) {
153
+ const entry = entries.findLast((item) => item.command === "dataset-context-pack" &&
154
+ path.basename(item.path) === "contract-report.json" &&
155
+ readWorkflowArtifact(context, item).value.type === "process");
156
+ if (!entry)
157
+ invalid("The Process context must be registered before quality review.");
158
+ const report = readWorkflowArtifact(context, entry);
159
+ const files = workflowObject(report.value.files);
160
+ for (const key of ["schema", "methodology", "ruleset"]) {
161
+ if (typeof files[key] !== "string" || !path.isAbsolute(files[key]))
162
+ invalid("Quality review requires the complete registered Process context.");
163
+ registered(context, entries, files[key]);
164
+ }
165
+ return entry;
166
+ }
167
+ /** Read-only scope projection, not a review decision or an approval template with default consent. */
168
+ export function foundryQualityReviewScope(context, qualificationSha256, entries, state = currentWorkflowState(context, entries)) {
169
+ if (state.qualityReviewSha256)
170
+ verifyQualityReviewEvidence(context, qualificationSha256, entries);
171
+ const set = state.assessment?.value.sets.find((item) => item.type === "process");
172
+ const rows = state.rows?.value.sets.find((item) => item.type === "process");
173
+ if (!set || !rows || !state.rows || !state.assessment || !context.accountIntent)
174
+ return null;
175
+ if (set.runtime_qualification_sha256 !== qualificationSha256)
176
+ return null;
177
+ if (typeof set.qa_report !== "string")
178
+ invalid("The current Process assessment has no QA report.");
179
+ const input = registered(context, entries, rows.file);
180
+ const { fact: qa, report, findings } = registeredQa(context, entries, set.qa_report);
181
+ const scope = rowScope(input.path);
182
+ const contextEntry = processContext(context, entries);
183
+ const candidates = scope.objects.flatMap((object) => findings
184
+ .filter((finding) => finding.code === code &&
185
+ finding.severity === "warning" &&
186
+ finding.process_file === `${object.id}__${object.version}.json` &&
187
+ finding.evidence !== null &&
188
+ typeof finding.evidence === "object" &&
189
+ !Array.isArray(finding.evidence) &&
190
+ finding.evidence.policy_decision_owner === "foundry")
191
+ .map((finding) => ({ ...object, code, finding_sha256: fingerprint(finding), finding })));
192
+ if (!candidates.length)
193
+ return null;
194
+ return {
195
+ binding: binding(context, input),
196
+ runtime_qualification_sha256: qualificationSha256,
197
+ rows_manifest_sha256: state.rows.entry.sha256,
198
+ assessment_sha256: state.assessment.entry.sha256,
199
+ context_sha256: contextEntry.sha256,
200
+ reference_inputs_sha256: state.referenceInputsSha256,
201
+ interaction_context_sha256: qualityReviewInteractionDigest(currentFoundryInteractionState(context, entries)?.state ?? null, scope.rows),
202
+ qa_report_sha256: qa.sha256,
203
+ qa_findings_sha256: fingerprint(findings),
204
+ expected_previous_sha256: state.qualityReview?.entry.sha256 ?? null,
205
+ candidates,
206
+ input,
207
+ qa,
208
+ rows_content_sha256: scope.sha256,
209
+ qa_observation_sha256: reportObservation(report, findings),
210
+ };
211
+ }
212
+ /** Mechanical selection material; an untouched draft is deliberately not an accepted input. */
213
+ export function createFoundryQualityReviewTemplate(scope) {
214
+ const issued = Date.now();
215
+ return {
216
+ schema: FOUNDRY_QUALITY_REVIEW_DRAFT_SCHEMA,
217
+ binding: scope.binding,
218
+ runtime_qualification_sha256: scope.runtime_qualification_sha256,
219
+ rows_manifest_sha256: scope.rows_manifest_sha256,
220
+ assessment_sha256: scope.assessment_sha256,
221
+ context_sha256: scope.context_sha256,
222
+ reference_inputs_sha256: scope.reference_inputs_sha256,
223
+ interaction_context_sha256: scope.interaction_context_sha256,
224
+ qa_report_sha256: scope.qa_report_sha256,
225
+ qa_findings_sha256: scope.qa_findings_sha256,
226
+ expected_previous_sha256: scope.expected_previous_sha256,
227
+ issued_at_utc: new Date(issued).toISOString(),
228
+ expires_at_utc: new Date(issued + 3600_000).toISOString(),
229
+ reviews: scope.candidates.map(({ finding: _finding, ...selection }) => ({
230
+ ...selection,
231
+ disposition: null,
232
+ evidence_ids: [],
233
+ rationale: "",
234
+ })),
235
+ evidence: [],
236
+ };
237
+ }
238
+ export async function recordFoundryQualityReview(context, qualified, entries, selected) {
239
+ assertSelectedFoundryQualityReviewInput(selected);
240
+ assertQualifiedFoundryRuntime(context, qualified);
241
+ const spec = selected.spec;
242
+ live(spec);
243
+ assertUnsealed(context, entries);
244
+ const state = currentWorkflowState(context, entries);
245
+ if (state.qualityReview?.value.source_sha256 === selected.descriptor.sha256) {
246
+ if (!state.qualityReviewSha256)
247
+ invalid("The previously accepted review is no longer current.");
248
+ if (fingerprint(parseFoundryQualityReviewInput(state.qualityReview.value.input)) !==
249
+ fingerprint(spec))
250
+ invalid("The accepted draft now selects different evidence; retain its original review and select the current scope explicitly.");
251
+ loadFoundryQualityReview(context, qualified, entries);
252
+ return state.qualityReview.value;
253
+ }
254
+ const scope = foundryQualityReviewScope(context, qualified.qualification_sha256, entries);
255
+ if (!scope)
256
+ invalid("Assess the current Process rows and exact mass observation before reviewing it.");
257
+ for (const key of [
258
+ "runtime_qualification_sha256",
259
+ "rows_manifest_sha256",
260
+ "assessment_sha256",
261
+ "context_sha256",
262
+ "reference_inputs_sha256",
263
+ "interaction_context_sha256",
264
+ "qa_report_sha256",
265
+ "qa_findings_sha256",
266
+ "expected_previous_sha256",
267
+ ])
268
+ if (spec[key] !== scope[key])
269
+ invalid(`Quality review does not match the current ${key}.`);
270
+ if (fingerprint(spec.binding) !== fingerprint(scope.binding))
271
+ invalid("Quality review is for another task, account, profile or current row scope.");
272
+ for (const review of spec.reviews) {
273
+ const candidate = scope.candidates.find((item) => item.row_index === review.row_index &&
274
+ item.id === review.id &&
275
+ item.version === review.version &&
276
+ item.payload_sha256 === review.payload_sha256 &&
277
+ item.finding_sha256 === review.finding_sha256);
278
+ if (!candidate)
279
+ invalid("Each decision must select an exact current Process and warning.");
280
+ }
281
+ const output = path.join(context.taskRoot, "outputs", "quality-review", randomUUID());
282
+ return runFoundryTaskOperation(context, {
283
+ command,
284
+ options: { descriptor: selected.descriptor, scope },
285
+ validateCurrent(index) {
286
+ assertSelectedFoundryQualityReviewInput(selected);
287
+ live(spec);
288
+ assertUnsealed(context, index);
289
+ const current = foundryQualityReviewScope(context, qualified.qualification_sha256, index);
290
+ if (!current || fingerprint(current) !== fingerprint(scope))
291
+ invalid("Quality review scope or predecessor changed before registration.");
292
+ },
293
+ }, (operation) => {
294
+ const snapshot = (fact, name) => {
295
+ const target = path.join(output, name);
296
+ operation.writeText(target, readSelectedSemanticBytes(fact));
297
+ const captured = captureFoundryInput(target);
298
+ if (captured.sha256 !== fact.sha256 || captured.bytes !== fact.bytes)
299
+ invalid("Quality-review snapshot differs from selected bytes.");
300
+ return captured;
301
+ };
302
+ const descriptor = snapshot(selected.descriptor, "descriptor.json");
303
+ const evidence = selected.evidence.map((fact, index) => ({
304
+ id: spec.evidence[index].id,
305
+ kind: spec.evidence[index].kind,
306
+ ...snapshot(fact, `evidence-${index}.txt`),
307
+ }));
308
+ const result = {
309
+ schema: "tiangong-foundry.quality-review-receipt.v1",
310
+ status: "accepted",
311
+ source_sha256: selected.descriptor.sha256,
312
+ descriptor,
313
+ input: spec,
314
+ runtime: context.runtime,
315
+ rows: scope.input,
316
+ qa: scope.qa,
317
+ rows_content_sha256: scope.rows_content_sha256,
318
+ qa_observation_sha256: scope.qa_observation_sha256,
319
+ evidence,
320
+ grants_permission: false,
321
+ };
322
+ operation.writeText(path.join(output, "reviewed-findings.jsonl"), spec.reviews
323
+ .map((review) => JSON.stringify({
324
+ ...review,
325
+ finding: scope.candidates.find((item) => item.finding_sha256 === review.finding_sha256).finding,
326
+ }))
327
+ .join("\n") + "\n");
328
+ operation.writeText(path.join(output, "quality-review-report.md"), [
329
+ "# Preparation quality review",
330
+ "",
331
+ "Raw Process QA is retained. This receipt grants no write permission.",
332
+ ``,
333
+ `Expires: ${spec.expires_at_utc}`,
334
+ ``,
335
+ ...spec.reviews.map((review) => `- ${review.id}@${review.version}, row ${review.row_index}: ${review.rationale}`),
336
+ "",
337
+ "Rerun the same task. Changed rows, QA, references, context or authority require a fresh review.",
338
+ "",
339
+ ].join("\n"));
340
+ operation.writeJson(path.join(output, receiptName), result);
341
+ return result;
342
+ });
343
+ }
344
+ const validated = new WeakSet();
345
+ function verifyQualityReviewEvidence(context, qualificationSha256, entries) {
346
+ const state = currentWorkflowState(context, entries);
347
+ const found = state.qualityReview;
348
+ if (!found || !state.qualityReviewSha256)
349
+ return null;
350
+ const spec = parseFoundryQualityReviewInput(found.value.input);
351
+ live(spec);
352
+ if (spec.runtime_qualification_sha256 !== qualificationSha256)
353
+ invalid("Quality review belongs to a different qualified runtime.");
354
+ const rows = state.rows?.value.sets.find((set) => set.type === "process");
355
+ if (!rows ||
356
+ fingerprint(binding(context, registered(context, entries, rows.file))) !==
357
+ fingerprint(spec.binding))
358
+ invalid("Quality review current rows, account or profile changed.");
359
+ const descriptor = workflowObject(found.value.descriptor);
360
+ if (typeof descriptor.path !== "string" ||
361
+ registered(context, entries, descriptor.path).sha256 !== found.value.source_sha256 ||
362
+ fingerprint(materializeFoundryQualityReviewInput(JSON.parse(readSelectedSemanticBytes(registered(context, entries, descriptor.path)).toString("utf8")), (file) => {
363
+ const index = spec.evidence.findIndex((item) => item.file === file);
364
+ const evidence = found.value.evidence;
365
+ if (index < 0 || !Array.isArray(evidence))
366
+ invalid("Generated quality review has no retained selected evidence.");
367
+ const snapshot = workflowObject(evidence[index]);
368
+ if (typeof snapshot.path !== "string")
369
+ invalid("Generated quality review evidence snapshot is missing.");
370
+ return registered(context, entries, snapshot.path);
371
+ })) !== fingerprint(spec))
372
+ invalid("Quality review descriptor is not the indexed selected input.");
373
+ if (!Array.isArray(found.value.evidence) || found.value.evidence.length !== spec.evidence.length)
374
+ invalid("Quality review evidence is incomplete.");
375
+ found.value.evidence.forEach((raw, index) => {
376
+ const fact = workflowObject(raw), expected = spec.evidence[index];
377
+ if (fact.id !== expected.id ||
378
+ fact.kind !== expected.kind ||
379
+ typeof fact.path !== "string" ||
380
+ registered(context, entries, fact.path).sha256 !== expected.sha256)
381
+ invalid("Quality review authority or source-model evidence changed.");
382
+ });
383
+ if (processContext(context, entries).sha256 !== spec.context_sha256)
384
+ invalid("Quality review contract context changed.");
385
+ const originalQa = workflowObject(found.value.qa);
386
+ if (typeof originalQa.path !== "string" ||
387
+ registered(context, entries, originalQa.path).sha256 !== spec.qa_report_sha256)
388
+ invalid("Quality review original QA evidence changed.");
389
+ const originalObservation = registeredQa(context, entries, originalQa.path);
390
+ if (fingerprint(originalObservation.findings) !== spec.qa_findings_sha256 ||
391
+ reportObservation(originalObservation.report, originalObservation.findings) !==
392
+ found.value.qa_observation_sha256)
393
+ invalid("Quality review original finding evidence changed.");
394
+ if (typeof found.value.rows_content_sha256 !== "string" ||
395
+ typeof found.value.qa_observation_sha256 !== "string")
396
+ invalid("Quality review has no complete row and observation binding.");
397
+ return { state, found, spec, references: originalObservation.references };
398
+ }
399
+ export function loadFoundryQualityReview(context, qualified, entries) {
400
+ assertQualifiedFoundryRuntime(context, qualified);
401
+ const observed = verifyQualityReviewEvidence(context, qualified.qualification_sha256, entries);
402
+ if (!observed)
403
+ return null;
404
+ const { state, found, spec, references } = observed;
405
+ const verify = () => {
406
+ assertQualifiedFoundryRuntime(context, qualified);
407
+ const current = verifyQualityReviewEvidence(context, qualified.qualification_sha256, entries);
408
+ if (current?.found.entry.sha256 !== found.entry.sha256)
409
+ invalid("Quality review is no longer current.");
410
+ };
411
+ verify();
412
+ const result = Object.freeze({
413
+ receipt_sha256: found.entry.sha256,
414
+ expires_at_utc: spec.expires_at_utc,
415
+ spec,
416
+ rows_content_sha256: String(found.value.rows_content_sha256),
417
+ qa_observation_sha256: String(found.value.qa_observation_sha256),
418
+ qaReferenceRows: Object.freeze(references.map((fact) => fact.path)),
419
+ validate: verify,
420
+ rowsMatch: (rowsFile, cleanupReport) => {
421
+ const original = state.rows.value.sets.find((set) => set.type === "process");
422
+ return unchangedQualityReviewRows({
423
+ originalRows: rowScope(original.file).rows,
424
+ finalRowsFile: rowsFile,
425
+ taskRoot: context.taskRoot,
426
+ assetRoot: context.assetRoot,
427
+ cleanupReport,
428
+ referenceFiles: references,
429
+ });
430
+ },
431
+ });
432
+ validated.add(result);
433
+ return result;
434
+ }
435
+ /** Called by the existing curation owner after fresh QA, including on cleaned final rows. */
436
+ export function reviewedFoundryQualityFindings(review, rowsFile, qaReport, findings, cleanupReport) {
437
+ if (!review || typeof review !== "object" || !validated.has(review))
438
+ invalid("A serialized decision cannot replace indexed quality-review admission.");
439
+ const selected = review;
440
+ selected.validate();
441
+ const scope = rowScope(rowsFile);
442
+ if (!selected.rowsMatch(rowsFile, cleanupReport) ||
443
+ fingerprint(findings) !== selected.spec.qa_findings_sha256 ||
444
+ reportObservation(qaReport, findings) !== selected.qa_observation_sha256)
445
+ invalid("Rows, references or the deterministic QA observation changed after quality review.");
446
+ return selected.spec.reviews.map((item) => {
447
+ const row = scope.objects[item.row_index];
448
+ const finding = findings.find((value) => fingerprint(value) === item.finding_sha256);
449
+ if (!row ||
450
+ row.id !== item.id ||
451
+ row.version !== item.version ||
452
+ row.payload_sha256 !== item.payload_sha256 ||
453
+ !finding ||
454
+ finding.code !== code ||
455
+ finding.process_file !== `${item.id}__${item.version}.json`)
456
+ invalid("The quality review no longer matches its exact Process finding.");
457
+ return { ...item, finding, receipt_sha256: selected.receipt_sha256 };
458
+ });
459
+ }
460
+ /** Recheck local review evidence at write admission; this function grants no write capability. */
461
+ export function assertFoundryQualityReviewForExecution(context, qualified, entries, finalRowsFile) {
462
+ for (const entry of [...entries].reverse()) {
463
+ if (entry.command !== "dataset-workflow-finalize" ||
464
+ path.basename(entry.path) !== "foundry-finalize.json")
465
+ continue;
466
+ const found = readWorkflowArtifact(context, entry);
467
+ const sets = Array.isArray(found.value.sets) ? found.value.sets.map(workflowObject) : [];
468
+ const scope = sets.find((set) => set.type === "process" && set.final_rows === finalRowsFile);
469
+ if (!scope)
470
+ continue;
471
+ if (found.value.quality_review_sha256 === undefined)
472
+ return;
473
+ const review = loadFoundryQualityReview(context, qualified, entries);
474
+ if (!review || review.receipt_sha256 !== found.value.quality_review_sha256)
475
+ invalid("Final rows require the same current preparation quality review before write admission.");
476
+ if (typeof scope.report !== "string")
477
+ invalid("Final quality-review evidence is missing.");
478
+ const owner = workflowObject(JSON.parse(readSelectedSemanticBytes(registered(context, entries, scope.report)).toString("utf8")));
479
+ const files = workflowObject(owner.files);
480
+ if (typeof files.qa_report !== "string" || typeof files.cleanup_report !== "string")
481
+ invalid("Final quality-review QA and cleanup evidence is missing.");
482
+ const qa = registeredQa(context, entries, path.resolve(context.assetRoot, files.qa_report));
483
+ const cleanup = registered(context, entries, path.resolve(context.assetRoot, files.cleanup_report));
484
+ reviewedFoundryQualityFindings(review, finalRowsFile, qa.report, qa.findings, cleanup.path);
485
+ return;
486
+ }
487
+ }
@@ -110,7 +110,9 @@ export function assertVerifiedFoundryIdentity(context, identity, qualification)
110
110
  identity.runtimeEntrySha256 !== context.runtime.entrySha256 ||
111
111
  (qualification !== undefined &&
112
112
  identity.runtimeQualificationSha256 !== qualification.qualification_sha256) ||
113
- !context.accountIntent)
113
+ !context.accountIntent ||
114
+ identity.receipt.project.project_ref !== context.accountIntent.projectRef ||
115
+ identity.receipt.identity.user_id !== context.accountIntent.userId)
114
116
  reject("identity_context_mismatch", "Identity proof is not bound to the current task context.");
115
117
  try {
116
118
  parseFreshIntentBoundAuthReceipt(identity.receipt, {
@@ -157,8 +157,8 @@ export function qualifyFoundryRuntime(context, options) {
157
157
  catch {
158
158
  return fail("runtime_cli_unqualified", "CLI runtime bytes do not match the independently selected C1 expectation.");
159
159
  }
160
- if (cli.package.version !== "0.1.26" || cli.platform !== context.platform)
161
- fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.26 C1 runtime on the selected platform.");
160
+ if (cli.package.version !== "0.1.28" || cli.platform !== context.platform)
161
+ fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.28 C1 runtime on the selected platform.");
162
162
  const cliExpectation = Object.freeze({ ...options.cliExpectation });
163
163
  if (cliExpectation.schema !== CLI_RUNTIME_EXPECTATION_SCHEMA)
164
164
  fail("runtime_cli_unqualified", "CLI runtime expectation is not the supported schema.");
@@ -9,7 +9,7 @@ import { resolveFoundryRuntimePaths } from "./foundry-runtime-paths.js";
9
9
  import { resolveTiangongLcaCliTidasSource, } from "./foundry-tidas-source.js";
10
10
  const require = createRequire(import.meta.url);
11
11
  const tiangongLcaCliPackageName = "@tiangong-lca/cli";
12
- const tiangongLcaCliPackageVersion = "0.1.26";
12
+ const tiangongLcaCliPackageVersion = "0.1.28";
13
13
  const tiangongLcaCliBinName = "tiangong-lca";
14
14
  const { repoRoot: foundryRepoRoot } = resolveFoundryRuntimePaths(import.meta.url);
15
15
  function isRecord(value) {
@@ -19,11 +19,12 @@ export declare function registerFoundryTaskAuthorization(context: FoundryRuntime
19
19
  evidence: readonly TaskApprovalEvidence[];
20
20
  expectedPreviousSha256?: string | null;
21
21
  validateCurrent?: (task: LoadedTask, index: readonly ArtifactEntry[]) => void;
22
+ refreshIdentity?: () => VerifiedFoundryIdentity;
22
23
  }, qualification?: QualifiedFoundryRuntime): Promise<{
23
24
  authorization_sha256: string;
24
25
  pointer_sha256: string;
25
26
  }>;
26
- export declare function loadFoundryTaskAuthorization(context: FoundryRuntimeContext, identity: VerifiedFoundryIdentity, inputFile: string, qualification?: QualifiedFoundryRuntime): Promise<ValidatedTaskAuthorization>;
27
+ export declare function loadFoundryTaskAuthorization(context: FoundryRuntimeContext, identity: VerifiedFoundryIdentity, inputFile: string, qualification?: QualifiedFoundryRuntime, refreshIdentity?: () => VerifiedFoundryIdentity): Promise<ValidatedTaskAuthorization>;
27
28
  /** Prepare, but do not activate, an exact successor grant for a verified derived task artifact. */
28
29
  export declare function prepareDerivedFoundryTaskAuthorization(context: FoundryRuntimeContext, qualification: QualifiedFoundryRuntime, identity: VerifiedFoundryIdentity, options: PrepareDerivedFoundryTaskAuthorizationOptions): Promise<Readonly<{
29
30
  grant: Readonly<{
@@ -1,12 +1,30 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, writeFoundryArtifact, assertFoundryWorkspaceActive, } from "./foundry-runtime-context.js";
4
+ import { captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, writeFoundryArtifact, assertFoundryWorkspaceActive, FoundryContextError, } from "./foundry-runtime-context.js";
5
5
  import { assertVerifiedFoundryIdentity, } from "./foundry-runtime-identity.js";
6
6
  import { assertFoundryTaskInputLineage, withFoundryTaskMetadata } from "./foundry-task-store.js";
7
7
  import { bytes, digest, exact, fail, object, readTaskBytes, reference, shaPattern, taskPath, } from "./foundry-task-io.js";
8
8
  import { validateTaskAuthorization, deriveTaskAuthorizationGrant, taskAuthorizationMatches, } from "./task-authorization.js";
9
9
  import { sha256Json } from "./identity-preflight-proof.js";
10
+ /** Only the trusted host can refresh identity, after the locked current snapshot is verified. */
11
+ function metadataIdentity(context, identity, qualification, refreshIdentity) {
12
+ try {
13
+ assertVerifiedFoundryIdentity(context, identity, qualification);
14
+ return identity;
15
+ }
16
+ catch (error) {
17
+ if (!refreshIdentity ||
18
+ !(error instanceof FoundryContextError) ||
19
+ error.code !== "identity_receipt_stale")
20
+ throw error;
21
+ }
22
+ const refreshed = refreshIdentity();
23
+ assertVerifiedFoundryIdentity(context, refreshed, qualification);
24
+ if (refreshed.mode !== identity.mode)
25
+ fail("identity_context_mismatch", "Identity refresh must retain the host authentication mode.");
26
+ return refreshed;
27
+ }
10
28
  function inputFact(context, file) {
11
29
  const resolved = resolveFoundryInputPath(context, file);
12
30
  return context.inputs.find((fact) => fact.path === resolved);
@@ -117,7 +135,7 @@ export async function registerFoundryTaskAuthorization(context, identity, option
117
135
  assertFoundryWorkspaceActive(context);
118
136
  assertVerifiedFoundryIdentity(context, identity, qualification);
119
137
  return withFoundryTaskMetadata(context, (task, index) => {
120
- assertVerifiedFoundryIdentity(context, identity, qualification);
138
+ identity = metadataIdentity(context, identity, qualification, options.refreshIdentity);
121
139
  options.validateCurrent?.(task, index);
122
140
  const input = inputFact(context, options.inputFile);
123
141
  const result = validateTaskAuthorization(options.grant, binding(context, task, input));
@@ -165,12 +183,12 @@ export async function registerFoundryTaskAuthorization(context, identity, option
165
183
  user_id: identity.receipt.identity.user_id,
166
184
  },
167
185
  };
168
- assertVerifiedFoundryIdentity(context, identity, qualification);
186
+ const registrationBytes = writeRegistration(context, registration);
187
+ options.validateCurrent?.(task, index);
188
+ identity = metadataIdentity(context, identity, qualification, options.refreshIdentity);
169
189
  if (validateTaskAuthorization(options.grant, binding(context, task, input)).status !==
170
190
  "authorized")
171
191
  fail("task_authorization_invalid", "Authorization expired or changed before it could be activated.");
172
- const registrationBytes = writeRegistration(context, registration);
173
- options.validateCurrent?.(task, index);
174
192
  const pointer = bytes({
175
193
  schema: "tiangong-foundry.authorization-pointer.v1",
176
194
  authorization_sha256: authorization.authorization_sha256,
@@ -183,14 +201,15 @@ export async function registerFoundryTaskAuthorization(context, identity, option
183
201
  };
184
202
  });
185
203
  }
186
- export async function loadFoundryTaskAuthorization(context, identity, inputFile, qualification) {
204
+ export async function loadFoundryTaskAuthorization(context, identity, inputFile, qualification, refreshIdentity) {
187
205
  assertVerifiedFoundryIdentity(context, identity, qualification);
188
206
  const loaded = await withFoundryTaskMetadata(context, (task) => {
189
- assertVerifiedFoundryIdentity(context, identity, qualification);
207
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
190
208
  const input = inputFact(context, inputFile);
191
209
  if (!fs.existsSync(taskPath(context, "authorization.json")))
192
210
  fail("task_authorization_required", "This task has no active registered authorization.");
193
- const pointer = object(JSON.parse(readTaskBytes(context, "authorization.json").toString("utf8")));
211
+ const pointerBytes = readTaskBytes(context, "authorization.json");
212
+ const pointer = object(JSON.parse(pointerBytes.toString("utf8")));
194
213
  exact(pointer, ["schema", "authorization_sha256", "registration_sha256"]);
195
214
  if (pointer.schema !== "tiangong-foundry.authorization-pointer.v1" ||
196
215
  typeof pointer.authorization_sha256 !== "string")
@@ -273,21 +292,23 @@ export async function loadFoundryTaskAuthorization(context, identity, inputFile,
273
292
  evidencePath !== file.path)
274
293
  fail("authorization_evidence_invalid", "Grant and selected evidence no longer agree.");
275
294
  }
276
- assertVerifiedFoundryIdentity(context, identity, qualification);
295
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
277
296
  const refreshed = validateTaskAuthorization(JSON.parse(grantBytes.toString("utf8")), binding(context, task, input));
278
297
  if (refreshed.status !== "authorized")
279
298
  fail("task_authorization_invalid", "Task authorization expired during evidence verification.");
299
+ if (!readTaskBytes(context, "authorization.json").equals(pointerBytes))
300
+ fail("authorization_update_conflict", "Approval changed during locked identity and evidence verification.");
280
301
  return {
281
302
  authorization: refreshed.authorization,
282
303
  registeredInput: registeredInput.path,
283
- pointerSha256: digest(readTaskBytes(context, "authorization.json")),
304
+ pointerSha256: digest(pointerBytes),
284
305
  inputPath: input.path,
285
306
  };
286
307
  });
287
308
  if (loaded.registeredInput !== loaded.inputPath) {
288
309
  await assertFoundryTaskInputLineage(context, loaded.registeredInput, loaded.inputPath);
289
310
  return withFoundryTaskMetadata(context, (task) => {
290
- assertVerifiedFoundryIdentity(context, identity, qualification);
311
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
291
312
  if (digest(readTaskBytes(context, "authorization.json")) !== loaded.pointerSha256)
292
313
  fail("authorization_update_conflict", "Approval changed during equivalent-content lineage verification.");
293
314
  if (!taskAuthorizationMatches(loaded.authorization, binding(context, task, inputFact(context, inputFile))))