@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,313 @@
1
+ import { validateUniqueRootReadbacks } from "./post-write-root-proof.js";
2
+ import { FoundryContextError } from "./foundry-runtime-context.js";
3
+ /**
4
+ * Pure, strict parsers for the owner CLI evidence a repair preparation binds.
5
+ *
6
+ * This module never spawns a process and never reads the ambient environment: the owner CLI is
7
+ * invoked by the repair preparation owner through the qualified runtime only, and every report that
8
+ * comes back is validated here against the exact contract, scope and expectation Foundry admitted.
9
+ * Anything unexpected - a wrong hash, an extra or reordered row, a claimed readback, a consumed
10
+ * attempt, a false mode - fails closed instead of being accepted as success.
11
+ */
12
+ export const FOUNDRY_REPAIR_PREPARATION_SCHEMA = "tiangong-foundry.repair-preparation.v1";
13
+ export const FOUNDRY_REPAIR_EVIDENCE_SCHEMA = "tiangong-foundry.repair-cli-evidence.v1";
14
+ const shaPattern = /^[0-9a-f]{64}$/u;
15
+ const admissionKeys = [
16
+ "schema",
17
+ "status",
18
+ "policy",
19
+ "before_sha256",
20
+ "desired_sha256",
21
+ "changed_paths",
22
+ "publication_ready",
23
+ ];
24
+ const admissionSchema = "dataset-draft-repair-admission.v1";
25
+ const admissionPolicy = "process-metadata-unknown-annual.v1";
26
+ const annualOnlyAuthoringCodes = new Set(["annual_supply_or_production_volume_missing"]);
27
+ const validationLayerNames = ["schema", "authoring_evidence", "content", "multilingual"];
28
+ function fail(code, message) {
29
+ throw new FoundryContextError(code, message);
30
+ }
31
+ function isRecord(value) {
32
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
33
+ }
34
+ function record(value, code, label) {
35
+ if (!isRecord(value))
36
+ fail(code, `${label} must be an object.`);
37
+ return value;
38
+ }
39
+ function exactKeys(value, keys, code, label) {
40
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
41
+ fail(code, `${label} has missing or unsupported fields.`);
42
+ }
43
+ function sha(value, code, label) {
44
+ if (typeof value !== "string" || !shaPattern.test(value))
45
+ fail(code, `${label} must be a lowercase SHA-256 hex digest.`);
46
+ return value;
47
+ }
48
+ function text(value, code, label) {
49
+ if (typeof value !== "string" || !value.trim())
50
+ fail(code, `${label} must be a non-empty string.`);
51
+ return value.trim();
52
+ }
53
+ function validationLayers(value, code, label) {
54
+ const layers = record(value, code, label);
55
+ for (const name of validationLayerNames) {
56
+ const layer = record(layers[name], code, `${label}.${name}`);
57
+ if (!["passed", "failed"].includes(String(layer.status)))
58
+ fail(code, `${label}.${name}.status must be passed or failed.`);
59
+ if (!Array.isArray(layer.issues) ||
60
+ layer.issue_count !== layer.issues.length ||
61
+ (layer.status === "passed" && layer.issues.length !== 0) ||
62
+ (layer.status === "failed" && layer.issues.length === 0))
63
+ fail(code, `${label}.${name} has inconsistent issue evidence.`);
64
+ }
65
+ return layers;
66
+ }
67
+ function layerStatus(layers, name) {
68
+ return String(record(layers[name], "repair_evidence_invalid", name).status);
69
+ }
70
+ function layerIssues(layers, name) {
71
+ const layer = record(layers[name], "repair_evidence_invalid", name);
72
+ if (!Array.isArray(layer.issues))
73
+ fail("repair_evidence_invalid", `${name} layer must report its issues array.`);
74
+ return layer.issues.map((issue) => record(issue, "repair_evidence_invalid", `${name} issue`));
75
+ }
76
+ function parseAdmission(value, action) {
77
+ const admission = record(value, "repair_admission_invalid", "Draft repair admission");
78
+ exactKeys(admission, admissionKeys, "repair_admission_invalid", "Draft repair admission");
79
+ if (admission.schema !== admissionSchema ||
80
+ admission.status !== "admitted" ||
81
+ admission.policy !== admissionPolicy ||
82
+ admission.publication_ready !== false)
83
+ fail("repair_admission_invalid", "Draft repair admission schema, status, policy or publication flag is invalid.");
84
+ const before = sha(admission.before_sha256, "repair_admission_invalid", "Admission before hash");
85
+ const desired = sha(admission.desired_sha256, "repair_admission_invalid", "Admission desired hash");
86
+ if (before !== action.before_sha256 || desired !== action.desired_sha256)
87
+ fail("repair_admission_invalid", "Draft repair admission must bind the exact action before and desired content.");
88
+ if (!Array.isArray(admission.changed_paths) ||
89
+ !admission.changed_paths.length ||
90
+ admission.changed_paths.some((path) => typeof path !== "string" || !path.trim()))
91
+ fail("repair_admission_invalid", "Draft repair admission must list its changed paths.");
92
+ return Object.freeze({
93
+ schema: admissionSchema,
94
+ status: "admitted",
95
+ policy: admissionPolicy,
96
+ before_sha256: before,
97
+ desired_sha256: desired,
98
+ changed_paths: Object.freeze([...admission.changed_paths]),
99
+ publication_ready: false,
100
+ });
101
+ }
102
+ /** The narrow unknown-annual exception: schema/content/multilingual pass, only the annual gap fails. */
103
+ function assertAnnualOnlyAuthoringGap(layers) {
104
+ for (const name of ["schema", "content", "multilingual"])
105
+ if (layerStatus(layers, name) !== "passed")
106
+ fail("repair_evidence_invalid", `The unknown-annual exception requires the ${name} validation layer to pass.`);
107
+ if (layerStatus(layers, "authoring_evidence") !== "failed")
108
+ fail("repair_evidence_invalid", "A metadata repair row must keep its authoring evidence status truthful.");
109
+ const issues = layerIssues(layers, "authoring_evidence");
110
+ if (!issues.length || issues.some((issue) => !annualOnlyAuthoringCodes.has(String(issue.code))))
111
+ fail("repair_evidence_invalid", "The only admissible authoring gap is the unknown annual supply or production volume.");
112
+ }
113
+ /**
114
+ * Validate the owner CLI's read-only `dataset save-draft --dry-run` report for one changed-scope
115
+ * repair: nothing dispatched, nothing consumed, every action prepared and bound to the exact scope.
116
+ */
117
+ export function parseFoundryRepairDryRunReport(report, expectation) {
118
+ const value = record(report, "repair_dry_run_invalid", "Owner CLI dry-run report");
119
+ if (value.schema_version !== 2 ||
120
+ value.status !== "completed" ||
121
+ value.requested_type !== expectation.dataset_type ||
122
+ value.mode !== "dry_run" ||
123
+ value.commit !== false)
124
+ fail("repair_dry_run_invalid", "The owner CLI report must prove a read-only dry run with commit=false.");
125
+ const bound = record(value.execution_contract, "repair_dry_run_invalid", "Bound contract");
126
+ if (bound.sha256 !== expectation.contract_sha256 ||
127
+ bound.execution_id !== expectation.execution_id ||
128
+ bound.target_mode !== "owner_draft")
129
+ fail("repair_dry_run_invalid", "The owner CLI report must bind the exact canonical contract Foundry admitted.");
130
+ const counts = record(value.counts, "repair_dry_run_invalid", "Dry-run counts");
131
+ const expectedActions = expectation.actions.length;
132
+ if (expectation.state_code !== "0" ||
133
+ expectedActions === 0 ||
134
+ counts.selected !== expectedActions ||
135
+ counts.prepared !== expectedActions ||
136
+ counts.executed !== 0 ||
137
+ counts.failed !== 0 ||
138
+ counts.blocked !== 0 ||
139
+ counts.unknown !== 0 ||
140
+ counts.attempts_consumed !== 0)
141
+ fail("repair_dry_run_invalid", "A repair preflight must prepare every selected action with zero writes, zero blocks and zero consumed attempts.");
142
+ const reportRows = Array.isArray(value.rows) ? value.rows : [];
143
+ if (reportRows.length !== expectedActions)
144
+ fail("repair_dry_run_invalid", "The dry-run report must carry exactly one row per action.");
145
+ const rows = expectation.actions.map((action, index) => {
146
+ const row = record(reportRows[index], "repair_dry_run_invalid", `Row ${index + 1}`);
147
+ if (row.index !== index ||
148
+ row.type !== expectation.dataset_type ||
149
+ row.table !== action.table ||
150
+ row.id !== action.id ||
151
+ row.version !== action.version ||
152
+ row.action_id !== action.action_id ||
153
+ row.desired_sha256 !== action.desired_sha256 ||
154
+ row.status !== "prepared" ||
155
+ row.operation !== "would_sync" ||
156
+ row.attempt_consumed !== false ||
157
+ row.replayed !== false)
158
+ fail("repair_dry_run_invalid", `Row ${index + 1} does not match the admitted action, order, draft operation or un-attempted state.`);
159
+ // A read-only preflight never claims a readback of the desired content.
160
+ if (row.readback !== "not_performed")
161
+ fail("repair_dry_run_invalid", `Row ${index + 1} must not claim a post-write readback.`);
162
+ const visible = record(row.visible_row, "repair_dry_run_invalid", "Fresh owner-draft observation");
163
+ if (visible.id !== action.id ||
164
+ visible.version !== action.version ||
165
+ visible.user_id !== expectation.owner_user_id ||
166
+ visible.state_code !== 0)
167
+ fail("repair_dry_run_invalid", `Row ${index + 1} must bind the admitted owner account.`);
168
+ const validation = record(row.validation, "repair_dry_run_invalid", `Row ${index + 1} validation`);
169
+ const payloadSha256 = sha(validation.payload_sha256, "repair_dry_run_invalid", `Row ${index + 1} validation payload hash`);
170
+ if (payloadSha256 !== action.desired_sha256)
171
+ fail("repair_dry_run_invalid", `Row ${index + 1} validation must hash the exact admitted candidate payload.`);
172
+ const layers = validationLayers(validation.validation_layers, "repair_dry_run_invalid", `Row ${index + 1} layers`);
173
+ let admission = null;
174
+ if (row.draft_repair_admission !== undefined && row.draft_repair_admission !== null) {
175
+ if (validation.ok !== false)
176
+ fail("repair_dry_run_invalid", `Row ${index + 1} must not claim a passing validation alongside a repair admission.`);
177
+ assertAnnualOnlyAuthoringGap(layers);
178
+ admission = parseAdmission(row.draft_repair_admission, action);
179
+ }
180
+ else if (validation.ok !== true) {
181
+ fail("repair_dry_run_invalid", `Row ${index + 1} is neither fully valid nor covered by an admitted metadata repair exception.`);
182
+ }
183
+ else if (validationLayerNames.some((name) => layerStatus(layers, name) !== "passed" || layerIssues(layers, name).length !== 0)) {
184
+ fail("repair_dry_run_invalid", `Row ${index + 1} claims validity while a validation layer failed or retains issues.`);
185
+ }
186
+ return Object.freeze({
187
+ index,
188
+ action_id: action.action_id,
189
+ table: action.table,
190
+ id: action.id,
191
+ version: action.version,
192
+ desired_sha256: action.desired_sha256,
193
+ validation_payload_sha256: payloadSha256,
194
+ validation_layers: layers,
195
+ admission,
196
+ });
197
+ });
198
+ return Object.freeze({
199
+ schema: FOUNDRY_REPAIR_EVIDENCE_SCHEMA,
200
+ kind: "metadata_dry_run",
201
+ mode: "dry_run",
202
+ commit: false,
203
+ status: text(value.status, "repair_dry_run_invalid", "Dry-run status"),
204
+ contract_sha256: expectation.contract_sha256,
205
+ execution_id: expectation.execution_id,
206
+ rows: Object.freeze(rows),
207
+ });
208
+ }
209
+ /**
210
+ * Validate the local `dataset validate` report used by the no-change path. The candidate may be
211
+ * authoring-incomplete (unknown annual volume) but must never be schema, content or multilingual
212
+ * invalid, and its payload hash must match the admitted content exactly.
213
+ */
214
+ export function parseFoundryRepairValidateReport(report, expectation) {
215
+ const value = record(report, "repair_validate_invalid", "Local validation report");
216
+ if (!Array.isArray(value.rows) || !value.rows.length)
217
+ fail("repair_validate_invalid", "Local validation must report every selected row.");
218
+ const wanted = expectation.actions.map((action) => action.desired_sha256).sort();
219
+ const seen = new Set();
220
+ for (const entry of value.rows) {
221
+ const row = record(entry, "repair_validate_invalid", "Validation row");
222
+ const payloadSha256 = sha(row.payload_sha256, "repair_validate_invalid", "Validation row payload hash");
223
+ if (!wanted.includes(payloadSha256))
224
+ fail("repair_validate_invalid", "Every validated row must hash the exact admitted repair content.");
225
+ if (seen.has(payloadSha256))
226
+ fail("repair_validate_invalid", "Validation must report each selected identity exactly once.");
227
+ seen.add(payloadSha256);
228
+ const layers = validationLayers(row.validation_layers, "repair_validate_invalid", "Row layers");
229
+ for (const name of ["schema", "content", "multilingual"])
230
+ if (layerStatus(layers, name) !== "passed")
231
+ fail("repair_validate_invalid", `The no-change proof requires the ${name} validation layer to pass.`);
232
+ const authoring = layerStatus(layers, "authoring_evidence");
233
+ if (authoring === "failed") {
234
+ const issues = layerIssues(layers, "authoring_evidence");
235
+ if (!issues.length ||
236
+ issues.some((issue) => !annualOnlyAuthoringCodes.has(String(issue.code))))
237
+ fail("repair_validate_invalid", "A failing authoring layer is only admissible for the unknown annual supply volume gap.");
238
+ }
239
+ }
240
+ if (seen.size !== wanted.length)
241
+ fail("repair_validate_invalid", "Local validation must cover every admitted repair action.");
242
+ const first = record(value.rows[0], "repair_validate_invalid", "Validation row");
243
+ return Object.freeze({
244
+ payload_sha256: sha(first.payload_sha256, "repair_validate_invalid", "Validation row payload hash"),
245
+ validation_layers: validationLayers(first.validation_layers, "repair_validate_invalid", "Validation layers"),
246
+ });
247
+ }
248
+ /**
249
+ * Validate the `dataset verify-remote --compare-root-payload` report. Only a fully passed remote
250
+ * readback with zero blockers, zero payload mismatches and no non-ok check status may support the
251
+ * no-change proof; the same check runs for the before and the candidate rows.
252
+ */
253
+ export function parseFoundryRepairRemoteReport(report, expectation) {
254
+ const value = record(report, "repair_remote_invalid", "Remote verification report");
255
+ if (value.status !== "passed_remote_verification")
256
+ fail("repair_remote_invalid", "The no-change proof requires a passed remote verification against the current rows.");
257
+ if (value.root_policy !== "existing")
258
+ fail("repair_remote_invalid", "The no-change proof requires the existing root policy.");
259
+ const counts = record(value.counts, "repair_remote_invalid", "Remote verification counts");
260
+ const rows = counts.rows;
261
+ const references = counts.references;
262
+ const checks = counts.checked;
263
+ if (!Number.isSafeInteger(rows) ||
264
+ !Number.isSafeInteger(references) ||
265
+ !Number.isSafeInteger(checks) ||
266
+ rows !== expectation.actions.length ||
267
+ references < expectation.actions.length ||
268
+ checks !== references + expectation.actions.length ||
269
+ counts.blockers !== 0)
270
+ fail("repair_remote_invalid", "Remote verification must cover every selected root and reference with zero blockers.");
271
+ if (counts.root_readback_checks !== expectation.actions.length ||
272
+ counts.root_payload_mismatches !== 0 ||
273
+ !Array.isArray(value.blockers) ||
274
+ value.blockers.length !== 0)
275
+ fail("repair_remote_invalid", "A no-change proof requires exact root payload readback with zero mismatches.");
276
+ const byStatus = record(counts.by_status, "repair_remote_invalid", "Remote status counts");
277
+ for (const [status, count] of Object.entries(byStatus))
278
+ if (!Number.isSafeInteger(count) || count < 0)
279
+ fail("repair_remote_invalid", "Remote status counts must be nonnegative integers.");
280
+ else if (status !== "ok" && count > 0)
281
+ fail("repair_remote_invalid", `Remote verification reported a non-ok check status (${status}).`);
282
+ if (byStatus.ok !== checks)
283
+ fail("repair_remote_invalid", "Remote verification must account for every check as passed.");
284
+ return Object.freeze({
285
+ rows,
286
+ references: references,
287
+ checks: checks,
288
+ });
289
+ }
290
+ /** Bind the actual JSONL root proofs, rather than trusting summary counters. */
291
+ export function assertFoundryRepairRootProof(report, checks, expectation, content) {
292
+ const counts = parseFoundryRepairRemoteReport(report, expectation);
293
+ if (!Array.isArray(checks) || checks.length !== counts.checks)
294
+ fail("repair_remote_invalid", "Remote check records must match the reported check count.");
295
+ const records = checks.map((value) => record(value, "repair_remote_invalid", "Remote check"));
296
+ if (records.some((value) => value.status !== "ok"))
297
+ fail("repair_remote_invalid", "Every recorded remote check must pass.");
298
+ const proof = validateUniqueRootReadbacks({
299
+ intended: expectation.actions.map((action, index) => ({
300
+ rowIndex: index,
301
+ table: action.table,
302
+ id: action.id,
303
+ version: action.version,
304
+ payloadSha256: content === "before" ? action.before_sha256 : action.desired_sha256,
305
+ })),
306
+ checks: records,
307
+ targetUserId: expectation.owner_user_id,
308
+ expectedStateCode: Number(expectation.state_code),
309
+ allowTraceHashOnlyNormalization: false,
310
+ });
311
+ if (proof.blockers.length || proof.uniqueReadbackCount !== expectation.actions.length)
312
+ fail("repair_remote_invalid", "Exact root proof rejected: " + proof.blockers.map((item) => item.code).join(", "));
313
+ }
@@ -0,0 +1,26 @@
1
+ import { type FoundryRepairExpectation } from "./foundry-repair-preflight.ts";
2
+ type JsonRecord = Record<string, unknown>;
3
+ /** Derive every expectation from the unchanged selected payloads, never from the CLI's claim. */
4
+ export declare function proveFoundryRepairRemoteIntegrity(input: {
5
+ report: JsonRecord;
6
+ checks: readonly unknown[];
7
+ expectation: FoundryRepairExpectation;
8
+ beforeRows: readonly unknown[];
9
+ candidateRows: readonly unknown[];
10
+ content: "before" | "candidate";
11
+ }): {
12
+ counts: {
13
+ readonly rows: number;
14
+ readonly references: number;
15
+ readonly checks: number;
16
+ };
17
+ retained_references: null;
18
+ } | {
19
+ counts: {
20
+ rows: number;
21
+ references: number;
22
+ checks: number;
23
+ };
24
+ retained_references: import("./foundry-repair-reference-proof.ts").FoundryRepairReferenceProof;
25
+ };
26
+ export {};
@@ -0,0 +1,120 @@
1
+ import { FoundryContextError } from "./foundry-runtime-context.js";
2
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
3
+ import { collectDatasetReferences } from "./import-curation/internal/workflow-reference-closure.js";
4
+ import { sha256Json } from "./identity-preflight-proof.js";
5
+ import { assertFoundryRepairRootProof, parseFoundryRepairRemoteReport, } from "./foundry-repair-preflight.js";
6
+ import { proveRetainedRepairReferences, } from "./foundry-repair-reference-proof.js";
7
+ /** Derive every expectation from the unchanged selected payloads, never from the CLI's claim. */
8
+ export function proveFoundryRepairRemoteIntegrity(input) {
9
+ const fail = () => {
10
+ throw new FoundryContextError("repair_reference_scope_changed", "Repair reference proof requires the exact before/candidate payloads and unchanged reference occurrences.");
11
+ };
12
+ const describe = (rows, role) => {
13
+ if (rows.length !== input.expectation.actions.length)
14
+ return fail();
15
+ const seen = new Set();
16
+ return rows.map((row, rowIndex) => {
17
+ const identity = datasetIdentity(row, rowIndex, "process");
18
+ const key = `${identity.id}@${identity.version}`;
19
+ const action = input.expectation.actions.find((item) => item.id === identity.id && item.version === identity.version);
20
+ if (!action || seen.has(key))
21
+ return fail();
22
+ seen.add(key);
23
+ const expectedHash = role === "before" ? action.before_sha256 : action.desired_sha256;
24
+ if (sha256Json(identity.payload) !== expectedHash)
25
+ return fail();
26
+ const references = collectDatasetReferences(identity.payload).map((reference) => {
27
+ if (!reference.table || !reference.id || !reference.version)
28
+ return fail();
29
+ return {
30
+ row_index: rowIndex,
31
+ path: reference.path,
32
+ table: reference.table,
33
+ id: reference.id,
34
+ version: reference.version,
35
+ };
36
+ });
37
+ return {
38
+ key,
39
+ action,
40
+ references,
41
+ root: {
42
+ row_index: rowIndex,
43
+ path: "/processDataSet",
44
+ table: action.table,
45
+ id: action.id,
46
+ version: action.version,
47
+ payload_sha256: expectedHash,
48
+ },
49
+ };
50
+ });
51
+ };
52
+ const before = describe(input.beforeRows, "before"), candidate = describe(input.candidateRows, "candidate");
53
+ for (const old of before) {
54
+ const next = candidate.find((row) => row.key === old.key);
55
+ if (!next)
56
+ return fail();
57
+ const references = (items) => items.map(({ row_index: _rowIndex, ...ref }) => JSON.stringify(ref)).sort();
58
+ if (JSON.stringify(references(old.references)) !== JSON.stringify(references(next.references)))
59
+ return fail();
60
+ }
61
+ const selected = input.content === "before" ? before : candidate;
62
+ const expectation = { ...input.expectation, actions: selected.map((row) => row.action) };
63
+ if (input.report.status === "passed_remote_verification") {
64
+ const key = (value) => JSON.stringify([value.row_index, value.path, value.table, value.id, value.version]);
65
+ const wanted = selected
66
+ .flatMap((row) => row.references)
67
+ .map(key)
68
+ .sort();
69
+ const actual = input.checks
70
+ .filter((value) => value && typeof value === "object" && value.role === "reference")
71
+ .map((value) => {
72
+ const item = value;
73
+ if (item.status !== "ok" ||
74
+ (item.exact_version !== undefined && item.exact_version !== item.version))
75
+ return fail();
76
+ return key(item);
77
+ })
78
+ .sort();
79
+ const roots = input.checks.filter((value) => value &&
80
+ typeof value === "object" &&
81
+ value.role === "root" &&
82
+ !String(value.path).endsWith("#readback"));
83
+ if (JSON.stringify(actual) !== JSON.stringify(wanted) ||
84
+ roots.length !== selected.length ||
85
+ Number(input.report.counts.references) !== wanted.length + selected.length)
86
+ return fail();
87
+ const rootKeys = roots
88
+ .map((value) => {
89
+ const item = value;
90
+ return JSON.stringify([item.table, item.id, item.version, item.path]);
91
+ })
92
+ .sort();
93
+ const expectedKeys = selected
94
+ .map(({ root }) => JSON.stringify([root.table, root.id, root.version, root.path]))
95
+ .sort();
96
+ if (JSON.stringify(rootKeys) !== JSON.stringify(expectedKeys))
97
+ return fail();
98
+ assertFoundryRepairRootProof(input.report, input.checks, expectation, input.content);
99
+ return {
100
+ counts: parseFoundryRepairRemoteReport(input.report, expectation),
101
+ retained_references: null,
102
+ };
103
+ }
104
+ const proof = proveRetainedRepairReferences({
105
+ report: input.report,
106
+ checks: input.checks,
107
+ roots: selected.map((row) => row.root),
108
+ references: selected.flatMap((row) => row.references),
109
+ target_user_id: expectation.owner_user_id,
110
+ expected_state_code: 0,
111
+ });
112
+ return {
113
+ counts: {
114
+ rows: selected.length,
115
+ references: Number(proof.counts.references),
116
+ checks: Number(proof.counts.checked),
117
+ },
118
+ retained_references: proof,
119
+ };
120
+ }
@@ -0,0 +1,63 @@
1
+ type JsonRecord = Record<string, unknown>;
2
+ /**
3
+ * Derive an integrity proof for a remote verification that blocked **only** on retained references.
4
+ *
5
+ * A `version_outdated` reference means the requested version exists exactly and is simply not the
6
+ * newest published one. For a metadata repair over a draft, retaining such a reference unchanged is
7
+ * not an integrity failure, so this module separates the integrity proof from the freshness finding
8
+ * instead of letting the freshness finding veto the whole readback.
9
+ *
10
+ * This module is pure: it reads its inputs, never writes to them, spawns nothing and performs no
11
+ * I/O. It does not rewrite the CLI report, does not change the CLI's status, and does not adjust
12
+ * `counts` -- the raw status and every counter are reported back verbatim so a reader can see that
13
+ * nothing was laundered into a generic quality pass. `publication_ready` is always `false`.
14
+ *
15
+ * Everything that is not explicitly admitted fails closed: a foreign status, a non-outdated
16
+ * blocker, a reference whose exact version is not the requested one, an `ok` bucket that disagrees
17
+ * with the records, duplicate or extra records, a re-declared expectation set, and any root
18
+ * evidence that does not satisfy the unchanged strict exact-payload/owner/state rule.
19
+ */
20
+ export declare const FOUNDRY_REPAIR_REFERENCE_PROOF_SCHEMA: "tiangong-foundry.repair-reference-proof.v1";
21
+ export interface FoundryRepairExpectedReference {
22
+ readonly row_index: number;
23
+ readonly path: string;
24
+ readonly table: string;
25
+ readonly id: string;
26
+ readonly version: string;
27
+ }
28
+ export interface FoundryRepairExpectedRoot extends FoundryRepairExpectedReference {
29
+ readonly payload_sha256: string;
30
+ }
31
+ export interface FoundryRepairRetainedReferenceRequest {
32
+ readonly report: unknown;
33
+ readonly checks: readonly unknown[];
34
+ /** Exact roots: the declared payload hash is enforced by the unchanged root-proof rule. */
35
+ readonly roots: readonly FoundryRepairExpectedRoot[];
36
+ /** Every reference the caller asserts is unchanged between the before and candidate payloads. */
37
+ readonly references: readonly FoundryRepairExpectedReference[];
38
+ readonly target_user_id: string;
39
+ readonly expected_state_code: number;
40
+ }
41
+ export interface FoundryRepairOutdatedReference {
42
+ readonly row_index: number;
43
+ readonly table: string;
44
+ readonly id: string;
45
+ readonly version: string;
46
+ readonly latest_version: string;
47
+ readonly path: string;
48
+ }
49
+ export interface FoundryRepairReferenceProof {
50
+ readonly schema: typeof FOUNDRY_REPAIR_REFERENCE_PROOF_SCHEMA;
51
+ /** The CLI's own status, reported unchanged. Never `passed_remote_verification`. */
52
+ readonly raw_status: string;
53
+ readonly raw_blocker_count: number;
54
+ /** The CLI's own counters, reported unchanged. */
55
+ readonly counts: JsonRecord;
56
+ readonly root_readbacks: number;
57
+ readonly references_verified: number;
58
+ readonly ok_checks: number;
59
+ readonly outdated: readonly FoundryRepairOutdatedReference[];
60
+ readonly publication_ready: false;
61
+ }
62
+ export declare function proveRetainedRepairReferences(input: FoundryRepairRetainedReferenceRequest): FoundryRepairReferenceProof;
63
+ export {};