@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
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { assertSelectedAuthorizationInput, } from "./foundry-authorization-input.js";
5
5
  import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
6
- import { FoundryContextError, readFoundryInput, captureFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
6
+ import { FoundryContextError, readFoundryInput, captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, } from "./foundry-runtime-context.js";
7
7
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
8
8
  import { currentWorkflowState, workflowObject } from "./foundry-workflow-state.js";
9
9
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
@@ -15,11 +15,16 @@ import { createFoundryExecutionCapsule } from "./foundry-execution-admission.js"
15
15
  import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
16
16
  import { createFoundryCommandSpec, createFileArtifactFact } from "./foundry-command-spec.js";
17
17
  import { parseFoundryCommandSpec } from "@tiangong-lca/cli/command-spec";
18
- import { readNativeInsertHandoff } from "./finalize-owners/native-insert-handoff.js";
18
+ import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
19
+ import { foundryRepairSelection, readFoundryRepairPreparation } from "./foundry-workflow-repair.js";
20
+ import { createFoundryRepairHandoffPlan } from "./foundry-repair-handoff.js";
21
+ import { readTaskJson } from "./foundry-task-io.js";
19
22
  export async function authorizeFoundryWorkflow(context, qualified, entries, selected, authentication = { mode: "oauth" }) {
20
23
  assertSelectedAuthorizationInput(selected);
21
24
  assertQualifiedFoundryRuntime(context, qualified);
22
25
  const state = currentWorkflowState(context, entries), spec = selected.spec;
26
+ if (spec.input_kind === "repair_rows")
27
+ return authorizeFoundryRepair(context, qualified, entries, selected, authentication, state);
23
28
  const finalization = state.finalization;
24
29
  if (state.authorization?.value.submission_sha256 === selected.descriptor.sha256)
25
30
  return state.authorization.value;
@@ -39,7 +44,7 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
39
44
  const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
40
45
  if (selected.executionContract) {
41
46
  try {
42
- readNativeInsertHandoff({
47
+ readNativeDraftHandoff({
43
48
  contractFile: selected.executionContract.path,
44
49
  rowsFile: inputFile,
45
50
  datasetType: spec.dataset_type,
@@ -50,7 +55,7 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
50
55
  });
51
56
  }
52
57
  catch {
53
- throw new FoundryContextError("authorization_execution_contract_invalid", "Native insert contract must bind the current final rows, owner, project and draft state before authorization.");
58
+ throw new FoundryContextError("authorization_execution_contract_invalid", "Native draft contract must bind the current final rows, owner, project and draft state before authorization.");
54
59
  }
55
60
  }
56
61
  const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
@@ -92,6 +97,153 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
92
97
  },
93
98
  });
94
99
  }
100
+ /**
101
+ * The repair authority. A repair approval names the registered preparation report, never a
102
+ * finalization: the report digest is the scope authority, the scope must be a prepared dispatchable
103
+ * metadata repair of the locked generic profile, and the signed native contract must still bind the
104
+ * immutable candidate rows and the exact owner account. No successor or closeout is produced here.
105
+ */
106
+ async function authorizeFoundryRepair(context, qualified, entries, selected, authentication, state) {
107
+ const spec = selected.spec;
108
+ const preparationFact = selected.repairPreparation;
109
+ if (state.authorization?.value.submission_sha256 === selected.descriptor.sha256)
110
+ return state.authorization.value;
111
+ const preparation = readFoundryRepairPreparation(context, entries);
112
+ if (!preparation)
113
+ throw new FoundryContextError("authorization_repair_preparation_missing", "A repair approval requires the current registered preparation report.");
114
+ if (preparation.entry.sha256 !== spec.finalization_sha256 ||
115
+ preparation.entry.sha256 !== preparationFact.sha256 ||
116
+ preparation.entry.bytes !== preparationFact.bytes)
117
+ throw new FoundryContextError("authorization_repair_preparation_mismatch", "Approval must select the registered preparation report bytes of this scope.");
118
+ const value = preparation.value;
119
+ if (value.status !== "prepared")
120
+ throw new FoundryContextError("authorization_repair_not_prepared", "Only a prepared dispatchable repair may be authorized; a no-change or blocked preparation carries no write authority.");
121
+ if (value.publication_ready !== false || value.remote_writes !== 0)
122
+ throw new FoundryContextError("authorization_repair_not_prepared", "Repair evidence must remain a non-publishing, zero-write preparation.");
123
+ const scope = workflowObject(value.scope);
124
+ const reportedActions = Array.isArray(scope.actions) ? scope.actions.map(workflowObject) : [];
125
+ if (scope.status !== "dispatchable" || !reportedActions.length)
126
+ throw new FoundryContextError("authorization_repair_scope_not_dispatchable", "A repair approval requires a dispatchable scope with at least one action.");
127
+ const job = readTaskJson(context, "foundry-job.json");
128
+ if (job.target_profile !== "generic")
129
+ throw new FoundryContextError("authorization_repair_profile_unsupported", "The repair lane admits only the generic profile.");
130
+ const selection = foundryRepairSelection(context);
131
+ const candidateFile = resolveFoundryInputPath(context, selection.candidate);
132
+ const beforeFile = resolveFoundryInputPath(context, selection.before);
133
+ const contractFile = selected.executionContract.path;
134
+ let native;
135
+ try {
136
+ native = readNativeDraftHandoff({
137
+ contractFile,
138
+ rowsFile: candidateFile,
139
+ datasetType: spec.dataset_type,
140
+ targetUserId: context.accountIntent.userId,
141
+ verifiedProjectRef: context.accountIntent.projectRef,
142
+ stateCode: "0",
143
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
144
+ });
145
+ }
146
+ catch {
147
+ throw new FoundryContextError("authorization_execution_contract_invalid", "Native draft contract must bind the current repair candidate rows, owner, project and draft state.");
148
+ }
149
+ const reportInputs = workflowObject(value.inputs);
150
+ const sameFileBytes = (fact, file) => {
151
+ const item = workflowObject(fact);
152
+ const current = captureFoundryInput(file);
153
+ return item.sha256 === current.sha256 && item.bytes === current.bytes;
154
+ };
155
+ if (workflowObject(value.contract).canonical_sha256 !== native.canonical_sha256 ||
156
+ scope.contract_sha256 !== native.canonical_sha256 ||
157
+ !sameFileBytes(reportInputs.contract, contractFile) ||
158
+ !sameFileBytes(reportInputs.before, beforeFile) ||
159
+ !sameFileBytes(reportInputs.candidate, candidateFile) ||
160
+ workflowObject(reportInputs.candidate).sha256 !== spec.input_sha256)
161
+ throw new FoundryContextError("authorization_repair_scope_mismatch", "The registered preparation must bind the exact selected contract, before and candidate bytes.");
162
+ for (const [index, action] of native.contract.actions.entries()) {
163
+ const reported = reportedActions[index];
164
+ if (reportedActions.length !== native.contract.actions.length ||
165
+ reported.action_id !== action.action_id ||
166
+ reported.table !== action.table ||
167
+ reported.id !== action.id ||
168
+ reported.version !== action.version ||
169
+ reported.before_sha256 !== action.before_sha256 ||
170
+ reported.desired_sha256 !== action.desired_sha256)
171
+ throw new FoundryContextError("authorization_repair_action_mismatch", "Registered repair actions must equal the signed native contract actions.");
172
+ }
173
+ const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
174
+ const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
175
+ const current = (index) => {
176
+ assertSelectedAuthorizationInput(selected);
177
+ const again = readFoundryRepairPreparation(context, index);
178
+ if (!again ||
179
+ again.entry.sha256 !== preparation.entry.sha256 ||
180
+ again.entry.bytes !== preparation.entry.bytes)
181
+ throw new FoundryContextError("authorization_repair_preparation_changed", "Repair evidence changed before approval activation.");
182
+ };
183
+ const registration = await registerFoundryTaskAuthorization(context, identity, {
184
+ inputFile: candidateFile,
185
+ grant,
186
+ evidence: spec.evidence.map((item, index) => ({
187
+ id: item.id,
188
+ kind: item.kind,
189
+ file: selected.evidence[index],
190
+ })),
191
+ expectedPreviousSha256: spec.expected_previous_sha256,
192
+ validateCurrent: (_, index) => current(index),
193
+ }, qualified);
194
+ const authorization = await loadFoundryTaskAuthorization(context, identity, candidateFile, qualified);
195
+ return recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, {
196
+ inputFile: candidateFile,
197
+ approvedInputFile: candidateFile,
198
+ scope: { type: spec.dataset_type, status: scope.status, actions: reportedActions },
199
+ finalizationSha256: spec.finalization_sha256,
200
+ datasetType: spec.dataset_type,
201
+ inputKind: spec.input_kind,
202
+ registration,
203
+ submissionSha256: selected.descriptor.sha256,
204
+ executionContract: selected.executionContract,
205
+ repairPreparation: preparationFact,
206
+ validateCurrent: current,
207
+ operationOptions: {
208
+ submission: selected.descriptor,
209
+ grant: selected.grant,
210
+ evidence: selected.evidence,
211
+ repair_preparation: selected.repairPreparation,
212
+ finalization: spec.finalization_sha256,
213
+ authorization: registration.authorization_sha256,
214
+ execution_contract: selected.executionContract,
215
+ },
216
+ });
217
+ }
218
+ /**
219
+ * Re-bind every emitted handoff command to the host-selected execution inputs: the final-row fact is
220
+ * re-derived from the approved file and every other bound artifact is resolved against the asset root.
221
+ * The commands keep their exact argv, so only the artifact paths are normalized.
222
+ */
223
+ function bindHandoffCommands(context, handoff, inputFile) {
224
+ const commands = workflowObject(handoff.commands);
225
+ for (const key of ["commit", "post_write_verify"]) {
226
+ if (!commands[key])
227
+ continue;
228
+ const command = parseFoundryCommandSpec(commands[key]);
229
+ commands[key] = createFoundryCommandSpec({
230
+ executable: command.executable,
231
+ argv: [...command.argv],
232
+ binding: {
233
+ artifacts: [
234
+ createFileArtifactFact({ role: "final_rows", path: inputFile, filePath: inputFile }),
235
+ ...command.binding.artifacts
236
+ .filter((artifact) => artifact.role !== "final_rows")
237
+ .map((artifact) => ({
238
+ ...artifact,
239
+ path: path.resolve(context.assetRoot, artifact.path),
240
+ })),
241
+ ],
242
+ },
243
+ });
244
+ }
245
+ return handoff;
246
+ }
95
247
  export async function recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, request) {
96
248
  const { inputFile, scope, registration } = request;
97
249
  const nonce = randomUUID(), output = resolveFoundryOutput(context, `outputs/authorization/${nonce}`);
@@ -124,29 +276,9 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
124
276
  ? { executionContractFile: request.executionContract.path }
125
277
  : {}),
126
278
  }));
127
- const commands = workflowObject(handoff.commands);
128
- for (const key of ["commit", "post_write_verify"]) {
129
- if (!commands[key])
130
- continue;
131
- const command = parseFoundryCommandSpec(commands[key]);
132
- commands[key] = createFoundryCommandSpec({
133
- executable: command.executable,
134
- argv: [...command.argv],
135
- binding: {
136
- artifacts: [
137
- createFileArtifactFact({ role: "final_rows", path: inputFile, filePath: inputFile }),
138
- ...command.binding.artifacts
139
- .filter((artifact) => artifact.role !== "final_rows")
140
- .map((artifact) => ({
141
- ...artifact,
142
- path: path.resolve(context.assetRoot, artifact.path),
143
- })),
144
- ],
145
- },
146
- });
147
- }
279
+ handoff = bindHandoffCommands(context, handoff, inputFile);
148
280
  fs.writeFileSync(path.join(output, "handoff", "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
149
- const command = commands.commit;
281
+ const command = workflowObject(handoff.commands).commit;
150
282
  if (command) {
151
283
  const requiredActions = authorization.allowed_actions.filter((action) => request.datasetType === "flow"
152
284
  ? action === "elementary_flow_write" || action === "elementary_flow_create_new"
@@ -174,6 +306,39 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
174
306
  });
175
307
  }
176
308
  }
309
+ if (request.inputKind === "repair_rows") {
310
+ // The repair scope has no finalization: its write plan is the reviewed native save-draft
311
+ // handoff over the immutable candidate rows and the selected execution contract. The capsule
312
+ // seals exactly that command, and the owner execution request stays a separate later stage.
313
+ const handoffDir = path.join(output, "handoff");
314
+ fs.mkdirSync(handoffDir, { recursive: true, mode: 0o700 });
315
+ handoff = bindHandoffCommands(context, createFoundryRepairHandoffPlan({
316
+ context,
317
+ candidateFile: inputFile,
318
+ contractFile: request.executionContract.path,
319
+ outDir: handoffDir,
320
+ }), inputFile);
321
+ fs.writeFileSync(path.join(handoffDir, "dataset-commit-handoff-plan.json"), JSON.stringify(handoff, null, 2) + "\n");
322
+ const command = workflowObject(handoff.commands).commit;
323
+ if (command) {
324
+ try {
325
+ assertVerifiedFoundryIdentity(context, identity, qualified);
326
+ }
327
+ catch (error) {
328
+ if (!(error instanceof FoundryContextError) || error.code !== "identity_receipt_stale")
329
+ throw error;
330
+ }
331
+ const sealingIdentity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
332
+ capsule = await createFoundryExecutionCapsule(context, qualified, sealingIdentity, {
333
+ command: "dataset-commit-handoff-plan",
334
+ approvedInputFile: request.approvedInputFile,
335
+ finalRowsFile: inputFile,
336
+ commandSpec: command,
337
+ requiredActions: [],
338
+ requiredQaWaivers: [],
339
+ });
340
+ }
341
+ }
177
342
  return await runFoundryTaskOperation(context, {
178
343
  command: "dataset-workflow-authorization",
179
344
  options: request.operationOptions,
@@ -198,6 +363,9 @@ export async function recordFoundryWorkflowAuthorization(context, qualified, ide
198
363
  capsule,
199
364
  handoff,
200
365
  submission_sha256: request.submissionSha256,
366
+ ...(request.repairPreparation
367
+ ? { repair_preparation: { ...request.repairPreparation } }
368
+ : {}),
201
369
  };
202
370
  operation.writeJson(path.join(output, "foundry-authorization.json"), result);
203
371
  return result;
@@ -86,6 +86,10 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
86
86
  const report = {
87
87
  schema: "tiangong-foundry.context-stage.v1",
88
88
  status: "completed",
89
+ cli: {
90
+ package: cli.packageSpec,
91
+ tidas_spec_source: cli.tidasSpecSource,
92
+ },
89
93
  reports,
90
94
  files,
91
95
  };
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { assertFoundryRepairExecution } from "./foundry-repair-execution.js";
2
3
  import path from "node:path";
3
4
  import { spawnSync } from "node:child_process";
4
5
  import { randomUUID } from "node:crypto";
@@ -29,7 +30,10 @@ export async function executeFoundryOwnerScope(context, qualified, entries, requ
29
30
  reason: "Foundry owner execution and readback",
30
31
  }, async () => {
31
32
  assertQualifiedFoundryRuntime(context, qualified);
32
- const inspected = await withFoundryTaskMetadata(context, (_, index) => inspectOwnerExecutions(context, index));
33
+ const inspected = await withFoundryTaskMetadata(context, (_, index) => {
34
+ assertFoundryRepairExecution(context, index, request);
35
+ return inspectOwnerExecutions(context, index);
36
+ });
33
37
  const consumed = inspected.consumed.get(request.scope_id);
34
38
  if (consumed && consumed.entry.sha256 !== requested.entry.sha256)
35
39
  throw new FoundryContextError("execution_request_changed", "A consumed scope must recover its original request.");
@@ -77,6 +81,7 @@ export async function executeFoundryOwnerScope(context, qualified, entries, requ
77
81
  lastRead = await readbackFoundryOwner(context, qualified, request, authentication, commitReport);
78
82
  return lastRead.proof.status === "verified" ? lastRead : null;
79
83
  };
84
+ await withFoundryTaskMetadata(context, (_, index) => assertFoundryRepairExecution(context, index, request));
80
85
  const batch = await runBoundedBatch({
81
86
  contract: request.contract,
82
87
  items: [request],
@@ -17,7 +17,7 @@ import { createHash } from "node:crypto";
17
17
  export async function finalizeFoundryWorkflow(context, qualified, entries, authentication = { mode: "oauth" }, approval, executionProgress) {
18
18
  assertQualifiedFoundryRuntime(context, qualified);
19
19
  const state = currentWorkflowState(context, entries), rows = state.rows;
20
- if (!rows || !state.assessment)
20
+ if (!rows || !state.assessment || !state.assessmentComplete)
21
21
  throw new FoundryContextError("workflow_assessment_required", "Assess the current rows before finalization.");
22
22
  const referenceOptions = new Map();
23
23
  for (const set of rows.value.sets) {
@@ -266,10 +266,13 @@ export async function finalizeFoundryWorkflow(context, qualified, entries, authe
266
266
  : {}),
267
267
  },
268
268
  validateCurrent(index) {
269
- if (currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
269
+ const current = currentWorkflowState(context, index);
270
+ if (current.rows?.entry.sha256 !== rows.entry.sha256)
270
271
  throw new FoundryContextError("workflow_rows_changed", "Rows changed during finalization.");
271
- if (currentWorkflowState(context, index).referenceInputsSha256 !==
272
- state.referenceInputsSha256)
272
+ if (!current.assessmentComplete ||
273
+ current.assessment?.entry.sha256 !== state.assessment?.entry.sha256)
274
+ throw new FoundryContextError("workflow_assessment_changed", "Assessment changed during finalization.");
275
+ if (current.referenceInputsSha256 !== state.referenceInputsSha256)
273
276
  throw new FoundryContextError("reference_input_changed", "Reference selection changed during finalization.");
274
277
  if (authorization &&
275
278
  (createHash("sha256")
@@ -0,0 +1,4 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ import { type SelectedFoundryInteractionInput } from "./foundry-interaction-input.ts";
4
+ export declare function recordFoundryInteractionInput(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], selected: SelectedFoundryInteractionInput, targetEntities: readonly string[]): Promise<Record<string, unknown>>;
@@ -0,0 +1,63 @@
1
+ import path from "node:path";
2
+ import { FoundryContextError, readFoundryInput, } from "./foundry-runtime-context.js";
3
+ import { runFoundryTaskOperation } from "./foundry-task-store.js";
4
+ import { advanceFoundryInteractionState, assertSelectedFoundryInteractionInput, currentFoundryInteractionState, FOUNDRY_INTERACTION_COMMAND, FOUNDRY_INTERACTION_REPORT, readSelectedFoundryInteractionBytes, } from "./foundry-interaction-input.js";
5
+ import { readWorkflowArtifact } from "./foundry-workflow-state.js";
6
+ import { createWorkflowStageDirectory } from "./foundry-workflow-io.js";
7
+ const resultName = "interaction-result.json";
8
+ function priorSubmission(context, entries, sha256) {
9
+ for (const entry of [...entries].reverse()) {
10
+ if (entry.command !== FOUNDRY_INTERACTION_COMMAND || path.basename(entry.path) !== resultName)
11
+ continue;
12
+ const report = readWorkflowArtifact(context, entry).value;
13
+ if (report.schema === "tiangong-foundry.interaction-result.v1" &&
14
+ report.descriptor_sha256 === sha256)
15
+ return report;
16
+ }
17
+ return null;
18
+ }
19
+ export async function recordFoundryInteractionInput(context, entries, selected, targetEntities) {
20
+ assertSelectedFoundryInteractionInput(selected);
21
+ const prior = priorSubmission(context, entries, selected.descriptor.sha256);
22
+ if (prior)
23
+ return prior;
24
+ const current = currentFoundryInteractionState(context, entries);
25
+ const currentSha = current?.entry.sha256 ?? null;
26
+ const known = new Set([
27
+ ...context.inputs.map((fact) => fact.sha256),
28
+ ...entries.map((entry) => entry.sha256),
29
+ ]);
30
+ const accepted = advanceFoundryInteractionState(current?.state ?? null, selected.spec, currentSha, known, new Set(targetEntities));
31
+ return runFoundryTaskOperation(context, {
32
+ command: FOUNDRY_INTERACTION_COMMAND,
33
+ options: {
34
+ descriptor: selected.descriptor,
35
+ expected_state_sha256: currentSha,
36
+ },
37
+ validateCurrent(index) {
38
+ if (index.some((entry) => ["dataset-workflow-execution-prepare", "dataset-workflow-execution-consume"].includes(entry.command)))
39
+ throw new FoundryContextError("interaction_after_approval", "Preserve the approved or attempted scope; a changed decision needs a separately reviewed task revision.");
40
+ const present = currentFoundryInteractionState(context, index);
41
+ if ((present?.entry.sha256 ?? null) !== currentSha)
42
+ throw new FoundryContextError("interaction_state_changed", "Interaction state changed before this input acquired the task lock.");
43
+ },
44
+ }, (operation) => {
45
+ assertSelectedFoundryInteractionInput(selected);
46
+ for (const input of context.inputs)
47
+ readFoundryInput(context, input.path);
48
+ const freshBytes = readSelectedFoundryInteractionBytes(selected.descriptor);
49
+ const output = createWorkflowStageDirectory(context, operation, "interaction");
50
+ operation.writeText(path.join(output, "interaction-input.json"), freshBytes);
51
+ operation.writeJson(path.join(output, FOUNDRY_INTERACTION_REPORT), accepted);
52
+ const result = {
53
+ schema: "tiangong-foundry.interaction-result.v1",
54
+ status: "completed",
55
+ task_id: selected.spec.task_id,
56
+ descriptor_sha256: selected.descriptor.sha256,
57
+ previous_state_sha256: currentSha,
58
+ event_count: accepted.events.length,
59
+ };
60
+ operation.writeJson(path.join(output, resultName), result);
61
+ return result;
62
+ });
63
+ }
@@ -0,0 +1,36 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ import { type FoundryAuthentication } from "./foundry-authentication-environment.ts";
4
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ type JsonRecord = Record<string, unknown>;
6
+ /** The task-store command this owner registers under; the facade owns invoking it. */
7
+ export declare const FOUNDRY_REPAIR_PREFLIGHT_COMMAND: "dataset-workflow-repair-preflight";
8
+ export declare const FOUNDRY_REPAIR_REPORT_NAME = "foundry-repair-preflight.json";
9
+ export declare const FOUNDRY_REPAIR_JOB_SCHEMA = "tiangong-foundry.repair-preparation.v1";
10
+ export interface FoundryRepairSelectionFacts {
11
+ readonly kind: string;
12
+ readonly contract: string;
13
+ readonly before: string;
14
+ readonly candidate: string;
15
+ }
16
+ export interface FoundryRepairPreparationRead {
17
+ readonly entry: ArtifactEntry;
18
+ readonly file: string;
19
+ readonly value: JsonRecord;
20
+ }
21
+ /** The immutable repair selection of the current task job. */
22
+ export declare function foundryRepairSelection(context: FoundryRuntimeContext): FoundryRepairSelectionFacts;
23
+ /**
24
+ * Read the already-registered preparation report for the current task scope. The report and every
25
+ * CLI evidence file it references must exist in the same producer index with exact bytes and hash; a
26
+ * report that names this scope but fails verification is rejected rather than ignored.
27
+ */
28
+ export declare function readFoundryRepairPreparation(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): FoundryRepairPreparationRead | null;
29
+ /**
30
+ * Prepare one repair through the qualified owner CLI and register the result as trusted producer
31
+ * evidence. Remote reads run outside the task metadata lock; registration happens inside the store's
32
+ * operation (which re-verifies inputs and producers), and a repeated preparation returns the
33
+ * already-registered report without issuing another remote call.
34
+ */
35
+ export declare function prepareFoundryRepair(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, _entries: readonly ArtifactEntry[], authentication: FoundryAuthentication): Promise<JsonRecord>;
36
+ export {};