@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,22 @@
1
+ import { type FoundryInputFact } from "./foundry-runtime-context.ts";
2
+ type Json = Record<string, unknown>;
3
+ /** Verify transport and content bindings; the CLI retains every scientific validation decision. */
4
+ export declare function parseFoundryPreparationCliReport(options: {
5
+ report: unknown;
6
+ rows: readonly unknown[];
7
+ input: string;
8
+ outDir: string;
9
+ exit: number;
10
+ }): Json[];
11
+ /** Project owner findings into the existing evidence-backed field patch workflow, without repairs. */
12
+ export declare function preparationValidationActions(row: Json, receipt?: Json): Json[];
13
+ export declare function preparationValidationEvidence(row: Json, report: string, hash: unknown): Json;
14
+ export declare function readPreparationCliEvidence(receipt: {
15
+ report: string;
16
+ exit: number;
17
+ input?: FoundryInputFact;
18
+ }, rows: readonly unknown[], input: string): {
19
+ rows: Json[];
20
+ sha256: string;
21
+ };
22
+ export {};
@@ -0,0 +1,213 @@
1
+ import { readRows } from "./import-curation/internal/runtime-io.js";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import { sha256Text } from "./identity-preflight-proof.js";
5
+ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
6
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
8
+ function record(value) {
9
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
10
+ }
11
+ function token(...values) {
12
+ for (const value of values)
13
+ if (typeof value === "string" && value.trim())
14
+ return value.trim();
15
+ return null;
16
+ }
17
+ const layerNames = ["schema", "authoring_evidence", "content", "multilingual"];
18
+ const profile = "tidas.process-allocation-reference.v1";
19
+ const tolerance = 0.0010000001;
20
+ function fail() {
21
+ throw new FoundryContextError("workflow_validation_invalid", "Owner CLI validation must bind the exact current Process rows, layers and Flow evidence.");
22
+ }
23
+ function object(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value))
25
+ return fail();
26
+ return value;
27
+ }
28
+ function findings(value, statuses) {
29
+ if (!statuses.includes(String(value.status)) || !Array.isArray(value.issues))
30
+ fail();
31
+ if (value.issue_count !== value.issues.length)
32
+ fail();
33
+ if ((value.status === "passed") !== (value.issues.length === 0))
34
+ fail();
35
+ return value.issues.map((issue) => {
36
+ const item = object(issue);
37
+ if (typeof item.code !== "string" ||
38
+ !item.code ||
39
+ typeof item.path !== "string" ||
40
+ typeof item.message !== "string")
41
+ fail();
42
+ return item;
43
+ });
44
+ }
45
+ /** Verify transport and content bindings; the CLI retains every scientific validation decision. */
46
+ export function parseFoundryPreparationCliReport(options) {
47
+ const report = object(options.report);
48
+ if (report.input_path !== options.input ||
49
+ report.requested_type !== "process" ||
50
+ object(report.files).report !==
51
+ path.join(options.outDir, "outputs", "validation-report.json") ||
52
+ !Array.isArray(report.rows) ||
53
+ report.rows.length !== options.rows.length)
54
+ fail();
55
+ const rows = report.rows.map((raw, index) => {
56
+ const row = object(raw);
57
+ const identity = datasetIdentity(options.rows[index], index, "process");
58
+ const candidateHash = sha256Json(identity.payload);
59
+ const wrapper = record(options.rows[index]);
60
+ const process = record(record(identity.payload).processDataSet);
61
+ const id = token(wrapper.id, record(record(process.processInformation).dataSetInformation)["common:UUID"]);
62
+ const version = token(wrapper.version, record(record(process.administrativeInformation).publicationAndOwnership)["common:dataSetVersion"]);
63
+ if (row.index !== index ||
64
+ row.id !== id ||
65
+ row.version !== version ||
66
+ row.type !== "process" ||
67
+ row.payload_sha256 !== candidateHash ||
68
+ !["valid", "invalid"].includes(String(row.status)))
69
+ fail();
70
+ const layers = object(row.validation_layers);
71
+ const layerIssues = layerNames.flatMap((name) => findings(object(layers[name]), ["passed", "failed"]));
72
+ const semantics = object(row.allocation_semantics);
73
+ if (semantics.profile !== profile ||
74
+ semantics.tolerance !== tolerance ||
75
+ semantics.candidate_sha256 !== candidateHash ||
76
+ semantics.options_sha256 !== sha256Json({ profile, tolerance }) ||
77
+ !Array.isArray(semantics.dependencies) ||
78
+ !Array.isArray(semantics.coverage))
79
+ fail();
80
+ const semanticIssues = findings(semantics, ["passed", "failed", "unresolved"]);
81
+ if (semantics.status === "passed") {
82
+ const coverage = semantics.coverage;
83
+ // SDK 0.5.1 emits applicable checks; undeclared/legacy modes omit target/fraction checks.
84
+ const required = ["allocation-target-type", "quantitative-reference"];
85
+ if (coverage.some((entry) => ["invalid", "unresolved"].includes(String(entry.status))) ||
86
+ required.some((check) => !coverage.some((entry) => entry.check === check)))
87
+ fail();
88
+ }
89
+ const supplied = object(options.rows[index]);
90
+ // Published dataset validate reads semantic_context from the original row only.
91
+ const suppliedContexts = [supplied];
92
+ const flowHashes = new Set();
93
+ for (const holder of suppliedContexts) {
94
+ const context = holder.semantic_context;
95
+ if (!context || typeof context !== "object" || Array.isArray(context))
96
+ continue;
97
+ const documents = context.flow_documents;
98
+ if (!Array.isArray(documents))
99
+ continue;
100
+ for (const document of documents) {
101
+ if (!document || typeof document !== "object" || Array.isArray(document))
102
+ continue;
103
+ const flow = document.flowDataSet;
104
+ if (!flow)
105
+ continue;
106
+ const information = flow.flowInformation;
107
+ const administration = flow.administrativeInformation;
108
+ const id = information?.dataSetInformation?.["common:UUID"];
109
+ const version = administration?.publicationAndOwnership?.["common:dataSetVersion"];
110
+ flowHashes.add(JSON.stringify([id, version, sha256Json(document)]));
111
+ }
112
+ }
113
+ for (const rawDependency of semantics.dependencies) {
114
+ const dependency = object(rawDependency);
115
+ if (!flowHashes.has(JSON.stringify([dependency.uuid, dependency.version, dependency.content_sha256])))
116
+ fail();
117
+ }
118
+ for (const rawCoverage of semantics.coverage) {
119
+ const coverage = object(rawCoverage);
120
+ if (typeof coverage.check !== "string" ||
121
+ !Array.isArray(coverage.path) ||
122
+ !["passed", "invalid", "unresolved", "not-applicable"].includes(String(coverage.status)))
123
+ fail();
124
+ }
125
+ const knownIssues = new Set([...layerIssues, ...semanticIssues].map(sha256Json));
126
+ if (!Array.isArray(row.issues) ||
127
+ row.issue_count !== row.issues.length ||
128
+ row.issues.some((issue) => !knownIssues.has(sha256Json(issue))) ||
129
+ (row.status === "valid") !== (row.issues.length === 0) ||
130
+ (row.status === "valid") !== (layerIssues.length + semanticIssues.length === 0))
131
+ fail();
132
+ return row;
133
+ });
134
+ const invalid = rows.filter((row) => row.status === "invalid").length;
135
+ const counts = object(report.counts);
136
+ if (counts.total !== rows.length ||
137
+ counts.invalid !== invalid ||
138
+ counts.valid !== rows.length - invalid ||
139
+ object(counts.by_type).process !== rows.length ||
140
+ options.exit !== (invalid ? 1 : 0) ||
141
+ report.status !== (invalid ? "completed_with_failures" : "completed"))
142
+ fail();
143
+ return rows;
144
+ }
145
+ /** Project owner findings into the existing evidence-backed field patch workflow, without repairs. */
146
+ export function preparationValidationActions(row, receipt) {
147
+ const layers = object(row.validation_layers);
148
+ const semantics = object(row.allocation_semantics);
149
+ const groups = [
150
+ ...layerNames.map((name) => ({ name, value: object(layers[name]) })),
151
+ { name: "allocation_semantics", value: semantics },
152
+ ];
153
+ return groups.flatMap(({ name, value }) => value.issues.map((issue) => ({
154
+ source: "cli_validation",
155
+ validation_layer: name,
156
+ code: issue.code,
157
+ path: issue.path,
158
+ message: issue.message,
159
+ action_kind: "ai_authoring",
160
+ required_owner: "foundry_ai_authoring",
161
+ ai_required: true,
162
+ instruction: "Review the source evidence and current owner finding in full task context. Use the existing bounded authoring patch workflow only for source-backed corrections, then rerun preparation on the exact changed candidate. Unknown scientific evidence remains blocked; do not invent quantities, annual periods, references or allocation fractions.",
163
+ evidence: {
164
+ ...receipt,
165
+ candidate_sha256: row.payload_sha256,
166
+ validation_layer: name,
167
+ validation_layers: layers,
168
+ allocation_semantics: semantics,
169
+ },
170
+ })));
171
+ }
172
+ export function preparationValidationEvidence(row, report, hash) {
173
+ return {
174
+ report_file: report,
175
+ report_sha256: hash,
176
+ row,
177
+ policy: "Owning CLI local save-equivalent evidence; native schema and final remote eligibility remain separate.",
178
+ };
179
+ }
180
+ export function readPreparationCliEvidence(receipt, rows, input) {
181
+ let validationRows = rows;
182
+ let validationInput = input;
183
+ if (receipt.input) {
184
+ const current = captureFoundryInput(receipt.input.path);
185
+ if (current.bytes > 8 * 1024 * 1024 || sha256Json(current) !== sha256Json(receipt.input))
186
+ fail();
187
+ validationRows = readRows(current.path);
188
+ if (validationRows.length !== rows.length ||
189
+ validationRows.some((row, index) => {
190
+ const original = datasetIdentity(rows[index], index, "process");
191
+ const derived = datasetIdentity(row, index, "process");
192
+ const source = record(rows[index]), wrapper = record(row);
193
+ return (original.id !== derived.id ||
194
+ original.version !== derived.version ||
195
+ sha256Json(original.payload) !== sha256Json(derived.payload) ||
196
+ source.id !== wrapper.id ||
197
+ source.version !== wrapper.version);
198
+ }))
199
+ fail();
200
+ validationInput = current.path;
201
+ }
202
+ const bytes = fs.readFileSync(receipt.report, "utf8");
203
+ return {
204
+ rows: parseFoundryPreparationCliReport({
205
+ report: JSON.parse(bytes),
206
+ rows: validationRows,
207
+ input: validationInput,
208
+ outDir: path.dirname(path.dirname(receipt.report)),
209
+ exit: receipt.exit,
210
+ }),
211
+ sha256: sha256Text(bytes),
212
+ };
213
+ }
@@ -0,0 +1,3 @@
1
+ import type { FoundryInteractionState } from "./foundry-interaction-types.ts";
2
+ /** Include both broad and object-scoped Process decisions, without importing other entity types. */
3
+ export declare function qualityReviewInteractionDigest(interaction: FoundryInteractionState | null, processRows: readonly unknown[]): string | null;
@@ -0,0 +1,18 @@
1
+ import { applicableFoundryInteractionDigestForObject } from "./foundry-interaction-projection.js";
2
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
3
+ import { sha256Json } from "./identity-preflight-proof.js";
4
+ /** Include both broad and object-scoped Process decisions, without importing other entity types. */
5
+ export function qualityReviewInteractionDigest(interaction, processRows) {
6
+ if (!interaction)
7
+ return null;
8
+ const scope = processRows.map((row, index) => {
9
+ const identity = datasetIdentity(row, index, "process");
10
+ return {
11
+ row_index: index,
12
+ id: identity.id,
13
+ version: identity.version,
14
+ interaction_sha256: applicableFoundryInteractionDigestForObject(interaction, "process", identity.id, identity.version),
15
+ };
16
+ });
17
+ return scope.some((item) => item.interaction_sha256 !== null) ? sha256Json(scope) : null;
18
+ }
@@ -0,0 +1,48 @@
1
+ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { TaskAuthorizationBinding } from "./task-authorization.ts";
3
+ export declare const FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA: "tiangong-foundry.quality-review-input.v1";
4
+ export declare const FOUNDRY_QUALITY_REVIEW_DRAFT_SCHEMA: "tiangong-foundry.quality-review-draft.v1";
5
+ export interface FoundryQualityReview {
6
+ readonly row_index: number;
7
+ readonly id: string;
8
+ readonly version: string;
9
+ readonly payload_sha256: string;
10
+ readonly finding_sha256: string;
11
+ readonly code: "process_material_balance_deviation";
12
+ readonly evidence_ids: readonly string[];
13
+ readonly rationale: string;
14
+ }
15
+ export interface FoundryQualityReviewEvidence {
16
+ readonly id: string;
17
+ readonly kind: "user-decision" | "source-model";
18
+ /** v1 evidence is selected as strict UTF-8 text, including source-model JSON. */
19
+ readonly file: string;
20
+ readonly sha256: string;
21
+ }
22
+ export interface FoundryQualityReviewInput {
23
+ readonly schema: typeof FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA;
24
+ readonly binding: Readonly<TaskAuthorizationBinding>;
25
+ readonly runtime_qualification_sha256: string;
26
+ readonly rows_manifest_sha256: string;
27
+ readonly assessment_sha256: string;
28
+ readonly context_sha256: string;
29
+ readonly reference_inputs_sha256: string | null;
30
+ readonly interaction_context_sha256: string | null;
31
+ readonly qa_report_sha256: string;
32
+ readonly qa_findings_sha256: string;
33
+ readonly expected_previous_sha256: string | null;
34
+ readonly issued_at_utc: string;
35
+ readonly expires_at_utc: string;
36
+ readonly reviews: readonly FoundryQualityReview[];
37
+ readonly evidence: readonly FoundryQualityReviewEvidence[];
38
+ }
39
+ export interface SelectedFoundryQualityReviewInput {
40
+ readonly spec: FoundryQualityReviewInput;
41
+ readonly descriptor: FoundryInputFact;
42
+ readonly evidence: readonly FoundryInputFact[];
43
+ }
44
+ export declare function parseFoundryQualityReviewInput(value: unknown): FoundryQualityReviewInput;
45
+ /** Expand only explicit completed decisions; file facts are captured by the owning caller. */
46
+ export declare function materializeFoundryQualityReviewInput(value: unknown, captureEvidence: (file: string) => FoundryInputFact): FoundryQualityReviewInput;
47
+ export declare function selectFoundryQualityReviewInput(context: FoundryRuntimeContext, descriptorFile: string): SelectedFoundryQualityReviewInput;
48
+ export declare function assertSelectedFoundryQualityReviewInput(value: SelectedFoundryQualityReviewInput): void;
@@ -0,0 +1,284 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
4
+ import { assertNotFoundrySessionFile, migrationCredentialPath } from "./foundry-private-path.js";
5
+ import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
6
+ export const FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA = "tiangong-foundry.quality-review-input.v1";
7
+ export const FOUNDRY_QUALITY_REVIEW_DRAFT_SCHEMA = "tiangong-foundry.quality-review-draft.v1";
8
+ const selections = new WeakSet();
9
+ const sha = /^[0-9a-f]{64}$/u;
10
+ const identifier = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u;
11
+ const bindingKeys = [
12
+ "workspace_id",
13
+ "task_id",
14
+ "actor_id",
15
+ "project_ref",
16
+ "user_id",
17
+ "profile_id",
18
+ "profile_sha256",
19
+ "input_scope_sha256",
20
+ ];
21
+ const hashKeys = [
22
+ "runtime_qualification_sha256",
23
+ "rows_manifest_sha256",
24
+ "assessment_sha256",
25
+ "context_sha256",
26
+ "qa_report_sha256",
27
+ "qa_findings_sha256",
28
+ ];
29
+ function invalid(message) {
30
+ throw new FoundryContextError("quality_review_input_invalid", message);
31
+ }
32
+ function record(value) {
33
+ if (!value || typeof value !== "object" || Array.isArray(value))
34
+ invalid("Quality review input requires complete objects.");
35
+ return value;
36
+ }
37
+ function exact(value, keys) {
38
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
39
+ invalid("Quality review input has missing or unsupported fields.");
40
+ }
41
+ function validTime(value) {
42
+ return (typeof value === "string" &&
43
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(value) &&
44
+ Number.isFinite(Date.parse(value)) &&
45
+ new Date(value).toISOString() === value);
46
+ }
47
+ function validPath(value) {
48
+ return (typeof value === "string" &&
49
+ Boolean(value.trim()) &&
50
+ value.length <= 4096 &&
51
+ !/[\0\r\n]/u.test(value));
52
+ }
53
+ export function parseFoundryQualityReviewInput(value) {
54
+ const data = record(value);
55
+ exact(data, [
56
+ "schema",
57
+ "binding",
58
+ ...hashKeys,
59
+ "reference_inputs_sha256",
60
+ "interaction_context_sha256",
61
+ "expected_previous_sha256",
62
+ "issued_at_utc",
63
+ "expires_at_utc",
64
+ "reviews",
65
+ "evidence",
66
+ ]);
67
+ const binding = record(data.binding);
68
+ exact(binding, bindingKeys);
69
+ if (data.schema !== FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA ||
70
+ bindingKeys.some((key) => typeof binding[key] !== "string" ||
71
+ !(key.endsWith("_sha256") ? sha : identifier).test(binding[key])) ||
72
+ !/^task-[0-9a-f]{64}-r[0-9]{4}$/u.test(String(binding.task_id)) ||
73
+ hashKeys.some((key) => typeof data[key] !== "string" || !sha.test(data[key])) ||
74
+ [
75
+ data.reference_inputs_sha256,
76
+ data.interaction_context_sha256,
77
+ data.expected_previous_sha256,
78
+ ].some((hash) => hash !== null && (typeof hash !== "string" || !sha.test(hash))) ||
79
+ !validTime(data.issued_at_utc) ||
80
+ !validTime(data.expires_at_utc) ||
81
+ !Array.isArray(data.reviews) ||
82
+ !data.reviews.length ||
83
+ data.reviews.length > 128 ||
84
+ !Array.isArray(data.evidence) ||
85
+ !data.evidence.length ||
86
+ data.evidence.length > 100)
87
+ invalid("Quality review scope, hashes, timestamps or bounded lists are invalid.");
88
+ const lifetime = Date.parse(data.expires_at_utc) - Date.parse(data.issued_at_utc);
89
+ if (lifetime <= 0 || lifetime > 24 * 60 * 60 * 1000)
90
+ invalid("Quality review validity must be a positive interval of at most 24 hours.");
91
+ const evidence = data.evidence.map((raw) => {
92
+ const item = record(raw);
93
+ exact(item, ["id", "kind", "file", "sha256"]);
94
+ if (typeof item.id !== "string" ||
95
+ !identifier.test(item.id) ||
96
+ (item.kind !== "user-decision" && item.kind !== "source-model") ||
97
+ !validPath(item.file) ||
98
+ typeof item.sha256 !== "string" ||
99
+ !sha.test(item.sha256))
100
+ invalid("Quality review evidence selection is invalid.");
101
+ return Object.freeze({ id: item.id, kind: item.kind, file: item.file, sha256: item.sha256 });
102
+ });
103
+ const evidenceById = new Map(evidence.map((item) => [item.id, item]));
104
+ if (evidenceById.size !== evidence.length)
105
+ invalid("Quality review evidence ids must be unique.");
106
+ const used = new Set();
107
+ const reviews = data.reviews.map((raw) => {
108
+ const item = record(raw);
109
+ exact(item, [
110
+ "row_index",
111
+ "id",
112
+ "version",
113
+ "payload_sha256",
114
+ "finding_sha256",
115
+ "code",
116
+ "evidence_ids",
117
+ "rationale",
118
+ ]);
119
+ if (typeof item.row_index !== "number" ||
120
+ !Number.isSafeInteger(item.row_index) ||
121
+ item.row_index < 0 ||
122
+ typeof item.id !== "string" ||
123
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(item.id) ||
124
+ typeof item.version !== "string" ||
125
+ !/^[0-9]{2}\.[0-9]{2}\.[0-9]{3}$/u.test(item.version) ||
126
+ typeof item.payload_sha256 !== "string" ||
127
+ !sha.test(item.payload_sha256) ||
128
+ typeof item.finding_sha256 !== "string" ||
129
+ !sha.test(item.finding_sha256) ||
130
+ item.code !== "process_material_balance_deviation" ||
131
+ !Array.isArray(item.evidence_ids) ||
132
+ !item.evidence_ids.length ||
133
+ item.evidence_ids.length > 100 ||
134
+ item.evidence_ids.some((id) => typeof id !== "string" || !identifier.test(id)) ||
135
+ new Set(item.evidence_ids).size !== item.evidence_ids.length ||
136
+ typeof item.rationale !== "string" ||
137
+ !item.rationale.trim() ||
138
+ item.rationale.length > 8192)
139
+ invalid("Quality review row, finding or rationale is invalid.");
140
+ const ids = item.evidence_ids;
141
+ const kinds = new Set(ids.map((id) => {
142
+ const selected = evidenceById.get(id);
143
+ if (!selected)
144
+ invalid("Every quality review evidence id must resolve.");
145
+ used.add(id);
146
+ return selected.kind;
147
+ }));
148
+ if (!kinds.has("user-decision") || !kinds.has("source-model"))
149
+ invalid("Every quality review requires user-decision and source-model evidence.");
150
+ return Object.freeze({
151
+ row_index: item.row_index,
152
+ id: item.id,
153
+ version: item.version,
154
+ payload_sha256: item.payload_sha256,
155
+ finding_sha256: item.finding_sha256,
156
+ code: item.code,
157
+ evidence_ids: Object.freeze([...ids]),
158
+ rationale: item.rationale,
159
+ });
160
+ });
161
+ if (used.size !== evidence.length ||
162
+ new Set(reviews.map((item) => item.row_index)).size !== reviews.length ||
163
+ new Set(reviews.map((item) => `${item.id}/${item.version}`)).size !== reviews.length ||
164
+ new Set(reviews.map((item) => item.finding_sha256)).size !== reviews.length)
165
+ invalid("Quality reviews cannot duplicate rows, identities or findings, or select unused evidence.");
166
+ return Object.freeze({
167
+ schema: FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA,
168
+ binding: Object.freeze({ ...binding }),
169
+ runtime_qualification_sha256: data.runtime_qualification_sha256,
170
+ rows_manifest_sha256: data.rows_manifest_sha256,
171
+ assessment_sha256: data.assessment_sha256,
172
+ context_sha256: data.context_sha256,
173
+ reference_inputs_sha256: data.reference_inputs_sha256,
174
+ interaction_context_sha256: data.interaction_context_sha256,
175
+ qa_report_sha256: data.qa_report_sha256,
176
+ qa_findings_sha256: data.qa_findings_sha256,
177
+ expected_previous_sha256: data.expected_previous_sha256,
178
+ issued_at_utc: data.issued_at_utc,
179
+ expires_at_utc: data.expires_at_utc,
180
+ reviews: Object.freeze(reviews),
181
+ evidence: Object.freeze(evidence),
182
+ });
183
+ }
184
+ function strictText(fact) {
185
+ try {
186
+ return new TextDecoder("utf-8", { fatal: true }).decode(readSelectedSemanticBytes(fact));
187
+ }
188
+ catch {
189
+ return invalid("Quality review input must retain exact strict UTF-8 bytes.");
190
+ }
191
+ }
192
+ /** Expand only explicit completed decisions; file facts are captured by the owning caller. */
193
+ export function materializeFoundryQualityReviewInput(value, captureEvidence) {
194
+ const data = record(value);
195
+ if (data.schema !== FOUNDRY_QUALITY_REVIEW_DRAFT_SCHEMA)
196
+ return parseFoundryQualityReviewInput(data);
197
+ if (!Array.isArray(data.reviews) ||
198
+ !data.reviews.length ||
199
+ data.reviews.length > 128 ||
200
+ !Array.isArray(data.evidence) ||
201
+ !data.evidence.length ||
202
+ data.evidence.length > 100)
203
+ invalid("Complete the selected review decisions and evidence before submission.");
204
+ const reviews = data.reviews.map((raw) => {
205
+ const review = record(raw);
206
+ if (review.disposition !== "accept-interpretation")
207
+ invalid("Each selected review requires an explicit accept-interpretation decision.");
208
+ const { disposition: _disposition, ...decision } = review;
209
+ return decision;
210
+ });
211
+ const evidence = data.evidence.map((raw) => {
212
+ const entry = record(raw);
213
+ exact(entry, ["id", "kind", "file"]);
214
+ if (!validPath(entry.file))
215
+ invalid("Select the actual quality review evidence file.");
216
+ return { ...entry, sha256: captureEvidence(entry.file).sha256 };
217
+ });
218
+ return parseFoundryQualityReviewInput({
219
+ ...data,
220
+ schema: FOUNDRY_QUALITY_REVIEW_INPUT_SCHEMA,
221
+ reviews,
222
+ evidence,
223
+ });
224
+ }
225
+ export function selectFoundryQualityReviewInput(context, descriptorFile) {
226
+ let total = 0;
227
+ const captured = new Map();
228
+ const capture = (name) => {
229
+ if (!validPath(name))
230
+ invalid("Quality review input path is invalid.");
231
+ const target = path.resolve(context.workspaceRoot, name);
232
+ if (migrationCredentialPath(path.relative(context.workspaceRoot, target)))
233
+ invalid("Credential paths cannot be quality review inputs.");
234
+ assertNotFoundrySessionFile(target, context.accountIntent?.sessionReference);
235
+ const previous = captured.get(target);
236
+ if (previous) {
237
+ readSelectedSemanticBytes(previous);
238
+ return previous;
239
+ }
240
+ const stat = fs.lstatSync(target);
241
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8 * 1024 * 1024)
242
+ invalid("Quality review inputs must be bounded regular files.");
243
+ total += stat.size;
244
+ if (total > 64 * 1024 * 1024)
245
+ invalid("Quality review inputs exceed the 64 MiB batch limit.");
246
+ const fact = Object.freeze(captureFoundryInput(target));
247
+ captured.set(target, fact);
248
+ return fact;
249
+ };
250
+ const descriptor = capture(descriptorFile);
251
+ let spec;
252
+ try {
253
+ spec = materializeFoundryQualityReviewInput(JSON.parse(strictText(descriptor)), capture);
254
+ }
255
+ catch {
256
+ invalid("Select a complete supported quality review input descriptor.");
257
+ }
258
+ if (spec.binding.workspace_id !== context.workspaceId ||
259
+ spec.binding.task_id !== context.taskId ||
260
+ spec.binding.actor_id !== context.actorId ||
261
+ !context.accountIntent ||
262
+ spec.binding.project_ref !== context.accountIntent.projectRef ||
263
+ spec.binding.user_id !== context.accountIntent.userId)
264
+ invalid("Quality review selection belongs to another workspace, task, actor or account.");
265
+ const evidence = spec.evidence.map((entry) => {
266
+ const fact = capture(entry.file);
267
+ if (fact.sha256 !== entry.sha256)
268
+ invalid("Quality review evidence differs from the selected digest.");
269
+ if (!strictText(fact).trim())
270
+ invalid("Quality review evidence must contain the actual decision or source-model evidence.");
271
+ return fact;
272
+ });
273
+ if (new Set([descriptor.path, ...evidence.map((fact) => fact.path)]).size !== evidence.length + 1)
274
+ invalid("Select each quality review file only once.");
275
+ const result = Object.freeze({ spec, descriptor, evidence: Object.freeze(evidence) });
276
+ selections.add(result);
277
+ return result;
278
+ }
279
+ export function assertSelectedFoundryQualityReviewInput(value) {
280
+ if (!selections.has(value))
281
+ invalid("Quality review input must be selected by the current host.");
282
+ for (const fact of [value.descriptor, ...value.evidence])
283
+ readSelectedSemanticBytes(fact);
284
+ }
@@ -0,0 +1,13 @@
1
+ /** Verify the existing cleanup producer's explicit validation-context proof. Never transform rows. */
2
+ export declare function unchangedQualityReviewRows(input: {
3
+ originalRows: readonly unknown[];
4
+ finalRowsFile: string;
5
+ taskRoot: string;
6
+ assetRoot: string;
7
+ cleanupReport?: unknown;
8
+ referenceFiles: readonly {
9
+ path: string;
10
+ bytes: number;
11
+ sha256: string;
12
+ }[];
13
+ }): boolean;