@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
@@ -204,6 +204,7 @@ interface FinalizeDependencies {
204
204
  repoRoot: string;
205
205
  reportFileFromCliStage: (stage: FinalizeStage, paths: string[], fallback: string) => string | null;
206
206
  readRowsFile: (filePath: string) => DatasetRow[];
207
+ readReferenceBytes?: (filePath: string) => Buffer;
207
208
  repairTrueSourceClassification: (row: DatasetRow, context: JsonRecord) => void;
208
209
  repairTrueSourceDescription: (row: DatasetRow, context: JsonRecord) => void;
209
210
  repairTrueSourceIdentity: (row: DatasetRow, context: JsonRecord) => void;
@@ -228,7 +229,7 @@ interface FinalizeDependencies {
228
229
  writeJson: (filePath: string, value: unknown) => void;
229
230
  writeJsonLines: (filePath: string, rows: readonly unknown[]) => void;
230
231
  }
231
- export declare function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }: FinalizeDependencies): {
232
+ export declare function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, readReferenceBytes, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }: FinalizeDependencies): {
232
233
  runDatasetPostAuthoringFinalize: (options: FinalizeOptions) => FinalizeStage;
233
234
  };
234
235
  export {};
@@ -1,8 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { taskAuthorizationAllows } from "../task-authorization.js";
4
5
  import { readOnlyStageContract } from "../stage-contract.js";
5
6
  import { selectFinalizeReferenceInputs } from "./finalize-reference-inputs.js";
7
+ import { readRows } from "../import-curation/internal/runtime-io.js";
6
8
  const postAuthoringFinalizeStageContract = readOnlyStageContract([
7
9
  {
8
10
  stage: "prepare_scope",
@@ -18,6 +20,7 @@ const postAuthoringFinalizeStageContract = readOnlyStageContract([
18
20
  purpose: "Apply identity reference rewrites, unresolved exchange externalization, BAFU source/contact rewrites, canonical support rewrites, and deterministic curation cleanup.",
19
21
  inputs: [
20
22
  "input rows",
23
+ "selected read-only Process validation references",
21
24
  "identity/preflight indexes",
22
25
  "BAFU source/contact policy",
23
26
  "canonical support cache",
@@ -87,7 +90,7 @@ function verifiedReferenceLedgerFilesForDir(ledgerDir) {
87
90
  .map((name) => path.join(ledgerDir, name))
88
91
  .filter((filePath) => fs.existsSync(filePath) && fs.statSync(filePath).isFile());
89
92
  }
90
- export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }) {
93
+ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonicalSupportRewrites, applyIdentityReferenceRewrites, asText, profileFor, blockersFromLocationAuditStage, buildLibraryContactPayload, booleanOption, compactStageReport, cloneJson, contactGlobalReference, datasetIdentity, datasetRowsFileStem, ensureArray, externalizeUnresolvedProcessFlowExchanges, fileExists, normalizedList, nowIso, postAuthoringPrewriteGateBlockers, processSourceReferenceRows, profileFullContextRequirement, repoRelativeMaybe, loadCanonicalSupportCache, repoRelativePath, repoRoot, reportFileFromCliStage, readRowsFile, readReferenceBytes = (file) => fs.readFileSync(file), repairTrueSourceClassification, repairTrueSourceDescription, repairTrueSourceIdentity, resolveRepoPath, rewriteCanonicalSourceReferences, rewriteContactReferences, rewriteTrueSourceReferenceDescriptions, runDatasetCommitHandoffPlan, runDatasetCurationCleanup, runDatasetCurationGate, runDatasetMutationManifest, runFinalizeAutoCurationQueue, runFinalizeIdentityPreflightStage, runTidasRowsValidation, runTiangongJsonStage, skippedPrewriteStage, sourceReferenceSemanticBlockers, sourceReferenceRewritesFileForRowsFile, sourceSemanticSummary, unique, writeFinalizeImportLedger, writeJson, writeJsonLines, }) {
91
94
  function stageStatus(value) {
92
95
  if (!value || typeof value !== "object")
93
96
  return "completed";
@@ -781,8 +784,32 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
781
784
  source: "canonical_support_rewrites",
782
785
  severity: blocker.severity || "error",
783
786
  }));
787
+ const validationReferences = referenceInputs.qaFiles.map((file) => {
788
+ const content = readReferenceBytes(file);
789
+ // The reader uses this path only to select JSON/JSONL; parsing and hashing
790
+ // must share the captured bytes rather than reopen a mutable selection.
791
+ const rows = readRows(file.toLowerCase(), () => content.toString("utf8"));
792
+ if (!fs.readFileSync(file).equals(content))
793
+ throw new Error("Selected Process validation reference bytes changed during capture.");
794
+ return {
795
+ rows,
796
+ fact: {
797
+ path: repoRelativePath(file),
798
+ bytes: content.length,
799
+ sha256: createHash("sha256").update(content).digest("hex"),
800
+ },
801
+ };
802
+ });
784
803
  const cleanup = timeStage("curation_cleanup", () => runDatasetCurationCleanup({
785
804
  repoRoot,
805
+ ...(validationReferences.length
806
+ ? {
807
+ processValidationReferences: {
808
+ rows: validationReferences.flatMap((reference) => reference.rows),
809
+ files: validationReferences.map((reference) => reference.fact),
810
+ },
811
+ }
812
+ : {}),
786
813
  options: {
787
814
  ...options,
788
815
  type: datasetType,
@@ -0,0 +1,6 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ /** Retain producer locator meaning; this proof permits no execution of the old package or old stages. */
4
+ export declare function verifyRegisteredAssessmentProducer(context: FoundryRuntimeContext, entry: ArtifactEntry, value: Record<string, unknown>, entries: readonly ArtifactEntry[]): string;
5
+ /** A retained set keeps the locator base of the operation that actually produced its manifest. */
6
+ export declare function registeredAssessmentSetProducerBase(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], set: Record<string, unknown>): string;
@@ -0,0 +1,167 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { FoundryContextError, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
+ import { readTaskBytes } from "./foundry-task-io.js";
6
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ import { readFoundryTaskRuntimeAdoptionChain } from "./foundry-task-runtime-adoption.js";
8
+ function hash(bytes) {
9
+ return createHash("sha256").update(bytes).digest("hex");
10
+ }
11
+ function object(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ function fail() {
15
+ throw new FoundryContextError("workflow_assessment_invalid", "The retained assessment producer is not proven by this task's original receipt and runtime identity.");
16
+ }
17
+ /** Retain producer locator meaning; this proof permits no execution of the old package or old stages. */
18
+ export function verifyRegisteredAssessmentProducer(context, entry, value, entries) {
19
+ const assessedBytes = readTaskBytes(context, entry.path);
20
+ if (assessedBytes.length !== entry.bytes ||
21
+ hash(assessedBytes) !== entry.sha256 ||
22
+ sha256Json(JSON.parse(assessedBytes.toString("utf8"))) !== sha256Json(value))
23
+ fail();
24
+ if (typeof value.owner_base !== "string" || !path.isAbsolute(value.owner_base))
25
+ fail();
26
+ const base = path.resolve(value.owner_base);
27
+ if (base === context.assetRoot)
28
+ return base;
29
+ try {
30
+ if (fs.realpathSync(base) !== base || !fs.statSync(base).isDirectory())
31
+ fail();
32
+ const jobBytes = readTaskBytes(context, "foundry-job.json"), job = JSON.parse(jobBytes.toString("utf8"));
33
+ const receiptBytes = readTaskBytes(context, entry.receipt.path), receipt = JSON.parse(receiptBytes.toString("utf8"));
34
+ if (hash(receiptBytes) !== entry.receipt.sha256 ||
35
+ !object(job) ||
36
+ !object(job.runtime_identity) ||
37
+ job.task_id !== context.taskId ||
38
+ job.actor_id !== context.actorId ||
39
+ !object(receipt) ||
40
+ receipt.status !== "completed" ||
41
+ receipt.mode !== "deterministic-local" ||
42
+ receipt.job_sha256 !== hash(jobBytes) ||
43
+ !object(receipt.plan) ||
44
+ typeof receipt.plan.path !== "string" ||
45
+ !Array.isArray(receipt.outputs))
46
+ fail();
47
+ const planBytes = readTaskBytes(context, receipt.plan.path), plan = JSON.parse(planBytes.toString("utf8"));
48
+ if (hash(planBytes) !== receipt.plan.sha256 ||
49
+ !object(plan) ||
50
+ plan.command !== "dataset-workflow-assessment" ||
51
+ plan.operation_id !== entry.operation_id ||
52
+ plan.job_sha256 !== hash(jobBytes) ||
53
+ plan.input_scope_sha256 !== entry.input_scope_sha256 ||
54
+ !receipt.outputs.some((item) => object(item) &&
55
+ item.path === entry.path &&
56
+ item.bytes === entry.bytes &&
57
+ item.sha256 === entry.sha256))
58
+ fail();
59
+ const packageFile = path.join(base, "package.json"), packageBytes = fs.readFileSync(packageFile), pkg = JSON.parse(packageBytes.toString("utf8"));
60
+ const chain = readFoundryTaskRuntimeAdoptionChain(context);
61
+ const expectedRuntime = chain?.runtimes.find((runtime) => runtime.root === base)?.identity ?? job.runtime_identity;
62
+ if (!object(pkg) ||
63
+ !object(pkg.foundryRuntime) ||
64
+ pkg.name !== "@tiangong-lca/foundry" ||
65
+ pkg.name !== expectedRuntime.package_name ||
66
+ pkg.version !== expectedRuntime.package_version ||
67
+ hash(packageBytes) !== expectedRuntime.manifest_sha256 ||
68
+ pkg.foundryRuntime.asset_root !== ".")
69
+ fail();
70
+ const declared = [
71
+ pkg.foundryRuntime.package_entry,
72
+ pkg.foundryRuntime.emitted_entry,
73
+ pkg.foundryRuntime.source_entry,
74
+ ];
75
+ const runtimeIdentity = expectedRuntime;
76
+ if (!declared.some((candidate) => {
77
+ if (typeof candidate !== "string")
78
+ return false;
79
+ const file = path.resolve(base, candidate);
80
+ if (!file.startsWith(`${base}${path.sep}`) ||
81
+ !fs.existsSync(file) ||
82
+ fs.realpathSync(file) !== file ||
83
+ !fs.statSync(file).isFile())
84
+ return false;
85
+ return hash(fs.readFileSync(file)) === runtimeIdentity.entry_sha256;
86
+ }))
87
+ fail();
88
+ const descriptorPath = path.join(base, "package-dist/assets/foundry-package-descriptor.json");
89
+ if (fs.existsSync(descriptorPath) && !chain) {
90
+ const currentDescriptorPath = path.join(context.runtimeRoot, "package-dist/assets/foundry-package-descriptor.json");
91
+ const descriptorBytes = fs.readFileSync(descriptorPath);
92
+ if (!fs.existsSync(currentDescriptorPath) ||
93
+ hash(descriptorBytes) !== hash(fs.readFileSync(currentDescriptorPath)))
94
+ fail();
95
+ const descriptor = JSON.parse(descriptorBytes.toString("utf8"));
96
+ if (!object(descriptor) ||
97
+ !Array.isArray(descriptor.files) ||
98
+ descriptor.files.length > 5000 ||
99
+ descriptor.files_sha256 !== sha256Json(descriptor.files))
100
+ fail();
101
+ for (const item of descriptor.files) {
102
+ if (!object(item) ||
103
+ typeof item.path !== "string" ||
104
+ typeof item.sha256 !== "string" ||
105
+ !Number.isSafeInteger(item.bytes))
106
+ fail();
107
+ const file = path.resolve(base, item.path);
108
+ if (path.isAbsolute(item.path) ||
109
+ !file.startsWith(base + path.sep) ||
110
+ fs.realpathSync(file) !== file)
111
+ fail();
112
+ const content = fs.readFileSync(file);
113
+ if (content.length !== item.bytes || hash(content) !== item.sha256)
114
+ fail();
115
+ }
116
+ }
117
+ // Original relative authoring locators must still name exact registered files in this task.
118
+ if (!Array.isArray(value.sets))
119
+ fail();
120
+ for (const raw of value.sets) {
121
+ if (!object(raw) || typeof raw.authoring_manifest !== "string")
122
+ fail();
123
+ const file = resolveFoundryOutput(context, raw.authoring_manifest);
124
+ const verify = (selected) => {
125
+ const registered = entries.find((item) => resolveFoundryOutput(context, item.path) === selected);
126
+ if (!registered)
127
+ fail();
128
+ const bytes = readTaskBytes(context, path.relative(context.taskRoot, selected));
129
+ if (bytes.length !== registered.bytes || hash(bytes) !== registered.sha256)
130
+ fail();
131
+ return bytes;
132
+ };
133
+ const manifest = JSON.parse(verify(file).toString("utf8"));
134
+ if (!object(manifest) || !Array.isArray(manifest.tasks))
135
+ fail();
136
+ for (const task of manifest.tasks) {
137
+ if (!object(task) || !object(task.files) || typeof task.files.task_json !== "string")
138
+ fail();
139
+ const resolved = resolveFoundryOutput(context, path.resolve(base, task.files.task_json));
140
+ verify(resolved);
141
+ }
142
+ }
143
+ return base;
144
+ }
145
+ catch {
146
+ return fail();
147
+ }
148
+ }
149
+ /** A retained set keeps the locator base of the operation that actually produced its manifest. */
150
+ export function registeredAssessmentSetProducerBase(context, entries, set) {
151
+ const manifestEntry = entries.find((item) => resolveFoundryOutput(context, item.path) === set.authoring_manifest);
152
+ const producerEntry = manifestEntry &&
153
+ entries.find((item) => item.operation_id === manifestEntry.operation_id &&
154
+ item.command === "dataset-workflow-assessment" &&
155
+ path.basename(item.path) === "foundry-assessment.json");
156
+ if (!producerEntry)
157
+ fail();
158
+ const bytes = readTaskBytes(context, producerEntry.path);
159
+ if (bytes.length !== producerEntry.bytes || hash(bytes) !== producerEntry.sha256)
160
+ fail();
161
+ const producer = JSON.parse(bytes.toString("utf8"));
162
+ if (!object(producer) ||
163
+ !Array.isArray(producer.sets) ||
164
+ !producer.sets.some((item) => object(item) && sha256Json(item) === sha256Json(set)))
165
+ fail();
166
+ return verifyRegisteredAssessmentProducer(context, producerEntry, producer, entries);
167
+ }
@@ -330,8 +330,12 @@ export const commandMetadata = {
330
330
  "profile",
331
331
  "context files",
332
332
  "queue artifacts",
333
+ "optional task-indexed exact-object preparation quality review",
334
+ ],
335
+ outputs: [
336
+ "dataset-curation-gate-report.json (raw QA plus separately reviewed findings)",
337
+ "ai-authoring-packages/*",
333
338
  ],
334
- outputs: ["dataset-curation-gate-report.json", "ai-authoring-packages/*"],
335
339
  keyTests: [
336
340
  goldenDiff,
337
341
  nodeTest("test/scenarios/identity-curation-context.test.mts", "curation gate authoring package carries full contract text and queue dependency rows"),
@@ -921,6 +925,7 @@ export const commandMetadata = {
921
925
  "schema/context files",
922
926
  "decision/patch evidence",
923
927
  "optional explicit Process QA reference rows and verified reference intent",
928
+ "optional task-indexed preparation quality review, rechecked against final rows and QA",
924
929
  ],
925
930
  outputs: [
926
931
  "post-authoring-finalize report (always)",
@@ -2,7 +2,7 @@ import { createClassificationDecisionCommands } from "./decision-owners/classifi
2
2
  import { createLocationDecisionCommands } from "./decision-owners/location.ts";
3
3
  import { createIdentityDecisionTaskCommands } from "./decision-owners/identity-task.ts";
4
4
  import { createIdentityDecisionCommands } from "./decision-owners/identity.ts";
5
- import type { FoundryRuntimeContext } from "./foundry-runtime-context.ts";
5
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
6
6
  import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
7
7
  interface FoundryDecisionOwners {
8
8
  classification: ReturnType<typeof createClassificationDecisionCommands>;
@@ -13,6 +13,7 @@ import { createLocationDecisionCommands } from "./decision-owners/location.js";
13
13
  import { createIdentityDecisionTaskCommands } from "./decision-owners/identity-task.js";
14
14
  import { createIdentityDecisionCommands } from "./decision-owners/identity.js";
15
15
  import { runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
16
+ import { FoundryContextError } from "./foundry-runtime-context.js";
16
17
  /** Reuse the existing owners without loading the developer dispatcher or ambient CLI overrides. */
17
18
  export function createFoundryDecisionOwners(context, qualified, temporary) {
18
19
  const runtime = createFoundryRuntimeUtils({ parseScalar, repoRoot: context.assetRoot });
@@ -35,13 +36,20 @@ export function createFoundryDecisionOwners(context, qualified, temporary) {
35
36
  profileFor,
36
37
  runTiangongJsonStage(stage, argv) {
37
38
  const result = runWorkflowLocalCliResult(context, qualified, temporary, argv);
38
- return {
39
- stage,
40
- exit_code: result.exit,
41
- report: result.report,
42
- stderr: "",
43
- status: result.report.status,
44
- };
39
+ return result.validate(() => {
40
+ const ownerStage = {
41
+ stage,
42
+ exit_code: result.exit,
43
+ report: result.report,
44
+ stderr: "",
45
+ status: String(result.report.status),
46
+ };
47
+ const reportFile = runtime.reportFileFromCliStage(ownerStage, ["files.report"], null);
48
+ if (!reportFile)
49
+ throw new FoundryContextError("workflow_report_invalid", "The local decision owner returned no existing report artifact.");
50
+ result.verifyReportFile(reportFile);
51
+ return ownerStage;
52
+ });
45
53
  },
46
54
  };
47
55
  const classification = createClassificationDecisionCommands(dependencies);
@@ -10,7 +10,8 @@ import { assertVerifiedFoundryIdentity, } from "./foundry-runtime-identity.js";
10
10
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
11
11
  import { foundryRuntimeCommandPolicy } from "./foundry-runtime-command-policy.js";
12
12
  import { loadFoundryTaskAuthorization } from "./foundry-task-authorization.js";
13
- import { assertFoundryTaskInputLineage } from "./foundry-task-store.js";
13
+ import { assertFoundryTaskInputLineage, readVerifiedTaskSnapshot } from "./foundry-task-store.js";
14
+ import { assertFoundryQualityReviewForExecution } from "./foundry-quality-review.js";
14
15
  import { taskAuthorizationAllows, taskAuthorizationWaivesQa, } from "./task-authorization.js";
15
16
  import { bytes, digest } from "./foundry-task-io.js";
16
17
  import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
@@ -188,6 +189,7 @@ async function verifyAdmission(context, qualification, identity, capsule, specVa
188
189
  fail("execution_command_unadmitted", "Selected command is not a qualified task stage.");
189
190
  const approved = selected(context, capsule.approved_input.path);
190
191
  const finalRows = selected(context, capsule.final_rows.path);
192
+ assertFoundryQualityReviewForExecution(context, qualification, readVerifiedTaskSnapshot(context).index, finalRows.path);
191
193
  assertFoundryMigrationNoReplay(context, finalRows.path);
192
194
  if (!sameFact(approved, capsule.approved_input) || !sameFact(finalRows, capsule.final_rows))
193
195
  fail("execution_input_changed", "Capsule input facts differ from current host selection.");
@@ -219,6 +221,7 @@ export async function createFoundryExecutionCapsule(context, qualification, iden
219
221
  assertVerifiedFoundryIdentity(context, identity, qualification);
220
222
  const approved = selected(context, options.approvedInputFile);
221
223
  const finalRows = selected(context, options.finalRowsFile);
224
+ assertFoundryQualityReviewForExecution(context, qualification, readVerifiedTaskSnapshot(context).index, finalRows.path);
222
225
  assertFoundryMigrationNoReplay(context, finalRows.path);
223
226
  const authorization = await loadFoundryTaskAuthorization(context, identity, finalRows.path, qualification);
224
227
  const spec = parseFoundryCommandSpec(options.commandSpec);
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { bindWorkflowChildExecution, workflowChildFailure, } from "./foundry-workflow-child-failure.js";
2
3
  import { parseScalar } from "./foundry-args.js";
3
4
  import { createFoundryRuntimeUtils, resolveTiangongLcaCliRuntimeCommand, } from "./foundry-runtime-utils.js";
4
5
  import { createTidasRowUtils } from "./tidas-row-utils.js";
@@ -26,9 +27,9 @@ import { runTidasRowsValidation } from "./tidas-adapter.js";
26
27
  import { ensureArray } from "./import-curation/internal/runtime-io.js";
27
28
  import { datasetIdentity, unwrapDatasetPayload, } from "./import-curation/internal/dataset-payload.js";
28
29
  import { workflowObject } from "./foundry-workflow-state.js";
29
- import { runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
30
+ import { assertWorkflowReportArtifact, runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
30
31
  import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
31
- import { FoundryContextError } from "./foundry-runtime-context.js";
32
+ import { FoundryContextError, readFoundryInput, } from "./foundry-runtime-context.js";
32
33
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
33
34
  function bind(factory, dependencies) {
34
35
  return factory(dependencies);
@@ -107,6 +108,7 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
107
108
  writeCloseoutImportLedger: undefined,
108
109
  readRowsFile: (file) => runtime.readRowsFile(file).map((row) => unwrapDatasetPayload(row, "")),
109
110
  });
111
+ const readOnlyReports = new WeakMap();
110
112
  const runTiangongJsonStage = (stage, argv) => {
111
113
  assertQualifiedFoundryRuntime(context, qualified);
112
114
  const name = argv.slice(0, 2).join(" ");
@@ -121,18 +123,26 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
121
123
  throw new FoundryContextError("finalize_write_forbidden", "Finalization cannot dispatch a remote mutation.");
122
124
  if (!dryRun && !remoteRead) {
123
125
  const result = runWorkflowLocalCliResult(context, qualified, temporary, argv);
124
- return {
125
- stage,
126
- exit_code: result.exit,
127
- report: result.report,
128
- status: result.report.status,
129
- command: cli.command,
130
- args: [...cli.args, ...argv],
131
- stderr: "",
132
- };
126
+ return result.validate(() => {
127
+ const ownerStage = {
128
+ stage,
129
+ exit_code: result.exit,
130
+ report: result.report,
131
+ status: String(result.report.status),
132
+ command: cli.command,
133
+ args: [...cli.args, ...argv],
134
+ stderr: "",
135
+ };
136
+ const reportFile = runtime.reportFileFromCliStage(ownerStage, ["files.report"], null);
137
+ if (!reportFile)
138
+ throw new FoundryContextError("workflow_report_invalid", "The local finalization owner returned no existing report artifact.");
139
+ result.verifyReportFile(reportFile);
140
+ return ownerStage;
141
+ });
133
142
  }
134
143
  if (!context.accountIntent)
135
144
  throw new FoundryContextError("needs_auth", "Remote finalization checks require explicit task account intent.");
145
+ const childExecution = bindWorkflowChildExecution(context, qualified, cli.bin_path, argv, temporary, cli.command);
136
146
  const result = spawnSync(cli.command, [...cli.args, ...argv], {
137
147
  cwd: temporary,
138
148
  env: execution.environment,
@@ -142,16 +152,31 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
142
152
  timeout: 120_000,
143
153
  maxBuffer: 16 * 1024 * 1024,
144
154
  });
145
- if (result.error || result.signal)
146
- throw new FoundryContextError("finalize_cli_failed", "The qualified read-only finalization stage did not finish.");
147
- let report;
155
+ const kind = result.error
156
+ ? "spawn_error"
157
+ : result.signal
158
+ ? "signal"
159
+ : ![0, 1, 2].includes(result.status ?? -1)
160
+ ? "exit_code"
161
+ : !result.stdout.trim()
162
+ ? "empty_stdout"
163
+ : null;
164
+ if (kind)
165
+ throw workflowChildFailure(childExecution, result, kind);
166
+ let parsed;
148
167
  try {
149
- report = workflowObject(JSON.parse(result.stdout));
168
+ parsed = JSON.parse(result.stdout);
150
169
  }
151
170
  catch {
152
- throw new FoundryContextError("finalize_cli_failed", "The qualified finalization stage returned no complete JSON report.");
171
+ throw workflowChildFailure(childExecution, result, "malformed_json");
153
172
  }
154
- return {
173
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
174
+ throw workflowChildFailure(childExecution, result, "invalid_report");
175
+ const report = workflowObject(parsed);
176
+ // Domain blocked/readback findings remain with the existing read-only owner contract.
177
+ if ("error" in report || typeof report.status !== "string" || !report.status.trim())
178
+ throw workflowChildFailure(childExecution, result, "stage_rejected", new FoundryContextError("finalize_cli_failed", "The qualified read-only owner returned an error or no stage status."));
179
+ const ownerStage = {
155
180
  stage,
156
181
  exit_code: result.status ?? 1,
157
182
  report,
@@ -160,6 +185,11 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
160
185
  args: [...cli.args, ...argv],
161
186
  stderr: result.stderr,
162
187
  };
188
+ readOnlyReports.set(ownerStage, {
189
+ outputDirectory: argv[argv.indexOf("--out-dir") + 1],
190
+ failure: (rejection) => workflowChildFailure(childExecution, result, "stage_rejected", rejection),
191
+ });
192
+ return ownerStage;
163
193
  };
164
194
  const finalize = bind(createPostAuthoringFinalizeCommands, {
165
195
  ...base,
@@ -171,6 +201,7 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
171
201
  ...finalizeUtils,
172
202
  ...handoff,
173
203
  profileFor,
204
+ readReferenceBytes: (file) => readFoundryInput(context, file),
174
205
  runDatasetCurationCleanup,
175
206
  runDatasetMutationManifest,
176
207
  runDatasetCurationGate: (request) => runDatasetCurationGate({
@@ -183,6 +214,22 @@ export function createFoundryFinalizeOwners(context, qualified, temporary, execu
183
214
  environment: localEnvironment,
184
215
  }),
185
216
  runTiangongJsonStage,
217
+ reportFileFromCliStage(stage, selectors, fallbackPath) {
218
+ const proof = readOnlyReports.get(stage);
219
+ if (!proof)
220
+ return runtime.reportFileFromCliStage(stage, selectors, fallbackPath);
221
+ try {
222
+ // Preserve the owner selectors and fallback rules. Some read-only commands return
223
+ // a summary rather than the same full report, so do not invent stdout/file equality.
224
+ const file = runtime.reportFileFromCliStage(stage, selectors, fallbackPath);
225
+ if (!file)
226
+ throw new FoundryContextError("finalize_report_invalid", "The read-only owner returned no existing selected or fallback report artifact.");
227
+ return assertWorkflowReportArtifact(context, file, proof.outputDirectory);
228
+ }
229
+ catch (error) {
230
+ throw proof.failure(error);
231
+ }
232
+ },
186
233
  writeFinalizeImportLedger: undefined,
187
234
  });
188
235
  return {
@@ -0,0 +1,24 @@
1
+ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ export declare const FOUNDRY_IDENTITY_STAGE_INPUT_SCHEMA: "tiangong-foundry.identity-stage-input.v1";
3
+ export interface FoundryIdentityStageTarget {
4
+ readonly dataset_type: "flow" | "process";
5
+ readonly dataset_id: string;
6
+ readonly dataset_version: string;
7
+ readonly source_row_sha256: string;
8
+ }
9
+ export interface FoundryIdentityStageInput {
10
+ readonly schema: typeof FOUNDRY_IDENTITY_STAGE_INPUT_SCHEMA;
11
+ readonly intent_id: string;
12
+ readonly task_id: string;
13
+ readonly actor_id: string;
14
+ readonly rows_report_sha256: string;
15
+ readonly predecessor_identity_sha256: string;
16
+ readonly targets: readonly FoundryIdentityStageTarget[];
17
+ }
18
+ export interface SelectedFoundryIdentityStageInput {
19
+ readonly descriptor: FoundryInputFact;
20
+ readonly value: FoundryIdentityStageInput;
21
+ }
22
+ export declare function parseFoundryIdentityStageInput(value: unknown): FoundryIdentityStageInput;
23
+ export declare function selectFoundryIdentityStageInput(context: FoundryRuntimeContext, file: string): SelectedFoundryIdentityStageInput;
24
+ export declare function assertSelectedFoundryIdentityStageInput(context: FoundryRuntimeContext, selected: SelectedFoundryIdentityStageInput): void;
@@ -0,0 +1,122 @@
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
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ export const FOUNDRY_IDENTITY_STAGE_INPUT_SCHEMA = "tiangong-foundry.identity-stage-input.v1";
8
+ const selectedInputs = new WeakMap();
9
+ const sha = /^[0-9a-f]{64}$/u;
10
+ const token = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u;
11
+ function invalid(message) {
12
+ throw new FoundryContextError("identity_stage_input_invalid", message);
13
+ }
14
+ function record(value) {
15
+ if (!value || typeof value !== "object" || Array.isArray(value))
16
+ invalid("Explicit identity stage input must be an object.");
17
+ return value;
18
+ }
19
+ function exact(value, keys) {
20
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
21
+ invalid("Explicit identity stage has missing or unsupported fields.");
22
+ }
23
+ export function parseFoundryIdentityStageInput(value) {
24
+ const data = record(value);
25
+ exact(data, [
26
+ "schema",
27
+ "intent_id",
28
+ "task_id",
29
+ "actor_id",
30
+ "rows_report_sha256",
31
+ "predecessor_identity_sha256",
32
+ "targets",
33
+ ]);
34
+ if (data.schema !== FOUNDRY_IDENTITY_STAGE_INPUT_SCHEMA ||
35
+ typeof data.intent_id !== "string" ||
36
+ !token.test(data.intent_id) ||
37
+ typeof data.task_id !== "string" ||
38
+ !/^task-[0-9a-f]{64}-r[0-9]{4}$/u.test(data.task_id) ||
39
+ typeof data.actor_id !== "string" ||
40
+ !token.test(data.actor_id) ||
41
+ typeof data.rows_report_sha256 !== "string" ||
42
+ !sha.test(data.rows_report_sha256) ||
43
+ typeof data.predecessor_identity_sha256 !== "string" ||
44
+ !sha.test(data.predecessor_identity_sha256) ||
45
+ !Array.isArray(data.targets) ||
46
+ !data.targets.length ||
47
+ data.targets.length > 64)
48
+ invalid("Explicit identity stage needs one stable intent, original task/actor and bounded exact roster.");
49
+ const targets = data.targets.map((raw) => {
50
+ const item = record(raw);
51
+ exact(item, ["dataset_type", "dataset_id", "dataset_version", "source_row_sha256"]);
52
+ if ((item.dataset_type !== "flow" && item.dataset_type !== "process") ||
53
+ typeof item.dataset_id !== "string" ||
54
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(item.dataset_id) ||
55
+ typeof item.dataset_version !== "string" ||
56
+ !/^[0-9]{2}\.[0-9]{2}\.[0-9]{3}$/u.test(item.dataset_version) ||
57
+ typeof item.source_row_sha256 !== "string" ||
58
+ !sha.test(item.source_row_sha256))
59
+ invalid("Readonly identity targets must select exact Flow/Process identities and unchanged registered row hashes.");
60
+ return Object.freeze({
61
+ dataset_type: item.dataset_type,
62
+ dataset_id: item.dataset_id,
63
+ dataset_version: item.dataset_version,
64
+ source_row_sha256: item.source_row_sha256,
65
+ });
66
+ });
67
+ if (new Set(targets.map((item) => `${item.dataset_type}:${item.dataset_id}:${item.dataset_version}`)).size !== targets.length)
68
+ invalid("Explicit identity stage target roster contains duplicates.");
69
+ return Object.freeze({
70
+ schema: FOUNDRY_IDENTITY_STAGE_INPUT_SCHEMA,
71
+ intent_id: data.intent_id,
72
+ task_id: data.task_id,
73
+ actor_id: data.actor_id,
74
+ rows_report_sha256: data.rows_report_sha256,
75
+ predecessor_identity_sha256: data.predecessor_identity_sha256,
76
+ targets: Object.freeze(targets),
77
+ });
78
+ }
79
+ function contextBinding(context) {
80
+ return sha256Json({
81
+ workspace: context.workspaceId,
82
+ task: context.taskId,
83
+ actor: context.actorId,
84
+ project: context.accountIntent?.projectRef ?? null,
85
+ user: context.accountIntent?.userId ?? null,
86
+ });
87
+ }
88
+ export function selectFoundryIdentityStageInput(context, file) {
89
+ if (!file || file.length > 4096 || /[\0\r\n]/u.test(file))
90
+ invalid("Explicit identity input path is invalid.");
91
+ const target = path.resolve(context.workspaceRoot, file);
92
+ if (migrationCredentialPath(path.relative(context.workspaceRoot, target)))
93
+ invalid("Credential paths cannot select an identity stage.");
94
+ assertNotFoundrySessionFile(target, context.accountIntent?.sessionReference);
95
+ let stat;
96
+ try {
97
+ stat = fs.lstatSync(target);
98
+ }
99
+ catch {
100
+ invalid("Explicit identity input must select an existing regular file.");
101
+ }
102
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
103
+ invalid("Explicit identity input must be a bounded regular file.");
104
+ const descriptor = Object.freeze(captureFoundryInput(target));
105
+ let value;
106
+ try {
107
+ value = parseFoundryIdentityStageInput(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(readSelectedSemanticBytes(descriptor))));
108
+ }
109
+ catch {
110
+ invalid("Select a complete supported explicit identity-stage input.");
111
+ }
112
+ if (value.task_id !== context.taskId || value.actor_id !== context.actorId)
113
+ invalid("Explicit identity input belongs to another task or actor.");
114
+ const selected = Object.freeze({ descriptor, value });
115
+ selectedInputs.set(selected, contextBinding(context));
116
+ return selected;
117
+ }
118
+ export function assertSelectedFoundryIdentityStageInput(context, selected) {
119
+ if (!selectedInputs.has(selected) || selectedInputs.get(selected) !== contextBinding(context))
120
+ invalid("Explicit identity intent requires the independently selected current task/account context.");
121
+ readSelectedSemanticBytes(selected.descriptor);
122
+ }