@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
@@ -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,6 +95,11 @@ 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;
99
104
  export declare function validateBoundExecutionManifest(value: unknown, binding: IdentityPreflightBinding, reportText: string | null): {
100
105
  ok: boolean;
@@ -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.`);
@@ -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
+ };
@@ -0,0 +1,415 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { createFileArtifactFact, createFoundryCommandSpec } from "./foundry-command-spec.js";
5
+ import { sha256Json, sha256Text, stableJson, parseFreshIntentBoundAuthReceipt, } from "./identity-preflight-proof.js";
6
+ /** Compare retained executable dependencies with the independent current/transition inventory. */
7
+ export function verifyRetainedIdentityCliInventory(value, bin) {
8
+ if (value.role !== "current_retained_cli_inventory" ||
9
+ !path.isAbsolute(value.root) ||
10
+ fs.realpathSync(value.root) !== value.root ||
11
+ fs.realpathSync(bin) !== path.join(value.root, "bin/tiangong-lca.js") ||
12
+ !Array.isArray(value.files) ||
13
+ value.files.length < 1 ||
14
+ value.files.length > 10_000 ||
15
+ sha256Text(JSON.stringify(value.files)) !== value.content_sha256 ||
16
+ new Set(value.files.map((file) => file.path)).size !== value.files.length)
17
+ throw new Error("Retained CLI inventory is invalid.");
18
+ for (const fact of value.files) {
19
+ const file = path.resolve(value.root, fact.path);
20
+ if (path.isAbsolute(fact.path) ||
21
+ !file.startsWith(value.root + path.sep) ||
22
+ fs.realpathSync(file) !== file)
23
+ throw new Error("Retained CLI inventory path changed.");
24
+ readIdentityRecoveryFact({ ...fact, path: file });
25
+ }
26
+ const pkg = JSON.parse(fs.readFileSync(path.join(value.root, "package.json"), "utf8"));
27
+ if (pkg.name !== "@tiangong-lca/cli" || pkg.version !== value.package_version)
28
+ throw new Error("Retained CLI package identity changed.");
29
+ }
30
+ /** Current readback of a retained executable; it does not claim a query-time runtime capture. */
31
+ export function observeRetainedIdentityExecutable(file) {
32
+ let fd;
33
+ try {
34
+ if (!path.isAbsolute(file) || fs.realpathSync(file) !== file)
35
+ return null;
36
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
37
+ const before = fs.fstatSync(fd, { bigint: true });
38
+ if (!before.isFile() || before.size < 1n || before.size > 256n * 1024n * 1024n)
39
+ return null;
40
+ const bytes = fs.readFileSync(fd), after = fs.fstatSync(fd, { bigint: true });
41
+ if (before.dev !== after.dev ||
42
+ before.ino !== after.ino ||
43
+ before.size !== after.size ||
44
+ before.mtimeNs !== after.mtimeNs ||
45
+ before.ctimeNs !== after.ctimeNs ||
46
+ BigInt(bytes.length) !== after.size)
47
+ return null;
48
+ return {
49
+ path: file,
50
+ bytes: bytes.length,
51
+ sha256: createHash("sha256").update(bytes).digest("hex"),
52
+ };
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ finally {
58
+ if (fd !== undefined)
59
+ fs.closeSync(fd);
60
+ }
61
+ }
62
+ function object(value) {
63
+ return value !== null && typeof value === "object" && !Array.isArray(value);
64
+ }
65
+ const hash = /^[0-9a-f]{64}$/u;
66
+ /** Read only the exact named regular original evidence; never discover reports or reconstruct attempts. */
67
+ export function readIdentityRecoveryFact(fact) {
68
+ const fd = fs.openSync(fact.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
69
+ try {
70
+ const stat = fs.fstatSync(fd);
71
+ if (!stat.isFile() || stat.size !== fact.bytes || stat.size > 8 * 1024 * 1024)
72
+ throw new Error("Recovery evidence changed.");
73
+ const bytes = fs.readFileSync(fd);
74
+ if (createHash("sha256").update(bytes).digest("hex") !== fact.sha256)
75
+ throw new Error("Recovery evidence changed.");
76
+ return bytes;
77
+ }
78
+ finally {
79
+ fs.closeSync(fd);
80
+ }
81
+ }
82
+ export function validateIdentityPreflightRecoveryEvidence(value, input) {
83
+ const fail = () => ({ ok: false, code: "identity_preflight_recovery_invalid" });
84
+ if (!object(value) ||
85
+ value.schema !== "tiangong-foundry.identity-preflight-recovery.v1" ||
86
+ value.new_cli_execution !== false ||
87
+ typeof value.task_id !== "string" ||
88
+ typeof value.actor_id !== "string" ||
89
+ !object(value.binding) ||
90
+ value.binding.schema !== "tiangong-foundry.identity-preflight-binding.v1" ||
91
+ !object(value.original) ||
92
+ !object(value.current_owner_interpretation_auth))
93
+ return fail();
94
+ if (typeof input.expectedRetainedCliContentSha256 !== "string" ||
95
+ !hash.test(input.expectedRetainedCliContentSha256) ||
96
+ !object(value.current_retained_cli_inventory) ||
97
+ value.current_retained_cli_inventory.content_sha256 !== input.expectedRetainedCliContentSha256)
98
+ return fail();
99
+ const { proof_sha256, ...scope } = value;
100
+ if (proof_sha256 !== sha256Json(scope))
101
+ return fail();
102
+ const binding = value.binding, original = value.original, auth = value.current_owner_interpretation_auth;
103
+ if (!object(binding.dataset) ||
104
+ !object(binding.request) ||
105
+ !object(binding.command) ||
106
+ !object(binding.cli) ||
107
+ !object(binding.account) ||
108
+ !object(binding.relevant_input_hashes))
109
+ return fail();
110
+ const { binding_sha256, ...bindingScope } = binding;
111
+ if (binding_sha256 !== sha256Json(bindingScope) ||
112
+ value.binding_sha256 !== binding_sha256 ||
113
+ binding.cli.package_name !== "@tiangong-lca/cli" ||
114
+ !["0.1.22", "0.1.27", "0.1.28"].includes(String(binding.cli.package_version)) ||
115
+ typeof binding.cli.package_integrity !== "string" ||
116
+ !/^sha256-[0-9a-f]{64}$/u.test(binding.cli.package_integrity) ||
117
+ binding.dataset.type !== input.datasetType ||
118
+ binding.dataset.id !== input.datasetId ||
119
+ binding.dataset.version !== input.datasetVersion ||
120
+ binding.dataset.target_sha256 !== input.targetSha256)
121
+ return fail();
122
+ if (original.attempt !== 1 ||
123
+ original.status !== "failed" ||
124
+ original.failure_code !== "identity_preflight_cli_exit_nonzero" ||
125
+ original.cli_exit_code !== 1 ||
126
+ !object(original.producer_auth) ||
127
+ typeof original.producer_auth.captured_at_utc !== "string" ||
128
+ !object(original.facts))
129
+ return fail();
130
+ for (const account of [original.producer_auth, auth]) {
131
+ if (account.project_ref !== binding.account.project_ref ||
132
+ account.user_id !== binding.account.user_id ||
133
+ typeof account.receipt_scope_sha256 !== "string" ||
134
+ !hash.test(account.receipt_scope_sha256))
135
+ return fail();
136
+ }
137
+ if ((input.expectedProjectRef && input.expectedProjectRef !== binding.account.project_ref) ||
138
+ (input.expectedUserId && input.expectedUserId !== binding.account.user_id))
139
+ return fail();
140
+ const prepared = Date.parse(String(original.batch_prepared_at_utc)), query = Date.parse(String(original.query_generated_at_utc)), completed = Date.parse(String(original.batch_completed_at_utc)), interpreted = Date.parse(String(value.recovered_at_utc)), admitted = Date.parse(String(auth.captured_at_utc));
141
+ if (![prepared, query, completed, interpreted, admitted].every(Number.isFinite) ||
142
+ query < prepared ||
143
+ completed < query ||
144
+ interpreted < completed ||
145
+ admitted > interpreted ||
146
+ interpreted - admitted > 300_000)
147
+ return fail();
148
+ if (input.requestText === null || input.reportText === null)
149
+ return fail();
150
+ try {
151
+ const request = JSON.parse(input.requestText), report = JSON.parse(input.reportText);
152
+ if (!object(request) ||
153
+ !object(report) ||
154
+ binding.request.bytes_sha256 !== sha256Text(input.requestText) ||
155
+ binding.request.canonical_sha256 !== sha256Json(request) ||
156
+ sha256Text(JSON.stringify(request.target)) !== input.targetSha256 ||
157
+ report.schema_version !== 1 ||
158
+ report.kind !== input.datasetType ||
159
+ report.status !== "needs_review" ||
160
+ report.decision !== "manual_review" ||
161
+ report.next_action !== "queue_manual_review" ||
162
+ report.generated_at_utc !== original.query_generated_at_utc ||
163
+ !object(report.target) ||
164
+ report.target.id !== input.datasetId ||
165
+ report.target.version !== input.datasetVersion ||
166
+ !Array.isArray(report.candidates) ||
167
+ !Array.isArray(report.candidate_sources) ||
168
+ !Array.isArray(report.findings) ||
169
+ !Array.isArray(report.blockers) ||
170
+ report.blockers.length ||
171
+ Object.hasOwn(report, "error") ||
172
+ (Object.hasOwn(report, "errors") &&
173
+ (!Array.isArray(report.errors) || report.errors.length)) ||
174
+ (Object.hasOwn(report, "ok") && report.ok !== true))
175
+ return fail();
176
+ const texts = new Map();
177
+ const facts = original.facts;
178
+ for (const key of [
179
+ "stage",
180
+ "run",
181
+ "results",
182
+ "preparation",
183
+ "audit",
184
+ "request",
185
+ "stdout",
186
+ "stderr",
187
+ "report",
188
+ "producer_receipt",
189
+ "producer_plan",
190
+ "job",
191
+ "index",
192
+ "source_file",
193
+ "assessment",
194
+ "auth_receipt",
195
+ ]) {
196
+ const fact = original.facts[key];
197
+ if (!object(fact) ||
198
+ typeof fact.path !== "string" ||
199
+ !Number.isSafeInteger(fact.bytes) ||
200
+ typeof fact.sha256 !== "string" ||
201
+ !hash.test(fact.sha256))
202
+ return fail();
203
+ texts.set(key, readIdentityRecoveryFact(fact).toString("utf8"));
204
+ }
205
+ if (texts.get("request") !== input.requestText ||
206
+ texts.get("report") !== input.reportText ||
207
+ texts.get("stderr") !== "" ||
208
+ stableJson(JSON.parse(texts.get("stdout"))) !== stableJson(report))
209
+ return fail();
210
+ const run = JSON.parse(texts.get("run")), stage = JSON.parse(texts.get("stage")), plan = JSON.parse(texts.get("producer_plan")), receipt = JSON.parse(texts.get("producer_receipt")), job = JSON.parse(texts.get("job"));
211
+ if (!object(run) ||
212
+ !object(stage) ||
213
+ !object(plan) ||
214
+ !object(receipt) ||
215
+ !object(job) ||
216
+ run.status !== "failed" ||
217
+ run.command !== "dataset-identity-preflight-run" ||
218
+ run.generated_at_utc !== original.batch_completed_at_utc ||
219
+ stage.schema !== "tiangong-foundry.identity-stage.v1" ||
220
+ stage.status !== "blocked" ||
221
+ plan.command !== "dataset-workflow-identity" ||
222
+ receipt.status !== "completed" ||
223
+ job.task_id !== value.task_id ||
224
+ job.actor_id !== value.actor_id ||
225
+ plan.job_sha256 !== facts.job.sha256 ||
226
+ receipt.job_sha256 !== plan.job_sha256 ||
227
+ !object(receipt.plan) ||
228
+ receipt.plan.sha256 !== facts.producer_plan.sha256 ||
229
+ !Array.isArray(receipt.outputs))
230
+ return fail();
231
+ const options = run.runtime_options;
232
+ if (!object(options) ||
233
+ !object(options.cli) ||
234
+ !object(options.auth_receipt) ||
235
+ options.cli.package !== `@tiangong-lca/cli@${String(binding.cli.package_version)}` ||
236
+ options.auth_receipt.project_ref !== original.producer_auth.project_ref ||
237
+ options.auth_receipt.user_id !== original.producer_auth.user_id ||
238
+ options.auth_receipt.receipt_scope_sha256 !== original.producer_auth.receipt_scope_sha256 ||
239
+ !object(stage.account) ||
240
+ stage.account.project_ref !== binding.account.project_ref ||
241
+ stage.account.user_id !== binding.account.user_id ||
242
+ !Array.isArray(run.results))
243
+ return fail();
244
+ const originalReceipt = parseFreshIntentBoundAuthReceipt(JSON.parse(texts.get("auth_receipt")), {
245
+ nowMs: prepared,
246
+ maxAgeMs: 300_000,
247
+ expectedProjectRef: String(binding.account.project_ref),
248
+ expectedUserId: String(binding.account.user_id),
249
+ });
250
+ if (originalReceipt.receipt_scope_sha256 !== original.producer_auth.receipt_scope_sha256 ||
251
+ originalReceipt.captured_at_utc !== original.producer_auth.captured_at_utc ||
252
+ originalReceipt.cli.package_name !== binding.cli.package_name ||
253
+ originalReceipt.cli.package_version !== binding.cli.package_version)
254
+ return fail();
255
+ const observed = value.current_retained_runtime_observation;
256
+ if (!object(observed) ||
257
+ observed.role !== "current_retained_runtime_observation" ||
258
+ observed.observed_at_utc !== value.recovered_at_utc ||
259
+ !object(observed.original_executable) ||
260
+ typeof observed.qualified_node_sha256 !== "string" ||
261
+ !hash.test(observed.qualified_node_sha256) ||
262
+ observed.original_executable.path !== options.cli.executable)
263
+ return fail();
264
+ const executable = observeRetainedIdentityExecutable(String(observed.original_executable.path));
265
+ if (!object(value.current_retained_cli_inventory) ||
266
+ value.current_retained_cli_inventory.package_version !== binding.cli.package_version ||
267
+ !Array.isArray(options.cli.args_prefix) ||
268
+ typeof options.cli.args_prefix[0] !== "string")
269
+ return fail();
270
+ verifyRetainedIdentityCliInventory(value.current_retained_cli_inventory, options.cli.args_prefix[0]);
271
+ if (!executable ||
272
+ executable.bytes !== observed.original_executable.bytes ||
273
+ executable.sha256 !== observed.original_executable.sha256 ||
274
+ executable.sha256 !== observed.qualified_node_sha256)
275
+ return fail();
276
+ const result = run.results.find((row) => object(row) &&
277
+ row.dataset_type === input.datasetType &&
278
+ row.dataset_id === input.datasetId &&
279
+ row.dataset_version === input.datasetVersion);
280
+ if (!object(result) ||
281
+ result.status !== "failed" ||
282
+ result.failure_code !== original.failure_code ||
283
+ result.cli_exit_code !== 1 ||
284
+ result.attempt !== 1 ||
285
+ result.attempts !== 1 ||
286
+ result.binding_sha256 !== binding_sha256 ||
287
+ result.request_bytes_sha256 !== binding.request.bytes_sha256 ||
288
+ result.report_status !== "needs_review" ||
289
+ result.decision !== "manual_review")
290
+ return fail();
291
+ const indexRows = texts
292
+ .get("index")
293
+ .trim()
294
+ .split(/\r?\n/u)
295
+ .map((line) => JSON.parse(line));
296
+ const selected = indexRows.filter((row) => object(row) &&
297
+ row.dataset_type === input.datasetType &&
298
+ row.dataset_id === input.datasetId &&
299
+ row.dataset_version === input.datasetVersion);
300
+ if (selected.length !== 1 || !object(selected[0]))
301
+ return fail();
302
+ const assessment = JSON.parse(texts.get("assessment"));
303
+ if (typeof original.producer_base !== "string" ||
304
+ !path.isAbsolute(original.producer_base) ||
305
+ !object(assessment) ||
306
+ assessment.owner_base !== original.producer_base ||
307
+ assessment.schema !== "tiangong-foundry.assessment-stage.v1")
308
+ return fail();
309
+ const row = selected[0], taskRoot = path.dirname(facts.job.path), resolve = (locator) => typeof locator === "string" ? path.resolve(String(original.producer_base), locator) : null;
310
+ // Absolute fact paths are confined to this original task and must match its registered producer outputs.
311
+ if (Object.values(facts).some((fact) => !path.isAbsolute(fact.path) || !fact.path.startsWith(taskRoot + path.sep)))
312
+ return fail();
313
+ if (resolve(row.request_file) !== facts.request.path ||
314
+ resolve(row.expected_report_file) !== facts.report.path ||
315
+ resolve(row.source_file) !== facts.source_file.path ||
316
+ binding.relevant_input_hashes.source_file !== facts.source_file.sha256 ||
317
+ row.request_bytes_sha256 !== binding.request.bytes_sha256 ||
318
+ row.target_sha256 !== input.targetSha256 ||
319
+ row.request_json_sha256 !== sha256Text(JSON.stringify(request)) ||
320
+ report.input_path !== facts.request.path ||
321
+ report.out_dir !== resolve(row.output_dir) ||
322
+ !object(report.files) ||
323
+ report.files.identity_decision !== facts.report.path)
324
+ return fail();
325
+ const semanticArgv = [
326
+ input.datasetType,
327
+ "identity-preflight",
328
+ "--json",
329
+ "--timeout-ms",
330
+ String(options.timeout_ms),
331
+ ];
332
+ const argv = [
333
+ input.datasetType,
334
+ "identity-preflight",
335
+ "--input",
336
+ facts.request.path,
337
+ "--out-dir",
338
+ String(report.out_dir),
339
+ "--json",
340
+ "--timeout-ms",
341
+ String(options.timeout_ms),
342
+ ];
343
+ if (stableJson(binding.command.semantic_argv) !== stableJson(semanticArgv) ||
344
+ !/^[1-9][0-9]*$/u.test(String(options.timeout_ms)) ||
345
+ options.max_attempts !== 1 ||
346
+ options.retry_failed !== null ||
347
+ !Array.isArray(options.cli.args_prefix) ||
348
+ options.cli.args_prefix.length !== 1 ||
349
+ typeof options.cli.args_prefix[0] !== "string" ||
350
+ `sha256-${sha256Text(fs.readFileSync(options.cli.args_prefix[0], "utf8"))}` !==
351
+ binding.cli.package_integrity ||
352
+ result.executable !== options.cli.executable ||
353
+ result.cli_package !== options.cli.package ||
354
+ stableJson(result.cli_args) !== stableJson(argv) ||
355
+ resolve(result.request_file) !== facts.request.path ||
356
+ resolve(result.report_file) !== facts.report.path ||
357
+ resolve(result.stdout_log) !== facts.stdout.path ||
358
+ resolve(result.stderr_log) !== facts.stderr.path)
359
+ return fail();
360
+ const spec = createFoundryCommandSpec({
361
+ executable: String(options.cli.executable),
362
+ argv: [...options.cli.args_prefix, ...argv],
363
+ binding: {
364
+ artifacts: [
365
+ createFileArtifactFact({
366
+ role: "identity_preflight_request",
367
+ path: String(row.request_file),
368
+ filePath: facts.request.path,
369
+ }),
370
+ ],
371
+ },
372
+ });
373
+ if (stableJson(result.command_spec) !== stableJson(spec) ||
374
+ stableJson(run.results) !==
375
+ stableJson(texts
376
+ .get("results")
377
+ .trim()
378
+ .split(/\r?\n/u)
379
+ .map((line) => JSON.parse(line))))
380
+ return fail();
381
+ const preparation = JSON.parse(texts.get("preparation")), audit = JSON.parse(texts.get("audit"));
382
+ if (!object(preparation) ||
383
+ preparation.status !== "ready" ||
384
+ preparation.generated_at_utc !== original.batch_prepared_at_utc ||
385
+ !object(audit) ||
386
+ audit.status !== "passed" ||
387
+ !Array.isArray(audit.blockers) ||
388
+ audit.blockers.length)
389
+ return fail();
390
+ for (const key of [
391
+ "stage",
392
+ "run",
393
+ "results",
394
+ "preparation",
395
+ "audit",
396
+ "request",
397
+ "stdout",
398
+ "stderr",
399
+ "report",
400
+ "index",
401
+ "auth_receipt",
402
+ ]) {
403
+ const fact = original.facts[key];
404
+ if (!receipt.outputs.some((item) => object(item) &&
405
+ item.sha256 === fact.sha256 &&
406
+ item.bytes === fact.bytes &&
407
+ path.resolve(taskRoot, String(item.path)) === fact.path))
408
+ return fail();
409
+ }
410
+ return { ok: true, binding: binding };
411
+ }
412
+ catch {
413
+ return fail();
414
+ }
415
+ }
@@ -20,6 +20,14 @@ interface CurationCleanupOptions extends JsonRecord {
20
20
  interface CurationCleanupArgs {
21
21
  repoRoot?: string;
22
22
  options?: CurationCleanupOptions;
23
+ processValidationReferences?: {
24
+ rows: readonly unknown[];
25
+ files: readonly {
26
+ path: string;
27
+ bytes: number;
28
+ sha256: string;
29
+ }[];
30
+ };
23
31
  io?: {
24
32
  nowIso?: () => string;
25
33
  fileExists: typeof fileExists;
@@ -28,5 +36,5 @@ interface CurationCleanupArgs {
28
36
  writeText: typeof writeText;
29
37
  };
30
38
  }
31
- export declare function runDatasetCurationCleanup({ repoRoot, options, io, }?: CurationCleanupArgs): JsonRecord;
39
+ export declare function runDatasetCurationCleanup({ repoRoot, options, processValidationReferences, io, }?: CurationCleanupArgs): JsonRecord;
32
40
  export {};