@tiangong-lca/foundry 0.1.2

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 (323) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +532 -0
  3. package/docs/architecture.md +450 -0
  4. package/docs/foundry-task-contracts.md +147 -0
  5. package/docs/import-profiles/bafu/constraints.md +343 -0
  6. package/docs/import-profiles/bafu/leaf-process-classification-authoring.md +153 -0
  7. package/docs/import-profiles/bafu/profile.md +183 -0
  8. package/docs/import-profiles/uslci/constraints.md +29 -0
  9. package/docs/import-profiles/uslci/profile.md +43 -0
  10. package/docs/import-profiles/worldsteel/constraints.md +77 -0
  11. package/docs/import-profiles/worldsteel/import-coverage.md +93 -0
  12. package/docs/import-profiles/worldsteel/import-plan.md +375 -0
  13. package/docs/import-profiles/worldsteel/profile.md +78 -0
  14. package/docs/package-distribution-contract.md +287 -0
  15. package/docs/public-runtime-contract.md +218 -0
  16. package/docs/runtime-context-contract.md +138 -0
  17. package/docs/safety-policy.md +164 -0
  18. package/docs/task-authorization-contract.md +131 -0
  19. package/docs/uslci-import-runbook.md +336 -0
  20. package/docs/workspace-migration-contract.md +127 -0
  21. package/package-dist/assets/foundry-package-descriptor.json +1661 -0
  22. package/package-dist/scripts/foundry-facade.d.ts +78 -0
  23. package/package-dist/scripts/foundry-facade.js +1317 -0
  24. package/package-dist/scripts/foundry-runtime.d.ts +180 -0
  25. package/package-dist/scripts/foundry-runtime.js +190 -0
  26. package/package-dist/scripts/lib/batch-orchestration/scope-attempt-ledger.d.ts +27 -0
  27. package/package-dist/scripts/lib/batch-orchestration/scope-attempt-ledger.js +85 -0
  28. package/package-dist/scripts/lib/batch-orchestration/scope-resume-contract.d.ts +38 -0
  29. package/package-dist/scripts/lib/batch-orchestration/scope-resume-contract.js +90 -0
  30. package/package-dist/scripts/lib/bundle-row-types.d.ts +44 -0
  31. package/package-dist/scripts/lib/bundle-row-types.js +46 -0
  32. package/package-dist/scripts/lib/bundle-sample-utils.d.ts +183 -0
  33. package/package-dist/scripts/lib/bundle-sample-utils.js +526 -0
  34. package/package-dist/scripts/lib/bundle-source-context.d.ts +31 -0
  35. package/package-dist/scripts/lib/bundle-source-context.js +142 -0
  36. package/package-dist/scripts/lib/canonical-description.d.ts +12 -0
  37. package/package-dist/scripts/lib/canonical-description.js +72 -0
  38. package/package-dist/scripts/lib/canonical-support-rewrites.d.ts +127 -0
  39. package/package-dist/scripts/lib/canonical-support-rewrites.js +527 -0
  40. package/package-dist/scripts/lib/decision-owners/classification.d.ts +245 -0
  41. package/package-dist/scripts/lib/decision-owners/classification.js +754 -0
  42. package/package-dist/scripts/lib/decision-owners/identity-preflight.d.ts +333 -0
  43. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +1353 -0
  44. package/package-dist/scripts/lib/decision-owners/identity-task.d.ts +130 -0
  45. package/package-dist/scripts/lib/decision-owners/identity-task.js +494 -0
  46. package/package-dist/scripts/lib/decision-owners/identity.d.ts +74 -0
  47. package/package-dist/scripts/lib/decision-owners/identity.js +443 -0
  48. package/package-dist/scripts/lib/decision-owners/location.d.ts +239 -0
  49. package/package-dist/scripts/lib/decision-owners/location.js +704 -0
  50. package/package-dist/scripts/lib/decision-task-utils.d.ts +484 -0
  51. package/package-dist/scripts/lib/decision-task-utils.js +735 -0
  52. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +52 -0
  53. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +146 -0
  54. package/package-dist/scripts/lib/finalize-owners/commit-handoff.d.ts +79 -0
  55. package/package-dist/scripts/lib/finalize-owners/commit-handoff.js +515 -0
  56. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +234 -0
  57. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +1720 -0
  58. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.d.ts +140 -0
  59. package/package-dist/scripts/lib/finalize-owners/post-write-closeout.js +656 -0
  60. package/package-dist/scripts/lib/foundry-args.d.ts +7 -0
  61. package/package-dist/scripts/lib/foundry-args.js +38 -0
  62. package/package-dist/scripts/lib/foundry-authentication-environment.d.ts +17 -0
  63. package/package-dist/scripts/lib/foundry-authentication-environment.js +55 -0
  64. package/package-dist/scripts/lib/foundry-authorization-input.d.ts +31 -0
  65. package/package-dist/scripts/lib/foundry-authorization-input.js +151 -0
  66. package/package-dist/scripts/lib/foundry-command-metadata.d.ts +32 -0
  67. package/package-dist/scripts/lib/foundry-command-metadata.js +1012 -0
  68. package/package-dist/scripts/lib/foundry-command-registry.d.ts +34 -0
  69. package/package-dist/scripts/lib/foundry-command-registry.js +241 -0
  70. package/package-dist/scripts/lib/foundry-command-spec.d.ts +1 -0
  71. package/package-dist/scripts/lib/foundry-command-spec.js +1 -0
  72. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +17 -0
  73. package/package-dist/scripts/lib/foundry-decision-owners.js +68 -0
  74. package/package-dist/scripts/lib/foundry-decision-routing.d.ts +3 -0
  75. package/package-dist/scripts/lib/foundry-decision-routing.js +38 -0
  76. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +33 -0
  77. package/package-dist/scripts/lib/foundry-execution-admission.js +225 -0
  78. package/package-dist/scripts/lib/foundry-execution-attempt.d.ts +11 -0
  79. package/package-dist/scripts/lib/foundry-execution-attempt.js +33 -0
  80. package/package-dist/scripts/lib/foundry-execution-context-format.d.ts +18 -0
  81. package/package-dist/scripts/lib/foundry-execution-context-format.js +83 -0
  82. package/package-dist/scripts/lib/foundry-facade-store.d.ts +25 -0
  83. package/package-dist/scripts/lib/foundry-facade-store.js +449 -0
  84. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +21 -0
  85. package/package-dist/scripts/lib/foundry-finalize-owners.js +203 -0
  86. package/package-dist/scripts/lib/foundry-identity-owners.d.ts +13 -0
  87. package/package-dist/scripts/lib/foundry-identity-owners.js +58 -0
  88. package/package-dist/scripts/lib/foundry-managed-host.d.ts +7 -0
  89. package/package-dist/scripts/lib/foundry-managed-host.js +173 -0
  90. package/package-dist/scripts/lib/foundry-migration-adoption-plan.d.ts +39 -0
  91. package/package-dist/scripts/lib/foundry-migration-adoption-plan.js +467 -0
  92. package/package-dist/scripts/lib/foundry-migration-adoption.d.ts +31 -0
  93. package/package-dist/scripts/lib/foundry-migration-adoption.js +187 -0
  94. package/package-dist/scripts/lib/foundry-migration-authority.d.ts +42 -0
  95. package/package-dist/scripts/lib/foundry-migration-authority.js +280 -0
  96. package/package-dist/scripts/lib/foundry-migration-inventory.d.ts +31 -0
  97. package/package-dist/scripts/lib/foundry-migration-inventory.js +148 -0
  98. package/package-dist/scripts/lib/foundry-migration-plan.d.ts +48 -0
  99. package/package-dist/scripts/lib/foundry-migration-plan.js +234 -0
  100. package/package-dist/scripts/lib/foundry-migration-replay.d.ts +3 -0
  101. package/package-dist/scripts/lib/foundry-migration-replay.js +134 -0
  102. package/package-dist/scripts/lib/foundry-migration-stage.d.ts +15 -0
  103. package/package-dist/scripts/lib/foundry-migration-stage.js +152 -0
  104. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +13 -0
  105. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +226 -0
  106. package/package-dist/scripts/lib/foundry-migration-transfer.d.ts +36 -0
  107. package/package-dist/scripts/lib/foundry-migration-transfer.js +350 -0
  108. package/package-dist/scripts/lib/foundry-operation-result.d.ts +71 -0
  109. package/package-dist/scripts/lib/foundry-operation-result.js +264 -0
  110. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +319 -0
  111. package/package-dist/scripts/lib/foundry-owner-execution-store.js +293 -0
  112. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +22 -0
  113. package/package-dist/scripts/lib/foundry-owner-readback.js +189 -0
  114. package/package-dist/scripts/lib/foundry-owner-trace-acceptance.d.ts +15 -0
  115. package/package-dist/scripts/lib/foundry-owner-trace-acceptance.js +68 -0
  116. package/package-dist/scripts/lib/foundry-package-contract.d.ts +56 -0
  117. package/package-dist/scripts/lib/foundry-package-contract.js +392 -0
  118. package/package-dist/scripts/lib/foundry-private-path.d.ts +2 -0
  119. package/package-dist/scripts/lib/foundry-private-path.js +20 -0
  120. package/package-dist/scripts/lib/foundry-runtime-cache.d.ts +3 -0
  121. package/package-dist/scripts/lib/foundry-runtime-cache.js +25 -0
  122. package/package-dist/scripts/lib/foundry-runtime-command-policy.d.ts +20 -0
  123. package/package-dist/scripts/lib/foundry-runtime-command-policy.js +173 -0
  124. package/package-dist/scripts/lib/foundry-runtime-context-types.d.ts +59 -0
  125. package/package-dist/scripts/lib/foundry-runtime-context-types.js +1 -0
  126. package/package-dist/scripts/lib/foundry-runtime-context.d.ts +27 -0
  127. package/package-dist/scripts/lib/foundry-runtime-context.js +668 -0
  128. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +9 -0
  129. package/package-dist/scripts/lib/foundry-runtime-environment.js +90 -0
  130. package/package-dist/scripts/lib/foundry-runtime-error.d.ts +4 -0
  131. package/package-dist/scripts/lib/foundry-runtime-error.js +8 -0
  132. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +18 -0
  133. package/package-dist/scripts/lib/foundry-runtime-identity.js +127 -0
  134. package/package-dist/scripts/lib/foundry-runtime-paths.d.ts +16 -0
  135. package/package-dist/scripts/lib/foundry-runtime-paths.js +159 -0
  136. package/package-dist/scripts/lib/foundry-runtime-qualification.d.ts +66 -0
  137. package/package-dist/scripts/lib/foundry-runtime-qualification.js +223 -0
  138. package/package-dist/scripts/lib/foundry-runtime-selection-record.d.ts +16 -0
  139. package/package-dist/scripts/lib/foundry-runtime-selection-record.js +32 -0
  140. package/package-dist/scripts/lib/foundry-runtime-selection.d.ts +14 -0
  141. package/package-dist/scripts/lib/foundry-runtime-selection.js +123 -0
  142. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +178 -0
  143. package/package-dist/scripts/lib/foundry-runtime-utils.js +603 -0
  144. package/package-dist/scripts/lib/foundry-semantic-input.d.ts +30 -0
  145. package/package-dist/scripts/lib/foundry-semantic-input.js +132 -0
  146. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +68 -0
  147. package/package-dist/scripts/lib/foundry-task-authorization.js +350 -0
  148. package/package-dist/scripts/lib/foundry-task-io.d.ts +18 -0
  149. package/package-dist/scripts/lib/foundry-task-io.js +92 -0
  150. package/package-dist/scripts/lib/foundry-task-registration.d.ts +6 -0
  151. package/package-dist/scripts/lib/foundry-task-registration.js +384 -0
  152. package/package-dist/scripts/lib/foundry-task-start-spec.d.ts +34 -0
  153. package/package-dist/scripts/lib/foundry-task-start-spec.js +161 -0
  154. package/package-dist/scripts/lib/foundry-task-store.d.ts +18 -0
  155. package/package-dist/scripts/lib/foundry-task-store.js +466 -0
  156. package/package-dist/scripts/lib/foundry-task-types.d.ts +99 -0
  157. package/package-dist/scripts/lib/foundry-task-types.js +1 -0
  158. package/package-dist/scripts/lib/foundry-workflow-approval-continuation.d.ts +6 -0
  159. package/package-dist/scripts/lib/foundry-workflow-approval-continuation.js +136 -0
  160. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +3 -0
  161. package/package-dist/scripts/lib/foundry-workflow-assessment.js +231 -0
  162. package/package-dist/scripts/lib/foundry-workflow-authorization.d.ts +22 -0
  163. package/package-dist/scripts/lib/foundry-workflow-authorization.js +174 -0
  164. package/package-dist/scripts/lib/foundry-workflow-context.d.ts +3 -0
  165. package/package-dist/scripts/lib/foundry-workflow-context.js +99 -0
  166. package/package-dist/scripts/lib/foundry-workflow-decisions.d.ts +18 -0
  167. package/package-dist/scripts/lib/foundry-workflow-decisions.js +123 -0
  168. package/package-dist/scripts/lib/foundry-workflow-execution.d.ts +8 -0
  169. package/package-dist/scripts/lib/foundry-workflow-execution.js +248 -0
  170. package/package-dist/scripts/lib/foundry-workflow-finalize.d.ts +13 -0
  171. package/package-dist/scripts/lib/foundry-workflow-finalize.js +264 -0
  172. package/package-dist/scripts/lib/foundry-workflow-identity-apply.d.ts +14 -0
  173. package/package-dist/scripts/lib/foundry-workflow-identity-apply.js +159 -0
  174. package/package-dist/scripts/lib/foundry-workflow-identity.d.ts +6 -0
  175. package/package-dist/scripts/lib/foundry-workflow-identity.js +153 -0
  176. package/package-dist/scripts/lib/foundry-workflow-import.d.ts +4 -0
  177. package/package-dist/scripts/lib/foundry-workflow-import.js +70 -0
  178. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +11 -0
  179. package/package-dist/scripts/lib/foundry-workflow-io.js +77 -0
  180. package/package-dist/scripts/lib/foundry-workflow-reference-verify.d.ts +41 -0
  181. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +266 -0
  182. package/package-dist/scripts/lib/foundry-workflow-rows.d.ts +2 -0
  183. package/package-dist/scripts/lib/foundry-workflow-rows.js +47 -0
  184. package/package-dist/scripts/lib/foundry-workflow-semantic.d.ts +5 -0
  185. package/package-dist/scripts/lib/foundry-workflow-semantic.js +367 -0
  186. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +37 -0
  187. package/package-dist/scripts/lib/foundry-workflow-state.js +158 -0
  188. package/package-dist/scripts/lib/full-context-proof.d.ts +51 -0
  189. package/package-dist/scripts/lib/full-context-proof.js +932 -0
  190. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +184 -0
  191. package/package-dist/scripts/lib/identity-preflight-artifacts.js +573 -0
  192. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +117 -0
  193. package/package-dist/scripts/lib/identity-preflight-proof.js +341 -0
  194. package/package-dist/scripts/lib/identity-reference-rewrite-utils.d.ts +147 -0
  195. package/package-dist/scripts/lib/identity-reference-rewrite-utils.js +817 -0
  196. package/package-dist/scripts/lib/import-curation/authoring-packages.d.ts +28 -0
  197. package/package-dist/scripts/lib/import-curation/authoring-packages.js +92 -0
  198. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +32 -0
  199. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +203 -0
  200. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +47 -0
  201. package/package-dist/scripts/lib/import-curation/curation-gate.js +528 -0
  202. package/package-dist/scripts/lib/import-curation/internal/artifact-inputs.d.ts +24 -0
  203. package/package-dist/scripts/lib/import-curation/internal/artifact-inputs.js +152 -0
  204. package/package-dist/scripts/lib/import-curation/internal/authoring-patch-workflow.d.ts +3 -0
  205. package/package-dist/scripts/lib/import-curation/internal/authoring-patch-workflow.js +3 -0
  206. package/package-dist/scripts/lib/import-curation/internal/authoring-task-workflow.d.ts +1 -0
  207. package/package-dist/scripts/lib/import-curation/internal/authoring-task-workflow.js +1 -0
  208. package/package-dist/scripts/lib/import-curation/internal/context-inputs.d.ts +56 -0
  209. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +206 -0
  210. package/package-dist/scripts/lib/import-curation/internal/curation-gate-workflow.d.ts +14 -0
  211. package/package-dist/scripts/lib/import-curation/internal/curation-gate-workflow.js +14 -0
  212. package/package-dist/scripts/lib/import-curation/internal/dataset-payload.d.ts +70 -0
  213. package/package-dist/scripts/lib/import-curation/internal/dataset-payload.js +141 -0
  214. package/package-dist/scripts/lib/import-curation/internal/dataset-types.d.ts +25 -0
  215. package/package-dist/scripts/lib/import-curation/internal/dataset-types.js +45 -0
  216. package/package-dist/scripts/lib/import-curation/internal/full-context-proof.d.ts +129 -0
  217. package/package-dist/scripts/lib/import-curation/internal/full-context-proof.js +552 -0
  218. package/package-dist/scripts/lib/import-curation/internal/hash-utils.d.ts +2 -0
  219. package/package-dist/scripts/lib/import-curation/internal/hash-utils.js +10 -0
  220. package/package-dist/scripts/lib/import-curation/internal/mutation-manifest-workflow.d.ts +15 -0
  221. package/package-dist/scripts/lib/import-curation/internal/mutation-manifest-workflow.js +15 -0
  222. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.d.ts +31 -0
  223. package/package-dist/scripts/lib/import-curation/internal/prewrite-cleanup.js +467 -0
  224. package/package-dist/scripts/lib/import-curation/internal/profiles-config.d.ts +47 -0
  225. package/package-dist/scripts/lib/import-curation/internal/profiles-config.js +88 -0
  226. package/package-dist/scripts/lib/import-curation/internal/runtime-io.d.ts +23 -0
  227. package/package-dist/scripts/lib/import-curation/internal/runtime-io.js +132 -0
  228. package/package-dist/scripts/lib/import-curation/internal/trace-summary.d.ts +53 -0
  229. package/package-dist/scripts/lib/import-curation/internal/trace-summary.js +114 -0
  230. package/package-dist/scripts/lib/import-curation/internal/workflow-authoring-tasks.d.ts +141 -0
  231. package/package-dist/scripts/lib/import-curation/internal/workflow-authoring-tasks.js +854 -0
  232. package/package-dist/scripts/lib/import-curation/internal/workflow-decision-apply-context.d.ts +20 -0
  233. package/package-dist/scripts/lib/import-curation/internal/workflow-decision-apply-context.js +46 -0
  234. package/package-dist/scripts/lib/import-curation/internal/workflow-decision-full-context.d.ts +110 -0
  235. package/package-dist/scripts/lib/import-curation/internal/workflow-decision-full-context.js +782 -0
  236. package/package-dist/scripts/lib/import-curation/internal/workflow-dry-run-context.d.ts +24 -0
  237. package/package-dist/scripts/lib/import-curation/internal/workflow-dry-run-context.js +191 -0
  238. package/package-dist/scripts/lib/import-curation/internal/workflow-evidence-scope.d.ts +80 -0
  239. package/package-dist/scripts/lib/import-curation/internal/workflow-evidence-scope.js +359 -0
  240. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-decision-context.d.ts +146 -0
  241. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-decision-context.js +381 -0
  242. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.d.ts +223 -0
  243. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +1079 -0
  244. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-collect.d.ts +41 -0
  245. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-collect.js +412 -0
  246. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-evidence-context.d.ts +117 -0
  247. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-evidence-context.js +278 -0
  248. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-evidence.d.ts +59 -0
  249. package/package-dist/scripts/lib/import-curation/internal/workflow-patch-evidence.js +593 -0
  250. package/package-dist/scripts/lib/import-curation/internal/workflow-queue-context.d.ts +58 -0
  251. package/package-dist/scripts/lib/import-curation/internal/workflow-queue-context.js +263 -0
  252. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.d.ts +177 -0
  253. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +812 -0
  254. package/package-dist/scripts/lib/import-curation/internal/workflow-row-transform-context.d.ts +159 -0
  255. package/package-dist/scripts/lib/import-curation/internal/workflow-row-transform-context.js +466 -0
  256. package/package-dist/scripts/lib/import-curation/internal/workflow-semantic-actions.d.ts +152 -0
  257. package/package-dist/scripts/lib/import-curation/internal/workflow-semantic-actions.js +1377 -0
  258. package/package-dist/scripts/lib/import-curation/internal/workflow-source-reference-context.d.ts +38 -0
  259. package/package-dist/scripts/lib/import-curation/internal/workflow-source-reference-context.js +116 -0
  260. package/package-dist/scripts/lib/import-curation/mutation-manifest.d.ts +51 -0
  261. package/package-dist/scripts/lib/import-curation/mutation-manifest.js +542 -0
  262. package/package-dist/scripts/lib/import-curation/patch-collect.d.ts +18 -0
  263. package/package-dist/scripts/lib/import-curation/patch-collect.js +172 -0
  264. package/package-dist/scripts/lib/import-curation/profiles.d.ts +1 -0
  265. package/package-dist/scripts/lib/import-curation/profiles.js +1 -0
  266. package/package-dist/scripts/lib/import-curation/trace-summary.d.ts +1 -0
  267. package/package-dist/scripts/lib/import-curation/trace-summary.js +1 -0
  268. package/package-dist/scripts/lib/oauth-session-reference.d.ts +1 -0
  269. package/package-dist/scripts/lib/oauth-session-reference.js +20 -0
  270. package/package-dist/scripts/lib/post-authoring-finalize-utils.d.ts +95 -0
  271. package/package-dist/scripts/lib/post-authoring-finalize-utils.js +548 -0
  272. package/package-dist/scripts/lib/post-write-root-proof.d.ts +44 -0
  273. package/package-dist/scripts/lib/post-write-root-proof.js +169 -0
  274. package/package-dist/scripts/lib/reference-description-text.d.ts +2 -0
  275. package/package-dist/scripts/lib/reference-description-text.js +12 -0
  276. package/package-dist/scripts/lib/remote-verification-accepted-diff.d.ts +42 -0
  277. package/package-dist/scripts/lib/remote-verification-accepted-diff.js +424 -0
  278. package/package-dist/scripts/lib/same-identity-commit-recovery.d.ts +8 -0
  279. package/package-dist/scripts/lib/same-identity-commit-recovery.js +52 -0
  280. package/package-dist/scripts/lib/source-semantics.d.ts +255 -0
  281. package/package-dist/scripts/lib/source-semantics.js +888 -0
  282. package/package-dist/scripts/lib/stage-contract.d.ts +36 -0
  283. package/package-dist/scripts/lib/stage-contract.js +25 -0
  284. package/package-dist/scripts/lib/task-authorization.d.ts +84 -0
  285. package/package-dist/scripts/lib/task-authorization.js +210 -0
  286. package/package-dist/scripts/lib/tidas-adapter.d.ts +113 -0
  287. package/package-dist/scripts/lib/tidas-adapter.js +525 -0
  288. package/package-dist/scripts/lib/tidas-language-utils.d.ts +8 -0
  289. package/package-dist/scripts/lib/tidas-language-utils.js +206 -0
  290. package/package-dist/scripts/lib/tidas-row-utils.d.ts +70 -0
  291. package/package-dist/scripts/lib/tidas-row-utils.js +225 -0
  292. package/package-dist/scripts/lib/trace-coverage.d.ts +53 -0
  293. package/package-dist/scripts/lib/trace-coverage.js +178 -0
  294. package/package-dist/scripts/package-entry.d.ts +2 -0
  295. package/package-dist/scripts/package-entry.js +4 -0
  296. package/package-dist/scripts/public-api.d.ts +80 -0
  297. package/package-dist/scripts/public-api.js +28 -0
  298. package/package-dist/scripts/runtime-entry.d.ts +23 -0
  299. package/package-dist/scripts/runtime-entry.js +424 -0
  300. package/package.json +93 -0
  301. package/specs/canonical-support/flow-properties-unit-groups.json +2692 -0
  302. package/specs/import-profiles.json +118 -0
  303. package/specs/prewrite-content-policy.json +105 -0
  304. package/specs/schemas/authorization-derivation.schema.json +34 -0
  305. package/specs/schemas/execution-context.schema.json +68 -0
  306. package/specs/schemas/foundry-authorization-input.schema.json +120 -0
  307. package/specs/schemas/foundry-facade-request-index.schema.json +78 -0
  308. package/specs/schemas/foundry-managed-runtime.schema.json +122 -0
  309. package/specs/schemas/foundry-migration-activation.schema.json +213 -0
  310. package/specs/schemas/foundry-migration-adoption-plan.schema.json +548 -0
  311. package/specs/schemas/foundry-migration-transfer-receipt.schema.json +93 -0
  312. package/specs/schemas/foundry-operation-result.schema.json +147 -0
  313. package/specs/schemas/foundry-package-descriptor.schema.json +134 -0
  314. package/specs/schemas/foundry-runtime-selection.schema.json +59 -0
  315. package/specs/schemas/foundry-semantic-input.schema.json +36 -0
  316. package/specs/schemas/foundry-task-start.schema.json +123 -0
  317. package/specs/schemas/foundry-workspace-migration-pending.schema.json +17 -0
  318. package/specs/schemas/foundry-workspace-migration-plan.schema.json +59 -0
  319. package/specs/schemas/foundry-workspace-migration-transfer-plan.schema.json +357 -0
  320. package/specs/schemas/foundry-workspace-v2.schema.json +70 -0
  321. package/specs/schemas/runtime-qualification.schema.json +63 -0
  322. package/specs/schemas/task-authorization.schema.json +154 -0
  323. package/specs/schemas/tidas-runtime-expectation.schema.json +54 -0
@@ -0,0 +1,1353 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+ import { createIdentityPreflightBinding, parseFreshIntentBoundAuthReceipt, validateBoundExecutionManifest, validateIdentityPreflightExecution, } from "../identity-preflight-proof.js";
6
+ import { createFileArtifactFact, createFoundryCommandSpec } from "../foundry-command-spec.js";
7
+ import { readOnlyStageContract } from "../stage-contract.js";
8
+ // Run-level identity-preflight RESULT cache (env-gated; off unless
9
+ // BAFU_IDENTITY_PREFLIGHT_RESULT_CACHE points at a directory). Entries are keyed by
10
+ // the complete execution binding hash, including target, request, CLI, account, and
11
+ // input evidence. Only positive canonical-reuse results may be published or restored;
12
+ // negative/create-new searches must be repeated. After an identity is minted or
13
+ // committed, the batch runner scans the bound manifests and removes every positive
14
+ // cache entry for that dataset identity before another scope can reuse stale evidence.
15
+ function identityPreflightResultCacheDir(resolveRepoPath, environment) {
16
+ const raw = environment.BAFU_IDENTITY_PREFLIGHT_RESULT_CACHE;
17
+ return raw ? resolveRepoPath(raw) : null;
18
+ }
19
+ function identityPreflightResultCacheEntryDir(cacheDir, bindingSha256) {
20
+ if (!cacheDir || !bindingSha256)
21
+ return null;
22
+ return path.join(cacheDir, bindingSha256);
23
+ }
24
+ const identityPreflightRunStageContract = readOnlyStageContract([
25
+ {
26
+ stage: "load_index",
27
+ phase: "prepare",
28
+ purpose: "Read and select rows from a Foundry identity-preflight request index.",
29
+ inputs: ["identity-preflight-requests.jsonl", "dataset type/id/offset/limit options"],
30
+ outputs: ["selected request rows"],
31
+ side_effects: [],
32
+ },
33
+ {
34
+ stage: "normalize_requests",
35
+ phase: "rewrite_cleanup",
36
+ purpose: "Resolve request files, output directories, row keys, retry settings, and timeout settings before invoking the published CLI.",
37
+ inputs: ["selected request rows", "runner options"],
38
+ outputs: ["normalized executable request descriptors"],
39
+ side_effects: [],
40
+ },
41
+ {
42
+ stage: "execute_cli_preflight",
43
+ phase: "gate_validate",
44
+ purpose: "Execute the published tiangong-lca flow/process identity-preflight command for each selected request.",
45
+ inputs: ["selected request rows", "request JSON files"],
46
+ outputs: ["identity-decision.json", "identity candidate artifacts", "stdout/stderr logs"],
47
+ side_effects: ["runs published CLI read-only search", "writes local .foundry artifacts"],
48
+ },
49
+ {
50
+ stage: "collect_evidence",
51
+ phase: "report",
52
+ purpose: "Normalize CLI results so blocked/needs-review identity findings remain evidence rather than runner failures.",
53
+ inputs: ["CLI stdout", "identity-decision report files"],
54
+ outputs: ["identity-preflight-run-results.jsonl"],
55
+ side_effects: ["writes local .foundry artifacts"],
56
+ },
57
+ {
58
+ stage: "report",
59
+ phase: "report",
60
+ purpose: "Emit selected counts, failures, identity findings, and artifact paths.",
61
+ inputs: ["normalized run results"],
62
+ outputs: ["dataset-identity-preflight-run-report.json"],
63
+ side_effects: ["writes local .foundry artifacts"],
64
+ },
65
+ ]);
66
+ export function createIdentityPreflightRunCommands({ executionEnvironment = process.env, executionCwd, asText, booleanOption, buildIdentityPreflightArtifacts, datasetIdentity, ensureArray, fileExists, identityPreflightSourceIndexPaths, integerOption, jsonSha256, loadIdentityPreflightSourceFileMap, normalizedList, nowIso, positiveIntegerOption, readJson, readJsonLines, readRowsFile, repoRelativeMaybe, repoRelativePath, repoRoot, resolveRepoPath, resolveTiangongLcaCliCommand, resolveTiangongLcaCliCommandPrefix, resolveTiangongLcaCliBin, safeFileToken, sha256Text, shellQuote, writeJson, writeJsonLines, writeText, }) {
67
+ function identityPreflightRunIndexPath(options) {
68
+ return resolveRepoPath(options.index ||
69
+ options.input ||
70
+ options.identityPreflightIndex ||
71
+ options.identityPreflightRequests);
72
+ }
73
+ function identityPreflightSpawnTimeoutMs(timeoutMs) {
74
+ const graceMs = Math.min(5_000, Math.max(250, Math.ceil(timeoutMs * 0.1)));
75
+ return timeoutMs + graceMs;
76
+ }
77
+ function identityPreflightRunReportFile(row) {
78
+ const explicit = row.expected_report_file ||
79
+ row.identity_decision_file ||
80
+ row.identityDecisionFile ||
81
+ row.report_file ||
82
+ row.reportFile;
83
+ if (explicit)
84
+ return resolveRepoPath(explicit);
85
+ const outputDir = row.output_dir || row.outputDir;
86
+ return outputDir
87
+ ? path.join(resolveRepoPath(outputDir), "outputs", "identity-decision.json")
88
+ : null;
89
+ }
90
+ function identityPreflightRunOutputDir(row) {
91
+ const outputDir = row.output_dir || row.outputDir;
92
+ if (outputDir)
93
+ return resolveRepoPath(outputDir);
94
+ const reportFile = identityPreflightRunReportFile(row);
95
+ return reportFile ? path.dirname(path.dirname(reportFile)) : null;
96
+ }
97
+ function identityPreflightRunRequestFile(row) {
98
+ return resolveRepoPath(row.request_file || row.requestFile || row.input);
99
+ }
100
+ function identityPreflightRunRowKey(row, index) {
101
+ return [
102
+ row.dataset_type || row.type || "dataset",
103
+ row.dataset_id || row.entity_id || row.id || `row-${index}`,
104
+ row.dataset_version || row.version || "00.00.001",
105
+ ].join(":");
106
+ }
107
+ function selectIdentityPreflightRunRows(rows, options) {
108
+ const datasetTypes = new Set(normalizedList(options.datasetType || options.datasetTypes || options.type));
109
+ const ids = new Set(normalizedList(options.id || options.ids || options.datasetId));
110
+ const offset = Math.max(0, integerOption(options.offset, 0) ?? 0);
111
+ const limit = positiveIntegerOption(options.limit || options.count, null);
112
+ const filtered = rows.filter((row) => {
113
+ const datasetType = asText(row.dataset_type || row.type);
114
+ const id = asText(row.dataset_id || row.entity_id || row.id);
115
+ if (datasetTypes.size > 0 && !datasetTypes.has(datasetType))
116
+ return false;
117
+ if (ids.size > 0 && !ids.has(id))
118
+ return false;
119
+ return true;
120
+ });
121
+ return filtered.slice(offset, limit ? offset + limit : undefined);
122
+ }
123
+ function identityPreflightRunIdentityKey(row) {
124
+ return [
125
+ asText(row?.dataset_type || row?.type),
126
+ asText(row?.dataset_id || row?.entity_id || row?.id),
127
+ asText(row?.dataset_version || row?.version) || "00.00.001",
128
+ ].join(":");
129
+ }
130
+ function parseJsonMaybe(text) {
131
+ try {
132
+ return text ? JSON.parse(String(text)) : null;
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ function retryFailedRowsFromArtifact(value) {
139
+ if (!value)
140
+ return [];
141
+ if (Array.isArray(value))
142
+ return value.flatMap(retryFailedRowsFromArtifact);
143
+ if (typeof value !== "object" || value === null)
144
+ return [];
145
+ const artifact = value;
146
+ const directStatus = asText(artifact.status);
147
+ const hasFailure = directStatus === "failed" || Boolean(artifact.failure_code) || artifact.failed === true;
148
+ const nested = [
149
+ artifact.results,
150
+ artifact.rows,
151
+ artifact.items,
152
+ artifact.blockers,
153
+ artifact.failures,
154
+ ].flatMap(retryFailedRowsFromArtifact);
155
+ return hasFailure ? [artifact, ...nested] : nested;
156
+ }
157
+ function retryFailedKeysFromArtifact(retryFailedPath) {
158
+ if (!retryFailedPath || !fileExists(retryFailedPath))
159
+ return new Set();
160
+ const value = retryFailedPath.toLowerCase().endsWith(".jsonl")
161
+ ? readJsonLines(retryFailedPath)
162
+ : readJson(retryFailedPath);
163
+ const keys = retryFailedRowsFromArtifact(value)
164
+ .map(identityPreflightRunIdentityKey)
165
+ .filter((key) => !key.startsWith(":"));
166
+ return new Set(keys);
167
+ }
168
+ function retriableIdentityPreflightFailure(row) {
169
+ return ["identity_preflight_timeout", "identity_preflight_report_missing_or_non_json"].includes(row.failure_code ?? "");
170
+ }
171
+ function reusablePositiveIdentityReport(report) {
172
+ const decision = asText(report?.decision).toLowerCase();
173
+ return (["reuse", "reuse_existing", "reuse_existing_reference", "block_duplicate"].includes(decision) && ensureArray(report?.candidates).length > 0);
174
+ }
175
+ function runDatasetIdentityPreflightRun(options) {
176
+ if (options.help) {
177
+ return {
178
+ schema_version: 1,
179
+ status: "help",
180
+ command: "dataset-identity-preflight-run",
181
+ purpose: "Execute Foundry-generated process/flow identity-preflight request indexes through the CLI without writing the database.",
182
+ usage: [
183
+ "node scripts/foundry.ts dataset-identity-preflight-run --index <identity-preflight-requests.jsonl> --out-dir <run-dir> --timeout-ms 60000",
184
+ "node scripts/foundry.ts dataset-identity-preflight-run --index ./identity-preflight-requests/identity-preflight-requests.jsonl --only-pending --timeout-ms 60000",
185
+ "node scripts/foundry.ts dataset-identity-preflight-run --index ./identity-preflight-requests/identity-preflight-requests.jsonl --retry-failed ./identity-preflight-run/dataset-identity-preflight-run-report.json --max-attempts 3",
186
+ ],
187
+ ...identityPreflightRunStageContract,
188
+ };
189
+ }
190
+ const indexPath = identityPreflightRunIndexPath(options);
191
+ if (!indexPath || !fileExists(indexPath)) {
192
+ throw new Error("--index is required and must point to identity-preflight-requests.jsonl.");
193
+ }
194
+ const outDir = resolveRepoPath(options.outDir || path.join(path.dirname(path.dirname(indexPath)), "identity-preflight-run"));
195
+ const rows = readJsonLines(indexPath);
196
+ const retryFailedPath = resolveRepoPath(options.retryFailed || options.retryFailedReport || options.retryLedger);
197
+ const retryFailedKeys = retryFailedPath ? retryFailedKeysFromArtifact(retryFailedPath) : null;
198
+ const initiallySelectedRows = selectIdentityPreflightRunRows(rows, options);
199
+ const selectedRows = retryFailedKeys
200
+ ? initiallySelectedRows.filter((row) => retryFailedKeys.has(identityPreflightRunIdentityKey(row)))
201
+ : initiallySelectedRows;
202
+ const onlyPending = booleanOption(options.onlyPending);
203
+ const dryRun = booleanOption(options.dryRun);
204
+ const maxAttempts = positiveIntegerOption(options.maxAttempts || options.retryMaxAttempts, retryFailedKeys ? 3 : 1) ?? (retryFailedKeys ? 3 : 1);
205
+ const timeoutMs = positiveIntegerOption(options.timeoutMs || options.timeout || options.identityPreflightTimeoutMs, 60_000) ?? 60_000;
206
+ const spawnTimeoutMs = identityPreflightSpawnTimeoutMs(timeoutMs);
207
+ const cli = resolveTiangongLcaCliCommand
208
+ ? resolveTiangongLcaCliCommand()
209
+ : {
210
+ command: resolveTiangongLcaCliBin(),
211
+ args: [],
212
+ display: resolveTiangongLcaCliBin(),
213
+ package: null,
214
+ };
215
+ const authReceiptPath = resolveRepoPath(options.authReceipt || options.authIdentityReceipt || options.accountReceipt);
216
+ const verifiedProjectRef = asText(executionEnvironment.FOUNDRY_VERIFIED_PROJECT_REF);
217
+ const verifiedUserId = asText(executionEnvironment.FOUNDRY_VERIFIED_USER_ID);
218
+ const optionExpectedProjectRef = asText(options.expectedProjectRef || options.expectedProject || options.projectRef);
219
+ const optionExpectedUserId = asText(options.expectedUserId || options.targetUserId);
220
+ if ((verifiedProjectRef &&
221
+ optionExpectedProjectRef &&
222
+ verifiedProjectRef !== optionExpectedProjectRef) ||
223
+ (verifiedUserId && optionExpectedUserId && verifiedUserId !== optionExpectedUserId)) {
224
+ throw new Error("Identity-preflight expected account does not match the receipt-bound env.");
225
+ }
226
+ const expectedProjectRef = verifiedProjectRef ||
227
+ optionExpectedProjectRef ||
228
+ asText(executionEnvironment.FOUNDRY_EXPECTED_PROJECT_REF);
229
+ const expectedUserId = verifiedUserId ||
230
+ optionExpectedUserId ||
231
+ asText(executionEnvironment.FOUNDRY_EXPECTED_USER_ID);
232
+ let authReceipt = null;
233
+ if (!dryRun && selectedRows.length > 0) {
234
+ if (!expectedProjectRef || !expectedUserId) {
235
+ throw new Error("Identity-preflight execution requires --expected-project-ref and --expected-user-id (or receipt-bound Foundry account env).");
236
+ }
237
+ let receiptValue;
238
+ if (authReceiptPath) {
239
+ if (!verifiedProjectRef || !verifiedUserId) {
240
+ throw new Error("Explicit --auth-receipt requires a receipt-bound Foundry account environment.");
241
+ }
242
+ if (!fileExists(authReceiptPath)) {
243
+ throw new Error("--auth-receipt must point to a readable CLI AuthIdentityReceipt.");
244
+ }
245
+ receiptValue = readJson(authReceiptPath);
246
+ }
247
+ else {
248
+ const receiptArgs = [
249
+ ...cli.args,
250
+ "auth",
251
+ "identity-receipt",
252
+ "--expected-project-ref",
253
+ expectedProjectRef,
254
+ "--expected-user-id",
255
+ expectedUserId,
256
+ "--json",
257
+ ];
258
+ const receiptResult = spawnSync(cli.command, receiptArgs, {
259
+ cwd: executionCwd ?? repoRoot,
260
+ env: {
261
+ ...executionEnvironment,
262
+ TIANGONG_LCA_AUTH_MODE: "oauth",
263
+ TIANGONG_LCA_DISABLE_SESSION_CACHE: "false",
264
+ TIANGONG_LCA_FORCE_REAUTH: "false",
265
+ },
266
+ encoding: "utf8",
267
+ maxBuffer: 256 * 1024,
268
+ timeout: 30_000,
269
+ killSignal: "SIGTERM",
270
+ shell: false,
271
+ windowsHide: true,
272
+ });
273
+ if (receiptResult.error ||
274
+ receiptResult.status !== 0 ||
275
+ receiptResult.signal !== null ||
276
+ receiptResult.stderr !== "") {
277
+ throw new Error("CLI auth identity-receipt failed before identity-preflight execution.");
278
+ }
279
+ receiptValue = parseJsonMaybe(String(receiptResult.stdout || "").trim());
280
+ if (!receiptValue) {
281
+ throw new Error("CLI auth identity-receipt did not emit one JSON receipt.");
282
+ }
283
+ }
284
+ authReceipt = parseFreshIntentBoundAuthReceipt(receiptValue, {
285
+ nowMs: Date.now(),
286
+ maxAgeMs: positiveIntegerOption(options.authReceiptMaxAgeMs, 300_000) ?? 300_000,
287
+ expectedProjectRef,
288
+ expectedUserId,
289
+ });
290
+ }
291
+ const logDir = path.join(outDir, "logs");
292
+ const resultRows = [];
293
+ const resultCacheDir = identityPreflightResultCacheDir(resolveRepoPath, executionEnvironment);
294
+ selectedRows.forEach((row, selectedIndex) => {
295
+ const datasetType = asText(row.dataset_type || row.type);
296
+ const datasetId = asText(row.dataset_id || row.entity_id || row.id);
297
+ const datasetVersion = asText(row.dataset_version || row.version) || "00.00.001";
298
+ const requestFile = identityPreflightRunRequestFile(row);
299
+ const outputDir = identityPreflightRunOutputDir(row);
300
+ const reportFile = identityPreflightRunReportFile(row);
301
+ const key = identityPreflightRunRowKey(row, selectedIndex);
302
+ const logToken = safeFileToken(key, `row-${selectedIndex}`);
303
+ const stdoutLog = path.join(logDir, `${logToken}.stdout.json`);
304
+ const stderrLog = path.join(logDir, `${logToken}.stderr.log`);
305
+ const cliArgs = [
306
+ datasetType,
307
+ "identity-preflight",
308
+ "--input",
309
+ requestFile,
310
+ "--out-dir",
311
+ outputDir,
312
+ "--json",
313
+ "--timeout-ms",
314
+ String(timeoutMs),
315
+ ];
316
+ let baseRow = {
317
+ selected_index: selectedIndex,
318
+ dataset_type: datasetType,
319
+ dataset_id: datasetId,
320
+ dataset_version: datasetVersion,
321
+ request_file: repoRelativeMaybe(requestFile),
322
+ output_dir: repoRelativeMaybe(outputDir),
323
+ report_file: repoRelativeMaybe(reportFile),
324
+ command: [cli.command, ...cli.args, ...cliArgs].map(shellQuote).join(" "),
325
+ executable: cli.command,
326
+ cli_package: cli.package,
327
+ cli_args: cliArgs,
328
+ command_spec: requestFile && fileExists(requestFile)
329
+ ? createFoundryCommandSpec({
330
+ executable: cli.command,
331
+ argv: [...cli.args, ...cliArgs],
332
+ binding: {
333
+ artifacts: [
334
+ createFileArtifactFact({
335
+ role: "identity_preflight_request",
336
+ path: repoRelativePath(requestFile),
337
+ filePath: requestFile,
338
+ }),
339
+ ],
340
+ },
341
+ })
342
+ : null,
343
+ stdout_log: repoRelativePath(stdoutLog),
344
+ stderr_log: repoRelativePath(stderrLog),
345
+ };
346
+ if (!datasetType || !["flow", "process"].includes(datasetType)) {
347
+ resultRows.push({
348
+ ...baseRow,
349
+ status: "failed",
350
+ failure_code: "identity_preflight_dataset_type_invalid",
351
+ cli_exit_code: null,
352
+ report_status: null,
353
+ decision: null,
354
+ });
355
+ return;
356
+ }
357
+ if (!requestFile || !fileExists(requestFile)) {
358
+ resultRows.push({
359
+ ...baseRow,
360
+ status: "failed",
361
+ failure_code: "identity_preflight_request_missing",
362
+ cli_exit_code: null,
363
+ report_status: null,
364
+ decision: null,
365
+ });
366
+ return;
367
+ }
368
+ if (!outputDir) {
369
+ resultRows.push({
370
+ ...baseRow,
371
+ status: "failed",
372
+ failure_code: "identity_preflight_output_dir_missing",
373
+ cli_exit_code: null,
374
+ report_status: null,
375
+ decision: null,
376
+ });
377
+ return;
378
+ }
379
+ const requestText = fs.readFileSync(requestFile, "utf8");
380
+ const requestBytesSha256 = sha256Text(requestText);
381
+ if (row.request_bytes_sha256 && asText(row.request_bytes_sha256) !== requestBytesSha256) {
382
+ resultRows.push({
383
+ ...baseRow,
384
+ status: "failed",
385
+ failure_code: "identity_preflight_request_hash_drift",
386
+ cli_exit_code: null,
387
+ report_status: null,
388
+ decision: null,
389
+ });
390
+ return;
391
+ }
392
+ let requestValue;
393
+ try {
394
+ requestValue = JSON.parse(requestText);
395
+ }
396
+ catch {
397
+ resultRows.push({
398
+ ...baseRow,
399
+ status: "failed",
400
+ failure_code: "identity_preflight_request_non_json",
401
+ cli_exit_code: null,
402
+ report_status: null,
403
+ decision: null,
404
+ });
405
+ return;
406
+ }
407
+ if (row.request_json_sha256 && asText(row.request_json_sha256) !== jsonSha256(requestValue)) {
408
+ resultRows.push({
409
+ ...baseRow,
410
+ status: "failed",
411
+ failure_code: "identity_preflight_request_json_hash_drift",
412
+ cli_exit_code: null,
413
+ report_status: null,
414
+ decision: null,
415
+ });
416
+ return;
417
+ }
418
+ const requestTargetSha256 = jsonSha256(requestValue?.target);
419
+ const declaredTargetSha256 = asText(row.target_sha256) || requestTargetSha256;
420
+ if (declaredTargetSha256 !== requestTargetSha256) {
421
+ resultRows.push({
422
+ ...baseRow,
423
+ status: "failed",
424
+ failure_code: "identity_preflight_target_hash_drift",
425
+ cli_exit_code: null,
426
+ report_status: null,
427
+ decision: null,
428
+ });
429
+ return;
430
+ }
431
+ const relevantInputHashes = {
432
+ ...(row.relevant_input_hashes && typeof row.relevant_input_hashes === "object"
433
+ ? row.relevant_input_hashes
434
+ : {}),
435
+ };
436
+ const sourceFile = resolveRepoPath(row.source_file || row.sourceFile);
437
+ if (sourceFile && fileExists(sourceFile)) {
438
+ relevantInputHashes.source_file = sha256Text(fs.readFileSync(sourceFile, "utf8"));
439
+ }
440
+ const packageSpec = asText(cli.package);
441
+ const packageAt = packageSpec.lastIndexOf("@");
442
+ const packageName = packageAt > 0 ? packageSpec.slice(0, packageAt) : packageSpec || "cli-override";
443
+ const packageVersion = asText(cli.package_version) ||
444
+ (packageAt > 0 ? packageSpec.slice(packageAt + 1) : "override");
445
+ const binPath = asText(cli.bin_path);
446
+ const packageIntegrity = binPath && fileExists(binPath)
447
+ ? `sha256-${sha256Text(fs.readFileSync(binPath, "utf8"))}`
448
+ : null;
449
+ let executionBinding;
450
+ try {
451
+ executionBinding = createIdentityPreflightBinding({
452
+ datasetType,
453
+ datasetId,
454
+ datasetVersion,
455
+ targetSha256: declaredTargetSha256,
456
+ requestText,
457
+ semanticArgv: [
458
+ datasetType,
459
+ "identity-preflight",
460
+ "--json",
461
+ "--timeout-ms",
462
+ String(timeoutMs),
463
+ ],
464
+ cli: { packageName, packageVersion, packageIntegrity },
465
+ authReceipt,
466
+ relevantInputHashes,
467
+ });
468
+ }
469
+ catch {
470
+ resultRows.push({
471
+ ...baseRow,
472
+ status: "failed",
473
+ failure_code: "identity_preflight_execution_binding_invalid",
474
+ cli_exit_code: null,
475
+ report_status: null,
476
+ decision: null,
477
+ });
478
+ return;
479
+ }
480
+ const executionManifestFile = path.join(outputDir, "outputs", "foundry-identity-preflight-execution.json");
481
+ const resultCacheEntryDir = identityPreflightResultCacheEntryDir(resultCacheDir, executionBinding.binding_sha256);
482
+ baseRow = {
483
+ ...baseRow,
484
+ request_bytes_sha256: requestBytesSha256,
485
+ binding_sha256: executionBinding.binding_sha256,
486
+ execution_manifest_file: repoRelativeMaybe(executionManifestFile),
487
+ };
488
+ if (resultCacheEntryDir && reportFile && outputDir && !fileExists(reportFile)) {
489
+ const cachedReportFile = path.join(resultCacheEntryDir, "identity-decision.json");
490
+ const cachedManifestFile = path.join(resultCacheEntryDir, "foundry-identity-preflight-execution.json");
491
+ if (fileExists(cachedReportFile) && fileExists(cachedManifestFile)) {
492
+ try {
493
+ const cachedReportText = fs.readFileSync(cachedReportFile, "utf8");
494
+ const cachedManifest = readJson(cachedManifestFile);
495
+ if (validateBoundExecutionManifest(cachedManifest, executionBinding, cachedReportText).ok) {
496
+ const outputsDir = path.join(outputDir, "outputs");
497
+ const restoredReport = JSON.parse(cachedReportText);
498
+ if (!reusablePositiveIdentityReport(restoredReport)) {
499
+ throw new Error("unsafe negative identity cache entry");
500
+ }
501
+ fs.mkdirSync(outputsDir, { recursive: true });
502
+ fs.cpSync(resultCacheEntryDir, outputsDir, { recursive: true });
503
+ resultRows.push({
504
+ ...baseRow,
505
+ status: "restored_from_bound_cache",
506
+ cli_exit_code: null,
507
+ report_status: restoredReport.status ?? null,
508
+ decision: restoredReport.decision ?? null,
509
+ result_cache_entry: repoRelativeMaybe(resultCacheEntryDir),
510
+ });
511
+ return;
512
+ }
513
+ }
514
+ catch {
515
+ // Invalid or racing cache entries are ignored and never become evidence.
516
+ }
517
+ }
518
+ }
519
+ if (onlyPending &&
520
+ reportFile &&
521
+ fileExists(reportFile) &&
522
+ fileExists(executionManifestFile)) {
523
+ try {
524
+ const existingReportText = fs.readFileSync(reportFile, "utf8");
525
+ const existingManifest = readJson(executionManifestFile);
526
+ if (validateBoundExecutionManifest(existingManifest, executionBinding, existingReportText)
527
+ .ok) {
528
+ const existingReport = JSON.parse(existingReportText);
529
+ if (!reusablePositiveIdentityReport(existingReport)) {
530
+ throw new Error("negative identity evidence must be searched again");
531
+ }
532
+ resultRows.push({
533
+ ...baseRow,
534
+ status: "skipped_bound_execution",
535
+ cli_exit_code: null,
536
+ report_status: existingReport.status ?? null,
537
+ decision: existingReport.decision ?? null,
538
+ });
539
+ return;
540
+ }
541
+ }
542
+ catch {
543
+ // Existing bytes without a valid exact binding must be executed again.
544
+ }
545
+ }
546
+ if (dryRun) {
547
+ resultRows.push({
548
+ ...baseRow,
549
+ status: "planned",
550
+ attempts: 0,
551
+ cli_exit_code: null,
552
+ report_status: null,
553
+ decision: null,
554
+ });
555
+ return;
556
+ }
557
+ const attemptRows = [];
558
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
559
+ const attemptSuffix = maxAttempts > 1 ? `.attempt-${attempt}` : "";
560
+ const attemptStdoutLog = maxAttempts > 1
561
+ ? path.join(logDir, `${logToken}${attemptSuffix}.stdout.json`)
562
+ : stdoutLog;
563
+ const attemptStderrLog = maxAttempts > 1 ? path.join(logDir, `${logToken}${attemptSuffix}.stderr.log`) : stderrLog;
564
+ const spawnArgs = [...cli.args, ...cliArgs];
565
+ const startedAtMs = Date.now();
566
+ const result = spawnSync(cli.command, spawnArgs, {
567
+ cwd: executionCwd ?? repoRoot,
568
+ env: executionEnvironment,
569
+ encoding: "utf8",
570
+ // Mega-scope flows return large preflight payloads on stdout; the 1MB
571
+ // spawnSync default overflows with ENOBUFS. Cap below V8's max string length.
572
+ maxBuffer: 512 * 1024 * 1024,
573
+ timeout: spawnTimeoutMs,
574
+ killSignal: "SIGTERM",
575
+ });
576
+ writeText(attemptStdoutLog, result.stdout || "");
577
+ writeText(attemptStderrLog, result.stderr || "");
578
+ const timedOut = (result.error && "code" in result.error && result.error.code === "ETIMEDOUT") ||
579
+ result.signal === "SIGTERM";
580
+ if (result.error && !timedOut)
581
+ throw result.error;
582
+ const cliExitCode = typeof result.status === "number" ? result.status : 1;
583
+ const stdoutReport = parseJsonMaybe(result.stdout);
584
+ const diskReportText = reportFile && fileExists(reportFile) ? fs.readFileSync(reportFile, "utf8") : null;
585
+ const diskReport = parseJsonMaybe(diskReportText);
586
+ const report = stdoutReport || diskReport;
587
+ const executionValidation = timedOut
588
+ ? null
589
+ : validateIdentityPreflightExecution({
590
+ binding: executionBinding,
591
+ exitCode: cliExitCode,
592
+ stdoutText: result.stdout || "",
593
+ diskReportText,
594
+ startedAtMs,
595
+ diskReportMtimeMs: reportFile && fileExists(reportFile) ? fs.statSync(reportFile).mtimeMs : null,
596
+ completedAtUtc: nowIso(),
597
+ });
598
+ if (executionValidation?.ok) {
599
+ writeJson(executionManifestFile, executionValidation.manifest);
600
+ }
601
+ const attemptRow = timedOut
602
+ ? {
603
+ ...baseRow,
604
+ attempt,
605
+ attempts: attempt,
606
+ stdout_log: repoRelativePath(attemptStdoutLog),
607
+ stderr_log: repoRelativePath(attemptStderrLog),
608
+ status: "failed",
609
+ failure_code: "identity_preflight_timeout",
610
+ cli_exit_code: null,
611
+ report_status: report?.status ?? null,
612
+ decision: report?.decision ?? null,
613
+ confidence: report?.confidence ?? null,
614
+ next_action: report?.next_action ?? null,
615
+ blocker_count: ensureArray(report?.blockers).length,
616
+ candidate_count: ensureArray(report?.candidates).length,
617
+ candidate_source_count: ensureArray(report?.candidate_sources).length,
618
+ signal: result.signal ?? null,
619
+ timeout_ms: timeoutMs,
620
+ spawn_timeout_ms: spawnTimeoutMs,
621
+ }
622
+ : {
623
+ ...baseRow,
624
+ attempt,
625
+ attempts: attempt,
626
+ stdout_log: repoRelativePath(attemptStdoutLog),
627
+ stderr_log: repoRelativePath(attemptStderrLog),
628
+ status: executionValidation?.ok ? "completed" : "failed",
629
+ failure_code: executionValidation?.ok
630
+ ? null
631
+ : executionValidation?.code || "identity_preflight_execution_invalid",
632
+ cli_exit_code: cliExitCode,
633
+ report_status: report?.status ?? null,
634
+ decision: report?.decision ?? null,
635
+ confidence: report?.confidence ?? null,
636
+ next_action: report?.next_action ?? null,
637
+ blocker_count: ensureArray(report?.blockers).length,
638
+ candidate_count: ensureArray(report?.candidates).length,
639
+ candidate_source_count: ensureArray(report?.candidate_sources).length,
640
+ };
641
+ attemptRows.push(attemptRow);
642
+ if (!retriableIdentityPreflightFailure(attemptRow))
643
+ break;
644
+ }
645
+ const finalAttempt = attemptRows.at(-1);
646
+ if (!finalAttempt) {
647
+ throw new Error("Identity-preflight execution produced no attempt evidence.");
648
+ }
649
+ // Persist only a fully validated result under its complete execution binding.
650
+ if (resultCacheEntryDir &&
651
+ finalAttempt?.status === "completed" &&
652
+ outputDir &&
653
+ reportFile &&
654
+ fileExists(reportFile) &&
655
+ fs.existsSync(path.join(outputDir, "outputs")) &&
656
+ fs.statSync(path.join(outputDir, "outputs")).isDirectory()) {
657
+ try {
658
+ const cacheableReport = JSON.parse(fs.readFileSync(reportFile, "utf8"));
659
+ if (!reusablePositiveIdentityReport(cacheableReport)) {
660
+ throw new Error("negative identity evidence is not cacheable");
661
+ }
662
+ fs.mkdirSync(path.dirname(resultCacheEntryDir), { recursive: true });
663
+ // Publish atomically: copy into a process-unique temp dir on the same
664
+ // filesystem, then rename into place. Parallel scope workers share this
665
+ // cache dir and reference the same flows (high cross-scope overlap), so a
666
+ // non-atomic rm+cp races — one worker's rmSync deletes a subtree another
667
+ // is mid-copy on, throwing EINVAL and aborting the whole stage. rename is
668
+ // atomic; if another worker already published this identity, keep theirs
669
+ // (same flow identity => equivalent result). Cache writes are best-effort
670
+ // and must never fail the import.
671
+ const tmpDir = `${resultCacheEntryDir}.tmp-${process.pid}-${selectedIndex}`;
672
+ fs.rmSync(tmpDir, { recursive: true, force: true });
673
+ fs.cpSync(path.join(outputDir, "outputs"), tmpDir, { recursive: true });
674
+ if (fs.existsSync(resultCacheEntryDir)) {
675
+ fs.rmSync(tmpDir, { recursive: true, force: true });
676
+ }
677
+ else {
678
+ try {
679
+ fs.renameSync(tmpDir, resultCacheEntryDir);
680
+ }
681
+ catch {
682
+ fs.rmSync(tmpDir, { recursive: true, force: true });
683
+ }
684
+ }
685
+ }
686
+ catch {
687
+ // Cache persistence is best-effort; never fail the import because of it.
688
+ }
689
+ }
690
+ resultRows.push({
691
+ ...finalAttempt,
692
+ retry_attempts: attemptRows.map((attemptRow) => ({
693
+ attempt: attemptRow.attempt,
694
+ status: attemptRow.status,
695
+ failure_code: attemptRow.failure_code ?? null,
696
+ cli_exit_code: attemptRow.cli_exit_code,
697
+ stdout_log: attemptRow.stdout_log,
698
+ stderr_log: attemptRow.stderr_log,
699
+ })),
700
+ });
701
+ });
702
+ const failedRows = resultRows.filter((row) => row.status === "failed");
703
+ const identityFindingRows = resultRows.filter((row) => ["blocked", "needs_review"].includes(row.report_status ?? ""));
704
+ const blockers = failedRows.map((row) => ({
705
+ code: row.failure_code || "identity_preflight_run_failed",
706
+ message: "Identity-preflight runner could not produce usable evidence for a selected row.",
707
+ dataset_type: row.dataset_type || null,
708
+ dataset_id: row.dataset_id || null,
709
+ dataset_version: row.dataset_version || null,
710
+ request_file: row.request_file || null,
711
+ report_file: row.report_file || null,
712
+ stdout_log: row.stdout_log || null,
713
+ stderr_log: row.stderr_log || null,
714
+ }));
715
+ const status = dryRun
716
+ ? "planned"
717
+ : failedRows.length > 0
718
+ ? "failed"
719
+ : identityFindingRows.length > 0
720
+ ? "completed_with_identity_findings"
721
+ : "completed";
722
+ const resultsPath = path.join(outDir, "identity-preflight-run-results.jsonl");
723
+ const reportPath = path.join(outDir, "dataset-identity-preflight-run-report.json");
724
+ writeJsonLines(resultsPath, resultRows);
725
+ const report = {
726
+ schema_version: 1,
727
+ generated_at_utc: nowIso(),
728
+ status,
729
+ command: "dataset-identity-preflight-run",
730
+ index_file: repoRelativePath(indexPath),
731
+ ...identityPreflightRunStageContract,
732
+ runtime_options: {
733
+ timeout_ms: timeoutMs,
734
+ spawn_timeout_ms: spawnTimeoutMs,
735
+ max_attempts: maxAttempts,
736
+ result_cache_dir: repoRelativeMaybe(resultCacheDir),
737
+ retry_failed: retryFailedPath && fileExists(retryFailedPath) ? repoRelativePath(retryFailedPath) : null,
738
+ cli: {
739
+ command: cli.display,
740
+ executable: cli.command,
741
+ args_prefix: cli.args,
742
+ package: cli.package,
743
+ source: cli.source,
744
+ },
745
+ auth_receipt: authReceipt
746
+ ? {
747
+ file: repoRelativeMaybe(authReceiptPath),
748
+ project_ref: authReceipt.project.project_ref,
749
+ user_id: authReceipt.identity.user_id,
750
+ receipt_scope_sha256: authReceipt.receipt_scope_sha256,
751
+ }
752
+ : null,
753
+ },
754
+ counts: {
755
+ index_rows: rows.length,
756
+ initially_selected_rows: initiallySelectedRows.length,
757
+ retry_failed_input_rows: retryFailedKeys ? retryFailedKeys.size : 0,
758
+ selected_rows: selectedRows.length,
759
+ attempts: resultRows.reduce((total, row) => total + Number(row.attempts ?? 0), 0),
760
+ planned: resultRows.filter((row) => row.status === "planned").length,
761
+ completed: resultRows.filter((row) => row.status === "completed").length,
762
+ restored_from_bound_cache: resultRows.filter((row) => row.status === "restored_from_bound_cache").length,
763
+ skipped_bound_execution: resultRows.filter((row) => row.status === "skipped_bound_execution").length,
764
+ skipped_existing_report: resultRows.filter((row) => row.status === "skipped_existing_report").length,
765
+ failed: failedRows.length,
766
+ identity_blocked: resultRows.filter((row) => row.report_status === "blocked").length,
767
+ identity_needs_review: resultRows.filter((row) => row.report_status === "needs_review")
768
+ .length,
769
+ cli_exit_nonzero: resultRows.filter((row) => Number.isInteger(row.cli_exit_code) && row.cli_exit_code !== 0).length,
770
+ blockers: blockers.length,
771
+ },
772
+ policy: {
773
+ fail_closed_execution: "Every nonzero CLI exit, missing/malformed stdout or disk report, stale disk report, stdout/disk mismatch, ok:false, failed/error status, or execution-binding drift fails the selected row and batch.",
774
+ valid_identity_findings: "A blocked/needs_review report remains diagnostic evidence only when the CLI exits zero and stdout/disk bytes are bound by a valid execution manifest.",
775
+ curation_gate_usage: "Pass this same index to dataset-curation-gate with --identity-preflight-index so authoring packages include current and dependency identity-preflight context.",
776
+ },
777
+ files: {
778
+ report: repoRelativePath(reportPath),
779
+ results: repoRelativePath(resultsPath),
780
+ },
781
+ blockers,
782
+ results: resultRows,
783
+ };
784
+ writeJson(reportPath, report);
785
+ return report;
786
+ }
787
+ function identityPreflightIndexMergeKey(row) {
788
+ const datasetType = asText(row?.dataset_type || row?.type);
789
+ const datasetId = asText(row?.dataset_id || row?.entity_id || row?.id);
790
+ const datasetVersion = asText(row?.dataset_version || row?.version) || "00.00.001";
791
+ if (!datasetType || !datasetId || !datasetVersion)
792
+ return null;
793
+ return `${datasetType}::${datasetId}::${datasetVersion}`;
794
+ }
795
+ function runDatasetIdentityPreflightIndexMerge(options) {
796
+ if (options.help) {
797
+ return {
798
+ schema_version: 1,
799
+ status: "help",
800
+ command: "dataset-identity-preflight-index-merge",
801
+ purpose: "Merge refreshed current-scope identity-preflight request rows into an existing index while preserving dependency preflight evidence. This command is local-only and never writes the database.",
802
+ usage: [
803
+ "node scripts/foundry.ts dataset-identity-preflight-index-merge --base-index <old identity-preflight-requests.jsonl> --update-index <fresh current identity-preflight-requests.jsonl> --out-dir <merge-dir>",
804
+ "node scripts/foundry.ts dataset-identity-preflight-index-merge --base-index ./identity-preflight-requests.jsonl --update-index ./fresh/identity-preflight-requests.jsonl",
805
+ ],
806
+ remote_write_mode: "read-only",
807
+ };
808
+ }
809
+ const baseIndex = resolveRepoPath(options.baseIndex || options.base || options.index);
810
+ if (!baseIndex || !fileExists(baseIndex)) {
811
+ throw new Error("--base-index is required and must point to identity-preflight-requests.jsonl.");
812
+ }
813
+ const updateIndexes = normalizedList(options.updateIndex ||
814
+ options.updateIndexes ||
815
+ options.refreshIndex ||
816
+ options.refreshIndexes).map((file) => resolveRepoPath(file));
817
+ if (updateIndexes.length === 0 || updateIndexes.some((file) => !fileExists(file))) {
818
+ throw new Error("--update-index is required and every update index must be readable.");
819
+ }
820
+ const outDir = resolveRepoPath(options.outDir ||
821
+ path.join(path.dirname(path.dirname(baseIndex)), "identity-preflight-index-merge"));
822
+ const outPath = resolveRepoPath(options.out || options.output || path.join(outDir, "identity-preflight-requests.jsonl"));
823
+ const reportPath = path.join(outDir, "dataset-identity-preflight-index-merge-report.json");
824
+ const blockers = [];
825
+ const mergedRows = [];
826
+ const rowIndexByKey = new Map();
827
+ const stats = {
828
+ base_rows: 0,
829
+ update_indexes: updateIndexes.length,
830
+ update_rows: 0,
831
+ replaced_rows: 0,
832
+ added_rows: 0,
833
+ duplicate_update_rows: 0,
834
+ };
835
+ const addRow = (row, sourceFile, sourceIndex, mode) => {
836
+ const key = identityPreflightIndexMergeKey(row);
837
+ if (!key) {
838
+ blockers.push({
839
+ code: "identity_preflight_index_row_key_missing",
840
+ message: "Identity preflight index rows must include dataset_type, dataset_id, and dataset_version.",
841
+ source_file: repoRelativeMaybe(sourceFile),
842
+ source_index: sourceIndex,
843
+ mode,
844
+ });
845
+ return;
846
+ }
847
+ const nextRow = {
848
+ ...row,
849
+ merge_source: mode,
850
+ merge_source_file: repoRelativeMaybe(sourceFile),
851
+ };
852
+ if (!rowIndexByKey.has(key)) {
853
+ rowIndexByKey.set(key, mergedRows.length);
854
+ mergedRows.push(nextRow);
855
+ if (mode === "update")
856
+ stats.added_rows += 1;
857
+ return;
858
+ }
859
+ const existingIndex = rowIndexByKey.get(key);
860
+ if (mode === "base") {
861
+ blockers.push({
862
+ code: "identity_preflight_index_base_duplicate_key",
863
+ message: "Base identity preflight index contains duplicate dataset identity rows.",
864
+ key,
865
+ source_file: repoRelativeMaybe(sourceFile),
866
+ source_index: sourceIndex,
867
+ });
868
+ return;
869
+ }
870
+ if (mergedRows[existingIndex]?.merge_source === "update") {
871
+ stats.duplicate_update_rows += 1;
872
+ }
873
+ else {
874
+ stats.replaced_rows += 1;
875
+ }
876
+ mergedRows[existingIndex] = nextRow;
877
+ };
878
+ const baseRows = readJsonLines(baseIndex);
879
+ stats.base_rows = baseRows.length;
880
+ baseRows.forEach((row, index) => addRow(row, baseIndex, index, "base"));
881
+ for (const updateIndex of updateIndexes) {
882
+ const updateRows = readJsonLines(updateIndex);
883
+ stats.update_rows += updateRows.length;
884
+ updateRows.forEach((row, index) => addRow(row, updateIndex, index, "update"));
885
+ }
886
+ if (blockers.length === 0)
887
+ writeJsonLines(outPath, mergedRows);
888
+ const report = {
889
+ schema_version: 1,
890
+ generated_at_utc: nowIso(),
891
+ status: blockers.length === 0 ? "ready" : "blocked",
892
+ command: "dataset-identity-preflight-index-merge",
893
+ remote_write_mode: "read-only",
894
+ policy: {
895
+ exact_rows_scope: "Updated rows replace base rows by dataset_type + dataset_id + dataset_version, preserving dependency preflight rows that were not refreshed.",
896
+ post_patch_usage: "Use this after field patch apply plus current-scope identity-preflight refresh, then pass the merged index to dataset-curation-gate.",
897
+ },
898
+ inputs: {
899
+ base_index: repoRelativePath(baseIndex),
900
+ update_indexes: updateIndexes.map(repoRelativePath),
901
+ },
902
+ counts: {
903
+ ...stats,
904
+ output_rows: blockers.length === 0 ? mergedRows.length : 0,
905
+ blockers: blockers.length,
906
+ },
907
+ files: {
908
+ report: repoRelativePath(reportPath),
909
+ merged_index: blockers.length === 0 ? repoRelativePath(outPath) : null,
910
+ },
911
+ blockers,
912
+ };
913
+ writeJson(reportPath, report);
914
+ return report;
915
+ }
916
+ function runDatasetIdentityPreflightRequestsBuild(options) {
917
+ if (options.help) {
918
+ return {
919
+ schema_version: 1,
920
+ status: "help",
921
+ command: "dataset-identity-preflight-requests-build",
922
+ usage: [
923
+ "node scripts/foundry.ts dataset-identity-preflight-requests-build --type process --rows-file ./rows/processes.jsonl --out-dir ./.foundry/workspaces/task/identity-preflight-refresh",
924
+ "node scripts/foundry.ts dataset-identity-preflight-requests-build --type flow --rows-file ./rows/flows.jsonl --out-dir ./.foundry/workspaces/task/identity-preflight-refresh",
925
+ "node scripts/foundry.ts dataset-identity-preflight-requests-build --type process --rows-file ./rows/patched-processes.jsonl --source-index ./identity-preflight-requests/identity-preflight-requests.jsonl --out-dir ./identity-preflight-refresh",
926
+ ],
927
+ purpose: "Build a fresh CLI identity-preflight request index from the exact current process or flow rows file.",
928
+ remote_write_mode: "read-only",
929
+ };
930
+ }
931
+ const datasetType = asText(options.type || options.datasetType).toLowerCase();
932
+ if (!["flow", "process"].includes(datasetType)) {
933
+ throw new Error("--type must be flow or process.");
934
+ }
935
+ const rowsFile = resolveRepoPath(options.rowsFile || options.input || options.inputRows);
936
+ if (!rowsFile || !fileExists(rowsFile)) {
937
+ throw new Error("--rows-file must point to a readable process/flow rows file.");
938
+ }
939
+ const outDir = resolveRepoPath(options.outDir ||
940
+ path.join(path.dirname(path.dirname(rowsFile)), "identity-preflight-refresh"));
941
+ const cliBin = resolveTiangongLcaCliCommandPrefix
942
+ ? resolveTiangongLcaCliCommandPrefix()
943
+ : [resolveTiangongLcaCliBin()];
944
+ const rows = readRowsFile(rowsFile);
945
+ const sourceIndexPaths = identityPreflightSourceIndexPaths(options);
946
+ const sourceContext = loadIdentityPreflightSourceFileMap(sourceIndexPaths);
947
+ const rowsByType = {
948
+ flow: new Map(),
949
+ process: new Map(),
950
+ };
951
+ const sourceByType = {
952
+ flow: new Map(),
953
+ process: new Map(),
954
+ };
955
+ const blockers = [];
956
+ blockers.push(...sourceContext.blockers);
957
+ let sourceContextMatches = 0;
958
+ let sourceContextMissingMatches = 0;
959
+ rows.forEach((row, index) => {
960
+ const identity = datasetIdentity(row, datasetType);
961
+ if (!identity.id || !identity.version) {
962
+ blockers.push({
963
+ code: "identity_preflight_request_identity_missing",
964
+ row_index: index,
965
+ dataset_type: datasetType,
966
+ message: "Rows used to build identity-preflight requests must include common:UUID and common:dataSetVersion.",
967
+ });
968
+ return;
969
+ }
970
+ const key = `${identity.id}::${identity.version}`;
971
+ const sourceIndexKey = `${datasetType}:${identity.id}:${identity.version}`;
972
+ const inheritedSourceFile = sourceContext.sourceFilesByIdentity.get(sourceIndexKey) ?? null;
973
+ if (sourceIndexPaths.length > 0) {
974
+ if (inheritedSourceFile) {
975
+ sourceByType[datasetType].set(key, inheritedSourceFile);
976
+ sourceContextMatches += 1;
977
+ }
978
+ else {
979
+ sourceContextMissingMatches += 1;
980
+ blockers.push({
981
+ code: "identity_preflight_source_context_match_missing",
982
+ row_index: index,
983
+ dataset_type: datasetType,
984
+ dataset_id: identity.id,
985
+ dataset_version: identity.version,
986
+ message: "The supplied --source-index does not contain source_file context for this current row.",
987
+ });
988
+ }
989
+ }
990
+ const existing = rowsByType[datasetType].get(key);
991
+ if (existing && jsonSha256(existing) !== jsonSha256(row)) {
992
+ blockers.push({
993
+ code: "identity_preflight_request_duplicate_payload_conflict",
994
+ row_index: index,
995
+ dataset_type: datasetType,
996
+ dataset_id: identity.id,
997
+ dataset_version: identity.version,
998
+ message: "The rows file contains duplicate identity keys with different payloads.",
999
+ });
1000
+ return;
1001
+ }
1002
+ rowsByType[datasetType].set(key, row);
1003
+ });
1004
+ const artifacts = buildIdentityPreflightArtifacts({
1005
+ rowsByType,
1006
+ sourceByType,
1007
+ outDir,
1008
+ cliBin,
1009
+ });
1010
+ const reportPath = path.join(outDir, "dataset-identity-preflight-requests-build-report.json");
1011
+ const report = {
1012
+ schema_version: 1,
1013
+ generated_at_utc: nowIso(),
1014
+ status: blockers.length > 0 ? "blocked" : "ready",
1015
+ command: "dataset-identity-preflight-requests-build",
1016
+ dataset_type: datasetType,
1017
+ rows_file: repoRelativePath(rowsFile),
1018
+ remote_write_mode: "read-only",
1019
+ policy: {
1020
+ exact_rows_scope: "Each request target is the exact row payload from rows_file, and each index row records target_sha256 so curation can reject stale preflight evidence.",
1021
+ edge_search_payload: "The generated request carries a compact fielded query plus supported filter/data_source/match parameters for flow_hybrid_search or process_hybrid_search.",
1022
+ source_context_refresh: "When --source-index is supplied, refreshed requests inherit the original source_file trace context for the same dataset identity so post-patch search queries do not lose source-package evidence.",
1023
+ },
1024
+ counts: {
1025
+ input_rows: rows.length,
1026
+ request_rows: artifacts.rows.length,
1027
+ source_index_files: sourceIndexPaths.length,
1028
+ source_index_rows: sourceContext.rowCount,
1029
+ source_context_matches: sourceContextMatches,
1030
+ source_context_missing_matches: sourceContextMissingMatches,
1031
+ blockers: blockers.length,
1032
+ },
1033
+ files: {
1034
+ report: repoRelativePath(reportPath),
1035
+ identity_preflight_requests: repoRelativePath(artifacts.indexPath),
1036
+ requests_root: repoRelativePath(artifacts.root),
1037
+ source_indexes: sourceIndexPaths.map(repoRelativePath),
1038
+ },
1039
+ blockers,
1040
+ };
1041
+ writeJson(reportPath, report);
1042
+ return report;
1043
+ }
1044
+ const identityPreflightQueryNoisePatterns = [
1045
+ {
1046
+ code: "not_specified_source_phrase",
1047
+ pattern: /\bNot specified by the .* source\.?\b/iu,
1048
+ },
1049
+ {
1050
+ code: "ilcd_format_noise",
1051
+ pattern: /\bILCD format\b/iu,
1052
+ },
1053
+ {
1054
+ code: "generic_not_specified",
1055
+ pattern: /(?:^|[:;\n]\s*)Not specified(?:[.;\n]|$)/iu,
1056
+ },
1057
+ {
1058
+ code: "ecospold_location_in_name",
1059
+ pattern: /\{[A-Z][A-Z0-9_-]{1,12}\}/u,
1060
+ },
1061
+ {
1062
+ code: "leading_xx_name_placeholder",
1063
+ pattern: /(?:^|\n)(?:process|flow) name:\s*x{2,}\b/iu,
1064
+ },
1065
+ ];
1066
+ function identityPreflightQueryForAudit(row) {
1067
+ return (asText(row?.remote_search?.edge_request?.body?.query) ||
1068
+ asText(row?.remote_search?.query) ||
1069
+ asText(row?.remote_candidate_search?.query) ||
1070
+ asText(row?.request?.remote_candidate_search?.query));
1071
+ }
1072
+ function identityPreflightEdgeBodyForAudit(row) {
1073
+ const body = row?.remote_search?.edge_request?.body;
1074
+ if (body && typeof body === "object" && !Array.isArray(body))
1075
+ return body;
1076
+ const request = row?.remote_candidate_search ?? row?.request?.remote_candidate_search;
1077
+ if (request && typeof request === "object" && !Array.isArray(request)) {
1078
+ return {
1079
+ query: request.query,
1080
+ ...(request.filter ? { filter: request.filter } : {}),
1081
+ ...(request.limit ? { match_count: request.limit, page_size: request.limit } : {}),
1082
+ ...(request.data_source ? { data_source: request.data_source } : {}),
1083
+ ...(request.match_threshold ? { match_threshold: request.match_threshold } : {}),
1084
+ ...(request.lexical_weight ? { lexical_weight: request.lexical_weight } : {}),
1085
+ ...(request.semantic_weight ? { semantic_weight: request.semantic_weight } : {}),
1086
+ ...(request.rrf_k ? { rrf_k: request.rrf_k } : {}),
1087
+ };
1088
+ }
1089
+ return {};
1090
+ }
1091
+ function identityPreflightRequestForAudit(indexPath, row) {
1092
+ const requestFile = resolveRepoPath(row?.request_file);
1093
+ if (!requestFile || !fileExists(requestFile))
1094
+ return null;
1095
+ try {
1096
+ return readJson(requestFile);
1097
+ }
1098
+ catch (error) {
1099
+ throw new Error(`Could not read identity-preflight request file from ${repoRelativePath(indexPath)}: ${repoRelativePath(requestFile)}: ${error}`);
1100
+ }
1101
+ }
1102
+ function hasQueryLabel(query, label) {
1103
+ return new RegExp(`(?:^|\\n)${label.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}:`, "iu").test(query);
1104
+ }
1105
+ function flowTypeFromQuery(query) {
1106
+ const match = query.match(/(?:^|\n)flow type:\s*([^\n;]+)/iu);
1107
+ return asText(match?.[1]);
1108
+ }
1109
+ function identityPreflightRequiredQueryLabels(row, query) {
1110
+ const datasetType = asText(row?.dataset_type ?? row?.datasetType).toLowerCase();
1111
+ if (datasetType === "process") {
1112
+ return [
1113
+ "process name",
1114
+ "reference flow",
1115
+ "geography",
1116
+ "classification or sector",
1117
+ "exchange flow refs",
1118
+ ];
1119
+ }
1120
+ if (datasetType === "flow") {
1121
+ const labels = ["flow name", "flow type", "reference property", "category or compartment"];
1122
+ if (/^elementary flow$/iu.test(flowTypeFromQuery(query))) {
1123
+ labels.push("compartment aliases");
1124
+ if (row?.source_file)
1125
+ labels.push("source classification or compartment");
1126
+ }
1127
+ else {
1128
+ labels.push("geography or market");
1129
+ }
1130
+ return labels;
1131
+ }
1132
+ return ["query"];
1133
+ }
1134
+ function identityPreflightSearchEndpointForType(datasetType) {
1135
+ if (datasetType === "process")
1136
+ return "process_hybrid_search";
1137
+ if (datasetType === "flow")
1138
+ return "flow_hybrid_search";
1139
+ return null;
1140
+ }
1141
+ function auditIdentityPreflightQueryRow({ row, index, indexPath, }) {
1142
+ const blockers = [];
1143
+ const warnings = [];
1144
+ const datasetType = asText(row?.dataset_type ?? row?.datasetType).toLowerCase();
1145
+ const datasetId = asText(row?.dataset_id ?? row?.datasetId ?? row?.id);
1146
+ const datasetVersion = asText(row?.dataset_version ?? row?.datasetVersion ?? row?.version);
1147
+ const request = identityPreflightRequestForAudit(indexPath, row);
1148
+ const requestEnvelope = request;
1149
+ const mergedRow = requestEnvelope
1150
+ ? {
1151
+ ...row,
1152
+ request: requestEnvelope,
1153
+ remote_candidate_search: row?.remote_candidate_search ?? requestEnvelope.remote_candidate_search,
1154
+ }
1155
+ : row;
1156
+ const query = identityPreflightQueryForAudit(mergedRow);
1157
+ const edgeBody = identityPreflightEdgeBodyForAudit(mergedRow);
1158
+ const expectedEndpoint = identityPreflightSearchEndpointForType(datasetType);
1159
+ const actualEndpoint = asText(row?.remote_search?.edge_request?.endpoint);
1160
+ const base = {
1161
+ row_index: index,
1162
+ dataset_type: datasetType || null,
1163
+ dataset_id: datasetId || null,
1164
+ dataset_version: datasetVersion || null,
1165
+ request_file: row?.request_file ?? null,
1166
+ };
1167
+ if (!["flow", "process"].includes(datasetType)) {
1168
+ blockers.push({
1169
+ ...base,
1170
+ code: "identity_preflight_query_dataset_type_invalid",
1171
+ message: "Identity-preflight query audit only supports process and flow rows.",
1172
+ });
1173
+ }
1174
+ if (!query) {
1175
+ blockers.push({
1176
+ ...base,
1177
+ code: "identity_preflight_query_missing",
1178
+ message: "Identity-preflight row must send a non-empty query to hybrid search.",
1179
+ });
1180
+ }
1181
+ if (query.length > 1800) {
1182
+ blockers.push({
1183
+ ...base,
1184
+ code: "identity_preflight_query_too_long",
1185
+ query_length: query.length,
1186
+ message: "Hybrid search query must stay within the Foundry compact query limit.",
1187
+ });
1188
+ }
1189
+ if (expectedEndpoint && actualEndpoint && actualEndpoint !== expectedEndpoint) {
1190
+ blockers.push({
1191
+ ...base,
1192
+ code: "identity_preflight_query_endpoint_mismatch",
1193
+ expected_endpoint: expectedEndpoint,
1194
+ actual_endpoint: actualEndpoint,
1195
+ message: "Identity-preflight edge request endpoint does not match the dataset type.",
1196
+ });
1197
+ }
1198
+ for (const label of identityPreflightRequiredQueryLabels(row, query)) {
1199
+ if (label === "query")
1200
+ continue;
1201
+ if (!hasQueryLabel(query, label)) {
1202
+ blockers.push({
1203
+ ...base,
1204
+ code: "identity_preflight_query_required_label_missing",
1205
+ label,
1206
+ message: `Hybrid search query is missing required fielded label: ${label}.`,
1207
+ });
1208
+ }
1209
+ }
1210
+ for (const { code, pattern } of identityPreflightQueryNoisePatterns) {
1211
+ const match = query.match(pattern);
1212
+ if (match) {
1213
+ blockers.push({
1214
+ ...base,
1215
+ code: "identity_preflight_query_noise",
1216
+ noise_code: code,
1217
+ matched_text: match[0],
1218
+ message: "Hybrid search query contains placeholder or converted-format noise that should be repaired before remote candidate search.",
1219
+ });
1220
+ }
1221
+ }
1222
+ const edgeQuery = asText(edgeBody.query);
1223
+ if (query && edgeQuery && edgeQuery !== query) {
1224
+ blockers.push({
1225
+ ...base,
1226
+ code: "identity_preflight_query_edge_body_mismatch",
1227
+ message: "Index remote_search.query and edge_request.body.query differ; audit cannot prove what Edge receives.",
1228
+ });
1229
+ }
1230
+ if (datasetType === "flow") {
1231
+ const flowType = flowTypeFromQuery(query);
1232
+ const filterFlowType = asText(edgeBody?.filter?.flowType);
1233
+ if (flowType && !filterFlowType) {
1234
+ blockers.push({
1235
+ ...base,
1236
+ code: "identity_preflight_query_flow_type_filter_missing",
1237
+ flow_type: flowType,
1238
+ message: "Flow hybrid search should include a flowType filter matching the query flow type.",
1239
+ });
1240
+ }
1241
+ else if (flowType && filterFlowType && filterFlowType !== flowType) {
1242
+ blockers.push({
1243
+ ...base,
1244
+ code: "identity_preflight_query_flow_type_filter_mismatch",
1245
+ flow_type: flowType,
1246
+ filter_flow_type: filterFlowType,
1247
+ message: "Flow hybrid search flowType filter does not match the query flow type.",
1248
+ });
1249
+ }
1250
+ }
1251
+ if (!edgeBody.data_source) {
1252
+ warnings.push({
1253
+ ...base,
1254
+ code: "identity_preflight_query_data_source_missing",
1255
+ message: "Hybrid search data_source is not explicit; Edge will use its default.",
1256
+ });
1257
+ }
1258
+ if (!edgeBody.match_count || !edgeBody.page_size) {
1259
+ warnings.push({
1260
+ ...base,
1261
+ code: "identity_preflight_query_result_limit_missing",
1262
+ message: "Hybrid search match_count/page_size is not explicit; Edge will use its default.",
1263
+ });
1264
+ }
1265
+ return {
1266
+ ...base,
1267
+ status: blockers.length > 0 ? "blocked" : "passed",
1268
+ query_sha256: query ? sha256Text(query) : null,
1269
+ query_length: query.length,
1270
+ labels: query
1271
+ .split(/\n/u)
1272
+ .map((line) => line.match(/^([^:]+):/u)?.[1])
1273
+ .filter(Boolean),
1274
+ edge_request: {
1275
+ endpoint: actualEndpoint || expectedEndpoint,
1276
+ data_source: edgeBody.data_source ?? null,
1277
+ match_count: edgeBody.match_count ?? null,
1278
+ page_size: edgeBody.page_size ?? null,
1279
+ filter: edgeBody.filter ?? null,
1280
+ },
1281
+ blockers,
1282
+ warnings,
1283
+ };
1284
+ }
1285
+ function runDatasetIdentityPreflightQueryAudit(options) {
1286
+ if (options.help) {
1287
+ return {
1288
+ schema_version: 1,
1289
+ status: "help",
1290
+ command: "dataset-identity-preflight-query-audit",
1291
+ usage: [
1292
+ "node scripts/foundry.ts dataset-identity-preflight-query-audit --index ./identity-preflight-requests/identity-preflight-requests.jsonl --out-dir ./identity-preflight-query-audit",
1293
+ ],
1294
+ purpose: "Audit generated process/flow identity-preflight hybrid-search queries before remote candidate search.",
1295
+ remote_write_mode: "read-only",
1296
+ };
1297
+ }
1298
+ const indexPath = resolveRepoPath(options.index ||
1299
+ options.identityPreflightIndex ||
1300
+ options.identityPreflightRequests ||
1301
+ options.identityPreflightRequestsIndex);
1302
+ if (!indexPath || !fileExists(indexPath)) {
1303
+ throw new Error("--index must point to a readable identity-preflight index.");
1304
+ }
1305
+ const outDir = resolveRepoPath(options.outDir ||
1306
+ path.join(path.dirname(path.dirname(indexPath)), "identity-preflight-query-audit"));
1307
+ const rows = readJsonLines(indexPath);
1308
+ const auditedRows = rows.map((row, index) => auditIdentityPreflightQueryRow({ row, index, indexPath }));
1309
+ const blockers = auditedRows.flatMap((row) => row.blockers);
1310
+ const warnings = auditedRows.flatMap((row) => row.warnings);
1311
+ const reportPath = path.join(outDir, "dataset-identity-preflight-query-audit-report.json");
1312
+ const rowsPath = path.join(outDir, "identity-preflight-query-audit.jsonl");
1313
+ writeJsonLines(rowsPath, auditedRows);
1314
+ const report = {
1315
+ schema_version: 1,
1316
+ generated_at_utc: nowIso(),
1317
+ status: blockers.length > 0 ? "blocked" : "passed",
1318
+ command: "dataset-identity-preflight-query-audit",
1319
+ index_file: repoRelativePath(indexPath),
1320
+ remote_write_mode: "read-only",
1321
+ policy: {
1322
+ edge_body_contract: "flow_hybrid_search/process_hybrid_search only parse query, filter/filter_condition, match options, and data_source; complete identity and source evidence must be present in query.",
1323
+ profile_hints_contract: "remote_candidate_search.profile_hints are retained for local CLI/AI identity decisions but are not sent in the Edge request body.",
1324
+ noise_policy: "Queries must not carry converted placeholder/source-format strings such as ILCD format, Not specified by the source, EcoSpold-style {GLO} name suffixes, or leading xx placeholders.",
1325
+ },
1326
+ counts: {
1327
+ rows: rows.length,
1328
+ passed_rows: auditedRows.filter((row) => row.status === "passed").length,
1329
+ blocked_rows: auditedRows.filter((row) => row.status === "blocked").length,
1330
+ process_rows: rows.filter((row) => asText(row?.dataset_type ?? row?.datasetType).toLowerCase() === "process").length,
1331
+ flow_rows: rows.filter((row) => asText(row?.dataset_type ?? row?.datasetType).toLowerCase() === "flow").length,
1332
+ blockers: blockers.length,
1333
+ warnings: warnings.length,
1334
+ },
1335
+ files: {
1336
+ report: repoRelativePath(reportPath),
1337
+ rows: repoRelativePath(rowsPath),
1338
+ },
1339
+ blockers,
1340
+ warnings,
1341
+ };
1342
+ writeJson(reportPath, report);
1343
+ return report;
1344
+ }
1345
+ return {
1346
+ identityPreflightRunIndexPath,
1347
+ identityPreflightRunReportFile,
1348
+ runDatasetIdentityPreflightIndexMerge,
1349
+ runDatasetIdentityPreflightQueryAudit,
1350
+ runDatasetIdentityPreflightRequestsBuild,
1351
+ runDatasetIdentityPreflightRun,
1352
+ };
1353
+ }