@tiangong-lca/foundry 0.1.17 → 0.1.19

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 (162) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +15 -3
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +45 -13
  5. package/docs/public-runtime-contract.md +85 -5
  6. package/docs/runtime-context-contract.md +22 -4
  7. package/docs/task-authorization-contract.md +15 -3
  8. package/docs/workspace-migration-contract.md +5 -3
  9. package/package-dist/assets/foundry-package-descriptor.json +541 -177
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +261 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +2 -2
  13. package/package-dist/scripts/lib/bundle-sample-utils.d.ts +4 -4
  14. package/package-dist/scripts/lib/bundle-source-context.d.ts +6 -4
  15. package/package-dist/scripts/lib/bundle-source-context.js +10 -8
  16. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +18 -6
  17. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  18. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  19. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +11 -1
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +65 -9
  21. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  22. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  23. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  24. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  25. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  26. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  27. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  28. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  29. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  30. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  31. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  32. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  33. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  34. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  35. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  36. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  37. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  38. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  39. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  40. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  41. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  42. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  43. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  44. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  45. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  46. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  47. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  48. package/package-dist/scripts/lib/foundry-execution-admission.js +28 -3
  49. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  50. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  51. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  52. package/package-dist/scripts/lib/foundry-finalize-owners.js +126 -13
  53. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  54. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  55. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  56. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  57. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  58. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  59. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  60. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  61. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  62. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  63. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  64. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  65. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  66. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  67. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  68. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  69. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  70. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  71. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  72. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  73. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  74. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +2 -0
  75. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +96 -3
  76. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  77. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  78. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  79. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  80. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  81. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  82. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  83. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  84. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  85. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  86. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  87. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  88. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  89. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  90. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  91. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  92. package/package-dist/scripts/lib/foundry-runtime-identity.js +22 -2
  93. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  94. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  95. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  96. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  97. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  98. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  99. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  100. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  101. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  102. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  103. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  104. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  105. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  106. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  107. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  108. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  109. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  110. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  111. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  112. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  113. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  114. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  115. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  116. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  117. package/package-dist/scripts/lib/foundry-workflow-assessment.js +165 -34
  118. package/package-dist/scripts/lib/foundry-workflow-authorization.js +99 -5
  119. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  120. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  121. package/package-dist/scripts/lib/foundry-workflow-context.js +92 -22
  122. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  123. package/package-dist/scripts/lib/foundry-workflow-finalize.js +64 -3
  124. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  125. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  126. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  127. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +717 -0
  128. package/package-dist/scripts/lib/foundry-workflow-identity.js +26 -11
  129. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  130. package/package-dist/scripts/lib/foundry-workflow-io.js +102 -16
  131. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  132. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  133. package/package-dist/scripts/lib/foundry-workflow-semantic.js +65 -31
  134. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  135. package/package-dist/scripts/lib/foundry-workflow-state.js +165 -22
  136. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  137. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  138. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +6 -0
  139. package/package-dist/scripts/lib/identity-preflight-proof.js +92 -13
  140. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  141. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  142. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  143. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  144. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +1 -0
  145. package/package-dist/scripts/lib/import-curation/curation-gate.js +19 -1
  146. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  147. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  148. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  149. package/package-dist/scripts/package-entry.js +2 -3
  150. package/package-dist/scripts/public-api.d.ts +5 -0
  151. package/package-dist/scripts/public-api.js +2 -0
  152. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  153. package/package-dist/scripts/runtime-entry.js +42 -15
  154. package/package.json +6 -2
  155. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  156. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  157. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  158. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  159. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  160. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  161. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  162. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,717 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { withBatchRunLock } from "@tiangong-lca/cli/batch";
5
+ import { assertCliRuntimeMatches } from "@tiangong-lca/cli/runtime";
6
+ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
7
+ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
8
+ import { assertVerifiedFoundryIdentity, verifyFoundryRuntimeIdentity, } from "./foundry-runtime-identity.js";
9
+ import { createFoundryAuthenticationEnvironment } from "./foundry-authentication-environment.js";
10
+ import { readRetainedFoundryEdgeIdentity, runFoundryEdgeIdentityPreflight, } from "./foundry-edge-identity-preflight.js";
11
+ import { createFoundryIdentityOwners } from "./foundry-identity-owners.js";
12
+ import { inspectOwnerExecutions } from "./foundry-owner-execution-store.js";
13
+ import { currentFoundryInteractionState, currentFoundryQuestions, currentFoundryInvestigations, } from "./foundry-interaction-input.js";
14
+ import { readSelectedSemanticBytes } from "./foundry-semantic-input.js";
15
+ import { assertSelectedFoundryIdentityStageInput, } from "./foundry-identity-stage-input.js";
16
+ import { runFoundryTaskOperation, withFoundryTaskMetadata } from "./foundry-task-store.js";
17
+ import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
18
+ import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
19
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
20
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
21
+ import { readRows } from "./import-curation/internal/runtime-io.js";
22
+ import { createFileArtifactFact, createFoundryCommandSpec } from "./foundry-command-spec.js";
23
+ import { createIdentityPreflightBinding, parseFreshIntentBoundAuthReceipt, sha256Json, sha256Text, stableJson, validateBoundExecutionManifest, validateIdentityPreflightExecution, } from "./identity-preflight-proof.js";
24
+ const prepareCommand = "dataset-workflow-identity-stage-prepare";
25
+ const dispatchCommand = "dataset-workflow-identity-stage-dispatch";
26
+ const sensitiveCommands = new Set([
27
+ "dataset-workflow-finalize",
28
+ "dataset-workflow-authorization",
29
+ "dataset-workflow-native-contract",
30
+ "dataset-workflow-execution-prepare",
31
+ "dataset-workflow-execution-result",
32
+ "dataset-workflow-execution-consume",
33
+ "dataset-workflow-execution-observation",
34
+ ]);
35
+ function reject(reason) {
36
+ throw new FoundryContextError("identity_stage_input_invalid", `Explicit read-only identity stage cannot be admitted (${reason}).`);
37
+ }
38
+ function key(target) {
39
+ return JSON.stringify([target.dataset_type, target.dataset_id, target.dataset_version]);
40
+ }
41
+ function readJson(file) {
42
+ const fact = captureFoundryInput(file);
43
+ return workflowObject(JSON.parse(readSelectedSemanticBytes(fact).toString("utf8")));
44
+ }
45
+ function jsonLines(file) {
46
+ const text = readSelectedSemanticBytes(captureFoundryInput(file)).toString("utf8");
47
+ if (text && !text.endsWith("\n"))
48
+ reject("incomplete-index");
49
+ return text
50
+ .split("\n")
51
+ .filter(Boolean)
52
+ .map((line) => workflowObject(JSON.parse(line)));
53
+ }
54
+ function selectedBytes(selected) {
55
+ const content = readSelectedSemanticBytes(selected.descriptor);
56
+ if (stableJson(JSON.parse(content.toString("utf8"))) !== stableJson(selected.value))
57
+ reject("descriptor-binding");
58
+ return content;
59
+ }
60
+ function assertNativeUnprepared(context, entries) {
61
+ // The existing native owner validates all consumed, legacy and UNKNOWN attempt state first.
62
+ const execution = inspectOwnerExecutions(context, entries);
63
+ if (execution.requests.length ||
64
+ execution.consumed.size ||
65
+ execution.pending.length ||
66
+ entries.some((entry) => sensitiveCommands.has(entry.command)) ||
67
+ fs.existsSync(resolveFoundryOutput(context, "authorization.json")))
68
+ reject("native-owner-history-requires-original-recovery");
69
+ }
70
+ /** An explicit new read-only execution. Its local transactions only prepare or capture evidence. */
71
+ export async function runExplicitFoundryIdentityStage(context, qualified, entries, selected, authentication = { mode: "oauth" }, options = {}) {
72
+ options.signal?.throwIfAborted();
73
+ assertQualifiedFoundryRuntime(context, qualified);
74
+ assertSelectedFoundryIdentityStageInput(context, selected);
75
+ selectedBytes(selected);
76
+ const intent = selected.value;
77
+ if (intent.task_id !== context.taskId ||
78
+ intent.actor_id !== context.actorId ||
79
+ !context.accountIntent)
80
+ reject("task-actor-account");
81
+ // Same lock names and sorted order as native dispatch and runtime adoption.
82
+ const scopes = [
83
+ ...new Set([
84
+ ...["flow", "process"].map((type) => sha256Json({ task: context.taskId, type })),
85
+ sha256Json({ task: context.taskId, type: "explicit-identity-stage" }),
86
+ ]),
87
+ ].sort();
88
+ const locked = (at) => at === scopes.length
89
+ ? runLocked(context, qualified, entries, selected, authentication, options.signal)
90
+ : withBatchRunLock({
91
+ runPath: resolveFoundryOutput(context, `owner-locks/${context.taskId}-${scopes[at]}.json`, "state"),
92
+ identity: { task: context.taskId, scope: scopes[at] },
93
+ reason: "Foundry explicit read-only identity stage",
94
+ }, () => locked(at + 1));
95
+ return locked(0);
96
+ }
97
+ async function runLocked(context, qualified, prefix, selected, authentication, signal) {
98
+ const intent = selected.value;
99
+ const intentSha256 = sha256Json(intent);
100
+ const stageId = sha256Json({
101
+ task: context.taskId,
102
+ actor: context.actorId,
103
+ intent_id: intent.intent_id,
104
+ });
105
+ const output = resolveFoundryOutput(context, `outputs/identity-stage/${stageId}`);
106
+ const prepareFile = path.join(output, "prepared", "identity-stage-preparation.json");
107
+ let rowsFile = "";
108
+ let predecessorFile = "";
109
+ let targets = [];
110
+ const validateCurrent = (index) => {
111
+ signal?.throwIfAborted();
112
+ assertQualifiedFoundryRuntime(context, qualified);
113
+ assertSelectedFoundryIdentityStageInput(context, selected);
114
+ selectedBytes(selected);
115
+ for (const fact of context.inputs)
116
+ readFoundryInput(context, fact.path);
117
+ if (index.length < prefix.length ||
118
+ prefix.some((entry, at) => entry.record_sha256 !== index[at].record_sha256))
119
+ reject("retained-index-prefix");
120
+ assertNativeUnprepared(context, index);
121
+ const interaction = currentFoundryInteractionState(context, index);
122
+ if (interaction) {
123
+ const questions = currentFoundryQuestions(interaction.state);
124
+ const investigations = currentFoundryInvestigations(interaction.state);
125
+ if (questions.length || investigations.length)
126
+ throw new FoundryContextError(questions.length ? "interaction_decision_pending" : "interaction_investigation_pending", "Resolve the current question or investigation before identity preflight.");
127
+ }
128
+ const state = currentWorkflowState(context, index), rows = state.rows;
129
+ if (!rows ||
130
+ rows.entry.sha256 !== intent.rows_report_sha256 ||
131
+ (!state.assessment && !state.retainedAssessment))
132
+ reject("current-rows-assessment");
133
+ const predecessor = index.find((entry) => entry.command === "dataset-workflow-identity" &&
134
+ path.basename(entry.path) === "foundry-identity.json" &&
135
+ entry.sha256 === intent.predecessor_identity_sha256);
136
+ if (!predecessor)
137
+ reject("indexed-predecessor");
138
+ const old = readWorkflowArtifact(context, predecessor);
139
+ const predecessorAccount = workflowObject(old.value.account);
140
+ if (old.value.status !== "blocked" ||
141
+ old.value.rows_report !== rows.file ||
142
+ old.value.explicit_new_stage === true ||
143
+ predecessorAccount.project_ref !== context.accountIntent.projectRef ||
144
+ predecessorAccount.user_id !== context.accountIntent.userId)
145
+ reject("blocked-original-predecessor");
146
+ rowsFile = rows.file;
147
+ predecessorFile = old.file;
148
+ const roster = rows.value.sets
149
+ .filter((set) => set.type === "flow" || set.type === "process")
150
+ .flatMap((set) => {
151
+ readFoundryInput(context, set.file);
152
+ const values = readRows(set.file);
153
+ if (values.length !== set.count)
154
+ reject("registered-row-count");
155
+ return values.map((row) => {
156
+ const identity = datasetIdentity(row, 0, set.type);
157
+ return {
158
+ dataset_type: set.type,
159
+ dataset_id: identity.id,
160
+ dataset_version: identity.version,
161
+ source_row_sha256: sha256Json(row),
162
+ source_file: set.file,
163
+ };
164
+ });
165
+ });
166
+ if (!roster.length ||
167
+ new Set(roster.map(key)).size !== roster.length ||
168
+ intent.targets.length !== roster.length ||
169
+ new Set(intent.targets.map(key)).size !== intent.targets.length ||
170
+ intent.targets.some((target) => !roster.some((row) => key(row) === key(target) && row.source_row_sha256 === target.source_row_sha256)))
171
+ reject("exact-current-flow-process-roster");
172
+ targets = roster;
173
+ for (const entry of index.filter((item) => item.command === prepareCommand &&
174
+ path.basename(item.path) === "identity-stage-preparation.json")) {
175
+ const retained = readWorkflowArtifact(context, entry).value;
176
+ if (retained.intent_id === intent.intent_id && retained.intent_sha256 !== intentSha256)
177
+ reject("intent-already-bound");
178
+ if (retained.stage_id === stageId &&
179
+ retained.qualification_sha256 !== qualified.qualification_sha256)
180
+ reject("intent-runtime-changed");
181
+ if (retained.stage_id === stageId && retained.authentication_mode !== authentication.mode)
182
+ reject("intent-authentication-mode-changed");
183
+ if (retained.stage_id !== stageId &&
184
+ retained.rows_report_sha256 === intent.rows_report_sha256 &&
185
+ retained.predecessor_identity_sha256 === intent.predecessor_identity_sha256)
186
+ reject("overlapping-retained-stage");
187
+ }
188
+ if (state.identity?.entry.sha256 !== intent.predecessor_identity_sha256 &&
189
+ state.identity?.value.stage_id !== stageId)
190
+ reject("current-predecessor-changed");
191
+ };
192
+ const retainedStageFile = (file, command) => withFoundryTaskMetadata(context, (_, index) => {
193
+ validateCurrent(index);
194
+ const entry = index.findLast((item) => item.command === command && path.resolve(context.taskRoot, item.path) === file);
195
+ return entry ? readWorkflowArtifact(context, entry).value : null;
196
+ });
197
+ const environment = createFoundryAuthenticationEnvironment(authentication, context.accountIntent.sessionReference, process.env);
198
+ environment.FOUNDRY_VERIFIED_PROJECT_REF = context.accountIntent.projectRef;
199
+ environment.FOUNDRY_VERIFIED_USER_ID = context.accountIntent.userId;
200
+ fs.mkdirSync(output, { recursive: true, mode: 0o700 });
201
+ try {
202
+ const prepare = (await retainedStageFile(prepareFile, prepareCommand)) ??
203
+ (await runFoundryTaskOperation(context, {
204
+ command: prepareCommand,
205
+ options: {
206
+ stage_id: stageId,
207
+ intent_sha256: intentSha256,
208
+ rows_report_sha256: intent.rows_report_sha256,
209
+ predecessor_identity_sha256: intent.predecessor_identity_sha256,
210
+ },
211
+ validateCurrent,
212
+ }, (operation) => {
213
+ const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
214
+ const cli = assertCliRuntimeMatches(qualified.cli.expectation);
215
+ const installed = resolveInstalledTiangongLcaCliPackage();
216
+ const root = path.dirname(prepareFile);
217
+ operation.writeText(path.join(root, "selected-intent.json"), selectedBytes(selected));
218
+ operation.writeJson(path.join(root, "identity-receipt.json"), identity.receipt);
219
+ operation.writeJson(path.join(root, "roster.json"), targets);
220
+ operation.writeJson(path.join(root, "runtime-cli-inventory.json"), {
221
+ qualification: qualified,
222
+ cli: {
223
+ root: installed.packageRoot,
224
+ bin: captureFoundryInput(installed.binPath),
225
+ files: cli.files,
226
+ },
227
+ executable: captureFoundryInput(process.execPath),
228
+ });
229
+ const preparedTargets = [];
230
+ for (const target of targets) {
231
+ const type = target.dataset_type;
232
+ // The published owner names outputs by ID. A separate version-bound parent prevents collisions.
233
+ const outDir = path.join(root, "targets", sha256Json(target));
234
+ const sourceIndex = path.join(outDir, "source-context.jsonl");
235
+ const rowFile = path.join(outDir, "selected-row.jsonl");
236
+ const row = readRows(target.source_file).find((value) => sha256Json(value) === target.source_row_sha256);
237
+ if (!row)
238
+ reject("prepared-source-row");
239
+ operation.writeText(rowFile, JSON.stringify(row) + "\n");
240
+ operation.writeText(sourceIndex, JSON.stringify({ ...target, source_file: rowFile }) + "\n");
241
+ const owner = createFoundryIdentityOwners(context, qualified, type, {
242
+ environment,
243
+ cwd: root,
244
+ });
245
+ const built = workflowObject(owner.invoke(() => owner.preflight.runDatasetIdentityPreflightRequestsBuild({
246
+ type,
247
+ rowsFile: rowFile,
248
+ sourceIndex,
249
+ outDir,
250
+ })));
251
+ const indexFile = resolveFoundryOutput(context, path.resolve(context.assetRoot, String(workflowObject(built.files).identity_preflight_requests)));
252
+ const audited = workflowObject(owner.invoke(() => owner.preflight.runDatasetIdentityPreflightQueryAudit({
253
+ index: indexFile,
254
+ outDir: path.join(outDir, "query-audit"),
255
+ })));
256
+ if (built.status !== "ready" || audited.status !== "passed")
257
+ reject(`request-query-audit:${JSON.stringify({ prepare: built.blockers, audit: audited.blockers })}`);
258
+ const indexRows = jsonLines(indexFile);
259
+ if (indexRows.length !== 1 ||
260
+ key(indexRows[0]) !== key(target))
261
+ reject("prepared-roster-count");
262
+ const admittedRow = {
263
+ ...indexRows[0],
264
+ relevant_input_hashes: {
265
+ registered_rows: captureFoundryInput(target.source_file).sha256,
266
+ source_row: target.source_row_sha256,
267
+ },
268
+ };
269
+ const admittedIndex = path.join(outDir, "admitted-identity-preflight-requests.jsonl");
270
+ operation.writeText(admittedIndex, JSON.stringify(admittedRow) + "\n");
271
+ preparedTargets.push({
272
+ ...target,
273
+ owner_source_file: rowFile,
274
+ index: admittedIndex,
275
+ row: admittedRow,
276
+ });
277
+ }
278
+ registerWorkflowStageFiles(context, operation, root);
279
+ const report = {
280
+ schema: "tiangong-foundry.identity-stage-preparation.v1",
281
+ stage_id: stageId,
282
+ intent_id: intent.intent_id,
283
+ descriptor_sha256: selected.descriptor.sha256,
284
+ intent_sha256: intentSha256,
285
+ task_id: context.taskId,
286
+ actor_id: context.actorId,
287
+ rows_report: rowsFile,
288
+ rows_report_sha256: intent.rows_report_sha256,
289
+ predecessor_identity: {
290
+ path: predecessorFile,
291
+ sha256: intent.predecessor_identity_sha256,
292
+ },
293
+ predecessor_identity_sha256: intent.predecessor_identity_sha256,
294
+ qualification_sha256: qualified.qualification_sha256,
295
+ authentication_mode: identity.mode,
296
+ targets: preparedTargets,
297
+ account: {
298
+ project_ref: context.accountIntent.projectRef,
299
+ user_id: context.accountIntent.userId,
300
+ },
301
+ prepared_at_utc: operation.nowIso(),
302
+ };
303
+ operation.writeJson(prepareFile, report);
304
+ return report;
305
+ }));
306
+ const preparedTargets = prepare.targets;
307
+ if (prepare.schema !== "tiangong-foundry.identity-stage-preparation.v1" ||
308
+ prepare.stage_id !== stageId ||
309
+ prepare.intent_sha256 !== intentSha256 ||
310
+ prepare.qualification_sha256 !== qualified.qualification_sha256 ||
311
+ !Array.isArray(preparedTargets) ||
312
+ preparedTargets.length !== targets.length)
313
+ reject("retained-preparation");
314
+ const usesEdge = qualified.cli.expectation.package_version === "0.4.0";
315
+ const accepted = [];
316
+ const blockers = [];
317
+ let invocations = 0;
318
+ let thisInvocation = 0;
319
+ for (const target of preparedTargets) {
320
+ signal?.throwIfAborted();
321
+ const targetId = sha256Json({ stage_id: stageId, target });
322
+ const targetRoot = path.join(output, "dispatch", targetId), claimFile = path.join(targetRoot, "dispatch.json");
323
+ const authFile = path.join(targetRoot, "identity-receipt.json"), runDir = path.join(targetRoot, "run");
324
+ let newlyClaimed = false;
325
+ let identity = null;
326
+ const claim = (await retainedStageFile(claimFile, dispatchCommand)) ??
327
+ (await runFoundryTaskOperation(context, {
328
+ command: dispatchCommand,
329
+ options: { stage_id: stageId, target_id: targetId, intent_sha256: intentSha256 },
330
+ validateCurrent(index) {
331
+ validateCurrent(index);
332
+ // Verify after expensive locked metadata; serialized receipts never extend permission.
333
+ if (!fs.existsSync(claimFile))
334
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
335
+ },
336
+ }, (operation) => {
337
+ if (fs.existsSync(claimFile)) {
338
+ // An orphan file without its completed native receipt cannot prove dispatch admission.
339
+ const orphaned = {
340
+ schema: "tiangong-foundry.identity-stage-orphan-observation.v1",
341
+ stage_id: stageId,
342
+ target_id: targetId,
343
+ target,
344
+ claim: captureFoundryInput(claimFile),
345
+ admission_status: "ORPHANED_CLAIM_UNPROVEN",
346
+ };
347
+ operation.writeJson(path.join(targetRoot, "orphaned-claim.json"), orphaned);
348
+ return orphaned;
349
+ }
350
+ if (!identity)
351
+ reject("fresh-dispatch-identity");
352
+ assertVerifiedFoundryIdentity(context, identity, qualified);
353
+ operation.writeJson(authFile, identity.receipt);
354
+ const value = {
355
+ schema: "tiangong-foundry.identity-stage-dispatch.v1",
356
+ stage_id: stageId,
357
+ target_id: targetId,
358
+ intent_id: intent.intent_id,
359
+ target,
360
+ auth_receipt: captureFoundryInput(authFile),
361
+ qualification_sha256: qualified.qualification_sha256,
362
+ authentication_mode: identity.mode,
363
+ max_attempts: 1,
364
+ dispatch_state: "CLAIMED_OUTCOME_UNPROVEN",
365
+ claimed_at_utc: new Date().toISOString(),
366
+ };
367
+ operation.writeJson(claimFile, value);
368
+ newlyClaimed = true;
369
+ return value;
370
+ }));
371
+ if (newlyClaimed) {
372
+ signal?.throwIfAborted();
373
+ const fresh = identity;
374
+ if (!fresh)
375
+ reject("fresh-dispatch-identity");
376
+ assertVerifiedFoundryIdentity(context, fresh, qualified);
377
+ // Keep CLI startup independent of digest paths and the workspace's .env.
378
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "foundry-identity-stage-"));
379
+ try {
380
+ fs.chmodSync(temporary, 0o700);
381
+ const owner = createFoundryIdentityOwners(context, qualified, target.dataset_type, {
382
+ environment,
383
+ cwd: temporary,
384
+ });
385
+ try {
386
+ if (thisInvocation !== null)
387
+ thisInvocation += 1;
388
+ if (usesEdge)
389
+ await runFoundryEdgeIdentityPreflight(context, qualified, authentication, target.dataset_type, target.index, runDir, {
390
+ dispatchSha256: sha256Json(claim),
391
+ sourceSha256: captureFoundryInput(target.owner_source_file).sha256,
392
+ claimedAt: String(claim.claimed_at_utc),
393
+ receipt: fresh.receipt,
394
+ });
395
+ else
396
+ owner.invoke(() => owner.preflight.runDatasetIdentityPreflightRun({
397
+ index: target.index,
398
+ outDir: runDir,
399
+ authReceipt: authFile,
400
+ expectedProjectRef: context.accountIntent.projectRef,
401
+ expectedUserId: context.accountIntent.userId,
402
+ maxAttempts: 1,
403
+ timeoutMs: 60_000,
404
+ authReceiptMaxAgeMs: 60_000,
405
+ }));
406
+ }
407
+ catch {
408
+ // Retained logs may prove the original result; no new invocation follows this claim.
409
+ }
410
+ }
411
+ finally {
412
+ fs.rmSync(temporary, { recursive: true, force: true });
413
+ }
414
+ }
415
+ signal?.throwIfAborted();
416
+ await withFoundryTaskMetadata(context, (_, index) => validateCurrent(index));
417
+ try {
418
+ const run = acceptRetainedTarget(context, qualified, target, claim, authFile, runDir, authentication.mode);
419
+ accepted.push({ target, ...run, runDir });
420
+ if (invocations !== null)
421
+ invocations += 1;
422
+ }
423
+ catch (error) {
424
+ invocations = null;
425
+ if (newlyClaimed)
426
+ thisInvocation = null;
427
+ blockers.push({
428
+ code: "identity_stage_outcome_unproven",
429
+ target,
430
+ disposition: "UNKNOWN_DO_NOT_REPLAY",
431
+ reason: error instanceof Error ? error.message : "missing-execution-evidence",
432
+ });
433
+ // A partial stage cannot evade this claim through another intent or launch later targets.
434
+ break;
435
+ }
436
+ }
437
+ const resultId = sha256Json({
438
+ accepted: accepted.map(({ target, run }) => ({ target: key(target), run: sha256Json(run) })),
439
+ blockers,
440
+ });
441
+ const resultRoot = path.join(output, "results", resultId);
442
+ const report = await runFoundryTaskOperation(context, {
443
+ command: "dataset-workflow-identity",
444
+ options: {
445
+ stage_id: stageId,
446
+ result_id: resultId,
447
+ explicit_new_stage: true,
448
+ intent_sha256: intentSha256,
449
+ },
450
+ validateCurrent,
451
+ }, (operation) => {
452
+ // Partial raw outputs remain retained but unadopted. Only completed exact executions are indexed.
453
+ const retainedDirectories = [];
454
+ for (const { target, runDir } of accepted) {
455
+ retainedDirectories.push(runDir, resolveFoundryOutput(context, path.resolve(context.assetRoot, String(target.row.output_dir))));
456
+ }
457
+ registerWorkflowStageFiles(context, operation, retainedDirectories);
458
+ const combined = path.join(resultRoot, "identity-preflight-requests.jsonl");
459
+ operation.writeText(combined, accepted.map(({ row }) => JSON.stringify(row)).join("\n") + (accepted.length ? "\n" : ""));
460
+ const sets = [];
461
+ const grouped = new Map();
462
+ for (const item of accepted) {
463
+ const groupKey = JSON.stringify([item.target.dataset_type, item.target.source_file]);
464
+ grouped.set(groupKey, [...(grouped.get(groupKey) ?? []), item]);
465
+ }
466
+ for (const [groupKey, items] of grouped) {
467
+ const groupRoot = path.join(resultRoot, "sets", sha256Text(groupKey));
468
+ const index = path.join(groupRoot, "identity-preflight-requests.jsonl");
469
+ operation.writeText(index, items.map(({ row }) => JSON.stringify(row)).join("\n") + "\n");
470
+ const summary = {
471
+ schema: "tiangong-foundry.identity-stage-set.v1",
472
+ remote_write_mode: "read-only",
473
+ status: items.some(({ run }) => run.status === "completed_with_identity_findings")
474
+ ? "completed_with_identity_findings"
475
+ : "completed",
476
+ type: items[0].target.dataset_type,
477
+ rows: items[0].target.source_file,
478
+ index,
479
+ owner_runs: items.map(({ run }) => path.resolve(context.assetRoot, String(workflowObject(run.files).report))),
480
+ };
481
+ const summaryFile = path.join(groupRoot, "identity-stage-set.json");
482
+ operation.writeJson(summaryFile, summary);
483
+ sets.push({
484
+ type: summary.type,
485
+ rows: summary.rows,
486
+ index,
487
+ report: summaryFile,
488
+ status: summary.status,
489
+ });
490
+ }
491
+ const report = {
492
+ schema: "tiangong-foundry.identity-stage.v1",
493
+ status: blockers.length ? "blocked" : "completed",
494
+ mode: "explicit-new-read-only-stage",
495
+ explicit_new_stage: true,
496
+ new_cli_execution: usesEdge
497
+ ? false
498
+ : accepted.length
499
+ ? true
500
+ : invocations === null
501
+ ? null
502
+ : false,
503
+ ...(usesEdge ? { execution_transport: "edge" } : {}),
504
+ stage_id: stageId,
505
+ intent_id: intent.intent_id,
506
+ task_id: context.taskId,
507
+ actor_id: context.actorId,
508
+ rows_report: rowsFile,
509
+ owner_base: context.assetRoot,
510
+ predecessor_identity: prepare.predecessor_identity,
511
+ account: prepare.account,
512
+ qualification_sha256: qualified.qualification_sha256,
513
+ authentication_mode: authentication.mode,
514
+ checked_at_utc: operation.nowIso(),
515
+ index: combined,
516
+ counts: {
517
+ admitted_targets: preparedTargets.length,
518
+ accepted_targets: accepted.length,
519
+ cli_invocations: usesEdge ? 0 : invocations,
520
+ ...(usesEdge ? { edge_invocations: invocations } : {}),
521
+ underlying_retrievals: null,
522
+ },
523
+ sets,
524
+ blockers,
525
+ };
526
+ operation.writeJson(path.join(resultRoot, "foundry-identity.json"), report);
527
+ return report;
528
+ });
529
+ return {
530
+ ...report,
531
+ this_invocation: {
532
+ cli_invocations: usesEdge ? 0 : thisInvocation,
533
+ ...(usesEdge ? { edge_invocations: thisInvocation } : {}),
534
+ underlying_retrievals: null,
535
+ },
536
+ };
537
+ }
538
+ finally {
539
+ delete environment.TIANGONG_LCA_ACCESS_TOKEN;
540
+ }
541
+ }
542
+ function acceptRetainedTarget(context, qualified, target, claim, authFile, runDir, authenticationMode) {
543
+ assertQualifiedFoundryRuntime(context, qualified);
544
+ if (claim.admission_status === "ORPHANED_CLAIM_UNPROVEN")
545
+ reject("orphaned-claim-unproven");
546
+ const originalMode = claim.authentication_mode;
547
+ if ((originalMode !== "oauth" && originalMode !== "headless") ||
548
+ originalMode !== authenticationMode)
549
+ reject("retained-authentication-mode-changed");
550
+ if (claim.qualification_sha256 !== qualified.qualification_sha256 ||
551
+ stableJson(claim.target) !== stableJson(target) ||
552
+ claim.max_attempts !== 1)
553
+ reject("retained-claim-binding");
554
+ const authFact = captureFoundryInput(authFile);
555
+ if (stableJson(authFact) !== stableJson(claim.auth_receipt))
556
+ reject("retained-authentication-receipt");
557
+ const receipt = parseFreshIntentBoundAuthReceipt(readJson(authFile), {
558
+ nowMs: Date.parse(String(claim.claimed_at_utc)),
559
+ maxAgeMs: 60_000,
560
+ expectedProjectRef: context.accountIntent.projectRef,
561
+ expectedUserId: context.accountIntent.userId,
562
+ sessionMode: originalMode,
563
+ });
564
+ if (qualified.cli.expectation.package_version === "0.4.0") {
565
+ return readRetainedFoundryEdgeIdentity(context, target.dataset_type, target.row, runDir, originalMode, {
566
+ dispatchSha256: sha256Json(claim),
567
+ sourceSha256: captureFoundryInput(target.owner_source_file).sha256,
568
+ claimedAt: String(claim.claimed_at_utc),
569
+ receipt,
570
+ });
571
+ }
572
+ const runFile = path.join(runDir, "dataset-identity-preflight-run-report.json"), run = readJson(runFile);
573
+ const resolve = (value) => {
574
+ if (typeof value !== "string")
575
+ reject("retained-locator");
576
+ return resolveFoundryOutput(context, path.resolve(context.assetRoot, value));
577
+ };
578
+ if (resolve(workflowObject(run.files).report) !== resolve(runFile))
579
+ reject("retained-run-report-path");
580
+ if (!Array.isArray(run.results) ||
581
+ run.results.length !== 1 ||
582
+ !["completed", "completed_with_identity_findings"].includes(String(run.status)) ||
583
+ run.command !== "dataset-identity-preflight-run" ||
584
+ run.remote_write_mode !== "read-only" ||
585
+ resolve(run.index_file) !== target.index)
586
+ reject("retained-owner-result");
587
+ const result = workflowObject(run.results[0]), options = workflowObject(run.runtime_options), cli = workflowObject(options.cli);
588
+ const auth = workflowObject(options.auth_receipt), installed = resolveInstalledTiangongLcaCliPackage();
589
+ if (result.status !== "completed" ||
590
+ result.attempt !== 1 ||
591
+ result.attempts !== 1 ||
592
+ result.failure_code !== null ||
593
+ options.max_attempts !== 1 ||
594
+ options.timeout_ms !== 60_000 ||
595
+ options.retry_failed !== null ||
596
+ options.result_cache_dir !== null ||
597
+ cli.executable !== process.execPath ||
598
+ stableJson(cli.args_prefix) !== stableJson([installed.binPath]) ||
599
+ cli.package !== `${installed.packageName}@${installed.packageVersion}` ||
600
+ resolve(auth.file) !== authFile ||
601
+ auth.receipt_scope_sha256 !== receipt.receipt_scope_sha256 ||
602
+ auth.project_ref !== receipt.project.project_ref ||
603
+ auth.user_id !== receipt.identity.user_id)
604
+ reject("retained-owner-runtime-account-attempt");
605
+ if (key(result) !== key(target))
606
+ reject("retained-target-identity");
607
+ if (stableJson(jsonLines(resolve(workflowObject(run.files).results))) !== stableJson(run.results))
608
+ reject("retained-results-bytes");
609
+ const requestFile = resolve(target.row.request_file), reportFile = resolve(target.row.expected_report_file), outputDir = resolve(target.row.output_dir);
610
+ const requestText = fs.readFileSync(requestFile, "utf8"), request = readJson(requestFile);
611
+ if (target.row.request_bytes_sha256 !== sha256Text(requestText) ||
612
+ target.row.request_json_sha256 !== sha256Text(JSON.stringify(request)) ||
613
+ target.row.target_sha256 !== sha256Text(JSON.stringify(request.target)) ||
614
+ resolve(target.row.source_file) !== target.owner_source_file)
615
+ reject("retained-request-bytes");
616
+ const argv = [
617
+ target.dataset_type,
618
+ "identity-preflight",
619
+ "--input",
620
+ requestFile,
621
+ "--out-dir",
622
+ outputDir,
623
+ "--json",
624
+ "--timeout-ms",
625
+ "60000",
626
+ ];
627
+ const spec = createFoundryCommandSpec({
628
+ executable: process.execPath,
629
+ argv: [installed.binPath, ...argv],
630
+ binding: {
631
+ artifacts: [
632
+ createFileArtifactFact({
633
+ role: "identity_preflight_request",
634
+ path: String(target.row.request_file),
635
+ filePath: requestFile,
636
+ }),
637
+ ],
638
+ },
639
+ });
640
+ if (result.executable !== process.execPath ||
641
+ result.cli_package !== cli.package ||
642
+ stableJson(result.cli_args) !== stableJson(argv) ||
643
+ stableJson(result.command_spec) !== stableJson(spec) ||
644
+ resolve(result.request_file) !== requestFile ||
645
+ resolve(result.report_file) !== reportFile)
646
+ reject("retained-command-spec");
647
+ const binding = createIdentityPreflightBinding({
648
+ datasetType: target.dataset_type,
649
+ datasetId: target.dataset_id,
650
+ datasetVersion: target.dataset_version,
651
+ targetSha256: String(target.row.target_sha256),
652
+ requestText,
653
+ semanticArgv: [target.dataset_type, "identity-preflight", "--json", "--timeout-ms", "60000"],
654
+ cli: {
655
+ packageName: installed.packageName,
656
+ packageVersion: installed.packageVersion,
657
+ packageIntegrity: `sha256-${sha256Text(fs.readFileSync(installed.binPath, "utf8"))}`,
658
+ },
659
+ authReceipt: receipt,
660
+ relevantInputHashes: {
661
+ ...workflowObject(target.row.relevant_input_hashes ?? {}),
662
+ source_file: captureFoundryInput(target.owner_source_file).sha256,
663
+ },
664
+ });
665
+ if (result.binding_sha256 !== binding.binding_sha256)
666
+ reject("retained-execution-binding");
667
+ const reportText = fs.readFileSync(reportFile, "utf8");
668
+ const report = workflowObject(JSON.parse(reportText));
669
+ if (report.schema_version !== 1 ||
670
+ report.kind !== target.dataset_type ||
671
+ workflowObject(report.target).id !== target.dataset_id ||
672
+ workflowObject(report.target).version !== target.dataset_version ||
673
+ report.input_path !== requestFile ||
674
+ report.out_dir !== outputDir ||
675
+ workflowObject(report.files).identity_decision !== reportFile ||
676
+ Object.hasOwn(report, "error") ||
677
+ (Object.hasOwn(report, "errors") && (!Array.isArray(report.errors) || report.errors.length)) ||
678
+ result.report_status !== report.status ||
679
+ result.decision !== (report.decision ?? null) ||
680
+ result.signal != null ||
681
+ fs.readFileSync(resolve(result.stderr_log), "utf8") !== "" ||
682
+ typeof result.cli_exit_code !== "number" ||
683
+ ![0, 1].includes(result.cli_exit_code))
684
+ reject("retained-report-identity-path-outcome");
685
+ const manifest = readJson(resolve(result.execution_manifest_file));
686
+ const completedAt = Date.parse(String(manifest.completed_at_utc));
687
+ const generatedAt = Date.parse(String(report.generated_at_utc));
688
+ const runCompletedAt = Date.parse(String(run.generated_at_utc));
689
+ if (!Number.isFinite(completedAt) ||
690
+ !Number.isFinite(generatedAt) ||
691
+ !Number.isFinite(runCompletedAt) ||
692
+ generatedAt < Date.parse(String(claim.claimed_at_utc)) ||
693
+ generatedAt > completedAt ||
694
+ completedAt < Date.parse(String(claim.claimed_at_utc)) ||
695
+ completedAt > runCompletedAt)
696
+ reject("retained-execution-time");
697
+ const checked = validateIdentityPreflightExecution({
698
+ binding,
699
+ exitCode: Number(result.cli_exit_code),
700
+ stdoutText: fs.readFileSync(resolve(result.stdout_log), "utf8"),
701
+ diskReportText: reportText,
702
+ startedAtMs: Date.parse(String(claim.claimed_at_utc)),
703
+ diskReportMtimeMs: fs.statSync(reportFile).mtimeMs,
704
+ completedAtUtc: String(manifest.completed_at_utc),
705
+ requestFile,
706
+ outputDir,
707
+ reportFile,
708
+ stderrText: fs.readFileSync(resolve(result.stderr_log), "utf8"),
709
+ signal: result.signal == null ? null : String(result.signal),
710
+ });
711
+ if (!checked.ok)
712
+ reject(checked.code);
713
+ if (!validateBoundExecutionManifest(manifest, binding, reportText).ok ||
714
+ stableJson(manifest) !== stableJson(checked.manifest))
715
+ reject("retained-execution-manifest");
716
+ return { run, row: target.row };
717
+ }