@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,1317 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { assertFoundryCacheRootSeparated } from "./lib/foundry-runtime-cache.js";
5
+ import { createFoundryRuntime } from "./foundry-runtime.js";
6
+ import { captureFoundryInput, assertFoundryRuntimeHost, assertFoundryWorkspaceWrite, createFoundryRuntimeContext, FoundryContextError, initializeFoundryWorkspace, pendingFoundryMigration, } from "./lib/foundry-runtime-context.js";
7
+ import { commandNextActionBindingSha256, createFoundryOperationResult, } from "./lib/foundry-operation-result.js";
8
+ import { loadFoundryFacadeTaskRecord, registerFoundryFacadeTask, } from "./lib/foundry-facade-store.js";
9
+ import { parseFoundryTaskStartSpec, } from "./lib/foundry-task-start-spec.js";
10
+ import { qualifyFoundryRuntime, } from "./lib/foundry-runtime-qualification.js";
11
+ import { sha256Json } from "./lib/identity-preflight-proof.js";
12
+ import { inventoryFoundryWorkspace } from "./lib/foundry-migration-inventory.js";
13
+ import { planFoundryWorkspaceMigration, revalidateFoundryMigrationPlan, } from "./lib/foundry-migration-plan.js";
14
+ import { stageFoundryMigration, auditFoundryMigration } from "./lib/foundry-migration-transfer.js";
15
+ import { planFoundryMigrationAdoption, } from "./lib/foundry-migration-adoption-plan.js";
16
+ import { applyFoundryMigrationAdoption } from "./lib/foundry-migration-adoption.js";
17
+ import { readFoundryMigrationAuthority } from "./lib/foundry-migration-authority.js";
18
+ import { selectFoundryWorkspaceRuntime, } from "./lib/foundry-runtime-selection.js";
19
+ import { datasetTypePlural } from "./lib/import-curation/internal/dataset-types.js";
20
+ import { currentWorkflowState, workflowObject } from "./lib/foundry-workflow-state.js";
21
+ import { completedOwnerScopes, prepareFoundryOwnerExecution, } from "./lib/foundry-owner-execution-store.js";
22
+ import { executeFoundryOwnerScope } from "./lib/foundry-workflow-execution.js";
23
+ import { inspectFoundryReferences, verifyFoundryReferences, } from "./lib/foundry-workflow-reference-verify.js";
24
+ import { selectFoundrySemanticInput } from "./lib/foundry-semantic-input.js";
25
+ import { runFoundryWorkflowIdentity } from "./lib/foundry-workflow-identity.js";
26
+ import { finalizeFoundryWorkflow } from "./lib/foundry-workflow-finalize.js";
27
+ import { selectFoundryAuthorizationInput } from "./lib/foundry-authorization-input.js";
28
+ import { authorizeFoundryWorkflow } from "./lib/foundry-workflow-authorization.js";
29
+ import { continueFoundryPreparedApproval } from "./lib/foundry-workflow-approval-continuation.js";
30
+ const maxSpecBytes = 1024 * 1024;
31
+ const maxSeedBytes = 8 * 1024 * 1024;
32
+ function readCaptured(fact, maxBytes, code) {
33
+ if (fact.bytes > maxBytes)
34
+ throw new FoundryContextError(code, "Selected facade input exceeds its byte limit.");
35
+ const fd = fs.openSync(fact.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
36
+ try {
37
+ const opened = fs.fstatSync(fd);
38
+ const bytes = fs.readFileSync(fd);
39
+ if (!opened.isFile() ||
40
+ opened.size !== fact.bytes ||
41
+ bytes.length !== fact.bytes ||
42
+ createHash("sha256").update(bytes).digest("hex") !== fact.sha256)
43
+ throw new FoundryContextError(code, "Selected facade input changed while it was read.");
44
+ return bytes;
45
+ }
46
+ finally {
47
+ fs.closeSync(fd);
48
+ }
49
+ }
50
+ function fileArtifact(role, file) {
51
+ const fact = captureFoundryInput(file);
52
+ return Object.freeze({ kind: "file", role, ...fact });
53
+ }
54
+ function inlineArtifact(role, value) {
55
+ const bytes = Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
56
+ return Object.freeze({
57
+ kind: "inline",
58
+ role,
59
+ bytes: bytes.length,
60
+ sha256: createHash("sha256").update(bytes).digest("hex"),
61
+ value,
62
+ });
63
+ }
64
+ function human(code, instructions) {
65
+ return Object.freeze({ kind: "human", code, instructions });
66
+ }
67
+ function resumeCommand(context, record, ownerStage) {
68
+ const action = {
69
+ kind: "command",
70
+ code: ownerStage ? `resume_owner_${ownerStage}` : "resume_local_preparation",
71
+ executable: process.execPath,
72
+ argv: [
73
+ context.runtime.entryPath,
74
+ "task",
75
+ "resume",
76
+ "--workspace",
77
+ context.workspaceRoot,
78
+ "--task",
79
+ record.task_id,
80
+ "--actor",
81
+ record.spec.actor_id,
82
+ "--json",
83
+ ],
84
+ cwd: context.workspaceRoot,
85
+ purpose: ownerStage === "execution"
86
+ ? "Continue the approved owner scope using its exact sealed execution request."
87
+ : ownerStage === "readback"
88
+ ? "Read back the consumed owner scope using its retained request."
89
+ : ownerStage === "reference_verification"
90
+ ? "Verify the canonical references selected by the current semantic decisions."
91
+ : ownerStage === "approval_continuation"
92
+ ? "Continue sealing the current scope under its existing registered approval."
93
+ : "Resume the content-bound deterministic local preparation for this task revision.",
94
+ };
95
+ return Object.freeze({
96
+ ...action,
97
+ argv: Object.freeze([...action.argv]),
98
+ binding_sha256: commandNextActionBindingSha256(action),
99
+ });
100
+ }
101
+ function noPermission() {
102
+ return Object.freeze({
103
+ state: "not_required",
104
+ requested_actions: Object.freeze([]),
105
+ approval_reference: null,
106
+ });
107
+ }
108
+ function assertNotInterrupted(signal) {
109
+ if (signal?.aborted)
110
+ throw new FoundryContextError("operation_interrupted", "Operation was interrupted; retained evidence must be inspected before resume.");
111
+ }
112
+ function contextOptions(options) {
113
+ if (options.runtimeManager?.cacheDir !== undefined)
114
+ assertFoundryCacheRootSeparated(options.runtimeManager.cacheDir, path.resolve(options.cwd ?? process.cwd(), options.workspace));
115
+ return {
116
+ moduleUrl: options.moduleUrl,
117
+ workspace: options.workspace,
118
+ cacheBase: options.cacheBase,
119
+ managedCacheRoot: options.runtimeManager?.cacheDir,
120
+ cwd: options.cwd,
121
+ environment: options.environment,
122
+ accountIntent: options.accountIntent,
123
+ workspaceAccess: options.workspaceAccess,
124
+ };
125
+ }
126
+ function accountReadiness(context) {
127
+ const intent = context.accountIntent;
128
+ if (!intent)
129
+ return Object.freeze({ status: "not_requested", reference_selected: false });
130
+ if (!intent.sessionReference)
131
+ return Object.freeze({ status: "needs_auth", reference_selected: false });
132
+ try {
133
+ const stat = fs.lstatSync(intent.sessionReference);
134
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size < 1 || stat.size > 8 * 1024 * 1024)
135
+ return Object.freeze({ status: "needs_auth", reference_selected: true });
136
+ }
137
+ catch {
138
+ return Object.freeze({ status: "needs_auth", reference_selected: true });
139
+ }
140
+ return Object.freeze({ status: "configured_unverified", reference_selected: true });
141
+ }
142
+ function qualification(context, selected) {
143
+ return selected
144
+ ? qualifyFoundryRuntime(context, {
145
+ cliExpectation: selected.cliExpectation,
146
+ tidasExpectation: selected.tidasExpectation,
147
+ tidasExecutable: selected.tidasExecutable,
148
+ })
149
+ : undefined;
150
+ }
151
+ function runtimeIdentity(context, selected) {
152
+ const described = createFoundryRuntime(context, selected).describe();
153
+ return Object.freeze({
154
+ foundry: Object.freeze({
155
+ package_name: context.runtime.packageName,
156
+ package_version: context.runtime.packageVersion,
157
+ package_manifest_sha256: context.runtime.packageManifestSha256,
158
+ entry_sha256: context.runtime.entrySha256,
159
+ }),
160
+ platform: context.platform,
161
+ qualification: described.qualification,
162
+ account_readiness: accountReadiness(context),
163
+ });
164
+ }
165
+ function failure(operation, taskId, error, identity = null) {
166
+ const code = error instanceof FoundryContextError ? error.code : "runtime_operation_failed";
167
+ const systemCode = error &&
168
+ typeof error === "object" &&
169
+ "code" in error &&
170
+ [
171
+ "ENOENT",
172
+ "EACCES",
173
+ "EPERM",
174
+ "EINVAL",
175
+ "ENAMETOOLONG",
176
+ "EIO",
177
+ "ENOSPC",
178
+ "EBADF",
179
+ "EEXIST",
180
+ "ENOTDIR",
181
+ "EMFILE",
182
+ "ENFILE",
183
+ "EBUSY",
184
+ "UNKNOWN",
185
+ "ERR_INVALID_ARG_TYPE",
186
+ "ERR_INVALID_ARG_VALUE",
187
+ "ERR_OUT_OF_RANGE",
188
+ ].includes(String(error.code))
189
+ ? String(error.code)
190
+ : error instanceof SyntaxError
191
+ ? "SyntaxError"
192
+ : error instanceof TypeError
193
+ ? "TypeError"
194
+ : null;
195
+ const message = error instanceof FoundryContextError
196
+ ? error.message
197
+ : `Foundry could not complete this operation${systemCode ? ` (${systemCode})` : ""}; selected state was preserved.`;
198
+ const needsAuth = code === "needs_auth" || code.startsWith("identity_");
199
+ const needsInputCodes = new Set([
200
+ "task_not_found",
201
+ "workspace_not_initialized",
202
+ "input_not_selected",
203
+ "regular_file_required",
204
+ "credential_input_forbidden",
205
+ "task_id_invalid",
206
+ "task_account_invalid",
207
+ "task_document_invalid",
208
+ "task_document_limit",
209
+ "task_entities_invalid",
210
+ "task_profile_unknown",
211
+ "task_request_invalid",
212
+ "task_source_invalid",
213
+ ]);
214
+ const blockedCodes = new Set([
215
+ "facade_crash_recovery_conflict",
216
+ "task_actor_mismatch",
217
+ "task_account_mismatch",
218
+ "task_attempt_state_invalid",
219
+ "task_authorization_state_invalid",
220
+ "migration_inventory_limit",
221
+ "migration_depth_limit",
222
+ "workspace_migration_pending",
223
+ "workspace_read_only",
224
+ "workspace_runtime_incompatible",
225
+ "migration_replay_forbidden",
226
+ ]);
227
+ const needsInput = needsInputCodes.has(code) ||
228
+ code.startsWith("argument_") ||
229
+ code.startsWith("task_spec_") ||
230
+ code.startsWith("task_semantic_") ||
231
+ code.startsWith("task_authorization_input_") ||
232
+ code.startsWith("task_seed_");
233
+ const blocked = !needsAuth &&
234
+ !needsInput &&
235
+ (blockedCodes.has(code) ||
236
+ code.includes("mismatch") ||
237
+ code.includes("changed") ||
238
+ code.includes("legacy") ||
239
+ code.includes("unsupported") ||
240
+ code.includes("unqualified") ||
241
+ code.includes("required") ||
242
+ code.includes("invalid") ||
243
+ code.includes("conflict"));
244
+ return createFoundryOperationResult({
245
+ operation,
246
+ status: needsAuth ? "needs_auth" : needsInput ? "needs_input" : blocked ? "blocked" : "failed",
247
+ taskId,
248
+ artifacts: [],
249
+ blockers: [{ code, message, scope: taskId }],
250
+ nextActions: [],
251
+ runtimeIdentity: identity,
252
+ permissions: noPermission(),
253
+ });
254
+ }
255
+ function readSpec(file) {
256
+ const fact = captureFoundryInput(file);
257
+ let value;
258
+ try {
259
+ value = JSON.parse(readCaptured(fact, maxSpecBytes, "task_spec_invalid").toString("utf8"));
260
+ }
261
+ catch (error) {
262
+ if (error instanceof FoundryContextError)
263
+ throw error;
264
+ throw new FoundryContextError("task_spec_invalid", "Task-start spec is not complete JSON.");
265
+ }
266
+ return { fact, spec: parseFoundryTaskStartSpec(value) };
267
+ }
268
+ function selectedInputs(workspaceRoot, spec) {
269
+ return Object.freeze(spec.sources.map((source) => captureFoundryInput(path.resolve(workspaceRoot, source.path))));
270
+ }
271
+ function accountIntent(spec, host) {
272
+ if (host?.accountMode &&
273
+ host.projectRef === spec.account_intent?.project_ref &&
274
+ host.userId === spec.account_intent?.user_id &&
275
+ host.accountMode !== (spec.account_intent.account_mode ?? "ordinary"))
276
+ throw new FoundryContextError("task_account_mismatch", "Explicit host and task verification modes must agree.");
277
+ const inheritedReference = host &&
278
+ host.projectRef === spec.account_intent?.project_ref &&
279
+ host.userId === spec.account_intent?.user_id
280
+ ? host.sessionReference
281
+ : undefined;
282
+ return spec.account_intent
283
+ ? {
284
+ projectRef: spec.account_intent.project_ref,
285
+ userId: spec.account_intent.user_id,
286
+ ...(spec.account_intent.account_mode
287
+ ? { accountMode: spec.account_intent.account_mode }
288
+ : {}),
289
+ ...((spec.account_intent.session_reference ?? inheritedReference)
290
+ ? { sessionReference: spec.account_intent.session_reference ?? inheritedReference }
291
+ : {}),
292
+ }
293
+ : undefined;
294
+ }
295
+ function seed(spec, inputs) {
296
+ if (!spec.seed)
297
+ return undefined;
298
+ const index = spec.sources.findIndex((source) => source.path === spec.seed?.path);
299
+ const fact = inputs[index];
300
+ if (!fact)
301
+ throw new FoundryContextError("task_seed_invalid", "Selected task seed exceeds its limit.");
302
+ let value;
303
+ try {
304
+ value = JSON.parse(readCaptured(fact, maxSeedBytes, "task_seed_invalid").toString("utf8"));
305
+ }
306
+ catch (error) {
307
+ if (error instanceof FoundryContextError)
308
+ throw error;
309
+ throw new FoundryContextError("task_seed_invalid", "Selected task seed is not complete JSON.");
310
+ }
311
+ if (!value || typeof value !== "object" || Array.isArray(value))
312
+ throw new FoundryContextError("task_seed_invalid", "Selected task seed must be a JSON object.");
313
+ return value;
314
+ }
315
+ function taskContext(options, base, record, derived = []) {
316
+ return createFoundryRuntimeContext({
317
+ ...contextOptions(options),
318
+ workspace: base.workspaceRoot,
319
+ taskId: record.task_id,
320
+ actorId: record.spec.actor_id,
321
+ accountIntent: accountIntent(record.spec, options.accountIntent),
322
+ inputs: [
323
+ ...record.inputs,
324
+ ...derived.filter((fact) => !record.inputs.some((source) => source.path === fact.path)),
325
+ ],
326
+ });
327
+ }
328
+ function sourcePath(record, selected) {
329
+ const index = record.spec.sources.findIndex((source) => source.path === selected);
330
+ const fact = record.inputs[index];
331
+ if (!fact)
332
+ throw new FoundryContextError("task_spec_preparation_invalid", "Preparation input has no registered source fact.");
333
+ return fact.path;
334
+ }
335
+ function taskArtifacts(context, inspected) {
336
+ return inspected.artifacts.map((entry) => Object.freeze({
337
+ kind: "file",
338
+ role: path.basename(entry.path).replace(/[^a-zA-Z0-9._-]/gu, "_"),
339
+ path: path.join(context.taskRoot, entry.path),
340
+ bytes: entry.bytes,
341
+ sha256: entry.sha256,
342
+ }));
343
+ }
344
+ function completionProven(context, record, inspected) {
345
+ for (const entry of inspected.artifacts) {
346
+ if (entry.command !== "dataset-import-completion-report")
347
+ continue;
348
+ const file = path.join(context.taskRoot, entry.path);
349
+ let value;
350
+ try {
351
+ value = JSON.parse(readCaptured({ path: file, bytes: entry.bytes, sha256: entry.sha256 }, maxSeedBytes, "task_completion_invalid").toString("utf8"));
352
+ }
353
+ catch {
354
+ return false;
355
+ }
356
+ if (value && typeof value === "object" && !Array.isArray(value)) {
357
+ const report = value;
358
+ if (report.status === "completed" &&
359
+ report.task_id === record.task_id &&
360
+ (!Array.isArray(report.blockers) || report.blockers.length === 0))
361
+ return true;
362
+ }
363
+ }
364
+ return false;
365
+ }
366
+ function taskProjection(operation, context, record, inspected, identity) {
367
+ const artifacts = taskArtifacts(context, inspected);
368
+ if (completionProven(context, record, inspected))
369
+ return createFoundryOperationResult({
370
+ operation,
371
+ status: "completed",
372
+ taskId: record.task_id,
373
+ artifacts,
374
+ blockers: [],
375
+ nextActions: [],
376
+ runtimeIdentity: identity,
377
+ permissions: noPermission(),
378
+ });
379
+ let execution = null;
380
+ try {
381
+ execution = completedOwnerScopes(context, inspected.artifacts);
382
+ }
383
+ catch (error) {
384
+ if (!(error instanceof FoundryContextError) || error.code !== "execution_legacy_attempts")
385
+ throw error;
386
+ }
387
+ if (!execution || execution.pending.length)
388
+ return createFoundryOperationResult({
389
+ operation,
390
+ status: execution ? "needs_input" : "blocked",
391
+ taskId: record.task_id,
392
+ artifacts,
393
+ blockers: [
394
+ {
395
+ code: "mutation_readback_required",
396
+ message: "Existing attempt evidence requires its owner readback recovery and cannot replay.",
397
+ scope: record.task_id,
398
+ },
399
+ ],
400
+ nextActions: execution
401
+ ? [resumeCommand(context, record, "readback")]
402
+ : [
403
+ human("resume_owner_readback", "Use the retained owner attempt and readback evidence; do not dispatch another mutation."),
404
+ ],
405
+ runtimeIdentity: identity,
406
+ permissions: noPermission(),
407
+ });
408
+ const prepared = inspected.artifacts.some((entry) => entry.command === "dataset-curation-cleanup");
409
+ const nativeReport = artifacts.find((artifact) => artifact.kind === "file" &&
410
+ path.basename(artifact.path) === "foundry-native-import.json" &&
411
+ inspected.artifacts.some((entry) => entry.command === "dataset-tidas-import" &&
412
+ path.join(context.taskRoot, entry.path) === artifact.path));
413
+ if (nativeReport?.kind === "file") {
414
+ const result = JSON.parse(readCaptured(nativeReport, maxSeedBytes, "native_import_report_invalid").toString("utf8"));
415
+ if (!result ||
416
+ typeof result !== "object" ||
417
+ !("schema" in result) ||
418
+ result.schema !== "tiangong-foundry.native-import-stage.v1" ||
419
+ !("status" in result))
420
+ throw new FoundryContextError("native_import_report_invalid", "The registered native stage report is invalid.");
421
+ if (result.status !== "completed")
422
+ return createFoundryOperationResult({
423
+ operation,
424
+ status: "blocked",
425
+ taskId: record.task_id,
426
+ artifacts,
427
+ blockers: [
428
+ {
429
+ code: "native_import_blocked",
430
+ message: "Inspect the registered conversion report before continuing this source package.",
431
+ scope: record.task_id,
432
+ },
433
+ ],
434
+ nextActions: [
435
+ human("review_conversion_report", "Resolve the conversion findings for the selected source before continuing."),
436
+ ],
437
+ runtimeIdentity: identity,
438
+ permissions: noPermission(),
439
+ });
440
+ }
441
+ const workflow = currentWorkflowState(context, inspected.artifacts);
442
+ const references = inspectFoundryReferences(context, inspected.artifacts);
443
+ const scopeComplete = workflow.rows &&
444
+ (workflow.rows.value.sets.length > 0 || references.scope) &&
445
+ workflow.rows.value.sets.every((set) => execution.completed.has(set.type));
446
+ if (scopeComplete && (!references.scope || references.verified) && workflow.finalization)
447
+ return createFoundryOperationResult({
448
+ operation,
449
+ status: "completed",
450
+ taskId: record.task_id,
451
+ artifacts,
452
+ blockers: [],
453
+ nextActions: [],
454
+ runtimeIdentity: identity,
455
+ permissions: noPermission(),
456
+ });
457
+ if (workflow.finalization && references.scope && !references.verified)
458
+ return createFoundryOperationResult({
459
+ operation,
460
+ status: "needs_input",
461
+ taskId: record.task_id,
462
+ artifacts,
463
+ blockers: [
464
+ {
465
+ code: "reference_verification_required",
466
+ message: "Current canonical reference decisions require independent remote verification.",
467
+ scope: record.task_id,
468
+ },
469
+ ],
470
+ nextActions: [resumeCommand(context, record, "reference_verification")],
471
+ runtimeIdentity: identity,
472
+ permissions: noPermission(),
473
+ });
474
+ if (workflow.authorization &&
475
+ !execution.completed.has(String(workflow.authorization.value.dataset_type))) {
476
+ const report = workflow.authorization.value;
477
+ const code = report.status === "sealed"
478
+ ? "authorized_execution_pending"
479
+ : report.status === "authorized_current_rows"
480
+ ? "authorized_refinalization_pending"
481
+ : "authorized_handoff_requires_input";
482
+ return createFoundryOperationResult({
483
+ operation,
484
+ status: "needs_input",
485
+ taskId: record.task_id,
486
+ artifacts,
487
+ blockers: [
488
+ {
489
+ code,
490
+ message: report.status === "sealed"
491
+ ? "Current approval and execution capsule are recorded; owner execution remains pending."
492
+ : "Current approval is registered; resolve the remaining preparation or handoff work.",
493
+ scope: record.task_id,
494
+ },
495
+ ],
496
+ nextActions: report.status === "sealed"
497
+ ? [resumeCommand(context, record, "execution")]
498
+ : [
499
+ human(code, `Read the registered approval result ${workflow.authorization.file}. Existing approval does not permit replay of any consumed attempt.`),
500
+ ],
501
+ runtimeIdentity: identity,
502
+ permissions: {
503
+ state: "granted",
504
+ requested_actions: Array.isArray(report.allowed_actions)
505
+ ? report.allowed_actions.filter((item) => typeof item === "string")
506
+ : [],
507
+ approval_reference: String(report.authorization_sha256),
508
+ },
509
+ });
510
+ }
511
+ if (workflow.preparedApproval) {
512
+ const canContinue = Array.isArray(workflow.finalization?.value.sets) &&
513
+ workflow.finalization.value.sets
514
+ .map(workflowObject)
515
+ .some((scope) => scope.type === workflow.preparedApproval.value.dataset_type &&
516
+ scope.status === "ready_for_remote_write");
517
+ return createFoundryOperationResult({
518
+ operation,
519
+ status: "needs_input",
520
+ taskId: record.task_id,
521
+ artifacts,
522
+ blockers: [
523
+ {
524
+ code: "authorization_continuation_pending",
525
+ message: "Resume to verify the retained preparation approval and complete its current final-row derivation.",
526
+ scope: record.task_id,
527
+ },
528
+ ],
529
+ nextActions: canContinue
530
+ ? [resumeCommand(context, record, "approval_continuation")]
531
+ : [
532
+ human("resume_approval_continuation", `Retained preparation approval: ${workflow.preparedApproval.file}.`),
533
+ ],
534
+ runtimeIdentity: identity,
535
+ permissions: noPermission(),
536
+ });
537
+ }
538
+ if (workflow.finalization) {
539
+ const ready = workflow.finalization.value.status === "ready_for_authorization";
540
+ const found = workflow.finalization;
541
+ return createFoundryOperationResult({
542
+ operation,
543
+ status: "needs_input",
544
+ taskId: record.task_id,
545
+ artifacts,
546
+ blockers: [
547
+ {
548
+ code: ready ? "task_authorization_required" : "finalization_requires_input",
549
+ message: ready
550
+ ? "Final rows are prepared. Register current task approval before owner draft execution."
551
+ : "Resolve the registered finalization blockers before owner draft execution.",
552
+ scope: record.task_id,
553
+ },
554
+ ],
555
+ nextActions: [
556
+ human(ready ? "authorize_final_rows" : "review_finalization", `Read the current finalization report ${found.file} and its per-scope owner reports.`),
557
+ ],
558
+ runtimeIdentity: identity,
559
+ permissions: ready
560
+ ? { state: "required", requested_actions: [], approval_reference: null }
561
+ : noPermission(),
562
+ });
563
+ }
564
+ if (workflow.identity?.value.status === "blocked")
565
+ return createFoundryOperationResult({
566
+ operation,
567
+ status: "needs_input",
568
+ taskId: record.task_id,
569
+ artifacts,
570
+ blockers: [
571
+ {
572
+ code: "identity_preflight_requires_input",
573
+ message: "Review the identity preflight diagnostics. A subsequent resume retries this read-only stage against the same current rows.",
574
+ scope: record.task_id,
575
+ },
576
+ ],
577
+ nextActions: [
578
+ human("review_identity_preflight", `Read ${workflow.identity.file} and resolve the reported query or execution failure before retrying.`),
579
+ ],
580
+ runtimeIdentity: identity,
581
+ permissions: noPermission(),
582
+ });
583
+ const assessment = workflow.assessment?.entry;
584
+ if (assessment) {
585
+ const report = JSON.parse(readCaptured({ ...assessment, path: path.join(context.taskRoot, assessment.path) }, maxSeedBytes, "workflow_assessment_invalid").toString("utf8"));
586
+ if (!report ||
587
+ typeof report !== "object" ||
588
+ !("schema" in report) ||
589
+ report.schema !== "tiangong-foundry.assessment-stage.v1" ||
590
+ !("sets" in report) ||
591
+ !Array.isArray(report.sets))
592
+ throw new FoundryContextError("workflow_assessment_invalid", "Registered assessment metadata is invalid.");
593
+ const pending = report.sets.filter((value) => {
594
+ if (!value ||
595
+ typeof value !== "object" ||
596
+ !("curation_counts" in value) ||
597
+ !("authoring_counts" in value) ||
598
+ !("type" in value) ||
599
+ typeof value.type !== "string")
600
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment counts are missing.");
601
+ const curation = value.curation_counts;
602
+ const authoring = value.authoring_counts;
603
+ if (!curation ||
604
+ !authoring ||
605
+ !Number.isSafeInteger(curation.blocking_items) ||
606
+ !Number.isSafeInteger(authoring.tasks))
607
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment counts are invalid.");
608
+ for (const key of [
609
+ "rows",
610
+ "schema_report",
611
+ "qa_report",
612
+ "curation_report",
613
+ "authoring_manifest",
614
+ ]) {
615
+ const file = value[key];
616
+ if (typeof file !== "string")
617
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment file reference is missing.");
618
+ const expected = inspected.artifacts.find((entry) => path.join(context.taskRoot, entry.path) === file);
619
+ if (!expected)
620
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment references an unregistered artifact.");
621
+ const observed = captureFoundryInput(file);
622
+ if (observed.bytes !== expected.bytes || observed.sha256 !== expected.sha256)
623
+ throw new FoundryContextError("workflow_assessment_changed", "An assessed input or report changed; retain its original evidence before continuing.");
624
+ }
625
+ return Number(curation.blocking_items ?? 0) > 0 || Number(authoring.tasks ?? 0) > 0;
626
+ });
627
+ if (pending.length)
628
+ return createFoundryOperationResult({
629
+ operation,
630
+ status: "needs_input",
631
+ taskId: record.task_id,
632
+ artifacts,
633
+ blockers: pending.map((set) => ({
634
+ code: "curation_requires_input",
635
+ message: `Resolve the current ${set.type} curation and authoring work before a write handoff.`,
636
+ scope: record.task_id,
637
+ })),
638
+ nextActions: pending.flatMap((set) => [
639
+ human("review_semantic_work", `Read the registered curation report ${set.curation_report} and authoring manifest ${set.authoring_manifest}. Use their bound source/context evidence; no write permission is implied.`),
640
+ ...(set.decisions ?? []).map((work) => human(`review_${work.kind}_decisions`, `Read registered ${work.kind} task ${work.task} (${work.status}). Complete its bound decision template and submit it with semantic-input kind=${work.kind}.`)),
641
+ ]),
642
+ runtimeIdentity: identity,
643
+ permissions: noPermission(),
644
+ });
645
+ }
646
+ const nextActions = prepared
647
+ ? [
648
+ human("review_prepared_rows", "Review the current prepared artifacts and continue the returned task workflow."),
649
+ ]
650
+ : record.spec.preparation || !workflow.assessment
651
+ ? [resumeCommand(context, record)]
652
+ : [
653
+ human("review_assessment", "Review the registered curation reports and authoring-task manifests. Resolve their current semantic work before requesting a write handoff; assessment does not grant permission."),
654
+ ];
655
+ return createFoundryOperationResult({
656
+ operation,
657
+ status: "ready",
658
+ taskId: record.task_id,
659
+ artifacts,
660
+ blockers: [],
661
+ nextActions,
662
+ runtimeIdentity: identity,
663
+ permissions: noPermission(),
664
+ });
665
+ }
666
+ export function createFoundryFacade(options) {
667
+ const base = () => createFoundryRuntimeContext(contextOptions(options));
668
+ return Object.freeze({
669
+ async runtimeUse(input) {
670
+ try {
671
+ assertNotInterrupted(options.signal);
672
+ if (!options.workspaceAccess)
673
+ throw new FoundryContextError("workspace_runtime_selection_required", "Explicit runtime selection requires an independently qualified current host.");
674
+ const current = base();
675
+ const selected = await selectFoundryWorkspaceRuntime(current, options.workspaceAccess.manifest, input.manifest, {
676
+ requestId: input.requestId,
677
+ actorId: input.actorId,
678
+ access: input.access,
679
+ manager: { ...options.runtimeManager, signal: options.signal },
680
+ });
681
+ return createFoundryOperationResult({
682
+ operation: "workspace.migrate",
683
+ status: "ready",
684
+ taskId: null,
685
+ artifacts: [fileArtifact("workspace_runtime_selection", selected.path)],
686
+ blockers: [],
687
+ nextActions: [
688
+ human("launch_selected_runtime", "Launch through the independently trusted selected manifest. Previous and selected components remain leased; read-only selection does not permit task writes."),
689
+ ],
690
+ runtimeIdentity: runtimeIdentity(current),
691
+ permissions: noPermission(),
692
+ });
693
+ }
694
+ catch (error) {
695
+ return failure("workspace.migrate", null, error);
696
+ }
697
+ },
698
+ initialize() {
699
+ try {
700
+ assertNotInterrupted(options.signal);
701
+ const initial = base();
702
+ assertNotInterrupted(options.signal);
703
+ initializeFoundryWorkspace(initial);
704
+ assertNotInterrupted(options.signal);
705
+ const current = base();
706
+ const marker = path.join(current.controlRoot, "workspace.json");
707
+ return createFoundryOperationResult({
708
+ operation: "workspace.init",
709
+ status: "ready",
710
+ taskId: null,
711
+ artifacts: [fileArtifact("workspace_marker", marker)],
712
+ blockers: [],
713
+ nextActions: [],
714
+ runtimeIdentity: runtimeIdentity(current),
715
+ permissions: noPermission(),
716
+ });
717
+ }
718
+ catch (error) {
719
+ return failure("workspace.init", null, error);
720
+ }
721
+ },
722
+ doctor() {
723
+ try {
724
+ assertNotInterrupted(options.signal);
725
+ const current = base();
726
+ if (pendingFoundryMigration(current))
727
+ throw new FoundryContextError("workspace_migration_pending", "Migration is staged and requires task adoption and activation audit.");
728
+ const qualified = qualification(current, options.runtimeSelection);
729
+ assertNotInterrupted(options.signal);
730
+ const readiness = accountReadiness(current);
731
+ const nextActions = [
732
+ ...(current.workspaceId
733
+ ? []
734
+ : [human("initialize_workspace", "Initialize the selected user workspace.")]),
735
+ ...(qualified
736
+ ? []
737
+ : [
738
+ human("provide_qualified_runtime", "Launch through the trusted CLI runtime manager before a child-required stage."),
739
+ ]),
740
+ ...(readiness.status === "needs_auth"
741
+ ? [
742
+ human("authenticate_cli", "Complete the trusted CLI OAuth flow, then resume with the same account intent."),
743
+ ]
744
+ : []),
745
+ ];
746
+ return createFoundryOperationResult({
747
+ operation: "doctor",
748
+ status: readiness.status === "needs_auth" ? "needs_auth" : "ready",
749
+ taskId: null,
750
+ artifacts: [],
751
+ blockers: readiness.status === "needs_auth"
752
+ ? [
753
+ {
754
+ code: "needs_auth",
755
+ message: "The selected account intent needs a CLI-owned OAuth session before restricted work.",
756
+ scope: null,
757
+ },
758
+ ]
759
+ : [],
760
+ nextActions,
761
+ runtimeIdentity: runtimeIdentity(current, qualified),
762
+ permissions: noPermission(),
763
+ });
764
+ }
765
+ catch (error) {
766
+ return failure("doctor", null, error);
767
+ }
768
+ },
769
+ migrationDryRun(input) {
770
+ try {
771
+ assertNotInterrupted(options.signal);
772
+ assertFoundryRuntimeHost();
773
+ if (options.runtimeManager?.cacheDir !== undefined)
774
+ assertFoundryCacheRootSeparated(options.runtimeManager.cacheDir, path.resolve(options.cwd ?? process.cwd(), options.workspace));
775
+ const plan = input
776
+ ? planFoundryWorkspaceMigration(createFoundryRuntimeContext({
777
+ ...contextOptions(options),
778
+ workspace: input.destination,
779
+ }), {
780
+ sourceWorkspace: path.resolve(options.cwd ?? process.cwd(), options.workspace),
781
+ actorId: input.actorId,
782
+ requestId: input.requestId,
783
+ stageManifests: input.stageManifests,
784
+ externalInputs: input.externalInputs,
785
+ })
786
+ : inventoryFoundryWorkspace(options.workspace, {
787
+ sessionReference: options.accountIntent?.sessionReference,
788
+ });
789
+ assertNotInterrupted(options.signal);
790
+ return createFoundryOperationResult({
791
+ operation: "workspace.migrate",
792
+ status: "ready",
793
+ taskId: null,
794
+ artifacts: [
795
+ inlineArtifact(input ? "workspace_migration_transfer_plan" : "workspace_migration_plan", plan),
796
+ ],
797
+ blockers: [],
798
+ nextActions: input || ("disposition" in plan && plan.disposition === "explicit_migration_required")
799
+ ? [
800
+ human("review_workspace_migration", "Review this content-bound plan before an explicit migration apply; retained stage labels grant no write or replay permission."),
801
+ ]
802
+ : [],
803
+ runtimeIdentity: null,
804
+ permissions: noPermission(),
805
+ });
806
+ }
807
+ catch (error) {
808
+ return failure("workspace.migrate", null, error);
809
+ }
810
+ },
811
+ async migrationTransfer(input) {
812
+ try {
813
+ assertNotInterrupted(options.signal);
814
+ assertFoundryRuntimeHost();
815
+ const destination = createFoundryRuntimeContext({
816
+ ...contextOptions(options),
817
+ workspace: input.destination,
818
+ });
819
+ const planning = {
820
+ sourceWorkspace: path.resolve(options.cwd ?? process.cwd(), options.workspace),
821
+ actorId: input.actorId,
822
+ requestId: input.requestId,
823
+ stageManifests: input.stageManifests,
824
+ externalInputs: input.externalInputs,
825
+ };
826
+ if (input.audit && destination.migration) {
827
+ revalidateFoundryMigrationPlan(destination, planning, input.plan, destination.migration.plan_sha256);
828
+ const activation = readFoundryMigrationAuthority(destination.controlRoot, destination.workspaceId, destination.migration);
829
+ return createFoundryOperationResult({
830
+ operation: "workspace.migrate",
831
+ status: "ready",
832
+ taskId: null,
833
+ artifacts: [
834
+ fileArtifact("migration_activation_receipt", path.join(destination.controlRoot, "migrations", activation.plan_sha256, "activation.json")),
835
+ ],
836
+ blockers: [],
837
+ nextActions: [],
838
+ runtimeIdentity: runtimeIdentity(destination),
839
+ permissions: noPermission(),
840
+ });
841
+ }
842
+ const transfer = input.audit
843
+ ? auditFoundryMigration(destination, planning, input.plan)
844
+ : await stageFoundryMigration(destination, planning, input.plan, {
845
+ signal: options.signal,
846
+ });
847
+ return createFoundryOperationResult({
848
+ operation: "workspace.migrate",
849
+ status: "ready",
850
+ taskId: null,
851
+ artifacts: [fileArtifact("migration_transfer_receipt", transfer.path)],
852
+ blockers: [],
853
+ nextActions: [
854
+ human("complete_migration_adoption", "The source snapshot is staged and verified. Complete task adoption and activation audit before running this workspace."),
855
+ ],
856
+ runtimeIdentity: null,
857
+ permissions: noPermission(),
858
+ });
859
+ }
860
+ catch (error) {
861
+ return failure("workspace.migrate", null, error);
862
+ }
863
+ },
864
+ async migrationAdoption(input) {
865
+ try {
866
+ assertNotInterrupted(options.signal);
867
+ if (!options.workspaceAccess)
868
+ throw new FoundryContextError("workspace_runtime_selection_required", "Select an independently trusted Foundry runtime before task adoption.");
869
+ const destination = createFoundryRuntimeContext({
870
+ ...contextOptions(options),
871
+ workspace: input.destination,
872
+ });
873
+ const planning = {
874
+ sourceWorkspace: path.resolve(options.cwd ?? process.cwd(), options.workspace),
875
+ actorId: input.actorId,
876
+ requestId: input.requestId,
877
+ stageManifests: input.stageManifests,
878
+ externalInputs: input.externalInputs,
879
+ };
880
+ if (input.apply) {
881
+ if (input.adoptionPlan === undefined)
882
+ throw new FoundryContextError("migration_adoption_required", "Explicit application requires the reviewed adoption plan.");
883
+ const applied = await applyFoundryMigrationAdoption(destination, planning, input.plan, input.tasks, input.adoptionPlan, options.workspaceAccess.manifest, {
884
+ runtimeManager: options.runtimeManager,
885
+ createTaskFacade: () => createFoundryFacade({ ...options, workspace: destination.workspaceRoot }),
886
+ }, { signal: options.signal });
887
+ return createFoundryOperationResult({
888
+ operation: "workspace.migrate",
889
+ status: "ready",
890
+ taskId: null,
891
+ artifacts: [fileArtifact("migration_activation_receipt", applied.path)],
892
+ blockers: [],
893
+ nextActions: applied.activation.tasks.some((task) => task.disposition !== "local-unattempted")
894
+ ? [
895
+ human("retained_owner_recovery", "Retained terminal or unresolved legacy work stays under its original owner. Inspect the activation receipt before choosing status/readback recovery."),
896
+ ]
897
+ : [],
898
+ runtimeIdentity: runtimeIdentity(destination),
899
+ permissions: noPermission(),
900
+ });
901
+ }
902
+ if (input.adoptionPlan !== undefined)
903
+ throw new FoundryContextError("argument_migration_plan_invalid", "Adoption preview reconstructs its plan from independent selections.");
904
+ const planned = await planFoundryMigrationAdoption(destination, planning, input.plan, input.tasks, options.workspaceAccess.manifest);
905
+ return createFoundryOperationResult({
906
+ operation: "workspace.migrate",
907
+ status: "ready",
908
+ taskId: null,
909
+ artifacts: [inlineArtifact("migration_adoption_plan", planned)],
910
+ blockers: [],
911
+ nextActions: [
912
+ human("review_task_adoption", "Review the retained history classes, exact source mapping and current preparation before explicit application."),
913
+ ],
914
+ runtimeIdentity: runtimeIdentity(destination),
915
+ permissions: noPermission(),
916
+ });
917
+ }
918
+ catch (error) {
919
+ return failure("workspace.migrate", null, error);
920
+ }
921
+ },
922
+ async start(input) {
923
+ let current = null;
924
+ let taskId = null;
925
+ try {
926
+ assertNotInterrupted(options.signal);
927
+ current = base();
928
+ assertFoundryWorkspaceWrite(current);
929
+ if (!current.workspaceId)
930
+ throw new FoundryContextError("workspace_not_initialized", "Initialize the selected workspace before starting a task.");
931
+ const selectedSpec = readSpec(path.resolve(current.workspaceRoot, input.specFile));
932
+ const inputs = selectedInputs(current.workspaceRoot, selectedSpec.spec);
933
+ const selectedSeed = seed(selectedSpec.spec, inputs);
934
+ assertNotInterrupted(options.signal);
935
+ const record = await registerFoundryFacadeTask(current, {
936
+ specSource: selectedSpec.fact,
937
+ spec: selectedSpec.spec,
938
+ inputs,
939
+ createOrLoad: (taskId) => {
940
+ const context = createFoundryRuntimeContext({
941
+ ...contextOptions(options),
942
+ workspace: current.workspaceRoot,
943
+ taskId,
944
+ actorId: selectedSpec.spec.actor_id,
945
+ accountIntent: accountIntent(selectedSpec.spec, options.accountIntent),
946
+ inputs,
947
+ });
948
+ const task = createFoundryRuntime(context).startTask({
949
+ requestId: selectedSpec.spec.request_id,
950
+ lane: selectedSpec.spec.lane,
951
+ profileId: selectedSpec.spec.profile_id,
952
+ targetEntities: [...selectedSpec.spec.target_entities],
953
+ seed: selectedSeed,
954
+ });
955
+ return {
956
+ created_at_utc: task.job.created_at_utc,
957
+ inputs_sha256: sha256Json(task.sources),
958
+ };
959
+ },
960
+ });
961
+ taskId = record.task_id;
962
+ assertNotInterrupted(options.signal);
963
+ const context = taskContext(options, current, record);
964
+ const inspected = await createFoundryRuntime(context).inspectTask();
965
+ assertNotInterrupted(options.signal);
966
+ loadFoundryFacadeTaskRecord(current, record.task_id, record.spec.actor_id);
967
+ const result = taskProjection("task.start", context, record, inspected, runtimeIdentity(context));
968
+ const requestIndex = path.join(current.stateRoot, "facade-requests", `${record.request_sha256}.json`);
969
+ return createFoundryOperationResult({
970
+ ...result,
971
+ operation: "task.start",
972
+ taskId: record.task_id,
973
+ artifacts: [
974
+ fileArtifact("facade_request_index", requestIndex),
975
+ fileArtifact("foundry_job", path.join(context.taskRoot, "foundry-job.json")),
976
+ ],
977
+ nextActions: result.next_actions,
978
+ runtimeIdentity: result.runtime_identity,
979
+ permissions: result.permissions,
980
+ });
981
+ }
982
+ catch (error) {
983
+ return failure("task.start", taskId, error, current ? runtimeIdentity(current) : null);
984
+ }
985
+ },
986
+ async status(input) {
987
+ let current = null;
988
+ try {
989
+ assertNotInterrupted(options.signal);
990
+ current = base();
991
+ const record = loadFoundryFacadeTaskRecord(current, input.taskId, input.actorId);
992
+ const context = taskContext(options, current, record);
993
+ const qualified = qualification(context, options.runtimeSelection);
994
+ const inspected = await createFoundryRuntime(context, qualified).inspectTask();
995
+ assertNotInterrupted(options.signal);
996
+ const projection = taskProjection("task.status", context, record, inspected, runtimeIdentity(context, qualified));
997
+ if (context.workspaceAccess === "read")
998
+ return createFoundryOperationResult({
999
+ ...projection,
1000
+ operation: "task.status",
1001
+ taskId: projection.task_id,
1002
+ nextActions: [
1003
+ human("workspace_read_only", "This runtime can inspect retained task evidence. Select a write-qualified runtime before preparation or mutation."),
1004
+ ],
1005
+ runtimeIdentity: projection.runtime_identity,
1006
+ permissions: projection.permissions,
1007
+ });
1008
+ return projection;
1009
+ }
1010
+ catch (error) {
1011
+ return failure("task.status", input.taskId, error, current ? runtimeIdentity(current) : null);
1012
+ }
1013
+ },
1014
+ async resume(input) {
1015
+ let current = null;
1016
+ try {
1017
+ assertNotInterrupted(options.signal);
1018
+ current = base();
1019
+ assertFoundryWorkspaceWrite(current);
1020
+ const record = loadFoundryFacadeTaskRecord(current, input.taskId, input.actorId);
1021
+ const context = taskContext(options, current, record);
1022
+ const qualified = qualification(context, options.runtimeSelection);
1023
+ const runtime = createFoundryRuntime(context, qualified);
1024
+ const before = await runtime.inspectTask();
1025
+ assertNotInterrupted(options.signal);
1026
+ loadFoundryFacadeTaskRecord(current, record.task_id, record.spec.actor_id);
1027
+ const existing = taskProjection("task.resume", context, record, before, runtimeIdentity(context, qualified));
1028
+ if (existing.status === "completed" || existing.status === "blocked")
1029
+ return existing;
1030
+ const execution = completedOwnerScopes(context, before.artifacts);
1031
+ if (execution.pending.length) {
1032
+ if (input.authorizationInputFile || input.semanticInputFile)
1033
+ throw new FoundryContextError("execution_recovery_required", "Recover the consumed request before submitting changes.");
1034
+ if (!qualified)
1035
+ throw new FoundryContextError("runtime_unqualified", "Owner readback requires qualified runtime owners.");
1036
+ const selected = taskContext(options, current, record, before.artifacts.map((entry) => ({
1037
+ path: path.join(context.taskRoot, entry.path),
1038
+ bytes: entry.bytes,
1039
+ sha256: entry.sha256,
1040
+ })));
1041
+ await executeFoundryOwnerScope(selected, qualified, before.artifacts, execution.pending[0], options.authentication);
1042
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1043
+ }
1044
+ if (input.authorizationInputFile) {
1045
+ if (input.semanticInputFile || record.spec.preparation)
1046
+ throw new FoundryContextError("task_authorization_input_invalid", "Submit approval separately from semantic input or explicit cleanup.");
1047
+ if (!qualified)
1048
+ throw new FoundryContextError("runtime_unqualified", "Approval admission requires qualified runtime owners.");
1049
+ const submission = selectFoundryAuthorizationInput(context, input.authorizationInputFile);
1050
+ if (execution.completed.has(submission.spec.dataset_type))
1051
+ throw new FoundryContextError("execution_scope_completed", "A verified scope cannot receive new write approval.");
1052
+ const facts = before.artifacts.map((artifact) => ({
1053
+ path: path.join(context.taskRoot, artifact.path),
1054
+ bytes: artifact.bytes,
1055
+ sha256: artifact.sha256,
1056
+ }));
1057
+ const selected = taskContext(options, current, record, facts);
1058
+ await authorizeFoundryWorkflow(selected, qualified, before.artifacts, submission, options.authentication);
1059
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1060
+ }
1061
+ if (input.semanticInputFile) {
1062
+ if (execution.consumed.size)
1063
+ throw new FoundryContextError("execution_scope_consumed", "Retain consumed scope rows and their execution evidence.");
1064
+ if (record.spec.preparation)
1065
+ throw new FoundryContextError("task_semantic_input_invalid", "Explicit cleanup tasks do not accept semantic submissions.");
1066
+ const submission = selectFoundrySemanticInput(context, input.semanticInputFile);
1067
+ const facts = before.artifacts.map((artifact) => ({
1068
+ path: path.join(context.taskRoot, artifact.path),
1069
+ bytes: artifact.bytes,
1070
+ sha256: artifact.sha256,
1071
+ }));
1072
+ const selected = taskContext(options, current, record, facts);
1073
+ const result = await createFoundryRuntime(selected, qualified).applySemantic(before.artifacts, submission);
1074
+ assertNotInterrupted(options.signal);
1075
+ const after = await runtime.inspectTask();
1076
+ if (result.status !== "completed")
1077
+ return createFoundryOperationResult({
1078
+ operation: "task.resume",
1079
+ status: "needs_input",
1080
+ taskId: record.task_id,
1081
+ artifacts: taskArtifacts(context, after),
1082
+ blockers: [
1083
+ {
1084
+ code: "semantic_input_rejected",
1085
+ message: "Review the registered semantic result and correct the submitted input; prior rows remain current.",
1086
+ scope: record.task_id,
1087
+ },
1088
+ ],
1089
+ nextActions: [
1090
+ human("correct_semantic_input", "Use the semantic-result.json diagnostics and submit corrected input against the current assessment."),
1091
+ ],
1092
+ runtimeIdentity: runtimeIdentity(context, qualified),
1093
+ permissions: noPermission(),
1094
+ });
1095
+ return taskProjection("task.resume", context, record, after, runtimeIdentity(context, qualified));
1096
+ }
1097
+ const preparation = record.spec.preparation;
1098
+ const workflow = currentWorkflowState(context, before.artifacts);
1099
+ const references = inspectFoundryReferences(context, before.artifacts);
1100
+ if (!preparation && workflow.finalization && references.scope && !references.verified) {
1101
+ if (!qualified)
1102
+ throw new FoundryContextError("runtime_unqualified", "Reference verification requires qualified runtime owners.");
1103
+ const selected = taskContext(options, current, record, before.artifacts.map((entry) => ({
1104
+ path: path.join(context.taskRoot, entry.path),
1105
+ bytes: entry.bytes,
1106
+ sha256: entry.sha256,
1107
+ })));
1108
+ await verifyFoundryReferences(selected, qualified, before.artifacts, options.authentication);
1109
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1110
+ }
1111
+ if (!preparation &&
1112
+ workflow.authorization?.value.status === "sealed" &&
1113
+ !execution.completed.has(String(workflow.authorization.value.dataset_type))) {
1114
+ if (!qualified)
1115
+ throw new FoundryContextError("runtime_unqualified", "Owner execution requires qualified runtime owners.");
1116
+ const selected = taskContext(options, current, record, before.artifacts.map((entry) => ({
1117
+ path: path.join(context.taskRoot, entry.path),
1118
+ bytes: entry.bytes,
1119
+ sha256: entry.sha256,
1120
+ })));
1121
+ const request = execution.requests.find((item) => item.request.content.authorization === workflow.authorization.entry.sha256);
1122
+ if (request)
1123
+ await executeFoundryOwnerScope(selected, qualified, before.artifacts, request, options.authentication);
1124
+ else
1125
+ await prepareFoundryOwnerExecution(selected, before.artifacts);
1126
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1127
+ }
1128
+ if (!preparation &&
1129
+ execution.completed.size &&
1130
+ workflow.finalization?.value.execution_progress_sha256 !== execution.progressSha256) {
1131
+ if (!qualified)
1132
+ throw new FoundryContextError("runtime_unqualified", "Dependency finalization requires qualified runtime owners.");
1133
+ const selected = taskContext(options, current, record, before.artifacts.map((entry) => ({
1134
+ path: path.join(context.taskRoot, entry.path),
1135
+ bytes: entry.bytes,
1136
+ sha256: entry.sha256,
1137
+ })));
1138
+ await finalizeFoundryWorkflow(selected, qualified, before.artifacts, options.authentication, undefined, { sha256: execution.progressSha256, scopes: execution.completed });
1139
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1140
+ }
1141
+ const preparedApproval = workflow.authorization?.value.status === "authorized_current_rows"
1142
+ ? workflow.authorization
1143
+ : workflow.preparedApproval;
1144
+ if (!preparation && preparedApproval && workflow.authorization?.value.status !== "sealed") {
1145
+ if (!qualified)
1146
+ throw new FoundryContextError("runtime_unqualified", "Approval continuation requires qualified runtime owners.");
1147
+ const facts = before.artifacts.map((artifact) => ({
1148
+ path: path.join(context.taskRoot, artifact.path),
1149
+ bytes: artifact.bytes,
1150
+ sha256: artifact.sha256,
1151
+ }));
1152
+ const selected = taskContext(options, current, record, facts);
1153
+ await continueFoundryPreparedApproval(selected, qualified, before.artifacts, preparedApproval, options.authentication);
1154
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1155
+ }
1156
+ const imported = before.artifacts.some((artifact) => artifact.command === "dataset-tidas-import");
1157
+ const contextPrepared = before.artifacts.some((artifact) => artifact.command === "dataset-context-pack");
1158
+ const nativeRows = before.artifacts.filter((artifact) => artifact.command === "dataset-tidas-import" &&
1159
+ artifact.path.endsWith(".json") &&
1160
+ Object.values(datasetTypePlural).includes(/^outputs\/import\/[^/]+\/tidas\/([^/]+)\//u.exec(artifact.path)?.[1] ?? ""));
1161
+ const rowsPrepared = Boolean(workflow.rows);
1162
+ if (!preparation && record.spec.lane === "external-dataset-curated-import" && !imported) {
1163
+ if (record.inputs.length !== 1)
1164
+ throw new FoundryContextError("task_import_source_required", "Select one complete packaged input for native conversion.");
1165
+ await runtime.importPackage(record.inputs[0].path);
1166
+ assertNotInterrupted(options.signal);
1167
+ }
1168
+ else if (!preparation && !contextPrepared) {
1169
+ const closureTypes = Object.entries(datasetTypePlural)
1170
+ .filter(([, plural]) => nativeRows.some((artifact) => artifact.path.includes(`/tidas/${plural}/`)))
1171
+ .map(([type]) => type);
1172
+ await runtime.prepareContext([
1173
+ ...new Set([...record.spec.target_entities, ...closureTypes]),
1174
+ ]);
1175
+ assertNotInterrupted(options.signal);
1176
+ }
1177
+ else if (!preparation && !rowsPrepared) {
1178
+ const facts = record.spec.lane === "external-dataset-curated-import"
1179
+ ? nativeRows.map((artifact) => ({
1180
+ path: path.join(context.taskRoot, artifact.path),
1181
+ bytes: artifact.bytes,
1182
+ sha256: artifact.sha256,
1183
+ }))
1184
+ : record.inputs.filter((fact) => fact.path === sourcePath(record, record.spec.seed.path));
1185
+ const selected = taskContext(options, current, record, facts);
1186
+ await createFoundryRuntime(selected, qualified).materializeRows(facts.map((fact) => fact.path));
1187
+ assertNotInterrupted(options.signal);
1188
+ }
1189
+ else if (!preparation && !workflow.assessment) {
1190
+ const selectedArtifacts = before.artifacts.filter((artifact) => [
1191
+ "dataset-workflow-rows",
1192
+ "dataset-context-pack",
1193
+ "dataset-semantic-apply",
1194
+ "dataset-workflow-identity",
1195
+ ].includes(artifact.command));
1196
+ const facts = selectedArtifacts.map((artifact) => ({
1197
+ path: path.join(context.taskRoot, artifact.path),
1198
+ bytes: artifact.bytes,
1199
+ sha256: artifact.sha256,
1200
+ }));
1201
+ const rows = workflow.rows
1202
+ ? facts.find((fact) => fact.path === workflow.rows.file)
1203
+ : undefined;
1204
+ if (!rows)
1205
+ throw new FoundryContextError("workflow_rows_required", "Registered row preparation is required.");
1206
+ const contracts = facts
1207
+ .filter((fact) => path.basename(fact.path) === "contract-report.json")
1208
+ .map((fact) => fact.path);
1209
+ const selected = taskContext(options, current, record, facts);
1210
+ await createFoundryRuntime(selected, qualified).assessRows(rows.path, contracts, workflow.identity?.value.status === "completed" ? workflow.identity.file : undefined);
1211
+ assertNotInterrupted(options.signal);
1212
+ }
1213
+ else if (!preparation &&
1214
+ (existing.status === "ready" || workflow.identity?.value.status === "blocked") &&
1215
+ (!workflow.identity || workflow.identity.value.status === "blocked") &&
1216
+ workflow.rows?.value.sets.some((set) => ["flow", "process"].includes(set.type))) {
1217
+ if (!qualified)
1218
+ throw new FoundryContextError("runtime_unqualified", "Identity preflight requires qualified runtime owners.");
1219
+ const facts = before.artifacts.map((artifact) => ({
1220
+ path: path.join(context.taskRoot, artifact.path),
1221
+ bytes: artifact.bytes,
1222
+ sha256: artifact.sha256,
1223
+ }));
1224
+ const selected = taskContext(options, current, record, facts);
1225
+ const result = await runFoundryWorkflowIdentity(selected, qualified, before.artifacts, options.authentication);
1226
+ if (result.status !== "completed") {
1227
+ const after = await runtime.inspectTask();
1228
+ return createFoundryOperationResult({
1229
+ operation: "task.resume",
1230
+ status: "needs_input",
1231
+ taskId: record.task_id,
1232
+ artifacts: taskArtifacts(context, after),
1233
+ blockers: [
1234
+ {
1235
+ code: "identity_preflight_requires_input",
1236
+ message: "Review the registered identity preflight diagnostics before continuing.",
1237
+ scope: record.task_id,
1238
+ },
1239
+ ],
1240
+ nextActions: [],
1241
+ runtimeIdentity: runtimeIdentity(context, qualified),
1242
+ permissions: noPermission(),
1243
+ });
1244
+ }
1245
+ }
1246
+ if (!preparation &&
1247
+ existing.status === "ready" &&
1248
+ workflow.assessment &&
1249
+ !workflow.finalization &&
1250
+ (workflow.identity?.value.status === "completed" ||
1251
+ !workflow.rows?.value.sets.some((set) => ["flow", "process"].includes(set.type)))) {
1252
+ if (!qualified)
1253
+ throw new FoundryContextError("runtime_unqualified", "Finalization requires qualified runtime owners.");
1254
+ const facts = before.artifacts.map((artifact) => ({
1255
+ path: path.join(context.taskRoot, artifact.path),
1256
+ bytes: artifact.bytes,
1257
+ sha256: artifact.sha256,
1258
+ }));
1259
+ const selected = taskContext(options, current, record, facts);
1260
+ await finalizeFoundryWorkflow(selected, qualified, before.artifacts, options.authentication);
1261
+ assertNotInterrupted(options.signal);
1262
+ }
1263
+ if (preparation) {
1264
+ assertNotInterrupted(options.signal);
1265
+ await runtime.cleanup({
1266
+ input: sourcePath(record, preparation.input),
1267
+ type: preparation.type,
1268
+ outputDirectory: preparation.output_directory,
1269
+ sourceInput: preparation.source_input
1270
+ ? sourcePath(record, preparation.source_input)
1271
+ : undefined,
1272
+ profileId: record.spec.profile_id,
1273
+ });
1274
+ assertNotInterrupted(options.signal);
1275
+ }
1276
+ const inspected = await runtime.inspectTask();
1277
+ assertNotInterrupted(options.signal);
1278
+ const projected = taskProjection("task.resume", context, record, inspected, runtimeIdentity(context, qualified));
1279
+ if (!preparation)
1280
+ return projected;
1281
+ const artifacts = [...projected.artifacts];
1282
+ const cleaned = artifacts.find((artifact) => artifact.kind === "file" ? /\.cleaned\.jsonl$/u.test(artifact.path) : false);
1283
+ return createFoundryOperationResult({
1284
+ operation: "task.resume",
1285
+ status: projected.status,
1286
+ taskId: record.task_id,
1287
+ artifacts: cleaned
1288
+ ? [
1289
+ Object.freeze({ ...cleaned, role: "cleaned_rows" }),
1290
+ ...artifacts.filter((item) => item !== cleaned),
1291
+ ]
1292
+ : artifacts,
1293
+ blockers: projected.blockers,
1294
+ nextActions: projected.next_actions,
1295
+ runtimeIdentity: projected.runtime_identity,
1296
+ permissions: projected.permissions,
1297
+ });
1298
+ }
1299
+ catch (error) {
1300
+ return failure("task.resume", input.taskId, error, current ? runtimeIdentity(current) : null);
1301
+ }
1302
+ },
1303
+ requestBinding(input) {
1304
+ assertNotInterrupted(options.signal);
1305
+ const current = base();
1306
+ const record = loadFoundryFacadeTaskRecord(current, input.taskId, input.actorId);
1307
+ assertNotInterrupted(options.signal);
1308
+ return sha256Json({
1309
+ workspace_id: current.workspaceId,
1310
+ task_id: record.task_id,
1311
+ revision: record.revision,
1312
+ fingerprint_sha256: record.fingerprint_sha256,
1313
+ cwd: current.workspaceRoot,
1314
+ });
1315
+ },
1316
+ });
1317
+ }