@tiangong-lca/foundry 0.1.7 → 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 (59) 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 +6 -6
  9. package/docs/public-runtime-contract.md +22 -6
  10. package/docs/runtime-context-contract.md +9 -5
  11. package/docs/task-authorization-contract.md +8 -4
  12. package/package-dist/assets/foundry-package-descriptor.json +150 -84
  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-owner-execution-store.js +25 -2
  34. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +2 -0
  35. package/package-dist/scripts/lib/foundry-owner-readback.js +65 -14
  36. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  37. package/package-dist/scripts/lib/foundry-package-contract.js +4 -2
  38. package/package-dist/scripts/lib/foundry-reference-input.d.ts +28 -0
  39. package/package-dist/scripts/lib/foundry-reference-input.js +235 -0
  40. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  41. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  42. package/package-dist/scripts/lib/foundry-task-store.d.ts +1 -1
  43. package/package-dist/scripts/lib/foundry-workflow-authorization.d.ts +2 -1
  44. package/package-dist/scripts/lib/foundry-workflow-authorization.js +38 -2
  45. package/package-dist/scripts/lib/foundry-workflow-execution.js +7 -1
  46. package/package-dist/scripts/lib/foundry-workflow-finalize.js +43 -1
  47. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +2 -0
  48. package/package-dist/scripts/lib/foundry-workflow-state.js +31 -2
  49. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  50. package/package-dist/scripts/public-api.d.ts +1 -0
  51. package/package-dist/scripts/runtime-entry.js +2 -1
  52. package/package.json +3 -2
  53. package/specs/import-profiles.json +1 -1
  54. package/specs/prewrite-content-policy.json +1 -1
  55. package/specs/schemas/foundry-authorization-input.schema.json +38 -1
  56. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  57. package/specs/schemas/foundry-package-descriptor.schema.json +3 -2
  58. package/specs/schemas/foundry-reference-input.schema.json +137 -0
  59. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,146 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createFileArtifactFact } from "../foundry-command-spec.js";
4
+ import { sha256Json, sha256Text } from "../identity-preflight-proof.js";
5
+ import { datasetIdentity } from "../import-curation/internal/dataset-payload.js";
6
+ import { readRows } from "../import-curation/internal/runtime-io.js";
7
+ function fail(message) {
8
+ throw new Error(`--execution-contract-file: ${message}`);
9
+ }
10
+ function object(value) {
11
+ if (!value || typeof value !== "object" || Array.isArray(value))
12
+ return fail("Expected a native contract object.");
13
+ return value;
14
+ }
15
+ function token(value) {
16
+ if (typeof value !== "string" || !value.trim())
17
+ return fail("Contract identity fields must be non-empty strings.");
18
+ return value.trim();
19
+ }
20
+ export function assertExecutionContractSelection(options) {
21
+ if (Object.keys(options).some((key) => key.startsWith("executionContract") && key !== "executionContractFile") ||
22
+ (Object.hasOwn(options, "executionContractFile") &&
23
+ (typeof options.executionContractFile !== "string" ||
24
+ options.executionContractFile.trim().length === 0)))
25
+ fail("Use one non-empty string selection; unsupported options or repeated values are invalid.");
26
+ }
27
+ /** Consumer admission only; CLI owns parsing at execution, attempts and readback. */
28
+ export function readNativeInsertHandoff(input) {
29
+ const tables = { flow: "flows", process: "processes", source: "sources" };
30
+ if (!Object.hasOwn(tables, input.datasetType) || input.stateCode !== "0")
31
+ fail("Native insert handoffs support only Flow, Process and Source owner drafts.");
32
+ if (!fs.lstatSync(input.contractFile).isFile())
33
+ fail("Select a regular contract file.");
34
+ const bytes = fs.readFileSync(input.contractFile, "utf8");
35
+ const raw = object(JSON.parse(bytes));
36
+ const owner = object(raw.owner);
37
+ if (raw.schema_version !== "dataset-save-draft-execution-contract.v1" ||
38
+ raw.target_mode !== "owner_draft" ||
39
+ owner.state_code !== 0 ||
40
+ token(owner.user_id) !== input.targetUserId)
41
+ fail("Contract protocol, owner or draft scope does not match the handoff.");
42
+ const projectRef = token(raw.project_ref);
43
+ if (input.verifiedProjectRef && projectRef !== input.verifiedProjectRef)
44
+ fail("Contract project does not match the verified account context.");
45
+ const rowsText = fs.readFileSync(input.rowsFile, "utf8");
46
+ const rows = readRows(input.rowsFile, () => rowsText);
47
+ if (!Array.isArray(raw.actions) || !rows.length || raw.actions.length !== rows.length)
48
+ fail("Contract actions must match every selected final row exactly once.");
49
+ const actionIds = new Set();
50
+ const targets = new Set();
51
+ const actions = raw.actions.map((value, index) => {
52
+ const action = object(value);
53
+ const actionId = token(action.action_id);
54
+ const identity = datasetIdentity(rows[index], index, input.datasetType);
55
+ const root = object(object(identity.payload)[`${input.datasetType}DataSet`]);
56
+ const info = object(object(root[`${input.datasetType}Information`]).dataSetInformation);
57
+ const publication = object(object(root.administrativeInformation).publicationAndOwnership);
58
+ const id = token(info["common:UUID"]);
59
+ const version = token(publication["common:dataSetVersion"]);
60
+ const target = JSON.stringify([id, version]);
61
+ if (actionIds.has(actionId) ||
62
+ targets.has(target) ||
63
+ action.expected_operation !== "insert" ||
64
+ action.before_sha256 !== null ||
65
+ action.table !== tables[input.datasetType] ||
66
+ token(action.id) !== id ||
67
+ token(action.version) !== version ||
68
+ identity.id !== id ||
69
+ identity.version !== version ||
70
+ action.desired_sha256 !== sha256Json(identity.payload))
71
+ fail("Contract insert action does not bind the exact final payload and identity.");
72
+ if (!Array.isArray(action.dependency_action_ids))
73
+ fail("Action dependencies must be explicit.");
74
+ const dependencies = action.dependency_action_ids.map(token);
75
+ if (new Set(dependencies).size !== dependencies.length ||
76
+ dependencies.some((id) => !actionIds.has(id)))
77
+ fail("Dependencies must identify unique earlier contract actions.");
78
+ actionIds.add(actionId);
79
+ targets.add(target);
80
+ return {
81
+ action_id: actionId,
82
+ desired_sha256: action.desired_sha256,
83
+ expected_operation: "insert",
84
+ table: tables[input.datasetType],
85
+ id,
86
+ version,
87
+ before_sha256: null,
88
+ dependency_action_ids: dependencies,
89
+ };
90
+ });
91
+ // Project the native owner's normalized wire fields for its report digest.
92
+ // Raw file bytes are bound separately, so ignored metadata cannot drift.
93
+ const contract = {
94
+ schema_version: "dataset-save-draft-execution-contract.v1",
95
+ execution_id: token(raw.execution_id),
96
+ project_ref: projectRef,
97
+ target_mode: "owner_draft",
98
+ owner: {
99
+ user_id: token(owner.user_id),
100
+ email: token(owner.email).toLowerCase(),
101
+ state_code: 0,
102
+ },
103
+ actions,
104
+ };
105
+ const artifact = createFileArtifactFact({
106
+ role: "execution_contract",
107
+ path: input.relativePath(input.contractFile),
108
+ filePath: input.contractFile,
109
+ });
110
+ if (artifact.sha256 !== sha256Text(bytes))
111
+ fail("Contract bytes changed during admission.");
112
+ return {
113
+ artifact,
114
+ contract,
115
+ canonical_sha256: sha256Json(contract),
116
+ metadata: {
117
+ artifact,
118
+ canonical_sha256: sha256Json(contract),
119
+ execution_id: contract.execution_id,
120
+ project_ref: contract.project_ref,
121
+ operation: "insert",
122
+ },
123
+ rows_sha256: sha256Text(rowsText),
124
+ };
125
+ }
126
+ export function reserveNativeHandoffDirectory(directory) {
127
+ fs.mkdirSync(path.dirname(directory), { recursive: true });
128
+ fs.mkdirSync(directory);
129
+ }
130
+ export function nativeInsertCommitArguments(prefix, datasetType, rowsFile, outDir, contractFile) {
131
+ return [
132
+ ...prefix,
133
+ "dataset",
134
+ "save-draft",
135
+ "--type",
136
+ datasetType,
137
+ "--input",
138
+ rowsFile,
139
+ "--out-dir",
140
+ path.join(outDir, "commit", `${datasetType}-save-draft`),
141
+ "--execution-contract",
142
+ contractFile,
143
+ "--commit",
144
+ "--json",
145
+ ];
146
+ }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { taskAuthorizationAllows } from "../task-authorization.js";
4
4
  import { readOnlyStageContract } from "../stage-contract.js";
5
+ import { selectFinalizeReferenceInputs } from "./finalize-reference-inputs.js";
5
6
  const postAuthoringFinalizeStageContract = readOnlyStageContract([
6
7
  {
7
8
  stage: "prepare_scope",
@@ -659,6 +660,12 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
659
660
  if (!rowsFile || !fileExists(rowsFile)) {
660
661
  throw new Error("--rows-file is required and must point to patched or authored TIDAS rows.");
661
662
  }
663
+ const referenceInputs = selectFinalizeReferenceInputs({
664
+ options,
665
+ datasetType,
666
+ verifyRemote: booleanOption(options.verifyRemote || options.precommitVerifyRemote),
667
+ resolveFile: resolveRepoPath,
668
+ });
662
669
  const outDir = resolveRepoPath(options.outDir || `.foundry/workspaces/${datasetType}-post-authoring-finalize`);
663
670
  fs.mkdirSync(outDir, { recursive: true });
664
671
  const fullContextRequirement = profileFullContextRequirement(options.profile, datasetType);
@@ -1052,6 +1059,7 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1052
1059
  cleanedRowsFile,
1053
1060
  "--out-dir",
1054
1061
  qaOutDir,
1062
+ ...referenceInputs.qaFiles.flatMap((file) => ["--reference-rows-file", file]),
1055
1063
  "--json",
1056
1064
  ])
1057
1065
  : {
@@ -1265,6 +1273,8 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1265
1273
  String(options.remoteRootPolicy || options.rootPolicy || "candidate"),
1266
1274
  "--json",
1267
1275
  ];
1276
+ if (referenceInputs.intentFile)
1277
+ remoteArgs.push("--reference-intent-file", referenceInputs.intentFile);
1268
1278
  if (booleanOption(options.compareRootPayload || options.remoteCompareRootPayload)) {
1269
1279
  remoteArgs.push("--compare-root-payload");
1270
1280
  }
@@ -1515,6 +1525,9 @@ export function createPostAuthoringFinalizeCommands({ appendOption, applyCanonic
1515
1525
  schema_version: 1,
1516
1526
  started_at_utc: finalizeStartedAtUtc,
1517
1527
  generated_at_utc: nowIso(),
1528
+ ...(referenceInputs.intentFile
1529
+ ? { reference_intent_file: repoRelativePath(referenceInputs.intentFile) }
1530
+ : {}),
1518
1531
  status,
1519
1532
  dataset_type: datasetType,
1520
1533
  profile: mutationManifest.profile || String(options.profile || "generic"),
@@ -1,3 +1,4 @@
1
+ import type { FoundryArtifactFact } from "../foundry-command-spec.ts";
1
2
  import type { IntendedRoot, RootReadbackCheck } from "../post-write-root-proof.ts";
2
3
  type JsonRecord = Record<string, unknown>;
3
4
  type CountRecord = Record<string, unknown> & {
@@ -113,8 +114,9 @@ export type PostWriteCloseoutFactoryDependencies = {
113
114
  };
114
115
  export declare function createPostWriteCloseoutCommands({ executionEnvironment, asText, countJsonLinesFile, countRowsFile, datasetIdentity, ensureArray, fileExists, fullContextProofCheck, nowIso, readJsonArtifactOption, readJsonLines, readRowsFile, repoRelativeMaybe, repoRelativePath, reportInputPath, resolveRepoPath, sameResolvedPath, validateTraceQueueCoverageForRows, writeCloseoutImportLedger, writeJson, }: PostWriteCloseoutFactoryDependencies): {
115
116
  runDatasetPostWriteCloseout: (options: PostWriteCloseoutOptions) => JsonRecord;
116
- validatePostWriteVerifyForCloseout: ({ verifyReport, verifyReportPath, finalRowsFile, expectedRows, targetUserId, expectedStateCode, intendedRoots, allowTraceHashOnlyNormalization, blockers, }: {
117
+ validatePostWriteVerifyForCloseout: ({ verifyReport, handoffPlan, verifyReportPath, finalRowsFile, expectedRows, targetUserId, expectedStateCode, intendedRoots, allowTraceHashOnlyNormalization, blockers, }: {
117
118
  verifyReport: ReportValue;
119
+ handoffPlan?: ReportValue;
118
120
  verifyReportPath: string;
119
121
  finalRowsFile: string;
120
122
  expectedRows: number;
@@ -124,17 +126,21 @@ export declare function createPostWriteCloseoutCommands({ executionEnvironment,
124
126
  allowTraceHashOnlyNormalization: boolean;
125
127
  blockers: JsonRecord[];
126
128
  }) => {
129
+ referenceArtifacts?: FoundryArtifactFact[];
127
130
  checksFile: string | null;
128
131
  readbackChecks: RootReadbackCheck[];
129
132
  uniqueReadbackCount: number;
130
133
  };
131
- validateCommitReportForCloseout: ({ commitReport, commitReportPath, datasetType, finalRowsFile, expectedRows, blockers, }: {
134
+ validateCommitReportForCloseout: ({ commitReport, commitReportPath, datasetType, finalRowsFile, expectedRows, blockers, handoffPlan, targetUserId, expectedStateCode, }: {
132
135
  commitReport: ReportValue;
133
136
  commitReportPath: string;
134
137
  datasetType: string;
135
138
  finalRowsFile: string;
136
139
  expectedRows: number;
137
140
  blockers: JsonRecord[];
141
+ handoffPlan?: ReportValue;
142
+ targetUserId?: string;
143
+ expectedStateCode?: number | null;
138
144
  }) => void;
139
145
  };
140
146
  export {};
@@ -2,11 +2,34 @@ import path from "node:path";
2
2
  import { createFileArtifactFact } from "../foundry-command-spec.js";
3
3
  import { normalizeAllowedTraceHashDifference } from "../remote-verification-accepted-diff.js";
4
4
  import { canonicalPayloadSha256, validateUniqueRootReadbacks } from "../post-write-root-proof.js";
5
+ import { validateNativeInsertCloseout } from "./native-insert-closeout.js";
6
+ import { validateReferenceIntentReadback } from "./reference-intent-closeout.js";
5
7
  function isJsonRecord(value) {
6
8
  return typeof value === "object" && value !== null && !Array.isArray(value);
7
9
  }
8
10
  export function createPostWriteCloseoutCommands({ executionEnvironment = process.env, asText, countJsonLinesFile, countRowsFile, datasetIdentity, ensureArray, fileExists, fullContextProofCheck, nowIso, readJsonArtifactOption, readJsonLines, readRowsFile, repoRelativeMaybe, repoRelativePath, reportInputPath, resolveRepoPath, sameResolvedPath, validateTraceQueueCoverageForRows, writeCloseoutImportLedger, writeJson, }) {
9
- function validateCommitReportForCloseout({ commitReport, commitReportPath, datasetType, finalRowsFile, expectedRows, blockers, }) {
11
+ function validateCommitReportForCloseout({ commitReport, commitReportPath, datasetType, finalRowsFile, expectedRows, blockers, handoffPlan, targetUserId, expectedStateCode, }) {
12
+ try {
13
+ if (validateNativeInsertCloseout({
14
+ handoff: handoffPlan ?? {},
15
+ report: commitReport,
16
+ rowsFile: finalRowsFile,
17
+ datasetType,
18
+ targetUserId: targetUserId ?? asText(handoffPlan?.target_user_id),
19
+ stateCode: asText(expectedStateCode ?? handoffPlan?.expected_state_code),
20
+ expectedRows,
21
+ resolveFile: resolveRepoPath,
22
+ relativePath: repoRelativePath,
23
+ }))
24
+ return;
25
+ }
26
+ catch {
27
+ blockers.push({
28
+ code: "native_execution_evidence_invalid",
29
+ message: "Native contract, bound artifacts, command or exact completion evidence is missing, changed or inconsistent; mutation replay is forbidden.",
30
+ });
31
+ return;
32
+ }
10
33
  const inputPath = resolveRepoPath(reportInputPath(commitReport));
11
34
  const status = asText(commitReport.status);
12
35
  const mode = asText(commitReport.mode);
@@ -68,7 +91,25 @@ export function createPostWriteCloseoutCommands({ executionEnvironment = process
68
91
  });
69
92
  }
70
93
  }
71
- function validatePostWriteVerifyForCloseout({ verifyReport, verifyReportPath, finalRowsFile, expectedRows, targetUserId, expectedStateCode, intendedRoots, allowTraceHashOnlyNormalization, blockers, }) {
94
+ function validatePostWriteVerifyForCloseout({ verifyReport, handoffPlan, verifyReportPath, finalRowsFile, expectedRows, targetUserId, expectedStateCode, intendedRoots, allowTraceHashOnlyNormalization, blockers, }) {
95
+ let referenceArtifacts = [];
96
+ try {
97
+ referenceArtifacts = validateReferenceIntentReadback({
98
+ handoff: handoffPlan ?? {},
99
+ report: verifyReport,
100
+ rowsFile: finalRowsFile,
101
+ datasetType: asText(handoffPlan?.dataset_type),
102
+ targetUserId,
103
+ resolveFile: resolveRepoPath,
104
+ relativePath: repoRelativePath,
105
+ });
106
+ }
107
+ catch {
108
+ blockers.push({
109
+ code: "reference_intent_evidence_invalid",
110
+ message: "Post-write verification must retain the same current consumer, intent, precommit and review evidence as its handoff.",
111
+ });
112
+ }
72
113
  const inputPath = resolveRepoPath(reportInputPath(verifyReport));
73
114
  const counts = verifyReport.counts ?? {};
74
115
  const blockerCount = Number(counts.blockers ?? (Array.isArray(verifyReport.blockers) ? verifyReport.blockers.length : 0));
@@ -184,6 +225,7 @@ export function createPostWriteCloseoutCommands({ executionEnvironment = process
184
225
  checksFile,
185
226
  readbackChecks,
186
227
  uniqueReadbackCount: uniqueProof.uniqueReadbackCount,
228
+ ...(referenceArtifacts.length ? { referenceArtifacts } : {}),
187
229
  };
188
230
  }
189
231
  function validateTraceQueuesForCloseout({ handoffPlan, finalizeReport, mutationManifest, datasetType, finalRowsFile, blockers, }) {
@@ -538,9 +580,13 @@ export function createPostWriteCloseoutCommands({ executionEnvironment = process
538
580
  finalRowsFile,
539
581
  expectedRows,
540
582
  blockers,
583
+ handoffPlan,
584
+ targetUserId,
585
+ expectedStateCode,
541
586
  });
542
587
  rootProof = validatePostWriteVerifyForCloseout({
543
588
  verifyReport: verifyArtifact.value,
589
+ handoffPlan,
544
590
  verifyReportPath: verifyArtifact.path,
545
591
  finalRowsFile,
546
592
  expectedRows,
@@ -0,0 +1,12 @@
1
+ import { type FoundryArtifactFact } from "../foundry-command-spec.ts";
2
+ type RecordValue = Record<string, unknown>;
3
+ export declare function validateReferenceIntentReadback(input: {
4
+ handoff: RecordValue;
5
+ report: RecordValue;
6
+ rowsFile: string;
7
+ datasetType: string;
8
+ targetUserId: string;
9
+ resolveFile: (value: unknown) => string | null;
10
+ relativePath: (file: string) => string;
11
+ }): FoundryArtifactFact[];
12
+ export {};
@@ -0,0 +1,77 @@
1
+ import path from "node:path";
2
+ import { parseFoundryCommandSpec } from "../foundry-command-spec.js";
3
+ import { sha256Json } from "../identity-preflight-proof.js";
4
+ import { readHandoffReferenceEvidence } from "./handoff-reference-intent.js";
5
+ function requireEvidence(value) {
6
+ if (!value)
7
+ throw new Error("Reference intent readback evidence is missing, changed or inconsistent.");
8
+ }
9
+ function object(value) {
10
+ requireEvidence(value && typeof value === "object" && !Array.isArray(value));
11
+ return value;
12
+ }
13
+ export function validateReferenceIntentReadback(input) {
14
+ if (!Object.hasOwn(input.handoff, "reference_intent")) {
15
+ requireEvidence(!Object.hasOwn(input.report, "reference_intent"));
16
+ const commands = input.handoff.commands;
17
+ if (commands && typeof commands === "object") {
18
+ for (const raw of Object.values(commands)) {
19
+ if (!raw || typeof raw !== "object")
20
+ continue;
21
+ const argv = raw.argv;
22
+ requireEvidence(!Array.isArray(argv) ||
23
+ !argv.some((arg) => typeof arg === "string" && arg.split("=")[0] === "--reference-intent-file"));
24
+ }
25
+ }
26
+ return [];
27
+ }
28
+ const resolve = (value) => {
29
+ const file = input.resolveFile(value);
30
+ return file ? path.resolve(file) : null;
31
+ };
32
+ const metadata = object(input.handoff.reference_intent), intent = object(metadata.artifact), precommit = object(metadata.precommit_artifact);
33
+ const fresh = readHandoffReferenceEvidence({
34
+ finalize: {
35
+ files: { remote_verify_report: precommit.path },
36
+ reference_intent_file: intent.path,
37
+ },
38
+ options: { referenceIntentFile: intent.path },
39
+ rowsFile: input.rowsFile,
40
+ datasetType: input.datasetType,
41
+ targetUserId: input.targetUserId,
42
+ projectRef: String(input.handoff.verified_project_ref ?? ""),
43
+ resolveFile: input.resolveFile,
44
+ relativePath: input.relativePath,
45
+ });
46
+ requireEvidence(fresh && Array.isArray(metadata.review_artifacts));
47
+ const expected = [intent, precommit, ...metadata.review_artifacts.map(object)];
48
+ const sameFact = (a, b) => resolve(a.path) === resolve(b.path) && a.sha256 === b.sha256 && a.bytes === b.bytes;
49
+ requireEvidence(expected.length === fresh.artifacts.length &&
50
+ expected.every((fact, i) => fact.role === fresh.artifacts[i].role && sameFact(fact, fresh.artifacts[i])));
51
+ requireEvidence(metadata.actor_user_id === fresh.metadata.actor_user_id &&
52
+ metadata.project_ref === fresh.metadata.project_ref &&
53
+ metadata.consumers_sha256 === fresh.metadata.consumers_sha256);
54
+ const rows = object(input.handoff.final_rows_artifact);
55
+ requireEvidence(rows.sha256 === fresh.rows_sha256);
56
+ const commands = object(input.handoff.commands);
57
+ for (const key of ["commit", "post_write_verify"]) {
58
+ const command = parseFoundryCommandSpec(commands[key]);
59
+ for (const fact of [rows, ...expected])
60
+ requireEvidence(command.binding.artifacts.filter((bound) => sameFact(fact, bound)).length === 1);
61
+ const positions = command.argv.flatMap((arg, index) => arg === "--reference-intent-file" ? [index] : []);
62
+ requireEvidence(!command.argv.some((arg) => arg.startsWith("--reference-intent-file=")));
63
+ requireEvidence(key === "commit"
64
+ ? positions.length === 0
65
+ : positions.length === 1 && resolve(command.argv[positions[0] + 1]) === fresh.intentFile);
66
+ }
67
+ const readback = object(input.report.reference_intent);
68
+ requireEvidence(sameFact(object(readback.file), fresh.metadata.artifact) &&
69
+ readback.actor_user_id === metadata.actor_user_id &&
70
+ readback.project_ref === metadata.project_ref &&
71
+ sha256Json(readback.consumers) === metadata.consumers_sha256);
72
+ requireEvidence(Array.isArray(readback.review_files) &&
73
+ readback.review_files.length === fresh.metadata.review_artifacts.length);
74
+ for (const fact of fresh.metadata.review_artifacts)
75
+ requireEvidence(readback.review_files.filter((raw) => sameFact(object(raw), fact)).length === 1);
76
+ return fresh.artifacts.map((fact) => ({ ...fact, path: resolve(fact.path) }));
77
+ }
@@ -1,4 +1,5 @@
1
1
  import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
2
3
  export declare const FOUNDRY_AUTHORIZATION_INPUT_SCHEMA: "tiangong-foundry.authorization-input.v1";
3
4
  export interface FoundryAuthorizationInput {
4
5
  schema: typeof FOUNDRY_AUTHORIZATION_INPUT_SCHEMA;
@@ -9,6 +10,10 @@ export interface FoundryAuthorizationInput {
9
10
  input_kind: "current_rows" | "final_rows";
10
11
  input_sha256: string;
11
12
  expected_previous_sha256: string | null;
13
+ execution_contract?: {
14
+ file: string;
15
+ sha256: string;
16
+ };
12
17
  grant: {
13
18
  file: string;
14
19
  sha256: string;
@@ -25,7 +30,10 @@ export interface SelectedAuthorizationInput {
25
30
  readonly descriptor: FoundryInputFact;
26
31
  readonly grant: FoundryInputFact;
27
32
  readonly evidence: readonly FoundryInputFact[];
33
+ readonly executionContract?: FoundryInputFact;
34
+ readonly executionContractSource?: FoundryInputFact;
28
35
  }
29
36
  export declare function parseFoundryAuthorizationInput(value: unknown): FoundryAuthorizationInput;
30
37
  export declare function selectFoundryAuthorizationInput(context: FoundryRuntimeContext, file: string): SelectedAuthorizationInput;
31
38
  export declare function assertSelectedAuthorizationInput(value: SelectedAuthorizationInput): void;
39
+ export declare function snapshotFoundryAuthorizationContract(context: FoundryRuntimeContext, selected: SelectedAuthorizationInput, entries: readonly ArtifactEntry[]): Promise<SelectedAuthorizationInput>;
@@ -4,6 +4,7 @@ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-con
4
4
  import { assertNotFoundrySessionFile, migrationCredentialPath } from "./foundry-private-path.js";
5
5
  import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
6
6
  import { workflowObject } from "./foundry-workflow-state.js";
7
+ import { runFoundryTaskOperation } from "./foundry-task-store.js";
7
8
  export const FOUNDRY_AUTHORIZATION_INPUT_SCHEMA = "tiangong-foundry.authorization-input.v1";
8
9
  const sha = /^[0-9a-f]{64}$/u;
9
10
  const identifier = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u;
@@ -38,6 +39,7 @@ export function parseFoundryAuthorizationInput(value) {
38
39
  "expected_previous_sha256",
39
40
  "grant",
40
41
  "evidence",
42
+ ...(Object.hasOwn(data, "execution_contract") ? ["execution_contract"] : []),
41
43
  ]);
42
44
  if (data.schema !== FOUNDRY_AUTHORIZATION_INPUT_SCHEMA ||
43
45
  typeof data.task_id !== "string" ||
@@ -68,6 +70,15 @@ export function parseFoundryAuthorizationInput(value) {
68
70
  invalid("Authorization input must bind a current task, scope, finalization and explicit evidence.");
69
71
  const grant = workflowObject(data.grant);
70
72
  exact(grant, ["file", "sha256"]);
73
+ let executionContract;
74
+ if (Object.hasOwn(data, "execution_contract")) {
75
+ if (data.input_kind !== "final_rows" ||
76
+ !["flow", "process", "source"].includes(data.dataset_type))
77
+ invalid("Native insert contracts require finalized Flow, Process or Source rows.");
78
+ const selected = workflowObject(data.execution_contract);
79
+ exact(selected, ["file", "sha256"]);
80
+ executionContract = Object.freeze(fileReference(selected));
81
+ }
71
82
  const evidence = data.evidence.map((raw) => {
72
83
  const item = workflowObject(raw);
73
84
  exact(item, ["id", "kind", "file", "sha256"]);
@@ -91,6 +102,7 @@ export function parseFoundryAuthorizationInput(value) {
91
102
  expected_previous_sha256: data.expected_previous_sha256,
92
103
  grant: Object.freeze(fileReference(grant)),
93
104
  evidence: Object.freeze(evidence),
105
+ ...(executionContract ? { execution_contract: executionContract } : {}),
94
106
  });
95
107
  }
96
108
  export function selectFoundryAuthorizationInput(context, file) {
@@ -134,11 +146,15 @@ export function selectFoundryAuthorizationInput(context, file) {
134
146
  invalid("The selected grant must be a complete JSON object.");
135
147
  }
136
148
  Object.freeze(spec.evidence);
149
+ const executionContract = spec.execution_contract ? select(spec.execution_contract.file) : null;
150
+ if (executionContract && executionContract.sha256 !== spec.execution_contract.sha256)
151
+ invalid("Native execution contract bytes differ from the selected digest.");
137
152
  const result = Object.freeze({
138
153
  spec,
139
154
  descriptor,
140
155
  grant: selected[0],
141
156
  evidence: Object.freeze(selected.slice(1)),
157
+ ...(executionContract ? { executionContract } : {}),
142
158
  });
143
159
  selections.add(result);
144
160
  return result;
@@ -146,6 +162,57 @@ export function selectFoundryAuthorizationInput(context, file) {
146
162
  export function assertSelectedAuthorizationInput(value) {
147
163
  if (!selections.has(value))
148
164
  invalid("Approval input must be independently selected by the current host.");
149
- for (const fact of [value.descriptor, value.grant, ...value.evidence])
165
+ for (const fact of [
166
+ value.descriptor,
167
+ value.grant,
168
+ ...value.evidence,
169
+ ...(value.executionContract ? [value.executionContract] : []),
170
+ ...(value.executionContractSource ? [value.executionContractSource] : []),
171
+ ])
150
172
  readSelectedSemanticBytes(fact);
151
173
  }
174
+ export async function snapshotFoundryAuthorizationContract(context, selected, entries) {
175
+ assertSelectedAuthorizationInput(selected);
176
+ if (!selected.executionContract)
177
+ return selected;
178
+ if (!context.taskRoot)
179
+ invalid("A native contract snapshot requires the current task.");
180
+ const file = path.join(context.taskRoot, "outputs", "native-contracts", `${selected.executionContract.sha256}.json`);
181
+ const indexed = entries.find((entry) => path.resolve(context.taskRoot, entry.path) === file);
182
+ if (!indexed) {
183
+ await runFoundryTaskOperation(context, {
184
+ command: "dataset-workflow-native-contract",
185
+ options: {
186
+ contract: selected.executionContract,
187
+ task: selected.spec.task_id,
188
+ input: selected.spec.input_sha256,
189
+ finalization: selected.spec.finalization_sha256,
190
+ },
191
+ validateCurrent: () => assertSelectedAuthorizationInput(selected),
192
+ }, (operation) => {
193
+ operation.writeText(file, readSelectedSemanticBytes(selected.executionContract));
194
+ const result = {
195
+ status: "staged",
196
+ artifact: captureFoundryInput(file),
197
+ grants_permission: false,
198
+ };
199
+ operation.writeJson(`${file}.snapshot.json`, result);
200
+ return result;
201
+ });
202
+ }
203
+ else if (indexed.sha256 !== selected.executionContract.sha256 ||
204
+ indexed.bytes !== selected.executionContract.bytes) {
205
+ invalid("Indexed native contract differs from the selected content.");
206
+ }
207
+ const snapshot = Object.freeze({
208
+ ...selected,
209
+ executionContractSource: selected.executionContractSource ?? selected.executionContract,
210
+ executionContract: Object.freeze(captureFoundryInput(file)),
211
+ });
212
+ if (snapshot.executionContract.sha256 !== selected.executionContract.sha256 ||
213
+ snapshot.executionContract.bytes !== selected.executionContract.bytes)
214
+ invalid("Native contract snapshot differs from the independently selected bytes.");
215
+ selections.add(snapshot);
216
+ assertSelectedAuthorizationInput(snapshot);
217
+ return snapshot;
218
+ }
@@ -900,6 +900,7 @@ export const commandMetadata = {
900
900
  "queue artifacts",
901
901
  "schema/context files",
902
902
  "decision/patch evidence",
903
+ "optional explicit Process QA reference rows and verified reference intent",
903
904
  ],
904
905
  outputs: [
905
906
  "post-authoring-finalize report (always)",
@@ -910,6 +911,7 @@ export const commandMetadata = {
910
911
  "cleanup-blocked: every pre-existing stale artifact is preserved and reported",
911
912
  ],
912
913
  keyTests: [
914
+ nodeTest("test/scenarios/finalize-reference-inputs.test.mts", "explicit reference selections fail before finalizer outputs or owner CLI calls"),
913
915
  goldenDiff,
914
916
  postAuthoringFinalizeCommandContract,
915
917
  nodeTest("test/unit/foundry-stage-contract.test.mts", "complex workflow commands publish AI-readable stage contracts"),
@@ -927,13 +929,18 @@ export const commandMetadata = {
927
929
  "finalize report",
928
930
  "location audit evidence",
929
931
  "current task authorization for restricted final rows or QA exceptions",
932
+ "optional explicit native insert execution-contract file for Flow, Process or Source",
930
933
  ],
931
934
  outputs: [
932
935
  "commit handoff plan JSON report",
933
936
  "authoritative commit and post-write verify CommandSpecs with executable, argv, display, binding, and SHA-256",
934
937
  "final rows artifact facts with exact path, bytes, and SHA-256",
938
+ "conditional native execution-contract raw artifact and normalized owner report binding",
939
+ "conditional reference intent, precommit and review artifact bindings",
935
940
  ],
936
941
  keyTests: [
942
+ nodeTest("test/scenarios/handoff-reference-intent.test.mts", "handoff automatically retains the passing reference intent and all evidence in both command specs"),
943
+ nodeTest("test/scenarios/native-insert-closeout.test.mts", "native closeout rejects a completed report from a different contract despite exact root readback"),
937
944
  nodeTest("test/unit/handoff-identity-task-command-factories.test.mts", "mixed support handoff rechecks exact task actions against actual final rows"),
938
945
  nodeTest("test/unit/foundry-command-spec.test.mts", "CommandSpec blocks artifact byte drift before spawn and never executes display"),
939
946
  nodeTest("test/scenarios/full-context-completion-closeout.test.mts", "commit handoff blocks nonzero location audit blockers"),
@@ -944,9 +951,16 @@ export const commandMetadata = {
944
951
  category: "workflow-internal",
945
952
  ownerModule: "scripts/commands/post-write-closeout.ts",
946
953
  ownerExport: "createPostWriteCloseoutCommands().runDatasetPostWriteCloseout",
947
- inputs: ["final rows", "write result", "trace queues", "readback/verify evidence"],
954
+ inputs: [
955
+ "final rows",
956
+ "write result",
957
+ "trace queues",
958
+ "readback/verify evidence",
959
+ "native handoff contract binding when selected",
960
+ ],
948
961
  outputs: ["post-write-closeout-report.json"],
949
962
  keyTests: [
963
+ nodeTest("test/scenarios/native-insert-closeout.test.mts", "native closeout accepts exact consumed insert/readback evidence and still requires unique roots"),
950
964
  nodeTest("test/scenarios/full-context-completion-closeout.test.mts", "post-write closeout requires common:other trace queues to match final rows"),
951
965
  ],
952
966
  }),