@tiangong-lca/foundry 0.1.6 → 0.1.8

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 (64) hide show
  1. package/README.md +7 -5
  2. package/docs/architecture.md +7 -5
  3. package/docs/foundry-task-contracts.md +4 -4
  4. package/docs/import-profiles/worldsteel/constraints.md +3 -3
  5. package/docs/import-profiles/worldsteel/import-coverage.md +3 -3
  6. package/docs/import-profiles/worldsteel/import-plan.md +1 -1
  7. package/docs/import-profiles/worldsteel/profile.md +3 -3
  8. package/docs/package-distribution-contract.md +11 -7
  9. package/docs/public-runtime-contract.md +23 -7
  10. package/docs/runtime-context-contract.md +11 -5
  11. package/docs/task-authorization-contract.md +8 -4
  12. package/package-dist/assets/foundry-package-descriptor.json +166 -90
  13. package/package-dist/scripts/foundry-facade.d.ts +1 -0
  14. package/package-dist/scripts/foundry-facade.js +35 -4
  15. package/package-dist/scripts/lib/finalize-owners/commit-handoff.js +65 -10
  16. package/package-dist/scripts/lib/finalize-owners/finalize-reference-inputs.d.ts +12 -0
  17. package/package-dist/scripts/lib/finalize-owners/finalize-reference-inputs.js +57 -0
  18. package/package-dist/scripts/lib/finalize-owners/handoff-reference-intent.d.ts +28 -0
  19. package/package-dist/scripts/lib/finalize-owners/handoff-reference-intent.js +115 -0
  20. package/package-dist/scripts/lib/finalize-owners/native-insert-closeout.d.ts +13 -0
  21. package/package-dist/scripts/lib/finalize-owners/native-insert-closeout.js +99 -0
  22. package/package-dist/scripts/lib/finalize-owners/native-insert-handoff.d.ts +47 -0
  23. package/package-dist/scripts/lib/finalize-owners/native-insert-handoff.js +146 -0
  24. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +13 -0
  25. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.d.ts +8 -2
  26. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.js +48 -2
  27. package/package-dist/scripts/lib/finalize-owners/reference-intent-closeout.d.ts +12 -0
  28. package/package-dist/scripts/lib/finalize-owners/reference-intent-closeout.js +77 -0
  29. package/package-dist/scripts/lib/foundry-authorization-input.d.ts +8 -0
  30. package/package-dist/scripts/lib/foundry-authorization-input.js +68 -1
  31. package/package-dist/scripts/lib/foundry-command-metadata.js +15 -1
  32. package/package-dist/scripts/lib/foundry-execution-admission.js +82 -5
  33. package/package-dist/scripts/lib/foundry-managed-actions.d.ts +4 -0
  34. package/package-dist/scripts/lib/foundry-managed-actions.js +56 -0
  35. package/package-dist/scripts/lib/foundry-managed-host.d.ts +2 -2
  36. package/package-dist/scripts/lib/foundry-managed-host.js +2 -0
  37. package/package-dist/scripts/lib/foundry-owner-execution-store.js +25 -2
  38. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +2 -0
  39. package/package-dist/scripts/lib/foundry-owner-readback.js +65 -14
  40. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  41. package/package-dist/scripts/lib/foundry-package-contract.js +4 -2
  42. package/package-dist/scripts/lib/foundry-reference-input.d.ts +28 -0
  43. package/package-dist/scripts/lib/foundry-reference-input.js +235 -0
  44. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  45. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  46. package/package-dist/scripts/lib/foundry-task-store.d.ts +1 -1
  47. package/package-dist/scripts/lib/foundry-workflow-authorization.d.ts +2 -1
  48. package/package-dist/scripts/lib/foundry-workflow-authorization.js +38 -2
  49. package/package-dist/scripts/lib/foundry-workflow-execution.js +7 -1
  50. package/package-dist/scripts/lib/foundry-workflow-finalize.js +43 -1
  51. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +2 -0
  52. package/package-dist/scripts/lib/foundry-workflow-state.js +31 -2
  53. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  54. package/package-dist/scripts/public-api.d.ts +1 -0
  55. package/package-dist/scripts/runtime-entry.d.ts +5 -1
  56. package/package-dist/scripts/runtime-entry.js +4 -1
  57. package/package.json +3 -2
  58. package/specs/import-profiles.json +1 -1
  59. package/specs/prewrite-content-policy.json +1 -1
  60. package/specs/schemas/foundry-authorization-input.schema.json +38 -1
  61. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  62. package/specs/schemas/foundry-package-descriptor.schema.json +3 -2
  63. package/specs/schemas/foundry-reference-input.schema.json +137 -0
  64. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,235 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { captureFoundryInput, readFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
5
+ import { assertNotFoundrySessionFile, migrationCredentialPath } from "./foundry-private-path.js";
6
+ import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
7
+ import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
8
+ import { runFoundryTaskOperation } from "./foundry-task-store.js";
9
+ export const FOUNDRY_REFERENCE_INPUT_SCHEMA = "tiangong-foundry.reference-input.v1";
10
+ const selections = new WeakSet();
11
+ const sha = /^[a-f0-9]{64}$/u;
12
+ function invalid(message) {
13
+ throw new FoundryContextError("reference_input_invalid", message);
14
+ }
15
+ function exact(value, keys) {
16
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
17
+ invalid("Reference input has missing or unsupported fields.");
18
+ }
19
+ function file(value) {
20
+ const selected = workflowObject(value);
21
+ exact(selected, ["file", "sha256"]);
22
+ if (typeof selected.file !== "string" ||
23
+ !selected.file.trim() ||
24
+ selected.file.length > 4096 ||
25
+ /[\0\r\n]/u.test(selected.file) ||
26
+ typeof selected.sha256 !== "string" ||
27
+ !sha.test(selected.sha256))
28
+ invalid("Reference file selection is invalid.");
29
+ return Object.freeze({ file: selected.file, sha256: selected.sha256 });
30
+ }
31
+ export function parseFoundryReferenceInput(value) {
32
+ const data = workflowObject(value);
33
+ exact(data, [
34
+ "schema",
35
+ "task_id",
36
+ "actor_id",
37
+ "rows_manifest_sha256",
38
+ "dataset_type",
39
+ "qa_reference_rows",
40
+ "intent",
41
+ "review_files",
42
+ ]);
43
+ if (data.schema !== FOUNDRY_REFERENCE_INPUT_SCHEMA ||
44
+ typeof data.task_id !== "string" ||
45
+ !/^task-[0-9a-f]{64}-r[0-9]{4}$/u.test(data.task_id) ||
46
+ typeof data.actor_id !== "string" ||
47
+ !/^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u.test(data.actor_id) ||
48
+ typeof data.rows_manifest_sha256 !== "string" ||
49
+ !sha.test(data.rows_manifest_sha256) ||
50
+ typeof data.dataset_type !== "string" ||
51
+ ![
52
+ "process",
53
+ "flow",
54
+ "source",
55
+ "contact",
56
+ "lifecyclemodel",
57
+ "unitgroup",
58
+ "flowproperty",
59
+ ].includes(data.dataset_type) ||
60
+ !Array.isArray(data.qa_reference_rows) ||
61
+ !Array.isArray(data.review_files) ||
62
+ data.qa_reference_rows.length > 128 ||
63
+ data.review_files.length > 128)
64
+ invalid("Reference input scope or file lists are invalid.");
65
+ const qa = data.qa_reference_rows.map(file), reviews = data.review_files.map(file), intent = data.intent === null ? null : file(data.intent);
66
+ if ((!qa.length && !intent) ||
67
+ (qa.length && data.dataset_type !== "process") ||
68
+ Boolean(intent) !== Boolean(reviews.length))
69
+ invalid("Select Process QA references and/or one intent with its explicit reviews.");
70
+ return Object.freeze({
71
+ schema: FOUNDRY_REFERENCE_INPUT_SCHEMA,
72
+ task_id: data.task_id,
73
+ actor_id: data.actor_id,
74
+ rows_manifest_sha256: data.rows_manifest_sha256,
75
+ dataset_type: data.dataset_type,
76
+ qa_reference_rows: Object.freeze(qa),
77
+ intent,
78
+ review_files: Object.freeze(reviews),
79
+ });
80
+ }
81
+ export function selectFoundryReferenceInput(context, descriptorFile) {
82
+ let total = 0;
83
+ const capture = (name) => {
84
+ if (!name.trim() || name.length > 4096 || /[\0\r\n]/u.test(name))
85
+ invalid("Reference input path is invalid.");
86
+ const target = path.resolve(context.workspaceRoot, name);
87
+ if (migrationCredentialPath(path.relative(context.workspaceRoot, target)))
88
+ invalid("Credential paths cannot be reference inputs.");
89
+ assertNotFoundrySessionFile(target, context.accountIntent?.sessionReference);
90
+ const stat = fs.lstatSync(target);
91
+ if (!stat.isFile() || stat.size > 8 * 1024 * 1024)
92
+ invalid("Reference inputs must be bounded regular files.");
93
+ total += stat.size;
94
+ if (total > 64 * 1024 * 1024)
95
+ invalid("Reference input selection exceeds 64 MiB.");
96
+ return Object.freeze(captureFoundryInput(target));
97
+ };
98
+ const descriptor = capture(descriptorFile);
99
+ let spec;
100
+ try {
101
+ spec = parseFoundryReferenceInput(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(readSelectedSemanticBytes(descriptor))));
102
+ }
103
+ catch {
104
+ invalid("Select a complete supported reference-input descriptor.");
105
+ }
106
+ if (spec.task_id !== context.taskId || spec.actor_id !== context.actorId)
107
+ invalid("Reference selection belongs to another task or actor.");
108
+ const selected = (entry) => {
109
+ const fact = capture(entry.file);
110
+ if (fact.sha256 !== entry.sha256)
111
+ invalid("Reference input bytes differ from the selected digest.");
112
+ return fact;
113
+ };
114
+ const result = Object.freeze({
115
+ spec,
116
+ descriptor,
117
+ qa: Object.freeze(spec.qa_reference_rows.map(selected)),
118
+ intent: spec.intent ? selected(spec.intent) : null,
119
+ reviews: Object.freeze(spec.review_files.map(selected)),
120
+ });
121
+ if (new Set(result.qa.map((fact) => fact.path)).size !== result.qa.length ||
122
+ new Set(result.reviews.map((fact) => fact.path)).size !== result.reviews.length)
123
+ invalid("Select each reference file only once.");
124
+ selections.add(result);
125
+ return result;
126
+ }
127
+ function assertSelected(selected) {
128
+ if (!selections.has(selected))
129
+ invalid("Reference input must be selected by the current host.");
130
+ for (const fact of [
131
+ selected.descriptor,
132
+ ...selected.qa,
133
+ ...selected.reviews,
134
+ ...(selected.intent ? [selected.intent] : []),
135
+ ])
136
+ readSelectedSemanticBytes(fact);
137
+ }
138
+ export async function recordFoundryReferenceInput(context, entries, selected) {
139
+ assertSelected(selected);
140
+ const state = currentWorkflowState(context, entries), rows = state.rows;
141
+ if (!rows || rows.entry.sha256 !== selected.spec.rows_manifest_sha256)
142
+ invalid("Reference input requires the current row manifest.");
143
+ const set = rows.value.sets.find((item) => item.type === selected.spec.dataset_type);
144
+ if (!set)
145
+ invalid("Reference selection has no current dataset scope.");
146
+ const assertUnprepared = (index) => {
147
+ if (index.some((entry) => entry.command === "dataset-workflow-execution-prepare" &&
148
+ path.basename(entry.path) === "owner-execution-request.json" &&
149
+ workflowObject(readWorkflowArtifact(context, entry).value.policy).dataset_type ===
150
+ selected.spec.dataset_type))
151
+ invalid("A prepared or consumed owner scope cannot replace reference inputs.");
152
+ };
153
+ assertUnprepared(entries);
154
+ const previous = state.referenceInputs.get(set.type)?.entry.sha256 ?? null;
155
+ readFoundryInput(context, set.file);
156
+ const input = captureFoundryInput(set.file);
157
+ const existing = state.referenceInputs.get(set.type);
158
+ if (existing?.value.source_sha256 === selected.descriptor.sha256)
159
+ return existing.value;
160
+ let intentValue = null;
161
+ const reviewPointers = [];
162
+ if (selected.intent) {
163
+ try {
164
+ intentValue = workflowObject(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(readSelectedSemanticBytes(selected.intent))));
165
+ if (intentValue.schema_version !== "dataset-exact-reference-intent.v1" ||
166
+ !Array.isArray(intentValue.references) ||
167
+ !intentValue.references.length)
168
+ invalid("Reference intent does not expose the supported explicit review locators.");
169
+ for (const value of intentValue.references) {
170
+ const review = workflowObject(workflowObject(value).review);
171
+ if (typeof review.file !== "string")
172
+ invalid("Reference review locator is missing.");
173
+ const canonical = fs.realpathSync(path.resolve(path.dirname(selected.intent.path), review.file));
174
+ const fact = selected.reviews.find((item) => item.path === canonical && item.sha256 === review.sha256);
175
+ if (!fact)
176
+ invalid("Every intent review must match an independently selected file and digest.");
177
+ reviewPointers.push({ value: review, source: fact });
178
+ }
179
+ if (new Set(reviewPointers.map((item) => item.source.path)).size !== selected.reviews.length)
180
+ invalid("Reference selection contains unused review files.");
181
+ }
182
+ catch {
183
+ invalid("Reference intent and independently selected reviews do not match.");
184
+ }
185
+ }
186
+ const output = path.join(context.taskRoot, "outputs", "reference-input", randomUUID());
187
+ return runFoundryTaskOperation(context, {
188
+ command: "dataset-workflow-reference-input",
189
+ options: { descriptor: selected.descriptor, input, rows_manifest_sha256: rows.entry.sha256 },
190
+ validateCurrent(index) {
191
+ assertSelected(selected);
192
+ assertUnprepared(index);
193
+ if ((currentWorkflowState(context, index).referenceInputs.get(set.type)?.entry.sha256 ??
194
+ null) !== previous)
195
+ invalid("Reference selection changed concurrently.");
196
+ if (currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
197
+ invalid("Rows changed during reference selection.");
198
+ },
199
+ }, (operation) => {
200
+ const snapshot = (fact, name) => {
201
+ const target = path.join(output, name);
202
+ operation.writeText(target, readSelectedSemanticBytes(fact));
203
+ const captured = captureFoundryInput(target);
204
+ if (captured.sha256 !== fact.sha256 || captured.bytes !== fact.bytes)
205
+ invalid("Reference snapshot differs from selected bytes.");
206
+ return captured;
207
+ };
208
+ const qa = selected.qa.map((fact, index) => snapshot(fact, `qa-${index}${path.extname(fact.path).toLowerCase() === ".jsonl" ? ".jsonl" : ".json"}`));
209
+ const reviews = selected.reviews.map((fact, index) => snapshot(fact, `review-${index}.json`));
210
+ let intent = null;
211
+ if (selected.intent && intentValue) {
212
+ snapshot(selected.intent, "original-intent.json");
213
+ for (const pointer of reviewPointers)
214
+ pointer.value.file = reviews[selected.reviews.indexOf(pointer.source)].path;
215
+ const target = path.join(output, "intent.json");
216
+ operation.writeJson(target, intentValue);
217
+ intent = captureFoundryInput(target);
218
+ }
219
+ snapshot(selected.descriptor, "descriptor.json");
220
+ const result = {
221
+ schema: "tiangong-foundry.reference-selection.v1",
222
+ status: "selected",
223
+ dataset_type: set.type,
224
+ rows_manifest_sha256: rows.entry.sha256,
225
+ source_sha256: selected.descriptor.sha256,
226
+ input,
227
+ qa_files: qa,
228
+ intent,
229
+ review_files: reviews,
230
+ grants_permission: false,
231
+ };
232
+ operation.writeJson(path.join(output, "foundry-reference-input.json"), result);
233
+ return result;
234
+ });
235
+ }
@@ -157,8 +157,8 @@ export function qualifyFoundryRuntime(context, options) {
157
157
  catch {
158
158
  return fail("runtime_cli_unqualified", "CLI runtime bytes do not match the independently selected C1 expectation.");
159
159
  }
160
- if (cli.package.version !== "0.1.13" || cli.platform !== context.platform)
161
- fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.13 C1 runtime on the selected platform.");
160
+ if (cli.package.version !== "0.1.14" || cli.platform !== context.platform)
161
+ fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.14 C1 runtime on the selected platform.");
162
162
  const cliExpectation = Object.freeze({ ...options.cliExpectation });
163
163
  if (cliExpectation.schema !== CLI_RUNTIME_EXPECTATION_SCHEMA)
164
164
  fail("runtime_cli_unqualified", "CLI runtime expectation is not the supported schema.");
@@ -8,7 +8,7 @@ import { runtimeEnvFilePolicyDisabled, runtimeEnvFilePolicyKey, } from "./foundr
8
8
  import { resolveFoundryRuntimePaths } from "./foundry-runtime-paths.js";
9
9
  const require = createRequire(import.meta.url);
10
10
  const tiangongLcaCliPackageName = "@tiangong-lca/cli";
11
- const tiangongLcaCliPackageVersion = "0.1.13";
11
+ const tiangongLcaCliPackageVersion = "0.1.14";
12
12
  const tiangongLcaCliBinName = "tiangong-lca";
13
13
  const { repoRoot: foundryRepoRoot } = resolveFoundryRuntimePaths(import.meta.url);
14
14
  function isRecord(value) {
@@ -11,7 +11,7 @@ export declare function assertFoundryTaskInputLineage(context: FoundryRuntimeCon
11
11
  }>>;
12
12
  /** Short local preparation transaction. Remote mutation/batch execution must not use this replay path. */
13
13
  export declare function runFoundryTaskOperation(context: FoundryRuntimeContext, input: {
14
- command: "dataset-curation-cleanup" | "dataset-tidas-import" | "dataset-context-pack" | "dataset-workflow-rows" | "dataset-workflow-assessment" | "dataset-workflow-identity" | "dataset-workflow-finalize" | "dataset-workflow-authorization" | "dataset-workflow-execution-prepare" | "dataset-workflow-execution-result" | "dataset-workflow-execution-consume" | "dataset-workflow-execution-observation" | "dataset-workflow-reference-verify" | "dataset-semantic-apply";
14
+ command: "dataset-curation-cleanup" | "dataset-tidas-import" | "dataset-context-pack" | "dataset-workflow-rows" | "dataset-workflow-assessment" | "dataset-workflow-identity" | "dataset-workflow-finalize" | "dataset-workflow-authorization" | "dataset-workflow-native-contract" | "dataset-workflow-reference-input" | "dataset-workflow-execution-prepare" | "dataset-workflow-execution-result" | "dataset-workflow-execution-consume" | "dataset-workflow-execution-observation" | "dataset-workflow-reference-verify" | "dataset-semantic-apply";
15
15
  options: JsonRecord;
16
16
  task?: FoundryTaskOptions;
17
17
  validateCurrent?: (index: readonly ArtifactEntry[]) => void;
@@ -1,5 +1,5 @@
1
1
  import { type SelectedAuthorizationInput } from "./foundry-authorization-input.ts";
2
- import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type FoundryRuntimeContext, type FoundryInputFact } from "./foundry-runtime-context.ts";
3
3
  import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
4
4
  import { type FoundryAuthentication, type VerifiedFoundryIdentity } from "./foundry-runtime-identity.ts";
5
5
  import type { ValidatedTaskAuthorization } from "./task-authorization.ts";
@@ -17,6 +17,7 @@ export declare function recordFoundryWorkflowAuthorization(context: FoundryRunti
17
17
  pointer_sha256: string;
18
18
  };
19
19
  submissionSha256: string;
20
+ executionContract?: FoundryInputFact;
20
21
  operationOptions: Record<string, unknown>;
21
22
  validateCurrent: (index: readonly ArtifactEntry[]) => void;
22
23
  }): Promise<import("./foundry-task-types.ts").JsonRecord>;
@@ -7,7 +7,7 @@ import { FoundryContextError, readFoundryInput, captureFoundryInput, resolveFoun
7
7
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
8
8
  import { currentWorkflowState, workflowObject } from "./foundry-workflow-state.js";
9
9
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
10
- import { verifyFoundryRuntimeIdentity, } from "./foundry-runtime-identity.js";
10
+ import { verifyFoundryRuntimeIdentity, assertVerifiedFoundryIdentity, } from "./foundry-runtime-identity.js";
11
11
  import { registerFoundryTaskAuthorization, loadFoundryTaskAuthorization, } from "./foundry-task-authorization.js";
12
12
  import { createFoundryAuthenticationEnvironment } from "./foundry-authentication-environment.js";
13
13
  import { createFoundryFinalizeOwners } from "./foundry-finalize-owners.js";
@@ -15,6 +15,7 @@ import { createFoundryExecutionCapsule } from "./foundry-execution-admission.js"
15
15
  import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
16
16
  import { createFoundryCommandSpec, createFileArtifactFact } from "./foundry-command-spec.js";
17
17
  import { parseFoundryCommandSpec } from "@tiangong-lca/cli/command-spec";
18
+ import { readNativeInsertHandoff } from "./finalize-owners/native-insert-handoff.js";
18
19
  export async function authorizeFoundryWorkflow(context, qualified, entries, selected, authentication = { mode: "oauth" }) {
19
20
  assertSelectedAuthorizationInput(selected);
20
21
  assertQualifiedFoundryRuntime(context, qualified);
@@ -36,6 +37,22 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
36
37
  if (spec.input_kind === "final_rows" && scope.status !== "ready_for_remote_write")
37
38
  throw new FoundryContextError("authorization_scope_not_ready", "Final-row approval requires a ready owner scope.");
38
39
  const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
40
+ if (selected.executionContract) {
41
+ try {
42
+ readNativeInsertHandoff({
43
+ contractFile: selected.executionContract.path,
44
+ rowsFile: inputFile,
45
+ datasetType: spec.dataset_type,
46
+ targetUserId: context.accountIntent.userId,
47
+ verifiedProjectRef: context.accountIntent.projectRef,
48
+ stateCode: "0",
49
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
50
+ });
51
+ }
52
+ catch {
53
+ throw new FoundryContextError("authorization_execution_contract_invalid", "Native insert contract must bind the current final rows, owner, project and draft state before authorization.");
54
+ }
55
+ }
39
56
  const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
40
57
  const current = (index) => {
41
58
  assertSelectedAuthorizationInput(selected);
@@ -63,6 +80,7 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
63
80
  inputKind: spec.input_kind,
64
81
  registration,
65
82
  submissionSha256: selected.descriptor.sha256,
83
+ ...(selected.executionContract ? { executionContract: selected.executionContract } : {}),
66
84
  validateCurrent: current,
67
85
  operationOptions: {
68
86
  submission: selected.descriptor,
@@ -70,6 +88,7 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
70
88
  evidence: selected.evidence,
71
89
  finalization: spec.finalization_sha256,
72
90
  authorization: registration.authorization_sha256,
91
+ ...(selected.executionContract ? { execution_contract: selected.executionContract } : {}),
73
92
  },
74
93
  });
75
94
  }
@@ -101,6 +120,9 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
101
120
  taskAuthorization: authorization,
102
121
  taskAuthorizationBinding: authorization.binding,
103
122
  profile: authorization.binding.profile_id,
123
+ ...(request.executionContract
124
+ ? { executionContractFile: request.executionContract.path }
125
+ : {}),
104
126
  }));
105
127
  const commands = workflowObject(handoff.commands);
106
128
  for (const key of ["commit", "post_write_verify"]) {
@@ -113,6 +135,12 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
113
135
  binding: {
114
136
  artifacts: [
115
137
  createFileArtifactFact({ role: "final_rows", path: inputFile, filePath: inputFile }),
138
+ ...command.binding.artifacts
139
+ .filter((artifact) => artifact.role !== "final_rows")
140
+ .map((artifact) => ({
141
+ ...artifact,
142
+ path: path.resolve(context.assetRoot, artifact.path),
143
+ })),
116
144
  ],
117
145
  },
118
146
  });
@@ -126,7 +154,15 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
126
154
  ? action === `${request.datasetType}_write` ||
127
155
  action === "canonical_support_local_mint"
128
156
  : false);
129
- capsule = await createFoundryExecutionCapsule(context, qualified, identity, {
157
+ try {
158
+ assertVerifiedFoundryIdentity(context, identity, qualified);
159
+ }
160
+ catch (error) {
161
+ if (!(error instanceof FoundryContextError) || error.code !== "identity_receipt_stale")
162
+ throw error;
163
+ }
164
+ const sealingIdentity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
165
+ capsule = await createFoundryExecutionCapsule(context, qualified, sealingIdentity, {
130
166
  command: "dataset-commit-handoff-plan",
131
167
  approvedInputFile: request.approvedInputFile,
132
168
  finalRowsFile: inputFile,
@@ -4,7 +4,7 @@ import { spawnSync } from "node:child_process";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { runBoundedBatch, withBatchRunLock } from "@tiangong-lca/cli/batch";
6
6
  import { commandSpecOptionValue } from "@tiangong-lca/cli/command-spec";
7
- import { captureFoundryInput, FoundryContextError, resolveFoundryOutput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
7
+ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoundryOutput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
8
8
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
9
9
  import { verifyFoundryRuntimeIdentity, } from "./foundry-runtime-identity.js";
10
10
  import { rehydrateFoundryExecutionAdmission, assertFoundryExecutionAdmission, } from "./foundry-execution-admission.js";
@@ -51,6 +51,9 @@ export async function executeFoundryOwnerScope(context, qualified, entries, requ
51
51
  capsuleFile: request.content.capsule.path,
52
52
  commandSpec: request.content.commit,
53
53
  });
54
+ // Local rehydration can consume the receipt window; the final full pass
55
+ // must begin with a freshly verified current account, before any attempt.
56
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
54
57
  await assertFoundryExecutionAdmission(context, qualified, identity, admission);
55
58
  if (observation)
56
59
  throw new FoundryContextError("execution_observation_invalid", "Existing dispatch evidence cannot be treated as unattempted.");
@@ -154,6 +157,9 @@ export async function executeFoundryOwnerScope(context, qualified, entries, requ
154
157
  finalRowsFile: request.content.input.path,
155
158
  expectedRows: readRows(request.content.input.path).length,
156
159
  blockers: commitBlockers,
160
+ handoffPlan: JSON.parse(readFoundryInput(context, request.handoff_file).toString("utf8")),
161
+ targetUserId: request.policy.user_id,
162
+ expectedStateCode: 0,
157
163
  });
158
164
  }
159
165
  const disposition = result.error || result.signal || !report || !reportFile
@@ -19,6 +19,35 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
19
19
  const state = currentWorkflowState(context, entries), rows = state.rows;
20
20
  if (!rows || !state.assessment)
21
21
  throw new FoundryContextError("workflow_assessment_required", "Assess the current rows before finalization.");
22
+ const referenceOptions = new Map();
23
+ for (const set of rows.value.sets) {
24
+ if (executionProgress?.scopes.has(set.type))
25
+ continue;
26
+ const selection = state.referenceInputs.get(set.type);
27
+ if (!selection)
28
+ continue;
29
+ const intended = workflowObject(selection.value.input), current = captureFoundryInput(set.file);
30
+ if (current.sha256 !== intended.sha256 || current.bytes !== intended.bytes)
31
+ throw new FoundryContextError("reference_input_stale", "Select reference evidence for the current dataset rows before finalization.");
32
+ const paths = (raw) => {
33
+ if (!Array.isArray(raw))
34
+ throw new FoundryContextError("reference_input_invalid", "Registered reference file facts are invalid.");
35
+ return raw.map((value) => {
36
+ const fact = workflowObject(value);
37
+ if (typeof fact.path !== "string")
38
+ throw new FoundryContextError("reference_input_invalid", "Reference path is missing.");
39
+ readFoundryInput(context, fact.path);
40
+ return fact.path;
41
+ });
42
+ };
43
+ const qa = paths(selection.value.qa_files);
44
+ paths(selection.value.review_files);
45
+ const intent = selection.value.intent === null ? [] : paths([selection.value.intent]);
46
+ referenceOptions.set(set.type, {
47
+ ...(qa.length ? { qaReferenceRows: qa } : {}),
48
+ ...(intent.length ? { referenceIntentFile: intent[0] } : {}),
49
+ });
50
+ }
22
51
  const profile = await withFoundryTaskMetadata(context, (task, index) => {
23
52
  if (currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
24
53
  throw new FoundryContextError("workflow_rows_changed", "Current rows changed before finalization.");
@@ -136,6 +165,7 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
136
165
  const result = workflowObject(owners.invoke(() => owners.finalize.runDatasetPostAuthoringFinalize({
137
166
  type: ["unitgroup", "flowproperty"].includes(set.type) ? "support" : set.type,
138
167
  rowsFile: set.file,
168
+ ...referenceOptions.get(set.type),
139
169
  outDir: path.join(output, set.type),
140
170
  profile,
141
171
  ...(approval?.datasetType === set.type && authorization
@@ -228,10 +258,19 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
228
258
  assertQualifiedFoundryRuntime(context, qualified);
229
259
  return await runFoundryTaskOperation(context, {
230
260
  command: "dataset-workflow-finalize",
231
- options: { nonce, rows_report: rows.file },
261
+ options: {
262
+ nonce,
263
+ rows_report: rows.file,
264
+ ...(state.referenceInputsSha256
265
+ ? { reference_inputs_sha256: state.referenceInputsSha256 }
266
+ : {}),
267
+ },
232
268
  validateCurrent(index) {
233
269
  if (currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
234
270
  throw new FoundryContextError("workflow_rows_changed", "Rows changed during finalization.");
271
+ if (currentWorkflowState(context, index).referenceInputsSha256 !==
272
+ state.referenceInputsSha256)
273
+ throw new FoundryContextError("reference_input_changed", "Reference selection changed during finalization.");
235
274
  if (authorization &&
236
275
  (createHash("sha256")
237
276
  .update(readTaskBytes(context, "authorization.json"))
@@ -245,6 +284,9 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
245
284
  schema: "tiangong-foundry.finalize-stage.v1",
246
285
  status: blockers.length ? "blocked" : "ready_for_authorization",
247
286
  rows_report: rows.file,
287
+ ...(state.referenceInputsSha256
288
+ ? { reference_inputs_sha256: state.referenceInputsSha256 }
289
+ : {}),
248
290
  assessment_report: state.assessment.file,
249
291
  owner_base: context.assetRoot,
250
292
  approval_source_sha256: approval?.sourceSha256 ?? null,
@@ -34,4 +34,6 @@ export declare function currentWorkflowState(context: FoundryRuntimeContext, ent
34
34
  finalization: WorkflowArtifact<Record<string, unknown>> | null;
35
35
  authorization: WorkflowArtifact<Record<string, unknown>> | null;
36
36
  preparedApproval: WorkflowArtifact<Record<string, unknown>> | null;
37
+ referenceInputs: Map<string, WorkflowArtifact<Record<string, unknown>>>;
38
+ referenceInputsSha256: string | null;
37
39
  };
@@ -110,6 +110,25 @@ export function currentWorkflowState(context, entries) {
110
110
  }
111
111
  }
112
112
  }
113
+ const referenceInputs = new Map();
114
+ for (const entry of entries) {
115
+ if (entry.command !== "dataset-workflow-reference-input" ||
116
+ path.basename(entry.path) !== "foundry-reference-input.json")
117
+ continue;
118
+ const found = readWorkflowArtifact(context, entry);
119
+ if (found.value.schema !== "tiangong-foundry.reference-selection.v1" ||
120
+ found.value.status !== "selected" ||
121
+ typeof found.value.dataset_type !== "string")
122
+ throw new FoundryContextError("reference_input_invalid", "Registered reference selection is invalid.");
123
+ referenceInputs.set(found.value.dataset_type, found);
124
+ }
125
+ const referenceInputsSha256 = referenceInputs.size
126
+ ? createHash("sha256")
127
+ .update(JSON.stringify([...referenceInputs]
128
+ .sort(([a], [b]) => a.localeCompare(b))
129
+ .map(([type, found]) => [type, found.entry.sha256])))
130
+ .digest("hex")
131
+ : null;
113
132
  let finalization = null;
114
133
  if (rows && assessment) {
115
134
  for (const entry of [...entries].reverse()) {
@@ -122,7 +141,8 @@ export function currentWorkflowState(context, entries) {
122
141
  !Array.isArray(found.value.blockers))
123
142
  throw new FoundryContextError("workflow_finalize_invalid", "Registered finalization metadata is invalid.");
124
143
  if (found.value.rows_report === rows.file &&
125
- found.value.assessment_report === assessment.file) {
144
+ found.value.assessment_report === assessment.file &&
145
+ (found.value.reference_inputs_sha256 ?? null) === referenceInputsSha256) {
126
146
  finalization = found;
127
147
  break;
128
148
  }
@@ -154,5 +174,14 @@ export function currentWorkflowState(context, entries) {
154
174
  }
155
175
  }
156
176
  }
157
- return { rows, assessment, identity, finalization, authorization, preparedApproval };
177
+ return {
178
+ rows,
179
+ assessment,
180
+ identity,
181
+ finalization,
182
+ authorization,
183
+ preparedApproval,
184
+ referenceInputs,
185
+ referenceInputsSha256,
186
+ };
158
187
  }
@@ -6,7 +6,7 @@ import { asText, directoryExists, ensureArray, fileExists, readJson, readText, r
6
6
  function asJsonRecord(value) {
7
7
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8
8
  }
9
- export const tidasSchemaSearchRoots = ["@tiangong-lca/cli@0.1.13/assets/tidas-schemas"];
9
+ export const tidasSchemaSearchRoots = ["@tiangong-lca/cli@0.1.14/assets/tidas-schemas"];
10
10
  export function tidasSchemaPath(repoRoot, schemaFile) {
11
11
  void repoRoot;
12
12
  const candidate = path.join(resolveInstalledTiangongLcaCliPackage().schemaDir, schemaFile);
@@ -63,6 +63,7 @@ export declare function createFoundryFacade(options: FoundryPackageFacadeOptions
63
63
  actorId: string;
64
64
  semanticInputFile?: string;
65
65
  authorizationInputFile?: string;
66
+ referenceInputFile?: string;
66
67
  }): Promise<import("./lib/foundry-operation-result.ts").FoundryOperationResult>;
67
68
  requestBinding(input: {
68
69
  taskId: string;
@@ -4,6 +4,7 @@ import type { FoundryRuntimeManagerOptions } from "./lib/foundry-runtime-selecti
4
4
  import type { FoundryAuthentication } from "./lib/foundry-runtime-identity.ts";
5
5
  import { type FoundryFacadeRuntimeSelection } from "./foundry-facade.ts";
6
6
  import { type FoundryWorkspaceAccess, type FoundryAccountIntent } from "./lib/foundry-runtime-context.ts";
7
+ import { type FoundryOperationResult } from "./lib/foundry-operation-result.ts";
7
8
  export interface FoundryRuntimeCommandHost {
8
9
  readonly runtimeSelection?: FoundryFacadeRuntimeSelection;
9
10
  readonly workspaceAccess?: FoundryWorkspaceAccess;
@@ -16,7 +17,10 @@ export interface FoundryRuntimeCommandHost {
16
17
  readonly writeStdout?: (text: string) => void;
17
18
  readonly setExitCode?: (code: number) => void;
18
19
  }
19
- type PrepareRuntimeHost = (signal: AbortSignal) => Promise<Omit<FoundryRuntimeCommandHost, "signal" | "writeStdout" | "setExitCode">>;
20
+ export type PreparedFoundryRuntimeHost = Omit<FoundryRuntimeCommandHost, "signal" | "writeStdout" | "setExitCode"> & {
21
+ readonly projectNextActions?: (result: FoundryOperationResult) => FoundryOperationResult;
22
+ };
23
+ type PrepareRuntimeHost = (signal: AbortSignal) => Promise<PreparedFoundryRuntimeHost>;
20
24
  export declare function runFoundryRuntimeCommand(argv?: string[], host?: FoundryRuntimeCommandHost, prepareHost?: PrepareRuntimeHost): Promise<void>;
21
25
  /** Package bin boundary: never fall back to repository/developer commands. */
22
26
  export declare function runFoundryPublicCommand(argv?: string[], host?: FoundryRuntimeCommandHost, prepareHost?: PrepareRuntimeHost): Promise<void>;
@@ -119,7 +119,7 @@ async function runPublicCommand(parsed, host) {
119
119
  : parsed.operation === "task.start"
120
120
  ? ["spec"]
121
121
  : parsed.operation === "task.resume"
122
- ? ["task", "actor", "semanticInput", "authorizationInput"]
122
+ ? ["task", "actor", "semanticInput", "authorizationInput", "referenceInput"]
123
123
  : parsed.operation === "task.status"
124
124
  ? ["task", "actor"]
125
125
  : []),
@@ -298,6 +298,7 @@ async function runPublicCommand(parsed, host) {
298
298
  taskId,
299
299
  actorId,
300
300
  semanticInputFile: option(parsed.args.semanticInput, "--semantic-input") ?? undefined,
301
+ referenceInputFile: option(parsed.args.referenceInput, "--reference-input") ?? undefined,
301
302
  authorizationInputFile: option(parsed.args.authorizationInput, "--authorization-input") ?? undefined,
302
303
  });
303
304
  }
@@ -385,6 +386,8 @@ export async function runFoundryRuntimeCommand(argv = process.argv, host = {}, p
385
386
  ...prepared,
386
387
  signal: effectiveHost.signal,
387
388
  });
389
+ if (prepared.projectNextActions)
390
+ result = prepared.projectNextActions(result);
388
391
  }
389
392
  catch (error) {
390
393
  result = effectiveHost.signal?.aborted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiangong-lca/foundry",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "Control plane for TianGong LCA external dataset import and TIDAS authoring work.",
6
6
  "repository": {
@@ -42,6 +42,7 @@
42
42
  "specs/schemas/foundry-task-start.schema.json",
43
43
  "specs/schemas/foundry-semantic-input.schema.json",
44
44
  "specs/schemas/foundry-authorization-input.schema.json",
45
+ "specs/schemas/foundry-reference-input.schema.json",
45
46
  "specs/schemas/foundry-workspace-migration-plan.schema.json",
46
47
  "specs/schemas/foundry-workspace-migration-transfer-plan.schema.json",
47
48
  "specs/schemas/foundry-migration-transfer-receipt.schema.json",
@@ -80,7 +81,7 @@
80
81
  },
81
82
  "license": "MIT",
82
83
  "dependencies": {
83
- "@tiangong-lca/cli": "0.1.13"
84
+ "@tiangong-lca/cli": "0.1.14"
84
85
  },
85
86
  "foundryRuntime": {
86
87
  "schema": "tiangong-foundry.runtime-layout.v2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schema_version": 2,
3
- "updated_at_utc": "2026-09-09T12:44:03Z",
3
+ "updated_at_utc": "2026-09-10T23:06:45Z",
4
4
  "default_profile": "generic",
5
5
  "profiles": {
6
6
  "generic": {