@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
@@ -1,10 +1,13 @@
1
1
  import path from "node:path";
2
+ import fs from "node:fs";
3
+ import { assertReferenceIntentSelection, readHandoffReferenceEvidence, } from "./handoff-reference-intent.js";
2
4
  import process from "node:process";
3
5
  import { createFileArtifactFact, createFoundryCommandSpec } from "../foundry-command-spec.js";
4
6
  import { taskAuthorizationAllows, taskAuthorizationMatches, taskAuthorizationWaivesQa, } from "../task-authorization.js";
5
7
  import { datasetIdentity, detectDatasetType } from "../import-curation/internal/dataset-payload.js";
6
8
  import { readRows } from "../import-curation/internal/runtime-io.js";
7
9
  import { flowPrewriteIdentityBlockers } from "../import-curation/internal/workflow-identity-preflight.js";
10
+ import { assertExecutionContractSelection, readNativeInsertHandoff, reserveNativeHandoffDirectory, nativeInsertCommitArguments, } from "./native-insert-handoff.js";
8
11
  function commitCommandForDatasetType(datasetType, rowsFile, outDir, { appendOption, resolveTiangongLcaCliBin, resolveTiangongLcaCliCommand, targetUserId = null, allowAccountLocalSupportAndElementary = false, } = {}) {
9
12
  const cliPrefix = () => {
10
13
  if (resolveTiangongLcaCliCommand) {
@@ -164,6 +167,8 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
164
167
  }
165
168
  }
166
169
  function runDatasetCommitHandoffPlan(options) {
170
+ assertExecutionContractSelection(options);
171
+ assertReferenceIntentSelection(options);
167
172
  if (options.help) {
168
173
  return {
169
174
  schema_version: 1,
@@ -172,6 +177,7 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
172
177
  usage: [
173
178
  "node scripts/foundry.ts dataset-commit-handoff-plan --finalize-report <dataset-post-authoring-finalize-report.json> --out-dir <handoff-dir>",
174
179
  "node scripts/foundry.ts dataset-commit-handoff-plan --finalize-report <dataset-post-authoring-finalize-report.json> --state-code <expected-state-code> --out-dir <handoff-dir>",
180
+ "node scripts/foundry.ts dataset-commit-handoff-plan --finalize-report <report.json> --execution-contract-file <native-insert-contract.json> --out-dir <new-handoff-dir>",
175
181
  ],
176
182
  purpose: "Build a read-only explicit commit handoff plan from a ready post-authoring finalize report. It never writes the database.",
177
183
  remote_write_mode: "read-only",
@@ -206,7 +212,35 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
206
212
  const explicitStateCode = asText(options.stateCode ?? options.expectedStateCode);
207
213
  const stateCode = explicitStateCode || "0";
208
214
  const stateCodeSource = explicitStateCode ? "explicit_option" : "default_draft_write_state";
209
- const commitSupportsTargetUserId = ["flow", "process"].includes(datasetType);
215
+ const contractFile = typeof options.executionContractFile === "string"
216
+ ? resolveRepoPath(options.executionContractFile)
217
+ : null;
218
+ if (contractFile && fileExists(outDir))
219
+ throw new Error("--execution-contract-file requires a fresh handoff output directory.");
220
+ const native = contractFile && finalRowsFile
221
+ ? readNativeInsertHandoff({
222
+ contractFile,
223
+ rowsFile: finalRowsFile,
224
+ datasetType,
225
+ targetUserId,
226
+ verifiedProjectRef,
227
+ stateCode,
228
+ relativePath: repoRelativePath,
229
+ })
230
+ : null;
231
+ const reference = readHandoffReferenceEvidence({
232
+ finalize: finalizeReport,
233
+ options,
234
+ rowsFile: finalRowsFile,
235
+ datasetType,
236
+ targetUserId,
237
+ projectRef: verifiedProjectRef,
238
+ resolveFile: resolveRepoPath,
239
+ relativePath: repoRelativePath,
240
+ });
241
+ if (reference && fs.existsSync(outDir))
242
+ throw new Error("--reference-intent-file requires a fresh handoff output directory.");
243
+ const commitSupportsTargetUserId = !native && ["flow", "process"].includes(datasetType);
210
244
  const blockers = [];
211
245
  if (finalizeReport.status !== "ready_for_remote_write") {
212
246
  blockers.push({
@@ -340,7 +374,7 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
340
374
  }
341
375
  const allowAccountLocalSupportAndElementary = requiredSupportActions.size > 0 &&
342
376
  [...requiredSupportActions].every((action) => taskAuthorizationAllows(handoffProfile?.authorization, action));
343
- const commitArgs = finalRowsFile
377
+ const legacyCommitArgs = finalRowsFile && !native
344
378
  ? commitCommandForDatasetType(datasetType, finalRowsFile, outDir, {
345
379
  appendOption,
346
380
  resolveTiangongLcaCliCommand,
@@ -355,6 +389,9 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
355
389
  return [cli.command, ...cli.args];
356
390
  })()
357
391
  : [resolveTiangongLcaCliBin()];
392
+ const commitArgs = native && finalRowsFile && contractFile
393
+ ? nativeInsertCommitArguments(cliPrefix, datasetType, finalRowsFile, outDir, contractFile)
394
+ : legacyCommitArgs;
358
395
  const verifyArgs = finalRowsFile
359
396
  ? [
360
397
  ...cliPrefix,
@@ -383,7 +420,14 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
383
420
  filePath: finalRowsFile,
384
421
  })
385
422
  : null;
423
+ if (reference) {
424
+ verifyArgs.push("--reference-intent-file", reference.intentFile);
425
+ if (reference.rows_sha256 !== finalRowsArtifact?.sha256)
426
+ throw new Error("--reference-intent-file consumer bytes changed during handoff.");
427
+ }
386
428
  const requestedAuthorization = options.taskAuthorization;
429
+ if (native && native.rows_sha256 !== finalRowsArtifact?.sha256)
430
+ throw new Error("--execution-contract-file final rows changed during handoff admission.");
387
431
  if (taskAuthorizationMatches(requestedAuthorization, options.taskAuthorizationBinding) &&
388
432
  requestedAuthorization.binding.input_scope_sha256 !== finalRowsArtifact?.sha256) {
389
433
  blockers.push({
@@ -420,6 +464,9 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
420
464
  blockers,
421
465
  });
422
466
  const readyForExplicitCommit = blockers.length === 0;
467
+ const boundArtifacts = finalRowsArtifact
468
+ ? [finalRowsArtifact, ...(native ? [native.artifact] : []), ...(reference?.artifacts ?? [])]
469
+ : [];
423
470
  const report = {
424
471
  schema_version: 1,
425
472
  generated_at_utc: nowIso(),
@@ -443,17 +490,23 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
443
490
  account_mode: accountMode,
444
491
  expected_state_code: stateCode || null,
445
492
  expected_state_code_source: stateCodeSource,
493
+ ...(native ? { execution_contract: native.metadata } : {}),
494
+ ...(reference ? { reference_intent: reference.metadata } : {}),
446
495
  account_write_guard: {
447
496
  target_user_id_required: true,
448
497
  target_user_id: targetUserId || null,
449
498
  commit_command_supports_target_user_id: commitSupportsTargetUserId,
450
- commit_account_binding: commitSupportsTargetUserId
451
- ? "target_user_id_cli_argument"
452
- : "current_cli_auth_session",
499
+ commit_account_binding: native
500
+ ? "native_execution_contract"
501
+ : commitSupportsTargetUserId
502
+ ? "target_user_id_cli_argument"
503
+ : "current_cli_auth_session",
453
504
  verify_account_binding: "target_user_id_cli_argument",
454
- execution_precondition: commitSupportsTargetUserId
455
- ? "Run the commit command with the target-user-id argument emitted in this plan."
456
- : "Run the commit command only in a CLI session authenticated as the recorded target_user_id; this published CLI commit command does not accept --target-user-id.",
505
+ execution_precondition: native
506
+ ? "Run only the exact native execution contract under its matching owner/project session; the CLI owns persistent attempt and readback-only recovery."
507
+ : commitSupportsTargetUserId
508
+ ? "Run the commit command with the target-user-id argument emitted in this plan."
509
+ : "Run the commit command only in a CLI session authenticated as the recorded target_user_id; this published CLI commit command does not accept --target-user-id.",
457
510
  },
458
511
  policy: {
459
512
  commit_boundary: "This plan does not write the database. An approved runner must execute the authoritative commit CommandSpec, then the post_write_verify CommandSpec, without a shell.",
@@ -482,14 +535,14 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
482
535
  ? createFoundryCommandSpec({
483
536
  executable: commitArgs[0],
484
537
  argv: commitArgs.slice(1),
485
- binding: { artifacts: [finalRowsArtifact] },
538
+ binding: { artifacts: boundArtifacts },
486
539
  })
487
540
  : null,
488
541
  post_write_verify: readyForExplicitCommit && finalRowsArtifact
489
542
  ? createFoundryCommandSpec({
490
543
  executable: verifyArgs[0],
491
544
  argv: verifyArgs.slice(1),
492
- binding: { artifacts: [finalRowsArtifact] },
545
+ binding: { artifacts: boundArtifacts },
493
546
  })
494
547
  : null,
495
548
  },
@@ -500,6 +553,8 @@ export function createCommitHandoffCommands({ executionEnvironment = process.env
500
553
  },
501
554
  };
502
555
  const reportPath = path.join(outDir, "dataset-commit-handoff-plan.json");
556
+ if (native || reference)
557
+ reserveNativeHandoffDirectory(outDir);
503
558
  writeJson(reportPath, report);
504
559
  return {
505
560
  ...report,
@@ -0,0 +1,12 @@
1
+ type Options = Record<string, unknown>;
2
+ /** Input selection only. The CLI owns dimensional QA and exact-reference eligibility. */
3
+ export declare function selectFinalizeReferenceInputs(input: {
4
+ options: Options;
5
+ datasetType: string;
6
+ verifyRemote: boolean;
7
+ resolveFile: (value: unknown) => string | null;
8
+ }): {
9
+ qaFiles: string[];
10
+ intentFile: string | null;
11
+ };
12
+ export {};
@@ -0,0 +1,57 @@
1
+ import fs from "node:fs";
2
+ function invalid(option, message) {
3
+ throw new Error(`${option}: ${message}`);
4
+ }
5
+ function selectedFile(value, option, resolve) {
6
+ if (typeof value !== "string" || !value.trim())
7
+ invalid(option, "Select an explicit non-empty file path.");
8
+ const file = resolve(value);
9
+ try {
10
+ if (!file || !fs.lstatSync(file).isFile())
11
+ invalid(option, "Select a readable regular file.");
12
+ fs.accessSync(file, fs.constants.R_OK);
13
+ }
14
+ catch {
15
+ invalid(option, "The explicitly selected file is missing or is not a readable regular file.");
16
+ }
17
+ return file;
18
+ }
19
+ /** Input selection only. The CLI owns dimensional QA and exact-reference eligibility. */
20
+ export function selectFinalizeReferenceInputs(input) {
21
+ if (Object.keys(input.options).some((key) => key.startsWith("referenceIntent") && key !== "referenceIntentFile"))
22
+ invalid("--reference-intent-file", "Unsupported reference intent selection.");
23
+ let qaFiles = [];
24
+ if (Object.hasOwn(input.options, "qaReferenceRows")) {
25
+ if (input.datasetType !== "process")
26
+ invalid("--qa-reference-rows", "Explicit unit evidence belongs to Process QA.");
27
+ const selected = Array.isArray(input.options.qaReferenceRows)
28
+ ? input.options.qaReferenceRows
29
+ : [input.options.qaReferenceRows];
30
+ if (!selected.length)
31
+ invalid("--qa-reference-rows", "Select at least one reference-row file.");
32
+ qaFiles = [
33
+ ...new Set(selected.map((file) => selectedFile(file, "--qa-reference-rows", input.resolveFile))),
34
+ ];
35
+ }
36
+ let intentFile = null;
37
+ if (Object.hasOwn(input.options, "referenceIntentFile")) {
38
+ if (!input.verifyRemote)
39
+ invalid("--reference-intent-file", "Explicit intent requires remote reference verification.");
40
+ intentFile = selectedFile(input.options.referenceIntentFile, "--reference-intent-file", input.resolveFile);
41
+ try {
42
+ const stat = fs.statSync(intentFile);
43
+ if (stat.size > 8 * 1024 * 1024)
44
+ invalid("--reference-intent-file", "Intent exceeds the 8 MiB selection limit.");
45
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(intentFile)));
46
+ if (!value ||
47
+ typeof value !== "object" ||
48
+ Array.isArray(value) ||
49
+ value.schema_version !== "dataset-exact-reference-intent.v1")
50
+ invalid("--reference-intent-file", "Select the supported CLI intent JSON object.");
51
+ }
52
+ catch {
53
+ invalid("--reference-intent-file", "Select a bounded valid CLI intent JSON object.");
54
+ }
55
+ }
56
+ return { qaFiles, intentFile };
57
+ }
@@ -0,0 +1,28 @@
1
+ import { createFileArtifactFact } from "../foundry-command-spec.ts";
2
+ type RecordValue = Record<string, unknown>;
3
+ type Fact = ReturnType<typeof createFileArtifactFact>;
4
+ export declare function assertReferenceIntentSelection(options: RecordValue): void;
5
+ export interface HandoffReferenceMetadata {
6
+ artifact: Fact;
7
+ precommit_artifact: Fact;
8
+ review_artifacts: Fact[];
9
+ actor_user_id: string;
10
+ project_ref: string;
11
+ consumers_sha256: string;
12
+ }
13
+ export declare function readHandoffReferenceEvidence(input: {
14
+ finalize: RecordValue;
15
+ options: RecordValue;
16
+ rowsFile: string | null;
17
+ datasetType: string;
18
+ targetUserId: string;
19
+ projectRef: string;
20
+ resolveFile: (value: unknown) => string | null;
21
+ relativePath: (file: string) => string;
22
+ }): {
23
+ metadata: HandoffReferenceMetadata;
24
+ artifacts: import("@tiangong-lca/cli/command-spec").FoundryArtifactFact[];
25
+ intentFile: string;
26
+ rows_sha256: string;
27
+ } | null;
28
+ export {};
@@ -0,0 +1,115 @@
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 { readRows } from "../import-curation/internal/runtime-io.js";
6
+ import { datasetIdentity, detectDatasetType } from "../import-curation/internal/dataset-payload.js";
7
+ import { bundleRowTypes } from "../bundle-row-types.js";
8
+ function requireBinding(condition) {
9
+ if (!condition)
10
+ throw new Error("--reference-intent-file: current precommit, consumer, intent and review evidence must match.");
11
+ }
12
+ function object(value) {
13
+ requireBinding(value && typeof value === "object" && !Array.isArray(value));
14
+ return value;
15
+ }
16
+ export function assertReferenceIntentSelection(options) {
17
+ requireBinding(!Object.keys(options).some((key) => key.startsWith("referenceIntent") && key !== "referenceIntentFile"));
18
+ if (Object.hasOwn(options, "referenceIntentFile"))
19
+ requireBinding(typeof options.referenceIntentFile === "string" && options.referenceIntentFile.trim());
20
+ }
21
+ export function readHandoffReferenceEvidence(input) {
22
+ assertReferenceIntentSelection(input.options);
23
+ const resolve = (value) => {
24
+ const file = input.resolveFile(value);
25
+ return file ? path.resolve(file) : null;
26
+ };
27
+ const files = input.finalize.files;
28
+ const precommitFile = files && typeof files === "object"
29
+ ? resolve(files.remote_verify_report)
30
+ : null;
31
+ if (!precommitFile) {
32
+ requireBinding(!Object.hasOwn(input.options, "referenceIntentFile") &&
33
+ !Object.hasOwn(input.finalize, "reference_intent_file"));
34
+ return null;
35
+ }
36
+ const precommit = object(JSON.parse(fs.readFileSync(precommitFile, "utf8")));
37
+ if (!Object.hasOwn(precommit, "reference_intent")) {
38
+ requireBinding(!Object.hasOwn(input.options, "referenceIntentFile") &&
39
+ !Object.hasOwn(input.finalize, "reference_intent_file"));
40
+ return null;
41
+ }
42
+ const binding = object(precommit.reference_intent);
43
+ requireBinding(input.rowsFile &&
44
+ precommit.status === "passed_remote_verification" &&
45
+ object(precommit.counts).blockers === 0 &&
46
+ Array.isArray(precommit.blockers) &&
47
+ precommit.blockers.length === 0 &&
48
+ resolve(precommit.input_path) === resolve(input.rowsFile));
49
+ const capture = (raw, role) => {
50
+ const expected = object(raw), file = resolve(expected.path);
51
+ requireBinding(file && fs.lstatSync(file).isFile());
52
+ const fact = createFileArtifactFact({ role, path: input.relativePath(file), filePath: file });
53
+ requireBinding(fact.sha256 === expected.sha256 && fact.bytes === expected.bytes);
54
+ return fact;
55
+ };
56
+ const artifact = capture(binding.file, "reference_intent");
57
+ if (Object.hasOwn(input.finalize, "reference_intent_file"))
58
+ requireBinding(resolve(input.finalize.reference_intent_file) === resolve(artifact.path));
59
+ if (Object.hasOwn(input.options, "referenceIntentFile"))
60
+ requireBinding(resolve(input.options.referenceIntentFile) === resolve(artifact.path));
61
+ requireBinding(binding.actor_user_id === input.targetUserId &&
62
+ typeof binding.project_ref === "string" &&
63
+ (!input.projectRef || binding.project_ref === input.projectRef));
64
+ const rowText = fs.readFileSync(input.rowsFile, "utf8"), rows = readRows(input.rowsFile, () => rowText);
65
+ const consumers = rows.map((row, row_index) => {
66
+ const type = detectDatasetType(row, input.datasetType);
67
+ requireBinding(Object.hasOwn(bundleRowTypes, type));
68
+ const identity = datasetIdentity(row, row_index, type);
69
+ return {
70
+ row_index,
71
+ table: bundleRowTypes[type].plural,
72
+ id: identity.id.toLowerCase(),
73
+ version: identity.version,
74
+ payload_sha256: sha256Json(identity.payload),
75
+ };
76
+ });
77
+ requireBinding(rows.length > 0 &&
78
+ object(precommit.counts).rows === rows.length &&
79
+ sha256Json(binding.consumers) === sha256Json(consumers));
80
+ requireBinding(Array.isArray(binding.review_files) &&
81
+ binding.review_files.length > 0 &&
82
+ Array.isArray(binding.references) &&
83
+ binding.references.length > 0);
84
+ const reviewArtifacts = binding.review_files.map((fact) => capture(fact, "reference_review"));
85
+ requireBinding(new Set(reviewArtifacts.map((fact) => resolve(fact.path))).size === reviewArtifacts.length);
86
+ const usedReviews = new Set();
87
+ for (const raw of binding.references) {
88
+ const review = object(object(raw).review), fact = object(review.file);
89
+ const matching = reviewArtifacts.filter((candidate) => resolve(candidate.path) === resolve(fact.path) &&
90
+ candidate.sha256 === fact.sha256 &&
91
+ candidate.bytes === fact.bytes);
92
+ requireBinding(matching.length === 1);
93
+ usedReviews.add(resolve(matching[0].path));
94
+ }
95
+ requireBinding(usedReviews.size === reviewArtifacts.length);
96
+ const precommitArtifact = createFileArtifactFact({
97
+ role: "reference_precommit",
98
+ path: input.relativePath(precommitFile),
99
+ filePath: precommitFile,
100
+ });
101
+ const metadata = {
102
+ artifact,
103
+ precommit_artifact: precommitArtifact,
104
+ review_artifacts: reviewArtifacts,
105
+ actor_user_id: input.targetUserId,
106
+ project_ref: binding.project_ref,
107
+ consumers_sha256: sha256Json(consumers),
108
+ };
109
+ return {
110
+ metadata,
111
+ artifacts: [artifact, precommitArtifact, ...reviewArtifacts],
112
+ intentFile: resolve(artifact.path),
113
+ rows_sha256: sha256Text(rowText),
114
+ };
115
+ }
@@ -0,0 +1,13 @@
1
+ type JsonRecord = Record<string, unknown>;
2
+ export declare function validateNativeInsertCloseout(input: {
3
+ handoff: JsonRecord;
4
+ report: JsonRecord;
5
+ rowsFile: string;
6
+ datasetType: string;
7
+ targetUserId: string;
8
+ stateCode: string;
9
+ expectedRows: number;
10
+ resolveFile: (value: unknown) => string | null;
11
+ relativePath: (file: string) => string;
12
+ }): boolean;
13
+ export {};
@@ -0,0 +1,99 @@
1
+ import path from "node:path";
2
+ import { parseFoundryCommandSpec } from "../foundry-command-spec.js";
3
+ import { sha256Json } from "../identity-preflight-proof.js";
4
+ import { readNativeInsertHandoff } from "./native-insert-handoff.js";
5
+ function requireEvidence(condition) {
6
+ if (!condition)
7
+ throw new Error("Native insert completion evidence is missing or inconsistent.");
8
+ }
9
+ function object(value) {
10
+ requireEvidence(value && typeof value === "object" && !Array.isArray(value));
11
+ return value;
12
+ }
13
+ export function validateNativeInsertCloseout(input) {
14
+ const resolveFile = (value) => {
15
+ const file = input.resolveFile(value);
16
+ return file ? path.resolve(file) : null;
17
+ };
18
+ if (!Object.hasOwn(input.handoff, "execution_contract")) {
19
+ requireEvidence(!Object.hasOwn(input.report, "execution_contract"));
20
+ return false;
21
+ }
22
+ const binding = object(input.handoff.execution_contract);
23
+ const artifact = object(binding.artifact);
24
+ const contractFile = resolveFile(artifact.path);
25
+ requireEvidence(contractFile && binding.operation === "insert");
26
+ const native = readNativeInsertHandoff({
27
+ contractFile,
28
+ rowsFile: input.rowsFile,
29
+ datasetType: input.datasetType,
30
+ targetUserId: input.targetUserId,
31
+ verifiedProjectRef: String(input.handoff.verified_project_ref ?? ""),
32
+ stateCode: input.stateCode,
33
+ relativePath: input.relativePath,
34
+ });
35
+ requireEvidence(sha256Json(artifact) === sha256Json(native.artifact) &&
36
+ binding.canonical_sha256 === native.canonical_sha256 &&
37
+ binding.execution_id === native.contract.execution_id &&
38
+ binding.project_ref === native.contract.project_ref);
39
+ const rowsArtifact = object(input.handoff.final_rows_artifact);
40
+ requireEvidence(rowsArtifact.sha256 === native.rows_sha256);
41
+ const commands = object(input.handoff.commands);
42
+ for (const key of ["commit", "post_write_verify"]) {
43
+ const spec = parseFoundryCommandSpec(commands[key]);
44
+ for (const expected of [artifact, rowsArtifact]) {
45
+ const matching = spec.binding.artifacts.filter((fact) => resolveFile(fact.path) === resolveFile(expected.path));
46
+ requireEvidence(matching.length === 1 &&
47
+ matching[0].sha256 === expected.sha256 &&
48
+ matching[0].bytes === expected.bytes);
49
+ }
50
+ if (key === "commit") {
51
+ const positions = spec.argv.flatMap((value, index) => value === "--execution-contract" ? [index] : []);
52
+ requireEvidence(positions.length === 1 && resolveFile(spec.argv[positions[0] + 1]) === contractFile);
53
+ const typeFlag = spec.argv.indexOf("--type");
54
+ requireEvidence(typeFlag >= 2 &&
55
+ spec.argv[typeFlag - 2] === "dataset" &&
56
+ spec.argv[typeFlag - 1] === "save-draft" &&
57
+ spec.argv[typeFlag + 1] === input.datasetType);
58
+ }
59
+ }
60
+ const report = input.report;
61
+ const contractReport = object(report.execution_contract);
62
+ const counts = object(report.counts);
63
+ const actions = native.contract.actions;
64
+ requireEvidence(actions.length === input.expectedRows && input.expectedRows > 0);
65
+ requireEvidence(report.schema_version === 2 &&
66
+ report.mode === "commit" &&
67
+ report.commit === true &&
68
+ report.status === "completed" &&
69
+ report.requested_type === input.datasetType &&
70
+ resolveFile(report.input_path) === resolveFile(input.rowsFile) &&
71
+ resolveFile(contractReport.path) === contractFile &&
72
+ contractReport.sha256 === native.canonical_sha256 &&
73
+ contractReport.execution_id === native.contract.execution_id &&
74
+ contractReport.target_mode === "owner_draft" &&
75
+ counts.selected === actions.length &&
76
+ counts.executed === actions.length &&
77
+ counts.attempts_consumed === actions.length &&
78
+ counts.failed === 0 &&
79
+ counts.unknown === 0 &&
80
+ counts.blocked === 0 &&
81
+ Array.isArray(report.rows) &&
82
+ report.rows.length === actions.length);
83
+ for (const [index, action] of actions.entries()) {
84
+ const row = object(report.rows[index]);
85
+ requireEvidence(row.index === index &&
86
+ row.type === input.datasetType &&
87
+ row.table === action.table &&
88
+ row.id === action.id &&
89
+ row.version === action.version &&
90
+ row.action_id === action.action_id &&
91
+ row.desired_sha256 === action.desired_sha256 &&
92
+ row.status === "executed" &&
93
+ row.operation === "insert" &&
94
+ row.attempt_consumed === true &&
95
+ row.replayed === false &&
96
+ row.readback === "desired_exact");
97
+ }
98
+ return true;
99
+ }
@@ -0,0 +1,47 @@
1
+ type JsonRecord = Record<string, unknown>;
2
+ export declare function assertExecutionContractSelection(options: JsonRecord): void;
3
+ /** Consumer admission only; CLI owns parsing at execution, attempts and readback. */
4
+ export declare function readNativeInsertHandoff(input: {
5
+ contractFile: string;
6
+ rowsFile: string;
7
+ datasetType: string;
8
+ targetUserId: string;
9
+ verifiedProjectRef: string;
10
+ stateCode: string;
11
+ relativePath: (file: string) => string;
12
+ }): {
13
+ artifact: import("@tiangong-lca/cli/command-spec").FoundryArtifactFact;
14
+ contract: {
15
+ schema_version: string;
16
+ execution_id: string;
17
+ project_ref: string;
18
+ target_mode: string;
19
+ owner: {
20
+ user_id: string;
21
+ email: string;
22
+ state_code: number;
23
+ };
24
+ actions: {
25
+ action_id: string;
26
+ desired_sha256: string;
27
+ expected_operation: "insert";
28
+ table: string;
29
+ id: string;
30
+ version: string;
31
+ before_sha256: null;
32
+ dependency_action_ids: string[];
33
+ }[];
34
+ };
35
+ canonical_sha256: string;
36
+ metadata: {
37
+ artifact: import("@tiangong-lca/cli/command-spec").FoundryArtifactFact;
38
+ canonical_sha256: string;
39
+ execution_id: string;
40
+ project_ref: string;
41
+ operation: string;
42
+ };
43
+ rows_sha256: string;
44
+ };
45
+ export declare function reserveNativeHandoffDirectory(directory: string): void;
46
+ export declare function nativeInsertCommitArguments(prefix: readonly string[], datasetType: string, rowsFile: string, outDir: string, contractFile: string): string[];
47
+ export {};