@tiangong-lca/foundry 0.1.9 → 0.1.10

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 (83) hide show
  1. package/README.md +10 -8
  2. package/docs/architecture.md +9 -7
  3. package/docs/foundry-task-contracts.md +10 -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 +9 -9
  11. package/docs/public-runtime-contract.md +17 -7
  12. package/docs/runtime-context-contract.md +5 -5
  13. package/docs/task-authorization-contract.md +3 -3
  14. package/package-dist/assets/foundry-package-descriptor.json +218 -128
  15. package/package-dist/scripts/foundry-facade.js +71 -0
  16. package/package-dist/scripts/foundry-runtime.d.ts +12 -2
  17. package/package-dist/scripts/lib/finalize-owners/commit-handoff.js +3 -3
  18. package/package-dist/scripts/lib/finalize-owners/{native-insert-closeout.d.ts → native-draft-closeout.d.ts} +1 -1
  19. package/package-dist/scripts/lib/finalize-owners/{native-insert-closeout.js → native-draft-closeout.js} +10 -6
  20. package/package-dist/scripts/lib/finalize-owners/{native-insert-handoff.d.ts → native-draft-handoff.d.ts} +7 -5
  21. package/package-dist/scripts/lib/finalize-owners/{native-insert-handoff.js → native-draft-handoff.js} +30 -11
  22. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.js +2 -2
  23. package/package-dist/scripts/lib/foundry-authorization-input.d.ts +10 -1
  24. package/package-dist/scripts/lib/foundry-authorization-input.js +27 -3
  25. package/package-dist/scripts/lib/foundry-command-metadata.js +25 -2
  26. package/package-dist/scripts/lib/foundry-command-registry.d.ts +4 -4
  27. package/package-dist/scripts/lib/foundry-command-registry.js +3 -0
  28. package/package-dist/scripts/lib/foundry-execution-admission.js +3 -3
  29. package/package-dist/scripts/lib/foundry-facade-store.js +56 -6
  30. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +33 -16
  31. package/package-dist/scripts/lib/foundry-owner-execution-store.js +32 -3
  32. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +3 -0
  33. package/package-dist/scripts/lib/foundry-owner-readback.js +101 -27
  34. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  35. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  36. package/package-dist/scripts/lib/foundry-repair-execution.d.ts +11 -0
  37. package/package-dist/scripts/lib/foundry-repair-execution.js +70 -0
  38. package/package-dist/scripts/lib/foundry-repair-handoff.d.ts +16 -0
  39. package/package-dist/scripts/lib/foundry-repair-handoff.js +108 -0
  40. package/package-dist/scripts/lib/foundry-repair-preflight.d.ts +96 -0
  41. package/package-dist/scripts/lib/foundry-repair-preflight.js +313 -0
  42. package/package-dist/scripts/lib/foundry-repair-reference-binding.d.ts +26 -0
  43. package/package-dist/scripts/lib/foundry-repair-reference-binding.js +120 -0
  44. package/package-dist/scripts/lib/foundry-repair-reference-proof.d.ts +63 -0
  45. package/package-dist/scripts/lib/foundry-repair-reference-proof.js +329 -0
  46. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +76 -0
  47. package/package-dist/scripts/lib/foundry-repair-scope.js +304 -0
  48. package/package-dist/scripts/lib/foundry-runtime-command-policy.js +1 -0
  49. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  50. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +3 -0
  51. package/package-dist/scripts/lib/foundry-runtime-utils.js +6 -1
  52. package/package-dist/scripts/lib/foundry-successor-predecessor.d.ts +36 -0
  53. package/package-dist/scripts/lib/foundry-successor-predecessor.js +399 -0
  54. package/package-dist/scripts/lib/foundry-task-registration.js +64 -3
  55. package/package-dist/scripts/lib/foundry-task-start-spec.d.ts +3 -0
  56. package/package-dist/scripts/lib/foundry-task-start-spec.js +24 -1
  57. package/package-dist/scripts/lib/foundry-task-store.d.ts +13 -1
  58. package/package-dist/scripts/lib/foundry-task-store.js +23 -12
  59. package/package-dist/scripts/lib/foundry-task-types.d.ts +22 -1
  60. package/package-dist/scripts/lib/foundry-tidas-source.d.ts +15 -0
  61. package/package-dist/scripts/lib/foundry-tidas-source.js +90 -0
  62. package/package-dist/scripts/lib/foundry-workflow-authorization.d.ts +2 -1
  63. package/package-dist/scripts/lib/foundry-workflow-authorization.js +194 -26
  64. package/package-dist/scripts/lib/foundry-workflow-context.js +4 -0
  65. package/package-dist/scripts/lib/foundry-workflow-execution.js +6 -1
  66. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +36 -0
  67. package/package-dist/scripts/lib/foundry-workflow-repair.js +580 -0
  68. package/package-dist/scripts/lib/foundry-workflow-state.js +66 -18
  69. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -8
  70. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  71. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.d.ts +13 -2
  72. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.js +100 -29
  73. package/package-dist/scripts/lib/import-curation/internal/workflow-authoring-tasks.js +1 -2
  74. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-collect.js +2 -3
  75. package/package-dist/scripts/lib/import-curation/internal/workflow-queue-context.js +8 -8
  76. package/package-dist/scripts/lib/import-curation/internal/workflow-semantic-actions.js +12 -2
  77. package/package.json +2 -2
  78. package/specs/import-profiles.json +1 -1
  79. package/specs/schemas/foundry-authorization-input.schema.json +45 -2
  80. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  81. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  82. package/specs/schemas/foundry-task-start.schema.json +200 -19
  83. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,580 @@
1
+ import { proveFoundryRepairRemoteIntegrity } from "./foundry-repair-reference-binding.js";
2
+ import { readRows } from "./import-curation/internal/runtime-io.js";
3
+ import childProcess from "node:child_process";
4
+ import { randomUUID } from "node:crypto";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, } from "./foundry-runtime-context.js";
8
+ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
9
+ import { verifyFoundryRuntimeIdentity } from "./foundry-runtime-identity.js";
10
+ import { createFoundryAuthenticationEnvironment, } from "./foundry-authentication-environment.js";
11
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
12
+ import { runFoundryTaskOperation, withFoundryTaskMetadata } from "./foundry-task-store.js";
13
+ import { createWorkflowDirectory, createWorkflowStageDirectory } from "./foundry-workflow-io.js";
14
+ import { readWorkflowArtifact } from "./foundry-workflow-state.js";
15
+ import { readFoundryRepairScope } from "./foundry-repair-scope.js";
16
+ import { FOUNDRY_REPAIR_PREPARATION_SCHEMA, parseFoundryRepairDryRunReport, parseFoundryRepairValidateReport, } from "./foundry-repair-preflight.js";
17
+ import { readTaskJson, relative as taskRelative } from "./foundry-task-io.js";
18
+ import { sha256Json } from "./identity-preflight-proof.js";
19
+ /** The task-store command this owner registers under; the facade owns invoking it. */
20
+ export const FOUNDRY_REPAIR_PREFLIGHT_COMMAND = "dataset-workflow-repair-preflight";
21
+ export const FOUNDRY_REPAIR_REPORT_NAME = "foundry-repair-preflight.json";
22
+ export const FOUNDRY_REPAIR_JOB_SCHEMA = "tiangong-foundry.repair-preparation.v1";
23
+ const CLI_TIMEOUT_MS = 120_000;
24
+ const MAX_REPORT_BYTES = 64 * 1024 * 1024;
25
+ function fail(code, message) {
26
+ throw new FoundryContextError(code, message);
27
+ }
28
+ function isRecord(value) {
29
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
30
+ }
31
+ function record(value, code, label) {
32
+ if (!isRecord(value))
33
+ fail(code, `${label} must be an object.`);
34
+ return value;
35
+ }
36
+ function readRemoteChecks(file) {
37
+ let fd;
38
+ try {
39
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
40
+ const stat = fs.fstatSync(fd);
41
+ if (!stat.isFile() || stat.size > MAX_REPORT_BYTES)
42
+ fail("repair_remote_invalid", "Remote checks must be a bounded regular file.");
43
+ return fs
44
+ .readFileSync(fd, "utf8")
45
+ .split(/\r?\n/u)
46
+ .filter((line) => line.trim())
47
+ .map((line) => JSON.parse(line));
48
+ }
49
+ catch {
50
+ return fail("repair_remote_invalid", "Remote check records are missing or invalid.");
51
+ }
52
+ finally {
53
+ if (fd !== undefined)
54
+ fs.closeSync(fd);
55
+ }
56
+ }
57
+ function sameFact(left, right, code, label) {
58
+ const item = record(left, code, label);
59
+ const other = record(right, code, label);
60
+ if (typeof item.path !== "string" ||
61
+ !Number.isSafeInteger(item.bytes) ||
62
+ typeof item.sha256 !== "string" ||
63
+ !/^[0-9a-f]{64}$/u.test(item.sha256))
64
+ fail(code, `${label} is not an exact file fact.`);
65
+ return item.path === other.path && item.bytes === other.bytes && item.sha256 === other.sha256;
66
+ }
67
+ /** The immutable repair selection of the current task job. */
68
+ export function foundryRepairSelection(context) {
69
+ if (!context.taskRoot)
70
+ fail("repair_task_required", "Repair preparation requires the current task.");
71
+ const raw = readTaskJson(context, "foundry-job.json");
72
+ if (raw.lane !== "existing-owner-draft-repair" ||
73
+ raw.task_id !== context.taskId ||
74
+ raw.workspace_id !== context.workspaceId ||
75
+ raw.actor_id !== context.actorId)
76
+ fail("repair_task_required", "Repair selection must belong to this registered task and actor.");
77
+ const repair = raw.repair;
78
+ if (!isRecord(repair))
79
+ fail("repair_task_required", "Only an existing-owner-draft-repair task can be prepared.");
80
+ for (const key of ["contract", "before", "candidate"])
81
+ if (typeof repair[key] !== "string" || !repair[key])
82
+ fail("repair_task_required", "The repair selection is incomplete.");
83
+ return Object.freeze({
84
+ kind: String(repair.kind ?? ""),
85
+ contract: repair.contract,
86
+ before: repair.before,
87
+ candidate: repair.candidate,
88
+ });
89
+ }
90
+ /**
91
+ * Strictly offline re-check of one repair scope: the three selected inputs are re-read against the
92
+ * captured task scope, then the scope rules are re-applied. No remote work happens here.
93
+ */
94
+ function resolveRepairScope(context) {
95
+ const selection = foundryRepairSelection(context);
96
+ const account = context.accountIntent;
97
+ if (!account)
98
+ fail("repair_account_required", "Repair preparation requires the owner account intent.");
99
+ const contractFile = resolveFoundryInputPath(context, selection.contract);
100
+ const beforeFile = resolveFoundryInputPath(context, selection.before);
101
+ const candidateFile = resolveFoundryInputPath(context, selection.candidate);
102
+ for (const file of [contractFile, beforeFile, candidateFile])
103
+ readFoundryInput(context, file, MAX_REPORT_BYTES);
104
+ const scope = readFoundryRepairScope({
105
+ contractFile,
106
+ beforeFile,
107
+ candidateFile,
108
+ datasetType: "process",
109
+ targetUserId: account.userId,
110
+ verifiedProjectRef: account.projectRef,
111
+ stateCode: "0",
112
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
113
+ });
114
+ return { scope, contractFile, beforeFile, candidateFile };
115
+ }
116
+ function expectationOf(context, scope, contractFile) {
117
+ const raw = JSON.parse(fs.readFileSync(contractFile, "utf8"));
118
+ const account = context.accountIntent;
119
+ return Object.freeze({
120
+ dataset_type: "process",
121
+ contract_sha256: scope.contract_sha256,
122
+ execution_id: String(raw.execution_id ?? "").trim(),
123
+ owner_user_id: account.userId,
124
+ project_ref: account.projectRef,
125
+ state_code: "0",
126
+ actions: Object.freeze(scope.actions.map((action) => ({
127
+ action_id: action.action_id,
128
+ table: action.table,
129
+ id: action.id,
130
+ version: action.version,
131
+ before_sha256: action.before_sha256,
132
+ desired_sha256: action.desired_sha256,
133
+ }))),
134
+ });
135
+ }
136
+ /**
137
+ * The single trusted owner-CLI boundary: the qualified installed package, an isolated child
138
+ * environment derived from the explicit account intent, a clean temporary working directory, no
139
+ * shell and a bounded timeout. The ambient `TIANGONG_LCA_CLI_BIN` override is never consulted.
140
+ */
141
+ function runOwnerCli(input) {
142
+ assertQualifiedFoundryRuntime(input.context, input.qualified);
143
+ const cli = resolveInstalledTiangongLcaCliPackage();
144
+ // Use the same allowlisted auth/state environment as the commit owner. An ephemeral HOME or
145
+ // XDG_STATE_HOME would hide retained CLI attempts from the read-only preflight.
146
+ const environment = createFoundryAuthenticationEnvironment(input.authentication, input.context.accountIntent?.sessionReference, process.env);
147
+ environment.TMPDIR = input.temporary;
148
+ environment.TEMP = input.temporary;
149
+ environment.TMP = input.temporary;
150
+ const completed = childProcess.spawnSync(process.execPath, [cli.binPath, ...input.argv], {
151
+ cwd: input.temporary,
152
+ env: environment,
153
+ shell: false,
154
+ timeout: CLI_TIMEOUT_MS,
155
+ encoding: "utf8",
156
+ maxBuffer: MAX_REPORT_BYTES,
157
+ });
158
+ delete environment.TIANGONG_LCA_ACCESS_TOKEN;
159
+ assertQualifiedFoundryRuntime(input.context, input.qualified);
160
+ if (completed.error || completed.signal || ![0, 1, 2].includes(completed.status ?? -1))
161
+ fail("repair_cli_unavailable", "The qualified owner CLI could not complete its read-only operation.");
162
+ const stdout = typeof completed.stdout === "string" ? completed.stdout.trim() : "";
163
+ if (!stdout)
164
+ fail("repair_cli_report_missing", "The owner CLI returned no machine-readable report.");
165
+ let report;
166
+ try {
167
+ report = JSON.parse(stdout);
168
+ }
169
+ catch {
170
+ fail("repair_cli_report_invalid", "The owner CLI report is not one JSON object.");
171
+ }
172
+ const selectedInput = input.argv[input.argv.indexOf("--input") + 1];
173
+ if (input.argv.indexOf("--input") < 0 ||
174
+ typeof report.input_path !== "string" ||
175
+ path.resolve(report.input_path) !== path.resolve(selectedInput))
176
+ fail("repair_cli_report_invalid", "Repair owner report must name the exact selected input.");
177
+ const out = input.argv[input.argv.indexOf("--out-dir") + 1];
178
+ if (!out || input.argv.indexOf("--out-dir") < 0)
179
+ fail("repair_cli_report_invalid", "A repair read must bind its evidence output directory.");
180
+ fs.writeFileSync(path.join(out, "owner-report.json"), JSON.stringify(report, null, 2) + "\n", {
181
+ mode: 0o600,
182
+ flag: "wx",
183
+ });
184
+ return { exit: completed.status, report };
185
+ }
186
+ /**
187
+ * Read the already-registered preparation report for the current task scope. The report and every
188
+ * CLI evidence file it references must exist in the same producer index with exact bytes and hash; a
189
+ * report that names this scope but fails verification is rejected rather than ignored.
190
+ */
191
+ export function readFoundryRepairPreparation(context, entries) {
192
+ const selection = foundryRepairSelection(context);
193
+ const currentScope = resolveRepairScope(context);
194
+ for (const file of [selection.contract, selection.before, selection.candidate])
195
+ readFoundryInput(context, resolveFoundryInputPath(context, file), MAX_REPORT_BYTES);
196
+ const selected = [selection.contract, selection.before, selection.candidate].map((file) => captureFoundryInput(resolveFoundryInputPath(context, file)));
197
+ const candidates = entries
198
+ .filter((entry) => entry.command === FOUNDRY_REPAIR_PREFLIGHT_COMMAND &&
199
+ path.basename(entry.path) === FOUNDRY_REPAIR_REPORT_NAME)
200
+ .sort((left, right) => left.sequence - right.sequence)
201
+ .reverse();
202
+ for (const entry of candidates) {
203
+ const artifact = readWorkflowArtifact(context, entry);
204
+ const value = artifact.value;
205
+ if (value.schema !== FOUNDRY_REPAIR_PREPARATION_SCHEMA)
206
+ fail("repair_report_invalid", "An indexed repair preparation report has an unknown schema.");
207
+ const inputs = record(value.inputs, "repair_report_invalid", "Report inputs");
208
+ if (!sameFact(inputs.contract, selected[0], "repair_report_invalid", "Report contract") ||
209
+ !sameFact(inputs.before, selected[1], "repair_report_invalid", "Report before rows") ||
210
+ !sameFact(inputs.candidate, selected[2], "repair_report_invalid", "Report candidate rows"))
211
+ fail("repair_report_invalid", "Indexed repair evidence differs from the immutable task scope.");
212
+ if (!["prepared", "no_change_verified", "blocked"].includes(String(value.status)) ||
213
+ value.remote_writes !== 0 ||
214
+ value.publication_ready !== false ||
215
+ !Array.isArray(value.blockers) ||
216
+ (value.status === "blocked" ? value.blockers.length === 0 : value.blockers.length !== 0))
217
+ fail("repair_report_invalid", "Repair evidence carries inconsistent readiness or effect claims.");
218
+ if (sha256Json(value.scope) !== sha256Json(currentScope.scope) ||
219
+ sha256Json(value.account) !==
220
+ sha256Json({
221
+ project_ref: context.accountIntent.projectRef,
222
+ user_id: context.accountIntent.userId,
223
+ state_code: "0",
224
+ account_mode: context.accountIntent.accountMode ?? "ordinary",
225
+ }))
226
+ fail("repair_report_invalid", "Repair evidence must bind the current exact scope and account.");
227
+ const evidence = record(value.evidence, "repair_report_invalid", "Report evidence");
228
+ if (!Array.isArray(evidence.files) || (value.status !== "blocked" && !evidence.files.length))
229
+ fail("repair_report_invalid", "A repair preparation report must bind its CLI evidence files.");
230
+ const verified = new Map();
231
+ for (const item of evidence.files) {
232
+ const bound = record(item, "repair_report_invalid", "Evidence file");
233
+ const match = entries.find((candidate) => candidate.path === bound.path &&
234
+ candidate.operation_id === entry.operation_id &&
235
+ candidate.command === FOUNDRY_REPAIR_PREFLIGHT_COMMAND &&
236
+ candidate.receipt.path === entry.receipt.path &&
237
+ candidate.receipt.sha256 === entry.receipt.sha256 &&
238
+ candidate.bytes === bound.bytes &&
239
+ candidate.sha256 === bound.sha256);
240
+ if (!match)
241
+ fail("repair_report_invalid", "Every CLI evidence file must be registered by the same producer with exact bytes and hash.");
242
+ const observed = captureFoundryInput(resolveFoundryOutput(context, match.path));
243
+ if (observed.bytes !== match.bytes || observed.sha256 !== match.sha256)
244
+ fail("repair_report_invalid", "Registered CLI evidence bytes changed.");
245
+ if (typeof bound.role !== "string" || verified.has(bound.role))
246
+ fail("repair_report_invalid", "CLI evidence roles must be explicit and unique.");
247
+ verified.set(bound.role, match);
248
+ }
249
+ const ownerReport = (role, input) => {
250
+ const file = verified.get(`${role}:out/owner-report.json`);
251
+ if (!file)
252
+ fail("repair_report_invalid", "Repair evidence is missing an owner report.");
253
+ const report = readWorkflowArtifact(context, file).value;
254
+ if (report.input_path !== input)
255
+ fail("repair_report_invalid", "An owner report names another input selection.");
256
+ return report;
257
+ };
258
+ const expected = expectationOf(context, currentScope.scope, currentScope.contractFile);
259
+ const verifyRoots = (role) => {
260
+ const report = ownerReport(`verify-remote-${role}`, role === "before" ? currentScope.beforeFile : currentScope.candidateFile);
261
+ const checks = verified.get(`verify-remote-${role}:out/outputs/remote-verification.jsonl`);
262
+ if (!checks)
263
+ fail("repair_report_invalid", "Repair evidence is missing its root check records.");
264
+ return proveFoundryRepairRemoteIntegrity({
265
+ report,
266
+ checks: readRemoteChecks(resolveFoundryOutput(context, checks.path)),
267
+ expectation: expected,
268
+ beforeRows: readRows(currentScope.beforeFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
269
+ candidateRows: readRows(currentScope.candidateFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
270
+ content: role,
271
+ });
272
+ };
273
+ if (value.status === "prepared") {
274
+ if (currentScope.scope.status !== "dispatchable")
275
+ fail("repair_report_invalid", "A no-op is not a write preparation.");
276
+ parseFoundryRepairDryRunReport(ownerReport("dry-run", currentScope.candidateFile), expected);
277
+ verifyRoots("before");
278
+ }
279
+ else if (value.status === "no_change_verified") {
280
+ if (currentScope.scope.status !== "satisfied" ||
281
+ currentScope.scope.actions.some((action) => action.before_sha256 !== action.desired_sha256))
282
+ fail("repair_report_invalid", "No-change completion requires identical complete before and desired content.");
283
+ parseFoundryRepairValidateReport(ownerReport("validate", currentScope.candidateFile), expected);
284
+ verifyRoots("before");
285
+ verifyRoots("candidate");
286
+ }
287
+ return Object.freeze({ entry, file: artifact.file, value });
288
+ }
289
+ return null;
290
+ }
291
+ /**
292
+ * Prepare one repair through the qualified owner CLI and register the result as trusted producer
293
+ * evidence. Remote reads run outside the task metadata lock; registration happens inside the store's
294
+ * operation (which re-verifies inputs and producers), and a repeated preparation returns the
295
+ * already-registered report without issuing another remote call.
296
+ */
297
+ export async function prepareFoundryRepair(context, qualified, _entries, authentication) {
298
+ const currentEntries = await withFoundryTaskMetadata(context, (_, index) => [...index], {
299
+ verifyCommands: [FOUNDRY_REPAIR_PREFLIGHT_COMMAND],
300
+ });
301
+ const existing = readFoundryRepairPreparation(context, currentEntries);
302
+ if (existing && existing.value.status !== "blocked")
303
+ return existing.value;
304
+ assertQualifiedFoundryRuntime(context, qualified);
305
+ const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
306
+ const { scope, contractFile, beforeFile, candidateFile } = resolveRepairScope(context);
307
+ const expectation = expectationOf(context, scope, contractFile);
308
+ const temporary = createWorkflowDirectory(context, "tmp/repair-");
309
+ const blockers = [];
310
+ const evidenceDetails = [];
311
+ const stagedTrees = [];
312
+ let status = "blocked";
313
+ try {
314
+ // The remote phase runs outside the task metadata lock; the pre-check re-verifies the selected
315
+ // inputs and the producers of any earlier repair preflight before the owner CLI is invoked.
316
+ await withFoundryTaskMetadata(context, () => undefined, {
317
+ verifyCommands: [FOUNDRY_REPAIR_PREFLIGHT_COMMAND],
318
+ });
319
+ try {
320
+ if (scope.status === "dispatchable") {
321
+ const outDir = path.join(temporary, "dry-run", "out");
322
+ fs.mkdirSync(outDir, { recursive: true, mode: 0o700 });
323
+ stagedTrees.push({ name: "dry-run", directory: path.join(temporary, "dry-run") });
324
+ const run = runOwnerCli({
325
+ context,
326
+ qualified,
327
+ authentication,
328
+ temporary,
329
+ argv: [
330
+ "dataset",
331
+ "save-draft",
332
+ "--type",
333
+ "process",
334
+ "--input",
335
+ candidateFile,
336
+ "--out-dir",
337
+ outDir,
338
+ "--execution-contract",
339
+ contractFile,
340
+ "--dry-run",
341
+ "--json",
342
+ ],
343
+ });
344
+ const dryRun = parseFoundryRepairDryRunReport(run.report, expectation);
345
+ if (run.exit !== 0)
346
+ fail("repair_cli_failed", "Prepared CLI rows require a successful preflight exit.");
347
+ evidenceDetails.push({
348
+ role: "dry_run",
349
+ exit: run.exit,
350
+ report: JSON.parse(JSON.stringify(dryRun)),
351
+ });
352
+ const verifyDir = path.join(temporary, "verify-remote-before", "out");
353
+ fs.mkdirSync(verifyDir, { recursive: true, mode: 0o700 });
354
+ stagedTrees.push({
355
+ name: "verify-remote-before",
356
+ directory: path.join(temporary, "verify-remote-before"),
357
+ });
358
+ const verified = runOwnerCli({
359
+ context,
360
+ qualified,
361
+ authentication,
362
+ temporary,
363
+ argv: [
364
+ "dataset",
365
+ "verify-remote",
366
+ "--input",
367
+ beforeFile,
368
+ "--out-dir",
369
+ verifyDir,
370
+ "--root-policy",
371
+ "existing",
372
+ "--compare-root-payload",
373
+ "--target-user-id",
374
+ expectation.owner_user_id,
375
+ "--state-code",
376
+ "0",
377
+ "--json",
378
+ ],
379
+ });
380
+ const referenceProof = proveFoundryRepairRemoteIntegrity({
381
+ report: verified.report,
382
+ checks: readRemoteChecks(path.join(verifyDir, "outputs", "remote-verification.jsonl")),
383
+ expectation,
384
+ beforeRows: readRows(beforeFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
385
+ candidateRows: readRows(candidateFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
386
+ content: "before",
387
+ });
388
+ if (verified.exit !== (referenceProof.retained_references ? 1 : 0))
389
+ fail("repair_cli_failed", "Existing reference closure requires a successful owner read.");
390
+ evidenceDetails.push({
391
+ role: "reference_verification",
392
+ exit: verified.exit,
393
+ counts: { ...referenceProof.counts },
394
+ retained_references: referenceProof.retained_references,
395
+ });
396
+ status = "prepared";
397
+ }
398
+ else {
399
+ // No-change scope: the CLI metadata dry run legitimately rejects a candidate that changes
400
+ // nothing, so the no-op proof is a local three-layer validation plus a fresh exact remote
401
+ // readback of the stored before and candidate content. Only a fully passed readback may set
402
+ // the status, and the result is never publication ready.
403
+ const validateDir = path.join(temporary, "validate", "out");
404
+ fs.mkdirSync(validateDir, { recursive: true, mode: 0o700 });
405
+ stagedTrees.push({ name: "validate", directory: path.join(temporary, "validate") });
406
+ const validationRun = runOwnerCli({
407
+ context,
408
+ qualified,
409
+ authentication,
410
+ temporary,
411
+ argv: [
412
+ "dataset",
413
+ "validate",
414
+ "--type",
415
+ "process",
416
+ "--input",
417
+ candidateFile,
418
+ "--out-dir",
419
+ validateDir,
420
+ "--json",
421
+ ],
422
+ });
423
+ const validated = parseFoundryRepairValidateReport(validationRun.report, expectation);
424
+ // CLI validation uses exit 1 for the retained unknown-annual evidence gap; the parser
425
+ // separately requires schema/content/multilingual success. Exit 2 is not validation proof.
426
+ if (validationRun.exit !== 0 && validationRun.exit !== 1)
427
+ fail("repair_cli_failed", "No-change validation requires a completed owner validation run.");
428
+ evidenceDetails.push({
429
+ role: "validate",
430
+ exit: validationRun.exit,
431
+ report: JSON.parse(JSON.stringify(validated)),
432
+ });
433
+ const remote = [];
434
+ for (const [role, file] of [
435
+ ["before", beforeFile],
436
+ ["candidate", candidateFile],
437
+ ]) {
438
+ const remoteDir = path.join(temporary, `verify-remote-${role}`, "out");
439
+ fs.mkdirSync(remoteDir, { recursive: true, mode: 0o700 });
440
+ stagedTrees.push({
441
+ name: `verify-remote-${role}`,
442
+ directory: path.join(temporary, `verify-remote-${role}`),
443
+ });
444
+ const remoteRun = runOwnerCli({
445
+ context,
446
+ qualified,
447
+ authentication,
448
+ temporary,
449
+ argv: [
450
+ "dataset",
451
+ "verify-remote",
452
+ "--input",
453
+ file,
454
+ "--out-dir",
455
+ remoteDir,
456
+ "--root-policy",
457
+ "existing",
458
+ "--compare-root-payload",
459
+ "--target-user-id",
460
+ context.accountIntent.userId,
461
+ "--state-code",
462
+ "0",
463
+ "--json",
464
+ ],
465
+ });
466
+ const integrity = proveFoundryRepairRemoteIntegrity({
467
+ report: remoteRun.report,
468
+ checks: readRemoteChecks(path.join(remoteDir, "outputs", "remote-verification.jsonl")),
469
+ expectation,
470
+ beforeRows: readRows(beforeFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
471
+ candidateRows: readRows(candidateFile, (file) => readFoundryInput(context, file, MAX_REPORT_BYTES).toString("utf8")),
472
+ content: role,
473
+ });
474
+ if (remoteRun.exit !== (integrity.retained_references ? 1 : 0))
475
+ fail("repair_cli_failed", "Exact remote verification requires a successful owner exit.");
476
+ remote.push({
477
+ role,
478
+ exit: remoteRun.exit,
479
+ counts: { ...integrity.counts },
480
+ retained_references: integrity.retained_references,
481
+ });
482
+ }
483
+ evidenceDetails.push({ role: "remote_readback", proofs: remote });
484
+ status = "no_change_verified";
485
+ }
486
+ }
487
+ catch (error) {
488
+ if (!(error instanceof FoundryContextError))
489
+ throw error;
490
+ blockers.push({ code: error.code, message: error.message });
491
+ status = "blocked";
492
+ evidenceDetails.push({ role: "blocked", code: error.code });
493
+ }
494
+ return await runFoundryTaskOperation(context, {
495
+ command: FOUNDRY_REPAIR_PREFLIGHT_COMMAND,
496
+ options: {
497
+ task: context.taskId,
498
+ scope: scope.contract_sha256,
499
+ status,
500
+ nonce: randomUUID(),
501
+ },
502
+ validateCurrent: () => {
503
+ for (const file of [contractFile, beforeFile, candidateFile])
504
+ readFoundryInput(context, file, MAX_REPORT_BYTES);
505
+ resolveRepairScope(context);
506
+ },
507
+ }, (operation) => {
508
+ const stage = createWorkflowStageDirectory(context, operation, "repair");
509
+ const files = [];
510
+ for (const tree of stagedTrees) {
511
+ const visit = (directory) => {
512
+ for (const name of fs.readdirSync(directory).sort()) {
513
+ const absolute = path.join(directory, name);
514
+ const stat = fs.lstatSync(absolute);
515
+ if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory()))
516
+ fail("repair_output_invalid", "Repair evidence must remain regular files and directories.");
517
+ if (stat.isDirectory()) {
518
+ visit(absolute);
519
+ continue;
520
+ }
521
+ const file = path.relative(tree.directory, absolute);
522
+ const relative = path.join("cli", tree.name, file);
523
+ operation.writeText(path.join(stage, relative), fs.readFileSync(absolute));
524
+ files.push({
525
+ role: `${tree.name}:${file.split(path.sep).join("/")}`,
526
+ path: taskRelative(context, path.join(stage, relative)),
527
+ bytes: fs.statSync(path.join(stage, relative)).size,
528
+ sha256: captureFoundryInput(path.join(stage, relative)).sha256,
529
+ });
530
+ }
531
+ };
532
+ visit(tree.directory);
533
+ }
534
+ const report = {
535
+ schema: FOUNDRY_REPAIR_PREPARATION_SCHEMA,
536
+ status,
537
+ scope: {
538
+ kind: scope.kind,
539
+ status: scope.status,
540
+ contract_sha256: scope.contract_sha256,
541
+ rows_sha256: scope.rows_sha256,
542
+ changed_paths: [...scope.changed_paths],
543
+ actions: scope.actions.map((action) => ({ ...action })),
544
+ },
545
+ contract: {
546
+ role: "execution_contract",
547
+ ...captureFoundryInput(contractFile),
548
+ canonical_sha256: scope.contract_sha256,
549
+ execution_id: expectation.execution_id,
550
+ operation: "save_draft",
551
+ },
552
+ inputs: {
553
+ contract: captureFoundryInput(contractFile),
554
+ before: captureFoundryInput(beforeFile),
555
+ candidate: captureFoundryInput(candidateFile),
556
+ },
557
+ account: {
558
+ project_ref: context.accountIntent.projectRef,
559
+ user_id: context.accountIntent.userId,
560
+ state_code: "0",
561
+ account_mode: context.accountIntent.accountMode ?? "ordinary",
562
+ },
563
+ runtime: {
564
+ cli_source: "installed_package",
565
+ qualification_sha256: identity.runtimeQualificationSha256,
566
+ authentication_mode: identity.mode,
567
+ },
568
+ evidence: { files, detail: evidenceDetails },
569
+ remote_writes: 0,
570
+ publication_ready: false,
571
+ blockers,
572
+ };
573
+ operation.writeJson(path.join(stage, FOUNDRY_REPAIR_REPORT_NAME), report);
574
+ return report;
575
+ });
576
+ }
577
+ finally {
578
+ fs.rmSync(temporary, { recursive: true, force: true });
579
+ }
580
+ }