@tiangong-lca/foundry 0.1.18 → 0.1.20

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 (116) hide show
  1. package/README.md +5 -3
  2. package/docs/architecture.md +5 -3
  3. package/docs/foundry-task-contracts.md +2 -0
  4. package/docs/package-distribution-contract.md +10 -8
  5. package/docs/public-runtime-contract.md +53 -3
  6. package/docs/runtime-context-contract.md +7 -3
  7. package/docs/task-authorization-contract.md +2 -0
  8. package/package-dist/assets/foundry-package-descriptor.json +374 -136
  9. package/package-dist/scripts/foundry-facade.d.ts +6 -0
  10. package/package-dist/scripts/foundry-facade.js +38 -0
  11. package/package-dist/scripts/foundry-runtime.d.ts +3 -2
  12. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  13. package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
  14. package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
  15. package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
  16. package/package-dist/scripts/lib/final-delivery-review.js +108 -0
  17. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  18. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  19. package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  21. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  22. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  23. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  24. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  25. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  26. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  27. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  28. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  29. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  30. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  31. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  32. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  33. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +24 -0
  34. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +209 -0
  35. package/package-dist/scripts/lib/foundry-edge-session.d.ts +32 -0
  36. package/package-dist/scripts/lib/foundry-edge-session.js +203 -0
  37. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  38. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  39. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  40. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  41. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  42. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  43. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  44. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  45. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  46. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  47. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  48. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  49. package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
  50. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  51. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  52. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  53. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  54. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  55. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +21 -0
  56. package/package-dist/scripts/lib/foundry-owner-readback.js +61 -0
  57. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  58. package/package-dist/scripts/lib/foundry-package-contract.js +8 -2
  59. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  60. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  61. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  62. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  63. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  64. package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
  65. package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
  66. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  67. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
  68. package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
  69. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  70. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  71. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  72. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  73. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  74. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  75. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  76. package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
  77. package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
  78. package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
  79. package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
  80. package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
  81. package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
  82. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
  83. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  84. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  85. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  86. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  87. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  88. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  89. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  90. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  91. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  92. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  93. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  94. package/package-dist/scripts/lib/foundry-workflow-execution.js +57 -5
  95. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  96. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  97. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  98. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  99. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  100. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
  101. package/package-dist/scripts/lib/foundry-workflow-repair.js +204 -2
  102. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  103. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  104. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  105. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  106. package/package-dist/scripts/public-api.d.ts +6 -0
  107. package/package-dist/scripts/runtime-entry.js +15 -6
  108. package/package.json +5 -2
  109. package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
  110. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  111. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  112. package/specs/schemas/foundry-package-descriptor.schema.json +5 -2
  113. package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
  114. package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
  115. package/specs/schemas/foundry-task-start.schema.json +10 -2
  116. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -64,6 +64,12 @@ export declare function createFoundryFacade(options: FoundryFacadeOptions): Read
64
64
  start(input: {
65
65
  specFile: string;
66
66
  }): Promise<FoundryOperationResult>;
67
+ prepareInput(input: {
68
+ taskId: string;
69
+ actorId: string;
70
+ kind: "interaction" | "semantic";
71
+ draftFile: string;
72
+ }): Promise<FoundryOperationResult>;
67
73
  status(input: {
68
74
  taskId: string;
69
75
  actorId: string;
@@ -1,3 +1,4 @@
1
+ import { prepareFoundryTaskInput } from "./lib/foundry-task-input-preparation.js";
1
2
  import { planFoundryTaskRuntimeAdoption, applyFoundryTaskRuntimeAdoption, } from "./lib/foundry-task-runtime-adoption-write.js";
2
3
  import { assertRuntimeAdoptionToolkit, assertAdoptedRuntimeToolkit, readFoundryTaskRuntimeAdoption, } from "./lib/foundry-task-runtime-adoption.js";
3
4
  import { assertFoundryRepairExecution } from "./lib/foundry-repair-execution.js";
@@ -199,6 +200,9 @@ function failure(operation, taskId, error, identity = null) {
199
200
  "EMFILE",
200
201
  "ENFILE",
201
202
  "EBUSY",
203
+ "BATCH_RUN_LOCK_TIMEOUT",
204
+ "BATCH_RUN_LOCK_IDENTITY_CONFLICT",
205
+ "ERR_SYSTEM_ERROR",
202
206
  "UNKNOWN",
203
207
  "ERR_INVALID_ARG_TYPE",
204
208
  "ERR_INVALID_ARG_VALUE",
@@ -1551,6 +1555,40 @@ export function createFoundryFacade(options) {
1551
1555
  return failure("task.start", taskId, error, current ? runtimeIdentity(current) : null);
1552
1556
  }
1553
1557
  },
1558
+ async prepareInput(input) {
1559
+ let current = null;
1560
+ try {
1561
+ assertNotInterrupted(options.signal);
1562
+ current = base();
1563
+ const record = loadFoundryFacadeTaskRecord(current, input.taskId, input.actorId);
1564
+ const context = taskContext(options, current, record);
1565
+ const qualified = qualification(context, options.runtimeSelection);
1566
+ const runtime = createFoundryRuntime(context, qualified);
1567
+ const before = await runtime.inspectTask();
1568
+ if (input.kind !== "interaction" && input.kind !== "semantic")
1569
+ throw new FoundryContextError("task_input_draft_invalid", "Select interaction or semantic input preparation.");
1570
+ const descriptor = prepareFoundryTaskInput(context, before.artifacts, record.spec.target_entities, input.kind, input.draftFile);
1571
+ const after = await runtime.inspectTask();
1572
+ if (sha256Json(before.artifacts) !== sha256Json(after.artifacts))
1573
+ throw new FoundryContextError("task_input_state_changed", "Task evidence changed during input preparation. Inspect the current task and prepare again.");
1574
+ assertNotInterrupted(options.signal);
1575
+ return createFoundryOperationResult({
1576
+ operation: "task.prepare-input",
1577
+ status: "ready",
1578
+ taskId: record.task_id,
1579
+ artifacts: [inlineArtifact("prepared_task_input", descriptor)],
1580
+ blockers: [],
1581
+ nextActions: [
1582
+ human("save_prepared_task_input", `Save the prepared_task_input value as JSON and submit it through task resume --${input.kind}-input. Its SHA-256 bindings name the current indexed state and exact raw file bytes. Review the selected decisions and evidence before submission.`),
1583
+ ],
1584
+ runtimeIdentity: runtimeIdentity(context, qualified),
1585
+ permissions: noPermission(),
1586
+ });
1587
+ }
1588
+ catch (error) {
1589
+ return failure("task.prepare-input", input.taskId, error, current ? runtimeIdentity(current) : null);
1590
+ }
1591
+ },
1554
1592
  async status(input) {
1555
1593
  let current = null;
1556
1594
  try {
@@ -52,6 +52,7 @@ export declare function createFoundryRuntime(context: FoundryRuntimeContext, qua
52
52
  contract: string;
53
53
  before: string;
54
54
  candidate: string;
55
+ scientific?: string;
55
56
  predecessor: Readonly<{
56
57
  task_id: string;
57
58
  receipt_sha256: string;
@@ -138,7 +139,7 @@ export declare function createFoundryRuntime(context: FoundryRuntimeContext, qua
138
139
  capsule_sha256: string;
139
140
  }>>;
140
141
  rehydrateExecution: (identity: VerifiedFoundryIdentity, options: RehydrateFoundryExecutionAdmissionOptions) => Promise<FoundryExecutionAdmission>;
141
- admitExecution: (identity: VerifiedFoundryIdentity, admission: FoundryExecutionAdmission) => Promise<import("@tiangong-lca/cli/command-spec").FoundryCommandSpec>;
142
+ admitExecution: (identity: VerifiedFoundryIdentity, admission: FoundryExecutionAdmission) => Promise<import("./lib/foundry-edge-support-plan.ts").EdgeSupportPlan | import("@tiangong-lca/cli/command-spec").FoundryCommandSpec>;
142
143
  profiles: () => import("./lib/import-curation/internal/profiles-config.ts").ImportProfilesList;
143
144
  describe: () => {
144
145
  platform: string;
@@ -181,7 +182,7 @@ export declare function createFoundryRuntime(context: FoundryRuntimeContext, qua
181
182
  };
182
183
  command_policy: {
183
184
  total: number;
184
- public_operations: readonly ["workspace.init", "doctor", "task.start", "task.status", "task.resume", "task.adopt-runtime", "workspace.migrate"];
185
+ public_operations: readonly ["workspace.init", "doctor", "task.start", "task.status", "task.prepare-input", "task.resume", "task.adopt-runtime", "workspace.migrate"];
185
186
  public_facade: ("acceptance-check" | "capabilities-list" | "dataset-authoring-patch-collect" | "dataset-authoring-plan" | "dataset-authoring-task-build" | "dataset-bafu-authoring-patches-autofill" | "dataset-bafu-batch-import-run" | "dataset-bafu-identity-decisions-autofill" | "dataset-bafu-leaf-classification-category-map-project" | "dataset-bafu-leaf-classification-tasks-prepare" | "dataset-bafu-process-scope-e2e" | "dataset-bafu-universe-coverage-report" | "dataset-bundle-sample-rows" | "dataset-canonical-support-mappings-autofill" | "dataset-classification-decision-task-build" | "dataset-classification-decisions-apply" | "dataset-commit-handoff-plan" | "dataset-curation-cleanup" | "dataset-curation-gate" | "dataset-curation-queue-build" | "dataset-identity-decision-task-build" | "dataset-identity-decisions-apply" | "dataset-identity-preflight-index-merge" | "dataset-identity-preflight-query-audit" | "dataset-identity-preflight-requests-build" | "dataset-identity-preflight-run" | "dataset-identity-reference-rewrites-apply" | "dataset-import-completion-report" | "dataset-import-ledger-report" | "dataset-incremental-change-set-compose" | "dataset-library-authoring-plan" | "dataset-library-classification-decisions-project" | "dataset-library-decisions-apply" | "dataset-library-identity-decisions-from-preflight" | "dataset-library-index-build" | "dataset-location-decision-task-build" | "dataset-location-decisions-apply" | "dataset-location-decisions-suggest" | "dataset-mutation-manifest" | "dataset-patch-apply" | "dataset-post-authoring-finalize" | "dataset-post-write-closeout" | "dataset-process-scope-run" | "dataset-support-cache-refresh" | "dataset-tidas-import" | "dataset-tidas-validate" | "dataset-topology-convergence-compose" | "dataset-uslci-batch-import-run" | "dataset-worldsteel-batch-import-run" | "doctor" | "env-check" | "execution-capsule-admit" | "final-delivery-promote" | "init" | "profiles-list" | "route-task" | "storage-check" | "surface-audit" | "task-complete" | "tasks-check" | "tasks-list" | "tidas-handshake" | "workflow-check" | "workspace-map")[];
186
187
  internal_only: number;
187
188
  excluded: ("acceptance-check" | "capabilities-list" | "dataset-authoring-patch-collect" | "dataset-authoring-plan" | "dataset-authoring-task-build" | "dataset-bafu-authoring-patches-autofill" | "dataset-bafu-batch-import-run" | "dataset-bafu-identity-decisions-autofill" | "dataset-bafu-leaf-classification-category-map-project" | "dataset-bafu-leaf-classification-tasks-prepare" | "dataset-bafu-process-scope-e2e" | "dataset-bafu-universe-coverage-report" | "dataset-bundle-sample-rows" | "dataset-canonical-support-mappings-autofill" | "dataset-classification-decision-task-build" | "dataset-classification-decisions-apply" | "dataset-commit-handoff-plan" | "dataset-curation-cleanup" | "dataset-curation-gate" | "dataset-curation-queue-build" | "dataset-identity-decision-task-build" | "dataset-identity-decisions-apply" | "dataset-identity-preflight-index-merge" | "dataset-identity-preflight-query-audit" | "dataset-identity-preflight-requests-build" | "dataset-identity-preflight-run" | "dataset-identity-reference-rewrites-apply" | "dataset-import-completion-report" | "dataset-import-ledger-report" | "dataset-incremental-change-set-compose" | "dataset-library-authoring-plan" | "dataset-library-classification-decisions-project" | "dataset-library-decisions-apply" | "dataset-library-identity-decisions-from-preflight" | "dataset-library-index-build" | "dataset-location-decision-task-build" | "dataset-location-decisions-apply" | "dataset-location-decisions-suggest" | "dataset-mutation-manifest" | "dataset-patch-apply" | "dataset-post-authoring-finalize" | "dataset-post-write-closeout" | "dataset-process-scope-run" | "dataset-support-cache-refresh" | "dataset-tidas-import" | "dataset-tidas-validate" | "dataset-topology-convergence-compose" | "dataset-uslci-batch-import-run" | "dataset-worldsteel-batch-import-run" | "doctor" | "env-check" | "execution-capsule-admit" | "final-delivery-promote" | "init" | "profiles-list" | "route-task" | "storage-check" | "surface-audit" | "task-complete" | "tasks-check" | "tasks-list" | "tidas-handshake" | "workflow-check" | "workspace-map")[];
@@ -290,7 +290,9 @@ export function createIdentityPreflightRunCommands({ executionEnvironment = proc
290
290
  maxAgeMs: positiveIntegerOption(options.authReceiptMaxAgeMs, 300_000) ?? 300_000,
291
291
  expectedProjectRef,
292
292
  expectedUserId,
293
- sessionMode: executionEnvironment.TIANGONG_LCA_AUTH_MODE === "access_token" ? "headless" : "oauth",
293
+ sessionMode: ["access-token", "access_token"].includes(executionEnvironment.TIANGONG_LCA_AUTH_MODE ?? "")
294
+ ? "headless"
295
+ : "oauth",
294
296
  });
295
297
  }
296
298
  const logDir = path.join(outDir, "logs");
@@ -0,0 +1,40 @@
1
+ import crypto from "node:crypto";
2
+ export type JsonRecord = Record<string, unknown>;
3
+ export declare const MANIFEST_SCHEMA = "foundry-final-delivery-manifest.v1";
4
+ export declare const REPORT_SCHEMA = "foundry-final-delivery-promotion-report.v1";
5
+ export declare const LEDGER_SCHEMA = "foundry-final-delivery-promotion-ledger-row.v1";
6
+ export declare const SEAL_SCHEMA = "foundry-final-delivery-promotion-seal.v1";
7
+ export declare const MAX_ZIP_ENTRIES = 10000;
8
+ export declare const MAX_ZIP_ENTRY_BYTES: number;
9
+ export declare const MAX_ZIP_TOTAL_BYTES: number;
10
+ export declare function sha256(value: crypto.BinaryLike): string;
11
+ export declare function compareText(left: string, right: string): number;
12
+ export declare function stableJson(value: unknown): string;
13
+ export declare function isPlainObject(value: unknown): value is JsonRecord;
14
+ export declare function isSha256(value: unknown): boolean;
15
+ export declare function pathIsInside(root: string, candidate: string): boolean;
16
+ export declare function safeRelativePath(value: unknown): boolean;
17
+ export declare function writeExclusive(filePath: string, content: string | Buffer): void;
18
+ export declare function writeJsonExclusive(filePath: string, value: unknown): void;
19
+ export declare function relativeToRepo(repoRoot: string, filePath: string): string;
20
+ export type CheckSeverity = "P0" | "P1";
21
+ export type LedgerRow = {
22
+ schema_version: string;
23
+ check_id: string;
24
+ status: "PASS" | "FAIL";
25
+ severity: CheckSeverity | null;
26
+ detail: string;
27
+ evidence: unknown;
28
+ };
29
+ export type CheckCollector = {
30
+ add: (checkId: string, passed: boolean, severity: CheckSeverity, detail: string, evidence?: unknown) => boolean;
31
+ rows: LedgerRow[];
32
+ };
33
+ export declare function scanTextWithDecodedStrings(raw: string, value: unknown): string;
34
+ export declare function decodeArtifactText(buffer: Buffer): string;
35
+ export declare class PromotionArtifactError extends Error {
36
+ readonly code: string;
37
+ constructor(code: string, message: string);
38
+ }
39
+ export declare function artifactErrorCode(error: unknown): string;
40
+ export declare function checkCollector(): CheckCollector;
@@ -0,0 +1,145 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ export const MANIFEST_SCHEMA = "foundry-final-delivery-manifest.v1";
5
+ export const REPORT_SCHEMA = "foundry-final-delivery-promotion-report.v1";
6
+ export const LEDGER_SCHEMA = "foundry-final-delivery-promotion-ledger-row.v1";
7
+ export const SEAL_SCHEMA = "foundry-final-delivery-promotion-seal.v1";
8
+ export const MAX_ZIP_ENTRIES = 10_000;
9
+ export const MAX_ZIP_ENTRY_BYTES = 32 * 1024 * 1024;
10
+ export const MAX_ZIP_TOTAL_BYTES = 64 * 1024 * 1024;
11
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/u;
12
+ export function sha256(value) {
13
+ return crypto.createHash("sha256").update(value).digest("hex");
14
+ }
15
+ export function compareText(left, right) {
16
+ if (left < right)
17
+ return -1;
18
+ if (left > right)
19
+ return 1;
20
+ return 0;
21
+ }
22
+ function stableValue(value) {
23
+ if (Array.isArray(value))
24
+ return value.map(stableValue);
25
+ if (isPlainObject(value)) {
26
+ return Object.fromEntries(Object.entries(value)
27
+ .sort(([left], [right]) => compareText(left, right))
28
+ .map(([key, child]) => [key, stableValue(child)]));
29
+ }
30
+ return value;
31
+ }
32
+ // Content-addressed evidence must hash the same regardless of object key insertion order.
33
+ export function stableJson(value) {
34
+ return JSON.stringify(stableValue(value));
35
+ }
36
+ export function isPlainObject(value) {
37
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
38
+ }
39
+ export function isSha256(value) {
40
+ return typeof value === "string" && SHA256_PATTERN.test(value);
41
+ }
42
+ export function pathIsInside(root, candidate) {
43
+ const relative = path.relative(root, candidate);
44
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
45
+ }
46
+ export function safeRelativePath(value) {
47
+ return Boolean(typeof value === "string" &&
48
+ value.length > 0 &&
49
+ !path.posix.isAbsolute(value) &&
50
+ !value.includes("\\") &&
51
+ !value.split("/").includes("..") &&
52
+ path.posix.normalize(value) === value);
53
+ }
54
+ // Every promotion artifact is written with an exclusive create so earlier evidence is never
55
+ // overwritten, and a failed run leaves no partial replacement of prior bytes.
56
+ export function writeExclusive(filePath, content) {
57
+ fs.writeFileSync(filePath, content, { flag: "wx" });
58
+ }
59
+ export function writeJsonExclusive(filePath, value) {
60
+ writeExclusive(filePath, `${JSON.stringify(value, null, 2)}\n`);
61
+ }
62
+ export function relativeToRepo(repoRoot, filePath) {
63
+ return pathIsInside(repoRoot, filePath) ? path.relative(repoRoot, filePath) : filePath;
64
+ }
65
+ function collectStrings(value, out) {
66
+ // Keys are collected as well as values: a decoded key reaches a reader exactly like a value does,
67
+ // and an escaped key can carry a literal a raw-byte scan never sees.
68
+ if (typeof value === "string") {
69
+ out.push(value);
70
+ return;
71
+ }
72
+ if (Array.isArray(value)) {
73
+ for (const item of value)
74
+ collectStrings(item, out);
75
+ return;
76
+ }
77
+ if (isPlainObject(value)) {
78
+ for (const [key, child] of Object.entries(value)) {
79
+ out.push(key);
80
+ collectStrings(child, out);
81
+ }
82
+ }
83
+ }
84
+ // JSON string escaping can hide a literal from a raw byte scan, so the decoded keys and values of
85
+ // already-parsed content are scanned alongside the exact source bytes.
86
+ export function scanTextWithDecodedStrings(raw, value) {
87
+ const decoded = [];
88
+ collectStrings(value, decoded);
89
+ return decoded.length > 0 ? `${raw}\n${decoded.join("\n")}` : raw;
90
+ }
91
+ // Tab, newline and carriage return are the only control characters a supported text artifact may
92
+ // carry; any other C0 control or DEL means the bytes are not the text they claim to be.
93
+ function hasUnsupportedControl(text) {
94
+ for (const character of text) {
95
+ const code = character.codePointAt(0) ?? 0;
96
+ if (code === 0x09 || code === 0x0a || code === 0x0d)
97
+ continue;
98
+ if (code < 0x20 || code === 0x7f)
99
+ return true;
100
+ }
101
+ return false;
102
+ }
103
+ // The supported text encoding is strict UTF-8. Silent replacement would scan text that is not the
104
+ // artifact's own content, so an undecodable byte fails closed instead.
105
+ export function decodeArtifactText(buffer) {
106
+ let text;
107
+ try {
108
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buffer);
109
+ }
110
+ catch {
111
+ throw new PromotionArtifactError("artifact_text_encoding_invalid", "A text artifact must be valid UTF-8 and cannot contain undecodable bytes.");
112
+ }
113
+ if (hasUnsupportedControl(text)) {
114
+ throw new PromotionArtifactError("artifact_control_byte", "A text artifact cannot contain an unsupported control byte.");
115
+ }
116
+ return text;
117
+ }
118
+ // Every parse failure carries a stable category. The message is for local debugging only and is
119
+ // never written into the promotion ledger or report, so raw artifact text cannot leak outward.
120
+ export class PromotionArtifactError extends Error {
121
+ code;
122
+ constructor(code, message) {
123
+ super(message);
124
+ this.name = "PromotionArtifactError";
125
+ this.code = code;
126
+ }
127
+ }
128
+ export function artifactErrorCode(error) {
129
+ return error instanceof PromotionArtifactError ? error.code : "artifact_parse_failed";
130
+ }
131
+ export function checkCollector() {
132
+ const rows = [];
133
+ function add(checkId, passed, severity, detail, evidence = null) {
134
+ rows.push({
135
+ schema_version: LEDGER_SCHEMA,
136
+ check_id: checkId,
137
+ status: passed ? "PASS" : "FAIL",
138
+ severity: passed ? null : severity,
139
+ detail,
140
+ evidence,
141
+ });
142
+ return passed;
143
+ }
144
+ return { add, rows };
145
+ }
@@ -0,0 +1,37 @@
1
+ import { type JsonRecord } from "./final-delivery-manifest.ts";
2
+ export type ReviewerDeclaration = JsonRecord & {
3
+ reviewer_id?: string;
4
+ artifact_id?: string;
5
+ required_artifact_ids?: unknown;
6
+ };
7
+ export type ReviewerReport = JsonRecord & {
8
+ reviewer_id?: string;
9
+ status?: string;
10
+ reviewed_artifacts?: unknown;
11
+ findings?: {
12
+ p0?: number;
13
+ p1?: number;
14
+ };
15
+ };
16
+ export type ReviewedArtifactBinding = {
17
+ artifact_id: string;
18
+ sha256: string;
19
+ bytes: number;
20
+ };
21
+ export declare function reviewerDeclarations(manifest: JsonRecord): ReviewerDeclaration[];
22
+ export declare function reviewerIdentityValid(reviewer: ReviewerDeclaration, producerId: unknown, seenReviewerIds: ReadonlySet<string>, seenArtifactIds: ReadonlySet<string>): boolean;
23
+ export declare function reviewerPassValid(report: unknown, reviewerId: unknown): boolean;
24
+ export type ReviewScope = {
25
+ bindings: ReviewedArtifactBinding[];
26
+ duplicateIds: string[];
27
+ malformedCount: number;
28
+ };
29
+ export declare function reviewScope(report: unknown): ReviewScope | null;
30
+ export declare function reviewerCoverageValid(report: unknown, required: readonly unknown[], currentBindings: ReadonlyMap<string, {
31
+ sha256: string;
32
+ bytes: number;
33
+ }>, reviewerArtifactId: unknown): boolean;
34
+ export declare function reviewerContentBindingValid(report: unknown, required: readonly unknown[], currentBindings: ReadonlyMap<string, {
35
+ sha256: string;
36
+ bytes: number;
37
+ }>): boolean;
@@ -0,0 +1,108 @@
1
+ import { isPlainObject, isSha256 } from "./final-delivery-manifest.js";
2
+ export function reviewerDeclarations(manifest) {
3
+ const reviewers = manifest.reviewers;
4
+ if (!Array.isArray(reviewers))
5
+ return [];
6
+ return reviewers.filter(isPlainObject);
7
+ }
8
+ // The reviewer identity must be present, independent of the producer, and used at most once.
9
+ export function reviewerIdentityValid(reviewer, producerId, seenReviewerIds, seenArtifactIds) {
10
+ const reviewerId = reviewer?.reviewer_id;
11
+ const artifactId = reviewer?.artifact_id;
12
+ return Boolean(reviewerId &&
13
+ reviewerId !== producerId &&
14
+ !seenReviewerIds.has(reviewerId) &&
15
+ artifactId &&
16
+ !seenArtifactIds.has(artifactId));
17
+ }
18
+ // A PASS disposition is only meaningful when the report names the same reviewer and declares
19
+ // zero P0 and P1 findings, so a producer cannot close its own evidence gap.
20
+ export function reviewerPassValid(report, reviewerId) {
21
+ if (!isPlainObject(report))
22
+ return false;
23
+ const typed = report;
24
+ return (typed.reviewer_id === reviewerId &&
25
+ typed.status === "PASS" &&
26
+ typed.findings?.p0 === 0 &&
27
+ typed.findings?.p1 === 0);
28
+ }
29
+ function reviewedBinding(value) {
30
+ if (!isPlainObject(value))
31
+ return null;
32
+ const artifactId = value.artifact_id;
33
+ const sha256 = value.sha256;
34
+ const bytes = value.bytes;
35
+ if (typeof artifactId !== "string" || artifactId.length === 0)
36
+ return null;
37
+ if (!isSha256(sha256))
38
+ return null;
39
+ if (!Number.isInteger(bytes) || bytes < 0)
40
+ return null;
41
+ return { artifact_id: artifactId, sha256: sha256, bytes: bytes };
42
+ }
43
+ export function reviewScope(report) {
44
+ if (!isPlainObject(report))
45
+ return null;
46
+ const reviewed = report.reviewed_artifacts;
47
+ if (!Array.isArray(reviewed) || reviewed.length === 0)
48
+ return null;
49
+ const bindings = [];
50
+ const seen = new Set();
51
+ const duplicateIds = [];
52
+ let malformedCount = 0;
53
+ for (const entry of reviewed) {
54
+ const binding = reviewedBinding(entry);
55
+ if (!binding) {
56
+ malformedCount += 1;
57
+ continue;
58
+ }
59
+ if (seen.has(binding.artifact_id))
60
+ duplicateIds.push(binding.artifact_id);
61
+ seen.add(binding.artifact_id);
62
+ bindings.push(binding);
63
+ }
64
+ return { bindings, duplicateIds, malformedCount };
65
+ }
66
+ // Review coverage is content-bound. Each manifest-required artifact must be individually bound to
67
+ // the exact SHA-256 and byte count the reviewer saw, and those values must still match the bytes
68
+ // the manifest currently binds. The reviewer's own report artifact is excluded so the binding
69
+ // cannot be made circular by hashing the report that carries the hash.
70
+ export function reviewerCoverageValid(report, required, currentBindings, reviewerArtifactId) {
71
+ const scope = reviewScope(report);
72
+ if (!scope)
73
+ return false;
74
+ if (scope.malformedCount > 0 || scope.duplicateIds.length > 0)
75
+ return false;
76
+ const boundIds = new Set(scope.bindings.map((binding) => binding.artifact_id));
77
+ if (typeof reviewerArtifactId === "string" && boundIds.has(reviewerArtifactId))
78
+ return false;
79
+ // A binding for an artifact that is not in the manifest is an unknown identity, not coverage.
80
+ for (const id of boundIds) {
81
+ if (!currentBindings.has(id))
82
+ return false;
83
+ }
84
+ if (required.length === 0 || new Set(required).size !== required.length)
85
+ return false;
86
+ return required.every((id) => typeof id === "string" && boundIds.has(id));
87
+ }
88
+ export function reviewerContentBindingValid(report, required, currentBindings) {
89
+ const scope = reviewScope(report);
90
+ if (!scope)
91
+ return false;
92
+ if (scope.malformedCount > 0 || scope.duplicateIds.length > 0)
93
+ return false;
94
+ // Every binding the report declares must match the current bytes, not only the required ones: a
95
+ // stale or wrong digest on a voluntarily-included artifact is still a false claim.
96
+ for (const binding of scope.bindings) {
97
+ const current = currentBindings.get(binding.artifact_id);
98
+ if (!current)
99
+ return false;
100
+ if (binding.sha256 !== current.sha256 || binding.bytes !== current.bytes)
101
+ return false;
102
+ }
103
+ // `required_artifact_ids` sets the minimum coverage, not the set to verify.
104
+ const boundIds = new Set(scope.bindings.map((binding) => binding.artifact_id));
105
+ return (required.length > 0 &&
106
+ new Set(required).size === required.length &&
107
+ required.every((id) => typeof id === "string" && boundIds.has(id)));
108
+ }
@@ -3,7 +3,8 @@ type CliResolution = {
3
3
  command: string;
4
4
  args: string[];
5
5
  display: string;
6
- package: JsonRecord | null;
6
+ package: string | JsonRecord | null;
7
+ package_version?: string | null;
7
8
  };
8
9
  export type CliWrapperOptions = Record<string, unknown> & {
9
10
  help?: unknown;
@@ -48,5 +49,75 @@ export type CliWrapperFactoryDependencies = {
48
49
  export declare function createCliWrapperCommands({ executionEnvironment, executionCwd, appendOption, appendRepeatedOptions, repoRoot, resolveTiangongLcaCliCommand, resolveTiangongLcaCliBin, }: CliWrapperFactoryDependencies): {
49
50
  runDatasetCurationQueueBuild: (options: CliWrapperOptions) => JsonRecord;
50
51
  runDatasetPatchApply: (options: CliWrapperOptions) => JsonRecord;
52
+ runDatasetQaStage: (stage: string, argv: string[]) => {
53
+ stage: string;
54
+ exit_code: number;
55
+ report: {
56
+ schema: string;
57
+ status: string;
58
+ rows_file: string;
59
+ validation_input: string;
60
+ validation_operation: string;
61
+ validations: {
62
+ id: string;
63
+ version: string;
64
+ result: string;
65
+ reference_documents: string | null;
66
+ complete_sha256: string;
67
+ }[];
68
+ rows: {
69
+ findings: {
70
+ entity_id: string;
71
+ version: string;
72
+ severity: string;
73
+ code: string;
74
+ path: string;
75
+ message: string;
76
+ }[];
77
+ }[];
78
+ findings: {
79
+ entity_id: string;
80
+ version: string;
81
+ severity: string;
82
+ code: string;
83
+ path: string;
84
+ message: string;
85
+ }[];
86
+ files: {
87
+ report: string;
88
+ };
89
+ } | {
90
+ status: string;
91
+ policy_decision_owner: string;
92
+ qa_mode: string;
93
+ mass_balance: import("../foundry-process-mass-balance.ts").ProcessMassBalance[];
94
+ findings: {
95
+ process_file: string;
96
+ severity: "info" | "warning" | "blocker";
97
+ code: string;
98
+ methodology_rule_id: string | null;
99
+ message: string;
100
+ source: "rule";
101
+ evidence?: {
102
+ [x: string]: unknown;
103
+ };
104
+ }[];
105
+ schema: string;
106
+ rows_file: string;
107
+ reference_evidence: import("../foundry-runtime-context-types.ts").FoundryInputFact[];
108
+ files: {
109
+ report: string;
110
+ };
111
+ };
112
+ report_file: string;
113
+ cli_validation?: {
114
+ report: string;
115
+ exit: number;
116
+ } | undefined;
117
+ status: string;
118
+ command: string;
119
+ args: string[];
120
+ stderr: string;
121
+ } | null;
51
122
  };
52
123
  export {};