@tiangong-lca/foundry 0.1.9 → 0.1.11

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 (107) hide show
  1. package/README.md +13 -11
  2. package/docs/architecture.md +12 -10
  3. package/docs/foundry-task-contracts.md +16 -4
  4. package/docs/import-profiles/bafu/constraints.md +1 -1
  5. package/docs/import-profiles/bafu/profile.md +1 -1
  6. package/docs/import-profiles/worldsteel/constraints.md +3 -3
  7. package/docs/import-profiles/worldsteel/import-coverage.md +3 -3
  8. package/docs/import-profiles/worldsteel/import-plan.md +4 -4
  9. package/docs/import-profiles/worldsteel/profile.md +3 -3
  10. package/docs/package-distribution-contract.md +11 -9
  11. package/docs/public-runtime-contract.md +31 -9
  12. package/docs/runtime-context-contract.md +7 -5
  13. package/docs/task-authorization-contract.md +5 -3
  14. package/package-dist/assets/foundry-package-descriptor.json +300 -154
  15. package/package-dist/scripts/foundry-facade.d.ts +1 -0
  16. package/package-dist/scripts/foundry-facade.js +233 -28
  17. package/package-dist/scripts/foundry-runtime.d.ts +14 -3
  18. package/package-dist/scripts/foundry-runtime.js +2 -2
  19. package/package-dist/scripts/lib/finalize-owners/commit-handoff.js +3 -3
  20. package/package-dist/scripts/lib/finalize-owners/{native-insert-closeout.d.ts → native-draft-closeout.d.ts} +1 -1
  21. package/package-dist/scripts/lib/finalize-owners/{native-insert-closeout.js → native-draft-closeout.js} +10 -6
  22. package/package-dist/scripts/lib/finalize-owners/{native-insert-handoff.d.ts → native-draft-handoff.d.ts} +7 -5
  23. package/package-dist/scripts/lib/finalize-owners/{native-insert-handoff.js → native-draft-handoff.js} +30 -11
  24. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.js +2 -2
  25. package/package-dist/scripts/lib/foundry-authorization-input.d.ts +10 -1
  26. package/package-dist/scripts/lib/foundry-authorization-input.js +27 -3
  27. package/package-dist/scripts/lib/foundry-command-metadata.js +25 -2
  28. package/package-dist/scripts/lib/foundry-command-registry.d.ts +4 -4
  29. package/package-dist/scripts/lib/foundry-command-registry.js +3 -0
  30. package/package-dist/scripts/lib/foundry-execution-admission.js +3 -3
  31. package/package-dist/scripts/lib/foundry-facade-store.js +56 -6
  32. package/package-dist/scripts/lib/foundry-interaction-input.d.ts +19 -0
  33. package/package-dist/scripts/lib/foundry-interaction-input.js +327 -0
  34. package/package-dist/scripts/lib/foundry-interaction-projection.d.ts +22 -0
  35. package/package-dist/scripts/lib/foundry-interaction-projection.js +81 -0
  36. package/package-dist/scripts/lib/foundry-interaction-types.d.ts +17 -0
  37. package/package-dist/scripts/lib/foundry-interaction-types.js +4 -0
  38. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +33 -16
  39. package/package-dist/scripts/lib/foundry-owner-execution-store.js +66 -5
  40. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +3 -0
  41. package/package-dist/scripts/lib/foundry-owner-readback.js +101 -27
  42. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  43. package/package-dist/scripts/lib/foundry-package-contract.js +4 -2
  44. package/package-dist/scripts/lib/foundry-repair-execution.d.ts +11 -0
  45. package/package-dist/scripts/lib/foundry-repair-execution.js +70 -0
  46. package/package-dist/scripts/lib/foundry-repair-handoff.d.ts +16 -0
  47. package/package-dist/scripts/lib/foundry-repair-handoff.js +108 -0
  48. package/package-dist/scripts/lib/foundry-repair-preflight.d.ts +96 -0
  49. package/package-dist/scripts/lib/foundry-repair-preflight.js +313 -0
  50. package/package-dist/scripts/lib/foundry-repair-reference-binding.d.ts +26 -0
  51. package/package-dist/scripts/lib/foundry-repair-reference-binding.js +120 -0
  52. package/package-dist/scripts/lib/foundry-repair-reference-proof.d.ts +63 -0
  53. package/package-dist/scripts/lib/foundry-repair-reference-proof.js +329 -0
  54. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +76 -0
  55. package/package-dist/scripts/lib/foundry-repair-scope.js +304 -0
  56. package/package-dist/scripts/lib/foundry-runtime-command-policy.js +1 -0
  57. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  58. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +3 -0
  59. package/package-dist/scripts/lib/foundry-runtime-utils.js +6 -1
  60. package/package-dist/scripts/lib/foundry-semantic-input.d.ts +2 -0
  61. package/package-dist/scripts/lib/foundry-semantic-input.js +29 -2
  62. package/package-dist/scripts/lib/foundry-semantic-interaction.d.ts +12 -0
  63. package/package-dist/scripts/lib/foundry-semantic-interaction.js +38 -0
  64. package/package-dist/scripts/lib/foundry-successor-predecessor.d.ts +36 -0
  65. package/package-dist/scripts/lib/foundry-successor-predecessor.js +399 -0
  66. package/package-dist/scripts/lib/foundry-task-registration.js +64 -3
  67. package/package-dist/scripts/lib/foundry-task-start-spec.d.ts +14 -0
  68. package/package-dist/scripts/lib/foundry-task-start-spec.js +60 -1
  69. package/package-dist/scripts/lib/foundry-task-store.d.ts +13 -1
  70. package/package-dist/scripts/lib/foundry-task-store.js +23 -12
  71. package/package-dist/scripts/lib/foundry-task-types.d.ts +22 -1
  72. package/package-dist/scripts/lib/foundry-tidas-source.d.ts +15 -0
  73. package/package-dist/scripts/lib/foundry-tidas-source.js +90 -0
  74. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +7 -1
  75. package/package-dist/scripts/lib/foundry-workflow-assessment.js +127 -6
  76. package/package-dist/scripts/lib/foundry-workflow-authorization.d.ts +2 -1
  77. package/package-dist/scripts/lib/foundry-workflow-authorization.js +194 -26
  78. package/package-dist/scripts/lib/foundry-workflow-context.js +4 -0
  79. package/package-dist/scripts/lib/foundry-workflow-execution.js +6 -1
  80. package/package-dist/scripts/lib/foundry-workflow-finalize.js +7 -4
  81. package/package-dist/scripts/lib/foundry-workflow-interaction.d.ts +4 -0
  82. package/package-dist/scripts/lib/foundry-workflow-interaction.js +63 -0
  83. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +36 -0
  84. package/package-dist/scripts/lib/foundry-workflow-repair.js +580 -0
  85. package/package-dist/scripts/lib/foundry-workflow-semantic.js +21 -1
  86. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +9 -1
  87. package/package-dist/scripts/lib/foundry-workflow-state.js +239 -39
  88. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -8
  89. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  90. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.d.ts +13 -2
  91. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.js +100 -29
  92. package/package-dist/scripts/lib/import-curation/internal/workflow-authoring-tasks.js +1 -2
  93. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-collect.js +2 -3
  94. package/package-dist/scripts/lib/import-curation/internal/workflow-queue-context.js +8 -8
  95. package/package-dist/scripts/lib/import-curation/internal/workflow-semantic-actions.js +12 -2
  96. package/package-dist/scripts/public-api.d.ts +2 -0
  97. package/package-dist/scripts/public-api.js +1 -0
  98. package/package-dist/scripts/runtime-entry.js +9 -1
  99. package/package.json +3 -2
  100. package/specs/import-profiles.json +1 -1
  101. package/specs/schemas/foundry-authorization-input.schema.json +45 -2
  102. package/specs/schemas/foundry-interaction-input.schema.json +173 -0
  103. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  104. package/specs/schemas/foundry-package-descriptor.schema.json +3 -2
  105. package/specs/schemas/foundry-semantic-input.schema.json +12 -1
  106. package/specs/schemas/foundry-task-start.schema.json +275 -19
  107. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -8,6 +8,41 @@ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoun
8
8
  import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
9
9
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
10
10
  import { sha256Json } from "./identity-preflight-proof.js";
11
+ import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
12
+ import { currentFoundryQuestions, currentFoundryInvestigations, foundryInteractionScopeApplies, } from "./foundry-interaction-projection.js";
13
+ function assertOwnerInteractionReady(context, entries, datasetType, repairScope) {
14
+ if (repairScope)
15
+ return;
16
+ const state = currentWorkflowState(context, entries);
17
+ if (!state.assessmentComplete)
18
+ throw new FoundryContextError("execution_assessment_incomplete", "Owner execution requires complete current assessment coverage.");
19
+ const interaction = currentFoundryInteractionState(context, entries);
20
+ if (interaction &&
21
+ [
22
+ ...currentFoundryQuestions(interaction.state),
23
+ ...currentFoundryInvestigations(interaction.state),
24
+ ].some((question) => foundryInteractionScopeApplies(question.dataset_type, datasetType)))
25
+ throw new FoundryContextError("interaction_decision_pending", "An applicable question or investigation remains unresolved before owner execution.");
26
+ }
27
+ /**
28
+ * The finalization and mutation evidence a sealed owner scope must retain. Only the registered repair
29
+ * scope — the repair kind whose handoff declares `repair_scope: true` — has neither; any other sealed
30
+ * scope that lost one is refused rather than prepared.
31
+ */
32
+ export function ownerExecutionScopeFiles(assetRoot, authorizationValue, handoff) {
33
+ const repairScope = authorizationValue.input_kind === "repair_rows" && handoff.repair_scope === true;
34
+ const file = (value, label) => {
35
+ if (typeof value === "string" && value)
36
+ return path.resolve(assetRoot, value);
37
+ if (repairScope)
38
+ return null;
39
+ throw new FoundryContextError("execution_request_invalid", `A sealed owner scope must retain its ${label}.`);
40
+ };
41
+ return Object.freeze({
42
+ finalize_file: file(handoff.finalize_report, "finalization report"),
43
+ mutation_file: file(handoff.mutation_manifest, "mutation manifest"),
44
+ });
45
+ }
11
46
  function buildRequest(context, authorization) {
12
47
  const value = authorization.value, input = workflowObject(value.input), capsule = workflowObject(value.capsule), handoff = workflowObject(value.handoff);
13
48
  if (value.status !== "sealed" ||
@@ -39,6 +74,9 @@ function buildRequest(context, authorization) {
39
74
  state_code: 0,
40
75
  dataset_type: value.dataset_type,
41
76
  account_mode: String(handoff.account_mode ?? "ordinary"),
77
+ ...(value.input_kind === "repair_rows" && handoff.repair_scope === true
78
+ ? { repair_scope: true }
79
+ : {}),
42
80
  };
43
81
  const projection = JSON.parse(JSON.stringify(content));
44
82
  const contract = createBatchContract({
@@ -55,8 +93,7 @@ function buildRequest(context, authorization) {
55
93
  contract,
56
94
  item_contract: itemContract,
57
95
  handoff_file: path.resolve(context.assetRoot, String(workflowObject(handoff.files).report)),
58
- finalize_file: path.resolve(context.assetRoot, String(handoff.finalize_report)),
59
- mutation_file: path.resolve(context.assetRoot, String(handoff.mutation_manifest)),
96
+ ...ownerExecutionScopeFiles(context.assetRoot, value, handoff),
60
97
  };
61
98
  }
62
99
  export async function prepareFoundryOwnerExecution(context, entries) {
@@ -64,12 +101,15 @@ export async function prepareFoundryOwnerExecution(context, entries) {
64
101
  if (!approval || approval.value.status !== "sealed")
65
102
  throw new FoundryContextError("execution_approval_required", "A current sealed approval is required.");
66
103
  const request = buildRequest(context, approval);
104
+ assertOwnerInteractionReady(context, entries, request.policy.dataset_type, request.policy.repair_scope === true);
67
105
  return runFoundryTaskOperation(context, {
68
106
  command: "dataset-workflow-execution-prepare",
69
107
  options: { authorization: approval.entry.sha256 },
70
108
  validateCurrent(index) {
71
- if (currentWorkflowState(context, index).authorization?.entry.sha256 !== approval.entry.sha256)
109
+ const latest = currentWorkflowState(context, index);
110
+ if (latest.authorization?.entry.sha256 !== approval.entry.sha256)
72
111
  throw new FoundryContextError("execution_approval_changed", "Approval changed before execution preparation.");
112
+ assertOwnerInteractionReady(context, index, request.policy.dataset_type, request.policy.repair_scope === true);
73
113
  },
74
114
  }, (operation) => {
75
115
  operation.writeJson(`outputs/execution-requests/${request.scope_id}/${approval.entry.sha256}/owner-execution-request.json`, request);
@@ -175,7 +215,20 @@ export async function markOwnerAttemptConsumed(context, artifact) {
175
215
  item_contract: artifact.request.item_contract,
176
216
  attempts: 1,
177
217
  };
178
- return runFoundryTaskOperation(context, { command: "dataset-workflow-execution-consume", options: { request: artifact.entry.sha256 } }, (operation) => {
218
+ return runFoundryTaskOperation(context, {
219
+ command: "dataset-workflow-execution-consume",
220
+ options: { request: artifact.entry.sha256 },
221
+ validateCurrent(index) {
222
+ const current = readOwnerExecutionRequests(context, index);
223
+ if (!current.some((item) => item.entry.sha256 === artifact.entry.sha256))
224
+ throw new FoundryContextError("execution_request_changed", "The owner request changed before its attempt was consumed.");
225
+ assertOwnerInteractionReady(context, index, artifact.request.policy.dataset_type, artifact.request.policy.repair_scope === true);
226
+ if (artifact.request.policy.repair_scope !== true &&
227
+ currentWorkflowState(context, index).authorization?.entry.sha256 !==
228
+ artifact.request.content.authorization)
229
+ throw new FoundryContextError("execution_approval_changed", "Approval changed before the owner attempt was consumed.");
230
+ },
231
+ }, (operation) => {
179
232
  operation.writeJson(`attempts/owner-v1/${artifact.request.scope_id}/consumed.json`, value);
180
233
  return value;
181
234
  });
@@ -281,7 +334,15 @@ export function inspectOwnerExecutions(context, entries) {
281
334
  const fact = workflowObject(raw);
282
335
  if (typeof fact.path !== "string")
283
336
  throw new FoundryContextError("execution_result_invalid", "Readback content fact is missing.");
284
- resolveFoundryOutput(context, fact.path);
337
+ if (item.request.policy.repair_scope === true && raw === proof.input) {
338
+ if (fact.path !== item.request.content.input.path ||
339
+ fact.sha256 !== item.request.content.input.sha256 ||
340
+ fact.bytes !== item.request.content.input.bytes)
341
+ throw new FoundryContextError("execution_result_invalid", "Repair readback input must equal the registered source candidate.");
342
+ readFoundryInput(context, fact.path);
343
+ }
344
+ else
345
+ resolveFoundryOutput(context, fact.path);
285
346
  const current = captureFoundryInput(fact.path);
286
347
  if (current.sha256 !== fact.sha256 || current.bytes !== fact.bytes)
287
348
  throw new FoundryContextError("execution_result_changed", "Recorded execution readback evidence changed.");
@@ -19,6 +19,9 @@ export declare function readbackFoundryOwner(context: FoundryRuntimeContext, qua
19
19
  checks: import("./foundry-runtime-context-types.ts").FoundryInputFact | null;
20
20
  };
21
21
  acceptance: import("./foundry-runtime-context-types.ts").FoundryInputFact | null;
22
+ repair_preparation?: import("./foundry-runtime-context-types.ts").FoundryInputFact | undefined;
23
+ publication_ready?: boolean | undefined;
24
+ retained_reference_integrity?: import("./foundry-repair-reference-proof.ts").FoundryRepairReferenceProof | null | undefined;
22
25
  blockers: Record<string, unknown>[];
23
26
  };
24
27
  }>;
@@ -1,4 +1,8 @@
1
+ import { proveFoundryRepairRemoteIntegrity } from "./foundry-repair-reference-binding.js";
1
2
  import fs from "node:fs";
3
+ import { assertFoundryRepairExecution } from "./foundry-repair-execution.js";
4
+ import { withFoundryTaskMetadata } from "./foundry-task-store.js";
5
+ import { validateNativeDraftCloseout } from "./finalize-owners/native-draft-closeout.js";
2
6
  import path from "node:path";
3
7
  import { spawnSync } from "node:child_process";
4
8
  import { randomUUID } from "node:crypto";
@@ -13,13 +17,14 @@ import { createFoundryFinalizeOwners } from "./foundry-finalize-owners.js";
13
17
  import { canonicalPayloadSha256 } from "./post-write-root-proof.js";
14
18
  import { normalizeAllowedTraceHashDifference } from "./remote-verification-accepted-diff.js";
15
19
  import { datasetIdentity, unwrapDatasetPayload, } from "./import-curation/internal/dataset-payload.js";
16
- import { buildReferenceClosureBlockers } from "./import-curation/internal/workflow-reference-closure.js";
17
- import { readRows } from "./import-curation/internal/runtime-io.js";
20
+ import { buildReferenceClosureBlockers, referenceKey, } from "./import-curation/internal/workflow-reference-closure.js";
21
+ import { readRows, repoRelativePath } from "./import-curation/internal/runtime-io.js";
18
22
  import { bundleRowTypes } from "./bundle-row-types.js";
19
23
  import { workflowObject } from "./foundry-workflow-state.js";
20
24
  import { acceptFoundryOwnerTraceDifference } from "./foundry-owner-trace-acceptance.js";
21
25
  export async function readbackFoundryOwner(context, qualified, request, authentication = { mode: "oauth" }, commitReport) {
22
26
  assertQualifiedFoundryRuntime(context, qualified);
27
+ const repair = await withFoundryTaskMetadata(context, (_, entries) => assertFoundryRepairExecution(context, entries, request));
23
28
  const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
24
29
  if (identity.receipt.project.project_ref !== request.policy.project_ref ||
25
30
  identity.receipt.identity.user_id !== request.policy.user_id)
@@ -87,6 +92,10 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
87
92
  let report = {}, reportFile = null, checksFile = null;
88
93
  try {
89
94
  report = workflowObject(JSON.parse(result.stdout));
95
+ if (repair &&
96
+ (typeof report.input_path !== "string" ||
97
+ path.resolve(report.input_path) !== path.resolve(request.content.input.path)))
98
+ throw new Error("Repair readback report must name the exact selected candidate input.");
90
99
  const files = workflowObject(report.files);
91
100
  for (const name of ["report", "checks"]) {
92
101
  const file = typeof files[name] === "string" ? resolveFoundryOutput(context, files[name]) : null;
@@ -122,7 +131,8 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
122
131
  !result.signal &&
123
132
  // The published CLI uses exit 1 for a completed, blocked remote report.
124
133
  result.status === 1 &&
125
- request.policy.account_mode === "ordinary") {
134
+ request.policy.account_mode === "ordinary" &&
135
+ !repair) {
126
136
  const accepted = acceptFoundryOwnerTraceDifference(context, qualified, request, reportFile, output, environment);
127
137
  if (accepted.accepted) {
128
138
  reportFile = resolveFoundryOutput(context, accepted.verifyReportPath);
@@ -131,7 +141,41 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
131
141
  acceptance = captureFoundryInput(resolveFoundryOutput(context, accepted.acceptanceReportPath));
132
142
  }
133
143
  }
134
- if (result.error || result.signal || (result.status !== 0 && !acceptance))
144
+ let repairIntegrity = null;
145
+ if (repair &&
146
+ !blockers.length &&
147
+ reportFile &&
148
+ checksFile &&
149
+ !result.error &&
150
+ !result.signal &&
151
+ (result.status === 0 || result.status === 1)) {
152
+ try {
153
+ repairIntegrity = proveFoundryRepairRemoteIntegrity({
154
+ report,
155
+ checks: fs
156
+ .readFileSync(checksFile, "utf8")
157
+ .split(/\r?\n/u)
158
+ .filter((line) => line.trim())
159
+ .map((line) => JSON.parse(line)),
160
+ expectation: repair.expectation,
161
+ beforeRows: readRows(repair.beforeFile, (file) => readFoundryInput(context, file).toString("utf8")),
162
+ candidateRows: readRows(request.content.input.path, (file) => readFoundryInput(context, file).toString("utf8")),
163
+ content: "candidate",
164
+ });
165
+ if (result.status !== (repairIntegrity.retained_references ? 1 : 0))
166
+ throw new Error("Repair owner status and exit disagree.");
167
+ }
168
+ catch (error) {
169
+ repairIntegrity = null;
170
+ blockers.push({
171
+ code: "repair_reference_integrity_unproven",
172
+ message: error instanceof FoundryContextError
173
+ ? error.message
174
+ : "Repair reference evidence is invalid.",
175
+ });
176
+ }
177
+ }
178
+ if (result.error || result.signal || (result.status !== 0 && !acceptance && !repairIntegrity))
135
179
  blockers.push({ code: "readback_cli_failed", exit_code: result.status });
136
180
  if (!blockers.length && reportFile) {
137
181
  const rows = readRows(request.content.input.path).map((row) => unwrapDatasetPayload(row, request.policy.dataset_type));
@@ -156,18 +200,20 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
156
200
  environment,
157
201
  tidasExecutable: qualified.tidas.executable_path,
158
202
  });
159
- const rootProof = owners.closeout.validatePostWriteVerifyForCloseout({
160
- handoffPlan: JSON.parse(readFoundryInput(context, request.handoff_file).toString("utf8")),
161
- verifyReport: report,
162
- verifyReportPath: reportFile,
163
- finalRowsFile: request.content.input.path,
164
- expectedRows: rows.length,
165
- targetUserId: request.policy.user_id,
166
- expectedStateCode: 0,
167
- intendedRoots: intended,
168
- allowTraceHashOnlyNormalization: request.policy.account_mode !== "production-test",
169
- blockers,
170
- });
203
+ const rootProof = repair
204
+ ? { referenceArtifacts: [] }
205
+ : owners.closeout.validatePostWriteVerifyForCloseout({
206
+ handoffPlan: JSON.parse(readFoundryInput(context, request.handoff_file).toString("utf8")),
207
+ verifyReport: report,
208
+ verifyReportPath: reportFile,
209
+ finalRowsFile: request.content.input.path,
210
+ expectedRows: rows.length,
211
+ targetUserId: request.policy.user_id,
212
+ expectedStateCode: 0,
213
+ intendedRoots: intended,
214
+ allowTraceHashOnlyNormalization: !repair && request.policy.account_mode !== "production-test",
215
+ blockers,
216
+ });
171
217
  referenceFacts = (rootProof.referenceArtifacts ?? []).map(({ path, sha256, bytes }) => ({
172
218
  path,
173
219
  sha256,
@@ -179,20 +225,41 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
179
225
  datasetType: type,
180
226
  remoteVerifyArtifact: { value: report },
181
227
  allowAccountLocalSupportAndElementary: false,
228
+ ...(repairIntegrity?.retained_references
229
+ ? {
230
+ provenReferenceKeys: new Set(repairIntegrity.retained_references.outdated.map(referenceKey)),
231
+ }
232
+ : {}),
182
233
  }));
183
234
  if (commitReport) {
184
235
  try {
185
- const closed = workflowObject(owners.closeout.runDatasetPostWriteCloseout({
186
- handoffPlan: request.handoff_file,
187
- commitReport,
188
- postWriteVerifyReport: reportFile,
189
- rowsFile: request.content.input.path,
190
- finalizeReport: request.finalize_file,
191
- mutationManifest: request.mutation_file,
192
- outDir: path.join(output, "closeout"),
193
- targetUserId: request.policy.user_id,
194
- stateCode: "0",
195
- }));
236
+ const closed = repair
237
+ ? (() => {
238
+ if (!validateNativeDraftCloseout({
239
+ handoff: repair.handoff,
240
+ report: workflowObject(JSON.parse(fs.readFileSync(commitReport, "utf8"))),
241
+ rowsFile: request.content.input.path,
242
+ datasetType: request.policy.dataset_type,
243
+ targetUserId: request.policy.user_id,
244
+ stateCode: "0",
245
+ expectedRows: rows.length,
246
+ resolveFile: (value) => typeof value === "string" ? path.resolve(context.assetRoot, value) : null,
247
+ relativePath: (file) => repoRelativePath(context.assetRoot, file),
248
+ }))
249
+ throw new Error("Repair requires its consumed native contract receipt.");
250
+ return { status: "completed" };
251
+ })()
252
+ : workflowObject(owners.closeout.runDatasetPostWriteCloseout({
253
+ handoffPlan: request.handoff_file,
254
+ commitReport,
255
+ postWriteVerifyReport: reportFile,
256
+ rowsFile: request.content.input.path,
257
+ finalizeReport: request.finalize_file,
258
+ mutationManifest: request.mutation_file,
259
+ outDir: path.join(output, "closeout"),
260
+ targetUserId: request.policy.user_id,
261
+ stateCode: "0",
262
+ }));
196
263
  if (closed.status !== "completed")
197
264
  blockers.push({ code: "owner_closeout_blocked", report: closed });
198
265
  if (commitFact && captureFoundryInput(commitReport).sha256 !== commitFact.sha256)
@@ -229,6 +296,13 @@ export async function readbackFoundryOwner(context, qualified, request, authenti
229
296
  ...(referenceFacts.length ? { reference_evidence: referenceFacts } : {}),
230
297
  original_verification: original,
231
298
  acceptance,
299
+ ...(repair
300
+ ? {
301
+ repair_preparation: captureFoundryInput(repair.preparation.file),
302
+ publication_ready: false,
303
+ retained_reference_integrity: repairIntegrity?.retained_references ?? null,
304
+ }
305
+ : {}),
232
306
  blockers,
233
307
  };
234
308
  fs.writeFileSync(path.join(output, "owner-readback.json"), JSON.stringify(proof, null, 2) + "\n");
@@ -1,15 +1,15 @@
1
1
  export declare const FOUNDRY_PACKAGE_DESCRIPTOR_SCHEMA: "tiangong-foundry.package-descriptor.v1";
2
2
  export declare const foundryPackageDescriptorPath: "package-dist/assets/foundry-package-descriptor.json";
3
- export declare const foundryPackageStaticFiles: readonly ["package-dist/", "specs/import-profiles.json", "specs/prewrite-content-policy.json", "specs/canonical-support/flow-properties-unit-groups.json", "specs/schemas/authorization-derivation.schema.json", "specs/schemas/execution-context.schema.json", "specs/schemas/foundry-facade-request-index.schema.json", "specs/schemas/foundry-operation-result.schema.json", "specs/schemas/foundry-package-descriptor.schema.json", "specs/schemas/foundry-task-start.schema.json", "specs/schemas/foundry-semantic-input.schema.json", "specs/schemas/foundry-authorization-input.schema.json", "specs/schemas/foundry-reference-input.schema.json", "specs/schemas/foundry-workspace-migration-plan.schema.json", "specs/schemas/foundry-workspace-migration-transfer-plan.schema.json", "specs/schemas/foundry-migration-transfer-receipt.schema.json", "specs/schemas/foundry-workspace-migration-pending.schema.json", "specs/schemas/foundry-migration-adoption-plan.schema.json", "specs/schemas/foundry-migration-activation.schema.json", "specs/schemas/foundry-workspace-v2.schema.json", "specs/schemas/foundry-runtime-selection.schema.json", "specs/schemas/foundry-managed-runtime.schema.json", "specs/schemas/runtime-qualification.schema.json", "specs/schemas/task-authorization.schema.json", "specs/schemas/tidas-runtime-expectation.schema.json", "docs/architecture.md", "docs/package-distribution-contract.md", "docs/foundry-task-contracts.md", "docs/public-runtime-contract.md", "docs/runtime-context-contract.md", "docs/workspace-migration-contract.md", "docs/safety-policy.md", "docs/task-authorization-contract.md", "docs/import-profiles/bafu/constraints.md", "docs/import-profiles/bafu/leaf-process-classification-authoring.md", "docs/import-profiles/bafu/profile.md", "docs/import-profiles/uslci/constraints.md", "docs/import-profiles/uslci/profile.md", "docs/uslci-import-runbook.md", "docs/import-profiles/worldsteel/constraints.md", "docs/import-profiles/worldsteel/import-coverage.md", "docs/import-profiles/worldsteel/import-plan.md", "docs/import-profiles/worldsteel/profile.md", "README.md", "LICENSE"];
3
+ export declare const foundryPackageStaticFiles: readonly ["package-dist/", "specs/import-profiles.json", "specs/prewrite-content-policy.json", "specs/canonical-support/flow-properties-unit-groups.json", "specs/schemas/authorization-derivation.schema.json", "specs/schemas/execution-context.schema.json", "specs/schemas/foundry-facade-request-index.schema.json", "specs/schemas/foundry-operation-result.schema.json", "specs/schemas/foundry-package-descriptor.schema.json", "specs/schemas/foundry-task-start.schema.json", "specs/schemas/foundry-semantic-input.schema.json", "specs/schemas/foundry-interaction-input.schema.json", "specs/schemas/foundry-authorization-input.schema.json", "specs/schemas/foundry-reference-input.schema.json", "specs/schemas/foundry-workspace-migration-plan.schema.json", "specs/schemas/foundry-workspace-migration-transfer-plan.schema.json", "specs/schemas/foundry-migration-transfer-receipt.schema.json", "specs/schemas/foundry-workspace-migration-pending.schema.json", "specs/schemas/foundry-migration-adoption-plan.schema.json", "specs/schemas/foundry-migration-activation.schema.json", "specs/schemas/foundry-workspace-v2.schema.json", "specs/schemas/foundry-runtime-selection.schema.json", "specs/schemas/foundry-managed-runtime.schema.json", "specs/schemas/runtime-qualification.schema.json", "specs/schemas/task-authorization.schema.json", "specs/schemas/tidas-runtime-expectation.schema.json", "docs/architecture.md", "docs/package-distribution-contract.md", "docs/foundry-task-contracts.md", "docs/public-runtime-contract.md", "docs/runtime-context-contract.md", "docs/workspace-migration-contract.md", "docs/safety-policy.md", "docs/task-authorization-contract.md", "docs/import-profiles/bafu/constraints.md", "docs/import-profiles/bafu/leaf-process-classification-authoring.md", "docs/import-profiles/bafu/profile.md", "docs/import-profiles/uslci/constraints.md", "docs/import-profiles/uslci/profile.md", "docs/uslci-import-runbook.md", "docs/import-profiles/worldsteel/constraints.md", "docs/import-profiles/worldsteel/import-coverage.md", "docs/import-profiles/worldsteel/import-plan.md", "docs/import-profiles/worldsteel/profile.md", "README.md", "LICENSE"];
4
4
  declare const packageName = "@tiangong-lca/foundry";
5
- declare const packageVersion = "0.1.9";
5
+ declare const packageVersion = "0.1.11";
6
6
  declare const cliPackageName = "@tiangong-lca/cli";
7
- declare const cliPackageVersion = "0.1.14";
7
+ declare const cliPackageVersion = "0.1.19";
8
8
  declare const packageBin = "package-dist/scripts/package-entry.js";
9
9
  declare const packageApi = "package-dist/scripts/public-api.js";
10
10
  declare const packageTypes = "package-dist/scripts/public-api.d.ts";
11
11
  declare const supportedPlatforms: readonly ["linux-x64", "linux-arm64", "darwin-arm64", "win32-x64"];
12
- declare const protocolSchemas: readonly ["tiangong-foundry.operation-result.v1", "tiangong-foundry.task-start.v1", "tiangong-foundry.semantic-input.v1", "tiangong-foundry.authorization-input.v1", "tiangong-foundry.reference-input.v1", "tiangong-foundry.facade-request-index.v1", "tiangong-foundry.workspace-migration-plan.v1", "tiangong-foundry.workspace-migration-transfer-plan.v2", "tiangong-foundry.migration-transfer-receipt.v1", "tiangong-foundry.workspace-migration-pending.v1", "tiangong-foundry.migration-adoption-plan.v1", "tiangong-foundry.migration-activation.v1", "tiangong-foundry.workspace.v2", "tiangong-foundry.workspace-runtime-selection.v1", "tiangong-foundry.managed-runtime.v1", "tiangong-foundry.runtime-qualification.v1", "tiangong-foundry.tidas-runtime-expectation.v1", "tiangong-foundry.execution-context.v1", "tiangong-foundry.authorization-derivation.v1", "tiangong-foundry.task-authorization.v1"];
12
+ declare const protocolSchemas: readonly ["tiangong-foundry.operation-result.v1", "tiangong-foundry.task-start.v1", "tiangong-foundry.semantic-input.v1", "tiangong-foundry.interaction-input.v1", "tiangong-foundry.authorization-input.v1", "tiangong-foundry.reference-input.v1", "tiangong-foundry.facade-request-index.v1", "tiangong-foundry.workspace-migration-plan.v1", "tiangong-foundry.workspace-migration-transfer-plan.v2", "tiangong-foundry.migration-transfer-receipt.v1", "tiangong-foundry.workspace-migration-pending.v1", "tiangong-foundry.migration-adoption-plan.v1", "tiangong-foundry.migration-activation.v1", "tiangong-foundry.workspace.v2", "tiangong-foundry.workspace-runtime-selection.v1", "tiangong-foundry.managed-runtime.v1", "tiangong-foundry.runtime-qualification.v1", "tiangong-foundry.tidas-runtime-expectation.v1", "tiangong-foundry.execution-context.v1", "tiangong-foundry.authorization-derivation.v1", "tiangong-foundry.task-authorization.v1"];
13
13
  export interface FoundryPackageFileFact {
14
14
  readonly path: string;
15
15
  readonly bytes: number;
@@ -16,6 +16,7 @@ export const foundryPackageStaticFiles = Object.freeze([
16
16
  "specs/schemas/foundry-package-descriptor.schema.json",
17
17
  "specs/schemas/foundry-task-start.schema.json",
18
18
  "specs/schemas/foundry-semantic-input.schema.json",
19
+ "specs/schemas/foundry-interaction-input.schema.json",
19
20
  "specs/schemas/foundry-authorization-input.schema.json",
20
21
  "specs/schemas/foundry-reference-input.schema.json",
21
22
  "specs/schemas/foundry-workspace-migration-plan.schema.json",
@@ -52,10 +53,10 @@ export const foundryPackageStaticFiles = Object.freeze([
52
53
  "LICENSE",
53
54
  ]);
54
55
  const packageName = "@tiangong-lca/foundry";
55
- const packageVersion = "0.1.9";
56
+ const packageVersion = "0.1.11";
56
57
  const packageDescription = "Control plane for TianGong LCA external dataset import and TIDAS authoring work.";
57
58
  const cliPackageName = "@tiangong-lca/cli";
58
- const cliPackageVersion = "0.1.14";
59
+ const cliPackageVersion = "0.1.19";
59
60
  const packageBin = "package-dist/scripts/package-entry.js";
60
61
  const packageApi = "package-dist/scripts/public-api.js";
61
62
  const packageTypes = "package-dist/scripts/public-api.d.ts";
@@ -69,6 +70,7 @@ const protocolSchemas = Object.freeze([
69
70
  "tiangong-foundry.operation-result.v1",
70
71
  "tiangong-foundry.task-start.v1",
71
72
  "tiangong-foundry.semantic-input.v1",
73
+ "tiangong-foundry.interaction-input.v1",
72
74
  "tiangong-foundry.authorization-input.v1",
73
75
  "tiangong-foundry.reference-input.v1",
74
76
  "tiangong-foundry.facade-request-index.v1",
@@ -0,0 +1,11 @@
1
+ import type { FoundryRepairExpectation } from "./foundry-repair-preflight.ts";
2
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
3
+ import type { OwnerExecutionRequest } from "./foundry-owner-execution-store.ts";
4
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ /** Re-admit the immutable repair scope at execution and readback; never infer it from a handoff flag. */
6
+ export declare function assertFoundryRepairExecution(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], request: OwnerExecutionRequest): {
7
+ preparation: import("./foundry-workflow-repair.ts").FoundryRepairPreparationRead;
8
+ handoff: Record<string, unknown>;
9
+ expectation: FoundryRepairExpectation;
10
+ beforeFile: string;
11
+ } | null;
@@ -0,0 +1,70 @@
1
+ import path from "node:path";
2
+ import { commandSpecOptionValue } from "@tiangong-lca/cli/command-spec";
3
+ import { captureFoundryInput, FoundryContextError, resolveFoundryInputPath, } from "./foundry-runtime-context.js";
4
+ import { readTaskJson } from "./foundry-task-io.js";
5
+ import { readFoundryRepairPreparation, foundryRepairSelection } from "./foundry-workflow-repair.js";
6
+ import { readWorkflowArtifact, workflowObject } from "./foundry-workflow-state.js";
7
+ /** Re-admit the immutable repair scope at execution and readback; never infer it from a handoff flag. */
8
+ export function assertFoundryRepairExecution(context, entries, request) {
9
+ const job = readTaskJson(context, "foundry-job.json");
10
+ if (job.lane !== "existing-owner-draft-repair")
11
+ return null;
12
+ const fail = () => {
13
+ throw new FoundryContextError("repair_execution_mismatch", "Repair execution must retain its exact prepared scope, owner contract and authorized candidate.");
14
+ };
15
+ const preparation = readFoundryRepairPreparation(context, entries);
16
+ const approvalEntry = entries.find((entry) => entry.command === "dataset-workflow-authorization" &&
17
+ entry.sha256 === request.content.authorization &&
18
+ path.basename(entry.path) === "foundry-authorization.json");
19
+ if (!preparation || !approvalEntry)
20
+ return fail();
21
+ const handoffEntry = entries.find((entry) => path.resolve(context.taskRoot, entry.path) === request.handoff_file &&
22
+ entry.operation_id === approvalEntry.operation_id &&
23
+ entry.command === approvalEntry.command &&
24
+ entry.receipt.sha256 === approvalEntry.receipt.sha256);
25
+ if (!handoffEntry)
26
+ return fail();
27
+ const handoff = readWorkflowArtifact(context, handoffEntry).value;
28
+ const approval = readWorkflowArtifact(context, approvalEntry).value;
29
+ const selection = foundryRepairSelection(context);
30
+ const candidate = captureFoundryInput(resolveFoundryInputPath(context, selection.candidate));
31
+ const contractFile = commandSpecOptionValue(request.content.commit, "--execution-contract");
32
+ if (!contractFile)
33
+ return fail();
34
+ const contract = captureFoundryInput(contractFile);
35
+ const expectedContract = workflowObject(workflowObject(preparation.value.inputs).contract);
36
+ if (job.target_profile !== "generic" ||
37
+ handoff.repair_scope !== true ||
38
+ preparation.value.status !== "prepared" ||
39
+ preparation.value.publication_ready !== false ||
40
+ approval.input_kind !== "repair_rows" ||
41
+ approval.finalization_sha256 !== preparation.entry.sha256 ||
42
+ approval.status !== "sealed" ||
43
+ candidate.path !== request.content.input.path ||
44
+ candidate.bytes !== request.content.input.bytes ||
45
+ candidate.sha256 !== request.content.input.sha256 ||
46
+ contract.bytes !== expectedContract.bytes ||
47
+ contract.sha256 !== expectedContract.sha256 ||
48
+ request.policy.dataset_type !== "process" ||
49
+ request.policy.state_code !== 0 ||
50
+ request.policy.user_id !== context.accountIntent?.userId ||
51
+ request.policy.project_ref !== context.accountIntent.projectRef)
52
+ return fail();
53
+ const scope = workflowObject(preparation.value.scope);
54
+ const contractProof = workflowObject(preparation.value.contract);
55
+ const expectation = {
56
+ dataset_type: "process",
57
+ contract_sha256: String(scope.contract_sha256),
58
+ execution_id: String(contractProof.execution_id),
59
+ owner_user_id: context.accountIntent.userId,
60
+ project_ref: context.accountIntent.projectRef,
61
+ state_code: "0",
62
+ actions: scope.actions,
63
+ };
64
+ return {
65
+ preparation,
66
+ handoff,
67
+ expectation,
68
+ beforeFile: resolveFoundryInputPath(context, selection.before),
69
+ };
70
+ }
@@ -0,0 +1,16 @@
1
+ import type { FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ type JsonRecord = Record<string, unknown>;
3
+ /**
4
+ * The reviewed owner-draft write plan of one prepared repair. It is the repair counterpart of the
5
+ * finalization commit handoff: the same native save-draft commit CommandSpec plus its post-write
6
+ * verification, bound to the candidate rows and the selected execution contract. The plan carries the
7
+ * admitted native contract metadata unchanged, so the closeout owner can consume it. Nothing is
8
+ * dispatched here, and the plan is not authority by itself.
9
+ */
10
+ export declare function createFoundryRepairHandoffPlan(input: {
11
+ context: FoundryRuntimeContext;
12
+ candidateFile: string;
13
+ contractFile: string;
14
+ outDir: string;
15
+ }): JsonRecord;
16
+ export {};
@@ -0,0 +1,108 @@
1
+ import path from "node:path";
2
+ import { createFileArtifactFact, createFoundryCommandSpec } from "@tiangong-lca/cli/command-spec";
3
+ import { nativeDraftCommitArguments, readNativeDraftHandoff, } from "./finalize-owners/native-draft-handoff.js";
4
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
5
+ import { repoRelativePath } from "./import-curation/internal/runtime-io.js";
6
+ /**
7
+ * The reviewed owner-draft write plan of one prepared repair. It is the repair counterpart of the
8
+ * finalization commit handoff: the same native save-draft commit CommandSpec plus its post-write
9
+ * verification, bound to the candidate rows and the selected execution contract. The plan carries the
10
+ * admitted native contract metadata unchanged, so the closeout owner can consume it. Nothing is
11
+ * dispatched here, and the plan is not authority by itself.
12
+ */
13
+ export function createFoundryRepairHandoffPlan(input) {
14
+ const account = input.context.accountIntent;
15
+ if (!account)
16
+ throw new Error("A repair handoff plan requires the current account intent.");
17
+ const relativePath = (file) => repoRelativePath(input.context.assetRoot, file);
18
+ const native = readNativeDraftHandoff({
19
+ contractFile: input.contractFile,
20
+ rowsFile: input.candidateFile,
21
+ datasetType: "process",
22
+ targetUserId: account.userId,
23
+ verifiedProjectRef: account.projectRef,
24
+ stateCode: "0",
25
+ relativePath,
26
+ });
27
+ const approved = createFileArtifactFact({
28
+ role: "final_rows",
29
+ path: relativePath(input.candidateFile),
30
+ filePath: input.candidateFile,
31
+ });
32
+ if (native.rows_sha256 !== approved.sha256)
33
+ throw new Error("--execution-contract-file repair candidate rows changed during handoff admission.");
34
+ const cli = resolveInstalledTiangongLcaCliPackage();
35
+ const prefix = [process.execPath, cli.binPath];
36
+ const commit = nativeDraftCommitArguments(prefix, "process", input.candidateFile, input.outDir, input.contractFile);
37
+ const verify = [
38
+ ...prefix,
39
+ "dataset",
40
+ "verify-remote",
41
+ "--input",
42
+ input.candidateFile,
43
+ "--out-dir",
44
+ path.join(input.outDir, "post-write-verify"),
45
+ "--root-policy",
46
+ "existing",
47
+ "--compare-root-payload",
48
+ "--json",
49
+ "--target-user-id",
50
+ account.userId,
51
+ "--state-code",
52
+ "0",
53
+ ];
54
+ const bound = [approved, native.artifact];
55
+ const report = {
56
+ schema_version: 1,
57
+ generated_at_utc: new Date().toISOString(),
58
+ status: "ready_for_explicit_commit",
59
+ dataset_type: "process",
60
+ profile: "generic",
61
+ remote_write_mode: "read-only",
62
+ repair_scope: true,
63
+ final_rows_file: input.candidateFile,
64
+ final_rows_artifact: approved,
65
+ target_user_id: account.userId,
66
+ verified_project_ref: account.projectRef,
67
+ account_mode: account.accountMode ?? "ordinary",
68
+ expected_state_code: "0",
69
+ execution_contract: { ...native.metadata },
70
+ account_write_guard: {
71
+ target_user_id_required: true,
72
+ target_user_id: account.userId,
73
+ commit_command_supports_target_user_id: true,
74
+ commit_account_binding: "native_execution_contract",
75
+ verify_account_binding: "target_user_id_cli_argument",
76
+ execution_precondition: "Run only the exact native execution contract under its matching owner/project session; the CLI owns persistent attempt and readback-only recovery.",
77
+ },
78
+ policy: {
79
+ commit_boundary: "This plan does not write the database. The sealed owner execution request runs the authoritative commit CommandSpec, then the post_write_verify CommandSpec, without a shell.",
80
+ post_write_verify_required: true,
81
+ compare_root_payload_required: true,
82
+ },
83
+ blockers: [],
84
+ commands: {
85
+ commit: createFoundryCommandSpec({
86
+ executable: commit[0],
87
+ argv: commit.slice(1),
88
+ binding: { artifacts: bound },
89
+ }),
90
+ post_write_verify: createFoundryCommandSpec({
91
+ executable: verify[0],
92
+ argv: verify.slice(1),
93
+ binding: { artifacts: bound },
94
+ }),
95
+ },
96
+ files: {
97
+ expected_commit_report_dir: path.join(input.outDir, "commit"),
98
+ expected_post_write_verify_dir: path.join(input.outDir, "post-write-verify"),
99
+ },
100
+ };
101
+ return {
102
+ ...report,
103
+ files: {
104
+ ...report.files,
105
+ report: relativePath(path.join(input.outDir, "dataset-commit-handoff-plan.json")),
106
+ },
107
+ };
108
+ }