@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,1377 @@
1
+ import path from "node:path";
2
+ import { normalizeTidasLanguageCode } from "../../tidas-language-utils.js";
3
+ import { fullContextAiCompletionRequirement } from "./context-inputs.js";
4
+ import { dataSetInformation, datasetRoot } from "./dataset-payload.js";
5
+ import { sha256Text } from "./hash-utils.js";
6
+ import { annualSupplyMissingDataSentinelText } from "./prewrite-cleanup.js";
7
+ import { asText, ensureArray, fileExists, readJson, repoRelativeArtifactPath, repoRelativePath, resolveRepoPath, } from "./runtime-io.js";
8
+ import { collectCommonOtherTraceEntries } from "./trace-summary.js";
9
+ import { hasNonEmptyTraceEvidence } from "./workflow-authoring-tasks.js";
10
+ import { hasStructuredTraceEvidence } from "./workflow-patch-evidence.js";
11
+ import { isAnnualSupplyTarget } from "./workflow-queue-context.js";
12
+ function isRecord(value) {
13
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function asRecord(value) {
16
+ return isRecord(value) ? value : {};
17
+ }
18
+ function asActionItem(value) {
19
+ return isRecord(value) ? value : {};
20
+ }
21
+ // part-02.mjs
22
+ export function collectTextEntries(value, pathName = "") {
23
+ const entries = [];
24
+ const visit = (node, currentPath) => {
25
+ if (typeof node === "string") {
26
+ entries.push({ path: currentPath, text: node });
27
+ return;
28
+ }
29
+ if (!node || typeof node !== "object")
30
+ return;
31
+ if (Array.isArray(node)) {
32
+ node.forEach((item, index) => visit(item, `${currentPath}[${index}]`));
33
+ return;
34
+ }
35
+ for (const [key, child] of Object.entries(node)) {
36
+ if (key.startsWith("@"))
37
+ continue;
38
+ visit(child, currentPath ? `${currentPath}.${key}` : key);
39
+ }
40
+ };
41
+ visit(value, pathName);
42
+ return entries;
43
+ }
44
+ export function nameCarrier(root, datasetType) {
45
+ const info = dataSetInformation(root, datasetType);
46
+ return info?.name && typeof info.name === "object" ? info.name : {};
47
+ }
48
+ export function nameTextForPayload(payload, datasetType) {
49
+ const root = datasetRoot(payload, datasetType);
50
+ return collectTextEntries(nameCarrier(root, datasetType))
51
+ .map((entry) => entry.text)
52
+ .join(" ");
53
+ }
54
+ export function flowTypeForPayload(payload) {
55
+ const root = datasetRoot(payload, "flow");
56
+ return asText(root?.modellingAndValidation?.LCIMethod?.typeOfDataSet ??
57
+ root?.modellingAndValidation?.LCIMethodAndAllocation?.typeOfDataSet);
58
+ }
59
+ export function flowUsesElementaryClassification(payload) {
60
+ return /^elementary flow$/iu.test(flowTypeForPayload(payload));
61
+ }
62
+ export function flowUsesProductClassification(payload) {
63
+ const type = flowTypeForPayload(payload);
64
+ return /^product flow$/iu.test(type) || /^waste flow$/iu.test(type);
65
+ }
66
+ export function classificationActionPathForPayload(payload, datasetType) {
67
+ if (datasetType === "flow") {
68
+ return flowUsesElementaryClassification(payload)
69
+ ? "flowDataSet.flowInformation.dataSetInformation.classificationInformation.common:elementaryFlowCategorization"
70
+ : "flowDataSet.flowInformation.dataSetInformation.classificationInformation.common:classification";
71
+ }
72
+ return "processDataSet.processInformation.dataSetInformation.classificationInformation.common:classification";
73
+ }
74
+ export function classificationEntriesForPayload(payload, datasetType) {
75
+ const root = datasetRoot(payload, datasetType);
76
+ const info = dataSetInformation(root, datasetType);
77
+ if (datasetType === "flow") {
78
+ const classificationInformation = info?.classificationInformation ?? {};
79
+ const categories = classificationInformation?.["common:elementaryFlowCategorization"]?.["common:category"] ??
80
+ classificationInformation?.elementaryFlowCategorization?.category ??
81
+ [];
82
+ const classes = classificationInformation?.["common:classification"]?.["common:class"] ??
83
+ classificationInformation?.classification?.class ??
84
+ [];
85
+ const items = flowUsesElementaryClassification(payload) ? categories : classes;
86
+ return ensureArray(items)
87
+ .filter((entry) => entry && typeof entry === "object")
88
+ .map((entry, index) => ({
89
+ index,
90
+ level: asText(entry["@level"]),
91
+ class_id: asText(entry["@classId"] ?? entry["@catId"]),
92
+ text: asText(entry["#text"]),
93
+ }));
94
+ }
95
+ const classes = info?.classificationInformation?.["common:classification"]?.["common:class"] ??
96
+ info?.classificationInformation?.classification?.class ??
97
+ [];
98
+ return ensureArray(classes)
99
+ .filter((entry) => entry && typeof entry === "object")
100
+ .map((entry, index) => ({
101
+ index,
102
+ level: asText(entry["@level"]),
103
+ class_id: asText(entry["@classId"] ?? entry["@catId"]),
104
+ text: asText(entry["#text"]),
105
+ }));
106
+ }
107
+ export function classificationPathForPayload(payload, datasetType) {
108
+ return classificationEntriesForPayload(payload, datasetType)
109
+ .map((entry) => entry.text)
110
+ .filter(Boolean)
111
+ .join(" > ");
112
+ }
113
+ export function processExchangeList(payload) {
114
+ const root = datasetRoot(payload, "process");
115
+ return ensureArray(root?.exchanges?.exchange).filter(isRecord);
116
+ }
117
+ export function hasFoundryOtherEvidence(value, evidenceKey, acceptedStatuses = []) {
118
+ let found = false;
119
+ const accepted = new Set(acceptedStatuses.map((status) => String(status).toLowerCase()));
120
+ const visit = (node) => {
121
+ if (found || !node || typeof node !== "object")
122
+ return;
123
+ if (Array.isArray(node)) {
124
+ for (const item of node)
125
+ visit(item);
126
+ return;
127
+ }
128
+ const record = node;
129
+ const other = record["common:other"];
130
+ if (other && typeof other === "object" && !Array.isArray(other)) {
131
+ const evidence = other[evidenceKey];
132
+ if (evidence !== undefined) {
133
+ if (accepted.size === 0) {
134
+ found = true;
135
+ return;
136
+ }
137
+ for (const item of ensureArray(evidence)) {
138
+ const typedItem = asRecord(item);
139
+ const status = asText(typedItem.status ?? typedItem.decision_status ?? typedItem.decisionStatus);
140
+ if (status && accepted.has(status.toLowerCase())) {
141
+ found = true;
142
+ return;
143
+ }
144
+ }
145
+ }
146
+ }
147
+ for (const child of Object.values(record))
148
+ visit(child);
149
+ };
150
+ visit(value);
151
+ return found;
152
+ }
153
+ export function semanticActionItem({ code, path: itemPath, message, evidence, instruction, common_other_deferral_allowed = false, action_kind = "ai_authoring", }) {
154
+ return {
155
+ source: "profile_semantic_gate",
156
+ code,
157
+ path: itemPath ?? null,
158
+ message,
159
+ evidence: evidence ?? null,
160
+ instruction,
161
+ action_kind,
162
+ required_owner: "foundry_ai_authoring",
163
+ ai_required: true,
164
+ common_other_deferral_allowed,
165
+ };
166
+ }
167
+ export function textValue(value) {
168
+ if (value === undefined || value === null)
169
+ return "";
170
+ if (typeof value === "string")
171
+ return value.trim();
172
+ if (typeof value === "number" || typeof value === "boolean")
173
+ return String(value);
174
+ if (Array.isArray(value))
175
+ return value.map(textValue).filter(Boolean).join(" | ");
176
+ if (typeof value !== "object")
177
+ return "";
178
+ const record = value;
179
+ const direct = record["#text"] ?? record.text ?? record.value;
180
+ if (direct !== undefined && direct !== value)
181
+ return textValue(direct);
182
+ return Object.entries(record)
183
+ .filter(([key]) => !key.startsWith("@"))
184
+ .map(([, child]) => textValue(child))
185
+ .filter(Boolean)
186
+ .join(" | ");
187
+ }
188
+ export function isPlaceholderishText(value, { allowNone = false } = {}) {
189
+ const text = textValue(value);
190
+ if (!text)
191
+ return true;
192
+ if (allowNone && /^none$/iu.test(text))
193
+ return false;
194
+ return /^(na|n\/a|not specified|not declared|unspecified|undefined|-|--|unknown)$/iu.test(text);
195
+ }
196
+ export function hasMeaningfulFieldValue(value) {
197
+ return !isPlaceholderishText(value);
198
+ }
199
+ export function sourceTracePayloads(value) {
200
+ const payloads = [];
201
+ const visit = (node) => {
202
+ if (!node || typeof node !== "object")
203
+ return;
204
+ if (Array.isArray(node)) {
205
+ for (const item of node)
206
+ visit(item);
207
+ return;
208
+ }
209
+ const record = node;
210
+ const trace = record["tidasimport:sourceTrace"];
211
+ if (isRecord(trace) && trace.payload) {
212
+ payloads.push(trace.payload);
213
+ }
214
+ for (const child of Object.values(record))
215
+ visit(child);
216
+ };
217
+ visit(value);
218
+ return payloads;
219
+ }
220
+ export function traceObjectsNamed(value, names) {
221
+ const wanted = new Set(ensureArray(names)
222
+ .map((name) => asText(name))
223
+ .filter(Boolean));
224
+ const found = [];
225
+ const visit = (node, pathParts = []) => {
226
+ if (!node || typeof node !== "object")
227
+ return;
228
+ if (Array.isArray(node)) {
229
+ node.forEach((item, index) => visit(item, [...pathParts, String(index)]));
230
+ return;
231
+ }
232
+ const record = node;
233
+ const name = asText(record.name);
234
+ if (wanted.has(name) && Array.isArray(record.attributes)) {
235
+ found.push({ node: record, trace_path: pathParts.join(".") || "<root>" });
236
+ }
237
+ for (const [key, child] of Object.entries(record))
238
+ visit(child, [...pathParts, key]);
239
+ };
240
+ for (const payload of ensureArray(value))
241
+ visit(payload);
242
+ return found;
243
+ }
244
+ export function traceAttributeMap(traceObject) {
245
+ const record = asRecord(traceObject);
246
+ return new Map(ensureArray(record.attributes)
247
+ .map((attribute) => {
248
+ const typedAttribute = asRecord(attribute);
249
+ return [asText(typedAttribute.name), textValue(typedAttribute.value)];
250
+ })
251
+ .filter(([name, value]) => Boolean(name && value)));
252
+ }
253
+ export function firstTraceAttribute(payloads, objectNames, attributeNames, options = {}) {
254
+ const names = ensureArray(attributeNames)
255
+ .map((name) => asText(name))
256
+ .filter(Boolean);
257
+ for (const traceObject of traceObjectsNamed(payloads, objectNames)) {
258
+ const attributes = traceAttributeMap(traceObject.node);
259
+ for (const name of names) {
260
+ const value = attributes.get(name);
261
+ if (value && !isPlaceholderishText(value, options)) {
262
+ return {
263
+ object_name: asText(traceObject.node.name),
264
+ attribute_name: name,
265
+ value,
266
+ trace_path: traceObject.trace_path,
267
+ };
268
+ }
269
+ }
270
+ }
271
+ return null;
272
+ }
273
+ export function sourceTraceLanguage(payloads, fallback = "en") {
274
+ const rawLanguage = (firstTraceAttribute(payloads, "dataSetInformation", "localLanguageCode")?.value ||
275
+ firstTraceAttribute(payloads, "dataSetInformation", "languageCode")?.value ||
276
+ fallback)
277
+ .slice(0, 8)
278
+ .toLowerCase();
279
+ return normalizeTidasLanguageCode(rawLanguage, { field: "source trace language" });
280
+ }
281
+ export function multiLangSuggestion(value, language = "en") {
282
+ return {
283
+ "@xml:lang": normalizeTidasLanguageCode(language),
284
+ "#text": textValue(value),
285
+ };
286
+ }
287
+ export function sourceTraceEvidence(attribute, extra = {}) {
288
+ return {
289
+ source: "tidasimport:sourceTrace",
290
+ trace_path: attribute?.trace_path ?? null,
291
+ object_name: attribute?.object_name ?? null,
292
+ attribute_name: attribute?.attribute_name ?? null,
293
+ value: attribute?.value ?? null,
294
+ ...extra,
295
+ };
296
+ }
297
+ export function locationCodeCandidate(value) {
298
+ const text = textValue(value);
299
+ if (!text)
300
+ return null;
301
+ const normalized = text.replace(/[{}]/gu, "").trim();
302
+ if (/^RoW$/u.test(normalized))
303
+ return normalized;
304
+ if (/^[A-Z0-9]{2,}(?:[-+&][A-Z0-9]{2,})*$/u.test(normalized)) {
305
+ return normalized;
306
+ }
307
+ return null;
308
+ }
309
+ export function flowNameLocationEvidence(root) {
310
+ const flowInformation = asRecord(root.flowInformation);
311
+ const dataSetInfo = asRecord(flowInformation.dataSetInformation);
312
+ const name = asRecord(dataSetInfo.name);
313
+ const value = name.mixAndLocationTypes;
314
+ const code = locationCodeCandidate(value);
315
+ if (!code)
316
+ return null;
317
+ return {
318
+ source: "flowDataSet.flowInformation.dataSetInformation.name.mixAndLocationTypes",
319
+ source_kind: "flow_name_mix_and_location_types",
320
+ value: textValue(value),
321
+ suggested_value: code,
322
+ };
323
+ }
324
+ export function nameFieldPath(datasetType, field) {
325
+ const prefix = datasetType === "flow"
326
+ ? "flowDataSet.flowInformation.dataSetInformation.name"
327
+ : datasetType === "lifecyclemodel"
328
+ ? "lifeCycleModelDataSet.lifeCycleModelInformation.dataSetInformation.name"
329
+ : "processDataSet.processInformation.dataSetInformation.name";
330
+ return `${prefix}.${field}`;
331
+ }
332
+ // A trailing "{LOC}" brace in baseName that merely restates the dataset location
333
+ // (mixAndLocationTypes) is redundant, not an unsplit qualifier. Strip it before the
334
+ // base-segment scan so it does not raise a false
335
+ // `semantic_name_base_contains_unsplit_segments` finding (which would otherwise force an
336
+ // unsupported name split, e.g. "Tyre wear emissions, passenger car {RER}" with
337
+ // mixAndLocationTypes "RER"). Genuine qualifier braces, or location braces that do NOT
338
+ // match the dataset location, are left in place and still flagged.
339
+ function stripRedundantTrailingLocationBrace(baseName, mix) {
340
+ const text = String(baseName ?? "").trim();
341
+ const match = /\{(?<code>[A-Z0-9][A-Z0-9+&-]*)\}\s*$/u.exec(text);
342
+ if (!match?.groups?.code)
343
+ return text;
344
+ const mixCode = locationCodeCandidate(mix);
345
+ if (!mixCode)
346
+ return text;
347
+ const braceCode = locationCodeCandidate(match.groups.code);
348
+ if (!braceCode || braceCode !== mixCode)
349
+ return text;
350
+ return text.slice(0, match.index).trim();
351
+ }
352
+ export function namePlanQualityFindings(name) {
353
+ const typedName = asRecord(name);
354
+ const baseName = textValue(typedName.baseName);
355
+ const treatment = textValue(typedName.treatmentStandardsRoutes);
356
+ const mix = textValue(typedName.mixAndLocationTypes);
357
+ const quantitative = textValue(typedName.functionalUnitFlowProperties) || textValue(typedName.flowProperties);
358
+ const findings = [];
359
+ const sourceLocatorPatterns = [
360
+ {
361
+ kind: "latin-author-year",
362
+ // Season/period qualifiers ("summer 2018") are temporal scope, not citations.
363
+ regex: /\b(?!(?:summer|winter|spring|autumn|fall)\s)[A-Z][A-Za-z]+(?:\s+et\s+al\.)?\s+(?:19|20)\d{2}\b/iu,
364
+ },
365
+ {
366
+ kind: "cjk-author-year",
367
+ regex: /[\p{Script=Han}·]{2,12}\s*(?:19|20)\d{2}/u,
368
+ },
369
+ {
370
+ kind: "numbered-table",
371
+ regex: /\b(?:Table|Tbl\.)\s*\d+[A-Za-z]?\b/iu,
372
+ },
373
+ {
374
+ kind: "numbered-table-cjk",
375
+ regex: /表\s*\d+/u,
376
+ },
377
+ {
378
+ kind: "numbered-figure",
379
+ regex: /\b(?:Figure|Fig\.)\s*\d+[A-Za-z]?\b/iu,
380
+ },
381
+ {
382
+ kind: "numbered-figure-cjk",
383
+ regex: /图\s*\d+/u,
384
+ },
385
+ ];
386
+ for (const field of [
387
+ ["baseName", baseName],
388
+ ["treatmentStandardsRoutes", treatment],
389
+ ["mixAndLocationTypes", mix],
390
+ ["functionalUnitFlowProperties", quantitative],
391
+ ]) {
392
+ const [fieldName, text] = field;
393
+ if (!text)
394
+ continue;
395
+ const matches = sourceLocatorPatterns
396
+ .filter((pattern) => pattern.regex.test(text))
397
+ .map((pattern) => pattern.kind);
398
+ if (matches.length === 0)
399
+ continue;
400
+ findings.push({
401
+ code: "semantic_name_source_locator_in_name",
402
+ field: fieldName,
403
+ path_field: fieldName,
404
+ text,
405
+ evidence_kind: "name_plan_source_locator_scan",
406
+ detected_segments: matches,
407
+ });
408
+ }
409
+ const basePatterns = [
410
+ {
411
+ kind: "availability_or_location_phrase",
412
+ regex: /\b(?:at|to)\s+(?:freight ship|ship|plant|user|grid|market|sawmill|refinery|warehouse|consumer|regional storage|power plant|feed mill)\b/iu,
413
+ },
414
+ {
415
+ kind: "mix_phrase",
416
+ regex: /\b(?:production|market|consumption)\s+mix\b/iu,
417
+ },
418
+ {
419
+ kind: "source_location_after_production",
420
+ regex: /\bproduction\s+[A-Z]{2,3}\b/u,
421
+ },
422
+ {
423
+ kind: "braced_location_or_qualifier",
424
+ regex: /\{[A-Z0-9][A-Z0-9+&-]*\}/u,
425
+ },
426
+ ];
427
+ const baseNameForBaseScan = stripRedundantTrailingLocationBrace(baseName, mix);
428
+ const baseMatches = basePatterns
429
+ .filter((pattern) => pattern.regex.test(baseNameForBaseScan))
430
+ .map((pattern) => pattern.kind);
431
+ if (baseMatches.length > 0) {
432
+ findings.push({
433
+ code: "semantic_name_base_contains_unsplit_segments",
434
+ field: "baseName",
435
+ path_field: "baseName",
436
+ text: baseName,
437
+ evidence_kind: "name_plan_base_segment_scan",
438
+ detected_segments: baseMatches,
439
+ });
440
+ }
441
+ const quantitativeBaseMatches = [
442
+ // "wet & dry processes" is a manufacturing-route phrase (fibreboard), not a moisture state.
443
+ /\b(?:wet(?!\s*&\s*dry|\s+and\s+dry)|dry mass|measured as dry mass|moisture|water content|allocation exergy)\b/iu,
444
+ /\b(?:net calorific value|gross calorific value|lower heating value|upper heating value)\b/iu,
445
+ ]
446
+ .filter((regex) => regex.test(baseName))
447
+ .map((regex) => regex.source);
448
+ const quantitativeContainsSpecificQualifier = /\b(?:wet(?!\s*&\s*dry|\s+and\s+dry)|dry mass|measured as dry mass|moisture|water content|allocation exergy|net calorific value|gross calorific value|lower heating value|upper heating value)\b/iu.test(quantitative);
449
+ if (quantitativeBaseMatches.length > 0 && !quantitativeContainsSpecificQualifier) {
450
+ findings.push({
451
+ code: "semantic_name_quantitative_property_not_split",
452
+ field: "baseName",
453
+ path_field: "baseName",
454
+ text: baseName,
455
+ evidence_kind: "name_plan_quantitative_segment_scan",
456
+ detected_segments: quantitativeBaseMatches,
457
+ });
458
+ }
459
+ if (/^source-described route$/iu.test(treatment)) {
460
+ findings.push({
461
+ code: "semantic_name_treatment_placeholder",
462
+ field: "treatmentStandardsRoutes",
463
+ path_field: "treatmentStandardsRoutes",
464
+ text: treatment,
465
+ evidence_kind: "name_plan_placeholder_scan",
466
+ });
467
+ }
468
+ const mixCode = locationCodeCandidate(mix);
469
+ if (mixCode && mix === mixCode) {
470
+ findings.push({
471
+ code: "semantic_name_mix_location_too_bare",
472
+ field: "mixAndLocationTypes",
473
+ path_field: "mixAndLocationTypes",
474
+ text: mix,
475
+ evidence_kind: "name_plan_mix_location_scan",
476
+ location_code_candidate: mixCode,
477
+ });
478
+ }
479
+ return findings;
480
+ }
481
+ export function collectNamePlanQualitySemanticActions(payload, datasetType) {
482
+ if (!["flow", "process", "lifecyclemodel"].includes(datasetType))
483
+ return [];
484
+ const root = datasetRoot(payload, datasetType);
485
+ const name = nameCarrier(root, datasetType);
486
+ const findings = namePlanQualityFindings(name);
487
+ return findings.map((finding) => semanticActionItem({
488
+ code: finding.code,
489
+ path: nameFieldPath(datasetType, finding.path_field),
490
+ message: finding.code === "semantic_name_treatment_placeholder"
491
+ ? "name.treatmentStandardsRoutes still contains the generated placeholder source-described route."
492
+ : finding.code === "semantic_name_mix_location_too_bare"
493
+ ? "name.mixAndLocationTypes contains only a bare location code; the name plan should include the availability/mix/location-type phrase and keep the code in the formal geography/location field."
494
+ : finding.code === "semantic_name_source_locator_in_name"
495
+ ? "name contains source citation or source-locator text that belongs in provenance, source references, or source-backed property evidence rather than the dataset name."
496
+ : finding.code === "semantic_name_quantitative_property_not_split"
497
+ ? "name.baseName contains quantitative or allocation qualifiers that should be split into the formal name property field when source-backed."
498
+ : "name.baseName contains route, mix, availability, or location segments that should be split into the structured TIDAS name fields.",
499
+ evidence: {
500
+ ...finding,
501
+ current_name: {
502
+ baseName: textValue(name?.baseName) || null,
503
+ treatmentStandardsRoutes: textValue(name?.treatmentStandardsRoutes) || null,
504
+ mixAndLocationTypes: textValue(name?.mixAndLocationTypes) || null,
505
+ functionalUnitFlowProperties: textValue(name?.functionalUnitFlowProperties) ||
506
+ textValue(name?.flowProperties) ||
507
+ null,
508
+ },
509
+ },
510
+ instruction: "Use the source-language name-plan workflow and full source context to split the name once: baseName keeps only the core product/process/service name; treatmentStandardsRoutes receives production/treatment/route qualifiers; mixAndLocationTypes receives availability, mix, and location-type phrases such as at plant {CH}; functionalUnitFlowProperties or flowProperties receives quantitative qualifiers. Preserve the original full source name in provenance/mapping, not in baseName.",
511
+ }));
512
+ }
513
+ export function sourceTraceLocationEvidence(traces) {
514
+ const candidates = [
515
+ firstTraceAttribute(traces, "exchange", "location"),
516
+ firstTraceAttribute(traces, ["flow", "flowInformation", "dataSetInformation"], ["locationOfSupply", "mixAndLocationTypes", "location"]),
517
+ firstTraceAttribute(traces, ["process", "processInformation", "geography"], ["locationOfOperationSupplyOrProduction", "@location", "location"]),
518
+ ].filter((candidate) => candidate !== null);
519
+ if (candidates.length === 0)
520
+ return null;
521
+ const primary = candidates[0];
522
+ return sourceTraceEvidence(primary, {
523
+ suggested_value: locationCodeCandidate(primary.value) ?? primary.value,
524
+ candidate_sources: candidates.map((candidate) => ({
525
+ object_name: candidate.object_name,
526
+ attribute_name: candidate.attribute_name,
527
+ value: candidate.value,
528
+ trace_path: candidate.trace_path,
529
+ location_code_candidate: locationCodeCandidate(candidate.value),
530
+ })),
531
+ });
532
+ }
533
+ export function collectTextQualitySemanticActions(payload, datasetType) {
534
+ const entries = collectTextEntries(payload);
535
+ const actions = [];
536
+ const seen = new Set();
537
+ const add = (item) => {
538
+ const key = JSON.stringify([item.code, item.path, item.message]);
539
+ if (seen.has(key))
540
+ return;
541
+ seen.add(key);
542
+ actions.push(item);
543
+ };
544
+ for (const entry of entries) {
545
+ const text = entry.text.trim();
546
+ if (!text)
547
+ continue;
548
+ const pathLower = entry.path.toLowerCase();
549
+ const isNameLike = pathLower.includes(".name.") ||
550
+ pathLower.endsWith(".common:shortdescription.#text") ||
551
+ pathLower.endsWith(".common:shortname.#text") ||
552
+ pathLower.endsWith(".common:name.#text") ||
553
+ pathLower.includes("functionalunitorother");
554
+ if (/__AI_FILL_[A-Z0-9_]*__|TIDAS_IMPORT_PLACEHOLDER|UNSPECIFIED_TEXT|Not declared in source package|placeholder\.example|pending-confirmation/iu.test(text)) {
555
+ add(semanticActionItem({
556
+ code: "semantic_placeholder_text",
557
+ path: entry.path,
558
+ message: "Payload contains placeholder or unresolved import text that schema validation alone cannot accept.",
559
+ evidence: { text },
560
+ instruction: "Use the full schema/YAML/context authoring package to replace this with source-language content, or move unresolved provenance into common:other when schema permits.",
561
+ }));
562
+ }
563
+ if (/\bxx\b/iu.test(text) && isNameLike) {
564
+ add(semanticActionItem({
565
+ code: "semantic_name_placeholder_token",
566
+ path: entry.path,
567
+ message: 'Name-like text contains the placeholder token "xx".',
568
+ evidence: { text },
569
+ instruction: "Derive a source-language name plan from source evidence and TIDAS name YAML semantics; do not keep placeholder tokens in final name fields.",
570
+ }));
571
+ }
572
+ if (/\{[A-Z]{2,3}\}/u.test(text) && isNameLike) {
573
+ add(semanticActionItem({
574
+ code: "semantic_geography_token_in_name",
575
+ path: entry.path,
576
+ message: "Name-like text contains a geography token such as {GLO}; geography belongs in the geography/location fields or name-plan mix/location segment as defined by the contract.",
577
+ evidence: { text },
578
+ instruction: "Use the full schema/YAML/context authoring package to split geography out of base names and materialize display names from proper fields.",
579
+ }));
580
+ }
581
+ if (/\bBAFU ecoSpold1 source\b/iu.test(text) &&
582
+ /\b(Not specified|No |not declared|is specified)\b/iu.test(text)) {
583
+ add(semanticActionItem({
584
+ code: "semantic_source_system_boilerplate_visible",
585
+ path: entry.path,
586
+ message: "User-facing text contains source-system boilerplate. Source-system details should be evidence/provenance, not visible filler.",
587
+ evidence: { text },
588
+ instruction: 'Use neutral source-language text such as "Not specified" when the schema requires content; preserve BAFU/ecoSpold provenance in evidence or common:other.',
589
+ common_other_deferral_allowed: true,
590
+ }));
591
+ }
592
+ if (/\/Users\/|\.zip:|LCI ecoSpold version2 Files/iu.test(text)) {
593
+ add(semanticActionItem({
594
+ code: "semantic_local_source_path_visible",
595
+ path: entry.path,
596
+ message: "Payload contains local source path or package trace text in a visible field.",
597
+ evidence: { text },
598
+ instruction: "Move local/package trace to authoring evidence or safe common:other provenance before remote write.",
599
+ common_other_deferral_allowed: true,
600
+ }));
601
+ }
602
+ }
603
+ return actions.map((item) => ({ ...item, dataset_type: datasetType }));
604
+ }
605
+ export function isBafuConvertedDefaultProcessClassification(classificationPath) {
606
+ return /Other service activities\s*>\s*Activities of membership organizations\s*>\s*Activities of other membership organizations\s*>\s*Activities of other membership organizations n\.e\.c\.|Community,\s*social and personal services\s*>\s*Sewage and waste collection,\s*treatment and disposal and other environmental protection services\s*>\s*Other environmental protection services n\.e\.c\./iu.test(classificationPath);
607
+ }
608
+ export function collectClassificationSemanticActions(payload, datasetType, { profile = null, hasClassificationQueueContext = false } = {}) {
609
+ if (!["flow", "process"].includes(datasetType))
610
+ return [];
611
+ const classes = classificationEntriesForPayload(payload, datasetType);
612
+ const classificationPath = classificationPathForPayload(payload, datasetType);
613
+ const nameText = nameTextForPayload(payload, datasetType);
614
+ const actions = [];
615
+ if (classes.length === 0) {
616
+ actions.push(semanticActionItem({
617
+ code: "semantic_classification_missing",
618
+ path: classificationActionPathForPayload(payload, datasetType),
619
+ message: "Dataset is missing target classification information.",
620
+ instruction: "Select the target TianGong/TIDAS classification from full source context and record the decision basis.",
621
+ }));
622
+ return actions;
623
+ }
624
+ const sourceLooksIndustrial = /\b(hydrometallurgical|Li-ion|battery|batteries|Li salt|lithium|processing)\b/iu.test(nameText);
625
+ const sourceLooksWasteTreatment = /\b(disposal|waste treatment|treatment of|treatment,? (?:of )?.*batteries)\b/iu.test(nameText);
626
+ const classificationLooksService = /membership organizations|community, social and personal services|environmental protection services|other service activities/iu.test(classificationPath);
627
+ const classificationLooksWasteTreatment = /waste (?:collection,\s*)?treatment and disposal|waste treatment|hazardous waste treatment|waste treatment services/iu.test(classificationPath);
628
+ if (!hasClassificationQueueContext &&
629
+ (datasetType === "process" ||
630
+ (datasetType === "flow" && flowUsesProductClassification(payload))) &&
631
+ asText(profile?.id).toLowerCase() === "bafu" &&
632
+ isBafuConvertedDefaultProcessClassification(classificationPath)) {
633
+ actions.push(semanticActionItem({
634
+ code: "semantic_classification_converted_default",
635
+ path: classificationActionPathForPayload(payload, datasetType),
636
+ message: `BAFU ${datasetType} classification still has the converter default service path and must be replaced with a target TIDAS classification.`,
637
+ evidence: {
638
+ name_text: nameText,
639
+ classification_path: classificationPath,
640
+ },
641
+ instruction: `Use the BAFU source context, classification queue/candidates when available, and the full schema/YAML/context package to choose the target TianGong/TIDAS ${datasetType} classification.`,
642
+ }));
643
+ }
644
+ if (sourceLooksIndustrial &&
645
+ classificationLooksService &&
646
+ !(sourceLooksWasteTreatment && classificationLooksWasteTreatment)) {
647
+ actions.push(semanticActionItem({
648
+ code: "semantic_classification_mismatch",
649
+ path: datasetType === "flow"
650
+ ? "flowDataSet.flowInformation.dataSetInformation.classificationInformation.common:classification"
651
+ : "processDataSet.processInformation.dataSetInformation.classificationInformation.common:classification",
652
+ message: "The selected classification appears to be copied from source/converted data and does not match the dataset semantics.",
653
+ evidence: {
654
+ name_text: nameText,
655
+ classification_path: classificationPath,
656
+ },
657
+ instruction: "Use the classification command/candidates and full schema/YAML/context package to choose a target TianGong/TIDAS classification, and keep source classification only as provenance.",
658
+ }));
659
+ }
660
+ return actions;
661
+ }
662
+ export function effectiveContentDatasetType(payload, datasetType) {
663
+ const record = asRecord(payload);
664
+ if (record.processDataSet)
665
+ return "process";
666
+ if (record.flowDataSet)
667
+ return "flow";
668
+ if (record.sourceDataSet)
669
+ return "source";
670
+ if (record.contactDataSet)
671
+ return "contact";
672
+ return datasetType;
673
+ }
674
+ export function contentSaturationAction({ datasetType, code, path: itemPath, message, evidence, instruction, common_other_deferral_allowed = false, }) {
675
+ return {
676
+ ...semanticActionItem({
677
+ code,
678
+ path: itemPath,
679
+ message,
680
+ evidence,
681
+ instruction,
682
+ common_other_deferral_allowed,
683
+ }),
684
+ dataset_type: datasetType,
685
+ saturation_gate: true,
686
+ };
687
+ }
688
+ export function collectProcessContentSaturationActions(payload) {
689
+ const root = datasetRoot(payload, "process");
690
+ const info = root?.processInformation?.dataSetInformation ?? {};
691
+ const representativeness = root?.modellingAndValidation?.dataSourcesTreatmentAndRepresentativeness ?? {};
692
+ const traces = sourceTracePayloads(payload);
693
+ if (traces.length === 0)
694
+ return [];
695
+ const actions = [];
696
+ const localName = firstTraceAttribute(traces, "referenceFunction", "localName");
697
+ if (localName && !hasMeaningfulFieldValue(info["common:synonyms"])) {
698
+ const language = sourceTraceLanguage(traces, "de");
699
+ actions.push(contentSaturationAction({
700
+ datasetType: "process",
701
+ code: "semantic_content_saturation_process_synonyms_missing",
702
+ path: "processDataSet.processInformation.dataSetInformation.common:synonyms",
703
+ message: "Source trace contains a local/alternative process name, but process synonyms are empty.",
704
+ evidence: sourceTraceEvidence(localName, {
705
+ suggested_value: multiLangSuggestion(localName.value, language),
706
+ }),
707
+ instruction: "Use source trace and TIDAS process schema semantics to add the source-local process name as common:synonyms. Preserve the source language; do not invent translations.",
708
+ }));
709
+ }
710
+ const percent = firstTraceAttribute(traces, "representativeness", "percent");
711
+ if (percent && !hasMeaningfulFieldValue(representativeness.percentageSupplyOrProductionCovered)) {
712
+ actions.push(contentSaturationAction({
713
+ datasetType: "process",
714
+ code: "semantic_content_saturation_process_percentage_missing",
715
+ path: "processDataSet.modellingAndValidation.dataSourcesTreatmentAndRepresentativeness.percentageSupplyOrProductionCovered",
716
+ message: "Source trace contains representativeness.percent, but percentageSupplyOrProductionCovered is empty.",
717
+ evidence: sourceTraceEvidence(percent, { suggested_value: percent.value }),
718
+ instruction: "Fill percentageSupplyOrProductionCovered from representativeness.percent when the value is physically meaningful for the represented market/location.",
719
+ }));
720
+ }
721
+ const uncertaintyAdjustments = firstTraceAttribute(traces, "representativeness", "uncertaintyAdjustments", { allowNone: true });
722
+ if (uncertaintyAdjustments &&
723
+ !hasMeaningfulFieldValue(representativeness.uncertaintyAdjustments)) {
724
+ actions.push(contentSaturationAction({
725
+ datasetType: "process",
726
+ code: "semantic_content_saturation_process_uncertainty_adjustments_missing",
727
+ path: "processDataSet.modellingAndValidation.dataSourcesTreatmentAndRepresentativeness.uncertaintyAdjustments",
728
+ message: "Source trace contains uncertainty adjustment information, but uncertaintyAdjustments is empty.",
729
+ evidence: sourceTraceEvidence(uncertaintyAdjustments, {
730
+ suggested_value: multiLangSuggestion(uncertaintyAdjustments.value, "en"),
731
+ }),
732
+ instruction: "Fill uncertaintyAdjustments from source trace when the source explicitly states a value such as none; preserve source wording.",
733
+ }));
734
+ }
735
+ return actions;
736
+ }
737
+ export function flowReferencePropertyNames(root) {
738
+ const flowProperties = asRecord(root.flowProperties);
739
+ return ensureArray(flowProperties.flowProperty)
740
+ .map((property) => {
741
+ const reference = asRecord(asRecord(property).referenceToFlowPropertyDataSet);
742
+ return textValue(reference["common:shortDescription"] ?? reference.shortDescription);
743
+ })
744
+ .filter(Boolean);
745
+ }
746
+ export function collectFlowContentSaturationActions(payload) {
747
+ const root = datasetRoot(payload, "flow");
748
+ const info = root?.flowInformation?.dataSetInformation ?? {};
749
+ const traces = sourceTracePayloads(payload);
750
+ const actions = [];
751
+ const locationEvidence = sourceTraceLocationEvidence(traces) ?? flowNameLocationEvidence(root);
752
+ if (locationEvidence &&
753
+ !hasMeaningfulFieldValue(root?.flowInformation?.geography?.locationOfSupply)) {
754
+ actions.push(contentSaturationAction({
755
+ datasetType: "flow",
756
+ code: "semantic_content_saturation_flow_location_of_supply_missing",
757
+ path: "flowDataSet.flowInformation.geography.locationOfSupply",
758
+ message: "Flow context contains a location-of-supply candidate, but flow locationOfSupply is empty.",
759
+ evidence: locationEvidence,
760
+ instruction: "Fill locationOfSupply with the source-backed TIDAS/ILCD location code when the candidate is valid. If the candidate is not a valid code or conflicts with process/exchange geography, keep the scope blocked for location authoring.",
761
+ }));
762
+ }
763
+ const propertyNames = flowReferencePropertyNames(root);
764
+ if (propertyNames.length > 0 && !hasMeaningfulFieldValue(info.name?.flowProperties)) {
765
+ actions.push(contentSaturationAction({
766
+ datasetType: "flow",
767
+ code: "semantic_content_saturation_flow_quantitative_properties_missing",
768
+ path: "flowDataSet.flowInformation.dataSetInformation.name.flowProperties",
769
+ message: "Flow reference property evidence exists, but the name.flowProperties descriptor is empty.",
770
+ evidence: {
771
+ source: "flowDataSet.flowProperties.flowProperty.referenceToFlowPropertyDataSet",
772
+ reference_flow_properties: propertyNames,
773
+ suggested_value: multiLangSuggestion(propertyNames.join(", "), "en"),
774
+ },
775
+ instruction: "Fill the TIDAS flow name.flowProperties descriptor from the referenced quantitative flow property names when the values are not redundant with the base name.",
776
+ }));
777
+ }
778
+ const generalComment = firstTraceAttribute(traces, "exchange", "generalComment", {
779
+ allowNone: true,
780
+ });
781
+ if (generalComment && !hasMeaningfulFieldValue(info["common:generalComment"])) {
782
+ actions.push(contentSaturationAction({
783
+ datasetType: "flow",
784
+ code: "semantic_content_saturation_flow_general_comment_missing",
785
+ path: "flowDataSet.flowInformation.dataSetInformation.common:generalComment",
786
+ message: "Source trace contains exchange.generalComment, but flow generalComment is empty.",
787
+ evidence: sourceTraceEvidence(generalComment, {
788
+ suggested_value: multiLangSuggestion(generalComment.value, "en"),
789
+ }),
790
+ instruction: "Promote source-backed exchange generalComment into the product/waste flow comment when it describes the flow meaning, assumptions, or geography; otherwise preserve a structured reason in patch evidence.",
791
+ }));
792
+ }
793
+ return actions;
794
+ }
795
+ export function collectSourceContentSaturationActions(payload) {
796
+ const root = datasetRoot(payload, "source");
797
+ const info = root?.sourceInformation?.dataSetInformation ?? {};
798
+ const traces = sourceTracePayloads(payload);
799
+ if (traces.length === 0)
800
+ return [];
801
+ const sourceObjects = traceObjectsNamed(traces, "source");
802
+ if (sourceObjects.length === 0)
803
+ return [];
804
+ const description = textValue(info.sourceDescriptionOrComment);
805
+ const requiredAttributes = [
806
+ "firstAuthor",
807
+ "additionalAuthors",
808
+ "year",
809
+ "title",
810
+ "titleOfAnthology",
811
+ "placeOfPublications",
812
+ "publisher",
813
+ "volumeNo",
814
+ ];
815
+ const missing = [];
816
+ for (const traceObject of sourceObjects) {
817
+ const attributes = traceAttributeMap(traceObject.node);
818
+ for (const attributeName of requiredAttributes) {
819
+ const value = attributes.get(attributeName);
820
+ if (!value || isPlaceholderishText(value))
821
+ continue;
822
+ if (!description.toLowerCase().includes(value.toLowerCase())) {
823
+ missing.push({
824
+ object_name: asText(traceObject.node.name),
825
+ attribute_name: attributeName,
826
+ value,
827
+ trace_path: traceObject.trace_path,
828
+ });
829
+ }
830
+ }
831
+ }
832
+ if (missing.length === 0)
833
+ return [];
834
+ return [
835
+ contentSaturationAction({
836
+ datasetType: "source",
837
+ code: "semantic_content_saturation_source_description_incomplete",
838
+ path: "sourceDataSet.sourceInformation.dataSetInformation.sourceDescriptionOrComment",
839
+ message: "Source trace contains bibliographic fields that are not represented in sourceDescriptionOrComment.",
840
+ evidence: {
841
+ source: "tidasimport:sourceTrace",
842
+ missing_bibliographic_fields: missing,
843
+ current_description: description || null,
844
+ },
845
+ instruction: "Expand sourceDescriptionOrComment from the trace-backed bibliographic fields in one evidence-backed patch. Preserve source wording and do not invent DOI/URL values that are absent from context.",
846
+ }),
847
+ ];
848
+ }
849
+ export function collectContactContentSaturationActions(payload, { profile = null } = {}) {
850
+ const root = datasetRoot(payload, "contact");
851
+ const info = root?.contactInformation?.dataSetInformation ?? {};
852
+ if (asText(profile?.id).toLowerCase() !== "bafu")
853
+ return [];
854
+ const name = textValue(info["common:name"] ?? info["common:shortName"]);
855
+ if (!/\b(BAFU|FOEN|Federal Office for the Environment)\b/iu.test(name))
856
+ return [];
857
+ const required = [
858
+ ["WWWAddress", "contactDataSet.contactInformation.dataSetInformation.WWWAddress"],
859
+ ["email", "contactDataSet.contactInformation.dataSetInformation.email"],
860
+ ["telephone", "contactDataSet.contactInformation.dataSetInformation.telephone"],
861
+ ["contactAddress", "contactDataSet.contactInformation.dataSetInformation.contactAddress"],
862
+ [
863
+ "centralContactPoint",
864
+ "contactDataSet.contactInformation.dataSetInformation.centralContactPoint",
865
+ ],
866
+ ].filter(([field]) => !hasMeaningfulFieldValue(info[field]));
867
+ if (required.length === 0)
868
+ return [];
869
+ return [
870
+ contentSaturationAction({
871
+ datasetType: "contact",
872
+ code: "semantic_content_saturation_bafu_contact_incomplete",
873
+ path: "contactDataSet.contactInformation.dataSetInformation",
874
+ message: "BAFU/FOEN library contact is missing one or more official contact fields required by the BAFU import profile.",
875
+ evidence: {
876
+ contact_name: name,
877
+ missing_fields: required.map(([field, itemPath]) => ({ field, path: itemPath })),
878
+ profile_source: "docs/import-profiles/bafu/constraints.md",
879
+ },
880
+ instruction: "Fill the shared BAFU/FOEN contact fields from the profile-approved official contact evidence: website, email, telephone, postal address, and central contact point.",
881
+ }),
882
+ ];
883
+ }
884
+ export function collectContentSaturationSemanticActions(payload, datasetType, { profile = null } = {}) {
885
+ const effectiveDatasetType = effectiveContentDatasetType(payload, datasetType);
886
+ if (effectiveDatasetType === "process")
887
+ return collectProcessContentSaturationActions(payload);
888
+ if (effectiveDatasetType === "flow")
889
+ return collectFlowContentSaturationActions(payload);
890
+ if (effectiveDatasetType === "source")
891
+ return collectSourceContentSaturationActions(payload);
892
+ if (effectiveDatasetType === "contact") {
893
+ return collectContactContentSaturationActions(payload, { profile });
894
+ }
895
+ return [];
896
+ }
897
+ export function collectProcessExchangeSemanticActions(payload) {
898
+ const exchanges = processExchangeList(payload);
899
+ if (exchanges.length === 0)
900
+ return [];
901
+ const directions = exchanges.map((exchange) => asText(exchange.exchangeDirection));
902
+ const hasInput = directions.some((direction) => /^input$/iu.test(direction));
903
+ const hasOnlyOutput = directions.length > 0 && directions.every((direction) => /^output$/iu.test(direction));
904
+ if (!hasInput &&
905
+ hasOnlyOutput &&
906
+ !hasFoundryOtherEvidence(payload, "tiangongfoundry:sourceExchangeCompleteness", [
907
+ "source_only_output_exchange_verified",
908
+ "accepted_source_only_output",
909
+ "verified",
910
+ ])) {
911
+ return [
912
+ semanticActionItem({
913
+ code: "semantic_process_only_output_exchange_requires_review",
914
+ path: "processDataSet.exchanges.exchange",
915
+ message: "Process exchanges contain outputs only. This may be source-faithful, but it must be explicitly verified against the source package before remote write.",
916
+ evidence: { exchange_count: exchanges.length, directions },
917
+ instruction: "Analyze source EcoSpold/TIDAS trace in the full authoring package. If source really has only outputs, add evidence under common:other.tiangongfoundry:sourceExchangeCompleteness; otherwise repair the exchange set.",
918
+ }),
919
+ ];
920
+ }
921
+ return [];
922
+ }
923
+ export function collectFoundryTraceSemanticActions(payload, datasetType) {
924
+ const actions = [];
925
+ const add = (item) => actions.push({ ...item, dataset_type: datasetType });
926
+ for (const trace of collectCommonOtherTraceEntries(payload, "tiangongfoundry:unresolvedTrace")) {
927
+ const entry = trace.entry;
928
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
929
+ add(semanticActionItem({
930
+ code: "semantic_unresolved_trace_invalid",
931
+ path: trace.path,
932
+ message: "common:other.tiangongfoundry:unresolvedTrace entries must be structured JSON objects.",
933
+ evidence: { trace: entry ?? null },
934
+ instruction: "Rewrite the unresolved trace with status, action_item_code, blocked_path, reason, evidence, and next_action.",
935
+ common_other_deferral_allowed: true,
936
+ }));
937
+ continue;
938
+ }
939
+ const typedEntry = entry;
940
+ const status = asText(typedEntry.status ?? typedEntry.decision_status ?? typedEntry.decisionStatus);
941
+ const actionCode = asText(typedEntry.action_item_code ?? typedEntry.actionItemCode ?? typedEntry.code);
942
+ const blockedPath = asText(typedEntry.blocked_path ??
943
+ typedEntry.blockedPath ??
944
+ typedEntry.field_path ??
945
+ typedEntry.fieldPath ??
946
+ typedEntry.path);
947
+ const reason = asText(typedEntry.reason ?? typedEntry.deferred_reason ?? typedEntry.deferredReason);
948
+ const nextAction = asText(typedEntry.next_action ??
949
+ typedEntry.nextAction ??
950
+ typedEntry.follow_up ??
951
+ typedEntry.followUp);
952
+ const evidence = typedEntry.evidence ?? typedEntry.source_evidence ?? typedEntry.sourceEvidence;
953
+ const invalidReasons = [];
954
+ if (!["unresolved_deferred", "deferred_to_common_other", "needs_followup"].includes(status)) {
955
+ invalidReasons.push("status");
956
+ }
957
+ if (!actionCode)
958
+ invalidReasons.push("action_item_code");
959
+ if (!blockedPath)
960
+ invalidReasons.push("blocked_path");
961
+ if (!reason)
962
+ invalidReasons.push("reason");
963
+ if (!hasNonEmptyTraceEvidence(evidence)) {
964
+ invalidReasons.push("evidence");
965
+ }
966
+ else if (!hasStructuredTraceEvidence(evidence)) {
967
+ invalidReasons.push("evidence_pointer");
968
+ }
969
+ if (!nextAction)
970
+ invalidReasons.push("next_action");
971
+ if (invalidReasons.length > 0) {
972
+ add(semanticActionItem({
973
+ code: "semantic_unresolved_trace_invalid",
974
+ path: trace.path,
975
+ message: `common:other.tiangongfoundry:unresolvedTrace is missing or has invalid fields: ${invalidReasons.join(", ")}.`,
976
+ evidence: { invalid_fields: invalidReasons, trace: typedEntry },
977
+ instruction: "Rewrite the unresolved trace with status, action_item_code, blocked_path, reason, evidence, and next_action.",
978
+ common_other_deferral_allowed: true,
979
+ }));
980
+ }
981
+ }
982
+ for (const trace of collectCommonOtherTraceEntries(payload, "tiangongfoundry:sourceExchangeCompleteness")) {
983
+ const entry = trace.entry;
984
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
985
+ add(semanticActionItem({
986
+ code: "semantic_source_exchange_trace_invalid",
987
+ path: trace.path,
988
+ message: "common:other.tiangongfoundry:sourceExchangeCompleteness entries must be structured JSON objects.",
989
+ evidence: { trace: entry ?? null },
990
+ instruction: "Rewrite source exchange completeness evidence with accepted status and source trace evidence.",
991
+ common_other_deferral_allowed: true,
992
+ }));
993
+ continue;
994
+ }
995
+ const typedEntry = entry;
996
+ const status = asText(typedEntry.status ?? typedEntry.decision_status ?? typedEntry.decisionStatus);
997
+ const evidence = typedEntry.evidence ??
998
+ typedEntry.source_evidence ??
999
+ typedEntry.sourceEvidence ??
1000
+ typedEntry.trace;
1001
+ const invalidReasons = [];
1002
+ if (!["source_only_output_exchange_verified", "accepted_source_only_output", "verified"].includes(status)) {
1003
+ invalidReasons.push("status");
1004
+ }
1005
+ if (!hasNonEmptyTraceEvidence(evidence)) {
1006
+ invalidReasons.push("evidence");
1007
+ }
1008
+ else if (!hasStructuredTraceEvidence(evidence)) {
1009
+ invalidReasons.push("evidence_pointer");
1010
+ }
1011
+ if (invalidReasons.length > 0) {
1012
+ add(semanticActionItem({
1013
+ code: "semantic_source_exchange_trace_invalid",
1014
+ path: trace.path,
1015
+ message: `common:other.tiangongfoundry:sourceExchangeCompleteness is missing or has invalid fields: ${invalidReasons.join(", ")}.`,
1016
+ evidence: { invalid_fields: invalidReasons, trace: typedEntry },
1017
+ instruction: "Rewrite source exchange completeness evidence with accepted status and source trace evidence.",
1018
+ common_other_deferral_allowed: true,
1019
+ }));
1020
+ }
1021
+ }
1022
+ return actions;
1023
+ }
1024
+ export function collectFlowReuseSemanticActions(payload, datasetType) {
1025
+ if (datasetType !== "flow")
1026
+ return [];
1027
+ if (!flowUsesElementaryClassification(payload))
1028
+ return [];
1029
+ const classification = classificationEntriesForPayload(payload, "flow")
1030
+ .map((entry) => entry.text)
1031
+ .filter(Boolean)
1032
+ .join(" > ");
1033
+ return [
1034
+ semanticActionItem({
1035
+ code: "elementary_flow_requires_existing_database_match",
1036
+ path: "flowDataSet.flowInformation.dataSetInformation",
1037
+ message: "Elementary flow rows cannot be published as BAFU-owned flows. They must be resolved to an existing TianGong database elementary flow before any process that references them can be written.",
1038
+ evidence: {
1039
+ flow_type: flowTypeForPayload(payload) || null,
1040
+ source_flow_name: nameTextForPayload(payload, "flow") || null,
1041
+ source_classification: classification || null,
1042
+ },
1043
+ instruction: "Search TianGong existing elementary flows by UUID/version first, then CAS/name/category/synonyms and structured semantic candidates. Output a mapping to the selected existing flow and rewrite process exchange references. If no defensible existing flow exists, keep the flow unresolved in the mapping queue and block the referencing process write.",
1044
+ action_kind: "identity_decision_authoring",
1045
+ }),
1046
+ ];
1047
+ }
1048
+ export function collectProfileSemanticActionItems({ profile, datasetType, payload, hasClassificationQueueContext = false, }) {
1049
+ const requirement = fullContextAiCompletionRequirement(profile, datasetType);
1050
+ const profileId = asText(profile?.id).toLowerCase();
1051
+ const requiresBafuSupportSemanticGate = profileId === "bafu" && ["support", "contact", "source"].includes(datasetType);
1052
+ if (!requirement && !requiresBafuSupportSemanticGate)
1053
+ return [];
1054
+ return [
1055
+ ...collectTextQualitySemanticActions(payload, datasetType),
1056
+ ...collectNamePlanQualitySemanticActions(payload, datasetType),
1057
+ ...collectClassificationSemanticActions(payload, datasetType, {
1058
+ profile,
1059
+ hasClassificationQueueContext,
1060
+ }),
1061
+ ...collectContentSaturationSemanticActions(payload, datasetType, { profile }),
1062
+ ...collectFlowReuseSemanticActions(payload, datasetType),
1063
+ ...(datasetType === "process" ? collectProcessExchangeSemanticActions(payload) : []),
1064
+ ...collectFoundryTraceSemanticActions(payload, datasetType),
1065
+ ];
1066
+ }
1067
+ export function jsonPointerToken(value) {
1068
+ return String(value).replace(/~/gu, "~0").replace(/\//gu, "~1");
1069
+ }
1070
+ export function dotPathToJsonPointer(value) {
1071
+ const text = asText(value);
1072
+ if (!text || text === "<root>")
1073
+ return "/__AI_FILL_JSON_POINTER__";
1074
+ if (text.startsWith("/"))
1075
+ return text;
1076
+ const normalized = text.replace(/\[(\d+)\]/gu, ".$1").replace(/^\.+|\.+$/gu, "");
1077
+ const tokens = normalized
1078
+ .split(".")
1079
+ .map((token) => token.trim())
1080
+ .filter(Boolean);
1081
+ if (tokens.length === 0)
1082
+ return "/__AI_FILL_JSON_POINTER__";
1083
+ return `/${tokens.map(jsonPointerToken).join("/")}`;
1084
+ }
1085
+ export function actionItemClosure(item) {
1086
+ const typedItem = asActionItem(item);
1087
+ const code = asText(typedItem.code ?? typedItem.rule_id ?? typedItem.ruleId) || "action_item";
1088
+ const itemPath = asText(typedItem.path) || null;
1089
+ return {
1090
+ code,
1091
+ ...(itemPath ? { path: itemPath } : {}),
1092
+ };
1093
+ }
1094
+ export const allowedPatchResolutionModes = new Set([
1095
+ "evidence_backed_completion",
1096
+ "source_language_normalization",
1097
+ "classification_decision",
1098
+ "location_decision",
1099
+ "exchange_set_repaired",
1100
+ "source_trace_verified",
1101
+ "deferred_to_common_other",
1102
+ ]);
1103
+ export function actionItemAllowsCommonOtherDeferral(item) {
1104
+ const typedItem = asActionItem(item);
1105
+ if (typedItem.common_other_deferral_allowed === true ||
1106
+ typedItem.commonOtherDeferralAllowed === true) {
1107
+ return true;
1108
+ }
1109
+ const code = asText(typedItem.code ?? typedItem.rule_id ?? typedItem.ruleId);
1110
+ const itemPath = asText(typedItem.path);
1111
+ if (isAnnualSupplyTarget(code, itemPath))
1112
+ return true;
1113
+ return [
1114
+ "source_system_boilerplate",
1115
+ "local_source_path_visible",
1116
+ "trace_visible",
1117
+ "provenance_visible",
1118
+ ].some((token) => code.includes(token));
1119
+ }
1120
+ export function actionItemResolutionModes(item) {
1121
+ const typedItem = asActionItem(item);
1122
+ const code = asText(typedItem.code ?? typedItem.rule_id ?? typedItem.ruleId);
1123
+ const itemPath = asText(typedItem.path);
1124
+ if (code.includes("classification"))
1125
+ return ["classification_decision"];
1126
+ if (code.includes("location"))
1127
+ return ["location_decision"];
1128
+ if (isAnnualSupplyTarget(code, itemPath)) {
1129
+ return ["evidence_backed_completion", "deferred_to_common_other"];
1130
+ }
1131
+ if (code.includes("only_output_exchange"))
1132
+ return ["source_trace_verified", "exchange_set_repaired"];
1133
+ if (actionItemAllowsCommonOtherDeferral(item)) {
1134
+ return ["source_language_normalization", "deferred_to_common_other"];
1135
+ }
1136
+ if (code.includes("placeholder") || code.includes("geography_token") || code.includes("name")) {
1137
+ return ["evidence_backed_completion", "source_language_normalization"];
1138
+ }
1139
+ return ["evidence_backed_completion"];
1140
+ }
1141
+ export function compactActionItemForAuthoring(item, index) {
1142
+ const typedItem = asActionItem(item);
1143
+ const itemPath = asText(typedItem.path) || null;
1144
+ return {
1145
+ index,
1146
+ source: asText(typedItem.source) || null,
1147
+ code: asText(typedItem.code ?? typedItem.rule_id ?? typedItem.ruleId) || "action_item",
1148
+ path: itemPath,
1149
+ json_pointer: dotPathToJsonPointer(itemPath),
1150
+ message: asText(typedItem.message) || null,
1151
+ evidence: typedItem.evidence ?? null,
1152
+ instruction: asText(typedItem.instruction) || null,
1153
+ allowed_resolution_modes: actionItemResolutionModes(item),
1154
+ action_kind: asText(typedItem.action_kind) || "ai_authoring",
1155
+ required_owner: asText(typedItem.required_owner) || "foundry_ai_authoring",
1156
+ ai_required: typedItem.ai_required !== false,
1157
+ common_other_deferral_allowed: actionItemAllowsCommonOtherDeferral(item),
1158
+ deferral_cleanup_path: asText(typedItem.deferral_cleanup_path) || null,
1159
+ deferral_trace_path: asText(typedItem.deferral_trace_path) || null,
1160
+ };
1161
+ }
1162
+ export function markdownList(values, fallback = "- none") {
1163
+ const rows = ensureArray(values).filter((value) => value !== undefined && value !== null && value !== "");
1164
+ if (rows.length === 0)
1165
+ return fallback;
1166
+ return rows.map((value) => `- ${String(value)}`).join("\n");
1167
+ }
1168
+ export function relOrNull(repoRoot, filePath) {
1169
+ return filePath ? repoRelativePath(repoRoot, filePath) : null;
1170
+ }
1171
+ export function packageContextFileSummary(contextFiles) {
1172
+ return ensureArray(contextFiles).map((file) => {
1173
+ const typedFile = asRecord(file);
1174
+ return {
1175
+ kind: asText(typedFile.kind) || "context",
1176
+ path: asText(typedFile.path) || null,
1177
+ sha256: sha256Text(typedFile.text ?? ""),
1178
+ bytes: Buffer.byteLength(String(typedFile.text ?? ""), "utf8"),
1179
+ };
1180
+ });
1181
+ }
1182
+ export const decisionOnlyActionKinds = new Set([
1183
+ "identity_decision_authoring",
1184
+ "classification_decision_authoring",
1185
+ "location_decision_authoring",
1186
+ ]);
1187
+ export function isPatchAuthoringActionItem(item) {
1188
+ const typedItem = asActionItem(item);
1189
+ if (!item || typedItem.ai_required === false)
1190
+ return false;
1191
+ return !decisionOnlyActionKinds.has(asText(typedItem.action_kind));
1192
+ }
1193
+ export function patchAuthoringActionItems(packagePayload) {
1194
+ return ensureArray(asRecord(packagePayload).action_items)
1195
+ .filter(isPatchAuthoringActionItem)
1196
+ .map(compactActionItemForAuthoring);
1197
+ }
1198
+ export function decisionOnlyActionItems(packagePayload) {
1199
+ return ensureArray(asRecord(packagePayload).action_items)
1200
+ .filter((item) => asActionItem(item).ai_required !== false && !isPatchAuthoringActionItem(item))
1201
+ .map(compactActionItemForAuthoring);
1202
+ }
1203
+ export function buildPatchTemplate(packagePayload, packagePath) {
1204
+ const typedPackage = asRecord(packagePayload);
1205
+ const actionItems = patchAuthoringActionItems(packagePayload);
1206
+ const packageRef = path.basename(packagePath);
1207
+ const requiredContextKinds = ensureArray(asRecord(typedPackage.full_context_ai_completion).required_context_kinds ??
1208
+ asRecord(typedPackage.full_context_ai_completion).requiredContextKinds)
1209
+ .map((kind) => asText(kind))
1210
+ .filter(Boolean);
1211
+ const templateContextKinds = requiredContextKinds.length > 0
1212
+ ? requiredContextKinds
1213
+ : ["schema", "methodology_yaml", "ruleset"];
1214
+ return {
1215
+ schema_version: 1,
1216
+ kind: "tiangong_foundry_dataset_patch_template",
1217
+ template_status: "requires_ai_completion",
1218
+ instructions: [
1219
+ "Replace __AI_FILL_VALUE__ with the final JSON value and fill basis or evidence before applying.",
1220
+ "For full-context import profiles, every non-test operation must include both basis and structured evidence with source plus quote_or_trace/source_path/field_path/citation.",
1221
+ "Use test operations before replace/add/remove when preserving an existing value matters.",
1222
+ "Treat generated paths as suggestions. Adjust JSON Pointers when a field is an array or the authoring package shows a different concrete structure.",
1223
+ "Keep closes_action_items aligned with the authoring package action_items resolved by each operation.",
1224
+ "For full-context import profiles, every non-test operation must close at least one authoring action item; supporting cleanup operations should close the same item they are needed to resolve.",
1225
+ "Do not remove authoring_package; strict Foundry apply uses it for package lineage and action-item closure.",
1226
+ "Do not use common:other as a substitute for mandatory schema fields. Only action items whose allowed_resolution_modes include deferred_to_common_other may be deferred.",
1227
+ "For deferred_to_common_other, add tiangongfoundry:unresolvedTrace under common:other with status, action_item_code, blocked_path, reason, structured evidence, and next_action. Evidence must include source plus quote_or_trace/source_path/field_path/citation.",
1228
+ `Do not defer annualSupplyOrProductionVolume to common:other. When source annual volume evidence is missing, Foundry deterministic cleanup writes '${annualSupplyMissingDataSentinelText}' so the required schema field remains present and later database-side curation can bulk-locate it.`,
1229
+ "For source_trace_verified, add tiangongfoundry:sourceExchangeCompleteness under common:other with accepted status and structured source trace evidence. Evidence must include source plus quote_or_trace/source_path/field_path/citation.",
1230
+ ],
1231
+ patch_sets: [
1232
+ {
1233
+ dataset_id: typedPackage.entity_id ?? typedPackage.process_id ?? null,
1234
+ version: typedPackage.version ?? "00.00.001",
1235
+ authoring_package: packageRef,
1236
+ operations: actionItems.map((item) => ({
1237
+ op: "replace",
1238
+ path: item.json_pointer,
1239
+ value: "__AI_FILL_VALUE__",
1240
+ basis: "",
1241
+ evidence: {
1242
+ source: "",
1243
+ quote_or_trace: "",
1244
+ },
1245
+ resolution: {
1246
+ mode: "__AI_FILL_RESOLUTION_MODE__",
1247
+ allowed_modes: item.allowed_resolution_modes,
1248
+ used_context_kinds: templateContextKinds,
1249
+ summary: "",
1250
+ deferred_reason: null,
1251
+ },
1252
+ closes_action_items: [actionItemClosure(item)],
1253
+ })),
1254
+ },
1255
+ ],
1256
+ };
1257
+ }
1258
+ export function fullContextAiConfigRequiresAuthoring(value) {
1259
+ const record = asRecord(value);
1260
+ return record.required === true || record.required === "true";
1261
+ }
1262
+ export function requiredFullContextKinds(value) {
1263
+ const record = asRecord(value);
1264
+ const kinds = ensureArray(record.required_context_kinds ?? record.requiredContextKinds)
1265
+ .map((kind) => asText(kind))
1266
+ .filter(Boolean);
1267
+ return kinds.length > 0
1268
+ ? kinds
1269
+ : ["schema", "methodology_yaml", "ruleset", "classification_schema", "location_schema"];
1270
+ }
1271
+ export function requiredFullContextFilePatterns(value) {
1272
+ const record = asRecord(value);
1273
+ return ensureArray(record.required_context_file_patterns ?? record.requiredContextFilePatterns)
1274
+ .map((pattern) => asText(pattern))
1275
+ .filter(Boolean);
1276
+ }
1277
+ export function contextSummaryHasNonEmptyPayload(file) {
1278
+ const record = asRecord(file);
1279
+ if (Number(record.bytes ?? 0) > 0)
1280
+ return true;
1281
+ return Buffer.byteLength(String(record.text ?? ""), "utf8") > 0;
1282
+ }
1283
+ export function contextSummaryHasKind(files, kind) {
1284
+ return ensureArray(files).some((file) => asText(asRecord(file).kind) === kind && contextSummaryHasNonEmptyPayload(file));
1285
+ }
1286
+ export function contextSummaryHasPattern(files, pattern) {
1287
+ const needle = String(pattern).toLowerCase();
1288
+ return ensureArray(files).some((file) => String(asRecord(file).path ?? "")
1289
+ .toLowerCase()
1290
+ .includes(needle) && contextSummaryHasNonEmptyPayload(file));
1291
+ }
1292
+ export function stableSharedContextBundleSha256(bundle) {
1293
+ if (!bundle || typeof bundle !== "object" || Array.isArray(bundle)) {
1294
+ return null;
1295
+ }
1296
+ const { generated_at_utc: _generatedAtUtc, generatedAtUtc: _generatedAtUtcCamel, hash_scope: _hashScope, hashScope: _hashScopeCamel, sha256: _sha256, ...stablePayload } = bundle;
1297
+ return sha256Text(JSON.stringify(stablePayload));
1298
+ }
1299
+ export function sharedContextBundleReadinessBlockers({ repoRoot, sharedContextBundle, sourceKind, sourcePath = null, }) {
1300
+ const sharedContext = asRecord(sharedContextBundle);
1301
+ const sharedPath = asText(sharedContext.path);
1302
+ if (!sharedPath)
1303
+ return [];
1304
+ const expectedSha256 = asText(sharedContext.sha256);
1305
+ const prefix = sourceKind === "manifest"
1306
+ ? "authoring_manifest_shared_context_bundle"
1307
+ : "authoring_task_shared_context_bundle";
1308
+ const sourceField = sourceKind === "manifest" ? "task_manifest" : "authoring_task";
1309
+ const sourceValue = sourcePath ? repoRelativeArtifactPath(repoRoot, sourcePath) : null;
1310
+ const base = {
1311
+ stage: "ai_patch_collect",
1312
+ shared_context_bundle: repoRelativeArtifactPath(repoRoot, sharedPath),
1313
+ ...(sourceValue ? { [sourceField]: sourceValue } : {}),
1314
+ };
1315
+ const bundlePath = resolveRepoPath(repoRoot, sharedPath);
1316
+ if (!bundlePath || !fileExists(bundlePath)) {
1317
+ return [
1318
+ {
1319
+ ...base,
1320
+ code: `${prefix}_missing`,
1321
+ message: "AI patch collect cannot verify a referenced shared full-context bundle because it is unreadable.",
1322
+ expected_sha256: expectedSha256 || null,
1323
+ },
1324
+ ];
1325
+ }
1326
+ if (!expectedSha256) {
1327
+ return [
1328
+ {
1329
+ ...base,
1330
+ code: `${prefix}_hash_missing`,
1331
+ message: "AI patch collect requires shared full-context bundle references to be hash-bound.",
1332
+ },
1333
+ ];
1334
+ }
1335
+ try {
1336
+ const bundle = readJson(bundlePath);
1337
+ const actualSha256 = asText(bundle.sha256);
1338
+ const computedSha256 = stableSharedContextBundleSha256(bundle);
1339
+ const blockers = [];
1340
+ if (actualSha256 !== expectedSha256) {
1341
+ blockers.push({
1342
+ ...base,
1343
+ code: `${prefix}_hash_mismatch`,
1344
+ message: "Shared full-context bundle sha256 no longer matches the task or manifest reference.",
1345
+ expected_sha256: expectedSha256,
1346
+ actual_sha256: actualSha256 || null,
1347
+ });
1348
+ }
1349
+ if (actualSha256 && computedSha256 && actualSha256 !== computedSha256) {
1350
+ blockers.push({
1351
+ ...base,
1352
+ code: `${prefix}_content_hash_mismatch`,
1353
+ message: "Shared full-context bundle content no longer matches its recorded stable sha256.",
1354
+ expected_sha256: actualSha256,
1355
+ actual_sha256: computedSha256,
1356
+ });
1357
+ }
1358
+ if (!Array.isArray(bundle.files)) {
1359
+ blockers.push({
1360
+ ...base,
1361
+ code: `${prefix}_invalid`,
1362
+ message: "Shared full-context bundle must be a JSON object with files[].",
1363
+ });
1364
+ }
1365
+ return blockers;
1366
+ }
1367
+ catch (error) {
1368
+ return [
1369
+ {
1370
+ ...base,
1371
+ code: `${prefix}_invalid`,
1372
+ message: error instanceof Error ? error.message : String(error),
1373
+ expected_sha256: expectedSha256,
1374
+ },
1375
+ ];
1376
+ }
1377
+ }