@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,399 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { pathToFileURL } from "node:url";
5
+ import { captureFoundryInput, createFoundryRuntimeContext, currentFoundryRuntimeManifest, FoundryContextError, } from "./foundry-runtime-context.js";
6
+ import { readTaskBytes, readTaskJson } from "./foundry-task-io.js";
7
+ import { readVerifiedTaskSnapshot } from "./foundry-task-store.js";
8
+ import { readWorkflowArtifact, workflowObject } from "./foundry-workflow-state.js";
9
+ import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
10
+ import { sha256Json } from "./identity-preflight-proof.js";
11
+ import { FOUNDRY_REPAIR_PREFLIGHT_COMMAND, FOUNDRY_REPAIR_REPORT_NAME, } from "./foundry-workflow-repair.js";
12
+ import { FOUNDRY_REPAIR_PREPARATION_SCHEMA } from "./foundry-repair-preflight.js";
13
+ /** The producer commands whose registered artifacts carry the terminal no-dispatch evidence. */
14
+ const AUTHORIZATION_COMMAND = "dataset-workflow-authorization";
15
+ const PREPARE_COMMAND = "dataset-workflow-execution-prepare";
16
+ const CONSUME_COMMAND = "dataset-workflow-execution-consume";
17
+ const OBSERVATION_COMMAND = "dataset-workflow-execution-observation";
18
+ const RESULT_COMMAND = "dataset-workflow-execution-result";
19
+ /**
20
+ * Every artifact the verdict reads is verified as a produced task input, so its operation receipt
21
+ * must itself list these exact bytes and bind the same command, plan and input scope. A forged index
22
+ * entry that borrows another operation's receipt therefore fails even with a recomputed hash chain.
23
+ */
24
+ const evidenceCommands = Object.freeze([
25
+ FOUNDRY_REPAIR_PREFLIGHT_COMMAND,
26
+ AUTHORIZATION_COMMAND,
27
+ PREPARE_COMMAND,
28
+ CONSUME_COMMAND,
29
+ OBSERVATION_COMMAND,
30
+ RESULT_COMMAND,
31
+ ]);
32
+ const OBSERVATION_NAME = "dispatch-observation.json";
33
+ const RESULT_NAME = "owner-execution-result.json";
34
+ const RESULT_SCHEMA = "tiangong-foundry.owner-execution-result.v1";
35
+ const OBSERVATION_SCHEMA = "tiangong-foundry.dispatch-observation.v1";
36
+ const READBACK_SCHEMA = "tiangong-foundry.owner-readback.v1";
37
+ const CONSUMED_SCHEMA = "tiangong-foundry.owner-attempt-consumed.v1";
38
+ /** The CLI's definite terminal row statuses; `prepared`, `executed` and `unknown` never qualify. */
39
+ const definiteFailures = new Set(["failed", "blocked"]);
40
+ /**
41
+ * Attempt events that would prove the owner CLI actually completed a dispatch. Lifecycle events such
42
+ * as `item_completed`/`batch_completed` are emitted for failed items too and prove nothing either way.
43
+ */
44
+ const succeededEvents = new Set(["attempt_succeeded", "recovery_succeeded"]);
45
+ const shaPattern = /^[0-9a-f]{64}$/u;
46
+ const maxArtifactBytes = 8 * 1024 * 1024;
47
+ function isRecord(value) {
48
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
49
+ }
50
+ function record(value) {
51
+ return isRecord(value) ? value : {};
52
+ }
53
+ /**
54
+ * Refuse one successor link. Every predicate failure uses the established refusal code, so a caller
55
+ * can never misread the bounded exception as an unchecked state.
56
+ */
57
+ function refuse(taskId, why) {
58
+ throw new FoundryContextError("facade_predecessor_readback_required", `Retained predecessor ${taskId} does not prove a no-dispatch failure (${why}); use its original owner for status/readback before any revision can continue.`);
59
+ }
60
+ /** The mutable predecessor-state fingerprint re-checked around every read of that state. */
61
+ function stability(context) {
62
+ const digest = (file) => {
63
+ const bytes = readTaskBytes(context, file);
64
+ return createHash("sha256").update(bytes).digest("hex");
65
+ };
66
+ return [
67
+ digest("foundry-job.json"),
68
+ digest("artifact-index.jsonl"),
69
+ digest("account-intent.json"),
70
+ ].join(":");
71
+ }
72
+ function latestEntry(entries, command, basename) {
73
+ return (entries
74
+ .filter((entry) => entry.command === command && path.basename(entry.path) === basename)
75
+ .sort((left, right) => left.sequence - right.sequence)
76
+ .at(-1) ?? null);
77
+ }
78
+ /**
79
+ * The strict reader of one failed native commit report. It never trusts Foundry's own counters: the
80
+ * CLI's machine report must prove that nothing was executed and no CLI attempt was consumed, that
81
+ * every row is a definite failure, and that input, contract and every action are bound to the exact
82
+ * admitted scope. Returns the refusal reason, or null when the report qualifies.
83
+ */
84
+ export function noDispatchCommitReportProblem(value, expected) {
85
+ const report = record(value);
86
+ const contract = record(report.execution_contract);
87
+ const counts = record(report.counts);
88
+ const rows = Array.isArray(report.rows) ? report.rows : null;
89
+ if (report.schema_version !== 2 ||
90
+ report.mode !== "commit" ||
91
+ report.commit !== true ||
92
+ report.requested_type !== "process" ||
93
+ report.status !== "completed_with_failures" ||
94
+ typeof report.input_path !== "string" ||
95
+ path.resolve(report.input_path) !== path.resolve(expected.candidate_path) ||
96
+ contract.sha256 !== expected.contract_sha256 ||
97
+ contract.execution_id !== expected.execution_id ||
98
+ contract.target_mode !== "owner_draft" ||
99
+ typeof contract.path !== "string" ||
100
+ !contract.path)
101
+ return "the terminal report must remain a bound native commit attempt of this exact candidate and contract";
102
+ if (rows === null ||
103
+ rows.length !== expected.actions.length ||
104
+ counts.selected !== expected.actions.length ||
105
+ counts.prepared !== 0 ||
106
+ counts.executed !== 0 ||
107
+ counts.unknown !== 0 ||
108
+ counts.attempts_consumed !== 0 ||
109
+ !Number.isSafeInteger(counts.failed) ||
110
+ !Number.isSafeInteger(counts.blocked) ||
111
+ counts.failed < 0 ||
112
+ counts.blocked < 0 ||
113
+ counts.failed !== rows.filter((row) => record(row).status === "failed").length ||
114
+ counts.blocked !== rows.filter((row) => record(row).status === "blocked").length)
115
+ return "the terminal report must prove zero executed actions, zero consumed attempts, no unknown outcome and a row-consistent failed/blocked distribution";
116
+ for (const [index, raw] of rows.entries()) {
117
+ const row = record(raw);
118
+ if (row.index !== index ||
119
+ row.type !== "process" ||
120
+ typeof row.status !== "string" ||
121
+ !definiteFailures.has(row.status) ||
122
+ row.attempt_consumed !== false ||
123
+ row.replayed !== false ||
124
+ row.readback === "desired_exact")
125
+ return `row ${index + 1} must be one definite failed or blocked row that consumed no attempt and claims no readback`;
126
+ const action = expected.actions[index];
127
+ if (row.table !== action.table ||
128
+ row.id !== action.id ||
129
+ row.version !== action.version ||
130
+ row.action_id !== action.action_id ||
131
+ row.desired_sha256 !== action.desired_sha256)
132
+ return `row ${index + 1} does not bind the admitted action, entity identity or desired payload`;
133
+ }
134
+ return null;
135
+ }
136
+ /**
137
+ * Admit one successor revision over a predecessor whose only terminal evidence is a CLI failure that
138
+ * provably dispatched nothing. Every fact is re-derived from the predecessor's own hash-chained index
139
+ * on every call; nothing is cached, and the successor may never name one of the predecessor's files.
140
+ */
141
+ export function assertFoundryNoDispatchSuccessor(input) {
142
+ const { context, predecessorTaskId, successor } = input;
143
+ const spec = successor.spec;
144
+ const repair = spec.repair ?? null;
145
+ const declared = repair?.predecessor ?? null;
146
+ if (spec.lane !== "existing-owner-draft-repair" ||
147
+ !repair ||
148
+ spec.profile_id !== "generic" ||
149
+ !declared ||
150
+ declared.task_id !== predecessorTaskId ||
151
+ !shaPattern.test(declared.receipt_sha256))
152
+ refuse(predecessorTaskId, "only an explicit existing-owner-draft-repair successor naming this predecessor and its terminal report digest may continue");
153
+ const intent = spec.account_intent;
154
+ if (!intent)
155
+ refuse(predecessorTaskId, "a successor requires its explicit owner account intent");
156
+ const manifest = currentFoundryRuntimeManifest(context);
157
+ const predecessorContext = createFoundryRuntimeContext({
158
+ moduleUrl: pathToFileURL(context.runtime.entryPath).href,
159
+ workspace: context.workspaceRoot,
160
+ cacheBase: context.cacheBase,
161
+ // The predecessor is opened read-only under the same trusted host selection, so a migrated
162
+ // workspace keeps its runtime authority without gaining any write path here.
163
+ ...(manifest ? { workspaceAccess: { manifest, access: "read" } } : {}),
164
+ taskId: predecessorTaskId,
165
+ actorId: spec.actor_id,
166
+ inputs: input.predecessorInputs,
167
+ });
168
+ const taskRoot = predecessorContext.taskRoot;
169
+ if (predecessorContext.controlRoot !== context.controlRoot ||
170
+ predecessorContext.workspaceRoot !== context.workspaceRoot ||
171
+ !taskRoot ||
172
+ path.relative(context.controlRoot, taskRoot).startsWith(".."))
173
+ refuse(predecessorTaskId, "the predecessor must live inside this exact workspace");
174
+ let snapshotBefore;
175
+ try {
176
+ snapshotBefore = stability(predecessorContext);
177
+ }
178
+ catch {
179
+ refuse(predecessorTaskId, "the predecessor must retain its job, index and account registration");
180
+ }
181
+ const snapshot = readVerifiedTaskSnapshot(predecessorContext, {
182
+ verifyCommands: [...evidenceCommands],
183
+ });
184
+ const job = snapshot.task.job;
185
+ if (job.lane !== spec.lane ||
186
+ job.request_id !== spec.request_id ||
187
+ job.actor_id !== spec.actor_id ||
188
+ job.workspace_id !== context.workspaceId ||
189
+ job.target_profile !== spec.profile_id ||
190
+ !job.repair)
191
+ refuse(predecessorTaskId, "the predecessor must share this request, actor, lane and locked generic profile");
192
+ const account = readTaskJson(predecessorContext, "account-intent.json");
193
+ if (account.schema !== "tiangong-foundry.account-intent.v1" ||
194
+ account.workspace_id !== context.workspaceId ||
195
+ account.task_id !== predecessorTaskId ||
196
+ account.project_ref !== intent.project_ref ||
197
+ account.user_id !== intent.user_id ||
198
+ (account.account_mode ?? "ordinary") !== (intent.account_mode ?? "ordinary"))
199
+ refuse(predecessorTaskId, "the predecessor must be bound to this exact owner account");
200
+ const preparationEntry = latestEntry(snapshot.index, FOUNDRY_REPAIR_PREFLIGHT_COMMAND, FOUNDRY_REPAIR_REPORT_NAME);
201
+ if (!preparationEntry)
202
+ refuse(predecessorTaskId, "the predecessor retains no registered repair preparation");
203
+ const preparation = readWorkflowArtifact(predecessorContext, preparationEntry).value;
204
+ const preparationScope = record(preparation.scope);
205
+ const preparationContract = record(preparation.contract);
206
+ const preparationInputs = record(preparation.inputs);
207
+ const preparationAccount = record(preparation.account);
208
+ const actions = Array.isArray(preparationScope.actions)
209
+ ? preparationScope.actions.map((action) => record(action))
210
+ : null;
211
+ const candidateFact = record(preparationInputs.candidate);
212
+ const contractFact = record(preparationInputs.contract);
213
+ const beforeFact = record(preparationInputs.before);
214
+ if (preparation.schema !== FOUNDRY_REPAIR_PREPARATION_SCHEMA ||
215
+ preparation.status !== "prepared" ||
216
+ preparation.publication_ready !== false ||
217
+ preparation.remote_writes !== 0 ||
218
+ preparationScope.status !== "dispatchable" ||
219
+ !actions?.length ||
220
+ typeof candidateFact.path !== "string" ||
221
+ typeof candidateFact.sha256 !== "string" ||
222
+ typeof contractFact.path !== "string" ||
223
+ typeof beforeFact.sha256 !== "string" ||
224
+ typeof preparationContract.canonical_sha256 !== "string" ||
225
+ typeof preparationContract.execution_id !== "string" ||
226
+ preparationAccount.user_id !== intent.user_id ||
227
+ preparationAccount.project_ref !== intent.project_ref ||
228
+ preparationAccount.state_code !== "0")
229
+ refuse(predecessorTaskId, "the predecessor must retain one prepared dispatchable repair scope bound to this owner");
230
+ const resultEntry = latestEntry(snapshot.index, RESULT_COMMAND, RESULT_NAME);
231
+ if (!resultEntry)
232
+ refuse(predecessorTaskId, "the predecessor has no registered terminal owner execution result");
233
+ const result = readWorkflowArtifact(predecessorContext, resultEntry).value;
234
+ const observation = record(result.observation);
235
+ const boundReport = record(observation.report);
236
+ const readback = result.readback;
237
+ if (result.schema !== RESULT_SCHEMA ||
238
+ result.status !== "unresolved" ||
239
+ result.scope_id !== sha256Json({ task: predecessorTaskId, type: "process" }) ||
240
+ result.attempt_consumed !== true ||
241
+ (readback !== null && record(readback).schema !== READBACK_SCHEMA) ||
242
+ (readback !== null && record(readback).status !== "unresolved") ||
243
+ observation.schema !== OBSERVATION_SCHEMA ||
244
+ observation.disposition !== "failed" ||
245
+ typeof boundReport.path !== "string" ||
246
+ boundReport.sha256 !== declared.receipt_sha256)
247
+ refuse(predecessorTaskId, "the terminal result must be an unresolved definite dispatch failure bound to the declared report digest");
248
+ const boundReportPath = path.resolve(String(boundReport.path));
249
+ const requestEntry = snapshot.index.find((entry) => entry.command === PREPARE_COMMAND &&
250
+ entry.sha256 === result.request_sha256 &&
251
+ path.basename(entry.path) === "owner-execution-request.json");
252
+ if (!requestEntry)
253
+ refuse(predecessorTaskId, "the consumed attempt must name a registered owner execution request of this task");
254
+ const reportEntry = snapshot.index.find((entry) => entry.command === OBSERVATION_COMMAND &&
255
+ entry.sha256 === boundReport.sha256 &&
256
+ entry.bytes === boundReport.bytes &&
257
+ path.resolve(taskRoot, entry.path) === boundReportPath);
258
+ if (!reportEntry)
259
+ refuse(predecessorTaskId, "the terminal CLI report must be registered by its own producer with these exact bytes");
260
+ const observationEntry = latestEntry(snapshot.index, OBSERVATION_COMMAND, OBSERVATION_NAME);
261
+ if (!observationEntry ||
262
+ sha256Json(readWorkflowArtifact(predecessorContext, observationEntry).value) !==
263
+ sha256Json(observation))
264
+ refuse(predecessorTaskId, "the registered dispatch observation must equal the result's binding");
265
+ const terminalReport = readWorkflowArtifact(predecessorContext, reportEntry).value;
266
+ const problem = noDispatchCommitReportProblem(terminalReport, {
267
+ candidate_path: path.resolve(context.workspaceRoot, String(candidateFact.path)),
268
+ contract_sha256: String(preparationContract.canonical_sha256),
269
+ execution_id: String(preparationContract.execution_id),
270
+ actions: actions.map((action) => ({
271
+ action_id: String(action.action_id),
272
+ table: String(action.table),
273
+ id: String(action.id),
274
+ version: String(action.version),
275
+ desired_sha256: String(action.desired_sha256),
276
+ })),
277
+ });
278
+ if (problem)
279
+ refuse(predecessorTaskId, problem);
280
+ // The report names the contract it was given; that file, wherever the admission staged it, must
281
+ // re-derive to the exact canonical contract this scope was prepared and authorized under.
282
+ const reportContract = path.resolve(String(record(terminalReport.execution_contract).path));
283
+ let reportContractSha;
284
+ try {
285
+ reportContractSha = readNativeDraftHandoff({
286
+ contractFile: reportContract,
287
+ rowsFile: path.resolve(context.workspaceRoot, String(candidateFact.path)),
288
+ datasetType: "process",
289
+ targetUserId: intent.user_id,
290
+ verifiedProjectRef: intent.project_ref,
291
+ stateCode: "0",
292
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
293
+ }).canonical_sha256;
294
+ }
295
+ catch {
296
+ refuse(predecessorTaskId, "the terminal report must name a readable exact native contract");
297
+ }
298
+ if (reportContractSha !== String(preparationContract.canonical_sha256))
299
+ refuse(predecessorTaskId, "the terminal report's contract must equal the prepared scope contract");
300
+ // One registered scope only: the exception may not hide a second consumed scope, and no unknown
301
+ // file may sit beside the attempt evidence.
302
+ const scopeId = String(result.scope_id);
303
+ try {
304
+ const attemptsRoot = path.join(taskRoot, "attempts");
305
+ const ownerRoot = path.join(attemptsRoot, "owner-v1");
306
+ if (fs.readdirSync(attemptsRoot).sort().join(",") !== "owner-v1" ||
307
+ fs.readdirSync(ownerRoot).sort().join(",") !== scopeId)
308
+ refuse(predecessorTaskId, "attempt evidence must hold exactly the one consumed scope");
309
+ for (const name of fs.readdirSync(path.join(ownerRoot, scopeId)).sort()) {
310
+ const file = path.join(ownerRoot, scopeId, name);
311
+ const stat = fs.lstatSync(file);
312
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > maxArtifactBytes)
313
+ refuse(predecessorTaskId, "attempt evidence must remain bounded regular files");
314
+ if (name === "consumed.json") {
315
+ const consumedEntry = snapshot.index.find((entry) => entry.command === CONSUME_COMMAND &&
316
+ path.resolve(taskRoot, entry.path) === file &&
317
+ entry.sha256 === captureFoundryInput(file).sha256);
318
+ if (!consumedEntry)
319
+ refuse(predecessorTaskId, "the consumed marker must be registered by its own consume operation");
320
+ const consumed = readWorkflowArtifact(predecessorContext, consumedEntry).value;
321
+ if (consumed.schema !== CONSUMED_SCHEMA ||
322
+ consumed.scope_id !== scopeId ||
323
+ record(consumed.request).sha256 !== result.request_sha256)
324
+ refuse(predecessorTaskId, "the consumed marker must bind this exact owner request");
325
+ continue;
326
+ }
327
+ if (!/^events-[0-9a-f-]+\.jsonl$/u.test(name))
328
+ refuse(predecessorTaskId, "unknown attempt evidence cannot be treated as no-dispatch");
329
+ const text = fs.readFileSync(file, "utf8");
330
+ if (text && !text.endsWith("\n"))
331
+ refuse(predecessorTaskId, "incomplete attempt history cannot prove a terminal failure");
332
+ for (const line of text.split("\n").filter(Boolean)) {
333
+ const event = workflowObject(JSON.parse(line));
334
+ // Retry, resume, resource and recovery-failure events are all compatible with a dispatch
335
+ // that never reached the owner CLI; a success event is not.
336
+ if (event.schema_version !== 1 || succeededEvents.has(String(event.type)))
337
+ refuse(predecessorTaskId, "a successful owner attempt cannot prove that nothing was dispatched");
338
+ }
339
+ }
340
+ }
341
+ catch (error) {
342
+ if (error instanceof FoundryContextError)
343
+ throw error;
344
+ refuse(predecessorTaskId, "attempt evidence must stay complete and parseable");
345
+ }
346
+ // The successor must be a genuine, identity-stable change of the same owner draft.
347
+ const successorFiles = ["contract", "before", "candidate"].map((key) => {
348
+ const declaredPath = repair[key];
349
+ const index = spec.sources.findIndex((source) => source.path === declaredPath);
350
+ const fact = successor.inputs[index];
351
+ if (!fact)
352
+ refuse(predecessorTaskId, "successor inputs must be its own selected sources");
353
+ let current;
354
+ try {
355
+ current = captureFoundryInput(path.resolve(context.workspaceRoot, declaredPath));
356
+ }
357
+ catch {
358
+ refuse(predecessorTaskId, "successor selections must remain readable frozen files");
359
+ }
360
+ if (current.sha256 !== fact.sha256 || current.bytes !== fact.bytes)
361
+ refuse(predecessorTaskId, "successor selections must remain their exact frozen bytes");
362
+ return current.path;
363
+ });
364
+ const native = readNativeDraftHandoff({
365
+ contractFile: successorFiles[0],
366
+ rowsFile: successorFiles[2],
367
+ datasetType: "process",
368
+ targetUserId: intent.user_id,
369
+ verifiedProjectRef: intent.project_ref,
370
+ stateCode: "0",
371
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
372
+ });
373
+ const successorCandidate = captureFoundryInput(successorFiles[2]);
374
+ if (successorCandidate.sha256 === String(candidateFact.sha256))
375
+ refuse(predecessorTaskId, "a successor must submit different candidate bytes");
376
+ const prior = new Map(actions.map((action) => [
377
+ `${String(action.id)}@${String(action.version)}`,
378
+ {
379
+ table: String(action.table),
380
+ before: String(action.before_sha256),
381
+ desired: String(action.desired_sha256),
382
+ },
383
+ ]));
384
+ const successorActions = native.contract.actions;
385
+ let changed = false;
386
+ for (const action of successorActions) {
387
+ const bound = prior.get(`${action.id}@${action.version}`);
388
+ // A fresh before is allowed: the successor's own scope, fresh preflight and new grant prove the
389
+ // current stored state, while the old before proof is never inherited.
390
+ if (!bound || bound.table !== action.table)
391
+ refuse(predecessorTaskId, "every successor action must keep the same table and stable entity identity and version");
392
+ if (bound.desired !== action.desired_sha256)
393
+ changed = true;
394
+ }
395
+ if (successorActions.length !== actions.length || !changed)
396
+ refuse(predecessorTaskId, "a successor must change at least one real desired payload, never only its execution id or file path");
397
+ if (stability(predecessorContext) !== snapshotBefore)
398
+ refuse(predecessorTaskId, "predecessor evidence changed while its verdict was computed");
399
+ }
@@ -1,8 +1,9 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, resolveFoundryAsset, resolveFoundryOutput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
4
+ import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, resolveFoundryAsset, resolveFoundryOutput, resolveFoundryInputPath, writeFoundryArtifact, } from "./foundry-runtime-context.js";
5
5
  import { sha256Json } from "./identity-preflight-proof.js";
6
+ import { parseFoundryRepairSelection, readFoundryRepairScope, } from "./foundry-repair-scope.js";
6
7
  import { fail, object, exact, timestamp, bytes, digest, taskPath, readTaskBytes, readTaskJson, reference, facts, sameFact, maxDocumentBytes, } from "./foundry-task-io.js";
7
8
  const entityTypes = new Set([
8
9
  "contact",
@@ -130,6 +131,7 @@ export function loadTask(context, options) {
130
131
  "runtime_identity",
131
132
  "write_policy",
132
133
  "created_at_utc",
134
+ ...(Object.hasOwn(raw, "repair") ? ["repair"] : []),
133
135
  ]);
134
136
  if (raw.schema !== "tiangong-foundry.job.v2")
135
137
  fail("legacy_task_requires_migration", "Existing task schema must be migrated explicitly.");
@@ -142,7 +144,11 @@ export function loadTask(context, options) {
142
144
  if (typeof raw.request_id !== "string" ||
143
145
  !raw.request_id ||
144
146
  !timestamp(raw.created_at_utc) ||
145
- !["external-dataset-curated-import", "source-evidence-dataset-development"].includes(String(raw.lane)) ||
147
+ ![
148
+ "external-dataset-curated-import",
149
+ "source-evidence-dataset-development",
150
+ "existing-owner-draft-repair",
151
+ ].includes(String(raw.lane)) ||
146
152
  typeof raw.target_profile !== "string" ||
147
153
  !Array.isArray(raw.target_entities) ||
148
154
  !raw.target_entities.length ||
@@ -201,6 +207,7 @@ export function loadTask(context, options) {
201
207
  "profile-lock.json",
202
208
  "artifact-index.jsonl",
203
209
  ...(raw.seed_manifest ? ["seed-manifest.json"] : []),
210
+ ...(raw.repair ? ["repair-scope.json"] : []),
204
211
  ]);
205
212
  if (fs.readdirSync(context.taskRoot).some((name) => !allowed.has(name)) ||
206
213
  readTaskBytes(context, "artifact-index.jsonl").length > 0)
@@ -226,7 +233,18 @@ export function createTask(context, options) {
226
233
  fail("input_changed", "Selected source changed before task creation.");
227
234
  const lane = options.lane ?? "external-dataset-curated-import";
228
235
  const profileId = options.profileId ?? "generic";
229
- if (!["external-dataset-curated-import", "source-evidence-dataset-development"].includes(lane) ||
236
+ const repairSelection = lane === "existing-owner-draft-repair"
237
+ ? parseFoundryRepairSelection(options.repair ?? null, context.inputs.map((fact) => ({ path: fact.path })), (file) => resolveFoundryInputPath(context, file))
238
+ : options.repair
239
+ ? fail("task_spec_repair_lane_mismatch", "A repair selection is only valid under the existing-owner-draft-repair lane.")
240
+ : null;
241
+ if (repairSelection && (options.targetEntities ?? []).join(",") !== "process")
242
+ fail("task_spec_repair_invalid", "Phase 1 repair admits exactly one target entity type: process.");
243
+ if (![
244
+ "external-dataset-curated-import",
245
+ "source-evidence-dataset-development",
246
+ "existing-owner-draft-repair",
247
+ ].includes(lane) ||
230
248
  (options.requestId !== undefined &&
231
249
  (typeof options.requestId !== "string" ||
232
250
  !options.requestId ||
@@ -264,6 +282,7 @@ export function createTask(context, options) {
264
282
  runtime_identity: runtimeIdentity(context),
265
283
  write_policy: { mode: "dry-run", remote_state_code: 0 },
266
284
  created_at_utc: new Date().toISOString(),
285
+ ...(repairSelection ? { repair: repairSelection } : {}),
267
286
  };
268
287
  const registered = readRegistration(context);
269
288
  if (registered) {
@@ -286,6 +305,47 @@ export function createTask(context, options) {
286
305
  fail("task_document_limit", "Task metadata exceeds its bounded document limit.");
287
306
  const staging = resolveFoundryOutput(context, `task-initialization/${context.taskId}-${randomUUID()}`, "state");
288
307
  fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
308
+ let repairDocuments = [];
309
+ if (repairSelection) {
310
+ const userId = context.accountIntent?.userId;
311
+ const projectRef = context.accountIntent?.projectRef;
312
+ if (!userId || !projectRef)
313
+ fail("repair_scope_requires_account_intent", "A repair task requires the exact owner account intent before its scope can be validated.");
314
+ const boundPath = (selected) => {
315
+ const fact = context.inputs.find((input) => input.path === selected);
316
+ if (!fact)
317
+ fail("task_spec_repair_invalid", "Repair contract, before rows and candidate rows must each be captured selected inputs.");
318
+ return fact.path;
319
+ };
320
+ // Offline only: the registered scope validates the three captured inputs against each other.
321
+ // No owner CLI runs here. The fresh owner/state/before preflight belongs to task resume, outside
322
+ // the task lock, and is registered as trusted producer evidence there.
323
+ const scope = readFoundryRepairScope({
324
+ contractFile: boundPath(repairSelection.contract),
325
+ beforeFile: boundPath(repairSelection.before),
326
+ candidateFile: boundPath(repairSelection.candidate),
327
+ datasetType: "process",
328
+ targetUserId: userId,
329
+ verifiedProjectRef: projectRef,
330
+ stateCode: "0",
331
+ relativePath: (file) => path.relative(context.workspaceRoot, file),
332
+ });
333
+ repairDocuments = [
334
+ [
335
+ "repair-scope.json",
336
+ bytes({
337
+ schema: "tiangong-foundry.repair-scope-record.v1",
338
+ kind: scope.kind,
339
+ status: scope.status,
340
+ contract_sha256: scope.contract_sha256,
341
+ rows_sha256: scope.rows_sha256,
342
+ changed_paths: [...scope.changed_paths],
343
+ actions: scope.actions.map((action) => ({ ...action })),
344
+ remote_state_verified: false,
345
+ }),
346
+ ],
347
+ ];
348
+ }
289
349
  const documents = [
290
350
  ["source-manifest.json", sourceBytes],
291
351
  ["profile-lock.json", profileBytes],
@@ -294,6 +354,7 @@ export function createTask(context, options) {
294
354
  ];
295
355
  if (seedBytes)
296
356
  documents.push(["seed-manifest.json", seedBytes]);
357
+ documents.push(...repairDocuments);
297
358
  for (const [name, content] of documents) {
298
359
  const fd = fs.openSync(path.join(staging, name), "wx", 0o600);
299
360
  try {
@@ -1,5 +1,6 @@
1
1
  import type { FoundryInputFact } from "./foundry-runtime-context.ts";
2
2
  import type { Lane } from "./foundry-task-types.ts";
3
+ import { type FoundryRepairSelection } from "./foundry-repair-scope.ts";
3
4
  export declare const FOUNDRY_TASK_START_SPEC_SCHEMA: "tiangong-foundry.task-start.v1";
4
5
  interface SourceSelection {
5
6
  readonly path: string;
@@ -28,6 +29,8 @@ export interface FoundryTaskStartSpec {
28
29
  readonly seed: Readonly<SourceSelection> | null;
29
30
  readonly account_intent: Readonly<AccountIntentSelection> | null;
30
31
  readonly preparation: Readonly<CleanupPreparation> | null;
32
+ /** Present only for the existing-owner-draft-repair lane, so v1 fingerprints never change. */
33
+ readonly repair?: Readonly<FoundryRepairSelection>;
31
34
  }
32
35
  export declare function parseFoundryTaskStartSpec(value: unknown): FoundryTaskStartSpec;
33
36
  export declare function taskStartSpecFingerprint(spec: FoundryTaskStartSpec, inputs: readonly FoundryInputFact[]): string;
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { FoundryContextError } from "./foundry-runtime-context.js";
3
3
  import { sha256Json } from "./identity-preflight-proof.js";
4
+ import { parseFoundryRepairSelection, } from "./foundry-repair-scope.js";
4
5
  export const FOUNDRY_TASK_START_SPEC_SCHEMA = "tiangong-foundry.task-start.v1";
5
6
  const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/u;
6
7
  const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
@@ -108,13 +109,18 @@ export function parseFoundryTaskStartSpec(value) {
108
109
  "seed",
109
110
  "account_intent",
110
111
  "preparation",
112
+ ...(Object.hasOwn(item, "repair") ? ["repair"] : []),
111
113
  ], "Task-start spec");
112
114
  if (item.schema !== FOUNDRY_TASK_START_SPEC_SCHEMA ||
113
115
  typeof item.request_id !== "string" ||
114
116
  !idPattern.test(item.request_id) ||
115
117
  typeof item.actor_id !== "string" ||
116
118
  !idPattern.test(item.actor_id) ||
117
- !["external-dataset-curated-import", "source-evidence-dataset-development"].includes(String(item.lane)) ||
119
+ ![
120
+ "external-dataset-curated-import",
121
+ "source-evidence-dataset-development",
122
+ "existing-owner-draft-repair",
123
+ ].includes(String(item.lane)) ||
118
124
  typeof item.profile_id !== "string" ||
119
125
  !idPattern.test(item.profile_id) ||
120
126
  !Array.isArray(item.target_entities) ||
@@ -134,6 +140,22 @@ export function parseFoundryTaskStartSpec(value) {
134
140
  fail("task_seed_invalid", "Task seed must be one of the independently selected sources.");
135
141
  if (item.lane === "source-evidence-dataset-development" && !seed)
136
142
  fail("task_seed_required", "Source-evidence authoring requires one selected JSON seed file.");
143
+ const repair = item.lane === "existing-owner-draft-repair"
144
+ ? item.repair === undefined || item.repair === null
145
+ ? fail("task_spec_repair_lane_mismatch", "The existing-owner-draft-repair lane requires one repair selection.")
146
+ : parseFoundryRepairSelection(item.repair, sources)
147
+ : item.repair === undefined || item.repair === null
148
+ ? null
149
+ : fail("task_spec_repair_lane_mismatch", "A repair selection is only valid under the existing-owner-draft-repair lane.");
150
+ if (repair) {
151
+ if (seed)
152
+ fail("task_spec_repair_invalid", "A repair task never selects a seed manifest.");
153
+ if (item.preparation !== null)
154
+ fail("task_spec_repair_invalid", "A repair task never selects a cleanup preparation; the contract and rows are its only inputs.");
155
+ if (item.target_entities.length !== 1 ||
156
+ String(item.target_entities[0]) !== "process")
157
+ fail("task_spec_repair_invalid", "Phase 1 repair admits exactly one target entity type: process.");
158
+ }
137
159
  const spec = {
138
160
  schema: FOUNDRY_TASK_START_SPEC_SCHEMA,
139
161
  request_id: item.request_id,
@@ -145,6 +167,7 @@ export function parseFoundryTaskStartSpec(value) {
145
167
  seed,
146
168
  account_intent: account(item.account_intent),
147
169
  preparation: preparation(item.preparation, sources),
170
+ ...(repair ? { repair } : {}),
148
171
  };
149
172
  return Object.freeze(spec);
150
173
  }
@@ -1,6 +1,18 @@
1
1
  import { type FoundryRuntimeContext, type FoundryInputFact } from "./foundry-runtime-context.ts";
2
2
  import type { JsonRecord, ArtifactEntry, LoadedTask, FoundryTaskOptions, FoundryTaskOperation } from "./foundry-task-types.ts";
3
3
  export type { FoundryTaskOptions, FoundryTaskOperation, FoundryTaskJob, } from "./foundry-task-types.ts";
4
+ /**
5
+ * The synchronous verified snapshot of one task: registered job, bound account intent, hash-chained
6
+ * artifact index and re-verified frozen sources. It is the same verification the locked metadata
7
+ * transaction performs, exposed for read-only projections that cannot await; callers that read a
8
+ * *foreign* task synchronously must re-check the snapshot's stability themselves.
9
+ */
10
+ export declare function readVerifiedTaskSnapshot(context: FoundryRuntimeContext, options?: {
11
+ verifyCommands?: readonly string[];
12
+ }): {
13
+ readonly task: LoadedTask;
14
+ readonly index: readonly ArtifactEntry[];
15
+ };
4
16
  export declare function withFoundryTaskMetadata<T>(context: FoundryRuntimeContext, inspect: (task: LoadedTask, index: readonly ArtifactEntry[]) => T, options?: {
5
17
  verifyCommands?: readonly string[];
6
18
  }): Promise<T>;
@@ -11,7 +23,7 @@ export declare function assertFoundryTaskInputLineage(context: FoundryRuntimeCon
11
23
  }>>;
12
24
  /** Short local preparation transaction. Remote mutation/batch execution must not use this replay path. */
13
25
  export declare function runFoundryTaskOperation(context: FoundryRuntimeContext, input: {
14
- command: "dataset-curation-cleanup" | "dataset-tidas-import" | "dataset-context-pack" | "dataset-workflow-rows" | "dataset-workflow-assessment" | "dataset-workflow-identity" | "dataset-workflow-finalize" | "dataset-workflow-authorization" | "dataset-workflow-native-contract" | "dataset-workflow-reference-input" | "dataset-workflow-execution-prepare" | "dataset-workflow-execution-result" | "dataset-workflow-execution-consume" | "dataset-workflow-execution-observation" | "dataset-workflow-reference-verify" | "dataset-semantic-apply";
26
+ command: "dataset-curation-cleanup" | "dataset-tidas-import" | "dataset-context-pack" | "dataset-workflow-rows" | "dataset-workflow-assessment" | "dataset-workflow-identity" | "dataset-workflow-finalize" | "dataset-workflow-authorization" | "dataset-workflow-native-contract" | "dataset-workflow-repair-preflight" | "dataset-workflow-reference-input" | "dataset-workflow-execution-prepare" | "dataset-workflow-execution-result" | "dataset-workflow-execution-consume" | "dataset-workflow-execution-observation" | "dataset-workflow-reference-verify" | "dataset-semantic-apply";
15
27
  options: JsonRecord;
16
28
  task?: FoundryTaskOptions;
17
29
  validateCurrent?: (index: readonly ArtifactEntry[]) => void;